Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / NetworkAgent.cs @ 6f03d6e1

History | View | Annotate | Download (44.9 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="NetworkAgent.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42

    
43
using System;
44
using System.Collections.Generic;
45
using System.ComponentModel.Composition;
46
using System.Diagnostics;
47
using System.Diagnostics.Contracts;
48
using System.IO;
49
using System.Net;
50
using System.Reflection;
51
using System.Threading;
52
using System.Threading.Tasks;
53
using Castle.ActiveRecord;
54
using Pithos.Interfaces;
55
using Pithos.Network;
56
using log4net;
57

    
58
namespace Pithos.Core.Agents
59
{
60
    [Export]
61
    public class NetworkAgent
62
    {
63
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
64

    
65
        private Agent<CloudAction> _agent;
66

    
67
        [System.ComponentModel.Composition.Import]
68
        private DeleteAgent _deleteAgent=new DeleteAgent();
69

    
70
        [System.ComponentModel.Composition.Import]
71
        public IStatusKeeper StatusKeeper { get; set; }
72
        
73
        public IStatusNotification StatusNotification { get; set; }
74

    
75

    
76
        [System.ComponentModel.Composition.Import]
77
        public IPithosSettings Settings { get; set; }
78

    
79
        //The Proceed signals the poll agent that it can proceed with polling. 
80
        //Essentially it stops the poll agent to give priority to the network agent
81
        //Initially the event is signalled because we don't need to pause
82
        private readonly AsyncManualResetEvent _proceedEvent = new AsyncManualResetEvent(true);
83

    
84
        public AsyncManualResetEvent ProceedEvent
85
        {
86
            get { return _proceedEvent; }
87
        }
88

    
89

    
90
        public void Start()
91
        {
92
            if (_agent != null)
93
                return;
94

    
95
            if (Log.IsDebugEnabled)
96
                Log.Debug("Starting Network Agent");
97

    
98
            _agent = Agent<CloudAction>.Start(inbox =>
99
            {
100
                Action loop = null;
101
                loop = () =>
102
                {
103
                    _deleteAgent.ProceedEvent.Wait();
104
                    var message = inbox.Receive();
105
                    var process=message.Then(Process,inbox.CancellationToken);
106
                    inbox.LoopAsync(process, loop);
107
                };
108
                loop();
109
            });
110

    
111
        }
112

    
113
        private async Task Process(CloudAction action)
114
        {
115
            if (action == null)
116
                throw new ArgumentNullException("action");
117
            if (action.AccountInfo==null)
118
                throw new ArgumentException("The action.AccountInfo is empty","action");
119
            Contract.EndContractBlock();
120

    
121

    
122

    
123

    
124
            using (log4net.ThreadContext.Stacks["Operation"].Push(action.ToString()))
125
            {                
126

    
127
                var cloudFile = action.CloudFile;
128
                var downloadPath = action.GetDownloadPath();
129

    
130
                try
131
                {
132
                    StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,"Processing");
133
                    _proceedEvent.Reset();
134
                    //UpdateStatus(PithosStatus.Syncing);
135
                    var accountInfo = action.AccountInfo;
136

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

    
208
                    _agent.Post(action);
209
                }
210
                finally
211
                {
212
                    if (_agent.IsEmpty)
213
                        _proceedEvent.Set();
214
                    UpdateStatus(PithosStatus.LocalComplete);                                        
215
                }
216
            }
217
        }
218

    
219

    
220
        private void UpdateStatus(PithosStatus status)
221
        {
222
            StatusNotification.SetPithosStatus(status);
223
            //StatusNotification.Notify(new Notification());
224
        }
225

    
226
        private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
227
        {
228
            if (accountInfo == null)
229
                throw new ArgumentNullException("accountInfo");
230
            if (action == null)
231
                throw new ArgumentNullException("action");
232
            if (action.LocalFile == null)
233
                throw new ArgumentException("The action's local file is not specified", "action");
234
            if (!Path.IsPathRooted(action.LocalFile.FullName))
235
                throw new ArgumentException("The action's local file path must be absolute", "action");
236
            if (action.CloudFile == null)
237
                throw new ArgumentException("The action's cloud file is not specified", "action");
238
            Contract.EndContractBlock();
239
            using (ThreadContext.Stacks["Operation"].Push("RenameLocalFile"))
240
            {
241

    
242
                //We assume that the local file already exists, otherwise the poll agent
243
                //would have issued a download request
244

    
245
                var currentInfo = action.CloudFile;
246
                var previousInfo = action.CloudFile.Previous;
247
                var fileAgent = FileAgent.GetFileAgent(accountInfo);
248

    
249
                var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
250
                var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
251

    
252
                //In every case we need to move the local file first
253
                MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
254
            }
255
        }
256

    
257
        private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
258
                                   ObjectInfo currentInfo)
259
        {
260
            var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
261
            var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
262

    
263
            var isFile= (previousFile is FileInfo);
264
            var previousFullPath = isFile? 
265
                FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
266
                FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);                
267
            
268
            using (var gateOld = NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
269
            using (var gateNew = NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
270
            using (new SessionScope(FlushAction.Auto))
271
            {
272
                if (isFile)
273
                    (previousFile as FileInfo).MoveTo(newPath);
274
                else
275
                {
276
                    (previousFile as DirectoryInfo).MoveTo(newPath);
277
                }
278
                var state = StatusKeeper.GetStateByFilePath(previousFullPath);
279
                state.FilePath = newPath;
280
                state.SaveCopy();
281
                StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted);
282
            }            
283
        }
284

    
285
        private async Task SyncFiles(AccountInfo accountInfo,CloudAction action)
286
        {
287
            if (accountInfo == null)
288
                throw new ArgumentNullException("accountInfo");
289
            if (action==null)
290
                throw new ArgumentNullException("action");
291
            if (action.LocalFile==null)
292
                throw new ArgumentException("The action's local file is not specified","action");
293
            if (!Path.IsPathRooted(action.LocalFile.FullName))
294
                throw new ArgumentException("The action's local file path must be absolute","action");
295
            if (action.CloudFile== null)
296
                throw new ArgumentException("The action's cloud file is not specified", "action");
297
            Contract.EndContractBlock();
298
            using (ThreadContext.Stacks["Operation"].Push("SyncFiles"))
299
            {
300

    
301
                var localFile = action.LocalFile;
302
                var cloudFile = action.CloudFile;
303
                var downloadPath = action.LocalFile.GetProperCapitalization();
304

    
305
                var cloudHash = cloudFile.Hash.ToLower();
306
                var previousCloudHash = cloudFile.PreviousHash.ToLower();
307
                var localHash = action.TreeHash.Value.TopHash.ToHashString();// LocalHash.Value.ToLower();
308
                //var topHash = action.TopHash.Value.ToLower();
309

    
310
                //At this point we know that an object has changed on the server and that a local
311
                //file already exists. We need to decide whether the file has only changed on 
312
                //the server or there is a conflicting change on the client.
313
                //
314

    
315
                //If the hashes match, we are done
316
                if (cloudHash == localHash)
317
                {
318
                    Log.InfoFormat("Skipping {0}, hashes match", downloadPath);
319
                    return;
320
                }
321

    
322
                //The hashes DON'T match. We need to sync
323

    
324
                // If the previous tophash matches the local tophash, the file was only changed on the server. 
325
                if (localHash == previousCloudHash)
326
                {
327
                    await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
328
                }
329
                else
330
                {
331
                    //If the previous and local hash don't match, there was a local conflict
332
                    //that was not uploaded to the server. We have a conflict
333
                    ReportConflict(downloadPath);
334
                }
335
            }
336
        }
337

    
338
        private void ReportConflict(string downloadPath)
339
        {
340
            if (String.IsNullOrWhiteSpace(downloadPath))
341
                throw new ArgumentNullException("downloadPath");
342
            Contract.EndContractBlock();
343

    
344
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
345
            UpdateStatus(PithosStatus.HasConflicts);
346
            var message = String.Format("Conflict detected for file {0}", downloadPath);
347
            Log.Warn(message);
348
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
349
        }
350

    
351
        public void Post(CloudAction cloudAction)
352
        {
353
            if (cloudAction == null)
354
                throw new ArgumentNullException("cloudAction");
355
            if (cloudAction.AccountInfo==null)
356
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
357
            Contract.EndContractBlock();
358

    
359
            _deleteAgent.ProceedEvent.Wait();
360
/*
361

    
362
            //If the action targets a local file, add a treehash calculation
363
            if (!(cloudAction is CloudDeleteAction) && cloudAction.LocalFile as FileInfo != null)
364
            {
365
                var accountInfo = cloudAction.AccountInfo;
366
                var localFile = (FileInfo) cloudAction.LocalFile;
367

    
368
                if (localFile.Length > accountInfo.BlockSize)
369
                    cloudAction.TopHash =
370
                        new Lazy<string>(() => Signature.CalculateTreeHashAsync(localFile,
371
                                                                                accountInfo.BlockSize,
372
                                                                                accountInfo.BlockHash, Settings.HashingParallelism).Result
373
                                                    .TopHash.ToHashString());
374
                else
375
                {
376
                    cloudAction.TopHash = new Lazy<string>(() => cloudAction.LocalHash.Value);
377
                }
378

    
379
            }
380
            else
381
            {
382
                //The hash for a directory is the empty string
383
                cloudAction.TopHash = new Lazy<string>(() => String.Empty);
384
            }
385
*/
386
            
387
            if (cloudAction is CloudDeleteAction)
388
                _deleteAgent.Post((CloudDeleteAction)cloudAction);
389
            else
390
                _agent.Post(cloudAction);
391
        }
392
       
393

    
394
        public IEnumerable<CloudAction> GetEnumerable()
395
        {
396
            return _agent.GetEnumerable();
397
        }
398

    
399
        public Task GetDeleteAwaiter()
400
        {
401
            return _deleteAgent.ProceedEvent.WaitAsync();
402
        }
403
        public CancellationToken CancellationToken
404
        {
405
            get { return _agent.CancellationToken; }
406
        }
407

    
408
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
409
        {
410
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
411
        }
412

    
413

    
414

    
415
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
416
        {
417
            if (accountInfo==null)
418
                throw new ArgumentNullException("accountInfo");
419
            if (action==null)
420
                throw new ArgumentNullException("action");
421
            if (action.CloudFile==null)
422
                throw new ArgumentException("CloudFile","action");
423
            if (action.LocalFile==null)
424
                throw new ArgumentException("LocalFile","action");
425
            if (action.OldLocalFile==null)
426
                throw new ArgumentException("OldLocalFile","action");
427
            if (action.OldCloudFile==null)
428
                throw new ArgumentException("OldCloudFile","action");
429
            Contract.EndContractBlock();
430

    
431
            using (ThreadContext.Stacks["Operation"].Push("RenameCloudFile"))
432
            {
433

    
434
                var newFilePath = action.LocalFile.FullName;
435

    
436
                //How do we handle concurrent renames and deletes/uploads/downloads?
437
                //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
438
                //  This should never happen as the network agent executes only one action at a time
439
                //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
440
                //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
441
                //  same name will fail.
442
                //  This should never happen as the network agent executes only one action at a time.
443
                //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
444
                //  to remove the rename from the queue.
445
                //  We can probably ignore this case. It will result in an error which should be ignored            
446

    
447

    
448
                //The local file is already renamed
449
                StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
450

    
451

    
452
                var account = action.CloudFile.Account ?? accountInfo.UserName;
453
                var container = action.CloudFile.Container;
454

    
455
                var client = new CloudFilesClient(accountInfo);
456
                //TODO: What code is returned when the source file doesn't exist?
457
                client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
458

    
459
                StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
460
                StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
461
                NativeMethods.RaiseChangeNotification(newFilePath);
462
            }
463
        }
464

    
465
        //Download a file.
466
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
467
        {
468
            if (accountInfo == null)
469
                throw new ArgumentNullException("accountInfo");
470
            if (cloudFile == null)
471
                throw new ArgumentNullException("cloudFile");
472
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
473
                throw new ArgumentNullException("cloudFile");
474
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
475
                throw new ArgumentNullException("cloudFile");
476
            if (String.IsNullOrWhiteSpace(filePath))
477
                throw new ArgumentNullException("filePath");
478
            if (!Path.IsPathRooted(filePath))
479
                throw new ArgumentException("The filePath must be rooted", "filePath");
480
            Contract.EndContractBlock();
481

    
482
            using (ThreadContext.Stacks["Operation"].Push("DownloadCloudFile"))
483
            {
484

    
485
                var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
486
                var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
487

    
488
                var url = relativeUrl.ToString();
489
                if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
490
                    return;
491

    
492

    
493
                //Are we already downloading or uploading the file? 
494
                using (var gate = NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
495
                {
496
                    if (gate.Failed)
497
                        return;
498

    
499
                    var client = new CloudFilesClient(accountInfo);
500
                    var account = cloudFile.Account;
501
                    var container = cloudFile.Container;
502

    
503
                    if (cloudFile.Content_Type == @"application/directory")
504
                    {
505
                        if (!Directory.Exists(localPath))
506
                            try
507
                            {
508
                                Directory.CreateDirectory(localPath);
509
                                if (Log.IsDebugEnabled)
510
                                    Log.DebugFormat("Created Directory [{0}]",localPath);
511
                            }
512
                            catch (IOException)
513
                            {
514
                                var localInfo = new FileInfo(localPath);
515
                                if (localInfo.Exists && localInfo.Length == 0)
516
                                {
517
                                    Log.WarnFormat("Malformed directory object detected for [{0}]",localPath);
518
                                    localInfo.Delete();
519
                                    Directory.CreateDirectory(localPath);
520
                                    if (Log.IsDebugEnabled)
521
                                        Log.DebugFormat("Created Directory [{0}]", localPath);
522
                                }
523
                            }
524
                    }
525
                    else
526
                    {
527
                        var isChanged = IsObjectChanged(cloudFile, localPath);
528
                        if (isChanged)
529
                        {
530
                            //Retrieve the hashmap from the server
531
                            var serverHash = await client.GetHashMap(account, container, url);
532
                            //If it's a small file
533
                            if (serverHash.Hashes.Count == 1)
534
                                //Download it in one go
535
                                await
536
                                    DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath,
537
                                                            serverHash);
538
                            //Otherwise download it block by block
539
                            else
540
                                await
541
                                    DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath,
542
                                                       serverHash);
543

    
544
                            if (cloudFile.AllowedTo == "read")
545
                            {
546
                                var attributes = File.GetAttributes(localPath);
547
                                File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);
548
                            }
549
                        }
550
                    }
551

    
552
                    //Now we can store the object's metadata without worrying about ghost status entries
553
                    StatusKeeper.StoreInfo(localPath, cloudFile);
554

    
555
                }
556
            }
