Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 039a89e5

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

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

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

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

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

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

    
74
        public void Start()
75
        {
76

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

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

    
100
            });
101
        }
102

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

    
111
            var accountInfo = action.AccountInfo;
112

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

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

    
120
                try
121
                {
122

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

    
186
                    _agent.Post(action);
187
                }                
188
            }
189
        }
190

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

    
211
            var accountInfo = action.AccountInfo;
212

    
213
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
214
            {                
215
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
216

    
217
                var cloudFile = action.CloudFile;
218

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

    
230
                        // and then delete the file from the server
231
                        DeleteCloudFile(accountInfo, cloudFile);
232
                        Log.InfoFormat("[ACTION] End Delete {0}:{1}->{2}", action.Action, action.LocalFile,
233
                                       action.CloudFile.Name);
234
                    }
235
                }
236
                catch (WebException exc)
237
                {
238
                    Log.ErrorFormat("[WEB ERROR] {0} : {1} -> {2} due to exception\r\n{3}", action.Action, action.LocalFile, action.CloudFile, exc);
239
                }
240
                catch (OperationCanceledException)
241
                {
242
                    throw;
243
                }
244
                catch (DirectoryNotFoundException)
245
                {
246
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the directory was not found.\n Rescheduling a delete",
247
                        action.Action, action.LocalFile, action.CloudFile);
248
                    //Repost a delete action for the missing file
249
                    _deleteAgent.Post(action);                    
250
                }
251
                catch (FileNotFoundException)
252
                {
253
                    Log.ErrorFormat("{0} : {1} -> {2}  failed because the file was not found.\n Rescheduling a delete",
254
                        action.Action, action.LocalFile, action.CloudFile);
255
                    //Post a delete action for the missing file
256
                    _deleteAgent.Post(action);
257
                }
258
                catch (Exception exc)
259
                {
260
                    Log.ErrorFormat("[REQUEUE] {0} : {1} -> {2} due to exception\r\n{3}",
261
                                     action.Action, action.LocalFile, action.CloudFile, exc);
262

    
263
                    _deleteAgent.Post(action);
264
                }                
265
            }
266
        }
267

    
268
        private static string GetFileKey(ObjectInfo info)
269
        {
270
            var key = String.Format("{0}/{1}/{2}", info.Account, info.Container,info.Name);
271
            return key;
272
        }
273

    
274
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
275
        {
276
            if (accountInfo == null)
277
                throw new ArgumentNullException("accountInfo");
278
            if (action==null)
279
                throw new ArgumentNullException("action");
280
            if (action.LocalFile==null)
281
                throw new ArgumentException("The action's local file is not specified","action");
282
            if (!Path.IsPathRooted(action.LocalFile.FullName))
283
                throw new ArgumentException("The action's local file path must be absolute","action");
284
            if (action.CloudFile== null)
285
                throw new ArgumentException("The action's cloud file is not specified", "action");
286
            Contract.EndContractBlock();
287

    
288
            var localFile = action.LocalFile;
289
            var cloudFile = action.CloudFile;
290
            var downloadPath=action.LocalFile.GetProperCapitalization();
291

    
292
            var cloudHash = cloudFile.Hash.ToLower();
293
            var localHash = action.LocalHash.Value.ToLower();
294
            var topHash = action.TopHash.Value.ToLower();
295

    
296
            //Not enough to compare only the local hashes, also have to compare the tophashes
297
            
298
            //If any of the hashes match, we are done
299
            if ((cloudHash == localHash || cloudHash == topHash))
300
            {
301
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
302
                return;
303
            }
304

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

    
334
                        //In both cases we must mark the file as in conflict
335
                        ReportConflict(downloadPath);
336
                        break;
337
                    default:
338
                        //Other cases should never occur. Mark them as Conflict as well but log a warning
339
                        ReportConflict(downloadPath);
340
                        Log.WarnFormat("Unexcepted status {0} for file {1}->{2}", status,
341
                                       downloadPath, action.CloudFile.Name);
342
                        break;
343
                }
344
            }
345
        }
346

    
347
        private void ReportConflict(string downloadPath)
348
        {
349
            if (String.IsNullOrWhiteSpace(downloadPath))
350
                throw new ArgumentNullException("downloadPath");
351
            Contract.EndContractBlock();
352

    
353
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
354
            var message = String.Format("Conflict detected for file {0}", downloadPath);
355
            Log.Warn(message);
356
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
357
        }
