Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ f3d080df

History | View | Annotate | Download (48.5 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 Pithos.Interfaces;
49
using Pithos.Network;
50
using log4net;
51

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

    
60
        //A separate agent is used to execute delete actions immediatelly;
61
        private Agent<CloudDeleteAction> _deleteAgent;
62

    
63

    
64
        [Import]
65
        public IStatusKeeper StatusKeeper { get; set; }
66
        
67
        public IStatusNotification StatusNotification { get; set; }
68

    
69
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
70

    
71
        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
72

    
73
        public void Start()
74
        {
75

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

    
88
            _deleteAgent = Agent<CloudDeleteAction>.Start(inbox =>
89
            {
90
                Action loop = null;
91
                loop = () =>
92
                            {
93
                                var message = inbox.Receive();
94
                                var process = message.Then(ProcessDelete,inbox.CancellationToken);
95
                                inbox.LoopAsync(process, loop);
96
                            };
97
                loop();
98

    
99
            });
100
        }
101

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

    
110
            var accountInfo = action.AccountInfo;
111

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

    
116
                var cloudFile = action.CloudFile;
117
                var downloadPath = action.GetDownloadPath();
118

    
119
                try
120
                {
121

    
122
                    switch (action.Action)
123
                    {
124
                        case CloudActionType.UploadUnconditional:
125
                            await UploadCloudFile(action);
126
                            break;
127
                        case CloudActionType.DownloadUnconditional:
128

    
129
                            await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
130
                            break;
131
                        case CloudActionType.DeleteCloud:
132
                            //Redirect deletes to the delete agent 
133
                            _deleteAgent.Post((CloudDeleteAction)action);
134
                            break;
135
                        case CloudActionType.RenameCloud:
136
                            var moveAction = (CloudMoveAction)action;
137
                            RenameCloudFile(accountInfo, moveAction);
138
                            break;
139
                        case CloudActionType.MustSynch:
140
                            if (!File.Exists(downloadPath) && !Directory.Exists(downloadPath))
141
                            {
142
                                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
143
                            }
144
                            else
145
                            {
146
                                await SyncFiles(accountInfo, action);
147
                            }
148
                            break;
149
                    }
150
                    Log.InfoFormat("[ACTION] End Processing {0}:{1}->{2}", action.Action, action.LocalFile,
151
                                           action.CloudFile.Name);
152
                }
153
                catch (WebException exc)
154
                {
155
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
156
                }
157
                catch (OperationCanceledException)
158
                {
159
                    throw;
160
                }
161
                catch (DirectoryNotFoundException)
162
                {
163
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
164
                        action.Action, action.LocalFile, action.CloudFile);
165
                    //Post a delete action for the missing file
166
                    Post(new CloudDeleteAction(action));                    
167
                }
168
                catch (FileNotFoundException)
169
                {
170
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
171
                        action.Action, action.LocalFile, action.CloudFile);
172
                    //Post a delete action for the missing file
173
                    Post(new CloudDeleteAction(action));
174
                }
175
                catch (Exception exc)
176
                {
177
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
178
                                     action.Action, action.LocalFile, action.CloudFile, exc);
179

    
180
                    _agent.Post(action);
181
                }                
182
            }
183
        }
184

    
185
        /// <summary>
186
        /// Processes cloud delete actions
187
        /// </summary>
188
        /// <param name="action">The delete action to execute</param>
189
        /// <returns></returns>
190
        /// <remarks>
191
        /// When a file/folder is deleted locally, we must delete it ASAP from the server and block any download
192
        /// operations that may be in progress.
193
        /// <para>
194
        /// A separate agent is used to process deletes because the main agent may be busy with a long operation.
195
        /// </para>
196
        /// </remarks>
197
        private async Task ProcessDelete(CloudDeleteAction action)
