Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@ public static partial class NamedPipeMessages
/// <c>CommandId</c> after Git runs, so that the mount can remove the cone entries that
/// it added for that command.
/// <para>
/// The hook treats every reply other than <see cref="SuccessResult"/> as "not applied"
/// and lets Git run. This includes <see cref="FailureResult"/> and
/// The hook treats every reply other than <see cref="SuccessResult"/> as "not applied".
/// This includes <see cref="FailureResult"/>, <see cref="NotLockHolderResult"/>,
/// <see cref="NotEnabledResult"/>, <see cref="UnknownRequest"/> from an older mount that
/// does not handle these messages, <see cref="MountNotReadyResult"/>, no reply within the
/// wait budget, and no mount. Git then expands the sparse index in memory.
/// wait budget, and no mount. For a read-only command, Git then runs and expands the
/// sparse index in memory. A command that writes the index stops before Git runs when a
/// widen or an apply that it sent is not applied, unless the feature is off.
/// </para>
/// <para>
/// A widen request carries only repo-relative git-form paths that the hook resolved
Expand Down Expand Up @@ -63,10 +65,17 @@ public static class ConeManagement
/// <summary>The mount received the request, but automatic sparse index is not enabled.</summary>
public const string NotEnabledResult = "NE";

/// <summary>
/// The mount did not apply a widen or an apply, because the requesting Git process
/// does not hold the GVFS lock. A hook that does not know this result treats it as
/// <see cref="FailureResult"/>.
/// </summary>
public const string NotLockHolderResult = "NL";

/// <summary>
/// The time that the pre-command hook allows to connect and send a widen request. If
/// the hook cannot send the request in this time, it lets Git run, and it does not
/// send the request.
/// the hook cannot send the request in this time, it does not send the request, and
/// the widen fails (see <c>PreCommandConeRequests</c> in the hooks).
/// </summary>
public const int WidenWaitBudgetMs = 1000;

Expand Down
82 changes: 55 additions & 27 deletions GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,11 @@ namespace GVFS.Common.Sparse
/// does not change. Only a dehydrate (see below) can make the manager invalidate it.
/// </para>
/// <para>
/// Every failure lets Git run, because the hook treats any reply other than success as
/// "not applied". Git then expands the index in memory, which is slower but correct.
/// A failure does not change the cone or the index. The hook then lets a read-only command
/// run, and Git expands the index in memory. Git then reads a path without a local change
/// correctly, but it can miss a local change outside the cone, so the hook warns. The hook
/// stops a command that writes the index before Git runs (see <c>PreCommandConeRequests</c>
/// in the hooks).
/// </para>
/// <para>
/// Working-tree changes: Git sees a change to a file only when the index has an entry for
Expand Down Expand Up @@ -102,7 +105,7 @@ namespace GVFS.Common.Sparse
/// </remarks>
public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver
{
/// <summary>A widen with more paths is refused, and Git expands the index in memory.</summary>
/// <summary>A widen with more paths is refused. The hook does not send such a widen.</summary>
public const int MaxWidenPaths = 1000;

/// <summary>
Expand Down Expand Up @@ -159,10 +162,10 @@ public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver
private const string ReconcileEventName = "ConeReconcile";
private const int MaxTracedPaths = 10;

// A widen that waited longer than this for earlier requests does not start Git. Git then
// expands the index in memory. This keeps a widen far inside the hook's reply ceiling
// (WidenReplyCeilingMs), after which Git runs while the child Git process can still
// hold the index lock.
// A widen that waited longer than this for earlier requests does not start Git, and the
// hook gets a failure (see PreCommandConeRequests). This keeps a widen far inside the
// hook's reply ceiling (WidenReplyCeilingMs), after which the hook stops waiting while
// the child Git process can still hold the index lock.
private const int MaxQueueWaitBeforeApplyMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs / 2;

// A check that cannot write the cone file tries again after the change-check delay, at
Expand Down Expand Up @@ -342,7 +345,6 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t
return NamedPipeMessages.ConeManagement.NotEnabledResult;
}

bool succeeded;
switch (message.Header)
{
case NamedPipeMessages.ConeManagement.WidenRequest:
Expand All @@ -352,8 +354,7 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t
return NamedPipeMessages.ConeManagement.FailureResult;
}

succeeded = manager.TryWiden(widen);
break;
return ToReply(manager.HandleWiden(widen));

case NamedPipeMessages.ConeManagement.NarrowRequest:
if (!NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.NarrowParameters narrow))
Expand All @@ -362,8 +363,7 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t
return NamedPipeMessages.ConeManagement.FailureResult;
}