557
        }
558

    
559
        private bool IsObjectChanged(ObjectInfo cloudFile, string localPath)
560
        {
561
            //If the target is a directory, there are no changes to download
562
            if (Directory.Exists(localPath))
563
                return false;
564
            //If the file doesn't exist, we have a chagne
565
            if (!File.Exists(localPath)) 
566
                return true;
567
            //If there is no stored state, we have a change
568
            var localState = StatusKeeper.GetStateByFilePath(localPath);
569
            if (localState == null)
570
                return true;
571

    
572
            var info = new FileInfo(localPath);
573
            var shortHash = info.ComputeShortHash();
574
            //If the file is different from the stored state, we have a change
575
            if (localState.ShortHash != shortHash)
576
                return true;
577
            //If the top hashes differ, we have a change
578
            return (localState.Checksum != cloudFile.Hash);
579
        }
580

    
581
        //Download a small file with a single GET operation
582
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
583
        {
584
            if (client == null)
585
                throw new ArgumentNullException("client");
586
            if (cloudFile==null)
587
                throw new ArgumentNullException("cloudFile");
588
            if (relativeUrl == null)
589
                throw new ArgumentNullException("relativeUrl");
590
            if (String.IsNullOrWhiteSpace(filePath))
591
                throw new ArgumentNullException("filePath");
592
            if (!Path.IsPathRooted(filePath))
593
                throw new ArgumentException("The localPath must be rooted", "filePath");
594
            Contract.EndContractBlock();
595

    
596
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
597
            StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,String.Format("Downloading {0}",Path.GetFileName(localPath)));