358

    
359
        public void Post(CloudAction cloudAction)
360
        {
361
            if (cloudAction == null)
362
                throw new ArgumentNullException("cloudAction");
363
            if (cloudAction.AccountInfo==null)
364
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
365
            Contract.EndContractBlock();
366

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

    
395
       /* class ObjectInfoByNameComparer:IEqualityComparer<ObjectInfo>
396
        {
397
            public bool Equals(ObjectInfo x, ObjectInfo y)
398
            {
399
                return x.Name.Equals(y.Name,StringComparison.InvariantCultureIgnoreCase);
400
            }
401

    
402
            public int GetHashCode(ObjectInfo obj)
403
            {
404
                return obj.Name.ToLower().GetHashCode();
405
            }
406
        }*/
407

    
408
        
409

    
410
        //Remote files are polled periodically. Any changes are processed
411
        public async Task ProcessRemoteFiles(DateTime? since = null)
412
        {            
413
            await TaskEx.Delay(TimeSpan.FromSeconds(10),_agent.CancellationToken);
414

    
415
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
416
            {
417

    
418
                try
419
                {
420
                    //Next time we will check for all changes since the current check minus 1 second
421
                    //This is done to ensure there are no discrepancies due to clock differences
422
                    DateTime nextSince = DateTime.Now.AddSeconds(-1);
423

    
424
                    var tasks = from accountInfo in _accounts
425
                                select ProcessAccountFiles(accountInfo, since);
426

    
427
                    await TaskEx.WhenAll(tasks.ToList());
428

    
429
                    ProcessRemoteFiles(nextSince);
430
                }
431
                catch (Exception ex)
432
                {
433
                    Log.ErrorFormat("Error while processing accounts\r\n{0}",ex);
434
                    //In case of failure retry with the same parameter
435
                    ProcessRemoteFiles(since);
436
                }
437
                
438

    
439
            }
440
        }
441

    
442
        public async Task ProcessAccountFiles(AccountInfo accountInfo,DateTime? since=null)
443
        {   
444
            if (accountInfo==null)
445
                throw new ArgumentNullException("accountInfo");
446
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
447
                throw new ArgumentException("The AccountInfo.AccountPath is empty","accountInfo");
448
            Contract.EndContractBlock();
449

    
450
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
451
            {
452
                Log.Info("Scheduled");
453
                var client=new CloudFilesClient(accountInfo);
454

    
455
                var containers = client.ListContainers(accountInfo.UserName);
456
                
457
                CreateContainerFolders(accountInfo, containers);
458

    
459
                try
460
                {
461
                    
462
                    //Get the list of server objects changed since the last check
463
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
464
                    var listObjects = from container in containers
465
                                      select  Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
466
                                            client.ListObjects(accountInfo.UserName,container.Name, since),container.Name);
467

    
468

    
469
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
470

    
471
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
472
                    {
473
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
474

    
475
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
476
                        var remoteObjects = from objectList in listTasks
477
                                            where (string) objectList.AsyncState != "trash"
478
                                            from obj in objectList.Result
479
                                            select obj;
480

    
481
                        var trashObjects = dict["trash"].Result;
482
                        //var sharedObjects = ((Task<IList<ObjectInfo>>) task.Result[2]).Result;
483

    
484
                        //Items with the same name, hash may be both in the container and the trash
485
                        //Don't delete items that exist in the container
486
                        var realTrash = from trash in trashObjects
487
                                        where
488
                                            !remoteObjects.Any(
489
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
490
                                        select trash;
491
                        ProcessDeletedFiles(accountInfo, realTrash);
492

    
493

    
494
                        var remote = from info in remoteObjects
495
                                     //.Union(sharedObjects)
496
                                     let name = info.Name
497
                                     where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
498
                                           !name.StartsWith(FolderConstants.CacheFolder + "/",
499
                                                            StringComparison.InvariantCultureIgnoreCase)
500
                                     select info;
501

    
502
                        //Create a list of actions from the remote files
503
                        var allActions = ObjectsToActions(accountInfo, remote);
504

    
505
                        //And remove those that are already being processed by the agent
506
                        var distinctActions = allActions
507
                            .Except(_agent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
508
                            .ToList();
509

    
510
                        //Queue all the actions
511
                        foreach (var message in distinctActions)
512
                        {
513
                            Post(message);
514
                        }
515

    
516
                        Log.Info("[LISTENER] End Processing");
517
                    }
518
                }
519
                catch (Exception ex)
520
                {
521
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
522
                    return;
523
                }
524

    
525
                Log.Info("[LISTENER] Finished");
526

    
527
            }
528
        }
529

    
530
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
531
        {
532
            var containerPaths = from container in containers
533
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
534
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
535
                                 select containerPath;
536

    
537
            foreach (var path in containerPaths)
538
            {
539
                Directory.CreateDirectory(path);
540
            }
541
        }
542

    
543
        //Creates an appropriate action for each server file
544
        private IEnumerable<CloudAction> ObjectsToActions(AccountInfo accountInfo,IEnumerable<ObjectInfo> remote)
545
        {
546
            if (remote==null)
547
                throw new ArgumentNullException();
548
            Contract.EndContractBlock();
549
            var fileAgent = GetFileAgent(accountInfo);
550

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

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

    
590
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
591
        {
592
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
593
        }
594

    
595
        private void ProcessDeletedFiles(AccountInfo accountInfo,IEnumerable<ObjectInfo> trashObjects)
596
        {
597
            var fileAgent = GetFileAgent(accountInfo);
598
            foreach (var trashObject in trashObjects)
599
            {
600
                var barePath = trashObject.RelativeUrlToFilePath(accountInfo.UserName);
601
                //HACK: Assume only the "pithos" container is used. Must find out what happens when
602
                //deleting a file from a different container
603
                var relativePath = Path.Combine("pithos", barePath);
604
                fileAgent.Delete(relativePath);                                
605
            }
606
        }
607

    
608

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

    
639
            
640
            //The local file is already renamed
641
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
642

    
643

    
644
            var account = action.CloudFile.Account ?? accountInfo.UserName;
645
            var container = action.CloudFile.Container;
646
            
647
            var client = new CloudFilesClient(accountInfo);
648
            //TODO: What code is returned when the source file doesn't exist?
649
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
650

    
651
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
652
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
653
            NativeMethods.RaiseChangeNotification(newFilePath);
654
        }
655

    
656
        private void DeleteCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile)
657
        {
658
            if (accountInfo == null)
659
                throw new ArgumentNullException("accountInfo");
660
            if (cloudFile==null)
661
                throw new ArgumentNullException("cloudFile");
662

    
663
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
664
                throw new ArgumentException("Invalid container", "cloudFile");
665
            Contract.EndContractBlock();
666
            
667
            var fileAgent = GetFileAgent(accountInfo);
668

    
669
            using ( log4net.ThreadContext.Stacks["DeleteCloudFile"].Push("Delete"))
670
            {
671
                var fileName= cloudFile.RelativeUrlToFilePath(accountInfo.UserName);
672
                var info = fileAgent.GetFileSystemInfo(fileName);                
673
                var fullPath = info.FullName.ToLower();
674

    
675
                StatusKeeper.SetFileOverlayStatus(fullPath, FileOverlayStatus.Modified);
676

    
677
                var account = cloudFile.Account ?? accountInfo.UserName;
678
                var container = cloudFile.Container ;//?? FolderConstants.PithosContainer;
679

    
680
                var client = new CloudFilesClient(accountInfo);
681
                client.DeleteObject(account, container, cloudFile.Name);
682

    
683
                StatusKeeper.ClearFileStatus(fullPath);
684
            }
685
        }
686

    
687
        //Download a file.
688
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
689
        {
690
            if (accountInfo == null)
691
                throw new ArgumentNullException("accountInfo");
692
            if (cloudFile == null)
693
                throw new ArgumentNullException("cloudFile");
694
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
695
                throw new ArgumentNullException("cloudFile");
696
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
697
                throw new ArgumentNullException("cloudFile");
698
            if (String.IsNullOrWhiteSpace(filePath))
699
                throw new ArgumentNullException("filePath");
700
            if (!Path.IsPathRooted(filePath))
701
                throw new ArgumentException("The filePath must be rooted", "filePath");
702
            Contract.EndContractBlock();
703

    
704
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
705
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
706

    
707
            var url = relativeUrl.ToString();
708
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
709
                return;
710

    
711

    
712
            //Are we already downloading or uploading the file? 
713
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
714
            {
715
                if (gate.Failed)
716
                    return;
717
                //The file's hashmap will be stored in the same location with the extension .hashmap
718
                //var hashPath = Path.Combine(FileAgent.CachePath, relativePath + ".hashmap");
719
                
720
                var client = new CloudFilesClient(accountInfo);
721
                var account = cloudFile.Account;
722
                var container = cloudFile.Container;
723

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

    
742
                    if (cloudFile.AllowedTo == "read")
743
                    {
744
                        var attributes = File.GetAttributes(localPath);
745
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
746
                    }
747
                }
748

    
749
                //Now we can store the object's metadata without worrying about ghost status entries
750
                StatusKeeper.StoreInfo(localPath, cloudFile);
751
                
752
            }
753
        }
