Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 9d6d2f6e

History | View | Annotate | Download (50.6 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
        public void Start()
80
        {
81

    
82
            _agent = Agent<CloudAction>.Start(inbox =>
83
            {
84
                Action loop = null;
85
                loop = () =>
86
                {
87
                    _pauseAgent.Wait();
88
                    var message = inbox.Receive();
89
                    var process=message.Then(Process,inbox.CancellationToken);
90
                    inbox.LoopAsync(process, loop);
91
                };
92
                loop();
93
            });
94

    
95
            _deleteAgent = new ActionBlock<CloudDeleteAction>(message =>ProcessDelete(message),new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism=4});
96
            /*
97
                Action loop = null;
98
                loop = () =>
99
                            {
100
                                var message = inbox.Receive();
101
                                var process = message.Then(ProcessDelete,inbox.CancellationToken);
102
                                inbox.LoopAsync(process, loop);
103
                            };
104
                loop();
105
*/
106

    
107
        }
108

    
109
        private async Task Process(CloudAction action)
110
        {
111
            if (action == null)
112
                throw new ArgumentNullException("action");
113
            if (action.AccountInfo==null)
114
                throw new ArgumentException("The action.AccountInfo is empty","action");
115
            Contract.EndContractBlock();
116

    
117
            var accountInfo = action.AccountInfo;
118

    
119
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
120
            {                
121
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
122

    
123
                var cloudFile = action.CloudFile;
124
                var downloadPath = action.GetDownloadPath();
125

    
126
                try
127
                {
128

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

    
197
                    _agent.Post(action);
198
                }                
199
            }
200
        }
201

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

    
222
            var accountInfo = action.AccountInfo;
223

    
224
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
225
            {                
226
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
227

    
228
                var cloudFile = action.CloudFile;
229

    
230
                try
231
                {
232
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
233
                    //agent
234
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
235
                    {
236

    
237
                        //Add the file URL to the deleted files list
238
                        var key = GetFileKey(action.CloudFile);
239
                        _deletedFiles[key] = DateTime.Now;
240

    
241
                        _pauseAgent.Reset();
242
                        // and then delete the file from the server
243
                        DeleteCloudFile(accountInfo, cloudFile);
244

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

    
276
                    _deleteAgent.Post(action);
277
                }
278
                finally
279
                {
280
                    if (_deleteAgent.InputCount == 0)
281
                        _pauseAgent.Set();
282

    
283
                }
284
            }
285
        }
286

    
287
        private static string GetFileKey(ObjectInfo info)
288
        {
289
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
290
            return key;
291
        }
292

    
293
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
294
        {
295
            if (accountInfo == null)
296
                throw new ArgumentNullException("accountInfo");
297
            if (action==null)
298
                throw new ArgumentNullException("action");
299
            if (action.LocalFile==null)
300
                throw new ArgumentException("The action's local file is not specified","action");
301
            if (!Path.IsPathRooted(action.LocalFile.FullName))
302
                throw new ArgumentException("The action's local file path must be absolute","action");
303
            if (action.CloudFile== null)
304
                throw new ArgumentException("The action's cloud file is not specified", "action");
305
            Contract.EndContractBlock();
306

    
307
            var localFile = action.LocalFile;
308
            var cloudFile = action.CloudFile;
309
            var downloadPath=action.LocalFile.GetProperCapitalization();
310

    
311
            var cloudHash = cloudFile.Hash.ToLower();
312
            var localHash = action.LocalHash.Value.ToLower();
313
            var topHash = action.TopHash.Value.ToLower();
314

    
315
            //Not enough to compare only the local hashes, also have to compare the tophashes
316
            
317
            //If any of the hashes match, we are done
318
            if ((cloudHash == localHash || cloudHash == topHash))
319
            {
320
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
321
                return;
322
            }
323

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

    
353
                        //In both cases we must mark the file as in conflict
354
                        ReportConflict(downloadPath);
355
                        break;
356
                    default:
357
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
358
                        ReportConflict(downloadPath);
359
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
360
                                       downloadPath, action.CloudFile.Name);
361
                        break;
362
                }
363
            }
364
        }
365

    
366
        private void ReportConflict(string downloadPath)
