forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphLockFile.cs
More file actions
180 lines (163 loc) · 6.6 KB
/
Copy pathGraphLockFile.cs
File metadata and controls
180 lines (163 loc) · 6.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
using System;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
namespace Dynamo.Graph.Workspaces.Locking
{
/// <summary>
/// Describes the outcome of a <see cref="GraphLockFile.TryRead"/> call.
/// </summary>
internal enum GraphLockReadResult
{
NotFound,
Ok,
Corrupt,
TransientFailure
}
/// <summary>
/// Provides file-system operations for graph lock sidecar files.
/// </summary>
internal static class GraphLockFile
{
private static readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings
{
Culture = System.Globalization.CultureInfo.InvariantCulture,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
Formatting = Formatting.Indented,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.None
});
private static bool IsValidLockInfo(GraphLockInfo info) =>
info != null
&& info.SessionId != Guid.Empty
&& !string.IsNullOrEmpty(info.GraphPath)
&& info.ProcessId > 0;
/// <summary>
/// Gets the sidecar lock path for a graph file.
/// </summary>
/// <param name="graphPath">The graph file path.</param>
/// <returns>The sidecar lock file path.</returns>
internal static string GetLockFilePath(string graphPath)
{
return Path.GetFullPath(graphPath) + ".dynlock";
}
/// <summary>
/// Attempts to create a lock file only if it does not already exist.
/// </summary>
/// <param name="sidecarPath">The sidecar lock file path.</param>
/// <param name="info">The lock metadata to write.</param>
/// <returns>True if the lock file was created, false if one already exists.</returns>
internal static bool TryCreateNewLockFile(string sidecarPath, GraphLockInfo info)
{
try
{
using (var stream = new FileStream(sidecarPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
Serializer.Serialize(writer, info);
}
return true;
}
catch (IOException) when (File.Exists(sidecarPath))
{
return false;
}
}
/// <summary>
/// Attempts to read graph-lock metadata from a sidecar file.
/// </summary>
/// <param name="sidecarPath">The sidecar lock file path.</param>
/// <param name="info">The parsed lock metadata when reading succeeds.</param>
/// <returns>True if metadata was read; otherwise false.</returns>
internal static GraphLockReadResult TryRead(string sidecarPath, out GraphLockInfo info)
{
info = null;
if (!File.Exists(sidecarPath))
return GraphLockReadResult.NotFound;
const int maxAttempts = 2;
for (var attempt = 0; attempt < maxAttempts; attempt++)
{
try
{
using (var stream = File.Open(sidecarPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var reader = new StreamReader(stream, Encoding.UTF8))
using (var jsonReader = new JsonTextReader(reader))
{
info = Serializer.Deserialize<GraphLockInfo>(jsonReader);
}
return IsValidLockInfo(info) ? GraphLockReadResult.Ok : GraphLockReadResult.Corrupt;
}
catch (Exception ex) when (ex is JsonException)
{
return GraphLockReadResult.Corrupt;
}
catch (Exception ex) when (ex is IOException)
{
if (attempt == maxAttempts - 1)
return GraphLockReadResult.TransientFailure;
Thread.Sleep(50);
}
catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SecurityException)
{
return GraphLockReadResult.TransientFailure;
}
}
return GraphLockReadResult.TransientFailure;
}
/// <summary>
/// Updates a lock file heartbeat using a temp file and replace operation.
/// </summary>
/// <param name="sidecarPath">The sidecar lock file path.</param>
/// <param name="info">The lock metadata to write.</param>
internal static void WriteHeartbeat(string sidecarPath, GraphLockInfo info)
{
var tempPath = sidecarPath + ".tmp";
var replaced = false;
try
{
using (var stream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
Serializer.Serialize(writer, info);
}
try
{
File.Replace(tempPath, sidecarPath, null, true);
}
catch (Exception ex) when (ex is IOException || ex is PlatformNotSupportedException || ex is UnauthorizedAccessException)
{
File.Move(tempPath, sidecarPath, true);
}
replaced = true;
}
finally
{
// If the swap never completed (e.g. serialization threw), don't leave a stray scratch file.
if (!replaced && File.Exists(tempPath))
{
TryDelete(tempPath);
}
}
}
/// <summary>
/// Attempts to delete a sidecar lock file without throwing.
/// </summary>
/// <param name="sidecarPath">The sidecar lock file path.</param>
internal static void TryDelete(string sidecarPath)
{
try
{
File.Delete(sidecarPath);
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
{
Debug.WriteLine("GraphLock cleanup delete failed: " + ex.Message);
}
}
}
}