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