Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 3c76f045

History | View | Annotate | Download (50.3 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.Tasks;
48
using System.Threading.Tasks.Dataflow;
49
using Castle.ActiveRecord;
50
using Pithos.Interfaces;
51
using Pithos.Network;
52
using log4net;
53

    
54
namespace Pithos.Core.Agents
55
{
56
    //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
57
    [Export]
58
    public class NetworkAgent
59
    {
60
        private Agent<CloudAction> _agent;
61

    
62
        //A separate agent is used to execute delete actions immediatelly;
63
        private ActionBlock<CloudDeleteAction> _deleteAgent;
64
        readonly ConcurrentDictionary<string,DateTime> _deletedFiles=new ConcurrentDictionary<string, DateTime>();
65

    
66
        [System.ComponentModel.Composition.Import]
67
        public IStatusKeeper StatusKeeper { get; set; }
68
        
69
        public IStatusNotification StatusNotification { get; set; }
70

    
71
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
72

    
73
        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
74

    
75
        public void Start()
76
        {
77

    
78
            _agent = Agent<CloudAction>.Start(inbox =>
79
            {
80
                Action loop = null;
81
                loop = () =>
82
                {
83
                    var message = inbox.Receive();
84
                    var process=message.Then(Process,inbox.CancellationToken);
85
                    inbox.LoopAsync(process, loop);
86
                };
87
                loop();
88
            });
89

    
90
            _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
91
            /*
92
                Action loop = null;
93
                loop = () =>
94
                            {
95
                                var message = inbox.Receive();
96
                                var process = message.Then(ProcessDelete,inbox.CancellationToken);
97
                                inbox.LoopAsync(process, loop);
98
                            };
99
                loop();
100
*/
101

    
102
        }
103

    
104
        private async Task Process(CloudAction action)
105
        {
106
            if (action == null)
107
                throw new ArgumentNullException("action");
108
            if (action.AccountInfo==null)
109
                throw new ArgumentException("The action.AccountInfo is empty","action");
110
            Contract.EndContractBlock();
111

    
112
            var accountInfo = action.AccountInfo;
113

    
114
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
115
            {                
116
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
117

    
118
                var cloudFile = action.CloudFile;
119
                var downloadPath = action.GetDownloadPath();
120

    
121
                try
122
                {
123

    
124
                    if (action.Action == CloudActionType.DeleteCloud)
125
                    {
126
                        //Redirect deletes to the delete agent 
127
                        _deleteAgent.Post((CloudDeleteAction)action);                        
128
                    }
129
                    if (IsDeletedFile(action))
130
                    {
131
                        //Clear the status of already deleted files to avoid reprocessing
132
                        if (action.LocalFile != null)
133
                            this.StatusKeeper.ClearFileStatus(action.LocalFile.FullName);
134
                    }
135
                    else
136
                    {
137
                        switch (action.Action)
138
                        {
139
                            case CloudActionType.UploadUnconditional:
140
                                //Abort if the file was deleted before we reached this point
141
                                await UploadCloudFile(action);
142
                                break;
143
                            case CloudActionType.DownloadUnconditional:
144
                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
145
                                break;
146
                            case CloudActionType.RenameCloud:
147
                                var moveAction = (CloudMoveAction) action;
148
                                RenameCloudFile(accountInfo, moveAction);
149
                                break;
150
                            case CloudActionType.MustSynch:
151
                                if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
152
                                {
153
                                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
154
                                }
155
                                else
156
                                {
157
                                    await SyncFiles(accountInfo, action);
158
                                }
159
                                break;
160
                        }
161
                    }
162
                    Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
163
                                           action.CloudFile.Name);
164
                }
165
                catch (WebException exc)
166
                {
167
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
168
                }
169
                catch (OperationCanceledException)
170
                {
171
                    throw;
172
                }
173
                catch (DirectoryNotFoundException)
174
                {
175
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
176
                        action.Action, action.LocalFile, action.CloudFile);
177
                    //Post a delete action for the missing file
178
                    Post(new CloudDeleteAction(action));                    
179
                }
180
                catch (FileNotFoundException)
181
                {
182
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
183
                        action.Action, action.LocalFile, action.CloudFile);
184
                    //Post a delete action for the missing file
185
                    Post(new CloudDeleteAction(action));
186
                }
187
                catch (Exception exc)
188
                {
189
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
190
                                     action.Action, action.LocalFile, action.CloudFile, exc);
191

    
192
                    _agent.Post(action);
193
                }                
194
            }