598
            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
599

    
600
            var fileAgent = GetFileAgent(accountInfo);
601
            //Calculate the relative file path for the new file
602
            var relativePath = relativeUrl.RelativeUriToFilePath();
603
            //The file will be stored in a temporary location while downloading with an extension .download
604
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
605
            //Make sure the target folder exists. DownloadFileTask will not create the folder
606
            var tempFolder = Path.GetDirectoryName(tempPath);
607
            if (!Directory.Exists(tempFolder))
608
                Directory.CreateDirectory(tempFolder);
609

    
610
            //Download the object to the temporary location
611
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
612

    
613
            //Create the local folder if it doesn't exist (necessary for shared objects)
614
            var localFolder = Path.GetDirectoryName(localPath);
615
            if (!Directory.Exists(localFolder))
616
                try
617
                {
618
                    Directory.CreateDirectory(localFolder);
619
                }
620
                catch (IOException)
621
                {
622
                    //A file may already exist that has the same name as the new folder.
623
                    //This may be an artifact of the way Pithos handles directories
624
                    var fileInfo = new FileInfo(localFolder);
625
                    if (fileInfo.Exists && fileInfo.Length == 0)
626
                    {
627
                        fileInfo.Delete();
628
                        Directory.CreateDirectory(localFolder);
629
                    }
630
                    else 
631
                        throw;
632
                }
