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
17 changes: 13 additions & 4 deletions GVFS/GVFS.Common/GVFSLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,22 @@ public NamedPipeMessages.LockData GetLockHolderForCallbacks(out long? processSta
}
}

public bool TryAcquirePlaceholderCreation(Func<string, bool> canCreate, out IDisposable lease, out string command)
public bool TryAcquirePlaceholderCreation(Func<NamedPipeMessages.LockData, long?, bool> canCreate, out IDisposable lease, out string command)
{
NamedPipeMessages.LockData holder = this.GetLockHolderForCallbacks(out long? ownerStartTime);
lease = null;
command = holder?.ParsedCommand;
// Process ancestry checks must not block lock acquisition or release.
if (!canCreate(holder, ownerStartTime))
{
return false;
}

lock (this.acquisitionLock)
{
lease = null;
command = this.GetLockedGitCommand();
if (!canCreate(command))
NamedPipeMessages.LockData current = this.currentLockHolder.GetExternalHolder();
command = current?.ParsedCommand;
if (!ReferenceEquals(holder, current) || ownerStartTime != this.currentLockHolder.ExternalStartTime)
{
return false;
}
Expand Down
2 changes: 2 additions & 0 deletions GVFS/GVFS.Common/GitCommandLineParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public enum Verbs
UpdateIndex = 1 << 7,
Restore = 1 << 8,
Switch = 1 << 9,
Apply = 1 << 10,
}

public bool IsValidGitCommand
Expand Down Expand Up @@ -130,6 +131,7 @@ private Verbs StringToVerbs(string verb)
switch (verb)
{
case "add": return Verbs.AddOrStage;
case "apply": return Verbs.Apply;
case "checkout": return Verbs.Checkout;
case "commit": return Verbs.Commit;
case "mv": return Verbs.Move;
Expand Down
20 changes: 15 additions & 5 deletions GVFS/GVFS.FunctionalTests.LockHolder/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ public class Program
{
public static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "--read-placeholder")
if (args.Length > 0 && (args[0] == "--read-placeholder" || args[0] == "--read-placeholder-success"))
{
bool expectSuccess = args[0] == "--read-placeholder-success";
string path = Environment.GetEnvironmentVariable("GVFS_TEST_PLACEHOLDER_PATH");
string eventName = Environment.GetEnvironmentVariable("GVFS_TEST_PLACEHOLDER_EVENT_NAME");
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(eventName))
Expand All @@ -22,14 +23,18 @@ public static void Main(string[] args)
try
{
File.ReadAllText(path);
Console.Error.WriteLine("The child unexpectedly opened the placeholder.");
Environment.Exit(1);
if (!expectSuccess)
{
Console.Error.WriteLine("The child unexpectedly opened the placeholder.");
Environment.Exit(1);
}
}
catch (FileNotFoundException)
{
using (EventWaitHandle rejected = EventWaitHandle.OpenExisting(eventName))
if (expectSuccess)
{
rejected.Set();
Console.Error.WriteLine("The child could not open the placeholder.");
Environment.Exit(1);
}
}
catch (IOException e)
Expand All @@ -38,6 +43,11 @@ public static void Main(string[] args)
Environment.Exit(1);
}

using (EventWaitHandle completed = EventWaitHandle.OpenExisting(eventName))
{
completed.Set();
}

return;
}