198
        {
199
            if (action == null)
200
                throw new ArgumentNullException("action");
201
            if (action.AccountInfo==null)
202
                throw new ArgumentException("The action.AccountInfo is empty","action");
203
            Contract.EndContractBlock();
204

    
205
            var accountInfo = action.AccountInfo;
206

    
207
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
208
            {                
209
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
210

    
211
                var cloudFile = action.CloudFile;
212

    
213
                try
214
                {
215
                    //Acquire a lock on the deleted file to prevent uploading/downloading operations from the normal
216
                    //agent
217
                    using (var gate = NetworkGate.Acquire(action.LocalFile.FullName, NetworkOperation.Deleting))
218
                    {
219
                        // Remove any related actions from the normal agent
220
                        _agent.Remove(queuedAction =>
221
                                      queuedAction.CloudFile.Container == action.CloudFile.Container &&
222
                                      queuedAction.CloudFile.Name == action.CloudFile.Name);
223
                        // and then delete the file from the server
224
                        DeleteCloudFile(accountInfo, cloudFile);
225
                        Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
226
                                       action.CloudFile.Name);
227
                    }
228
                }
229
                catch (WebException exc)
230
                {
231
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
232
                }
233
                catch (OperationCanceledException)
234
                {
235
                    throw;
236
                }
237
                catch (DirectoryNotFoundException)
238
                {
239
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
240
                        action.Action, action.LocalFile, action.CloudFile);
241
                    //Repost a delete action for the missing file
242
                    _deleteAgent.Post(action);                    
243
                }
244
                catch (FileNotFoundException)
245
                {
246
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
247
                        action.Action, action.LocalFile, action.CloudFile);
248
                    //Post a delete action for the missing file
249
                    _deleteAgent.Post(action);
250
                }
251
                catch (Exception exc)
252
                {
253
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
254
                                     action.Action, action.LocalFile, action.CloudFile, exc);
255

    
256
                    _deleteAgent.Post(action);
257
                }                
258
            }
259
        }
260

    
261
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
262
        {
263
            if (accountInfo == null)
264
                throw new ArgumentNullException("accountInfo");
265
            if (action==null)
266
                throw new ArgumentNullException("action");
267
            if (action.LocalFile==null)
268
                throw new ArgumentException("The action's local file is not specified","action");
269
            if (!Path.IsPathRooted(action.LocalFile.FullName))
270
                throw new ArgumentException("The action's local file path must be absolute","action");
271
            if (action.CloudFile== null)
272
                throw new ArgumentException("The action's cloud file is not specified", "action");
273
            Contract.EndContractBlock();
274

    
275
            var localFile = action.LocalFile;
276
            var cloudFile = action.CloudFile;
277
            var downloadPath=action.LocalFile.GetProperCapitalization();
278

    
279
            var cloudHash = cloudFile.Hash.ToLower();
280
            var localHash = action.LocalHash.Value.ToLower();
281
            var topHash = action.TopHash.Value.ToLower();
282

    
283
            //Not enough to compare only the local hashes, also have to compare the tophashes
284
            
285
            //If any of the hashes match, we are done
286
            if ((cloudHash == localHash || cloudHash == topHash))
287
            {
288
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
289
                return;
290
            }
291

    
292
            //The hashes DON'T match. We need to sync
293
            var lastLocalTime = localFile.LastWriteTime;
294
            var lastUpTime = cloudFile.Last_Modified;
295
            
296
            //If the local file is newer upload it
297
            if (lastUpTime <= lastLocalTime)
298
            {
299
                //It probably means it was changed while the app was down                        
300
                UploadCloudFile(action);
301
            }
302
            else
303
            {
304
                //It the cloud file has a later date, it was modified by another user or computer.
305
                //We need to check the local file's status                
306
                var status = StatusKeeper.GetFileStatus(downloadPath);
307
                switch (status)
308
                {
309
                    case FileStatus.Unchanged:                        
310
                        //If the local file's status is Unchanged, we can go on and download the newer cloud file
311
                        await DownloadCloudFile(accountInfo,cloudFile,downloadPath);
312
                        break;
313
                    case FileStatus.Modified:
314
                        //If the local file is Modified, we may have a conflict. In this case we should mark the file as Conflict
315
                        //We can't ensure that a file modified online since the last time will appear as Modified, unless we 
316
                        //index all files before we start listening.                       
317
                    case FileStatus.Created:
318
                        //If the local file is Created, it means that the local and cloud files aren't related,
319
                        // yet they have the same name.
320

    
321
                        //In both cases we must mark the file as in conflict
322
                        ReportConflict(downloadPath);
323
                        break;
324
                    default:
325
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
326
                        ReportConflict(downloadPath);
327
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
328
                                       downloadPath, action.CloudFile.Name);
329
                        break;
330
                }
331
            }