754

    
755
        //Download a small file with a single GET operation
756
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
757
        {
758
            if (client == null)
759
                throw new ArgumentNullException("client");
760
            if (cloudFile==null)
761
                throw new ArgumentNullException("cloudFile");
762
            if (relativeUrl == null)
763
                throw new ArgumentNullException("relativeUrl");
764
            if (String.IsNullOrWhiteSpace(filePath))
765
                throw new ArgumentNullException("filePath");
766
            if (!Path.IsPathRooted(filePath))
767
                throw new ArgumentException("The localPath must be rooted", "filePath");
768
            Contract.EndContractBlock();
769

    
770
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
771
            //If the file already exists
772
            if (File.Exists(localPath))
773
            {
774
                //First check with MD5 as this is a small file
775
                var localMD5 = Signature.CalculateMD5(localPath);
776
                var cloudHash=serverHash.TopHash.ToHashString();
777
                if (localMD5==cloudHash)
778
                    return;
779
                //Then check with a treehash
780
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
781
                var localHash = localTreeHash.TopHash.ToHashString();
782
                if (localHash==cloudHash)
783
                    return;
784
            }
785

    
786
            var fileAgent = GetFileAgent(accountInfo);
787
            //Calculate the relative file path for the new file
788
            var relativePath = relativeUrl.RelativeUriToFilePath();
789
            //The file will be stored in a temporary location while downloading with an extension .download
790
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
791
            //Make sure the target folder exists. DownloadFileTask will not create the folder
792
            var tempFolder = Path.GetDirectoryName(tempPath);
793
            if (!Directory.Exists(tempFolder))
794
                Directory.CreateDirectory(tempFolder);
795

    
796
            //Download the object to the temporary location
797
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
798

    
799
            //Create the local folder if it doesn't exist (necessary for shared objects)
800
            var localFolder = Path.GetDirectoryName(localPath);
801
            if (!Directory.Exists(localFolder))
802
                Directory.CreateDirectory(localFolder);            
803
            //And move it to its actual location once downloading is finished
804
            if (File.Exists(localPath))
805
                File.Replace(tempPath,localPath,null,true);
806
            else
807
                File.Move(tempPath,localPath);
808
            //Notify listeners that a local file has changed
809
            StatusNotification.NotifyChangedFile(localPath);
810

    
811
                       
812
        }