succeeded = manager.TryNarrow(narrow);
break;
return manager.TryNarrow(narrow) ? NamedPipeMessages.ConeManagement.SuccessResult : NamedPipeMessages.ConeManagement.FailureResult;

case NamedPipeMessages.ConeManagement.ApplyRequest:
if (!NamedPipeMessages.ConeManagement.ApplyParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.ApplyParameters apply))
Expand All @@ -372,22 +372,57 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t
return NamedPipeMessages.ConeManagement.FailureResult;
}

succeeded = manager.TryApply(apply);
break;
return ToReply(manager.HandleApply(apply));

default:
throw new ArgumentException($"'{message.Header}' is not a cone request.", nameof(message));
}

return succeeded ? NamedPipeMessages.ConeManagement.SuccessResult : NamedPipeMessages.ConeManagement.FailureResult;
}

/// <summary>
/// Add the paths of a Git command to the cone and update the index. The hook waits for
/// the result before Git runs. The cone also gets every pending working-tree change.
/// </summary>
/// <returns>True when the cone and the index include the paths.</returns>
public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters)
internal bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters)
{
return IsApplied(this.HandleWiden(parameters));
}

/// <summary>
/// Apply the pending working-tree changes to the cone and the index before a Git command
/// reads the index. The hook waits for the result before Git runs.
/// </summary>
/// <returns>True when the cone and the index include every pending change.</returns>
internal bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters)
{
return IsApplied(this.HandleApply(parameters));
}

private static bool IsApplied(ConeChange change)
{
return change == ConeChange.Applied || change == ConeChange.ConeUnchanged;
}

/// <summary>
/// Return the reply to a widen or an apply. A hook stops a command that writes the index
/// when the reply is not <see cref="NamedPipeMessages.ConeManagement.SuccessResult"/>, and
/// <see cref="NamedPipeMessages.ConeManagement.NotLockHolderResult"/> lets it tell the
/// user that another Git command holds the GVFS lock.
/// </summary>
private static string ToReply(ConeChange change)
{
if (IsApplied(change))
{
return NamedPipeMessages.ConeManagement.SuccessResult;
}

return change == ConeChange.NotLockHolder
? NamedPipeMessages.ConeManagement.NotLockHolderResult
: NamedPipeMessages.ConeManagement.FailureResult;
}

private ConeChange HandleWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);

Expand All @@ -398,20 +433,14 @@ public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters
ApplyAttempt attempt = new ApplyAttempt();
ConeChange change = this.RunAndCatch(() => this.Widen(parameters, attempt, stopwatch, metadata), metadata);
this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: true, metadata);
bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged;

// A widen slower than WidenWaitBudgetMs is a warning. The hook waits for the reply up
// to WidenReplyCeilingMs, so the user's Git command waits for the widen.
this.TraceResult(WidenEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.WidenWaitBudgetMs, metadata);
return succeeded;
return change;
}

/// <summary>
/// Apply the pending working-tree changes to the cone and the index before a Git command
/// reads the index. The hook waits for the result before Git runs.
/// </summary>
/// <returns>True when the cone and the index include every pending change.</returns>
public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters)
private ConeChange HandleApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters)
{
ArgumentNullException.ThrowIfNull(parameters);

Expand All @@ -425,10 +454,9 @@ public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters
: ConeChange.NoCommandId,
metadata);
this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: false, metadata);
bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged;

this.TraceResult(ApplyEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs, metadata);
return succeeded;
return change;
}

/// <summary>
Expand Down
142 changes: 142 additions & 0 deletions GVFS/GVFS.Common/Sparse/ConeRequestFaultInjection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
using GVFS.Common.NamedPipes;
using System;
using System.Collections.Generic;
using System.IO;