195
        }
196

    
197
        /// <summary>
198
        /// Processes cloud delete actions
199
        /// </summary>
200
        /// <param name="action">The delete action to execute</param>
201
        /// <returns></returns>
202
        /// <remarks>
203
        /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
204
        /// operations that may be in progress.
205
        /// <para>
206
        /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
207
        /// </para>
208
        /// </remarks>
209
        private async Task ProcessDelete(CloudDeleteAction action)
210
        {
211
            if (action == null)
212
                throw new ArgumentNullException("action");
213
            if (action.AccountInfo==null)
214
                throw new ArgumentException("The action.AccountInfo is empty","action");
215
            Contract.EndContractBlock();
216

    
217
            var accountInfo = action.AccountInfo;
218

    
219
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
220
            {                
221
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
222

    
223
                var cloudFile = action.CloudFile;
224

    
225
                try
226
                {
227
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
228
                    //agent
229
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
230
                    {
231
                        
232
                        //Add the file URL to the deleted files list
233
                        var key = GetFileKey(action.CloudFile);
234
                        _deletedFiles[key]=DateTime.Now;
235

    
236

    
237
                        // and then delete the file from the server
238
                        DeleteCloudFile(accountInfo, cloudFile);
239

    
240
                        Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
241
                                       action.CloudFile.Name);
242
                    }
243
                }
244
                catch (WebException exc)
245
                {
246
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
247
                }
248
                catch (OperationCanceledException)
249
                {
250
                    throw;
251
                }
252
                catch (DirectoryNotFoundException)
253
                {
254
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
255
                        action.Action, action.LocalFile, action.CloudFile);
256
                    //Repost a delete action for the missing file
257
                    _deleteAgent.Post(action);                    
258
                }
259
                catch (FileNotFoundException)
260
                {
261
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
262
                        action.Action, action.LocalFile, action.CloudFile);
263
                    //Post a delete action for the missing file
264
                    _deleteAgent.Post(action);
265
                }
266
                catch (Exception exc)
267
                {
268
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
269
                                     action.Action, action.LocalFile, action.CloudFile, exc);
270

    
271
                    _deleteAgent.Post(action);
272
                }                
273
            }
274
        }
275

    
276
        private static string GetFileKey(ObjectInfo info)
277
        {
278
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
279
            return key;
280
        }
281

    
282
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
283
        {
284
            if (accountInfo == null)
285
                throw new ArgumentNullException("accountInfo");
286
            if (action==null)
287
                throw new ArgumentNullException("action");
288
            if (action.LocalFile==null)
289
                throw new ArgumentException("The action's local file is not specified","action");
290
            if (!Path.IsPathRooted(action.LocalFile.FullName))
291
                throw new ArgumentException("The action's local file path must be absolute","action");
292
            if (action.CloudFile== null)
293
                throw new ArgumentException("The action's cloud file is not specified", "action");
294
            Contract.EndContractBlock();
295

    
296
            var localFile = action.LocalFile;
297
            var cloudFile = action.CloudFile;
298
            var downloadPath=action.LocalFile.GetProperCapitalization();
299

    
300
            var cloudHash = cloudFile.Hash.ToLower();
301
            var localHash = action.LocalHash.Value.ToLower();
302
            var topHash = action.TopHash.Value.ToLower();
303

    
304
            //Not enough to compare only the local hashes, also have to compare the tophashes
305
            
306
            //If any of the hashes match, we are done
307
            if ((cloudHash == localHash || cloudHash == topHash))
308
            {
309
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
310
                return;
311
            }
312

    
313
            //The hashes DON'T match. We need to sync
314
            var lastLocalTime = localFile.LastWriteTime;
315
            var lastUpTime = cloudFile.Last_Modified;
316
            
317
            //If the local file is newer upload it
318
            if (lastUpTime <= lastLocalTime)
319
            {
320
                //It probably means it was changed while the app was down                        
321
                UploadCloudFile(action);
322
            }
323
            else
324
            {
325
                //It the cloud file has a later date, it was modified by another user or computer.
326
                //We need to check the local file's status                
327
                var status = StatusKeeper.GetFileStatus(downloadPath);
328
                switch (status)
329
                {
330
                    case FileStatus.Unchanged:                        
331
                        //If the local file's status is Unchanged, we can go on and download the newer cloud file
332
                        await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
333
                        break;
334
                    case FileStatus.Modified:
335
                        //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
336
                        //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
337
                        //index all files before we start listening.                       
338
                    case FileStatus.Created:
339
                        //If the local file is Created, it means that the local and cloud files aren't related,
340
                        // yet they have the same name.
341

    
342
                        //In both cases we must mark the file as in conflict
343
                        ReportConflict(downloadPath);
344
                        break;
345
                    default:
346
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
347
                        ReportConflict(downloadPath);
348
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
349
                                       downloadPath, action.CloudFile.Name);
350
                        break;
351
                }
352
            }