Expand Down
406 changes: 406 additions & 0 deletions GVFS/GVFS.FunctionalTests/Tests/GitCommands/ApplyTests.cs

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions GVFS/GVFS.Platform.Windows/PlaceholderRequestProcessTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,6 @@ internal PlaceholderRequestProcessTree(Func<uint, long?> getStartTime, Func<uint
internal bool? IsDescendant(uint processId, NamedPipeMessages.LockData holder, long? ownerStartTime)
{
int ownerId = holder.PID;
if (processId == ownerId)
{
return true;
}

if (processId == 0 || ownerId <= 0 || !ownerStartTime.HasValue)
{
return null;
Expand All @@ -53,6 +48,11 @@ internal PlaceholderRequestProcessTree(Func<uint, long?> getStartTime, Func<uint
return null;
}

if (processId == ownerId)
{
return true;
}

ProcessPair key = new ProcessPair(holder, ownerId, ownerStartTime.Value, processId, requestStart.Value);
CacheEntry entry;
lock (this.cacheGate)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using GVFS.Common.Tracing;
using GVFS.Common.NamedPipes;
using GVFS.Common;
using GVFS.Virtualization.FileSystem;
using Microsoft.Windows.ProjFS;
using System;
Expand All @@ -10,6 +11,24 @@ namespace GVFS.Platform.Windows
{
public partial class WindowsFileSystemVirtualizer
{
private static bool IsApplyCommand(NamedPipeMessages.LockData holder)
{
return new GitCommandLineParser(holder?.ParsedCommand).IsVerb(GitCommandLineParser.Verbs.Apply);
}

private static HResult GetPlaceholderRejectionResult(NamedPipeMessages.LockData holder)
{
// FileNotFound poisons ProjFS's path-wide negative cache, including the apply owner's next open.
return IsApplyCommand(holder) ?
(HResult)HResultExtensions.HResultFromNtStatus.FileNotAvailable : HResult.FileNotFound;
}

private bool CanCreatePlaceholderForRequest(NamedPipeMessages.LockData holder, long? ownerStartTime, uint processId)
{
return CanCreatePlaceholderForCommand(holder?.ParsedCommand) ||
(IsApplyCommand(holder) && this.IsRequestDescendant(processId, holder, ownerStartTime) == true);
}

private HResult DeferPlaceholderCreation(int commandId, string virtualPath, uint processId, string processName)
{
if (!this.TryRegisterCommand(commandId, out CancellationTokenSource cancellation))
Expand All @@ -27,7 +46,7 @@ private HResult DeferPlaceholderCreation(int commandId, string virtualPath, uint
}

NamedPipeMessages.LockData holder = this.Context.Repository.GVFSLock.GetLockHolderForCallbacks(out long? ownerStartTime);
if (isFolder || this.IsSpecialGitFile(fileName) || CanCreatePlaceholderForCommand(holder?.ParsedCommand))
if (isFolder || this.IsSpecialGitFile(fileName) || this.CanCreatePlaceholderForRequest(holder, ownerStartTime, processId))
{
FileOrNetworkRequest work = new FileOrNetworkRequest(
connection => this.GetPlaceholderInformationAsyncHandler(
Expand All @@ -49,10 +68,10 @@ private HResult DeferPlaceholderCreation(int commandId, string virtualPath, uint
request.BlockingReason = "GitCommand";
if (this.ShouldRejectDependentRequest(request, holder, ownerStartTime))
{
request.Result = HResult.FileNotFound;
request.Result = GetPlaceholderRejectionResult(holder);
this.FileSystemCallbacks.OnPlaceholderCreateBlockedForGit();
this.TracePlaceholderWait(request, request.BlockingReason);
this.TryCompleteCommand(commandId, HResult.FileNotFound);
this.TryCompleteCommand(commandId, request.Result.Value);
cancellation.Dispose();
}
else if (!this.placeholderWaitQueue.TryEnqueue(request, out bool stopping))
Expand Down Expand Up @@ -194,20 +213,19 @@ private void Run()
stop = this.stopping;
}

bool ready = false;
bool commandAllowsCreation = false;
bool projectionReady = false;
NamedPipeMessages.LockData holder = null;
long? ownerStartTime = null;
if (!stop && snapshot.Count > 0)
{
holder = this.owner.Context.Repository.GVFSLock.GetLockHolderForCallbacks(out ownerStartTime);
commandAllowsCreation = CanCreatePlaceholderForCommand(holder?.ParsedCommand);
ready = commandAllowsCreation &&
this.owner.FileSystemCallbacks.GitIndexProjection.IsProjectionParseComplete();
projectionReady = this.owner.FileSystemCallbacks.GitIndexProjection.IsProjectionParseComplete();
}

foreach (Request request in snapshot)
{
bool commandAllowsCreation = this.owner.CanCreatePlaceholderForRequest(holder, ownerStartTime, request.ProcessId);
bool ready = commandAllowsCreation && projectionReady;
bool schedule = false;
string outcome = null;
bool rejectDependent = !stop && !request.Scheduled && !request.Token.IsCancellationRequested &&
Expand Down Expand Up @@ -238,7 +256,7 @@ private void Run()
{
this.requests.Remove(request.CommandId);
request.Terminated = true;
request.Result = HResult.FileNotFound;
request.Result = GetPlaceholderRejectionResult(holder);
outcome = request.BlockingReason;
}
else
Expand Down Expand Up @@ -281,7 +299,7 @@ private void Run()

this.owner.TryCompleteCommand(
request.CommandId,
rejectDependent ? HResult.FileNotFound :
rejectDependent ? request.Result.Value :
stop ? (HResult)HResultExtensions.HResultFromNtStatus.DeviceNotReady :
(HResult)HResultExtensions.HResultFromNtStatus.FileNotAvailable);
}
Expand Down
15 changes: 9 additions & 6 deletions GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -742,22 +742,24 @@ public HResult GetPlaceholderInfoCallback(
return HResult.FileNotFound;
}

NamedPipeMessages.LockData holder = this.Context.Repository.GVFSLock.GetLockHolderForCallbacks(out long? ownerStartTime);
if (!isFolder &&
!this.IsSpecialGitFile(fileName) &&
!this.CanCreatePlaceholder())
!this.CanCreatePlaceholderForRequest(holder, ownerStartTime, triggeringProcessId))
{
HResult rejectionResult = GetPlaceholderRejectionResult(holder);
EventMetadata metadata = this.CreateEventMetadata(virtualPath);
metadata.Add("commandId", commandId);
metadata.Add("triggeringProcessId", triggeringProcessId);
metadata.Add("triggeringProcessImageFileName", triggeringProcessImageFileName);
metadata.Add("lockedGitCommand", holder?.ParsedCommand);
metadata.Add("completionResult", rejectionResult.ToString("X"));
metadata.Add(TracingConstants.MessageKey.VerboseMessage, $"{nameof(this.GetPlaceholderInfoCallback)}: Not allowed to create placeholder");
this.Context.Tracer.RelatedEvent(EventLevel.Verbose, nameof(this.GetPlaceholderInfoCallback), metadata);

this.FileSystemCallbacks.OnPlaceholderCreateBlockedForGit();

// Another process is modifying the working directory so we cannot modify it
// until they are done.
return HResult.FileNotFound;
return rejectionResult;
}

CancellationTokenSource cancellationSource;
Expand Down Expand Up @@ -911,9 +913,9 @@ public override bool TryStart(out string error)
{
error = string.Empty;

this.IsRequestDescendant ??= new PlaceholderRequestProcessTree(this.Context.Tracer).IsDescendant;
if (this.placeholderLockWaitMs > 0)
{
this.IsRequestDescendant ??= new PlaceholderRequestProcessTree(this.Context.Tracer).IsDescendant;
this.placeholderWaitQueue = new PlaceholderCreationWaitQueue(this);
}

Expand Down Expand Up @@ -1372,7 +1374,8 @@ private bool GetPlaceholderInformationAsyncHandler(
else
{
if (!this.Context.Repository.GVFSLock.TryAcquirePlaceholderCreation(
CanCreatePlaceholderForCommand, out IDisposable lease, out string blockingCommand))
(holder, ownerStartTime) => this.CanCreatePlaceholderForRequest(holder, ownerStartTime, triggeringProcessId),
out IDisposable lease, out string blockingCommand))
{
deferredRequest.BlockingReason = "GitCommand";
deferredRequest.BlockingCommand = blockingCommand;
Expand Down
44 changes: 39 additions & 5 deletions GVFS/GVFS.UnitTests/Common/GVFSLockTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Moq;
using NUnit.Framework;
using System;
using System.Threading.Tasks;

namespace GVFS.UnitTests.Common
{
Expand Down Expand Up @@ -187,8 +188,8 @@ public void LockRetriesContinueWhileAnotherOwnerHoldsTheLock(string firstDenial,
public void PlaceholderCreationLeasesBlockNewOwnersUntilEveryLeaseEnds()
{
GVFSLock gvfsLock = new GVFSLock(new MockTracer());
gvfsLock.TryAcquirePlaceholderCreation(_ => true, out IDisposable first, out _).ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation(_ => true, out IDisposable second, out _).ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation((_, _) => true, out IDisposable first, out _).ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation((_, _) => true, out IDisposable second, out _).ShouldBeTrue();
try
{
gvfsLock.TryAcquireLockForExternalRequestor(DefaultLockData, out _).ShouldBeFalse();
Expand All @@ -206,11 +207,11 @@ public void PlaceholderCreationLeasesBlockNewOwnersUntilEveryLeaseEnds()
}

gvfsLock.TryAcquireLockForGVFS().ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation(_ => true, out IDisposable duringBackgroundWork, out _).ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation((_, _) => true, out IDisposable duringBackgroundWork, out _).ShouldBeTrue();
gvfsLock.TryAcquireLockForGVFS().ShouldBeTrue();
duringBackgroundWork.Dispose();
gvfsLock.ReleaseLockHeldByGVFS();
gvfsLock.TryAcquirePlaceholderCreation(_ => false, out _, out _).ShouldBeFalse();
gvfsLock.TryAcquirePlaceholderCreation((_, _) => false, out _, out _).ShouldBeFalse();
}

[TestCase]
Expand All @@ -220,7 +221,7 @@ public void PlaceholderLeaseKeepsTheExistingAllowedCommandAsTheReportedOwner()
GVFSLock gvfsLock = new GVFSLock(new MockTracer());
NamedPipeMessages.LockData owner = new NamedPipeMessages.LockData(1234, false, false, "git status", string.Empty);
gvfsLock.TryAcquireLockForExternalRequestor(owner, out _).ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation(command => command == "git status", out IDisposable lease, out _).ShouldBeTrue();
gvfsLock.TryAcquirePlaceholderCreation((holder, _) => holder?.ParsedCommand == "git status", out IDisposable lease, out _).ShouldBeTrue();
using (lease)
{
gvfsLock.IsLockAvailableForExternalRequestor(out NamedPipeMessages.LockData reported).ShouldBeFalse();
Expand All @@ -235,6 +236,39 @@ public void PlaceholderLeaseKeepsTheExistingAllowedCommandAsTheReportedOwner()
gvfsLock.GetStatus().ShouldEqual("Free");
}

[TestCase]
public void PlaceholderLeaseChecksAncestryOutsideAcquisitionLockAndRejectsAReplacementOwner()
{
((MockPlatform)GVFSPlatform.Instance).ActiveProcesses.Add(1234);
GVFSLock gvfsLock = new GVFSLock(new MockTracer());
NamedPipeMessages.LockData owner = new NamedPipeMessages.LockData(1234, false, false, "git apply -", string.Empty);
gvfsLock.TryAcquireLockForExternalRequestor(owner, out _).ShouldBeTrue();
try
{
gvfsLock.TryAcquirePlaceholderCreation((holder, start) =>
{
ReferenceEquals(holder, owner).ShouldBeTrue();
start.ShouldEqual((long?)1234);
Task replacement = Task.Factory.StartNew(() =>
{
gvfsLock.ReleaseLockHeldByExternalProcess(1234).ShouldBeTrue();
gvfsLock.TryAcquireLockForExternalRequestor(
new NamedPipeMessages.LockData(1234, false, false, "git apply -", string.Empty), out _).ShouldBeTrue();
}, TaskCreationOptions.LongRunning);
replacement.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue("The ancestry check blocked lock acquisition or release.");
return true;
}, out IDisposable lease, out _).ShouldBeFalse();
lease.ShouldBeNull();
gvfsLock.ReleaseLockHeldByExternalProcess(1234).ShouldBeTrue();
gvfsLock.TryAcquireLockForGVFS().ShouldBeTrue();
gvfsLock.ReleaseLockHeldByGVFS();
}
finally
{
gvfsLock.ReleaseLockHeldByExternalProcess(1234);
}
}

[TestCase]
public void TryAcquireAndReleaseLockForExternalRequestor()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ protected override FileSystemVirtualizer CreateVirtualizer(CommonRepoSetup repo)
repo.Context.Tracer,
() => repo.Context.Repository.TryGetConfigValue(GVFS.Common.GVFSConstants.GitConfig.PlaceholderLockWaitMs, out string value) ? value : null))
{
IsRequestDescendant = (_, _, _) => false,
IsRequestDescendant = (id, holder, _) => id == holder.PID,
};
return this.WindowsVirtualizer;
}
Expand Down
Loading
Loading