367
        {
368
            if (String.IsNullOrWhiteSpace(downloadPath))
369
                throw new ArgumentNullException("downloadPath");
370
            Contract.EndContractBlock();
371

    
372
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
373
            var message = String.Format("Conflict detected for file {0}", downloadPath);
374
            Log.Warn(message);
375
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
376
        }
377

    
378
        public void Post(CloudAction cloudAction)
379
        {
380
            if (cloudAction == null)
381
                throw new ArgumentNullException("cloudAction");
382
            if (cloudAction.AccountInfo==null)
383
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
384
            Contract.EndContractBlock();
385

    
386
            _pauseAgent.Wait();
387

    
388
            //If the action targets a local file, add a treehash calculation
389
            if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
390
            {
391
                var accountInfo = cloudAction.AccountInfo;
392
                var localFile = (FileInfo) cloudAction.LocalFile;
393
                if (localFile.Length > accountInfo.BlockSize)
394
                    cloudAction.TopHash =
395
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
396
                                                                                accountInfo.BlockSize,
397
                                                                                accountInfo.BlockHash).Result
398
                                                    .TopHash.ToHashString());
399
                else
400
                {
401
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
402
                }
403
            }
404
            else
405
            {
406
                //The hash for a directory is the empty string
407
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
408
            }
409
            
410
            if (cloudAction is CloudDeleteAction)
411
                _deleteAgent.Post((CloudDeleteAction)cloudAction);
412
            else
413
                _agent.Post(cloudAction);
414
        }
415

    
416
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
417
        {
418
            public bool Equals(ObjectInfo x, ObjectInfo y)
419
            {
420
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
421
            }
422

    
423
            public int GetHashCode(ObjectInfo obj)
424
            {
425
                return obj.Name.ToLower().GetHashCode();
426
            }
427
        }*/
428

    
429
        
430

    
431
        //Remote files are polled periodically. Any changes are processed
432
        public async Task ProcessRemoteFiles(DateTime? since = null)
433
        {            
434
            await TaskEx.Delay(TimeSpan.FromSeconds(10),_agent.CancellationToken);
435

    
436
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
437
            {
438

    
439
                try
440
                {
441
                    //Next time we will check for all changes since the current check minus 1 second
442
                    //This is done to ensure there are no discrepancies due to clock differences
443
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
444

    
445
                    var tasks = from accountInfo in _accounts
446
                                select ProcessAccountFiles(accountInfo, since);
447

    
448
                    await TaskEx.WhenAll(tasks.ToList());
449

    
450
                    ProcessRemoteFiles(nextSince);
451
                }
452
                catch (Exception ex)
453
                {
454
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
455
                    //In case of failure retry with the same parameter
456
                    ProcessRemoteFiles(since);
457
                }
458
                
459

    
460
            }
461
        }
462

    
463
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
464
        {   
465
            if (accountInfo==null)
466
                throw new ArgumentNullException("accountInfo");
467
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
468
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
469
            Contract.EndContractBlock();
470

    
471
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
472
            {
473
                Log.Info("Scheduled");
474
                var client=new CloudFilesClient(accountInfo);
475

    
476
                var containers = client.ListContainers(accountInfo.UserName);
477
                
478
                CreateContainerFolders(accountInfo, containers);
479

    
480
                try
481
                {
482
                    _pauseAgent.Wait();
483
                    //Get the list of server objects changed since the last check
484
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
485
                    var listObjects = from container in containers
486
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
487
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
488

    
489

    
490
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
491

    
492
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
493
                    {
494
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
495

    
496
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
497
                        var remoteObjects = from objectList in listTasks
498
                                            where (string) objectList.AsyncState != "trash"
499
                                            from obj in objectList.Result
500
                                            select obj;
501

    
502
                        var trashObjects = dict["trash"].Result;
503
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
504

    
505
                        //Items with the same name, hash may be both in the container and the trash
506
                        //Don't delete items that exist in the container
507
                        var realTrash = from trash in trashObjects
508
                                        where
509
                                            !remoteObjects.Any(
510
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
511
                                        select trash;
512
                        ProcessDeletedFiles(accountInfo, realTrash);
513

    
514

    
515
                        var remote = from info in remoteObjects
516
                                     //.Union(sharedObjects)
517
                                     let name = info.Name
518
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
519
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
520
                                                            StringComparison.InvariantCultureIgnoreCase)
521
                                     select info;
522

    
523
                        //Create a list of actions from the remote files
524
                        var allActions = ObjectsToActions(accountInfo, remote);
525

    
526
                        //And remove those that are already being processed by the agent
527
                        var distinctActions = allActions
528
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
529
                            .ToList();
530

    
531
                        //Queue all the actions
532
                        foreach (var message in distinctActions)
533
                        {
534
                            Post(message);
535
                        }
536

    
537
                        Log.Info("[LISTENER] End Processing");
538
                    }
539
                }
540
                catch (Exception ex)
541
                {
542
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
543
                    return;
544
                }
545

    
546
                Log.Info("[LISTENER] Finished");
547

    
548
            }
549
        }