353
        }
354

    
355
        private void ReportConflict(string downloadPath)
356
        {
357
            if (String.IsNullOrWhiteSpace(downloadPath))
358
                throw new ArgumentNullException("downloadPath");
359
            Contract.EndContractBlock();
360

    
361
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
362
            var message = String.Format("Conflict detected for file {0}", downloadPath);
363
            Log.Warn(message);
364
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
365
        }
366

    
367
        public void Post(CloudAction cloudAction)
368
        {
369
            if (cloudAction == null)
370
                throw new ArgumentNullException("cloudAction");
371
            if (cloudAction.AccountInfo==null)
372
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
373
            Contract.EndContractBlock();
374

    
375
            //If the action targets a local file, add a treehash calculation
376
            if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
377
            {
378
                var accountInfo = cloudAction.AccountInfo;
379
                var localFile = (FileInfo) cloudAction.LocalFile;
380
                if (localFile.Length > accountInfo.BlockSize)
381
                    cloudAction.TopHash =
382
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
383
                                                                                accountInfo.BlockSize,
384
                                                                                accountInfo.BlockHash).Result
385
                                                    .TopHash.ToHashString());
386
                else
387
                {
388
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
389
                }
390
            }
391
            else
392
            {
393
                //The hash for a directory is the empty string
394
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
395
            }
396
            
397
            if (cloudAction is CloudDeleteAction)
398
                _deleteAgent.Post((CloudDeleteAction)cloudAction);
399
            else
400
                _agent.Post(cloudAction);
401
        }
402

    
403
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
404
        {
405
            public bool Equals(ObjectInfo x, ObjectInfo y)
406
            {
407
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
408
            }
409

    
410
            public int GetHashCode(ObjectInfo obj)
411
            {
412
                return obj.Name.ToLower().GetHashCode();
413
            }
414
        }*/
415

    
416
        
417

    
418
        //Remote files are polled periodically. Any changes are processed
419
        public async Task ProcessRemoteFiles(DateTime? since = null)
420
        {            
421
            await TaskEx.Delay(TimeSpan.FromSeconds(10),_agent.CancellationToken);
422

    
423
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
424
            {
425

    
426
                try
427
                {
428
                    //Next time we will check for all changes since the current check minus 1 second
429
                    //This is done to ensure there are no discrepancies due to clock differences
430
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
431

    
432
                    var tasks = from accountInfo in _accounts
433
                                select ProcessAccountFiles(accountInfo, since);
434

    
435
                    await TaskEx.WhenAll(tasks.ToList());
436

    
437
                    ProcessRemoteFiles(nextSince);
438
                }
439
                catch (Exception ex)
440
                {
441
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
442
                    //In case of failure retry with the same parameter
443
                    ProcessRemoteFiles(since);
444
                }
445
                
446

    
447
            }
448
        }
