-
-
Notifications
You must be signed in to change notification settings - Fork 345
/
Copy pathNetAsyncDownloader.cs
441 lines (386 loc) · 16.6 KB
/
NetAsyncDownloader.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
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using Autofac;
using CKAN.Configuration;
using log4net;
namespace CKAN
{
/// <summary>
/// Download lots of files at once!
/// </summary>
public class NetAsyncDownloader
{
// Private utility class for tracking downloads
private class NetAsyncDownloaderDownloadPart
{
public readonly Net.DownloadTarget target;
public DateTime lastProgressUpdateTime;
public string path;
public long bytesLeft;
public long size;
public int bytesPerSecond;
public bool triedFallback;
public Exception error;
public int lastProgressUpdateSize;
public event DownloadProgressChangedEventHandler Progress;
public event AsyncCompletedEventHandler Done;
private string mimeType;
private WebClient agent;
public NetAsyncDownloaderDownloadPart(Net.DownloadTarget target, string path = null)
{
this.target = target;
this.mimeType = target.mimeType;
this.triedFallback = false;
this.path = path ?? Path.GetTempFileName();
this.size = bytesLeft = target.size;
this.lastProgressUpdateTime = DateTime.Now;
}
public void Download(Uri url, string path)
{
ResetAgent();
agent.DownloadFileAsync(url, path);
}
public void Abort()
{
agent?.CancelAsync();
}
private void ResetAgent()
{
agent = new WebClient();
agent.Headers.Add("User-Agent", Net.UserAgentString);
// Tell the server what kind of files we want
if (!string.IsNullOrEmpty(mimeType))
{
log.InfoFormat("Setting MIME type {0}", mimeType);
agent.Headers.Add("Accept", mimeType);
}
// Check whether to use an auth token for this host
string token;
if (ServiceLocator.Container.Resolve<IConfiguration>().TryGetAuthToken(this.target.url.Host, out token)
&& !string.IsNullOrEmpty(token))
{
log.InfoFormat("Using auth token for {0}", this.target.url.Host);
// Send our auth token to the GitHub API (or whoever else needs one)
agent.Headers.Add("Authorization", $"token {token}");
}
// Forward progress and completion events to our listeners
agent.DownloadProgressChanged += (sender, args) => {
if (Progress != null)
{
Progress(sender, args);
}
};
agent.DownloadFileCompleted += (sender, args) => {
if (Done != null)
{
Done(sender, args);
}
};
}
}
/// <summary>
/// Downloads from hosts in this list will be done sequentially rather
/// than in parallel
/// </summary>
private static readonly HashSet<string> throttledHosts = new HashSet<string>()
{
/// GitHub returns a 403-Forbidden status sometimes if you try to download
/// too much in parallel, see https://github.com/KSP-CKAN/CKAN/issues/2210
"github.com",
"api.github.com",
"raw.githubusercontent.com",
};
private static readonly ILog log = LogManager.GetLogger(typeof (NetAsyncDownloader));
public readonly IUser User;
/// <summary>
/// Raised when data arrives for a download
/// </summary>
public event Action<Net.DownloadTarget, long, long> Progress;
private List<NetAsyncDownloaderDownloadPart> downloads = new List<NetAsyncDownloaderDownloadPart>();
private List<Net.DownloadTarget> queuedDownloads = new List<Net.DownloadTarget>();
private int completed_downloads;
//Used for inter-thread communication.
private volatile bool download_canceled;
private readonly ManualResetEvent complete_or_canceled;
public delegate void NetAsyncOneCompleted(Uri url, string filename, Exception error);
public NetAsyncOneCompleted onOneCompleted;
/// <summary>
/// Returns a perfectly boring NetAsyncDownloader.
/// </summary>
public NetAsyncDownloader(IUser user)
{
User = user;
complete_or_canceled = new ManualResetEvent(false);
}
/// <summary>
/// Downloads our files.
/// </summary>
/// <param name="targets">A collection of DownloadTargets</param>
private void Download(ICollection<Net.DownloadTarget> targets)
{
downloads.Clear();
queuedDownloads.Clear();
foreach (Net.DownloadTarget target in targets)
{
DownloadModule(target);
}
}
private void DownloadModule(Net.DownloadTarget target)
{
if (shouldQueue(target))
{
// Throttled host already downloading, we will get back to this later
queuedDownloads.Add(target);
}
else
{
// We need a new variable for our closure/lambda, hence index = 1+prev max
int index = downloads.Count;
var dl = new NetAsyncDownloaderDownloadPart(target);
downloads.Add(dl);
// Encode spaces to avoid confusing URL parsers
User.RaiseMessage("Downloading \"{0}\"",
dl.target.url.ToString().Replace(" ", "%20"));
// Schedule for us to get back progress reports.
dl.Progress += (sender, args) =>
FileProgressReport(index,
args.ProgressPercentage,
args.BytesReceived,
args.TotalBytesToReceive);
// And schedule a notification if we're done (or if something goes wrong)
dl.Done += (sender, args) =>
FileDownloadComplete(index, args.Error);
// Start the download!
dl.Download(dl.target.url, dl.path);
}
}
/// <summary>
/// Check whether a given download should be deferred to be started later.
/// Decision is made based on whether the host is throttled and whether
/// we're already downloading something else from it.
/// </summary>
/// <param name="target">Info about a requested download</param>
/// <returns>
/// true to queue, false to start immediately
/// </returns>
private bool shouldQueue(Net.DownloadTarget target)
{
return throttledHosts.Contains(target.url.Host)
&& downloads.Any(dl =>
dl.target.url.Host == target.url.Host
&& dl.bytesLeft > 0);
}
/// <summary>
/// Start a new batch of downloads
/// </summary>
/// <param name="urls">The downloads to begin</param>
public void DownloadAndWait(ICollection<Net.DownloadTarget> urls)
{
if (downloads.Count > completed_downloads)
{
// Some downloads are still in progress, add to the current batch
foreach (Net.DownloadTarget target in urls)
{
DownloadModule(target);
}
// Wait for completion along with original caller
// so we can handle completion tasks for the added mods
complete_or_canceled.WaitOne();
return;
}
completed_downloads = 0;
// Make sure we are ready to start a fresh batch
complete_or_canceled.Reset();
// Start the download!
Download(urls);
log.Debug("Waiting for downloads to finish...");
complete_or_canceled.WaitOne();
var old_download_canceled = download_canceled;
// Set up the inter-thread comms for next time. Can not be done at the start
// of the method as the thread could pause on the opening line long enough for
// a user to cancel.
download_canceled = false;
complete_or_canceled.Reset();
// If the user cancelled our progress, then signal that.
if (old_download_canceled)
{
// Abort all our traditional downloads, if there are any.
foreach (var download in downloads.ToList())
{
download.Abort();
}
// Signal to the caller that the user cancelled the download.
throw new CancelledActionKraken("Download cancelled by user");
}
// Check to see if we've had any errors. If so, then release the kraken!
List<KeyValuePair<int, Exception>> exceptions = new List<KeyValuePair<int, Exception>>();
for (int i = 0; i < downloads.Count; ++i)
{
if (downloads[i].error != null)
{
// Check if it's a certificate error. If so, report that instead,
// as this is common (and user-fixable) under Linux.
if (downloads[i].error is WebException)
{
WebException wex = downloads[i].error as WebException;
if (certificatePattern.IsMatch(wex.Message))
{
throw new MissingCertificateKraken();
}
else switch ((wex.Response as HttpWebResponse)?.StatusCode)
{
// Handle HTTP 403 used for throttling
case HttpStatusCode.Forbidden:
Uri infoUrl;
if (Net.ThrottledHosts.TryGetValue(downloads[i].target.url.Host, out infoUrl))
{
throw new DownloadThrottledKraken(downloads[i].target.url, infoUrl);
}
break;
}
}
// Otherwise just note the error and which download it came from,
// then throw them all at once later.
exceptions.Add(new KeyValuePair<int, Exception>(i, downloads[i].error));
}
}
if (exceptions.Count > 0)
{
throw new DownloadErrorsKraken(exceptions);
}
// Yay! Everything worked!
}
private static readonly Regex certificatePattern = new Regex(
@"authentication or decryption has failed",
RegexOptions.Compiled
);
/// <summary>
/// <see cref="IDownloader.CancelDownload()"/>
/// This will also call onCompleted with all null arguments.
/// </summary>
public void CancelDownload()
{
log.Info("Cancelling download");
download_canceled = true;
triggerCompleted();
}
private void triggerCompleted()
{
// Signal that we're done.
complete_or_canceled.Set();
}
/// <summary>
/// Generates a download progress report.
/// </summary>
/// <param name="index">Index of the file being downloaded</param>
/// <param name="percent">The percent complete</param>
/// <param name="bytesDownloaded">The bytes downloaded</param>
/// <param name="bytesToDownload">The total amount of bytes we expect to download</param>
private void FileProgressReport(int index, int percent, long bytesDownloaded, long bytesToDownload)
{
if (download_canceled)
{
return;
}
NetAsyncDownloaderDownloadPart download = downloads[index];
DateTime now = DateTime.Now;
TimeSpan timeSpan = now - download.lastProgressUpdateTime;
if (timeSpan.Seconds >= 3.0)
{
long bytesChange = bytesDownloaded - download.lastProgressUpdateSize;
download.lastProgressUpdateSize = (int) bytesDownloaded;
download.lastProgressUpdateTime = now;
download.bytesPerSecond = (int) bytesChange / timeSpan.Seconds;
}
download.size = bytesToDownload;
download.bytesLeft = download.size - bytesDownloaded;
if (Progress != null)
{
Progress(download.target, download.bytesLeft, download.size);
}
int totalBytesPerSecond = 0;
long totalBytesLeft = 0;
long totalSize = 0;
foreach (NetAsyncDownloaderDownloadPart t in downloads.ToList())
{
if (t.bytesLeft > 0)
{
totalBytesPerSecond += t.bytesPerSecond;
}
totalBytesLeft += t.bytesLeft;
totalSize += t.size;
}
foreach (Net.DownloadTarget t in queuedDownloads.ToList())
{
totalBytesLeft += t.size;
totalSize += t.size;
}
int totalPercentage = (int)(((totalSize - totalBytesLeft) * 100) / (totalSize));
if (!download_canceled)
{
// Math.Ceiling was added to avoid showing 0 MiB left when finishing
User.RaiseProgress(
String.Format("{0}/sec - downloading - {1} left",
CkanModule.FmtSize(totalBytesPerSecond),
CkanModule.FmtSize(totalBytesLeft)),
totalPercentage);
}
}
/// <summary>
/// This method gets called back by `WebClient` when a download is completed.
/// It in turncalls the onCompleted hook when *all* downloads are finished.
/// </summary>
private void FileDownloadComplete(int index, Exception error)
{
if (error != null)
{
log.InfoFormat("Error downloading {0}: {1}", downloads[index].target.url, error);
// Check whether we were already downloading the fallback url
if (!downloads[index].triedFallback && downloads[index].target.fallbackUrl != null)
{
log.InfoFormat("Trying fallback URL: {0}", downloads[index].target.fallbackUrl);
// Encode spaces to avoid confusing URL parsers
User.RaiseMessage("Failed to download \"{0}\", trying fallback \"{1}\"",
downloads[index].target.url.ToString().Replace(" ", "%20"),
downloads[index].target.fallbackUrl.ToString().Replace(" ", "%20")
);
// Try the fallbackUrl
downloads[index].triedFallback = true;
downloads[index].Download(downloads[index].target.fallbackUrl, downloads[index].path);
// Short circuit the completion process so the fallback can run
return;
}
else
{
downloads[index].error = error;
}
}
else
{
log.InfoFormat("Finished downloading {0}", downloads[index].target.url);
}
if (throttledHosts.Contains(downloads[index].target.url.Host))
{
var next = queuedDownloads.FirstOrDefault(dl =>
dl.url.Host == downloads[index].target.url.Host);
if (next != null)
{
// Start this host's next queued download
queuedDownloads.Remove(next);
DownloadModule(next);
}
}
onOneCompleted.Invoke(downloads[index].target.url, downloads[index].path, downloads[index].error);
if (++completed_downloads >= downloads.Count + queuedDownloads.Count)
{
triggerCompleted();
}
}
}
}