550

    
551
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
552
        {
553
            var containerPaths = from container in containers
554
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
555
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
556
                                 select containerPath;
557

    
558
            foreach (var path in containerPaths)
559
            {
560
                Directory.CreateDirectory(path);
561
            }
562
        }
563

    
564
        //Creates an appropriate action for each server file
565
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
566
        {
567
            if (remote==null)
568
                throw new ArgumentNullException();
569
            Contract.EndContractBlock();
570
            var fileAgent = GetFileAgent(accountInfo);
571

    
572
            //In order to avoid multiple iterations over the files, we iterate only once
573
            //over the remote files
574
            foreach (var objectInfo in remote)
575
            {
576
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
577
                //and remove any matching objects from the list, adding them to the commonObjects list
578
                
579
                if (fileAgent.Exists(relativePath))
580
                {
581
                    //If a directory object already exists, we don't need to perform any other action                    
582
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
583
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
584
                        continue;
585
                    using (new SessionScope(FlushAction.Never))
586
                    {
587
                        var state =  StatusKeeper.GetStateByFilePath(localFile.FullName);
588
                        //FileState.FindByFilePath(localFile.FullName);
589
                        //Common files should be checked on a per-case basis to detect differences, which is newer
590

    
591
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
592
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
593
                                                     accountInfo.BlockHash);
594
                    }
595
                }
596
                else
597
                {
598
                    //If there is no match we add them to the localFiles list
599
                    //but only if the file is not marked for deletion
600
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
601
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
602
                    if (fileStatus != FileStatus.Deleted)
603
                    {
604
                        //Remote files should be downloaded
605
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
606
                    }
607
                }
608
            }            
609
        }
610

    
611
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
612
        {
613
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
614
        }
615

    
616
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
617
        {
618
            var fileAgent = GetFileAgent(accountInfo);
619
            foreach (var trashObject in trashObjects)
620
            {
621
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
622
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
623
                //deleting a file from a different container
624
                var relativePath = Path.Combine("pithos", barePath);
625
                fileAgent.Delete(relativePath);                                
626
            }
627
        }
628

    
629

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

    
660
            
661
            //The local file is already renamed
662
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
663

    
664

    
665
            var account = action.CloudFile.Account ?? accountInfo.UserName;
666
            var container = action.CloudFile.Container;
667
            
668
            var client = new CloudFilesClient(accountInfo);
669
            //TODO: What code is returned when the source file doesn't exist?
670
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
671

    
672
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
673
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
674
            NativeMethods.RaiseChangeNotification(newFilePath);
675
        }
676

    
677
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
678
        {
679
            if (accountInfo == null)
680
                throw new ArgumentNullException("accountInfo");
681
            if (cloudFile==null)
682
                throw new ArgumentNullException("cloudFile");
683

    
684
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
685
                throw new ArgumentException("Invalid container", "cloudFile");
686
            Contract.EndContractBlock();
687
            
688
            var fileAgent = GetFileAgent(accountInfo);
689

    
690
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
691
            {
692
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
693
                var info = fileAgent.GetFileSystemInfo(fileName);                
694
                var fullPath = info.FullName.ToLower();
695

    
696
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
697

    
698
                var account = cloudFile.Account ?? accountInfo.UserName;
699
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
700

    
701
                var client = new CloudFilesClient(accountInfo);
702
                client.DeleteObject(account, container, cloudFile.Name);
703

    
704
                StatusKeeper.ClearFileStatus(fullPath);
705
            }
706
        }