449

    
450
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
451
        {   
452
            if (accountInfo==null)
453
                throw new ArgumentNullException("accountInfo");
454
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
455
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
456
            Contract.EndContractBlock();
457

    
458
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
459
            {
460
                Log.Info("Scheduled");
461
                var client=new CloudFilesClient(accountInfo);
462

    
463
                var containers = client.ListContainers(accountInfo.UserName);
464
                
465
                CreateContainerFolders(accountInfo, containers);
466

    
467
                try
468
                {
469
                    
470
                    //Get the list of server objects changed since the last check
471
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
472
                    var listObjects = from container in containers
473
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
474
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
475

    
476

    
477
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
478

    
479
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
480
                    {
481
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
482

    
483
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
484
                        var remoteObjects = from objectList in listTasks
485
                                            where (string) objectList.AsyncState != "trash"
486
                                            from obj in objectList.Result
487
                                            select obj;
488

    
489
                        var trashObjects = dict["trash"].Result;
490
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
491

    
492
                        //Items with the same name, hash may be both in the container and the trash
493
                        //Don't delete items that exist in the container
494
                        var realTrash = from trash in trashObjects
495
                                        where
496
                                            !remoteObjects.Any(
497
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
498
                                        select trash;
499
                        ProcessDeletedFiles(accountInfo, realTrash);
500

    
501

    
502
                        var remote = from info in remoteObjects
503
                                     //.Union(sharedObjects)
504
                                     let name = info.Name
505
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
506
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
507
                                                            StringComparison.InvariantCultureIgnoreCase)
508
                                     select info;
509

    
510
                        //Create a list of actions from the remote files
511
                        var allActions = ObjectsToActions(accountInfo, remote);
512

    
513
                        //And remove those that are already being processed by the agent
514
                        var distinctActions = allActions
515
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
516
                            .ToList();
517

    
518
                        //Queue all the actions
519
                        foreach (var message in distinctActions)
520
                        {
521
                            Post(message);
522
                        }
523

    
524
                        Log.Info("[LISTENER] End Processing");
525
                    }
526
                }
527
                catch (Exception ex)
528
                {
529
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
530
                    return;
531
                }
532

    
533
                Log.Info("[LISTENER] Finished");
534

    
535
            }
536
        }
537

    
538
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
539
        {
540
            var containerPaths = from container in containers
541
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
542
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
543
                                 select containerPath;
544

    
545
            foreach (var path in containerPaths)
546
            {
547
                Directory.CreateDirectory(path);
548
            }
549
        }
550

    
551
        //Creates an appropriate action for each server file
552
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
553
        {
554
            if (remote==null)
555
                throw new ArgumentNullException();
556
            Contract.EndContractBlock();
557
            var fileAgent = GetFileAgent(accountInfo);
558

    
559
            //In order to avoid multiple iterations over the files, we iterate only once
560
            //over the remote files
561
            foreach (var objectInfo in remote)
562
            {
563
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
564
                //and remove any matching objects from the list, adding them to the commonObjects list
565
                
566
                if (fileAgent.Exists(relativePath))
567
                {
568
                    //If a directory object already exists, we don't need to perform any other action                    
569
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
570
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
571
                        continue;
572
                    using (new SessionScope(FlushAction.Never))
573
                    {
574
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
575
                        //FileState.FindByFilePath(localFile.FullName);
576
                        //Common files should be checked on a per-case basis to detect differences, which is newer
577

    
578
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
579
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
580
                                                     accountInfo.BlockHash);
581
                    }
582
                }
583
                else
584
                {
585
                    //If there is no match we add them to the localFiles list
586
                    //but only if the file is not marked for deletion
587
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
588
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
589
                    if (fileStatus != FileStatus.Deleted)
590
                    {
591
                        //Remote files should be downloaded
592
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
593
                    }
594
                }
595
            }            
596
        }
597

    
598
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
599
        {
600
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
601
        }
