root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 133f83c2
History | View | Annotate | Download (55.2 kB)
1 |
// ----------------------------------------------------------------------- |
---|---|
2 |
// <copyright file="NetworkAgent.cs" company="GRNET"> |
3 |
// Copyright 2011 GRNET S.A. All rights reserved. |
4 |
// |
5 |
// Redistribution and use in source and binary forms, with or |
6 |
// without modification, are permitted provided that the following |
7 |
// conditions are met: |
8 |
// |
9 |
// 1. Redistributions of source code must retain the above |
10 |
// copyright notice, this list of conditions and the following |
11 |
// disclaimer. |
12 |
// |
13 |
// 2. Redistributions in binary form must reproduce the above |
14 |
// copyright notice, this list of conditions and the following |
15 |
// disclaimer in the documentation and/or other materials |
16 |
// provided with the distribution. |
17 |
// |
18 |
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS |
19 |
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
20 |
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR |
21 |
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR |
22 |
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
23 |
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
24 |
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF |
25 |
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
26 |
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
27 |
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
28 |
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
29 |
// POSSIBILITY OF SUCH DAMAGE. |
30 |
// |
31 |
// The views and conclusions contained in the software and |
32 |
// documentation are those of the authors and should not be |
33 |
// interpreted as representing official policies, either expressed |
34 |
// or implied, of GRNET S.A. |
35 |
// </copyright> |
36 |
// ----------------------------------------------------------------------- |
37 |
|
38 |
using System; |
39 |
using System.Collections.Concurrent; |
40 |
using System.Collections.Generic; |
41 |
using System.ComponentModel.Composition; |
42 |
using System.Diagnostics; |
43 |
using System.Diagnostics.Contracts; |
44 |
using System.IO; |
45 |
using System.Linq; |
46 |
using System.Net; |
47 |
using System.Threading; |
48 |
using System.Threading.Tasks; |
49 |
using System.Threading.Tasks.Dataflow; |
50 |
using Castle.ActiveRecord; |
51 |
using Pithos.Interfaces; |
52 |
using Pithos.Network; |
53 |
using log4net; |
54 |
|
55 |
namespace Pithos.Core.Agents |
56 |
{ |
57 |
//TODO: Ensure all network operations use exact casing. Pithos is case sensitive |
58 |
[Export] |
59 |
public class NetworkAgent |
60 |
{ |
61 |
private Agent<CloudAction> _agent; |
62 |
|
63 |
//A separate agent is used to execute delete actions immediatelly; |
64 |
private ActionBlock<CloudDeleteAction> _deleteAgent; |
65 |
readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>(); |
66 |
|
67 |
|
68 |
private readonly ManualResetEventSlim _pauseAgent = new ManualResetEventSlim(true); |
69 |
|
70 |
[System.ComponentModel.Composition.Import] |
71 |
public IStatusKeeper StatusKeeper { get; set; } |
72 |
|
73 |
public IStatusNotification StatusNotification { get; set; } |
74 |
|
75 |
private static readonly ILog Log = LogManager.GetLogger("NetworkAgent"); |
76 |
|
77 |
private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>(); |
78 |
|
79 |
[System.ComponentModel.Composition.Import] |
80 |
public IPithosSettings Settings { get; set; } |
81 |
|
82 |
private bool _firstPoll = true; |
83 |
public void Start() |
84 |
{ |
85 |
_firstPoll = true; |
86 |
_agent = Agent<CloudAction>.Start(inbox => |
87 |
{ |
88 |
Action loop = null; |
89 |
loop = () => |
90 |
{ |
91 |
_pauseAgent.Wait(); |
92 |
var message = inbox.Receive(); |
93 |
var process=message.Then(Process,inbox.CancellationToken); |
94 |
inbox.LoopAsync(process, loop); |
95 |
}; |
96 |
loop(); |
97 |
}); |
98 |
|
99 |
_deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4}); |
100 |
/* |
101 |
Action loop = null; |
102 |
loop = () => |
103 |
{ |
104 |
var message = inbox.Receive(); |
105 |
var process = message.Then(ProcessDelete,inbox.CancellationToken); |
106 |
inbox.LoopAsync(process, loop); |
107 |
}; |
108 |
loop(); |
109 |
*/ |
110 |
|
111 |
} |
112 |
|
113 |
private async Task Process(CloudAction action) |
114 |
{ |
115 |
if (action == null) |
116 |
throw new ArgumentNullException("action"); |
117 |
if (action.AccountInfo==null) |
118 |
throw new ArgumentException("The action.AccountInfo is empty","action"); |
119 |
Contract.EndContractBlock(); |
120 |
|
121 |
var accountInfo = action.AccountInfo; |
122 |
|
123 |
using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS")) |
124 |
{ |
125 |
Log.InfoFormat("[ACTION] Start Processing {0}", action); |
126 |
|
127 |
var cloudFile = action.CloudFile; |
128 |
var downloadPath = action.GetDownloadPath(); |
129 |
|
130 |
try |
131 |
{ |
132 |
|
133 |
if (action.Action == CloudActionType.DeleteCloud) |
134 |
{ |
135 |
//Redirect deletes to the delete agent |
136 |
_deleteAgent.Post((CloudDeleteAction)action); |
137 |
} |
138 |
if (IsDeletedFile(action)) |
139 |
{ |
140 |
//Clear the status of already deleted files to avoid reprocessing |
141 |
if (action.LocalFile != null) |
142 |
this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName); |
143 |
} |
144 |
else |
145 |
{ |
146 |
switch (action.Action) |
147 |
{ |
148 |
case CloudActionType.UploadUnconditional: |
149 |
//Abort if the file was deleted before we reached this point |
150 |
await UploadCloudFile(action); |
151 |
break; |
152 |
case CloudActionType.DownloadUnconditional: |
153 |
await DownloadCloudFile(accountInfo, cloudFile, downloadPath); |
154 |
break; |
155 |
case CloudActionType.RenameCloud: |
156 |
var moveAction = (CloudMoveAction) action; |
157 |
RenameCloudFile(accountInfo, moveAction); |
158 |
break; |
159 |
case CloudActionType.MustSynch: |
160 |
if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath)) |
161 |
{ |
162 |
await DownloadCloudFile(accountInfo, cloudFile, downloadPath); |
163 |
} |
164 |
else |
165 |
{ |
166 |
await SyncFiles(accountInfo, action); |
167 |
} |
168 |
break; |
169 |
} |
170 |
} |
171 |
Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile, |
172 |
action.CloudFile.Name); |
173 |
} |
174 |
catch (WebException exc) |
175 |
{ |
176 |
Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc); |
177 |
} |
178 |
catch (OperationCanceledException) |
179 |
{ |
180 |
throw; |
181 |
} |
182 |
catch (DirectoryNotFoundException) |
183 |
{ |
184 |
Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete", |
185 |
action.Action, action.LocalFile, action.CloudFile); |
186 |
//Post a delete action for the missing file |
187 |
Post(new CloudDeleteAction(action)); |
188 |
} |
189 |
catch (FileNotFoundException) |
190 |
{ |
191 |
Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete", |
192 |
action.Action, action.LocalFile, action.CloudFile); |
193 |
//Post a delete action for the missing file |
194 |
Post(new CloudDeleteAction(action)); |
195 |
} |
196 |
catch (Exception exc) |
197 |
{ |
198 |
Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}", |
199 |
action.Action, action.LocalFile, action.CloudFile, exc); |
200 |
|
201 |
_agent.Post(action); |
202 |
} |
203 |
} |
204 |
} |
205 |
|
206 |
/// <summary> |
207 |
/// Processes cloud delete actions |
208 |
/// </summary> |
209 |
/// <param name="action">The delete action to execute</param> |
210 |
/// <returns></returns> |
211 |
/// <remarks> |
212 |
/// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download |
213 |
/// operations that may be in progress. |
214 |
/// <para> |
215 |
/// A separate agent is used to process deletes because the main agent may be busy with a long operation. |
216 |
/// </para> |
217 |
/// </remarks> |
218 |
private async Task ProcessDelete(CloudDeleteAction action) |
219 |
{ |
220 |
if (action == null) |
221 |
throw new ArgumentNullException("action"); |
222 |
if (action.AccountInfo==null) |
223 |
throw new ArgumentException("The action.AccountInfo is empty","action"); |
224 |
Contract.EndContractBlock(); |
225 |
|
226 |
var accountInfo = action.AccountInfo; |
227 |
|
228 |
using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS")) |
229 |
{ |
230 |
Log.InfoFormat("[ACTION] Start Processing {0}", action); |
231 |
|
232 |
var cloudFile = action.CloudFile; |
233 |
|
234 |
try |
235 |
{ |
236 |
//Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal |
237 |
//agent |
238 |
using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting)) |
239 |
{ |
240 |
|
241 |
//Add the file URL to the deleted files list |
242 |
var key = GetFileKey(action.CloudFile); |
243 |
_deletedFiles[key] = DateTime.Now; |
244 |
|
245 |
_pauseAgent.Reset(); |
246 |
// and then delete the file from the server |
247 |
DeleteCloudFile(accountInfo, cloudFile); |
248 |
|
249 |
Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile, |
250 |
action.CloudFile.Name); |
251 |
} |
252 |
} |
253 |
catch (WebException exc) |
254 |
{ |
255 |
Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc); |
256 |
} |
257 |
catch (OperationCanceledException) |
258 |
{ |
259 |
throw; |
260 |
} |
261 |
catch (DirectoryNotFoundException) |
262 |
{ |
263 |
Log.ErrorFormat("{0} : {1} -> {2} failed because the directory was not found.\n Rescheduling a delete", |
264 |
action.Action, action.LocalFile, action.CloudFile); |
265 |
//Repost a delete action for the missing file |
266 |
_deleteAgent.Post(action); |
267 |
} |
268 |
catch (FileNotFoundException) |
269 |
{ |
270 |
Log.ErrorFormat("{0} : {1} -> {2} failed because the file was not found.\n Rescheduling a delete", |
271 |
action.Action, action.LocalFile, action.CloudFile); |
272 |
//Post a delete action for the missing file |
273 |
_deleteAgent.Post(action); |
274 |
} |
275 |
catch (Exception exc) |
276 |
{ |
277 |
Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}", |
278 |
action.Action, action.LocalFile, action.CloudFile, exc); |
279 |
|
280 |
_deleteAgent.Post(action); |
281 |
} |
282 |
finally |
283 |
{ |
284 |
if (_deleteAgent.InputCount == 0) |
285 |
_pauseAgent.Set(); |
286 |
|
287 |
} |
288 |
} |
289 |
} |
290 |
|
291 |
private static string GetFileKey(ObjectInfo info) |
292 |
{ |
293 |
var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name); |
294 |
return key; |
295 |
} |
296 |
|
297 |
private async Task SyncFiles(AccountInfo accountInfo,CloudAction action) |
298 |
{ |
299 |
if (accountInfo == null) |
300 |
throw new ArgumentNullException("accountInfo"); |
301 |
if (action==null) |
302 |
throw new ArgumentNullException("action"); |
303 |
if (action.LocalFile==null) |
304 |
throw new ArgumentException("The action's local file is not specified","action"); |
305 |
if (!Path.IsPathRooted(action.LocalFile.FullName)) |
306 |
throw new ArgumentException("The action's local file path must be absolute","action"); |
307 |
if (action.CloudFile== null) |
308 |
throw new ArgumentException("The action's cloud file is not specified", "action"); |
309 |
Contract.EndContractBlock(); |
310 |
|
311 |
var localFile = action.LocalFile; |
312 |
var cloudFile = action.CloudFile; |
313 |
var downloadPath=action.LocalFile.GetProperCapitalization(); |
314 |
|
315 |
var cloudHash = cloudFile.Hash.ToLower(); |
316 |
var localHash = action.LocalHash.Value.ToLower(); |
317 |
var topHash = action.TopHash.Value.ToLower(); |
318 |
|
319 |
//Not enough to compare only the local hashes, also have to compare the tophashes |
320 |
|
321 |
//If any of the hashes match, we are done |
322 |
if ((cloudHash == localHash || cloudHash == topHash)) |
323 |
{ |
324 |
Log.InfoFormat("Skipping {0}, hashes match",downloadPath); |
325 |
return; |
326 |
} |
327 |
|
328 |
//The hashes DON'T match. We need to sync |
329 |
var lastLocalTime = localFile.LastWriteTime; |
330 |
var lastUpTime = cloudFile.Last_Modified; |
331 |
|
332 |
//If the local file is newer upload it |
333 |
if (lastUpTime <= lastLocalTime) |
334 |
{ |
335 |
//It probably means it was changed while the app was down |
336 |
UploadCloudFile(action); |
337 |
} |
338 |
else |
339 |
{ |
340 |
//It the cloud file has a later date, it was modified by another user or computer. |
341 |
//We need to check the local file's status |
342 |
var status = StatusKeeper.GetFileStatus(downloadPath); |
343 |
switch (status) |
344 |
{ |
345 |
case FileStatus.Unchanged: |
346 |
//If the local file's status is Unchanged, we can go on and download the newer cloud file |
347 |
await DownloadCloudFile(accountInfo,cloudFile,downloadPath); |
348 |
break; |
349 |
case FileStatus.Modified: |
350 |
//If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict |
351 |
//We can't ensure that a file modified online since the last time will appear as Modified, unless we |
352 |
//index all files before we start listening. |
353 |
case FileStatus.Created: |
354 |
//If the local file is Created, it means that the local and cloud files aren't related, |
355 |
// yet they have the same name. |
356 |
|
357 |
//In both cases we must mark the file as in conflict |
358 |
ReportConflict(downloadPath); |
359 |
break; |
360 |
default: |
361 |
//Other cases should never occur. Mark them as Conflict as well but log a warning |
362 |
ReportConflict(downloadPath); |
363 |
Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status, |
364 |
downloadPath, action.CloudFile.Name); |
365 |
break; |
366 |
} |
367 |
} |
368 |
} |
369 |
|
370 |
private void ReportConflict(string downloadPath) |
371 |
{ |
372 |
if (String.IsNullOrWhiteSpace(downloadPath)) |
373 |
throw new ArgumentNullException("downloadPath"); |
374 |
Contract.EndContractBlock(); |
375 |
|
376 |
StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict); |
377 |
var message = String.Format("Conflict detected for file {0}", downloadPath); |
378 |
Log.Warn(message); |
379 |
StatusNotification.NotifyChange(message, TraceLevel.Warning); |
380 |
} |
381 |
|
382 |
public void Post(CloudAction cloudAction) |
383 |
{ |
384 |
if (cloudAction == null) |
385 |
throw new ArgumentNullException("cloudAction"); |
386 |
if (cloudAction.AccountInfo==null) |
387 |
throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction"); |
388 |
Contract.EndContractBlock(); |
389 |
|
390 |
_pauseAgent.Wait(); |
391 |
|
392 |
//If the action targets a local file, add a treehash calculation |
393 |
if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null) |
394 |
{ |
395 |
var accountInfo = cloudAction.AccountInfo; |
396 |
var localFile = (FileInfo) cloudAction.LocalFile; |
397 |
if (localFile.Length > accountInfo.BlockSize) |
398 |
cloudAction.TopHash = |
399 |
new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile, |
400 |
accountInfo.BlockSize, |
401 |
accountInfo.BlockHash).Result |
402 |
.TopHash.ToHashString()); |
403 |
else |
404 |
{ |
405 |
cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value); |
406 |
} |
407 |
} |
408 |
else |
409 |
{ |
410 |
//The hash for a directory is the empty string |
411 |
cloudAction.TopHash = new Lazy<string>(() => String.Empty); |
412 |
} |
413 |
|
414 |
if (cloudAction is CloudDeleteAction) |
415 |
_deleteAgent.Post((CloudDeleteAction)cloudAction); |
416 |
else |
417 |
_agent.Post(cloudAction); |
418 |
} |
419 |
|
420 |
/* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo> |
421 |
{ |
422 |
public bool Equals(ObjectInfo x, ObjectInfo y) |
423 |
{ |
424 |
return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase); |
425 |
} |
426 |
|
427 |
public int GetHashCode(ObjectInfo obj) |
428 |
{ |
429 |
return obj.Name.ToLower().GetHashCode(); |
430 |
} |
431 |
}*/ |
432 |
|
433 |
|
434 |
|
435 |
//Remote files are polled periodically. Any changes are processed |
436 |
public async Task PollRemoteFiles(DateTime? since = null) |
437 |
{ |
438 |
await TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval),_agent.CancellationToken); |
439 |
|
440 |
using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts")) |
441 |
{ |
442 |
|
443 |
try |
444 |
{ |
445 |
//Next time we will check for all changes since the current check minus 1 second |
446 |
//This is done to ensure there are no discrepancies due to clock differences |
447 |
DateTime nextSince = DateTime.Now.AddSeconds(-1); |
448 |
|
449 |
var tasks = from accountInfo in _accounts |
450 |
select ProcessAccountFiles(accountInfo, since); |
451 |
|
452 |
await TaskEx.WhenAll(tasks.ToList()); |
453 |
|
454 |
_firstPoll = false; |
455 |
PollRemoteFiles(nextSince); |
456 |
} |
457 |
catch (Exception ex) |
458 |
{ |
459 |
Log.ErrorFormat("Error while processing accounts\r\n{0}",ex); |
460 |
//In case of failure retry with the same parameter |
461 |
PollRemoteFiles(since); |
462 |
} |
463 |
|
464 |
|
465 |
} |
466 |
} |
467 |
|
468 |
public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null) |
469 |
{ |
470 |
if (accountInfo==null) |
471 |
throw new ArgumentNullException("accountInfo"); |
472 |
if (String.IsNullOrWhiteSpace(accountInfo.AccountPath)) |
473 |
throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo"); |
474 |
Contract.EndContractBlock(); |
475 |
|
476 |
using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName)) |
477 |
{ |
478 |
Log.Info("Scheduled"); |
479 |
var client=new CloudFilesClient(accountInfo); |
480 |
|
481 |
var containers = client.ListContainers(accountInfo.UserName); |
482 |
|
483 |
CreateContainerFolders(accountInfo, containers); |
484 |
|
485 |
try |
486 |
{ |
487 |
_pauseAgent.Wait(); |
488 |
//Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted |
489 |
//than delete a file that was created while we were executing the poll |
490 |
var pollTime = DateTime.Now; |
491 |
|
492 |
//Get the list of server objects changed since the last check |
493 |
//The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step |
494 |
var listObjects = from container in containers |
495 |
select Task<IList<ObjectInfo>>.Factory.StartNew(_ => |
496 |
client.ListObjects(accountInfo.UserName,container.Name, since),container.Name); |
497 |
|
498 |
|
499 |
var listTasks = await Task.Factory.WhenAll(listObjects.ToArray()); |
500 |
|
501 |
using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results")) |
502 |
{ |
503 |
var dict = listTasks.ToDictionary(t => t.AsyncState); |
504 |
|
505 |
//Get all non-trash objects. Remember, the container name is stored in AsyncState |
506 |
var remoteObjects = from objectList in listTasks |
507 |
where (string) objectList.AsyncState != "trash" |
508 |
from obj in objectList.Result |
509 |
select obj; |
510 |
|
511 |
//TODO: Change the way deleted objects are detected. |
512 |
//The list operation returns all existing objects so we could detect deleted remote objects |
513 |
//by detecting objects that exist only locally. There are several cases where this is NOT the case: |
514 |
//1. The first time the application runs, as there may be files that were added while |
515 |
// the application was down. |
516 |
//2. An object that is currently being uploaded will not appear in the remote list |
517 |
// until the upload finishes. |
518 |
// SOLUTION 1: Check the upload/download queue for the file |
519 |
// SOLUTION 2: Check the SQLite states for the file's entry. If it is being uploaded, |
520 |
// or its last modification was after the current poll, don't delete it. This way we don't |
521 |
// delete objects whose upload finished too late to be included in the list. |
522 |
//We need to detect and protect against such situations |
523 |
//TODO: Does FileState have a LastModification field? |
524 |
//TODO: How do we update the LastModification field? Do we need to add SQLite triggers? |
525 |
// Do we need to use a proper SQLite schema? |
526 |
// We can create a trigger with |
527 |
// CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW |
528 |
// BEGIN |
529 |
// UPDATE FileState SET LastModification=datetime('now') WHERE Id=old.Id; |
530 |
// END; |
531 |
// |
532 |
//NOTE: Some files may have been deleted remotely while the application was down. |
533 |
// We DO have to delete those files. Checking the trash makes it easy to detect them, |
534 |
// Otherwise, we can't be really sure whether we need to upload or delete |
535 |
// the local-only files. |
536 |
// SOLUTION 1: Ask the user when such a local-only file is detected during the first poll. |
537 |
// SOLUTION 2: Mark conflict and ask the user as in #1 |
538 |
|
539 |
var trashObjects = dict["trash"].Result; |
540 |
//var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result; |
541 |
|
542 |
//Items with the same name, hash may be both in the container and the trash |
543 |
//Don't delete items that exist in the container |
544 |
var realTrash = from trash in trashObjects |
545 |
where |
546 |
!remoteObjects.Any( |
547 |
info => info.Name == trash.Name && info.Hash == trash.Hash) |
548 |
select trash; |
549 |
ProcessTrashedFiles(accountInfo, realTrash); |
550 |
|
551 |
|
552 |
var cleanRemotes = (from info in remoteObjects |
553 |
//.Union(sharedObjects) |
554 |
let name = info.Name |
555 |
where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) && |
556 |
!name.StartsWith(FolderConstants.CacheFolder + "/", |
557 |
StringComparison.InvariantCultureIgnoreCase) |
558 |
select info).ToList(); |
559 |
|
560 |
|
561 |
|
562 |
ProcessDeletedFiles(accountInfo, cleanRemotes, pollTime); |
563 |
|
564 |
//Create a list of actions from the remote files |
565 |
var allActions = ObjectsToActions(accountInfo, cleanRemotes); |
566 |
|
567 |
|
568 |
//var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName); |
569 |
|
570 |
//And remove those that are already being processed by the agent |
571 |
var distinctActions = allActions |
572 |
.Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer()) |
573 |
.ToList(); |
574 |
|
575 |
//Queue all the actions |
576 |
foreach (var message in distinctActions) |
577 |
{ |
578 |
Post(message); |
579 |
} |
580 |
|
581 |
Log.Info("[LISTENER] End Processing"); |
582 |
} |
583 |
} |
584 |
catch (Exception ex) |
585 |
{ |
586 |
Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex); |
587 |
return; |
588 |
} |
589 |
|
590 |
Log.Info("[LISTENER] Finished"); |
591 |
|
592 |
} |
593 |
} |
594 |
|
595 |
/// <summary> |
596 |
/// Deletes local files that are not found in the list of cloud files |
597 |
/// </summary> |
598 |
/// <param name="accountInfo"></param> |
599 |
/// <param name="cloudFiles"></param> |
600 |
/// <param name="pollTime"></param> |
601 |
private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles, DateTime pollTime) |
602 |
{ |
603 |
if (accountInfo == null) |
604 |
throw new ArgumentNullException("accountInfo"); |
605 |
if (String.IsNullOrWhiteSpace(accountInfo.AccountPath)) |
606 |
throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo"); |
607 |
if (cloudFiles == null) |
608 |
throw new ArgumentNullException("cloudFiles"); |
609 |
Contract.EndContractBlock(); |
610 |
|
611 |
if (_firstPoll) return; |
612 |
|
613 |
var deleteCandidates = from state in FileState.Queryable |
614 |
let stateUrl = FileInfoExtensions.FromPath(state.FilePath) |
615 |
.AsRelativeUrlTo(accountInfo.AccountPath) |
616 |
where state.Modified <= pollTime && |
617 |
!cloudFiles.Any(r => r.Name == stateUrl) |
618 |
select state; |
619 |
|
620 |
foreach (var deleteCandidate in deleteCandidates) |
621 |
{ |
622 |
File.Delete(deleteCandidate.FilePath); |
623 |
StatusKeeper.ClearFileStatus(deleteCandidate.FilePath); |
624 |
} |
625 |
} |
626 |
|
627 |
private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers) |
628 |
{ |
629 |
var containerPaths = from container in containers |
630 |
let containerPath = Path.Combine(accountInfo.AccountPath, container.Name) |
631 |
where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath) |
632 |
select containerPath; |
633 |
|
634 |
foreach (var path in containerPaths) |
635 |
{ |
636 |
Directory.CreateDirectory(path); |
637 |
} |
638 |
} |
639 |
|
640 |
//Creates an appropriate action for each server file |
641 |
private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote) |
642 |
{ |
643 |
if (remote==null) |
644 |
throw new ArgumentNullException(); |
645 |
Contract.EndContractBlock(); |
646 |
var fileAgent = GetFileAgent(accountInfo); |
647 |
|
648 |
//In order to avoid multiple iterations over the files, we iterate only once |
649 |
//over the remote files |
650 |
foreach (var objectInfo in remote) |
651 |
{ |
652 |
var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName); |
653 |
//and remove any matching objects from the list, adding them to the commonObjects list |
654 |
|
655 |
if (fileAgent.Exists(relativePath)) |
656 |
{ |
657 |
//If a directory object already exists, we don't need to perform any other action |
658 |
var localFile = fileAgent.GetFileSystemInfo(relativePath); |
659 |
if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo) |
660 |
continue; |
661 |
using (new SessionScope(FlushAction.Never)) |
662 |
{ |
663 |
var state = StatusKeeper.GetStateByFilePath(localFile.FullName); |
664 |
//FileState.FindByFilePath(localFile.FullName); |
665 |
//Common files should be checked on a per-case basis to detect differences, which is newer |
666 |
|
667 |
yield return new CloudAction(accountInfo, CloudActionType.MustSynch, |
668 |
localFile, objectInfo, state, accountInfo.BlockSize, |
669 |
accountInfo.BlockHash); |
670 |
} |
671 |
} |
672 |
else |
673 |
{ |
674 |
//If there is no match we add them to the localFiles list |
675 |
//but only if the file is not marked for deletion |
676 |
var targetFile = Path.Combine(accountInfo.AccountPath, relativePath); |
677 |
var fileStatus = StatusKeeper.GetFileStatus(targetFile); |
678 |
if (fileStatus != FileStatus.Deleted) |
679 |
{ |
680 |
//Remote files should be downloaded |
681 |
yield return new CloudDownloadAction(accountInfo,objectInfo); |
682 |
} |
683 |
} |
684 |
} |
685 |
} |
686 |
|
687 |
private static FileAgent GetFileAgent(AccountInfo accountInfo) |
688 |
{ |
689 |
return AgentLocator<FileAgent>.Get(accountInfo.AccountPath); |
690 |
} |
691 |
|
692 |
private void ProcessTrashedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects) |
693 |
{ |
694 |
var fileAgent = GetFileAgent(accountInfo); |
695 |
foreach (var trashObject in trashObjects) |
696 |
{ |
697 |
var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName); |
698 |
//HACK: Assume only the "pithos" container is used. Must find out what happens when |
699 |
//deleting a file from a different container |
700 |
var relativePath = Path.Combine("pithos", barePath); |
701 |
fileAgent.Delete(relativePath); |
702 |
} |
703 |
} |
704 |
|
705 |
|
706 |
private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action) |
707 |
{ |
708 |
if (accountInfo==null) |
709 |
throw new ArgumentNullException("accountInfo"); |
710 |
if (action==null) |
711 |
throw new ArgumentNullException("action"); |
712 |
if (action.CloudFile==null) |
713 |
throw new ArgumentException("CloudFile","action"); |
714 |
if (action.LocalFile==null) |
715 |
throw new ArgumentException("LocalFile","action"); |
716 |
if (action.OldLocalFile==null) |
717 |
throw new ArgumentException("OldLocalFile","action"); |
718 |
if (action.OldCloudFile==null) |
719 |
throw new ArgumentException("OldCloudFile","action"); |
720 |
Contract.EndContractBlock(); |
721 |
|
722 |
|
723 |
var newFilePath = action.LocalFile.FullName; |
724 |
|
725 |
//How do we handle concurrent renames and deletes/uploads/downloads? |
726 |
//* A conflicting upload means that a file was renamed before it had a chance to finish uploading |
727 |
// This should never happen as the network agent executes only one action at a time |
728 |
//* A conflicting download means that the file was modified on the cloud. While we can go on and complete |
729 |
// the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the |
730 |
// same name will fail. |
731 |
// This should never happen as the network agent executes only one action at a time. |
732 |
//* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance |
733 |
// to remove the rename from the queue. |
734 |
// We can probably ignore this case. It will result in an error which should be ignored |
735 |
|
736 |
|
737 |
//The local file is already renamed |
738 |
StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified); |
739 |
|
740 |
|
741 |
var account = action.CloudFile.Account ?? accountInfo.UserName; |
742 |
var container = action.CloudFile.Container; |
743 |
|
744 |
var client = new CloudFilesClient(accountInfo); |
745 |
//TODO: What code is returned when the source file doesn't exist? |
746 |
client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name); |
747 |
|
748 |
StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged); |
749 |
StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal); |
750 |
NativeMethods.RaiseChangeNotification(newFilePath); |
751 |
} |
752 |
|
753 |
private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile) |
754 |
{ |
755 |
if (accountInfo == null) |
756 |
throw new ArgumentNullException("accountInfo"); |
757 |
if (cloudFile==null) |
758 |
throw new ArgumentNullException("cloudFile"); |
759 |
|
760 |
if (String.IsNullOrWhiteSpace(cloudFile.Container)) |
761 |
throw new ArgumentException("Invalid container", "cloudFile"); |
762 |
Contract.EndContractBlock(); |
763 |
|
764 |
var fileAgent = GetFileAgent(accountInfo); |
765 |
|
766 |
using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete")) |
767 |
{ |
768 |
var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName); |
769 |
var info = fileAgent.GetFileSystemInfo(fileName); |
770 |
var fullPath = info.FullName.ToLower(); |
771 |
|
772 |
StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified); |
773 |
|
774 |
var account = cloudFile.Account ?? accountInfo.UserName; |
775 |
var container = cloudFile.Container ;//?? FolderConstants.PithosContainer; |
776 |
|
777 |
var client = new CloudFilesClient(accountInfo); |
778 |
client.DeleteObject(account, container, cloudFile.Name); |
779 |
|
780 |
StatusKeeper.ClearFileStatus(fullPath); |
781 |
} |
782 |
} |
783 |
|
784 |
//Download a file. |
785 |
private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath) |
786 |
{ |
787 |
if (accountInfo == null) |
788 |
throw new ArgumentNullException("accountInfo"); |
789 |
if (cloudFile == null) |
790 |
throw new ArgumentNullException("cloudFile"); |
791 |
if (String.IsNullOrWhiteSpace(cloudFile.Account)) |
792 |
throw new ArgumentNullException("cloudFile"); |
793 |
if (String.IsNullOrWhiteSpace(cloudFile.Container)) |
794 |
throw new ArgumentNullException("cloudFile"); |
795 |
if (String.IsNullOrWhiteSpace(filePath)) |
796 |
throw new ArgumentNullException("filePath"); |
797 |
if (!Path.IsPathRooted(filePath)) |
798 |
throw new ArgumentException("The filePath must be rooted", "filePath"); |
799 |
Contract.EndContractBlock(); |
800 |
|
801 |
var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath); |
802 |
var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative); |
803 |
|
804 |
var url = relativeUrl.ToString(); |
805 |
if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase)) |
806 |
return; |
807 |
|
808 |
|
809 |
//Are we already downloading or uploading the file? |
810 |
using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading)) |
811 |
{ |
812 |
if (gate.Failed) |
813 |
return; |
814 |
//The file's hashmap will be stored in the same location with the extension .hashmap |
815 |
//var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap"); |
816 |
|
817 |
var client = new CloudFilesClient(accountInfo); |
818 |
var account = cloudFile.Account; |
819 |
var container = cloudFile.Container; |
820 |
|
821 |
if (cloudFile.Content_Type == @"application/directory") |
822 |
{ |
823 |
if (!Directory.Exists(localPath)) |
824 |
Directory.CreateDirectory(localPath); |
825 |
} |
826 |
else |
827 |
{ |
828 |
//Retrieve the hashmap from the server |
829 |
var serverHash = await client.GetHashMap(account, container, url); |
830 |
//If it's a small file |
831 |
if (serverHash.Hashes.Count == 1) |
832 |
//Download it in one go |
833 |
await |
834 |
DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash); |
835 |
//Otherwise download it block by block |
836 |
else |
837 |
await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash); |
838 |
|
839 |
if (cloudFile.AllowedTo == "read") |
840 |
{ |
841 |
var attributes = File.GetAttributes(localPath); |
842 |
File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly); |
843 |
} |
844 |
} |
845 |
|
846 |
//Now we can store the object's metadata without worrying about ghost status entries |
847 |
StatusKeeper.StoreInfo(localPath, cloudFile); |
848 |
|
849 |
} |
850 |
} |
851 |
|
852 |
//Download a small file with a single GET operation |
853 |
private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash) |
854 |
{ |
855 |
if (client == null) |
856 |
throw new ArgumentNullException("client"); |
857 |
if (cloudFile==null) |
858 |
throw new ArgumentNullException("cloudFile"); |
859 |
if (relativeUrl == null) |
860 |
throw new ArgumentNullException("relativeUrl"); |
861 |
if (String.IsNullOrWhiteSpace(filePath)) |
862 |
throw new ArgumentNullException("filePath"); |
863 |
if (!Path.IsPathRooted(filePath)) |
864 |
throw new ArgumentException("The localPath must be rooted", "filePath"); |
865 |
Contract.EndContractBlock(); |
866 |
|
867 |
var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath); |
868 |
//If the file already exists |
869 |
if (File.Exists(localPath)) |
870 |
{ |
871 |
//First check with MD5 as this is a small file |
872 |
var localMD5 = Signature.CalculateMD5(localPath); |
873 |
var cloudHash=serverHash.TopHash.ToHashString(); |
874 |
if (localMD5==cloudHash) |
875 |
return; |
876 |
//Then check with a treehash |
877 |
var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash); |
878 |
var localHash = localTreeHash.TopHash.ToHashString(); |
879 |
if (localHash==cloudHash) |
880 |
return; |
881 |
} |
882 |
|
883 |
var fileAgent = GetFileAgent(accountInfo); |
884 |
//Calculate the relative file path for the new file |
885 |
var relativePath = relativeUrl.RelativeUriToFilePath(); |
886 |
//The file will be stored in a temporary location while downloading with an extension .download |
887 |
var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download"); |
888 |
//Make sure the target folder exists. DownloadFileTask will not create the folder |
889 |
var tempFolder = Path.GetDirectoryName(tempPath); |
890 |
if (!Directory.Exists(tempFolder)) |
891 |
Directory.CreateDirectory(tempFolder); |
892 |
|
893 |
//Download the object to the temporary location |
894 |
await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath); |
895 |
|
896 |
//Create the local folder if it doesn't exist (necessary for shared objects) |
897 |
var localFolder = Path.GetDirectoryName(localPath); |
898 |
if (!Directory.Exists(localFolder)) |
899 |
Directory.CreateDirectory(localFolder); |
900 |
//And move it to its actual location once downloading is finished |
901 |
if (File.Exists(localPath)) |
902 |
File.Replace(tempPath,localPath,null,true); |
903 |
else |
904 |
File.Move(tempPath,localPath); |
905 |
//Notify listeners that a local file has changed |
906 |
StatusNotification.NotifyChangedFile(localPath); |
907 |
|
908 |
|
909 |
} |
910 |
|
911 |
//Download a file asynchronously using blocks |
912 |
public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash) |
913 |
{ |
914 |
if (client == null) |
915 |
throw new ArgumentNullException("client"); |
916 |
if (cloudFile == null) |
917 |
throw new ArgumentNullException("cloudFile"); |
918 |
if (relativeUrl == null) |
919 |
throw new ArgumentNullException("relativeUrl"); |
920 |
if (String.IsNullOrWhiteSpace(filePath)) |
921 |
throw new ArgumentNullException("filePath"); |
922 |
if (!Path.IsPathRooted(filePath)) |
923 |
throw new ArgumentException("The filePath must be rooted", "filePath"); |
924 |
if (serverHash == null) |
925 |
throw new ArgumentNullException("serverHash"); |
926 |
Contract.EndContractBlock(); |
927 |
|
928 |
var fileAgent = GetFileAgent(accountInfo); |
929 |
var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath); |
930 |
|
931 |
//Calculate the relative file path for the new file |
932 |
var relativePath = relativeUrl.RelativeUriToFilePath(); |
933 |
var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash); |
934 |
|
935 |
|
936 |
|
937 |
//Calculate the file's treehash |
938 |
var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash); |
939 |
|
940 |
//And compare it with the server's hash |
941 |
var upHashes = serverHash.GetHashesAsStrings(); |
942 |
var localHashes = treeHash.HashDictionary; |
943 |
for (int i = 0; i < upHashes.Length; i++) |
944 |
{ |
945 |
//For every non-matching hash |
946 |
var upHash = upHashes[i]; |
947 |
if (!localHashes.ContainsKey(upHash)) |
948 |
{ |
949 |
if (blockUpdater.UseOrphan(i, upHash)) |
950 |
{ |
951 |
Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath); |
952 |
continue; |
953 |
} |
954 |
Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath); |
955 |
var start = i*serverHash.BlockSize; |
956 |
//To download the last block just pass a null for the end of the range |
957 |
long? end = null; |
958 |
if (i < upHashes.Length - 1 ) |
959 |
end= ((i + 1)*serverHash.BlockSize) ; |
960 |
|
961 |
//Download the missing block |
962 |
var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end); |
963 |
|
964 |
//and store it |
965 |
blockUpdater.StoreBlock(i, block); |
966 |
|
967 |
|
968 |
Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath); |
969 |
} |
970 |
} |
971 |
|
972 |
//Want to avoid notifications if no changes were made |
973 |
var hasChanges = blockUpdater.HasBlocks; |
974 |
blockUpdater.Commit(); |
975 |
|
976 |
if (hasChanges) |
977 |
//Notify listeners that a local file has changed |
978 |
StatusNotification.NotifyChangedFile(localPath); |
979 |
|
980 |
Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath); |
981 |
} |
982 |
|
983 |
|
984 |
private async Task UploadCloudFile(CloudAction action) |
985 |
{ |
986 |
if (action == null) |
987 |
throw new ArgumentNullException("action"); |
988 |
Contract.EndContractBlock(); |
989 |
|
990 |
try |
991 |
{ |
992 |
var accountInfo = action.AccountInfo; |
993 |
|
994 |
var fileInfo = action.LocalFile; |
995 |
|
996 |
if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase)) |
997 |
return; |
998 |
|
999 |
var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath); |
1000 |
if (relativePath.StartsWith(FolderConstants.OthersFolder)) |
1001 |
{ |
1002 |
var parts = relativePath.Split('\\'); |
1003 |
var accountName = parts[1]; |
1004 |
var oldName = accountInfo.UserName; |
1005 |
var absoluteUri = accountInfo.StorageUri.AbsoluteUri; |
1006 |
var nameIndex = absoluteUri.IndexOf(oldName); |
1007 |
var root = absoluteUri.Substring(0, nameIndex); |
1008 |
|
1009 |
accountInfo = new AccountInfo |
1010 |
{ |
1011 |
UserName = accountName, |
1012 |
AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]), |
1013 |
StorageUri = new Uri(root + accountName), |
1014 |
BlockHash = accountInfo.BlockHash, |
1015 |
BlockSize = accountInfo.BlockSize, |
1016 |
Token = accountInfo.Token |
1017 |
}; |
1018 |
} |
1019 |
|
1020 |
|
1021 |
var fullFileName = fileInfo.GetProperCapitalization(); |
1022 |
using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading)) |
1023 |
{ |
1024 |
//Abort if the file is already being uploaded or downloaded |
1025 |
if (gate.Failed) |
1026 |
return; |
1027 |
|
1028 |
var cloudFile = action.CloudFile; |
1029 |
var account = cloudFile.Account ?? accountInfo.UserName; |
1030 |
|
1031 |
var client = new CloudFilesClient(accountInfo); |
1032 |
//Even if GetObjectInfo times out, we can proceed with the upload |
1033 |
var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name); |
1034 |
|
1035 |
//If this is a read-only file, do not upload changes |
1036 |
if (info.AllowedTo == "read") |
1037 |
return; |
1038 |
|
1039 |
//TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash |
1040 |
if (fileInfo is DirectoryInfo) |
1041 |
{ |
1042 |
//If the directory doesn't exist the Hash property will be empty |
1043 |
if (String.IsNullOrWhiteSpace(info.Hash)) |
1044 |
//Go on and create the directory |
1045 |
await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory"); |
1046 |
} |
1047 |
else |
1048 |
{ |
1049 |
|
1050 |
var cloudHash = info.Hash.ToLower(); |
1051 |
|
1052 |
var hash = action.LocalHash.Value; |
1053 |
var topHash = action.TopHash.Value; |
1054 |
|
1055 |
//If the file hashes match, abort the upload |
1056 |
if (hash == cloudHash || topHash == cloudHash) |
1057 |
{ |
1058 |
//but store any metadata changes |
1059 |
StatusKeeper.StoreInfo(fullFileName, info); |
1060 |
Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName); |
1061 |
return; |
1062 |
} |
1063 |
|
1064 |
|
1065 |
//Mark the file as modified while we upload it |
1066 |
StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified); |
1067 |
//And then upload it |
1068 |
|
1069 |
//Upload even small files using the Hashmap. The server may already contain |
1070 |
//the relevant block |
1071 |
|
1072 |
//First, calculate the tree hash |
1073 |
var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize, |
1074 |
accountInfo.BlockHash); |
1075 |
|
1076 |
await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash); |
1077 |
} |
1078 |
//If everything succeeds, change the file and overlay status to normal |
1079 |
StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal); |
1080 |
} |
1081 |
//Notify the Shell to update the overlays |
1082 |
NativeMethods.RaiseChangeNotification(fullFileName); |
1083 |
StatusNotification.NotifyChangedFile(fullFileName); |
1084 |
} |
1085 |
catch (AggregateException ex) |
1086 |
{ |
1087 |
var exc = ex.InnerException as WebException; |
1088 |
if (exc == null) |
1089 |
throw ex.InnerException; |
1090 |
if (HandleUploadWebException(action, exc)) |
1091 |
return; |
1092 |
throw; |
1093 |
} |
1094 |
catch (WebException ex) |
1095 |
{ |
1096 |
if (HandleUploadWebException(action, ex)) |
1097 |
return; |
1098 |
throw; |
1099 |
} |
1100 |
catch (Exception ex) |
1101 |
{ |
1102 |
Log.Error("Unexpected error while uploading file", ex); |
1103 |
throw; |
1104 |
} |
1105 |
|
1106 |
} |
1107 |
|
1108 |
private bool IsDeletedFile(CloudAction action) |
1109 |
{ |
1110 |
var key = GetFileKey(action.CloudFile); |
1111 |
DateTime entryDate; |
1112 |
if (_deletedFiles.TryGetValue(key, out entryDate)) |
1113 |
{ |
1114 |
//If the delete entry was created after this action, abort the action |
1115 |
if (entryDate > action.Created) |
1116 |
return true; |
1117 |
//Otherwise, remove the stale entry |
1118 |
_deletedFiles.TryRemove(key, out entryDate); |
1119 |
} |
1120 |
return false; |
1121 |
} |
1122 |
|
1123 |
private bool HandleUploadWebException(CloudAction action, WebException exc) |
1124 |
{ |
1125 |
var response = exc.Response as HttpWebResponse; |
1126 |
if (response == null) |
1127 |
throw exc; |
1128 |
if (response.StatusCode == HttpStatusCode.Unauthorized) |
1129 |
{ |
1130 |
Log.Error("Not allowed to upload file", exc); |
1131 |
var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName); |
1132 |
StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal); |
1133 |
StatusNotification.NotifyChange(message, TraceLevel.Warning); |
1134 |
return true; |
1135 |
} |
1136 |
return false; |
1137 |
} |
1138 |
|
1139 |
public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash) |
1140 |
{ |
1141 |
if (accountInfo == null) |
1142 |
throw new ArgumentNullException("accountInfo"); |
1143 |
if (cloudFile==null) |
1144 |
throw new ArgumentNullException("cloudFile"); |
1145 |
if (fileInfo == null) |
1146 |
throw new ArgumentNullException("fileInfo"); |
1147 |
if (String.IsNullOrWhiteSpace(url)) |
1148 |
throw new ArgumentNullException(url); |
1149 |
if (treeHash==null) |
1150 |
throw new ArgumentNullException("treeHash"); |
1151 |
if (String.IsNullOrWhiteSpace(cloudFile.Container) ) |
1152 |
throw new ArgumentException("Invalid container","cloudFile"); |
1153 |
Contract.EndContractBlock(); |
1154 |
|
1155 |
var fullFileName = fileInfo.GetProperCapitalization(); |
1156 |
|
1157 |
var account = cloudFile.Account ?? accountInfo.UserName; |
1158 |
var container = cloudFile.Container ; |
1159 |
|
1160 |
var client = new CloudFilesClient(accountInfo); |
1161 |
//Send the hashmap to the server |
1162 |
var missingHashes = await client.PutHashMap(account, container, url, treeHash); |
1163 |
//If the server returns no missing hashes, we are done |
1164 |
while (missingHashes.Count > 0) |
1165 |
{ |
1166 |
|
1167 |
var buffer = new byte[accountInfo.BlockSize]; |
1168 |
foreach (var missingHash in missingHashes) |
1169 |
{ |
1170 |
//Find the proper block |
1171 |
var blockIndex = treeHash.HashDictionary[missingHash]; |
1172 |
var offset = blockIndex*accountInfo.BlockSize; |
1173 |
|
1174 |
var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize); |
1175 |
|
1176 |
try |
1177 |
{ |
1178 |
//And upload the block |
1179 |
await client.PostBlock(account, container, buffer, 0, read); |
1180 |
Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName); |
1181 |
} |
1182 |
catch (Exception exc) |
1183 |
{ |
1184 |
Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc); |
1185 |
} |
1186 |
|
1187 |
} |
1188 |
|
1189 |
//Repeat until there are no more missing hashes |
1190 |
missingHashes = await client.PutHashMap(account, container, url, treeHash); |
1191 |
} |
1192 |
} |
1193 |
|
1194 |
|
1195 |
public void AddAccount(AccountInfo accountInfo) |
1196 |
{ |
1197 |
if (!_accounts.Contains(accountInfo)) |
1198 |
_accounts.Add(accountInfo); |
1199 |
} |
1200 |
} |
1201 |
|
1202 |
|
1203 |
|
1204 |
|
1205 |
} |