707

    
708
        //Download a file.
709
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
710
        {
711
            if (accountInfo == null)
712
                throw new ArgumentNullException("accountInfo");
713
            if (cloudFile == null)
714
                throw new ArgumentNullException("cloudFile");
715
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
716
                throw new ArgumentNullException("cloudFile");
717
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
718
                throw new ArgumentNullException("cloudFile");
719
            if (String.IsNullOrWhiteSpace(filePath))
720
                throw new ArgumentNullException("filePath");
721
            if (!Path.IsPathRooted(filePath))
722
                throw new ArgumentException("The filePath must be rooted", "filePath");
723
            Contract.EndContractBlock();
724

    
725
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
726
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
727

    
728
            var url = relativeUrl.ToString();
729
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
730
                return;
731

    
732

    
733
            //Are we already downloading or uploading the file? 
734
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
735
            {
736
                if (gate.Failed)
737
                    return;
738
                //The file's hashmap will be stored in the same location with the extension .hashmap
739
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
740
                
741
                var client = new CloudFilesClient(accountInfo);
742
                var account = cloudFile.Account;
743
                var container = cloudFile.Container;
744

    
745
                if (cloudFile.Content_Type == @"application/directory")
746
                {
747
                    if (!Directory.Exists(localPath))
748
                        Directory.CreateDirectory(localPath);
749
                }
750
                else
751
                {
752
                    //Retrieve the hashmap from the server
753
                    var serverHash = await client.GetHashMap(account, container, url);
754
                    //If it's a small file
755
                    if (serverHash.Hashes.Count == 1)
756
                        //Download it in one go
757
                        await
758
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
759
                        //Otherwise download it block by block
760
                    else
761
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
762

    
763
                    if (cloudFile.AllowedTo == "read")
764
                    {
765
                        var attributes = File.GetAttributes(localPath);
766
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
767
                    }
768
                }
769

    
770
                //Now we can store the object's metadata without worrying about ghost status entries
771
                StatusKeeper.StoreInfo(localPath, cloudFile);
772
                
773
            }
774
        }
775

    
776
        //Download a small file with a single GET operation
777
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
778
        {
779
            if (client == null)
780
                throw new ArgumentNullException("client");
781
            if (cloudFile==null)
782
                throw new ArgumentNullException("cloudFile");
783
            if (relativeUrl == null)
784
                throw new ArgumentNullException("relativeUrl");
785
            if (String.IsNullOrWhiteSpace(filePath))
786
                throw new ArgumentNullException("filePath");
787
            if (!Path.IsPathRooted(filePath))
788
                throw new ArgumentException("The localPath must be rooted", "filePath");
789
            Contract.EndContractBlock();
790

    
791
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
792
            //If the file already exists
793
            if (File.Exists(localPath))
794
            {
795
                //First check with MD5 as this is a small file
796
                var localMD5 = Signature.CalculateMD5(localPath);
797
                var cloudHash=serverHash.TopHash.ToHashString();
798
                if (localMD5==cloudHash)
799
                    return;
800
                //Then check with a treehash
801
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
802
                var localHash = localTreeHash.TopHash.ToHashString();
803
                if (localHash==cloudHash)
804
                    return;
805
            }
806

    
807
            var fileAgent = GetFileAgent(accountInfo);
808
            //Calculate the relative file path for the new file
809
            var relativePath = relativeUrl.RelativeUriToFilePath();
810
            //The file will be stored in a temporary location while downloading with an extension .download
811
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
812
            //Make sure the target folder exists. DownloadFileTask will not create the folder
813
            var tempFolder = Path.GetDirectoryName(tempPath);
814
            if (!Directory.Exists(tempFolder))
815
                Directory.CreateDirectory(tempFolder);
816

    
817
            //Download the object to the temporary location
818
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
819

    
820
            //Create the local folder if it doesn't exist (necessary for shared objects)
821
            var localFolder = Path.GetDirectoryName(localPath);
822
            if (!Directory.Exists(localFolder))
823
                Directory.CreateDirectory(localFolder);            
824
            //And move it to its actual location once downloading is finished
825
            if (File.Exists(localPath))
826
                File.Replace(tempPath,localPath,null,true);
827
            else
828
                File.Move(tempPath,localPath);
829
            //Notify listeners that a local file has changed
830
            StatusNotification.NotifyChangedFile(localPath);
831

    
832
                       
833
        }