602

    
603
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
604
        {
605
            var fileAgent = GetFileAgent(accountInfo);
606
            foreach (var trashObject in trashObjects)
607
            {
608
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
609
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
610
                //deleting a file from a different container
611
                var relativePath = Path.Combine("pithos", barePath);
612
                fileAgent.Delete(relativePath);                                
613
            }
614
        }
615

    
616

    
617
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
618
        {
619
            if (accountInfo==null)
620
                throw new ArgumentNullException("accountInfo");
621
            if (action==null)
622
                throw new ArgumentNullException("action");
623
            if (action.CloudFile==null)
624
                throw new ArgumentException("CloudFile","action");
625
            if (action.LocalFile==null)
626
                throw new ArgumentException("LocalFile","action");
627
            if (action.OldLocalFile==null)
628
                throw new ArgumentException("OldLocalFile","action");
629
            if (action.OldCloudFile==null)
630
                throw new ArgumentException("OldCloudFile","action");
631
            Contract.EndContractBlock();
632
            
633
            
634
            var newFilePath = action.LocalFile.FullName;
635
            
636
            //How do we handle concurrent renames and deletes/uploads/downloads?
637
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
638
            //  This should never happen as the network agent executes only one action at a time
639
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
640
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
641
            //  same name will fail.
642
            //  This should never happen as the network agent executes only one action at a time.
643
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
644
            //  to remove the rename from the queue.
645
            //  We can probably ignore this case. It will result in an error which should be ignored            
646

    
647
            
648
            //The local file is already renamed
649
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
650

    
651

    
652
            var account = action.CloudFile.Account ?? accountInfo.UserName;
653
            var container = action.CloudFile.Container;
654
            
655
            var client = new CloudFilesClient(accountInfo);
656
            //TODO: What code is returned when the source file doesn't exist?
657
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
658

    
659
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
660
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
661
            NativeMethods.RaiseChangeNotification(newFilePath);
662
        }
663

    
664
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
665
        {
666
            if (accountInfo == null)
667
                throw new ArgumentNullException("accountInfo");
668
            if (cloudFile==null)
669
                throw new ArgumentNullException("cloudFile");
670

    
671
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
672
                throw new ArgumentException("Invalid container", "cloudFile");
673
            Contract.EndContractBlock();
674
            
675
            var fileAgent = GetFileAgent(accountInfo);
676

    
677
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
678
            {
679
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
680
                var info = fileAgent.GetFileSystemInfo(fileName);                
681
                var fullPath = info.FullName.ToLower();
682

    
683
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
684

    
685
                var account = cloudFile.Account ?? accountInfo.UserName;
686
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
687

    
688
                var client = new CloudFilesClient(accountInfo);
689
                client.DeleteObject(account, container, cloudFile.Name);
690

    
691
                StatusKeeper.ClearFileStatus(fullPath);
692
            }
693
        }
694

    
695
        //Download a file.
696
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
697
        {
698
            if (accountInfo == null)
699
                throw new ArgumentNullException("accountInfo");
700
            if (cloudFile == null)
701
                throw new ArgumentNullException("cloudFile");
702
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
703
                throw new ArgumentNullException("cloudFile");
704
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
705
                throw new ArgumentNullException("cloudFile");
706
            if (String.IsNullOrWhiteSpace(filePath))
707
                throw new ArgumentNullException("filePath");
708
            if (!Path.IsPathRooted(filePath))
709
                throw new ArgumentException("The filePath must be rooted", "filePath");
710
            Contract.EndContractBlock();
711

    
712
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
713
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
714

    
715
            var url = relativeUrl.ToString();
716
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
717
                return;
718

    
719

    
720
            //Are we already downloading or uploading the file? 
721
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
722
            {
723
                if (gate.Failed)
724
                    return;
725
                //The file's hashmap will be stored in the same location with the extension .hashmap
726
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
727
                
728
                var client = new CloudFilesClient(accountInfo);
729
                var account = cloudFile.Account;
730
                var container = cloudFile.Container;
731

    
732
                if (cloudFile.Content_Type == @"application/directory")
733
                {
734
                    if (!Directory.Exists(localPath))
735
                        Directory.CreateDirectory(localPath);
736
                }
737
                else
738
                {
739
                    //Retrieve the hashmap from the server
740
                    var serverHash = await client.GetHashMap(account, container, url);
741
                    //If it's a small file
742
                    if (serverHash.Hashes.Count == 1)
743
                        //Download it in one go
744
                        await
745
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
746
                        //Otherwise download it block by block
747
                    else
748
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
749

    
750
                    if (cloudFile.AllowedTo == "read")
751
                    {
752
                        var attributes = File.GetAttributes(localPath);
753
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
754
                    }
755
                }
756

    
757
                //Now we can store the object's metadata without worrying about ghost status entries
758
                StatusKeeper.StoreInfo(localPath, cloudFile);
759
                
760
            }
761
        }