332
        }
333

    
334
        private void ReportConflict(string downloadPath)
335
        {
336
            if (String.IsNullOrWhiteSpace(downloadPath))
337
                throw new ArgumentNullException("downloadPath");
338
            Contract.EndContractBlock();
339

    
340
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
341
            var message = String.Format("Conflict detected for file {0}", downloadPath);
342
            Log.Warn(message);
343
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
344
        }
345

    
346
        public void Post(CloudAction cloudAction)
347
        {
348
            if (cloudAction == null)
349
                throw new ArgumentNullException("cloudAction");
350
            if (cloudAction.AccountInfo==null)
351
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
352
            Contract.EndContractBlock();
353

    
354
            //If the action targets a local file, add a treehash calculation
355
            if (cloudAction.LocalFile as FileInfo != null)
356
            {
357
                var accountInfo = cloudAction.AccountInfo;
358
                var localFile = (FileInfo) cloudAction.LocalFile;
359
                if (localFile.Length > accountInfo.BlockSize)
360
                    cloudAction.TopHash =
361
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
362
                                                                                accountInfo.BlockSize,
363
                                                                                accountInfo.BlockHash).Result
364
                                                    .TopHash.ToHashString());
365
                else
366
                {
367
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
368
                }
369
            }
370
            else
371
            {
372
                //The hash for a directory is the empty string
373
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
374
            }
375
            
376
            if (cloudAction is CloudDeleteAction)
377
                _deleteAgent.Post((CloudDeleteAction)cloudAction);
378
            else
379
                _agent.Post(cloudAction);
380
        }
381

    
382
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
383
        {
384
            public bool Equals(ObjectInfo x, ObjectInfo y)
385
            {
386
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
387
            }
388

    
389
            public int GetHashCode(ObjectInfo obj)
390
            {
391
                return obj.Name.ToLower().GetHashCode();
392
            }
393
        }*/
394

    
395
        
396

    
397
        //Remote files are polled periodically. Any changes are processed
398
        public async Task ProcessRemoteFiles(DateTime? since = null)
399
        {            
400
            await TaskEx.Delay(TimeSpan.FromSeconds(10),_agent.CancellationToken);
401

    
402
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
403
            {
404

    
405
                try
406
                {
407
                    //Next time we will check for all changes since the current check minus 1 second
408
                    //This is done to ensure there are no discrepancies due to clock differences
409
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
410

    
411
                    var tasks = from accountInfo in _accounts
412
                                select ProcessAccountFiles(accountInfo, since);
413

    
414
                    await TaskEx.WhenAll(tasks.ToList());
415

    
416
                    ProcessRemoteFiles(nextSince);
417
                }
418
                catch (Exception ex)
419
                {
420
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
421
                    //In case of failure retry with the same parameter
422
                    ProcessRemoteFiles(since);
423
                }
424
                
425

    
426
            }
427
        }
