-
Notifications
You must be signed in to change notification settings - Fork 451
/
BackgroundFileSystemTaskRunner.cs
323 lines (277 loc) · 11.8 KB
/
BackgroundFileSystemTaskRunner.cs
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
using GVFS.Common;
using GVFS.Common.FileSystem;
using GVFS.Common.Tracing;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace GVFS.Virtualization.Background
{
public class BackgroundFileSystemTaskRunner : IDisposable
{
private const int ActionRetryDelayMS = 50;
private const int RetryFailuresLogThreshold = 200;
private const int LogUpdateTaskThreshold = 25000;
private static readonly string EtwArea = nameof(BackgroundFileSystemTaskRunner);
private FileSystemTaskQueue backgroundTasks;
private AutoResetEvent wakeUpThread;
private Task backgroundThread;
private bool isStopping;
private GVFSContext context;
// TODO 656051: Replace these callbacks with an interface
private Func<FileSystemTaskResult> preCallback;
private Func<FileSystemTask, FileSystemTaskResult> callback;
private Func<FileSystemTaskResult> postCallback;
public BackgroundFileSystemTaskRunner(
GVFSContext context,
Func<FileSystemTaskResult> preCallback,
Func<FileSystemTask, FileSystemTaskResult> callback,
Func<FileSystemTaskResult> postCallback,
string databasePath)
{
this.context = context;
this.preCallback = preCallback;
this.callback = callback;
this.postCallback = postCallback;
string error;
if (!FileSystemTaskQueue.TryCreate(
this.context.Tracer,
databasePath,
new PhysicalFileSystem(),
out this.backgroundTasks,
out error))
{
string message = "Failed to create new background tasks folder: " + error;
context.Tracer.RelatedError(message);
throw new InvalidRepoException(message);
}
this.wakeUpThread = new AutoResetEvent(true);
}
// For Unit Testing
protected BackgroundFileSystemTaskRunner()
{
}
private enum AcquireGVFSLockResult
{
LockAcquired,
ShuttingDown
}
public virtual int Count
{
get { return this.backgroundTasks.Count; }
}
public virtual void SetCallbacks(
Func<FileSystemTaskResult> preCallback,
Func<FileSystemTask, FileSystemTaskResult> callback,
Func<FileSystemTaskResult> postCallback)
{
throw new NotSupportedException("This method is only meant for unit tests, and must be implemented by test class if necessary for use in tests");
}
public virtual void Start()
{
this.backgroundThread = Task.Factory.StartNew((Action)this.ProcessBackgroundTasks, TaskCreationOptions.LongRunning);
if (this.backgroundTasks.Count > 0)
{
this.wakeUpThread.Set();
}
}
public virtual void Enqueue(FileSystemTask backgroundTask)
{
this.backgroundTasks.EnqueueAndFlush(backgroundTask);
if (!this.isStopping)
{
this.wakeUpThread.Set();
}
}
public virtual void Shutdown()
{
this.isStopping = true;
this.wakeUpThread.Set();
this.backgroundThread.Wait();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (this.backgroundThread != null)
{
this.backgroundThread.Dispose();
this.backgroundThread = null;
}
}
private AcquireGVFSLockResult WaitToAcquireGVFSLock()
{
int attempts = 0;
while (!this.context.Repository.GVFSLock.TryAcquireLockForGVFS())
{
if (this.isStopping)
{
return AcquireGVFSLockResult.ShuttingDown;
}
++attempts;
if (attempts > RetryFailuresLogThreshold)
{
this.context.Tracer.RelatedWarning($"{nameof(this.WaitToAcquireGVFSLock)}: {nameof(BackgroundFileSystemTaskRunner)} unable to acquire lock, retrying");
attempts = 0;
}
Thread.Sleep(ActionRetryDelayMS);
}
return AcquireGVFSLockResult.LockAcquired;
}
private void ProcessBackgroundTasks()
{
FileSystemTask backgroundTask;
while (true)
{
AcquireGVFSLockResult acquireLockResult = AcquireGVFSLockResult.ShuttingDown;
try
{
this.wakeUpThread.WaitOne();
if (this.isStopping)
{
return;
}
acquireLockResult = this.WaitToAcquireGVFSLock();
switch (acquireLockResult)
{
case AcquireGVFSLockResult.LockAcquired:
break;
case AcquireGVFSLockResult.ShuttingDown:
return;
default:
this.LogErrorAndExit("Invalid " + nameof(AcquireGVFSLockResult) + " result");
return;
}
this.RunCallbackUntilSuccess(this.preCallback, "PreCallback");
int tasksProcessed = 0;
while (this.backgroundTasks.TryPeek(out backgroundTask))
{
if (tasksProcessed % LogUpdateTaskThreshold == 0 &&
(tasksProcessed >= LogUpdateTaskThreshold || this.backgroundTasks.Count >= LogUpdateTaskThreshold))
{
this.LogTaskProcessingStatus(tasksProcessed);
}
if (this.isStopping)
{
// If we are stopping, then ProjFS has already been shut down
// Some of the queued background tasks may require ProjFS, and so it is unsafe to
// proceed. GVFS will resume any queued tasks next time it is mounted
return;
}
FileSystemTaskResult callbackResult = this.callback(backgroundTask);
switch (callbackResult)
{
case FileSystemTaskResult.Success:
this.backgroundTasks.DequeueAndFlush(backgroundTask);
++tasksProcessed;
break;
case FileSystemTaskResult.RetryableError:
if (!this.isStopping)
{
Thread.Sleep(ActionRetryDelayMS);
}
break;
case FileSystemTaskResult.FatalError:
this.LogErrorAndExit("Callback encountered fatal error, exiting process");
break;
default:
this.LogErrorAndExit("Invalid background operation result");
break;
}
}
if (tasksProcessed >= LogUpdateTaskThreshold)
{
EventMetadata metadata = new EventMetadata();
metadata.Add("Area", EtwArea);
metadata.Add("TasksProcessed", tasksProcessed);
metadata.Add(TracingConstants.MessageKey.InfoMessage, "Processing background tasks complete");
this.context.Tracer.RelatedEvent(EventLevel.Informational, "TaskProcessingStatus", metadata);
}
if (this.isStopping)
{
return;
}
}
catch (Exception e)
{
this.LogErrorAndExit($"{nameof(this.ProcessBackgroundTasks)} caught unhandled exception, exiting process", e);
}
finally
{
this.PerformPostTaskProcessing(acquireLockResult);
}
}
}
private void PerformPostTaskProcessing(AcquireGVFSLockResult acquireLockResult)
{
try
{
if (acquireLockResult == AcquireGVFSLockResult.LockAcquired)
{
this.RunCallbackUntilSuccess(this.postCallback, "PostCallback");
if (this.backgroundTasks.Count == 0)
{
this.context.Repository.GVFSLock.ReleaseLockHeldByGVFS();
}
}
}
catch (Exception e)
{
this.LogErrorAndExit($"{nameof(this.ProcessBackgroundTasks)} caught unhandled exception in {nameof(this.PerformPostTaskProcessing)}, exiting process", e);
}
}
private void RunCallbackUntilSuccess(Func<FileSystemTaskResult> callback, string errorHeader)
{
int attempts = 0;
while (true)
{
FileSystemTaskResult callbackResult = callback();
switch (callbackResult)
{
case FileSystemTaskResult.Success:
return;
case FileSystemTaskResult.RetryableError:
if (this.isStopping)
{
return;
}
++attempts;
if (attempts > RetryFailuresLogThreshold)
{
this.context.Tracer.RelatedWarning("RunCallbackUntilSuccess(" + errorHeader + "): callback failed, retrying");
attempts = 0;
}
Thread.Sleep(ActionRetryDelayMS);
break;
case FileSystemTaskResult.FatalError:
this.LogErrorAndExit(errorHeader + " encountered fatal error, exiting process");
return;
default:
this.LogErrorAndExit(errorHeader + " result could not be found");
return;
}
}
}
private void LogErrorAndExit(string message, Exception e = null)
{
EventMetadata metadata = new EventMetadata();
metadata.Add("Area", EtwArea);
if (e != null)
{
metadata.Add("Exception", e.ToString());
}
this.context.Tracer.RelatedError(metadata, message);
Environment.Exit(1);
}
private void LogTaskProcessingStatus(int tasksProcessed)
{
EventMetadata metadata = new EventMetadata();
metadata.Add("BackgroundOperations", EtwArea);
metadata.Add("TasksProcessed", tasksProcessed);
metadata.Add("TasksRemaining", this.backgroundTasks.Count);
this.context.Tracer.RelatedEvent(EventLevel.Informational, "TaskProcessingStatus", metadata);
}
}
}