forked from microsoft/VFSForGit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInProcessMount.cs
More file actions
1741 lines (1509 loc) · 80.7 KB
/
Copy pathInProcessMount.cs
File metadata and controls
1741 lines (1509 loc) · 80.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using GVFS.Common;
using GVFS.Common.Database;
using GVFS.Common.FileSystem;
using GVFS.Common.Git;
using GVFS.Common.Http;
using GVFS.Common.Maintenance;
using GVFS.Common.NamedPipes;
using GVFS.Common.Prefetch;
using GVFS.Common.Tracing;
using GVFS.PlatformLoader;
using GVFS.Virtualization;
using GVFS.Virtualization.FileSystem;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static GVFS.Common.Git.LibGit2Repo;
namespace GVFS.Mount
{
public class InProcessMount
{
// Tests show that 250 is the max supported pipe name length
private const int MaxPipeNameLength = 250;
private const int MutexMaxWaitTimeMS = 500;
// This is value chosen based on tested scenarios to limit the required download time for
// all the trees. This is approximately the amount of trees that can be downloaded in 1 second.
// Downloading an entire commit pack also takes around 1 second, so this should limit downloading
// all the trees in a commit to ~2-3 seconds.
private const int MissingTreeThresholdForDownloadingCommitPack = 200;
// Number of unique missing trees to track with LRU eviction. Eviction is commit-based:
// when capacity is reached, the LRU commit and all its unique trees are dropped to make room.
// Set to 20x the threshold so that enough trees can accumulate for the heuristic to
// reliably trigger a commit pack download.
private const int TrackedTreeCapacity = MissingTreeThresholdForDownloadingCommitPack * 20;
private readonly bool showDebugWindow;
private FileSystemCallbacks fileSystemCallbacks;
private GVFSDatabase gvfsDatabase;
private GVFSEnlistment enlistment;
private ITracer tracer;
private GitMaintenanceScheduler maintenanceScheduler;
private CacheServerInfo cacheServer;
private RetryConfig retryConfig;
private GitStatusCacheConfig gitStatusCacheConfig;
private GVFSContext context;
private GVFSGitObjects gitObjects;
private MountState currentState;
private HeartbeatThread heartbeat;
private ManualResetEvent unmountEvent;
private readonly MissingTreeTracker missingTreeTracker;
// True if InProcessMount is calling git reset as part of processing
// a folder dehydrate request
private volatile bool resetForDehydrateInProgress;
public InProcessMount(ITracer tracer, GVFSEnlistment enlistment, CacheServerInfo cacheServer, RetryConfig retryConfig, GitStatusCacheConfig gitStatusCacheConfig, bool showDebugWindow)
{
this.tracer = tracer;
this.retryConfig = retryConfig;
this.gitStatusCacheConfig = gitStatusCacheConfig;
this.cacheServer = cacheServer;
this.enlistment = enlistment;
this.showDebugWindow = showDebugWindow;
this.unmountEvent = new ManualResetEvent(false);
this.missingTreeTracker = new MissingTreeTracker(tracer, TrackedTreeCapacity);
}
private enum MountState
{
Invalid = 0,
Mounting,
Ready,
Unmounting,
MountFailed
}
public void Mount(EventLevel verbosity, Keywords keywords)
{
this.currentState = MountState.Mounting;
// For worktree mounts, create the .gvfs metadata directory and
// bootstrap it with cache paths from the primary enlistment
if (this.enlistment.IsWorktree)
{
this.InitializeWorktreeMetadata();
}
string mountLockPath = Path.Combine(this.enlistment.DotGVFSRoot, GVFSConstants.DotGVFS.MountLock);
using (FileBasedLock mountLock = GVFSPlatform.Instance.CreateFileBasedLock(
new PhysicalFileSystem(),
this.tracer,
mountLockPath))
{
if (!mountLock.TryAcquireLock(out Exception lockException))
{
if (lockException is IOException)
{
this.FailMountAndExit(ReturnCode.MountAlreadyRunning, "Mount: Another mount process is already running.");
}
this.FailMountAndExit("Mount: Failed to acquire mount lock: {0}", lockException.Message);
}
this.MountWithLockAcquired(verbosity, keywords);
}
}
private void MountWithLockAcquired(EventLevel verbosity, Keywords keywords)
{
// Start auth + config query immediately — these are network-bound and don't
// depend on repo metadata or cache paths. Every millisecond of network latency
// we can overlap with local I/O is a win.
// TryInitializeAndQueryGVFSConfig combines the anonymous probe, credential fetch,
// and config query into at most 2 HTTP requests (1 for anonymous repos), reusing
// the same HttpClient/TCP connection.
Stopwatch parallelTimer = Stopwatch.StartNew();
var networkTask = Task.Run(() =>
{
Stopwatch sw = Stopwatch.StartNew();
ServerGVFSConfig config;
string authConfigError;
bool isAuthFailure;
if (!this.enlistment.Authentication.TryInitializeAndQueryGVFSConfig(
this.tracer, this.enlistment, this.retryConfig,
out config, out authConfigError, out isAuthFailure))
{
if (this.cacheServer != null && !string.IsNullOrWhiteSpace(this.cacheServer.Url))
{
this.tracer.RelatedWarning("Mount will proceed with fallback cache server: " + authConfigError);
config = null;
}
else
{
this.FailMountAndExit(
isAuthFailure ? ReturnCode.AuthenticationError : ReturnCode.GenericError,
"Unable to query /gvfs/config" + Environment.NewLine + authConfigError);
}
}
this.ValidateGVFSVersion(config);
this.tracer.RelatedInfo("ParallelMount: Auth + config completed in {0}ms", sw.ElapsedMilliseconds);
return config;
});
// We must initialize repo metadata before starting the pipe server so it
// can immediately handle status requests
string error;
if (!RepoMetadata.TryInitialize(this.tracer, this.enlistment.DotGVFSRoot, out error))
{
this.FailMountAndExit("Failed to load repo metadata: " + error);
}
string gitObjectsRoot;
if (!RepoMetadata.Instance.TryGetGitObjectsRoot(out gitObjectsRoot, out error))
{
this.FailMountAndExit("Failed to determine git objects root from repo metadata: " + error);
}
string localCacheRoot;
if (!RepoMetadata.Instance.TryGetLocalCacheRoot(out localCacheRoot, out error))
{
this.FailMountAndExit("Failed to determine local cache path from repo metadata: " + error);
}
string blobSizesRoot;
if (!RepoMetadata.Instance.TryGetBlobSizesRoot(out blobSizesRoot, out error))
{
this.FailMountAndExit("Failed to determine blob sizes root from repo metadata: " + error);
}
this.tracer.RelatedEvent(
EventLevel.Informational,
"CachePathsLoaded",
new EventMetadata
{
{ "gitObjectsRoot", gitObjectsRoot },
{ "localCacheRoot", localCacheRoot },
{ "blobSizesRoot", blobSizesRoot },
});
this.enlistment.InitializeCachePaths(localCacheRoot, gitObjectsRoot, blobSizesRoot);
// Local validations and git config run while we wait for the network
var localTask = Task.Run(() =>
{
Stopwatch sw = Stopwatch.StartNew();
this.ValidateGitVersion();
this.tracer.RelatedInfo("ParallelMount: ValidateGitVersion completed in {0}ms", sw.ElapsedMilliseconds);
this.ValidateHooksVersion();
this.ValidateFileSystemSupportsRequiredFeatures();
GitProcess git = new GitProcess(this.enlistment);
if (!git.IsValidRepo())
{
this.FailMountAndExit("The .git folder is missing or has invalid contents");
}
if (!GVFSPlatform.Instance.FileSystem.IsFileSystemSupported(this.enlistment.WorkingDirectoryRoot, out string fsError))
{
this.FailMountAndExit("FileSystem unsupported: " + fsError);
}
this.tracer.RelatedInfo("ParallelMount: Local validations completed in {0}ms", sw.ElapsedMilliseconds);
if (!this.TrySetRequiredGitConfigSettings())
{
this.FailMountAndExit("Unable to configure git repo");
}
this.LogEnlistmentInfoAndSetConfigValues();
this.tracer.RelatedInfo("ParallelMount: Local validations + git config completed in {0}ms", sw.ElapsedMilliseconds);
});
try
{
Task.WaitAll(networkTask, localTask);
}
catch (AggregateException ae)
{
this.FailMountAndExit(ae.Flatten().InnerExceptions[0].Message);
}
parallelTimer.Stop();
this.tracer.RelatedInfo("ParallelMount: All parallel tasks completed in {0}ms", parallelTimer.ElapsedMilliseconds);
ServerGVFSConfig serverGVFSConfig = networkTask.Result;
CacheServerResolver cacheServerResolver = new CacheServerResolver(this.tracer, this.enlistment);
this.cacheServer = cacheServerResolver.ResolveNameFromRemote(this.cacheServer.Url, serverGVFSConfig);
this.EnsureLocalCacheIsHealthy(serverGVFSConfig);
using (NamedPipeServer pipeServer = this.StartNamedPipe())
{
this.tracer.RelatedEvent(
EventLevel.Informational,
$"{nameof(this.Mount)}_StartedNamedPipe",
new EventMetadata { { "NamedPipeName", this.enlistment.NamedPipeName } });
this.context = this.CreateContext();
if (this.context.Unattended)
{
this.tracer.RelatedEvent(EventLevel.Critical, GVFSConstants.UnattendedEnvironmentVariable, null);
}
this.ValidateMountPoints();
string errorMessage;
// Worktrees share hooks with the primary enlistment via core.hookspath,
// so skip installation to avoid locking conflicts with the running mount.
if (!this.enlistment.IsWorktree && !HooksInstaller.TryUpdateHooks(this.context, out errorMessage))
{
this.FailMountAndExit(errorMessage);
}
GVFSPlatform.Instance.ConfigureVisualStudio(this.enlistment.GitBinPath, this.tracer);
this.MountAndStartWorkingDirectoryCallbacks(this.cacheServer);
try
{
Console.Title = "GVFS " + ProcessHelper.GetCurrentProcessVersion() + " - " + this.enlistment.WorkingDirectoryRoot;
}
catch (IOException)
{
// Console.Title throws when the process has no console (e.g. started as background/hidden process)
}
this.tracer.RelatedEvent(
EventLevel.Informational,
"Mount",
new EventMetadata
{
// Use TracingConstants.MessageKey.InfoMessage rather than TracingConstants.MessageKey.CriticalMessage
// as this message should not appear as an error
{ TracingConstants.MessageKey.InfoMessage, "Virtual repo is ready" },
},
Keywords.Telemetry);
this.currentState = MountState.Ready;
this.unmountEvent.WaitOne();
}
}
private GVFSContext CreateContext()
{
PhysicalFileSystem fileSystem = new PhysicalFileSystem();
GitRepo gitRepo = this.CreateOrReportAndExit(
() => new GitRepo(
this.tracer,
this.enlistment,
fileSystem),
"Failed to read git repo");
return new GVFSContext(this.tracer, fileSystem, gitRepo, this.enlistment);
}
private void ValidateMountPoints()
{
DirectoryInfo workingDirectoryRootInfo = new DirectoryInfo(this.enlistment.WorkingDirectoryBackingRoot);
if (!workingDirectoryRootInfo.Exists)
{
this.FailMountAndExit("Failed to initialize file system callbacks. Directory \"{0}\" must exist.", this.enlistment.WorkingDirectoryBackingRoot);
}
if (this.enlistment.IsWorktree)
{
// Worktrees have a .git file (not directory) pointing to the shared git dir
string dotGitFile = Path.Combine(this.enlistment.WorkingDirectoryBackingRoot, GVFSConstants.DotGit.Root);
if (!File.Exists(dotGitFile))
{
this.FailMountAndExit("Failed to mount worktree. File \"{0}\" must exist.", dotGitFile);
}
}
else
{
string dotGitPath = Path.Combine(this.enlistment.WorkingDirectoryBackingRoot, GVFSConstants.DotGit.Root);
DirectoryInfo dotGitPathInfo = new DirectoryInfo(dotGitPath);
if (!dotGitPathInfo.Exists)
{
this.FailMountAndExit("Failed to mount. Directory \"{0}\" must exist.", dotGitPathInfo);
}
}
}
/// <summary>
/// For worktree mounts, create the .gvfs metadata directory and
/// bootstrap RepoMetadata with cache paths from the primary enlistment.
/// </summary>
private void InitializeWorktreeMetadata()
{
string dotGVFSRoot = this.enlistment.DotGVFSRoot;
if (!Directory.Exists(dotGVFSRoot))
{
try
{
Directory.CreateDirectory(dotGVFSRoot);
this.tracer.RelatedInfo($"Created worktree metadata directory: {dotGVFSRoot}");
}
catch (Exception e)
{
this.FailMountAndExit("Failed to create worktree metadata directory '{0}': {1}", dotGVFSRoot, e.Message);
}
}
// Bootstrap RepoMetadata from the primary enlistment's metadata.
// Use try/finally to guarantee Shutdown() even if an unexpected
// exception occurs — the singleton must not be left pointing at
// the primary's metadata directory.
string primaryDotGVFS = Path.Combine(this.enlistment.PrimaryEnlistmentRoot, GVFSPlatform.Instance.Constants.DotGVFSRoot);
string error;
string gitObjectsRoot;
string localCacheRoot;
string blobSizesRoot;
if (!RepoMetadata.TryInitialize(this.tracer, primaryDotGVFS, out error))
{
this.FailMountAndExit("Failed to read primary enlistment metadata: " + error);
}
try
{
if (!RepoMetadata.Instance.TryGetGitObjectsRoot(out gitObjectsRoot, out error))
{
this.FailMountAndExit("Failed to read git objects root from primary metadata: " + error);
}
if (!RepoMetadata.Instance.TryGetLocalCacheRoot(out localCacheRoot, out error))
{
this.FailMountAndExit("Failed to read local cache root from primary metadata: " + error);
}
if (!RepoMetadata.Instance.TryGetBlobSizesRoot(out blobSizesRoot, out error))
{
this.FailMountAndExit("Failed to read blob sizes root from primary metadata: " + error);
}
}
finally
{
RepoMetadata.Shutdown();
}
// Initialize cache paths on the enlistment so SaveCloneMetadata
// can persist them into the worktree's metadata
this.enlistment.InitializeCachePaths(localCacheRoot, gitObjectsRoot, blobSizesRoot);
// Initialize the worktree's own metadata with cache paths,
// disk layout version, and a new enlistment ID
if (!RepoMetadata.TryInitialize(this.tracer, dotGVFSRoot, out error))
{
this.FailMountAndExit("Failed to initialize worktree metadata: " + error);
}
try
{
RepoMetadata.Instance.SaveCloneMetadata(this.tracer, this.enlistment);
}
finally
{
RepoMetadata.Shutdown();
}
}
private NamedPipeServer StartNamedPipe()
{
try
{
return NamedPipeServer.StartNewServer(this.enlistment.NamedPipeName, this.tracer, this.HandleRequest);
}
catch (PipeNameLengthException)
{
this.FailMountAndExit("Failed to create mount point. Mount path exceeds the maximum number of allowed characters");
return null;
}
}
private void FailMountAndExit(string error, params object[] args)
{
this.FailMountAndExit(ReturnCode.GenericError, error, args);
}
private void FailMountAndExit(ReturnCode returnCode, string error, params object[] args)
{
this.currentState = MountState.MountFailed;
this.tracer.RelatedError(error, args);
if (this.showDebugWindow)
{
Console.WriteLine("\nPress Enter to Exit");
Console.ReadLine();
}
if (this.fileSystemCallbacks != null)
{
this.fileSystemCallbacks.Dispose();
this.fileSystemCallbacks = null;
}
Environment.Exit((int)returnCode);
}
private T CreateOrReportAndExit<T>(Func<T> factory, string reportMessage)
{
try
{
return factory();
}
catch (Exception e)
{
this.FailMountAndExit(reportMessage + " " + e.ToString());
throw;
}
}
private void HandleRequest(ITracer tracer, string request, NamedPipeServer.Connection connection)
{
NamedPipeMessages.Message message = NamedPipeMessages.Message.FromString(request);
switch (message.Header)
{
case NamedPipeMessages.GetStatus.Request:
this.HandleGetStatusRequest(connection);
break;
case NamedPipeMessages.Unmount.Request:
this.HandleUnmountRequest(connection);
break;
case NamedPipeMessages.AcquireLock.AcquireRequest:
this.HandleLockRequest(message.Body, connection);
break;
case NamedPipeMessages.ReleaseLock.Request:
this.HandleReleaseLockRequest(message.Body, connection);
break;
case NamedPipeMessages.DownloadObject.DownloadRequest:
this.HandleDownloadObjectRequest(message, connection);
break;
case NamedPipeMessages.ModifiedPaths.ListRequest:
this.HandleModifiedPathsListRequest(message, connection);
break;
case NamedPipeMessages.PostIndexChanged.NotificationRequest:
this.HandlePostIndexChangedRequest(message, connection);
break;
case NamedPipeMessages.PrepareForUnstage.Request:
this.HandlePrepareForUnstageRequest(message, connection);
break;
case NamedPipeMessages.RunPostFetchJob.PostFetchJob:
this.HandlePostFetchJobRequest(message, connection);
break;
case NamedPipeMessages.DehydrateFolders.Dehydrate:
this.HandleDehydrateFolders(message, connection);
break;
case NamedPipeMessages.PrefetchCommits.Request:
this.HandlePrefetchCommitsRequest(connection);
break;
case NamedPipeMessages.PrefetchBlobs.RequestHeader:
this.HandlePrefetchBlobsRequest(message, connection);
break;
case NamedPipeMessages.HydrationStatus.Request:
this.HandleGetHydrationStatusRequest(connection);
break;
default:
EventMetadata metadata = new EventMetadata();
metadata.Add("Area", "Mount");
metadata.Add("Header", message.Header);
this.tracer.RelatedError(metadata, "HandleRequest: Unknown request");
connection.TrySendResponse(NamedPipeMessages.UnknownRequest);
break;
}
}
private void HandleGetHydrationStatusRequest(NamedPipeServer.Connection connection)
{
EnlistmentHydrationSummary summary = this.fileSystemCallbacks?.GetCachedHydrationSummary();
if (summary == null || !summary.IsValid)
{
this.tracer.RelatedInfo(
$"{nameof(this.HandleGetHydrationStatusRequest)}: " +
(summary == null ? "No cached hydration summary available yet" : "Cached hydration summary is invalid"));
connection.TrySendResponse(
new NamedPipeMessages.Message(NamedPipeMessages.HydrationStatus.NotAvailableResult, null));
return;
}
NamedPipeMessages.HydrationStatus.Response response = new NamedPipeMessages.HydrationStatus.Response
{
PlaceholderFileCount = summary.PlaceholderFileCount,
PlaceholderFolderCount = summary.PlaceholderFolderCount,
ModifiedFileCount = summary.ModifiedFileCount,
ModifiedFolderCount = summary.ModifiedFolderCount,
TotalFileCount = summary.TotalFileCount,
TotalFolderCount = summary.TotalFolderCount,
};
connection.TrySendResponse(
new NamedPipeMessages.Message(NamedPipeMessages.HydrationStatus.SuccessResult, response.ToBody()));
}
private void HandleDehydrateFolders(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.DehydrateFolders.Request request = NamedPipeMessages.DehydrateFolders.Request.FromMessage(message);
EventMetadata metadata = new EventMetadata();
metadata.Add(nameof(request.Folders), request.Folders);
metadata.Add(TracingConstants.MessageKey.InfoMessage, "Received dehydrate folders request");
this.tracer.RelatedEvent(EventLevel.Informational, nameof(this.HandleDehydrateFolders), metadata);
NamedPipeMessages.DehydrateFolders.Response response;
if (this.currentState == MountState.Ready)
{
response = new NamedPipeMessages.DehydrateFolders.Response(NamedPipeMessages.DehydrateFolders.DehydratedResult);
string[] folders = request.Folders.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder resetFolderPaths = new StringBuilder();
List<string> movedFolders = BackupFoldersWhileUnmounted(request, response, folders);
foreach (string folder in movedFolders)
{
if (this.fileSystemCallbacks.TryDehydrateFolder(folder, out string errorMessage))
{
response.SuccessfulFolders.Add(folder);
}
else
{
response.FailedFolders.Add($"{folder}\0{errorMessage}");
}
resetFolderPaths.Append($"\"{folder.Replace(Path.DirectorySeparatorChar, GVFSConstants.GitPathSeparator)}\" ");
}
// Since modified paths could have changed with the dehydrate, the paths that were dehydrated need to be reset in the index
string resetPaths = resetFolderPaths.ToString();
GitProcess gitProcess = new GitProcess(this.enlistment);
EventMetadata resetIndexMetadata = new EventMetadata();
resetIndexMetadata.Add(nameof(resetPaths), resetPaths);
GitProcess.Result refreshIndexResult;
this.resetForDehydrateInProgress = true;
try
{
// Because we've set resetForDehydrateInProgress to true, this call to 'git reset' will also force
// the projection to be updated (required because 'git reset' will adjust the skip worktree bits in
// the index).
refreshIndexResult = gitProcess.Reset(GVFSConstants.DotGit.HeadName, resetPaths);
}
finally
{
this.resetForDehydrateInProgress = false;
}
resetIndexMetadata.Add(nameof(refreshIndexResult.ExitCode), refreshIndexResult.ExitCode);
resetIndexMetadata.Add(nameof(refreshIndexResult.Output), refreshIndexResult.Output);
resetIndexMetadata.Add(nameof(refreshIndexResult.Errors), refreshIndexResult.Errors);
resetIndexMetadata.Add(TracingConstants.MessageKey.InfoMessage, $"{nameof(this.HandleDehydrateFolders)}: Reset git index");
this.tracer.RelatedEvent(EventLevel.Informational, $"{nameof(this.HandleDehydrateFolders)}_ResetIndex", resetIndexMetadata);
}
else
{
response = new NamedPipeMessages.DehydrateFolders.Response(NamedPipeMessages.DehydrateFolders.MountNotReadyResult);
}
connection.TrySendResponse(response.CreateMessage());
}
private List<string> BackupFoldersWhileUnmounted(NamedPipeMessages.DehydrateFolders.Request request, NamedPipeMessages.DehydrateFolders.Response response, string[] folders)
{
/* We can't move folders while the virtual file system is mounted, so unmount it first.
* After moving the folders, remount the virtual file system.
*/
var movedFolders = new List<string>();
try
{
/* Set to "Mounting" instead of "Unmounting" so that incoming requests
* that are rejected will know they can try again soon.
*/
this.currentState = MountState.Mounting;
this.UnmountAndStopWorkingDirectoryCallbacks(willRemountInSameProcess: true);
foreach (string folder in folders)
{
try
{
var source = Path.Combine(this.enlistment.WorkingDirectoryBackingRoot, folder);
var destination = Path.Combine(request.BackupFolderPath, folder);
var destinationParent = Path.GetDirectoryName(destination);
this.context.FileSystem.CreateDirectory(destinationParent);
if (this.context.FileSystem.DirectoryExists(source))
{
this.context.FileSystem.MoveDirectory(source, destination);
}
movedFolders.Add(folder);
}
catch (Exception ex)
{
response.FailedFolders.Add($"{folder}\0{ex.Message}");
continue;
}
}
}
finally
{
this.MountAndStartWorkingDirectoryCallbacks(this.cacheServer, alreadyInitialized: true);
this.currentState = MountState.Ready;
}
return movedFolders;
}
private void HandleLockRequest(string messageBody, NamedPipeServer.Connection connection)
{
NamedPipeMessages.AcquireLock.Response response;
NamedPipeMessages.LockRequest request = new NamedPipeMessages.LockRequest(messageBody);
NamedPipeMessages.LockData requester = request.RequestData;
if (this.currentState == MountState.Unmounting)
{
response = new NamedPipeMessages.AcquireLock.Response(NamedPipeMessages.AcquireLock.UnmountInProgressResult);
EventMetadata metadata = new EventMetadata();
metadata.Add("LockRequest", requester.ToString());
metadata.Add(TracingConstants.MessageKey.InfoMessage, "Request denied, unmount in progress");
this.tracer.RelatedEvent(EventLevel.Informational, "HandleLockRequest_UnmountInProgress", metadata);
}
else if (this.currentState != MountState.Ready)
{
response = new NamedPipeMessages.AcquireLock.Response(NamedPipeMessages.AcquireLock.MountNotReadyResult);
}
else
{
bool lockAcquired = false;
NamedPipeMessages.LockData existingExternalHolder = null;
string denyGVFSMessage = null;
bool lockAvailable = this.context.Repository.GVFSLock.IsLockAvailableForExternalRequestor(out existingExternalHolder);
bool isReadyForExternalLockRequests = this.fileSystemCallbacks.IsReadyForExternalAcquireLockRequests(requester, out denyGVFSMessage);
if (!requester.CheckAvailabilityOnly && isReadyForExternalLockRequests)
{
lockAcquired = this.context.Repository.GVFSLock.TryAcquireLockForExternalRequestor(requester, out existingExternalHolder);
}
if (requester.CheckAvailabilityOnly && lockAvailable && isReadyForExternalLockRequests)
{
response = new NamedPipeMessages.AcquireLock.Response(NamedPipeMessages.AcquireLock.AvailableResult);
}
else if (lockAcquired)
{
response = new NamedPipeMessages.AcquireLock.Response(NamedPipeMessages.AcquireLock.AcceptResult);
this.tracer.SetGitCommandSessionId(requester.GitCommandSessionId);
}
else if (existingExternalHolder == null)
{
response = new NamedPipeMessages.AcquireLock.Response(NamedPipeMessages.AcquireLock.DenyGVFSResult, responseData: null, denyGVFSMessage: denyGVFSMessage);
}
else
{
response = new NamedPipeMessages.AcquireLock.Response(NamedPipeMessages.AcquireLock.DenyGitResult, existingExternalHolder);
}
}
connection.TrySendResponse(response.CreateMessage());
}
private void HandleReleaseLockRequest(string messageBody, NamedPipeServer.Connection connection)
{
NamedPipeMessages.LockRequest request = new NamedPipeMessages.LockRequest(messageBody);
if (request.RequestData == null)
{
this.tracer.RelatedError($"{nameof(this.HandleReleaseLockRequest)} received invalid lock request with body '{messageBody}'");
this.UnmountAndStopWorkingDirectoryCallbacks();
Environment.Exit((int)ReturnCode.NullRequestData);
}
NamedPipeMessages.ReleaseLock.Response response = this.fileSystemCallbacks.TryReleaseExternalLock(request.RequestData.PID);
if (response.Result == NamedPipeMessages.ReleaseLock.SuccessResult)
{
this.tracer.SetGitCommandSessionId(string.Empty);
}
connection.TrySendResponse(response.CreateMessage());
}
private void HandlePostIndexChangedRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.PostIndexChanged.Response response;
NamedPipeMessages.PostIndexChanged.Request request = new NamedPipeMessages.PostIndexChanged.Request(message);
if (request == null)
{
response = new NamedPipeMessages.PostIndexChanged.Response(NamedPipeMessages.UnknownRequest);
}
else if (this.currentState != MountState.Ready)
{
response = new NamedPipeMessages.PostIndexChanged.Response(NamedPipeMessages.MountNotReadyResult);
}
else
{
if (this.resetForDehydrateInProgress)
{
// To avoid having to parse the index twice when dehydrating folders, repurpose the PostIndexChangedRequest
// for git reset to rebuild the projection. Additionally, if we were to call ForceIndexProjectionUpdate
// directly in HandleDehydrateFolders we'd have a race condition where the OnIndexWriteRequiringModifiedPathsValidation
// background task would be trying to parse the index at the same time as HandleDehydrateFolders
this.fileSystemCallbacks.ForceIndexProjectionUpdate(invalidateProjection: true, invalidateModifiedPaths: false);
}
else
{
this.fileSystemCallbacks.ForceIndexProjectionUpdate(request.UpdatedWorkingDirectory, request.UpdatedSkipWorktreeBits);
}
response = new NamedPipeMessages.PostIndexChanged.Response(NamedPipeMessages.PostIndexChanged.SuccessResult);
}
connection.TrySendResponse(response.CreateMessage());
}
/// <summary>
/// Handles a request to prepare for an unstage operation (e.g., restore --staged).
/// Finds index entries that are staged (not in HEAD) with skip-worktree set and adds
/// them to ModifiedPaths so that git will clear skip-worktree and process them.
/// Also forces a projection update to fix stale placeholders for modified/deleted files.
/// </summary>
private void HandlePrepareForUnstageRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.PrepareForUnstage.Response response;
if (this.currentState != MountState.Ready)
{
response = new NamedPipeMessages.PrepareForUnstage.Response(NamedPipeMessages.MountNotReadyResult);
}
else
{
try
{
string pathspec = message.Body;
bool success = this.fileSystemCallbacks.AddStagedFilesToModifiedPaths(pathspec, out int addedCount);
EventMetadata metadata = new EventMetadata();
metadata.Add("addedToModifiedPaths", addedCount);
metadata.Add("pathspec", pathspec ?? "(all)");
metadata.Add("success", success);
this.tracer.RelatedEvent(
EventLevel.Informational,
nameof(this.HandlePrepareForUnstageRequest),
metadata);
response = new NamedPipeMessages.PrepareForUnstage.Response(
success
? NamedPipeMessages.PrepareForUnstage.SuccessResult
: NamedPipeMessages.PrepareForUnstage.FailureResult);
}
catch (Exception e)
{
EventMetadata metadata = new EventMetadata();
metadata.Add("Exception", e.ToString());
this.tracer.RelatedError(metadata, nameof(this.HandlePrepareForUnstageRequest) + " failed");
response = new NamedPipeMessages.PrepareForUnstage.Response(NamedPipeMessages.PrepareForUnstage.FailureResult);
}
}
connection.TrySendResponse(response.CreateMessage());
}
private void HandleModifiedPathsListRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.ModifiedPaths.Response response;
NamedPipeMessages.ModifiedPaths.Request request = new NamedPipeMessages.ModifiedPaths.Request(message);
if (request == null)
{
response = new NamedPipeMessages.ModifiedPaths.Response(NamedPipeMessages.UnknownRequest);
}
else if (this.currentState != MountState.Ready)
{
response = new NamedPipeMessages.ModifiedPaths.Response(NamedPipeMessages.MountNotReadyResult);
}
else
{
if (request.Version != NamedPipeMessages.ModifiedPaths.CurrentVersion)
{
response = new NamedPipeMessages.ModifiedPaths.Response(NamedPipeMessages.ModifiedPaths.InvalidVersion);
}
else
{
string data = string.Join("\0", this.fileSystemCallbacks.GetAllModifiedPaths()) + "\0";
response = new NamedPipeMessages.ModifiedPaths.Response(NamedPipeMessages.ModifiedPaths.SuccessResult, data);
}
}
connection.TrySendResponse(response.CreateMessage());
}
private void HandleDownloadObjectRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.DownloadObject.Response response;
NamedPipeMessages.DownloadObject.Request request = new NamedPipeMessages.DownloadObject.Request(message);
string objectSha = request.RequestSha;
if (this.currentState != MountState.Ready)
{
response = new NamedPipeMessages.DownloadObject.Response(NamedPipeMessages.MountNotReadyResult);
}
else
{
if (!SHA1Util.IsValidShaFormat(objectSha))
{
response = new NamedPipeMessages.DownloadObject.Response(NamedPipeMessages.DownloadObject.InvalidSHAResult);
}
else
{
Stopwatch downloadTime = Stopwatch.StartNew();
/* If this is the root tree for a commit that was was just downloaded, assume that more
* trees will be needed soon and download them as well by using the download commit API.
*
* Otherwise, or as a fallback if the commit download fails, download the object directly.
*/
if (this.ShouldDownloadCommitPack(objectSha, out string commitSha)
&& this.gitObjects.TryDownloadCommit(commitSha))
{
this.DownloadedCommitPack(commitSha);
response = new NamedPipeMessages.DownloadObject.Response(NamedPipeMessages.DownloadObject.SuccessResult);
// FUTURE: Should the stats be updated to reflect all the trees in the pack?
// FUTURE: Should we try to clean up duplicate trees or increase depth of the commit download?
}
else if (this.gitObjects.TryDownloadAndSaveObject(objectSha, GVFSGitObjects.RequestSource.NamedPipeMessage) == GitObjects.DownloadAndSaveObjectResult.Success)
{
this.UpdateTreesForDownloadedCommits(objectSha);
response = new NamedPipeMessages.DownloadObject.Response(NamedPipeMessages.DownloadObject.SuccessResult);
}
else
{
response = new NamedPipeMessages.DownloadObject.Response(NamedPipeMessages.DownloadObject.DownloadFailed);
}
Native.ObjectTypes? objectType;
this.context.Repository.TryGetObjectType(objectSha, out objectType);
this.context.Repository.GVFSLock.Stats.RecordObjectDownload(objectType == Native.ObjectTypes.Blob, downloadTime.ElapsedMilliseconds);
if (objectType == Native.ObjectTypes.Commit
&& !this.context.Repository.CommitAndRootTreeExists(objectSha, out var treeSha)
&& !string.IsNullOrEmpty(treeSha))
{
/* If a commit is downloaded, it wasn't prefetched.
* The trees for the commit may be needed soon depending on the context.
* e.g. git log (without a pathspec) doesn't need trees, but git checkout does.
*
* If any prefetch has been done there is probably a similar commit/tree in the graph,
* but in case there isn't (such as if the cache server repack maintenance job is failing)
* we should still try to avoid downloading an excessive number of loose trees for a commit.
*
* Save the tree/commit so if more trees are requested we can download all the trees for the commit in a batch.
*/
this.missingTreeTracker.AddMissingRootTree(treeSha: treeSha, commitSha: objectSha);
}
}
}
connection.TrySendResponse(response.CreateMessage());
}
private bool ShouldDownloadCommitPack(string objectSha, out string commitSha)
{
if (!this.missingTreeTracker.TryGetCommits(objectSha, out string[] commitShas))
{
commitSha = null;
return false;
}
/* This is a heuristic to prevent downloading multiple packs related to git history commands.
* Closely related commits are likely to have similar trees, so we'll find fewer missing trees in them.
* Conversely, if we know (from previously downloaded missing trees) that a commit has a lot of missing
* trees left, we'll probably need to download many more trees for the commit so we should download the pack.
*/
int missingTreeCount = this.missingTreeTracker.GetHighestMissingTreeCount(commitShas, out commitSha);
return missingTreeCount > MissingTreeThresholdForDownloadingCommitPack;
}
private void UpdateTreesForDownloadedCommits(string objectSha)
{
/* If we are downloading missing trees, we probably are missing more trees for the commit.
* Update our list of trees associated with the commit so we can use the # of missing trees
* as a heuristic to decide whether to batch download all the trees for the commit the
* next time a missing one is requested.
*/
if (!this.missingTreeTracker.TryGetCommits(objectSha, out _))
{
return;
}
if (!this.context.Repository.TryGetObjectType(objectSha, out var objectType)
|| objectType != Native.ObjectTypes.Tree)
{
return;
}
if (this.context.Repository.TryGetMissingSubTrees(objectSha, out var missingSubTrees))
{
this.missingTreeTracker.AddMissingSubTrees(objectSha, missingSubTrees);
}
}
private void DownloadedCommitPack(string commitSha)
{
this.missingTreeTracker.MarkCommitComplete(commitSha);
}
private void HandlePostFetchJobRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.RunPostFetchJob.Request request = new NamedPipeMessages.RunPostFetchJob.Request(message);
this.tracer.RelatedInfo("Received post-fetch job request with body {0}", message.Body);
NamedPipeMessages.RunPostFetchJob.Response response;
if (this.currentState == MountState.Ready)
{
List<string> packIndexes = GVFSJsonOptions.Deserialize<List<string>>(message.Body);
this.maintenanceScheduler.EnqueueOneTimeStep(new PostFetchStep(this.context, packIndexes));
response = new NamedPipeMessages.RunPostFetchJob.Response(NamedPipeMessages.RunPostFetchJob.QueuedResult);
}
else
{
response = new NamedPipeMessages.RunPostFetchJob.Response(NamedPipeMessages.RunPostFetchJob.MountNotReadyResult);
}