428

    
429
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
430
        {   
431
            if (accountInfo==null)
432
                throw new ArgumentNullException("accountInfo");
433
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
434
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
435
            Contract.EndContractBlock();
436

    
437
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
438
            {
439
                Log.Info("Scheduled");
440
                var client=new CloudFilesClient(accountInfo);
441

    
442
                var containers = client.ListContainers(accountInfo.UserName);
443
                
444
                CreateContainerFolders(accountInfo, containers);
445

    
446
                try
447
                {
448
                    
449
                    //Get the list of server objects changed since the last check
450
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
451
                    var listObjects = from container in containers
452
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
453
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
454

    
455

    
456
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
457

    
458
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
459
                    {
460
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
461

    
462
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
463
                        var remoteObjects = from objectList in listTasks
464
                                            where (string) objectList.AsyncState != "trash"
465
                                            from obj in objectList.Result
466
                                            select obj;
467

    
468
                        var trashObjects = dict["trash"].Result;
469
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
470

    
471
                        //Items with the same name, hash may be both in the container and the trash
472
                        //Don't delete items that exist in the container
473
                        var realTrash = from trash in trashObjects
474
                                        where
475
                                            !remoteObjects.Any(
476
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
477
                                        select trash;
478
                        ProcessDeletedFiles(accountInfo, realTrash);
479

    
480

    
481
                        var remote = from info in remoteObjects
482
                                     //.Union(sharedObjects)
483
                                     let name = info.Name
484
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
485
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
486
                                                            StringComparison.InvariantCultureIgnoreCase)
487
                                     select info;
488

    
489
                        //Create a list of actions from the remote files
490
                        var allActions = ObjectsToActions(accountInfo, remote);
491

    
492
                        //And remove those that are already being processed by the agent
493
                        var distinctActions = allActions
494
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
495
                            .ToList();
496

    
497
                        //Queue all the actions
498
                        foreach (var message in distinctActions)
499
                        {
500
                            Post(message);
501
                        }
502

    
503
                        Log.Info("[LISTENER] End Processing");
504
                    }
505
                }
506
                catch (Exception ex)
507
                {
508
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
509
                    return;
510
                }
511

    
512
                Log.Info("[LISTENER] Finished");
513

    
514
            }
515
        }
516

    
517
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
518
        {
519
            var containerPaths = from container in containers
520
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
521
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
522
                                 select containerPath;
523

    
524
            foreach (var path in containerPaths)
525
            {
526
                Directory.CreateDirectory(path);
527
            }
528
        }
529

    
530
        //Creates an appropriate action for each server file
531
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
532
        {
533
            if (remote==null)
534
                throw new ArgumentNullException();
535
            Contract.EndContractBlock();
536
            var fileAgent = GetFileAgent(accountInfo);
537

    
538
            //In order to avoid multiple iterations over the files, we iterate only once
539
            //over the remote files
540
            foreach (var objectInfo in remote)
541
            {
542
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
543
                //and remove any matching objects from the list, adding them to the commonObjects list
544
                
545
                if (fileAgent.Exists(relativePath))
546
                {
547
                    //If a directory object already exists, we don't need to perform any other action                    
548
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
549
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
550
                        continue;
551
                    var state = FileState.FindByFilePath(localFile.FullName);
552
                    //Common files should be checked on a per-case basis to detect differences, which is newer
553

    
554
                    yield return new CloudAction(accountInfo,CloudActionType.MustSynch,
555
                                                   localFile, objectInfo, state, accountInfo.BlockSize,
556
                                                   accountInfo.BlockHash);
557
                }
558
                else
559
                {
560
                    //If there is no match we add them to the localFiles list
561
                    //but only if the file is not marked for deletion
562
                    var targetFile = Path.Combine(accountInfo.AccountPath, relativePath);
563
                    var fileStatus = StatusKeeper.GetFileStatus(targetFile);
564
                    if (fileStatus != FileStatus.Deleted)
565
                    {
566
                        //Remote files should be downloaded
567
                        yield return new CloudDownloadAction(accountInfo,objectInfo);
568
                    }
569
                }
570
            }            
571
        }
572

    
573
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
574
        {
575
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
576
        }