834

    
835
        //Download a file asynchronously using blocks
836
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
837
        {
838
            if (client == null)
839
                throw new ArgumentNullException("client");
840
            if (cloudFile == null)
841
                throw new ArgumentNullException("cloudFile");
842
            if (relativeUrl == null)
843
                throw new ArgumentNullException("relativeUrl");
844
            if (String.IsNullOrWhiteSpace(filePath))
845
                throw new ArgumentNullException("filePath");
846
            if (!Path.IsPathRooted(filePath))
847
                throw new ArgumentException("The filePath must be rooted", "filePath");
848
            if (serverHash == null)
849
                throw new ArgumentNullException("serverHash");
850
            Contract.EndContractBlock();
851
            
852
           var fileAgent = GetFileAgent(accountInfo);
853
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
854
            
855
            //Calculate the relative file path for the new file
856
            var relativePath = relativeUrl.RelativeUriToFilePath();
857
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
858

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

    
888
                    //and store it
889
                    blockUpdater.StoreBlock(i, block);
890

    
891

    
892
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
893
                }
894
            }
895

    
896
            //Want to avoid notifications if no changes were made
897
            var hasChanges = blockUpdater.HasBlocks;
898
            blockUpdater.Commit();
899
            
900
            if (hasChanges)
901
                //Notify listeners that a local file has changed
902
                StatusNotification.NotifyChangedFile(localPath);
903

    
904
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
905
        }
906

    
907

    
908
        private async Task UploadCloudFile(CloudAction action)
909
        {
910
            if (action == null)
911
                throw new ArgumentNullException("action");           
912
            Contract.EndContractBlock();
913

    
914
            try
915
            {
916
                var accountInfo = action.AccountInfo;
917

    
918
                var fileInfo = action.LocalFile;
919

    
920
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
921
                    return;
922
                
923
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
924
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
925
                {
926
                    var parts = relativePath.Split('\\');
927
                    var accountName = parts[1];
928
                    var oldName = accountInfo.UserName;
929
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
930
                    var nameIndex = absoluteUri.IndexOf(oldName);
931
                    var root = absoluteUri.Substring(0, nameIndex);
932

    
933
                    accountInfo = new AccountInfo
934
                    {
935
                        UserName = accountName,
936
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
937
                        StorageUri = new Uri(root + accountName),
938
                        BlockHash = accountInfo.BlockHash,
939
                        BlockSize = accountInfo.BlockSize,
940
                        Token = accountInfo.Token
941
                    };
942
                }
943

    
944

    
945
                var fullFileName = fileInfo.GetProperCapitalization();
946
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
947
                {
948
                    //Abort if the file is already being uploaded or downloaded
949
                    if (gate.Failed)
950
                        return;
951

    
952
                    var cloudFile = action.CloudFile;
953
                    var account = cloudFile.Account ?? accountInfo.UserName;
954

    
955
                    var client = new CloudFilesClient(accountInfo);                    
956
                    //Even if GetObjectInfo times out, we can proceed with the upload            
957
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
958

    
959
                    //If this is a read-only file, do not upload changes
960
                    if (info.AllowedTo == "read")
961
                        return;
962
                    
963
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
964
                    if (fileInfo is DirectoryInfo)
965
                    {
966
                        //If the directory doesn't exist the Hash property will be empty
967
                        if (String.IsNullOrWhiteSpace(info.Hash))
968
                            //Go on and create the directory
969
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
970
                    }
971
                    else
972
                    {
973

    
974
                        var cloudHash = info.Hash.ToLower();
975

    
976
                        var hash = action.LocalHash.Value;
977
                        var topHash = action.TopHash.Value;
978

    
979
                        //If the file hashes match, abort the upload
980
                        if (hash == cloudHash || topHash == cloudHash)
981
                        {
982
                            //but store any metadata changes 
983
                            StatusKeeper.StoreInfo(fullFileName, info);
984
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
985
                            return;
986
                        }
987

    
988

    
989
                        //Mark the file as modified while we upload it
990
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
991
                        //And then upload it
992

    
993
                        //Upload even small files using the Hashmap. The server may already contain
994
                        //the relevant block
995

    
996
                        //First, calculate the tree hash
997
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
998
                                                                              accountInfo.BlockHash);
999

    
1000
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
1001
                    }
1002
                    //If everything succeeds, change the file and overlay status to normal
1003
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1004
                }
1005
                //Notify the Shell to update the overlays
1006
                NativeMethods.RaiseChangeNotification(fullFileName);
1007
                StatusNotification.NotifyChangedFile(fullFileName);
1008
            }
