forked from Azure/azure-sdk-for-net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalTransferCheckpointer.cs
More file actions
447 lines (410 loc) · 17.6 KB
/
LocalTransferCheckpointer.cs
File metadata and controls
447 lines (410 loc) · 17.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Storage.Common;
using Azure.Storage.DataMovement.JobPlan;
using Azure.Storage.Shared;
namespace Azure.Storage.DataMovement
{
/// <summary>
/// Creates a checkpointer which uses a locally stored file to obtain
/// the information in order to resume transfers in the future.
/// </summary>
internal class LocalTransferCheckpointer : SerializerTransferCheckpointer
{
internal string _pathToCheckpointer;
/// <summary>
/// Stores references to the memory mapped files stored by IDs.
/// </summary>
private Dictionary<string, JobPlanFile> _transferStates;
/// <summary>
/// Initializes a new instance of <see cref="LocalTransferCheckpointer"/> class.
/// </summary>
/// <param name="folderPath">Path to the folder containing the checkpointing information to resume from.</param>
public LocalTransferCheckpointer(string folderPath)
{
_transferStates = new Dictionary<string, JobPlanFile>();
if (string.IsNullOrEmpty(folderPath))
{
_pathToCheckpointer = Path.Combine(Environment.CurrentDirectory, DataMovementConstants.DefaultCheckpointerPath);
if (!Directory.Exists(_pathToCheckpointer))
{
// If it does not already exist, create the default folder.
Directory.CreateDirectory(_pathToCheckpointer);
}
}
else if (!Directory.Exists(folderPath))
{
throw Errors.MissingCheckpointerPath(folderPath);
}
else
{
_pathToCheckpointer = folderPath;
InitializeExistingCheckpointer();
}
}
public override async Task AddNewJobAsync(
string transferId,
StorageResource source,
StorageResource destination,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(transferId, nameof(transferId));
Argument.AssertNotNull(source, nameof(source));
Argument.AssertNotNull(destination, nameof(destination));
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.ContainsKey(transferId))
{
throw Errors.CollisionTransferIdCheckpointer(transferId);
}
bool isContainer = source is StorageResourceContainer;
JobPlanHeader header = new(
DataMovementConstants.JobPlanFile.SchemaVersion,
transferId,
DateTimeOffset.UtcNow,
GetOperationType(source, destination),
source.ProviderId,
destination.ProviderId,
isContainer,
false, /* enumerationComplete */
new DataTransferStatus(),
source.Uri.ToSanitizedString(),
destination.Uri.ToSanitizedString(),
source.GetSourceCheckpointData(),
destination.GetDestinationCheckpointData());
using (Stream headerStream = new MemoryStream())
{
header.Serialize(headerStream);
headerStream.Position = 0;
JobPlanFile jobPlanFile = await JobPlanFile.CreateJobPlanFileAsync(
_pathToCheckpointer,
transferId,
headerStream,
cancellationToken).ConfigureAwait(false);
_transferStates.Add(transferId, jobPlanFile);
}
}
public override async Task AddNewJobPartAsync(
string transferId,
int partNumber,
Stream headerStream,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(transferId, nameof(transferId));
Argument.AssertNotNull(partNumber, nameof(partNumber));
Argument.AssertNotNull(headerStream, nameof(headerStream));
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
headerStream.Position = 0;
if (!_transferStates.ContainsKey(transferId))
{
// We should never get here because AddNewJobAsync should
// always be called first.
throw Errors.MissingTransferIdAddPartCheckpointer(transferId, partNumber);
}
JobPartPlanFile mappedFile = await JobPartPlanFile.CreateJobPartPlanFileAsync(
_pathToCheckpointer,
transferId,
partNumber,
headerStream,
cancellationToken).ConfigureAwait(false);
// Add the job part into the current state
if (!_transferStates[transferId].JobParts.TryAdd(partNumber, mappedFile))
{
throw Errors.CollisionJobPart(transferId, partNumber);
}
}
public override Task<int> CurrentJobPartCountAsync(
string transferId,
CancellationToken cancellationToken = default)
{
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.TryGetValue(transferId, out JobPlanFile result))
{
return Task.FromResult(result.JobParts.Count);
}
throw Errors.MissingTransferIdCheckpointer(transferId);
}
public override async Task<Stream> ReadJobPlanFileAsync(
string transferId,
int offset,
int length,
CancellationToken cancellationToken = default)
{
int bufferSize = length > 0 ? length : DataMovementConstants.DefaultStreamCopyBufferSize;
Stream copiedStream = new PooledMemoryStream(ArrayPool<byte>.Shared, bufferSize);
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.TryGetValue(transferId, out JobPlanFile jobPlanFile))
{
await jobPlanFile.WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(jobPlanFile.FilePath))
using (MemoryMappedViewStream mmfStream = mmf.CreateViewStream(offset, length, MemoryMappedFileAccess.Read))
{
await mmfStream.CopyToAsync(copiedStream, bufferSize, cancellationToken).ConfigureAwait(false);
}
copiedStream.Position = 0;
return copiedStream;
}
finally
{
jobPlanFile.WriteLock.Release();
}
}
else
{
throw Errors.MissingTransferIdCheckpointer(transferId);
}
}
public override async Task<Stream> ReadJobPartPlanFileAsync(
string transferId,
int partNumber,
int offset,
int length,
CancellationToken cancellationToken = default)
{
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.TryGetValue(transferId, out JobPlanFile jobPlanFile))
{
if (jobPlanFile.JobParts.TryGetValue(partNumber, out JobPartPlanFile jobPartPlanFile))
{
int bufferSize = length > 0 ? length : DataMovementConstants.DefaultStreamCopyBufferSize;
Stream copiedStream = new PooledMemoryStream(ArrayPool<byte>.Shared, bufferSize);
await jobPartPlanFile.WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(jobPartPlanFile.FilePath))
using (MemoryMappedViewStream mmfStream = mmf.CreateViewStream(offset, length, MemoryMappedFileAccess.Read))
{
await mmfStream.CopyToAsync(copiedStream, bufferSize, cancellationToken).ConfigureAwait(false);
}
copiedStream.Position = 0;
return copiedStream;
}
finally
{
jobPartPlanFile.WriteLock.Release();
}
}
else
{
throw Errors.MissingPartNumberCheckpointer(transferId, partNumber);
}
}
else
{
throw Errors.MissingTransferIdCheckpointer(transferId);
}
}
public override async Task WriteToJobPlanFileAsync(
string transferId,
int fileOffset,
byte[] buffer,
int bufferOffset,
int length,
CancellationToken cancellationToken = default)
{
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.TryGetValue(transferId, out JobPlanFile jobPlanFile))
{
await jobPlanFile.WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(jobPlanFile.FilePath, FileMode.Open))
using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(fileOffset, length, MemoryMappedFileAccess.Write))
{
accessor.WriteArray(0, buffer, bufferOffset, length);
accessor.Flush();
}
}
finally
{
jobPlanFile.WriteLock.Release();
}
}
else
{
throw Errors.MissingTransferIdCheckpointer(transferId);
}
}
public override Task<bool> TryRemoveStoredTransferAsync(string transferId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrWhiteSpace(transferId, nameof(transferId));
List<string> filesToDelete = new List<string>();
if (_transferStates.TryGetValue(transferId, out JobPlanFile jobPlanFile))
{
filesToDelete.Add(jobPlanFile.FilePath);
}
else
{
return Task.FromResult(false);
}
foreach (KeyValuePair<int,JobPartPlanFile> jobPartPair in jobPlanFile.JobParts)
{
filesToDelete.Add(jobPartPair.Value.FilePath);
}
bool result = true;
foreach (string file in filesToDelete)
{
try
{
File.Delete(file);
}
catch (FileNotFoundException)
{
// If we cannot find the file, it's either we deleted
// we have not created this job part yet.
}
catch
{
// If we run into an issue attempting to delete we should
// keep track that we could not at least delete one of files
// TODO: change return type to better show which files we
// were unable to remove
result = false;
}
}
_transferStates.Remove(transferId);
return Task.FromResult(result);
}
public override Task<List<string>> GetStoredTransfersAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(_transferStates.Keys.ToList());
}
public override async Task SetJobTransferStatusAsync(
string transferId,
DataTransferStatus status,
CancellationToken cancellationToken = default)
{
long length = DataMovementConstants.IntSizeInBytes;
int offset = DataMovementConstants.JobPlanFile.JobStatusIndex;
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.TryGetValue(transferId, out JobPlanFile jobPlanFile))
{
await jobPlanFile.WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(jobPlanFile.FilePath, FileMode.Open))
using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(offset, length))
{
accessor.Write(0, (int)status.ToJobPlanStatus());
accessor.Flush();
}
}
finally
{
jobPlanFile.WriteLock.Release();
}
}
else
{
throw Errors.MissingTransferIdCheckpointer(transferId);
}
}
public override async Task SetJobPartTransferStatusAsync(
string transferId,
int partNumber,
DataTransferStatus status,
CancellationToken cancellationToken = default)
{
long length = DataMovementConstants.IntSizeInBytes;
int offset = DataMovementConstants.JobPartPlanFile.JobPartStatusIndex;
CancellationHelper.ThrowIfCancellationRequested(cancellationToken);
if (_transferStates.TryGetValue(transferId, out JobPlanFile jobPlanFile))
{
if (jobPlanFile.JobParts.TryGetValue(partNumber, out JobPartPlanFile file))
{
await file.WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.FilePath, FileMode.Open))
using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(offset, length))
{
accessor.Write(0, (int)status.ToJobPlanStatus());
accessor.Flush();
}
}
finally
{
file.WriteLock.Release();
}
}
else
{
throw Errors.MissingPartNumberCheckpointer(transferId, partNumber);
}
}
else
{
throw Errors.MissingTransferIdCheckpointer(transferId);
}
}
/// <summary>
/// Takes the path of the checkpointer reads all the files in the top directory level
/// and populates the _transferStates.
/// </summary>
private void InitializeExistingCheckpointer()
{
// Enumerate the filesystem
IEnumerable<string> checkpointFiles = Directory.EnumerateFiles(_pathToCheckpointer);
// First, retrieve all valid job plan files
foreach (string path in checkpointFiles
.Where(p => Path.GetExtension(p) == DataMovementConstants.JobPlanFile.FileExtension))
{
// TODO: Should we check for valid schema version inside file now?
JobPlanFile jobPlanFile = JobPlanFile.LoadExistingJobPlanFile(path);
if (!_transferStates.ContainsKey(jobPlanFile.Id))
{
_transferStates.Add(jobPlanFile.Id, jobPlanFile);
}
else
{
throw Errors.CollisionTransferIdCheckpointer(jobPlanFile.Id);
}
}
// Retrieve all valid job part plan files stored in the checkpointer path.
foreach (string path in checkpointFiles
.Where(p => Path.GetExtension(p) == DataMovementConstants.JobPartPlanFile.FileExtension))
{
// Ensure each file has the correct format
if (JobPartPlanFileName.TryParseJobPartPlanFileName(path, out JobPartPlanFileName partPlanFileName))
{
// Job plan file should already exist since we already iterated job plan files
if (_transferStates.TryGetValue(partPlanFileName.Id, out JobPlanFile jobPlanFile))
{
jobPlanFile.JobParts.TryAdd(
partPlanFileName.JobPartNumber,
JobPartPlanFile.CreateExistingPartPlanFile(partPlanFileName));
}
}
}
}
private static JobPlanOperation GetOperationType(StorageResource source, StorageResource destination)
{
if (source.IsLocalResource() && !destination.IsLocalResource())
{
return JobPlanOperation.Upload;
}
else if (!source.IsLocalResource() && destination.IsLocalResource())
{
return JobPlanOperation.Download;
}
else if (!source.IsLocalResource() && !destination.IsLocalResource())
{
return JobPlanOperation.ServiceToService;
}
else
{
throw Errors.InvalidSourceDestinationParams();
}
}
}
}