577

    
578
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
579
        {
580
            var fileAgent = GetFileAgent(accountInfo);
581
            foreach (var trashObject in trashObjects)
582
            {
583
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
584
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
585
                //deleting a file from a different container
586
                var relativePath = Path.Combine("pithos", barePath);
587
                fileAgent.Delete(relativePath);                                
588
            }
589
        }
590

    
591

    
592
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
593
        {
594
            if (accountInfo==null)
595
                throw new ArgumentNullException("accountInfo");
596
            if (action==null)
597
                throw new ArgumentNullException("action");
598
            if (action.CloudFile==null)
599
                throw new ArgumentException("CloudFile","action");
600
            if (action.LocalFile==null)
601
                throw new ArgumentException("LocalFile","action");
602
            if (action.OldLocalFile==null)
603
                throw new ArgumentException("OldLocalFile","action");
604
            if (action.OldCloudFile==null)
605
                throw new ArgumentException("OldCloudFile","action");
606
            Contract.EndContractBlock();
607
            
608
            
609
            var newFilePath = action.LocalFile.FullName;
610
            
611
            //How do we handle concurrent renames and deletes/uploads/downloads?
612
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
613
            //  This should never happen as the network agent executes only one action at a time
614
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
615
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
616
            //  same name will fail.
617
            //  This should never happen as the network agent executes only one action at a time.
618
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
619
            //  to remove the rename from the queue.
620
            //  We can probably ignore this case. It will result in an error which should be ignored            
621

    
622
            
623
            //The local file is already renamed
624
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
625

    
626

    
627
            var account = action.CloudFile.Account ?? accountInfo.UserName;
628
            var container = action.CloudFile.Container;
629
            
630
            var client = new CloudFilesClient(accountInfo);
631
            //TODO: What code is returned when the source file doesn't exist?
632
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
633

    
634
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
635
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
636
            NativeMethods.RaiseChangeNotification(newFilePath);
637
        }
638

    
639
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
640
        {
641
            if (accountInfo == null)
642
                throw new ArgumentNullException("accountInfo");
643
            if (cloudFile==null)
644
                throw new ArgumentNullException("cloudFile");
645

    
646
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
647
                throw new ArgumentException("Invalid container", "cloudFile");
648
            Contract.EndContractBlock();
649
            
650
            var fileAgent = GetFileAgent(accountInfo);
651

    
652
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
653
            {
654
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
655
                var info = fileAgent.GetFileSystemInfo(fileName);                
656
                var fullPath = info.FullName.ToLower();
657

    
658
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
659

    
660
                var account = cloudFile.Account ?? accountInfo.UserName;
661
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
662

    
663
                var client = new CloudFilesClient(accountInfo);
664
                client.DeleteObject(account, container, cloudFile.Name);
665

    
666
                StatusKeeper.ClearFileStatus(fullPath);
667
            }
668
        }
669

    
670
        //Download a file.
671
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
672
        {
673
            if (accountInfo == null)
674
                throw new ArgumentNullException("accountInfo");
675
            if (cloudFile == null)
676
                throw new ArgumentNullException("cloudFile");
677
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
678
                throw new ArgumentNullException("cloudFile");
679
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
680
                throw new ArgumentNullException("cloudFile");
681
            if (String.IsNullOrWhiteSpace(filePath))
682
                throw new ArgumentNullException("filePath");
683
            if (!Path.IsPathRooted(filePath))
684
                throw new ArgumentException("The filePath must be rooted", "filePath");
685
            Contract.EndContractBlock();
686

    
687
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
688
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
689

    
690
            var url = relativeUrl.ToString();
691
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
692
                return;
693

    
694
            //Are we already downloading or uploading the file? 
695
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
696
            {
697
                if (gate.Failed)
698
                    return;
699
                //The file's hashmap will be stored in the same location with the extension .hashmap
700
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
701
                
702
                var client = new CloudFilesClient(accountInfo);
703
                var account = cloudFile.Account;
704
                var container = cloudFile.Container;
705

    
706
                if (cloudFile.Content_Type == @"application/directory")
707
                {
708
                    if (!Directory.Exists(localPath))
709
                        Directory.CreateDirectory(localPath);
710
                }
711
                else
712
                {
713
                    //Retrieve the hashmap from the server
714
                    var serverHash = await client.GetHashMap(account, container, url);
715
                    //If it's a small file
716
                    if (serverHash.Hashes.Count == 1)
717
                        //Download it in one go
718
                        await
719
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
720
                        //Otherwise download it block by block
721
                    else
722
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
723

    
724
                    if (cloudFile.AllowedTo == "read")
725
                    {
726
                        var attributes = File.GetAttributes(localPath);
727
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
728
                    }
729
                }
730

    
731
                //Now we can store the object's metadata without worrying about ghost status entries
732
                StatusKeeper.StoreInfo(localPath, cloudFile);
733
                
734
            }
735
        }