762

    
763
        //Download a small file with a single GET operation
764
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
765
        {
766
            if (client == null)
767
                throw new ArgumentNullException("client");
768
            if (cloudFile==null)
769
                throw new ArgumentNullException("cloudFile");
770
            if (relativeUrl == null)
771
                throw new ArgumentNullException("relativeUrl");
772
            if (String.IsNullOrWhiteSpace(filePath))
773
                throw new ArgumentNullException("filePath");
774
            if (!Path.IsPathRooted(filePath))
775
                throw new ArgumentException("The localPath must be rooted", "filePath");
776
            Contract.EndContractBlock();
777

    
778
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
779
            //If the file already exists
780
            if (File.Exists(localPath))
781
            {
782
                //First check with MD5 as this is a small file
783
                var localMD5 = Signature.CalculateMD5(localPath);
784
                var cloudHash=serverHash.TopHash.ToHashString();
785
                if (localMD5==cloudHash)
786
                    return;
787
                //Then check with a treehash
788
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
789
                var localHash = localTreeHash.TopHash.ToHashString();
790
                if (localHash==cloudHash)
791
                    return;
792
            }
793

    
794
            var fileAgent = GetFileAgent(accountInfo);
795
            //Calculate the relative file path for the new file
796
            var relativePath = relativeUrl.RelativeUriToFilePath();
797
            //The file will be stored in a temporary location while downloading with an extension .download
798
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
799
            //Make sure the target folder exists. DownloadFileTask will not create the folder
800
            var tempFolder = Path.GetDirectoryName(tempPath);
801
            if (!Directory.Exists(tempFolder))
802
                Directory.CreateDirectory(tempFolder);
803

    
804
            //Download the object to the temporary location
805
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
806

    
807
            //Create the local folder if it doesn't exist (necessary for shared objects)
808
            var localFolder = Path.GetDirectoryName(localPath);
809
            if (!Directory.Exists(localFolder))
810
                Directory.CreateDirectory(localFolder);            
811
            //And move it to its actual location once downloading is finished
812
            if (File.Exists(localPath))
813
                File.Replace(tempPath,localPath,null,true);
814
            else
815
                File.Move(tempPath,localPath);
816
            //Notify listeners that a local file has changed
817
            StatusNotification.NotifyChangedFile(localPath);
818

    
819
                       
820
        }
821

    
822
        //Download a file asynchronously using blocks
