forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphLockManager.cs
More file actions
637 lines (557 loc) · 24.6 KB
/
Copy pathGraphLockManager.cs
File metadata and controls
637 lines (557 loc) · 24.6 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
using Dynamo.Models;
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading;
namespace Dynamo.Graph.Workspaces.Locking
{
/// <summary>
/// Coordinates graph lock acquisition, heartbeat, and release for a Dynamo model.
/// </summary>
internal sealed class GraphLockManager : IDisposable
{
internal const int DefaultHeartbeatMilliseconds = 15000;
private const int StaleFactor = 3;
private const int MaxConsecutiveReadFailures = 3;
private readonly DynamoModel dynamoModel;
private readonly StringComparer pathComparer;
private readonly ConcurrentDictionary<string, OwnedLock> locks;
private readonly ConcurrentDictionary<string, byte> openingPaths;
private readonly Guid sessionId;
private readonly int processId;
private readonly DateTime processStartTimeUtc;
private readonly string machineName;
private readonly int heartbeatMilliseconds;
private readonly bool enabled;
private Timer heartbeatTimer;
private IGraphLockUserPrompt prompt;
private bool disposed;
private sealed class OwnedLock
{
internal string SidecarPath { get; set; }
internal GraphLockInfo Info { get; set; }
internal WorkspaceModel Workspace { get; set; }
internal int ConsecutiveReadFailures { get; set; }
}
/// <summary>
/// Initializes a graph lock manager for a Dynamo model.
/// </summary>
/// <param name="dynamoModel">The Dynamo model whose workspaces are tracked.</param>
/// <param name="prompt">The UI prompt used when a graph lock conflict is found.</param>
/// <param name="heartbeatMilliseconds">The heartbeat interval for owned locks.</param>
/// <param name="forceEnable">True to enable locking in modes that normally skip it.</param>
internal GraphLockManager(DynamoModel dynamoModel, IGraphLockUserPrompt prompt = null, int heartbeatMilliseconds = DefaultHeartbeatMilliseconds, bool forceEnable = false)
{
this.dynamoModel = dynamoModel;
this.prompt = prompt;
this.heartbeatMilliseconds = heartbeatMilliseconds;
pathComparer = StringComparer.OrdinalIgnoreCase;
locks = new ConcurrentDictionary<string, OwnedLock>(pathComparer);
openingPaths = new ConcurrentDictionary<string, byte>(pathComparer);
sessionId = Guid.NewGuid();
machineName = Environment.MachineName;
using (var process = Process.GetCurrentProcess())
{
processId = process.Id;
processStartTimeUtc = GetProcessStartTimeUtc(process);
}
enabled = forceEnable || (!DynamoModel.IsTestMode && !DynamoModel.IsHeadless && !dynamoModel.IsServiceMode);
if (!enabled)
{
return;
}
dynamoModel.WorkspaceAdded += OnWorkspaceAdded;
dynamoModel.WorkspaceRemoveStarted += OnWorkspaceRemoveStarted;
dynamoModel.WorkspaceRemoved += OnWorkspaceRemoved;
dynamoModel.WorkspaceClearingStarted += OnWorkspaceClearingStarted;
dynamoModel.ShutdownStarted += OnShutdownStarted;
AppDomain.CurrentDomain.ProcessExit += ReleaseAll;
AppDomain.CurrentDomain.UnhandledException += ReleaseAll;
heartbeatTimer = new Timer(RefreshHeartbeats, null, this.heartbeatMilliseconds, this.heartbeatMilliseconds);
}
/// <summary>
/// Sets the UI prompt used when a graph lock conflict is detected.
/// </summary>
/// <param name="userPrompt">The prompt implementation, or null to cancel conflicts silently.</param>
internal void SetPrompt(IGraphLockUserPrompt userPrompt)
{
prompt = userPrompt;
}
/// <summary>
/// Attempts to acquire a graph lock before opening a graph file.
/// </summary>
/// <param name="graphPath">The graph path requested by the user.</param>
/// <param name="allowPromptUI">True to allow user interaction when a conflict is found.</param>
/// <returns>The lock acquisition result and graph path to open.</returns>
internal GraphLockAcquireResult AcquireLock(string graphPath, bool allowPromptUI)
{
if (!enabled || string.IsNullOrEmpty(graphPath))
{
return GraphLockAcquireResult.Acquired(graphPath);
}
var normalizedPath = Path.GetFullPath(graphPath);
openingPaths[normalizedPath] = 0;
var result = AcquireLockInternal(normalizedPath, allowPromptUI, null);
if (!IsSamePath(normalizedPath, result.GraphPath))
{
openingPaths.TryRemove(normalizedPath, out _);
}
return result;
}
/// <summary>
/// Completes a graph open attempt and releases the lock if opening failed.
/// </summary>
/// <param name="graphPath">The graph path that was opened.</param>
/// <param name="succeeded">Whether the graph opened successfully.</param>
internal void CompleteOpen(string graphPath, bool succeeded)
{
if (!enabled || string.IsNullOrEmpty(graphPath))
{
return;
}
var normalizedPath = Path.GetFullPath(graphPath);
openingPaths.TryRemove(normalizedPath, out _);
if (!succeeded)
{
Release(normalizedPath);
}
}
/// <summary>
/// Releases the lock for a graph path.
/// </summary>
/// <param name="graphPath">The graph path whose lock should be released.</param>
internal void Release(string graphPath)
{
if (!enabled || string.IsNullOrEmpty(graphPath))
{
return;
}
var normalizedPath = Path.GetFullPath(graphPath);
if (openingPaths.ContainsKey(normalizedPath))
{
return;
}
if (locks.TryRemove(normalizedPath, out var owned))
{
ReleaseOwnedLock(normalizedPath, owned);
}
}
/// <summary>
/// Releases every lock owned by this manager.
/// </summary>
/// <param name="sender">Optional event sender.</param>
/// <param name="args">Optional event arguments.</param>
internal void ReleaseAll(object sender = null, EventArgs args = null)
{
foreach (var path in locks.Keys.ToList())
{
Release(path);
}
heartbeatTimer?.Dispose();
heartbeatTimer = null;
}
private GraphLockAcquireResult AcquireLockInternal(string normalizedPath, bool allowPromptUI, WorkspaceModel workspace)
{
var sidecarPath = GraphLockFile.GetLockFilePath(normalizedPath);
var info = BuildLockInfoForThisSession(normalizedPath);
for (var attempt = 0; attempt < 2; attempt++)
{
try
{
// No lock yet: create one and we are done
if (GraphLockFile.TryCreateNewLockFile(sidecarPath, info))
{
RegisterOwnedLock(normalizedPath, sidecarPath, info, workspace);
return GraphLockAcquireResult.Acquired(normalizedPath);
}
// A lock file already exists: read it to find out who owns it
var readResult = GraphLockFile.TryRead(sidecarPath, out var existingLock);
if (readResult == GraphLockReadResult.NotFound)
{
// The sidecar was deleted between TryCreateNewLockFile failing and TryRead.
// Retry the loop — TryCreateNewLockFile will succeed on the next attempt.
continue;
}
var lockResult = TryAcquireReadableLock(normalizedPath, sidecarPath, info, workspace, readResult, existingLock);
if (lockResult != null)
{
return lockResult;
}
// ExistingLock is Ok and live — a real conflict with another session.
return ResolveLockConflict(normalizedPath, allowPromptUI, workspace, existingLock);
}
catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException || ex is IOException)
{
dynamoModel.Logger?.Log("GraphLock unavailable: " + ex.Message);
}
}
return GraphLockAcquireResult.Unavailable(normalizedPath);
}
private GraphLockAcquireResult TryAcquireReadableLock(
string normalizedPath,
string sidecarPath,
GraphLockInfo info,
WorkspaceModel workspace,
GraphLockReadResult readResult,
GraphLockInfo existingLock)
{
if (readResult == GraphLockReadResult.Corrupt)
{
// Definitively unreadable — not evidence of a live owner.
// Safe to overwrite and take ownership.
GraphLockFile.WriteHeartbeat(sidecarPath, info);
RegisterOwnedLock(normalizedPath, sidecarPath, info, workspace);
return GraphLockAcquireResult.Acquired(normalizedPath);
}
if (readResult == GraphLockReadResult.TransientFailure)
{
// Could not read due to IO/permissions — a live owner may exist.
// Do not steal the lock. Redirect to copy to be safe.
dynamoModel.Logger?.Log( "GraphLock: could not read sidecar due to transient failure, redirecting to copy: " + sidecarPath);
return GraphLockAcquireResult.Unavailable(normalizedPath);
}
if (IsOwnedByThisSession(existingLock))
{
RegisterOwnedLock(normalizedPath, sidecarPath, existingLock, workspace);
return GraphLockAcquireResult.Acquired(normalizedPath);
}
// The lock is expired (no recent heartbeat) or owned by a process on this machine
// that is no longer running. Silently take ownership.
if (IsStale(existingLock) || IsDeadLocalProcess(existingLock))
{
GraphLockFile.WriteHeartbeat(sidecarPath, info);
RegisterOwnedLock(normalizedPath, sidecarPath, info, workspace);
return GraphLockAcquireResult.Acquired(normalizedPath);
}
return null;
}
private GraphLockAcquireResult ResolveLockConflict(string normalizedPath, bool allowPromptUI, WorkspaceModel workspace, GraphLockInfo existingLock)
{
if (allowPromptUI && prompt != null)
{
// Ask the user to cancel or save a copy to open instead
var response = prompt.AskUser(normalizedPath, existingLock);
return response.ShouldSaveAs
? CreateAndOpenCopy(normalizedPath, response.SaveAsPath, workspace, existingLock)
: GraphLockAcquireResult.Cancelled(existingLock);
}
if (allowPromptUI)
{
// UI prompts are allowed but no prompt is wired yet (for example, a file opened
// before the view model attached its prompt). Do not block the open: proceed
// without a lock rather than silently aborting the open
return GraphLockAcquireResult.Unavailable(normalizedPath);
}
return GraphLockAcquireResult.Cancelled(existingLock);
}
// Copies a locked graph to a user-selected path and locks that copy before opening
private GraphLockAcquireResult CreateAndOpenCopy( string sourcePath, string saveAsPath, WorkspaceModel workspace, GraphLockInfo existingLock)
{
if (string.IsNullOrWhiteSpace(saveAsPath))
{
return GraphLockAcquireResult.Cancelled(existingLock);
}
var normalizedSaveAsPath = Path.GetFullPath(saveAsPath);
if (IsSamePath(sourcePath, normalizedSaveAsPath))
{
return GraphLockAcquireResult.Cancelled(existingLock);
}
var sidecarPath = GraphLockFile.GetLockFilePath(normalizedSaveAsPath);
var info = BuildLockInfoForThisSession(normalizedSaveAsPath);
var ownsSaveAsLock = false;
try
{
if (GraphLockFile.TryCreateNewLockFile(sidecarPath, info))
{
ownsSaveAsLock = true;
}
else
{
GraphLockInfo saveAsLock;
var saveAsReadResult = GraphLockFile.TryRead(sidecarPath, out saveAsLock);
if (saveAsReadResult == GraphLockReadResult.Ok && IsOwnedByThisSession(saveAsLock))
{
info = saveAsLock;
ownsSaveAsLock = true;
}
else if (saveAsReadResult == GraphLockReadResult.Corrupt || IsStale(saveAsLock) || IsDeadLocalProcess(saveAsLock))
{
GraphLockFile.WriteHeartbeat(sidecarPath, info);
ownsSaveAsLock = true;
}
else
{
return GraphLockAcquireResult.Cancelled(saveAsLock);
}
}
File.Copy(sourcePath, normalizedSaveAsPath, true);
openingPaths[normalizedSaveAsPath] = 0;
RegisterOwnedLock(normalizedSaveAsPath, sidecarPath, info, workspace);
return GraphLockAcquireResult.Acquired(normalizedSaveAsPath);
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
{
dynamoModel.Logger?.Log("GraphLock save-as copy failed: " + ex.Message);
if (ownsSaveAsLock)
{
ReleaseOwnedLock(normalizedSaveAsPath, new OwnedLock { SidecarPath = sidecarPath, Info = info });
}
return GraphLockAcquireResult.Cancelled(existingLock);
}
}
private void RegisterOwnedLock(string normalizedPath, string sidecarPath, GraphLockInfo info, WorkspaceModel workspace)
{
locks[normalizedPath] = new OwnedLock
{
SidecarPath = sidecarPath,
Info = info,
Workspace = workspace
};
}
internal void RefreshHeartbeats(object state = null)
{
foreach (var pair in locks.ToList())
{
var owned = pair.Value;
try
{
GraphLockInfo current;
if (GraphLockFile.TryRead(owned.SidecarPath, out current) != GraphLockReadResult.Ok)
{
// Transient IO failure (antivirus, NAS hiccup) — don't drop the lock immediately.
// Only abandon after MaxConsecutiveReadFailures consecutive misses.
owned.ConsecutiveReadFailures++;
if (owned.ConsecutiveReadFailures >= MaxConsecutiveReadFailures)
{
dynamoModel.Logger?.Log(
$"GraphLock heartbeat read failed {MaxConsecutiveReadFailures} consecutive times, " +
$"dropping lock: {owned.SidecarPath}");
locks.TryRemove(pair.Key, out _);
}
else
{
dynamoModel.Logger?.Log(
$"GraphLock heartbeat read failed (attempt {owned.ConsecutiveReadFailures}), " +
$"will retry: {owned.SidecarPath}");
}
continue;
}
// Successful read — reset the failure counter
owned.ConsecutiveReadFailures = 0;
if (current.SessionId != owned.Info.SessionId)
{
// Lock was genuinely stolen by another instance — stop tracking
locks.TryRemove(pair.Key, out _);
continue;
}
owned.Info.LastHeartbeatUtc = DateTime.UtcNow;
GraphLockFile.WriteHeartbeat(owned.SidecarPath, owned.Info);
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
{
dynamoModel.Logger?.Log("GraphLock heartbeat failed: " + owned.SidecarPath + " - " + ex.Message);
}
}
}
private void ReleaseOwnedLock(string normalizedPath, OwnedLock owned)
{
try
{
GraphLockInfo current;
if (GraphLockFile.TryRead(owned.SidecarPath, out current) == GraphLockReadResult.Ok &&
current.SessionId == owned.Info.SessionId)
{
GraphLockFile.TryDelete(owned.SidecarPath);
}
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
{
dynamoModel.Logger?.Log("GraphLock release failed: " + normalizedPath + " - " + ex.Message);
}
}
private void OnWorkspaceAdded(WorkspaceModel workspace)
{
if (workspace == null || string.IsNullOrEmpty(workspace.FileName))
{
return;
}
var normalizedPath = Path.GetFullPath(workspace.FileName);
if (locks.TryGetValue(normalizedPath, out var owned))
{
owned.Workspace = workspace;
workspace.PropertyChanged += OnWorkspacePropertyChanged;
}
else if (!openingPaths.ContainsKey(normalizedPath))
{
// The workspace was added with Save As: acquire and register a lock so the saved
// file is protected against being opened by another Dynamo instance
AcquireLockInternal(normalizedPath, false, workspace);
}
workspace.PropertyChanged -= OnWorkspacePropertyChanged;
workspace.PropertyChanged += OnWorkspacePropertyChanged;
}
private void OnWorkspaceRemoveStarted(WorkspaceModel workspace)
{
ReleaseWorkspace(workspace);
}
private void OnWorkspaceRemoved(WorkspaceModel workspace)
{
if (workspace != null)
{
workspace.PropertyChanged -= OnWorkspacePropertyChanged;
ReleaseWorkspace(workspace);
}
}
private void OnWorkspaceClearingStarted(WorkspaceModel workspace)
{
ReleaseWorkspace(workspace);
}
private void OnWorkspacePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(WorkspaceModel.FileName))
{
return;
}
var workspace = sender as WorkspaceModel;
if (workspace == null || string.IsNullOrEmpty(workspace.FileName))
{
return;
}
var normalizedPath = Path.GetFullPath(workspace.FileName);
var oldPaths = locks
.Where(pair => pair.Value.Workspace == workspace && !IsSamePath(pair.Key, normalizedPath))
.Select(pair => pair.Key)
.ToList();
foreach (var oldPath in oldPaths)
{
Release(oldPath);
}
if (!locks.ContainsKey(normalizedPath))
{
AcquireLockInternal(normalizedPath, false, workspace);
}
}
private void OnShutdownStarted(DynamoModel model)
{
ReleaseAll();
}
private void ReleaseWorkspace(WorkspaceModel workspace)
{
if (workspace == null)
{
return;
}
var paths = locks
.Where(pair => pair.Value.Workspace == workspace)
.Select(pair => pair.Key)
.ToList();
foreach (var path in paths)
{
Release(path);
}
}
private bool IsStale(GraphLockInfo existingLock)
{
if (existingLock == null)
{
return true;
}
var ageSeconds = (DateTime.UtcNow - existingLock.LastHeartbeatUtc).TotalSeconds;
return ageSeconds > (heartbeatMilliseconds / 1000.0) * StaleFactor;
}
private bool IsOwnedByThisSession(GraphLockInfo existingLock)
{
return existingLock != null &&
(existingLock.SessionId == sessionId ||
(string.Equals(existingLock.MachineName, machineName, StringComparison.OrdinalIgnoreCase) &&
existingLock.ProcessId == processId &&
existingLock.ProcessStartUtc == processStartTimeUtc));
}
// Builds the lock metadata written by this Dynamo session
private GraphLockInfo BuildLockInfoForThisSession(string normalizedPath)
{
var now = DateTime.UtcNow;
return new GraphLockInfo
{
SessionId = sessionId,
GraphPath = normalizedPath,
MachineName = machineName,
ProcessId = processId,
ProcessStartUtc = processStartTimeUtc,
LastHeartbeatUtc = now
};
}
// Detects stale locks from dead processes on the same machine
private bool IsDeadLocalProcess(GraphLockInfo existingLock)
{
if (existingLock == null ||
!string.Equals(existingLock.MachineName, machineName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
try
{
using (var process = Process.GetProcessById(existingLock.ProcessId))
{
return GetProcessStartTimeUtc(process) != existingLock.ProcessStartUtc;
}
}
catch (ArgumentException)
{
return true;
}
catch (InvalidOperationException)
{
return true;
}
catch (Exception ex)
{
dynamoModel.Logger?.Log("GraphLock process liveness check failed: " + ex.Message);
return false;
}
}
private bool IsSamePath(string firstPath, string secondPath)
{
if (string.IsNullOrEmpty(firstPath) || string.IsNullOrEmpty(secondPath))
{
return false;
}
return pathComparer.Equals(Path.GetFullPath(firstPath), Path.GetFullPath(secondPath));
}
// Reads process start time safely because some platforms/processes can deny it
private static DateTime GetProcessStartTimeUtc(Process process)
{
try
{
return process.StartTime.ToUniversalTime();
}
catch (Exception)
{
return DateTime.MinValue;
}
}
/// <summary>
/// Releases owned graph locks and unsubscribes from Dynamo model events.
/// </summary>
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
dynamoModel.WorkspaceAdded -= OnWorkspaceAdded;
dynamoModel.WorkspaceRemoveStarted -= OnWorkspaceRemoveStarted;
dynamoModel.WorkspaceRemoved -= OnWorkspaceRemoved;
dynamoModel.WorkspaceClearingStarted -= OnWorkspaceClearingStarted;
dynamoModel.ShutdownStarted -= OnShutdownStarted;
AppDomain.CurrentDomain.ProcessExit -= ReleaseAll;
AppDomain.CurrentDomain.UnhandledException -= ReleaseAll;
ReleaseAll();
}
}
}