736

    
737
        //Download a small file with a single GET operation
738
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
739
        {
740
            if (client == null)
741
                throw new ArgumentNullException("client");
742
            if (cloudFile==null)
743
                throw new ArgumentNullException("cloudFile");
744
            if (relativeUrl == null)
745
                throw new ArgumentNullException("relativeUrl");
746
            if (String.IsNullOrWhiteSpace(filePath))
747
                throw new ArgumentNullException("filePath");
748
            if (!Path.IsPathRooted(filePath))
749
                throw new ArgumentException("The localPath must be rooted", "filePath");
750
            Contract.EndContractBlock();
751

    
752
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
753
            //If the file already exists
754
            if (File.Exists(localPath))
755
            {
756
                //First check with MD5 as this is a small file
757
                var localMD5 = Signature.CalculateMD5(localPath);
758
                var cloudHash=serverHash.TopHash.ToHashString();
759
                if (localMD5==cloudHash)
760
                    return;
761
                //Then check with a treehash
762
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
763
                var localHash = localTreeHash.TopHash.ToHashString();
764
                if (localHash==cloudHash)
765
                    return;
766
            }
767

    
768
            var fileAgent = GetFileAgent(accountInfo);
769
            //Calculate the relative file path for the new file
770
            var relativePath = relativeUrl.RelativeUriToFilePath();
771
            //The file will be stored in a temporary location while downloading with an extension .download
772
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
773
            //Make sure the target folder exists. DownloadFileTask will not create the folder
774
            var tempFolder = Path.GetDirectoryName(tempPath);
775
            if (!Directory.Exists(tempFolder))
776
                Directory.CreateDirectory(tempFolder);
777

    
778
            //Download the object to the temporary location
779
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
780

    
781
            //Create the local folder if it doesn't exist (necessary for shared objects)
782
            var localFolder = Path.GetDirectoryName(localPath);
783
            if (!Directory.Exists(localFolder))
784
                Directory.CreateDirectory(localFolder);            
785
            //And move it to its actual location once downloading is finished
786
            if (File.Exists(localPath))
787
                File.Replace(tempPath,localPath,null,true);
788
            else
789
                File.Move(tempPath,localPath);
790
            //Notify listeners that a local file has changed
791
            StatusNotification.NotifyChangedFile(localPath);
792

    
793
                       
794
        }
795

    
796
        //Download a file asynchronously using blocks
797
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
798
        {
799
            if (client == null)
800
                throw new ArgumentNullException("client");
801
            if (cloudFile == null)
802
                throw new ArgumentNullException("cloudFile");
803
            if (relativeUrl == null)
804
                throw new ArgumentNullException("relativeUrl");
805
            if (String.IsNullOrWhiteSpace(filePath))
806
                throw new ArgumentNullException("filePath");
807
            if (!Path.IsPathRooted(filePath))
808
                throw new ArgumentException("The filePath must be rooted", "filePath");
809
            if (serverHash == null)
810
                throw new ArgumentNullException("serverHash");
811
            Contract.EndContractBlock();
812
            
813
           var fileAgent = GetFileAgent(accountInfo);
814
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
815
            
816
            //Calculate the relative file path for the new file
817
            var relativePath = relativeUrl.RelativeUriToFilePath();
818
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
819

    
820
            
821
                        
822
            //Calculate the file's treehash
823
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash);
824
                