823
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
824
        {
825
            if (client == null)
826
                throw new ArgumentNullException("client");
827
            if (cloudFile == null)
828
                throw new ArgumentNullException("cloudFile");
829
            if (relativeUrl == null)
830
                throw new ArgumentNullException("relativeUrl");
831
            if (String.IsNullOrWhiteSpace(filePath))
832
                throw new ArgumentNullException("filePath");
833
            if (!Path.IsPathRooted(filePath))
834
                throw new ArgumentException("The filePath must be rooted", "filePath");
835
            if (serverHash == null)
836
                throw new ArgumentNullException("serverHash");
837
            Contract.EndContractBlock();
838
            
839
           var fileAgent = GetFileAgent(accountInfo);
840
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
841
            
842
            //Calculate the relative file path for the new file
843
            var relativePath = relativeUrl.RelativeUriToFilePath();
844
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
845

    
846
            
847
                        
848
            //Calculate the file's treehash
849
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
850
                
851
            //And compare it with the server's hash
852
            var upHashes = serverHash.GetHashesAsStrings();
853
            var localHashes = treeHash.HashDictionary;
854
            for (int i = 0; i < upHashes.Length; i++)
855
            {
856
                //For every non-matching hash
857
                var upHash = upHashes[i];
858
                if (!localHashes.ContainsKey(upHash))
859
                {
860
                    if (blockUpdater.UseOrphan(i, upHash))
861
                    {
862
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
863
                        continue;
864
                    }
865
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
866
                    var start = i*serverHash.BlockSize;
867
                    //To download the last block just pass a null for the end of the range
868
                    long? end = null;
869
                    if (i < upHashes.Length - 1 )
870
                        end= ((i + 1)*serverHash.BlockSize) ;
871
                            
872
                    //Download the missing block
873
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
874

    
875
                    //and store it
876
                    blockUpdater.StoreBlock(i, block);
877

    
878

    
879
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
880
                }
881
            }
882

    
883
            //Want to avoid notifications if no changes were made
884
            var hasChanges = blockUpdater.HasBlocks;
885
            blockUpdater.Commit();
886
            
887
            if (hasChanges)
888
                //Notify listeners that a local file has changed
889
                StatusNotification.NotifyChangedFile(localPath);
890

    
891
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
892
        }
893

    
894

    
895
        private async Task UploadCloudFile(CloudAction action)
896
        {
897
            if (action == null)
898
                throw new ArgumentNullException("action");           
899
            Contract.EndContractBlock();
900

    
901
            try
902
            {
903
                var accountInfo = action.AccountInfo;
904

    
905
                var fileInfo = action.LocalFile;
906

    
907
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
908
                    return;
909
                
910
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
911
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
912
                {
913
                    var parts = relativePath.Split('\\');
914
                    var accountName = parts[1];
915
                    var oldName = accountInfo.UserName;
916
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
917
                    var nameIndex = absoluteUri.IndexOf(oldName);
918
                    var root = absoluteUri.Substring(0, nameIndex);
919

    
920
                    accountInfo = new AccountInfo
921
                    {
922
                        UserName = accountName,
923
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
924
                        StorageUri = new Uri(root + accountName),
925
                        BlockHash = accountInfo.BlockHash,
926
                        BlockSize = accountInfo.BlockSize,
927
                        Token = accountInfo.Token
928
                    };
929
                }
930

    
931

    
932
                var fullFileName = fileInfo.GetProperCapitalization();
933
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
934
                {
935
                    //Abort if the file is already being uploaded or downloaded
936
                    if (gate.Failed)
937
                        return;
938

    
939
                    var cloudFile = action.CloudFile;
940
                    var account = cloudFile.Account ?? accountInfo.UserName;
941

    
942
                    var client = new CloudFilesClient(accountInfo);                    
943
                    //Even if GetObjectInfo times out, we can proceed with the upload            
944
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
945

    
946
                    //If this is a read-only file, do not upload changes
947
                    if (info.AllowedTo == "read")
948
                        return;
949
                    
950
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
951
                    if (fileInfo is DirectoryInfo)
952
                    {
953
                        //If the directory doesn't exist the Hash property will be empty
954
                        if (String.IsNullOrWhiteSpace(info.Hash))
955
                            //Go on and create the directory
956
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
957
                    }
958
                    else
959
                    {
960

    
961
                        var cloudHash = info.Hash.ToLower();
962

    
963
                        var hash = action.LocalHash.Value;
964
                        var topHash = action.TopHash.Value;
965

    
966
                        //If the file hashes match, abort the upload
967
                        if (hash == cloudHash || topHash == cloudHash)
968
                        {
969
                            //but store any metadata changes 
970
                            StatusKeeper.StoreInfo(fullFileName, info);
971
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
972
                            return;
973
                        }
974

    
975

    
976
                        //Mark the file as modified while we upload it
977
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
978
                        //And then upload it
979

    
980
                        //Upload even small files using the Hashmap. The server may already contain
981
                        //the relevant block
982

    
983
                        //First, calculate the tree hash
984
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
985
                                                                              accountInfo.BlockHash);
986

    
987
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
988
                    }
989
                    //If everything succeeds, change the file and overlay status to normal
990
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
991
                }
992
                //Notify the Shell to update the overlays
993
                NativeMethods.RaiseChangeNotification(fullFileName);
994
                StatusNotification.NotifyChangedFile(fullFileName);
995
            }