633
            //And move it to its actual location once downloading is finished
634
            if (File.Exists(localPath))
635
                File.Replace(tempPath,localPath,null,true);
636
            else
637
                File.Move(tempPath,localPath);
638
            //Notify listeners that a local file has changed
639
            StatusNotification.NotifyChangedFile(localPath);
640

    
641
                       
642
        }
643

    
644
        //Download a file asynchronously using blocks
645
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
646
        {
647
            if (client == null)
648
                throw new ArgumentNullException("client");
649
            if (cloudFile == null)
650
                throw new ArgumentNullException("cloudFile");
651
            if (relativeUrl == null)
652
                throw new ArgumentNullException("relativeUrl");
653
            if (String.IsNullOrWhiteSpace(filePath))
654
                throw new ArgumentNullException("filePath");
655
            if (!Path.IsPathRooted(filePath))
656
                throw new ArgumentException("The filePath must be rooted", "filePath");
657
            if (serverHash == null)
658
                throw new ArgumentNullException("serverHash");
659
            Contract.EndContractBlock();
660
            
661
           var fileAgent = GetFileAgent(accountInfo);
662
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
663
            
664
            //Calculate the relative file path for the new file
665
            var relativePath = relativeUrl.RelativeUriToFilePath();
666
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
667

    
668
            
669
            StatusNotification.SetPithosStatus(PithosStatus.LocalSyncing,String.Format("Calculating hashmap for {0} before download",Path.GetFileName(localPath)));
670
            //Calculate the file's treehash
671
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
672
                
673
            //And compare it with the server's hash
674
            var upHashes = serverHash.GetHashesAsStrings();
675
            var localHashes = treeHash.HashDictionary;
676
            ReportDownloadProgress(Path.GetFileName(localPath),0,upHashes.Length,cloudFile.Bytes);
677
            for (int i = 0; i < upHashes.Length; i++)
678
            {
679
                //For every non-matching hash
680
                var upHash = upHashes[i];
681
                if (!localHashes.ContainsKey(upHash))
682
                {
683
                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
684

    
685
                    if (blockUpdater.UseOrphan(i, upHash))
686
                    {
687
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
688
                        continue;
689
                    }
690
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
691
                    var start = i*serverHash.BlockSize;
692
                    //To download the last block just pass a null for the end of the range
693
                    long? end = null;
694
                    if (i < upHashes.Length - 1 )
695
                        end= ((i + 1)*serverHash.BlockSize) ;
696
                            
697
                    //Download the missing block
698
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
699

    
700
                    //and store it
701
                    blockUpdater.StoreBlock(i, block);
702

    
703

    
704
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
705
                }
706
                ReportDownloadProgress(Path.GetFileName(localPath), i, upHashes.Length, cloudFile.Bytes);
707
            }
708

    
709
            //Want to avoid notifications if no changes were made
710
            var hasChanges = blockUpdater.HasBlocks;
711
            blockUpdater.Commit();
712
            
713
            if (hasChanges)
714
                //Notify listeners that a local file has changed
715
                StatusNotification.NotifyChangedFile(localPath);
716

    
717
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
718
        }