825
            //And compare it with the server's hash
826
            var upHashes = serverHash.GetHashesAsStrings();
827
            var localHashes = treeHash.HashDictionary;
828
            for (int i = 0; i < upHashes.Length; i++)
829
            {
830
                //For every non-matching hash
831
                var upHash = upHashes[i];
832
                if (!localHashes.ContainsKey(upHash))
833
                {
834
                    if (blockUpdater.UseOrphan(i, upHash))
835
                    {
836
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
837
                        continue;
838
                    }
839
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
840
                    var start = i*serverHash.BlockSize;
841
                    //To download the last block just pass a null for the end of the range
842
                    long? end = null;
843
                    if (i < upHashes.Length - 1 )
844
                        end= ((i + 1)*serverHash.BlockSize) ;
845
                            
846
                    //Download the missing block
847
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
848

    
849
                    //and store it
850
                    blockUpdater.StoreBlock(i, block);
851

    
852

    
853
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
854
                }
855
            }
856

    
857
            //Want to avoid notifications if no changes were made
858
            var hasChanges = blockUpdater.HasBlocks;
859
            blockUpdater.Commit();
860
            
861
            if (hasChanges)
862
                //Notify listeners that a local file has changed
863
                StatusNotification.NotifyChangedFile(localPath);
864

    
865
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
866
        }
867

    
868

    
869
        private async Task UploadCloudFile(CloudAction action)
870
        {
871
            if (action == null)
872
                throw new ArgumentNullException("action");           
873
            Contract.EndContractBlock();
874

    
875
            try
876
            {
877
                var accountInfo = action.AccountInfo;
878

    
879
                var fileInfo = action.LocalFile;
880

    
881
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
882
                    return;
883

    
884
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
885
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
886
                {
887
                    var parts = relativePath.Split('\\');
888
                    var accountName = parts[1];
889
                    var oldName = accountInfo.UserName;
890
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
891
                    var nameIndex = absoluteUri.IndexOf(oldName);
892
                    var root = absoluteUri.Substring(0, nameIndex);
893

    
894
                    accountInfo = new AccountInfo
895
                    {
896
                        UserName = accountName,
897
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
898
                        StorageUri = new Uri(root + accountName),
899
                        BlockHash = accountInfo.BlockHash,
900
                        BlockSize = accountInfo.BlockSize,
901
                        Token = accountInfo.Token
902
                    };
903
                }
904

    
905

    
906
                var fullFileName = fileInfo.GetProperCapitalization();
907
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
908
                {
909
                    //Abort if the file is already being uploaded or downloaded
910
                    if (gate.Failed)
911
                        return;
912

    
913
                    var cloudFile = action.CloudFile;
914
                    var account = cloudFile.Account ?? accountInfo.UserName;
915

    
916
                    var client = new CloudFilesClient(accountInfo);                    
917
                    //Even if GetObjectInfo times out, we can proceed with the upload            
918
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
919

    
920
                    //If this is a read-only file, do not upload changes
921
                    if (info.AllowedTo == "read")
922
                        return;
923
                    
924
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
925
                    if (fileInfo is DirectoryInfo)
926
                    {
927
                        //If the directory doesn't exist the Hash property will be empty
928
                        if (String.IsNullOrWhiteSpace(info.Hash))
929
                            //Go on and create the directory
930
                            client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
931
                    }
932
                    else
933
                    {
934

    
935
                        var cloudHash = info.Hash.ToLower();
936

    
937
                        var hash = action.LocalHash.Value;
938
                        var topHash = action.TopHash.Value;
939

    
940
                        //If the file hashes match, abort the upload
941
                        if (hash == cloudHash || topHash == cloudHash)
942
                        {
943
                            //but store any metadata changes 
944
                            StatusKeeper.StoreInfo(fullFileName, info);
945
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
946
                            return;
947
                        }
948

    
949

    
950
                        //Mark the file as modified while we upload it
951
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
952
                        //And then upload it
953

    
954
                        //Upload even small files using the Hashmap. The server may already contain
955
                        //the relevant block
956

    
957
                        //First, calculate the tree hash
958
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
959
                                                                              accountInfo.BlockHash);
960

    
961
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
962
                    }
963
                    //If everything succeeds, change the file and overlay status to normal
964
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
965
                }
966
                //Notify the Shell to update the overlays
967
                NativeMethods.RaiseChangeNotification(fullFileName);
968
                StatusNotification.NotifyChangedFile(fullFileName);
969
            }