namespace GVFS.Common.Sparse
{
/// <summary>
/// Test only: makes the mount refuse cone widen and apply requests, so that the functional
/// tests can check what the hooks do when the mount cannot prepare the sparse index.
/// </summary>
/// <remarks>
/// The mount reads the <see cref="FaultFileEnvironmentVariable"/> environment variable once,
/// when it starts. Only the functional tests set it. When it is not set, this class does
/// nothing and the mount reads no file.
/// <para>
/// When it is set, the mount reads the named file at each widen and apply request, so that a
/// test can add and remove a fault while the mount runs. Each line of the file has a request
/// header (<see cref="NamedPipeMessages.ConeManagement.WidenRequest"/> or
/// <see cref="NamedPipeMessages.ConeManagement.ApplyRequest"/>), a space, and the reply
/// (<see cref="NamedPipeMessages.ConeManagement.FailureResult"/> or
/// <see cref="NamedPipeMessages.ConeManagement.NotLockHolderResult"/>). The mount sends that
/// reply and does not change the cone or the index. A missing file means no fault.
/// </para>
/// </remarks>
public sealed class ConeRequestFaultInjection
{
/// <summary>The environment variable that names the fault file. Test only.</summary>
public const string FaultFileEnvironmentVariable = "GVFS_TEST_CONE_REQUEST_FAULT_FILE";

// A fault file is a few short lines. A larger file is not a fault file.
private const int MaxFaultFileBytes = 4096;

private readonly string faultFilePath;
private readonly Func<string, string> readFile;

private ConeRequestFaultInjection(string faultFilePath, Func<string, string> readFile)
{
this.faultFilePath = faultFilePath;
this.readFile = readFile;
}

/// <summary>The path of the fault file.</summary>
public string FaultFilePath => this.faultFilePath;

/// <summary>
/// Return the fault injection that <see cref="FaultFileEnvironmentVariable"/> configures, or
/// null when the variable is not set.
/// </summary>
/// <param name="getEnvironmentVariable">Reads an environment variable.</param>
/// <param name="readFile">Returns the content of a file, or null when it does not exist.</param>
public static ConeRequestFaultInjection FromEnvironment(Func<string, string> getEnvironmentVariable, Func<string, string> readFile = null)
{
ArgumentNullException.ThrowIfNull(getEnvironmentVariable);

string path = getEnvironmentVariable(FaultFileEnvironmentVariable);
if (string.IsNullOrWhiteSpace(path))
{
return null;
}

return new ConeRequestFaultInjection(path, readFile ?? ReadSmallFile);
}

/// <summary>
/// Return the reply that the fault file sets for <paramref name="requestHeader"/>, or null
/// when the mount must handle the request. Never throws.
/// </summary>
public string GetForcedReply(string requestHeader)
{
if (requestHeader != NamedPipeMessages.ConeManagement.WidenRequest &&
requestHeader != NamedPipeMessages.ConeManagement.ApplyRequest)
{
return null;
}

string content;
try
{
content = this.readFile(this.faultFilePath);
}
catch (Exception e) when (!(e is OutOfMemoryException))
{
// A fault file that cannot be read, or a path that is not valid, means no fault.
return null;
}

return content == null ? null : ParseFaults(content).GetValueOrDefault(requestHeader);
}

/// <summary>
/// Parse the content of a fault file. Lines that are not valid are ignored.
/// </summary>
internal static Dictionary<string, string> ParseFaults(string content)
{
Dictionary<string, string> faults = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (string rawLine in content.Split('\n'))
{
string[] fields = rawLine.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length != 2)
{
continue;
}

bool isRequest = fields[0] == NamedPipeMessages.ConeManagement.WidenRequest ||
fields[0] == NamedPipeMessages.ConeManagement.ApplyRequest;
bool isReply = fields[1] == NamedPipeMessages.ConeManagement.FailureResult ||
fields[1] == NamedPipeMessages.ConeManagement.NotLockHolderResult;
if (isRequest && isReply)
{
faults[fields[0]] = fields[1];
}
}

return faults;
}

private static string ReadSmallFile(string path)
{
FileInfo file = new FileInfo(path);
if (!file.Exists || (file.Attributes & (FileAttributes.ReparsePoint | FileAttributes.Device)) != 0)
{
return null;
}

// Read at most one byte more than the limit, so that a file that grows after the
// check cannot make the read unbounded.
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
byte[] buffer = new byte[MaxFaultFileBytes + 1];
int length = 0;
int read;
while (length < buffer.Length && (read = stream.Read(buffer, length, buffer.Length - length)) > 0)
{
length += read;
}

return length > MaxFaultFileBytes ? null : System.Text.Encoding.UTF8.GetString(buffer, 0, length);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public void UnlockedCommandDoesNotChangeTheCone()
ProcessResult diff = this.GitWithTrace($"diff --stat -- {file}", out _);

diff.ExitCode.ShouldEqual(0, diff.Errors);
diff.Errors.ShouldContain(HookFailurePrefix + ": Rejected");
diff.Errors.ShouldContain(HookFailurePrefix + ": NotLockHolder");
this.ReadConeFile().ShouldEqual(coneBefore);
}

Expand Down
Loading
Loading