719

    
720

    
721
        private async Task UploadCloudFile(CloudAction action)
722
        {
723
            if (action == null)
724
                throw new ArgumentNullException("action");           
725
            Contract.EndContractBlock();
726
            using(ThreadContext.Stacks["Operation"].Push("UploadCloudFile"))
727
            {
728
                try
729
                {
730

    
731
                    var accountInfo = action.AccountInfo;
732

    
733
                    var fileInfo = action.LocalFile;
734

    
735
                    if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
736
                        return;
737
                    
738
                    //
739
                    if (action.FileState == null)
740
                        action.FileState = StatusKeeper.GetStateByFilePath(fileInfo.FullName);
741
                    if (action.FileState == null)
742
                    {
743
                        Log.WarnFormat("File [{0}] has no local state. It was probably created by a download action",fileInfo.FullName);
744
                        return;
745
                    }
746
                    //Do not upload files in conflict
747
                    if (action.FileState.FileStatus == FileStatus.Conflict )
748
                    {
749
                        Log.InfoFormat("Skipping file in conflict [{0}]",fileInfo.FullName);
750
                        return;
751
                    }
752
                    if (action.FileState.FileStatus == FileStatus.Forbidden)
753
                    {
754
                        Log.InfoFormat("Skipping forbidden file [{0}]",fileInfo.FullName);
755
                        return;
756
                    }
757

    
758
                    var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
759
                    if (relativePath.StartsWith(FolderConstants.OthersFolder))
760
                    {
761
                        var parts = relativePath.Split('\\');
762
                        var accountName = parts[1];
763
                        var oldName = accountInfo.UserName;
764
                        var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
765
                        var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
766
                        var root = absoluteUri.Substring(0, nameIndex);
767

    
768
                        accountInfo = new AccountInfo
769
                                          {
770
                                              UserName = accountName,
771
                                              AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
772
                                              StorageUri = new Uri(root + accountName),
773
                                              BlockHash = accountInfo.BlockHash,
774
                                              BlockSize = accountInfo.BlockSize,
775
                                              Token = accountInfo.Token
776
                                          };
777
                    }
778

    
779

    
780
                    var fullFileName = fileInfo.GetProperCapitalization();
781
                    using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
782
                    {
783
                        //Abort if the file is already being uploaded or downloaded
784
                        if (gate.Failed)
785
                            return;
786

    
787
                        var cloudFile = action.CloudFile;
788
                        var account = cloudFile.Account ?? accountInfo.UserName;
789
                        try
790
                        {
791

    
792
                        var client = new CloudFilesClient(accountInfo);
793
                        //Even if GetObjectInfo times out, we can proceed with the upload            
794
                        var cloudInfo = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
795

    
796
                        //If this is a read-only file, do not upload changes
797
                        if (cloudInfo.AllowedTo == "read")
798
                            return;
799

    
800
                        //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
801
                            if (fileInfo is DirectoryInfo)
802
                            {
803
                                //If the directory doesn't exist the Hash property will be empty
804
                                if (String.IsNullOrWhiteSpace(cloudInfo.Hash))
805
                                    //Go on and create the directory
806
                                    await
807
                                        client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName,
808
                                                         String.Empty, "application/directory");
809
                            }
810
                            else
811
                            {
812

    
813
                                var cloudHash = cloudInfo.Hash.ToLower();
814

    
815
                                StatusNotification.Notify(new StatusNotification(String.Format("Hashing {0} for Upload",fileInfo.Name)));
816

    
817
                                //TODO: This is the same as the calculation for the Local Hash!
818
                                //First, calculate the tree hash
819
/*
820
                                var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
821
                                                                                      accountInfo.BlockHash, 2);
822
*/
823

    
824

    
825
                                var treeHash = action.TreeHash.Value;
826
                                var topHash = treeHash.TopHash.ToHashString();
827
                                
828
                                //var topHash = action.TopHash.Value;
829

    
830
                                //If the file hashes match, abort the upload
831
                                if (topHash == cloudHash /*|| topHash == cloudHash*/)
832
                                {
833
                                    //but store any metadata changes 
834
                                    StatusKeeper.StoreInfo(fullFileName, cloudInfo);
835
                                    Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
836
                                    return;
837
                                }
838

    
839

    
840
                                //Mark the file as modified while we upload it
841
                                StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
842
                                //And then upload it
843

    
844
                                //Upload even small files using the Hashmap. The server may already contain
845
                                //the relevant block
846

    
847
                                //TODO: If the upload fails with a 403, abort it and mark conflict
848

    
849
                                await
850
                                    UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
851
                            }
852
                            //If everything succeeds, change the file and overlay status to normal
853
                            StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
854
                        }
855
                        catch (WebException exc)
856
                        {
857
                            var response=(exc.Response as HttpWebResponse);
858
                            if (response.StatusCode == HttpStatusCode.Forbidden)
859
                            {
860
                                StatusKeeper.SetFileState(fileInfo.FullName,FileStatus.Forbidden, FileOverlayStatus.Conflict);                                
861
                            }
862
                        }
863
                    }
864
                    //Notify the Shell to update the overlays
865
                    NativeMethods.RaiseChangeNotification(fullFileName);
866
                    StatusNotification.NotifyChangedFile(fullFileName);
867
                }
868
                catch (AggregateException ex)
869
                {
870
                    var exc = ex.InnerException as WebException;
871
                    if (exc == null)
872
                        throw ex.InnerException;
873
                    if (HandleUploadWebException(action, exc))
874
                        return;
875
                    throw;
876
                }
877
                catch (WebException ex)
878
                {
879
                    if (HandleUploadWebException(action, ex))
880
                        return;
881
                    throw;
882
                }
883
                catch (Exception ex)
884
                {
885
                    Log.Error("Unexpected error while uploading file", ex);
886
                    throw;
887
                }
888
            }