970
            catch (AggregateException ex)
971
            {
972
                var exc = ex.InnerException as WebException;
973
                if (exc == null)
974
                    throw ex.InnerException;
975
                if (HandleUploadWebException(action, exc)) 
976
                    return;
977
                throw;
978
            }
979
            catch (WebException ex)
980
            {
981
                if (HandleUploadWebException(action, ex))
982
                    return;
983
                throw;
984
            }
985
            catch (Exception ex)
986
            {
987
                Log.Error("Unexpected error while uploading file", ex);
988
                throw;
989
            }
990

    
991
        }
992

    
993
        private bool HandleUploadWebException(CloudAction action, WebException exc)
994
        {
995
            var response = exc.Response as HttpWebResponse;
996
            if (response == null)
997
                throw exc;
998
            if (response.StatusCode == HttpStatusCode.Unauthorized)
999
            {
1000
                Log.Error("Not allowed to upload file", exc);
1001
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1002
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1003
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1004
                return true;
1005
            }
1006
            return false;
1007
        }
1008

    
1009
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1010
        {
1011
            if (accountInfo == null)
1012
                throw new ArgumentNullException("accountInfo");
1013
            if (cloudFile==null)
1014
                throw new ArgumentNullException("cloudFile");
1015
            if (fileInfo == null)
1016
                throw new ArgumentNullException("fileInfo");
1017
            if (String.IsNullOrWhiteSpace(url))
1018
                throw new ArgumentNullException(url);
1019
            if (treeHash==null)
1020
                throw new ArgumentNullException("treeHash");
1021
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1022
                throw new ArgumentException("Invalid container","cloudFile");
1023
            Contract.EndContractBlock();
1024

    
1025
            var fullFileName = fileInfo.GetProperCapitalization();
1026

    
1027
            var account = cloudFile.Account ?? accountInfo.UserName;
1028
            var container = cloudFile.Container ;
1029

    
1030
            var client = new CloudFilesClient(accountInfo);
1031
            //Send the hashmap to the server            
1032
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1033
            //If the server returns no missing hashes, we are done
1034
            while (missingHashes.Count > 0)
1035
            {
1036

    
1037
                var buffer = new byte[accountInfo.BlockSize];
1038
                foreach (var missingHash in missingHashes)
1039
                {
1040
                    //Find the proper block
1041
                    var blockIndex = treeHash.HashDictionary[missingHash];
1042
                    var offset = blockIndex*accountInfo.BlockSize;
1043

    
1044
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1045

    
1046
                    try
1047
                    {
1048
                        //And upload the block                
1049
                        await client.PostBlock(account, container, buffer, 0, read);
1050
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1051
                    }
1052
                    catch (Exception exc)
1053
                    {
1054
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1055
                    }
1056

    
1057
                }
1058

    
1059
                //Repeat until there are no more missing hashes                
1060
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1061
            }
1062
        }
1063

    
1064

    
1065
        public void AddAccount(AccountInfo accountInfo)
1066
        {            
1067
            if (!_accounts.Contains(accountInfo))
1068
                _accounts.Add(accountInfo);
1069
        }
1070
    }
1071

    
1072
   
1073

    
1074

    
1075
}