996
            catch (AggregateException ex)
997
            {
998
                var exc = ex.InnerException as WebException;
999
                if (exc == null)
1000
                    throw ex.InnerException;
1001
                if (HandleUploadWebException(action, exc)) 
1002
                    return;
1003
                throw;
1004
            }
1005
            catch (WebException ex)
1006
            {
1007
                if (HandleUploadWebException(action, ex))
1008
                    return;
1009
                throw;
1010
            }
1011
            catch (Exception ex)
1012
            {
1013
                Log.Error("Unexpected error while uploading file", ex);
1014
                throw;
1015
            }
1016

    
1017
        }
1018

    
1019
        private bool IsDeletedFile(CloudAction action)
1020
        {            
1021
            var key = GetFileKey(action.CloudFile);
1022
            DateTime entryDate;
1023
            if (_deletedFiles.TryGetValue(key, out entryDate))
1024
            {
1025
                //If the delete entry was created after this action, abort the action
1026
                if (entryDate > action.Created)
1027
                    return true;
1028
                //Otherwise, remove the stale entry 
1029
                _deletedFiles.TryRemove(key, out entryDate);
1030
            }
1031
            return false;
1032
        }
1033

    
1034
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1035
        {
1036
            var response = exc.Response as HttpWebResponse;
1037
            if (response == null)
1038
                throw exc;
1039
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1040
            {
1041
                Log.Error("Not allowed to upload file", exc);
1042
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1043
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1044
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1045
                return true;
1046
            }
1047
            return false;
1048
        }
1049

    
1050
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1051
        {
1052
            if (accountInfo == null)
1053
                throw new ArgumentNullException("accountInfo");
1054
            if (cloudFile==null)
1055
                throw new ArgumentNullException("cloudFile");
1056
            if (fileInfo == null)
1057
                throw new ArgumentNullException("fileInfo");
1058
            if (String.IsNullOrWhiteSpace(url))
1059
                throw new ArgumentNullException(url);
1060
            if (treeHash==null)
1061
                throw new ArgumentNullException("treeHash");
1062
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1063
                throw new ArgumentException("Invalid container","cloudFile");
1064
            Contract.EndContractBlock();
1065

    
1066
            var fullFileName = fileInfo.GetProperCapitalization();
1067

    
1068
            var account = cloudFile.Account ?? accountInfo.UserName;
1069
            var container = cloudFile.Container ;
1070

    
1071
            var client = new CloudFilesClient(accountInfo);
1072
            //Send the hashmap to the server            
1073
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1074
            //If the server returns no missing hashes, we are done
1075
            while (missingHashes.Count > 0)
1076
            {
1077

    
1078
                var buffer = new byte[accountInfo.BlockSize];
1079
                foreach (var missingHash in missingHashes)
1080
                {
1081
                    //Find the proper block
1082
                    var blockIndex = treeHash.HashDictionary[missingHash];
1083
                    var offset = blockIndex*accountInfo.BlockSize;
1084

    
1085
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1086

    
1087
                    try
1088
                    {
1089
                        //And upload the block                
1090
                        await client.PostBlock(account, container, buffer, 0, read);
1091
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1092
                    }
1093
                    catch (Exception exc)
1094
                    {
1095
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1096
                    }
1097

    
1098
                }
1099

    
1100
                //Repeat until there are no more missing hashes                
1101
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1102
            }
1103
        }
1104

    
1105

    
1106
        public void AddAccount(AccountInfo accountInfo)
1107
        {            
1108
            if (!_accounts.Contains(accountInfo))
1109
                _accounts.Add(accountInfo);
1110
        }
1111
    }
1112

    
1113
   
1114

    
1115

    
1116
}