1009
            catch (AggregateException ex)
1010
            {
1011
                var exc = ex.InnerException as WebException;
1012
                if (exc == null)
1013
                    throw ex.InnerException;
1014
                if (HandleUploadWebException(action, exc)) 
1015
                    return;
1016
                throw;
1017
            }
1018
            catch (WebException ex)
1019
            {
1020
                if (HandleUploadWebException(action, ex))
1021
                    return;
1022
                throw;
1023
            }
1024
            catch (Exception ex)
1025
            {
1026
                Log.Error("Unexpected error while uploading file", ex);
1027
                throw;
1028
            }
1029

    
1030
        }
1031

    
1032
        private bool IsDeletedFile(CloudAction action)
1033
        {            
1034
            var key = GetFileKey(action.CloudFile);
1035
            DateTime entryDate;
1036
            if (_deletedFiles.TryGetValue(key, out entryDate))
1037
            {
1038
                //If the delete entry was created after this action, abort the action
1039
                if (entryDate > action.Created)
1040
                    return true;
1041
                //Otherwise, remove the stale entry 
1042
                _deletedFiles.TryRemove(key, out entryDate);
1043
            }
1044
            return false;
1045
        }
1046

    
1047
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1048
        {
1049
            var response = exc.Response as HttpWebResponse;
1050
            if (response == null)
1051
                throw exc;
1052
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1053
            {
1054
                Log.Error("Not allowed to upload file", exc);
1055
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1056
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1057
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1058
                return true;
1059
            }
1060
            return false;
1061
        }
1062

    
1063
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1064
        {
1065
            if (accountInfo == null)
1066
                throw new ArgumentNullException("accountInfo");
1067
            if (cloudFile==null)
1068
                throw new ArgumentNullException("cloudFile");
1069
            if (fileInfo == null)
1070
                throw new ArgumentNullException("fileInfo");
1071
            if (String.IsNullOrWhiteSpace(url))
1072
                throw new ArgumentNullException(url);
1073
            if (treeHash==null)
1074
                throw new ArgumentNullException("treeHash");
1075
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1076
                throw new ArgumentException("Invalid container","cloudFile");
1077
            Contract.EndContractBlock();
1078

    
1079
            var fullFileName = fileInfo.GetProperCapitalization();
1080

    
1081
            var account = cloudFile.Account ?? accountInfo.UserName;
1082
            var container = cloudFile.Container ;
1083

    
1084
            var client = new CloudFilesClient(accountInfo);
1085
            //Send the hashmap to the server            
1086
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1087
            //If the server returns no missing hashes, we are done
1088
            while (missingHashes.Count > 0)
1089
            {
1090

    
1091
                var buffer = new byte[accountInfo.BlockSize];
1092
                foreach (var missingHash in missingHashes)
1093
                {
1094
                    //Find the proper block
1095
                    var blockIndex = treeHash.HashDictionary[missingHash];
1096
                    var offset = blockIndex*accountInfo.BlockSize;
1097

    
1098
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1099

    
1100
                    try
1101
                    {
1102
                        //And upload the block                
1103
                        await client.PostBlock(account, container, buffer, 0, read);
1104
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1105
                    }
1106
                    catch (Exception exc)
1107
                    {
1108
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1109
                    }
1110

    
1111
                }
1112

    
1113
                //Repeat until there are no more missing hashes                
1114
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1115
            }
1116
        }
1117

    
1118

    
1119
        public void AddAccount(AccountInfo accountInfo)
1120
        {            
1121
            if (!_accounts.Contains(accountInfo))
1122
                _accounts.Add(accountInfo);
1123
        }
1124
    }
1125

    
1126
   
1127

    
1128

    
1129
}