889
        }
890

    
891

    
892

    
893
        private bool HandleUploadWebException(CloudAction action, WebException exc)
894
        {
895
            var response = exc.Response as HttpWebResponse;
896
            if (response == null)
897
                throw exc;
898
            if (response.StatusCode == HttpStatusCode.Unauthorized)
899
            {
900
                Log.Error("Not allowed to upload file", exc);
901
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
902
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
903
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
904
                return true;
905
            }
906
            return false;
907
        }
908

    
909
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
910
        {
911
            if (accountInfo == null)
912
                throw new ArgumentNullException("accountInfo");
913
            if (cloudFile==null)
914
                throw new ArgumentNullException("cloudFile");
915
            if (fileInfo == null)
916
                throw new ArgumentNullException("fileInfo");
917
            if (String.IsNullOrWhiteSpace(url))
918
                throw new ArgumentNullException(url);
919
            if (treeHash==null)
920
                throw new ArgumentNullException("treeHash");
921
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
922
                throw new ArgumentException("Invalid container","cloudFile");
923
            Contract.EndContractBlock();
924

    
925
            StatusNotification.Notify(new StatusNotification(String.Format("Uploading {0} for Upload", fileInfo.Name)));
926

    
927
            var fullFileName = fileInfo.GetProperCapitalization();
928

    
929
            var account = cloudFile.Account ?? accountInfo.UserName;
930
            var container = cloudFile.Container ;
931

    
932
            var client = new CloudFilesClient(accountInfo);            
933
            //Send the hashmap to the server            
934
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
935
            int block = 0;
936
            ReportUploadProgress(fileInfo.Name,block++, missingHashes.Count, fileInfo.Length);
937
            //If the server returns no missing hashes, we are done
938
            while (missingHashes.Count > 0)
939
            {
940

    
941
                var buffer = new byte[accountInfo.BlockSize];
942
                foreach (var missingHash in missingHashes)
943
                {
944
                    //Find the proper block
945
                    var blockIndex = treeHash.HashDictionary[missingHash];
946
                    var offset = blockIndex*accountInfo.BlockSize;
947

    
948
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
949

    
950
                    try
951
                    {
952
                        //And upload the block                
953
                        await client.PostBlock(account, container, buffer, 0, read);
954
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
955
                    }
956
                    catch (Exception exc)
957
                    {
958
                        Log.Error(String.Format("Uploading block {0} of {1}", blockIndex, fullFileName), exc);
959
                    }
960
                    ReportUploadProgress(fileInfo.Name,block++, missingHashes.Count, fileInfo.Length);
961
                }
962

    
963
                //Repeat until there are no more missing hashes                
964
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
965
            }
966

    
967
            ReportUploadProgress(fileInfo.Name, missingHashes.Count, missingHashes.Count, fileInfo.Length);
968
        }
969

    
970
        private void ReportUploadProgress(string fileName,int block, int totalBlocks, long fileSize)
971
        {
972
            StatusNotification.Notify(totalBlocks == 0
973
                                          ? new ProgressNotification(fileName, "Uploading", 1, 1, fileSize)
974
                                          : new ProgressNotification(fileName, "Uploading", block, totalBlocks, fileSize));
975
        }
976

    
977
        private void ReportDownloadProgress(string fileName,int block, int totalBlocks, long fileSize)
978
        {
979
            StatusNotification.Notify(totalBlocks == 0
980
                                          ? new ProgressNotification(fileName, "Downloading", 1, 1, fileSize)
981
                                          : new ProgressNotification(fileName, "Downloading", block, totalBlocks, fileSize));
982
        }
983
    }
984

    
985
   
986

    
987

    
988
}