813

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

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

    
867
                    //and store it
868
                    blockUpdater.StoreBlock(i, block);
869

    
870

    
871
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
872
                }
873
            }
874

    
875
            //Want to avoid notifications if no changes were made
876
            var hasChanges = blockUpdater.HasBlocks;
877
            blockUpdater.Commit();
878
            
879
            if (hasChanges)
880
                //Notify listeners that a local file has changed
881
                StatusNotification.NotifyChangedFile(localPath);
882

    
883
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
884
        }
885

    
886

    
887
        private async Task UploadCloudFile(CloudAction action)
888
        {
889
            if (action == null)
890
                throw new ArgumentNullException("action");           
891
            Contract.EndContractBlock();
892

    
893
            try
894
            {
895
                var accountInfo = action.AccountInfo;
896

    
897
                var fileInfo = action.LocalFile;
898

    
899
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
900
                    return;
901
                
902
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
903
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
904
                {
905
                    var parts = relativePath.Split('\\');
906
                    var accountName = parts[1];
907
                    var oldName = accountInfo.UserName;
908
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
909
                    var nameIndex = absoluteUri.IndexOf(oldName);
910
                    var root = absoluteUri.Substring(0, nameIndex);
911

    
912
                    accountInfo = new AccountInfo
913
                    {
914
                        UserName = accountName,
915
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
916
                        StorageUri = new Uri(root + accountName),
917
                        BlockHash = accountInfo.BlockHash,
918
                        BlockSize = accountInfo.BlockSize,
919
                        Token = accountInfo.Token
920
                    };
921
                }
922

    
923

    
924
                var fullFileName = fileInfo.GetProperCapitalization();
925
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
926
                {
927
                    //Abort if the file is already being uploaded or downloaded
928
                    if (gate.Failed)
929
                        return;
930

    
931
                    var cloudFile = action.CloudFile;
932
                    var account = cloudFile.Account ?? accountInfo.UserName;
933

    
934
                    var client = new CloudFilesClient(accountInfo);                    
935
                    //Even if GetObjectInfo times out, we can proceed with the upload            
936
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
937

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

    
953
                        var cloudHash = info.Hash.ToLower();
954

    
955
                        var hash = action.LocalHash.Value;
956
                        var topHash = action.TopHash.Value;
957

    
958
                        //If the file hashes match, abort the upload
959
                        if (hash == cloudHash || topHash == cloudHash)
960
                        {
961
                            //but store any metadata changes 
962
                            StatusKeeper.StoreInfo(fullFileName, info);
963
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
964
                            return;
965
                        }
966

    
967

    
968
                        //Mark the file as modified while we upload it
969
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
970
                        //And then upload it
971

    
972
                        //Upload even small files using the Hashmap. The server may already contain
973
                        //the relevant block
974

    
975
                        //First, calculate the tree hash
976
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
977
                                                                              accountInfo.BlockHash);
978

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

    
1009
        }
1010

    
1011
        private bool IsDeletedFile(CloudAction action)
1012
        {            
1013
            var key = GetFileKey(action.CloudFile);
1014
            DateTime entryDate;
1015
            if (_deletedFiles.TryGetValue(key, out entryDate))
1016
            {
1017
                //If the delete entry was created after this action, abort the action
1018
                if (entryDate > action.Created)
1019
                    return true;
1020
                //Otherwise, remove the stale entry 
1021
                _deletedFiles.TryRemove(key, out entryDate);
1022
            }
1023
            return false;
1024
        }
1025

    
1026
        private bool HandleUploadWebException(CloudAction action, WebException exc)
1027
        {
1028
            var response = exc.Response as HttpWebResponse;
1029
            if (response == null)
1030
                throw exc;
1031
            if (response.StatusCode == HttpStatusCode.Unauthorized)
1032
            {
1033
                Log.Error("Not allowed to upload file", exc);
1034
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
1035
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
1036
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
1037
                return true;
1038
            }
1039
            return false;
1040
        }
1041

    
1042
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
1043
        {
1044
            if (accountInfo == null)
1045
                throw new ArgumentNullException("accountInfo");
1046
            if (cloudFile==null)
1047
                throw new ArgumentNullException("cloudFile");
1048
            if (fileInfo == null)
1049
                throw new ArgumentNullException("fileInfo");
1050
            if (String.IsNullOrWhiteSpace(url))
1051
                throw new ArgumentNullException(url);
1052
            if (treeHash==null)
1053
                throw new ArgumentNullException("treeHash");
1054
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
1055
                throw new ArgumentException("Invalid container","cloudFile");
1056
            Contract.EndContractBlock();
1057

    
1058
            var fullFileName = fileInfo.GetProperCapitalization();
1059

    
1060
            var account = cloudFile.Account ?? accountInfo.UserName;
1061
            var container = cloudFile.Container ;
1062

    
1063
            var client = new CloudFilesClient(accountInfo);
1064
            //Send the hashmap to the server            
1065
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
1066
            //If the server returns no missing hashes, we are done
1067
            while (missingHashes.Count > 0)
1068
            {
1069

    
1070
                var buffer = new byte[accountInfo.BlockSize];
1071
                foreach (var missingHash in missingHashes)
1072
                {
1073
                    //Find the proper block
1074
                    var blockIndex = treeHash.HashDictionary[missingHash];
1075
                    var offset = blockIndex*accountInfo.BlockSize;
1076

    
1077
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
1078

    
1079
                    try
1080
                    {
1081
                        //And upload the block                
1082
                        await client.PostBlock(account, container, buffer, 0, read);
1083
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
1084
                    }
1085
                    catch (Exception exc)
1086
                    {
1087
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
1088
                    }
1089

    
1090
                }
1091

    
1092
                //Repeat until there are no more missing hashes                
1093
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
1094
            }
1095
        }
1096

    
1097

    
1098
        public void AddAccount(AccountInfo accountInfo)
1099
        {            
1100
            if (!_accounts.Contains(accountInfo))
1101
                _accounts.Add(accountInfo);
1102
        }
1103
    }
1104

    
1105
   
1106

    
1107

    
1108
}