-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
293 lines (254 loc) · 13.9 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Polly;
namespace Upload
{
class Program
{
static async Task Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.AddJsonFile("appsettings.Debug.json", false)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT")}.json", optional: true)
.Build();
var storageConnectionString = config.GetValue<string>("StorageConnectionString");
var sourceUri = new Uri(config.GetValue<string>("SourceUri"));
var sourceFile = config.GetValue<string>("SourceFile");
if (string.IsNullOrEmpty(sourceFile))
{
sourceFile = Path.GetFileName(sourceUri.LocalPath);
}
if (!File.Exists(sourceFile))
{
Console.WriteLine($"download sample file...");
var httpClient = new HttpClient();
using (var inputStream = await httpClient.GetStreamAsync(sourceUri))
using (var outputStream = new FileStream(sourceFile, FileMode.Create, FileAccess.ReadWrite))
{
await inputStream.CopyToAsync(outputStream);
}
}
var filePath = sourceFile;
var fileInfo = new FileInfo(filePath);
var fileSize = fileInfo.Length;
Console.WriteLine($"source:");
Console.WriteLine($"\tfrom: {filePath}");
/// Cloud Storage
///
var account = CloudStorageAccount.Parse(storageConnectionString);
var client = account.CreateCloudBlobClient();
var container = client.GetContainerReference("file");
await container.CreateIfNotExistsAsync();
// var fileInfo2 = new FileInfo(sourceFile);
// Console.WriteLine($"origin: {fileInfo.Name} => {fileInfo2.Length}");
// var b1 = container.GetBlockBlobReference("Build-2019-Keynote-Satya.mp4.parallel");
// b1.FetchAttributes();
// Console.WriteLine($" b1: {b1.Name} => {b1.Properties.Length}");
// var b2 = container.GetBlockBlobReference("Build-2019-Keynote-Satya.mp4.azcopy");
// b2.FetchAttributes();
// Console.WriteLine($" b2: {b2.Name} => {b2.Properties.Length}");
// return;
var stopwatch = new Stopwatch();
/// Blob
///
Console.WriteLine($"\tsize: {fileSize:##,#} bytes");
Console.WriteLine();
/// Simple Upload
///
// Console.WriteLine($"simple upload:");
// var blob = container.GetBlockBlobReference(Path.GetFileName(sourceFile) + ".simple");
// Console.WriteLine($"\tto: {blob.Uri}");
// if (await blob.ExistsAsync())
// {
// Console.WriteLine($"\tcleanup");
// await blob.DeleteIfExistsAsync();
// }
// stopwatch.Start();
// await blob.UploadFromFileAsync(filePath);
// stopwatch.Stop();
// Console.WriteLine($"\telapsed: {stopwatch.ElapsedMilliseconds:##,#} ms");
// Console.WriteLine($"\tthroughput: {(fileSize / stopwatch.ElapsedMilliseconds):##,#} bytes/sec (~{(fileSize / stopwatch.ElapsedMilliseconds) * 8:##,#} bps)");
// Console.WriteLine();
/// Simple Upload with BlobRequestOptions
///
// Console.WriteLine($"simple upload with `ParallelOperationThreadCount`:");
// blob = container.GetBlockBlobReference(Path.GetFileName(sourceFile) + ".simple-parallel");
// Console.WriteLine($"\tto: {blob.Uri}");
// if (await blob.ExistsAsync())
// {
// Console.WriteLine($"\tcleanup");
// await blob.DeleteIfExistsAsync();
// }
// stopwatch.Restart();
// var parallelOptions = new BlobRequestOptions
// {
// ParallelOperationThreadCount = 10
// };
// await blob.UploadFromFileAsync(filePath, null, parallelOptions, null);
// stopwatch.Stop();
// Console.WriteLine($"\telapsed: {stopwatch.ElapsedMilliseconds:##,#} ms");
// Console.WriteLine($"\tthroughput: {(fileSize / stopwatch.ElapsedMilliseconds):##,#} bytes/sec (~{(fileSize / stopwatch.ElapsedMilliseconds) * 8:##,#} bps)");
// Console.WriteLine();
/// Parallel Upload
///
Console.WriteLine($"parallel upload:");
var blob = container.GetBlockBlobReference(Path.GetFileName(sourceFile) + ".parallel");
Console.WriteLine($"\tto: {blob.Uri}");
// var blockSize = 1024 * 1024 * 10; //10MB
// var blockSize = 1024 * 1024 * 5; //5MB
var blockSize = 1024 * 1024 * 100; //100MB
// var blockSize = 1024 * 1024 * 1; //1MB
var uploadedBlock = Enumerable.Empty<ListBlockItem>();
try
{
uploadedBlock = await blob.DownloadBlockListAsync(BlockListingFilter.Uncommitted,
AccessCondition.GenerateEmptyCondition(),
new BlobRequestOptions { },
new OperationContext { });
}
catch (StorageException)
{
}
if (!uploadedBlock.Any())
{
// Console.WriteLine("\tcleanup");
// await blob.DeleteIfExistsAsync();
}
else
{
Console.WriteLine($"\tprevious upload {uploadedBlock.Count()} block(s) found!");
uploadedBlock.ToList().ForEach(x =>
{
var n = BitConverter.ToInt16(Convert.FromBase64String(x.Name));
Console.WriteLine($"\t\tblock: {x.Name} ({n}), length: {x.Length}, committed: {x.Committed}");
});
Console.Write($"\t\tpress Y for continue, N for new upload, C for commit to file. [Y/n/c] ");
var readKey = true;
while (readKey)
{
var input = Console.ReadKey();
switch (input.Key)
{
case ConsoleKey.C:
await blob.PutBlockListAsync(uploadedBlock.Select(x => x.Name));
return;
case ConsoleKey.N:
readKey = false;
uploadedBlock = Enumerable.Empty<ListBlockItem>();
// await blob.DeleteIfExistsAsync();
break;
case ConsoleKey.Enter:
case ConsoleKey.Y:
Console.WriteLine("\n\tcontinue to upload");
blockSize = (int)uploadedBlock.First().Length;
readKey = false;
break;
}
}
Console.WriteLine();
}
var taskCount = (int)Math.Ceiling((double)fileSize / blockSize);
var parallelize = 5;
var taskParams = Enumerable
.Range(1, taskCount)
.Select(x =>
{
long start = (x - 1) * (long)blockSize;
long end = Math.Min(start + blockSize - 1, fileSize - 1);
int length = (int)(end - start + 1);
var blockId = Convert.ToBase64String(BitConverter.GetBytes(x));
Func<Task<(byte[], string)>> get = async () =>
{
using (var sourceStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var md5 = MD5.Create())
{
var buffer = new byte[length];
sourceStream.Position = start;
await sourceStream.ReadAsync(buffer, 0, length);
var hash = Convert.ToBase64String(md5.ComputeHash(buffer));
return (buffer, hash);
}
};
return new { Sequence = x, N = x, BlockId = blockId, GetBufferAsync = get };
})
.Where(x => !uploadedBlock.Select(u => u.Name).Contains(x.BlockId))
.ToList();
try
{
if (!taskParams.Any())
{
// there is no more blocks needed to upload
uploadedBlock = await blob.DownloadBlockListAsync(BlockListingFilter.Uncommitted,
AccessCondition.GenerateEmptyCondition(),
new BlobRequestOptions { },
new OperationContext { });
await blob.PutBlockListAsync(uploadedBlock.Select(x => x.Name));
}
else
{
// upload blocks
Console.WriteLine($"\tblock size: {blockSize:##,#} bytes");
Console.WriteLine($"\ttasks: {taskCount}");
Console.WriteLine($"\tparallelize: {parallelize}");
stopwatch.Restart();
var completedCount = 0L;
using (var concurrencySemaphore = new SemaphoreSlim(parallelize))
{
var policy = Policy
.Handle<Exception>()
.RetryForeverAsync(x => Console.WriteLine($"\t\tthread {Thread.CurrentThread.ManagedThreadId,5:#####} retry after {x.GetType().Name}: {x.Message}"));
var tasks = new List<Task>();
foreach (var taskParam in taskParams)
{
await concurrencySemaphore.WaitAsync();
var (buffer, hash) = await taskParam.GetBufferAsync();
var innerStopwatch = new Stopwatch();
innerStopwatch.Start();
tasks.Add(policy.ExecuteAsync(() => blob.PutBlockAsync(taskParam.BlockId, new MemoryStream(buffer), hash)
.ContinueWith(x =>
{
innerStopwatch.Stop();
Interlocked.Increment(ref completedCount);
concurrencySemaphore.Release();
var progress = (completedCount / (double)taskCount) * 100;
Console.WriteLine($"\t\tthread {Thread.CurrentThread.ManagedThreadId,5:#####}, block {taskParam.N,3:###}, {progress,5:###.#}% completed, length {buffer.Length}, elapsed {innerStopwatch.Elapsed}");
})));
}
await Task.WhenAll(tasks);
}
// await blob.PutBlockListAsync(taskParams.Select(x => x.BlockId));
uploadedBlock = await blob.DownloadBlockListAsync(BlockListingFilter.Uncommitted,
AccessCondition.GenerateEmptyCondition(),
new BlobRequestOptions { },
new OperationContext { });
await blob.PutBlockListAsync(uploadedBlock.Select(x => x.Name));
}
await blob.FetchAttributesAsync();
}
finally
{
stopwatch.Stop();
Console.WriteLine($"\telapsed: {stopwatch.ElapsedMilliseconds:##,#} ms");
Console.WriteLine($"\tthroughput: {(fileSize / stopwatch.ElapsedMilliseconds):##,#} bytes/sec (~{(fileSize / stopwatch.ElapsedMilliseconds) * 8:##,#} bps)");
if (blob != null && blob.Properties != null)
{
Console.WriteLine($"\tblob: {blob.Properties.Length:##,#} bytes, {blob.Properties.Created}");
}
Console.WriteLine();
}
}
}
}