Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (37.4 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.Threading;
51
using System.Threading.Tasks;
52
using Castle.ActiveRecord;
53
using Pithos.Interfaces;
54
using Pithos.Network;
55
using log4net;
56

    
57
namespace Pithos.Core.Agents
58
{
59
    [Export]
60
    public class NetworkAgent
61
    {
62
        private Agent<CloudAction> _agent;
63

    
64
        [System.ComponentModel.Composition.Import]
65
        private DeleteAgent _deleteAgent=new DeleteAgent();
66

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

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

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

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

    
82
        public AsyncManualResetEvent ProceedEvent
83
        {
84
            get { return _proceedEvent; }
85
        }
86

    
87

    
88
        public void Start()
89
        {
90
            _agent = Agent<CloudAction>.Start(inbox =>
91
            {
92
                Action loop = null;
93
                loop = () =>
94
                {
95
                    _deleteAgent.ProceedEvent.Wait();
96
                    var message = inbox.Receive();
97
                    var process=message.Then(Process,inbox.CancellationToken);
98
                    inbox.LoopAsync(process, loop);
99
                };
100
                loop();
101
            });
102

    
103
        }
104

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

    
113

    
114

    
115

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

    
120
                var cloudFile = action.CloudFile;
121
                var downloadPath = action.GetDownloadPath();
122

    
123
                try
124
                {
125
                    _proceedEvent.Reset();
126
                    UpdateStatus(PithosStatus.Syncing);
127
                    var accountInfo = action.AccountInfo;
128

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

    
200
                    _agent.Post(action);
201
                }
202
                finally
203
                {
204
                    if (_agent.IsEmpty)
205
                        _proceedEvent.Set();
206
                    UpdateStatus(PithosStatus.InSynch);                                        
207
                }
208
            }
209
        }
210

    
211

    
212
        private void UpdateStatus(PithosStatus status)
213
        {
214
            StatusKeeper.SetPithosStatus(status);
215
            StatusNotification.Notify(new Notification());
216
        }
217

    
218
        private void RenameLocalFile(AccountInfo accountInfo, CloudAction action)
219
        {
220
            if (accountInfo == null)
221
                throw new ArgumentNullException("accountInfo");
222
            if (action == null)
223
                throw new ArgumentNullException("action");
224
            if (action.LocalFile == null)
225
                throw new ArgumentException("The action's local file is not specified", "action");
226
            if (!Path.IsPathRooted(action.LocalFile.FullName))
227
                throw new ArgumentException("The action's local file path must be absolute", "action");
228
            if (action.CloudFile == null)
229
                throw new ArgumentException("The action's cloud file is not specified", "action");
230
            Contract.EndContractBlock();
231

    
232
            //We assume that the local file already exists, otherwise the poll agent
233
            //would have issued a download request
234

    
235
            var currentInfo = action.CloudFile;
236
            var previousInfo = action.CloudFile.Previous;
237
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
238

    
239
            var previousRelativepath = previousInfo.RelativeUrlToFilePath(accountInfo.UserName);
240
            var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
241

    
242
            //In every case we need to move the local file first
243
            MoveLocalFile(accountInfo, previousFile, fileAgent, currentInfo);
244

    
245
        }
246

    
247
        private void MoveLocalFile(AccountInfo accountInfo, FileSystemInfo previousFile, FileAgent fileAgent,
248
                                   ObjectInfo currentInfo)
249
        {
250
            var currentRelativepath = currentInfo.RelativeUrlToFilePath(accountInfo.UserName);
251
            var newPath = Path.Combine(fileAgent.RootPath, currentRelativepath);
252

    
253
            var isFile= (previousFile is FileInfo);
254
            var previousFullPath = isFile? 
255
                FileInfoExtensions.GetProperFilePathCapitalization(previousFile.FullName):
256
                FileInfoExtensions.GetProperDirectoryCapitalization(previousFile.FullName);                
257
            
258
            using (var gateOld = NetworkGate.Acquire(previousFullPath, NetworkOperation.Renaming))
259
            using (var gateNew = NetworkGate.Acquire(newPath,NetworkOperation.Renaming))
260
            using (new SessionScope(FlushAction.Auto))
261
            {
262
                if (isFile)
263
                    (previousFile as FileInfo).MoveTo(newPath);
264
                else
265
                {
266
                    (previousFile as DirectoryInfo).MoveTo(newPath);
267
                }
268
                var state = StatusKeeper.GetStateByFilePath(previousFullPath);
269
                state.FilePath = newPath;
270
                state.SaveCopy();
271
                StatusKeeper.SetFileState(previousFullPath,FileStatus.Deleted,FileOverlayStatus.Deleted);
272
            }            
273
        }
274

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

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

    
293
            var cloudHash = cloudFile.Hash.ToLower();
294
            var previousCloudHash = cloudFile.PreviousHash.ToLower();
295
            var localHash = action.LocalHash.Value.ToLower();
296
            var topHash = action.TopHash.Value.ToLower();
297

    
298
            //At this point we know that an object has changed on the server and that a local
299
            //file already exists. We need to decide whether the file has only changed on 
300
            //the server or there is a conflicting change on the client.
301
            //
302
            
303
            //Not enough to compare only the local hashes (MD5), also have to compare the tophashes            
304
            //If any of the hashes match, we are done
305
            if ((cloudHash == localHash || cloudHash == topHash))
306
            {
307
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
308
                return;
309
            }
310

    
311
            //The hashes DON'T match. We need to sync
312

    
313
            // If the previous tophash matches the local tophash, the file was only changed on the server. 
314
            if (localHash == previousCloudHash)
315
            {
316
                await DownloadCloudFile(accountInfo, cloudFile, downloadPath);
317
            }
318
            else
319
            {
320
                //If the previous and local hash don't match, there was a local conflict
321
                //that was not uploaded to the server. We have a conflict
322
                ReportConflict(downloadPath);
323
            }
324
        }
325

    
326
        private void ReportConflict(string downloadPath)
327
        {
328
            if (String.IsNullOrWhiteSpace(downloadPath))
329
                throw new ArgumentNullException("downloadPath");
330
            Contract.EndContractBlock();
331

    
332
            StatusKeeper.SetFileOverlayStatus(downloadPath, FileOverlayStatus.Conflict);
333
            UpdateStatus(PithosStatus.HasConflicts);
334
            var message = String.Format("Conflict detected for file {0}", downloadPath);
335
            Log.Warn(message);
336
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
337
        }
338

    
339
        public void Post(CloudAction cloudAction)
340
        {
341
            if (cloudAction == null)
342
                throw new ArgumentNullException("cloudAction");
343
            if (cloudAction.AccountInfo==null)
344
                throw new ArgumentException("The CloudAction.AccountInfo is empty","cloudAction");
345
            Contract.EndContractBlock();
346

    
347
            _deleteAgent.ProceedEvent.Wait();
348

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

    
378
        public IEnumerable<CloudAction> GetEnumerable()
379
        {
380
            return _agent.GetEnumerable();
381
        }
382

    
383
        public Task GetDeleteAwaiter()
384
        {
385
            return _deleteAgent.ProceedEvent.WaitAsync();
386
        }
387
        public CancellationToken CancellationToken
388
        {
389
            get { return _agent.CancellationToken; }
390
        }
391

    
392
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
393
        {
394
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
395
        }
396

    
397

    
398

    
399
        private void RenameCloudFile(AccountInfo accountInfo,CloudMoveAction action)
400
        {
401
            if (accountInfo==null)
402
                throw new ArgumentNullException("accountInfo");
403
            if (action==null)
404
                throw new ArgumentNullException("action");
405
            if (action.CloudFile==null)
406
                throw new ArgumentException("CloudFile","action");
407
            if (action.LocalFile==null)
408
                throw new ArgumentException("LocalFile","action");
409
            if (action.OldLocalFile==null)
410
                throw new ArgumentException("OldLocalFile","action");
411
            if (action.OldCloudFile==null)
412
                throw new ArgumentException("OldCloudFile","action");
413
            Contract.EndContractBlock();
414
            
415
            
416
            var newFilePath = action.LocalFile.FullName;
417
            
418
            //How do we handle concurrent renames and deletes/uploads/downloads?
419
            //* A conflicting upload means that a file was renamed before it had a chance to finish uploading
420
            //  This should never happen as the network agent executes only one action at a time
421
            //* A conflicting download means that the file was modified on the cloud. While we can go on and complete
422
            //  the rename, there may be a problem if the file is downloaded in blocks, as subsequent block requests for the 
423
            //  same name will fail.
424
            //  This should never happen as the network agent executes only one action at a time.
425
            //* A conflicting delete can happen if the rename was followed by a delete action that didn't have the chance
426
            //  to remove the rename from the queue.
427
            //  We can probably ignore this case. It will result in an error which should be ignored            
428

    
429
            
430
            //The local file is already renamed
431
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
432

    
433

    
434
            var account = action.CloudFile.Account ?? accountInfo.UserName;
435
            var container = action.CloudFile.Container;
436
            
437
            var client = new CloudFilesClient(accountInfo);
438
            //TODO: What code is returned when the source file doesn't exist?
439
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
440

    
441
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
442
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
443
            NativeMethods.RaiseChangeNotification(newFilePath);
444
        }
445

    
446
        //Download a file.
447
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
448
        {
449
            if (accountInfo == null)
450
                throw new ArgumentNullException("accountInfo");
451
            if (cloudFile == null)
452
                throw new ArgumentNullException("cloudFile");
453
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
454
                throw new ArgumentNullException("cloudFile");
455
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
456
                throw new ArgumentNullException("cloudFile");
457
            if (String.IsNullOrWhiteSpace(filePath))
458
                throw new ArgumentNullException("filePath");
459
            if (!Path.IsPathRooted(filePath))
460
                throw new ArgumentException("The filePath must be rooted", "filePath");
461
            Contract.EndContractBlock();
462
            
463

    
464
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
465
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
466

    
467
            var url = relativeUrl.ToString();
468
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
469
                return;
470

    
471

    
472
            //Are we already downloading or uploading the file? 
473
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
474
            {
475
                if (gate.Failed)
476
                    return;
477
                
478
                var client = new CloudFilesClient(accountInfo);
479
                var account = cloudFile.Account;
480
                var container = cloudFile.Container;
481

    
482
                if (cloudFile.Content_Type == @"application/directory")
483
                {
484
                    if (!Directory.Exists(localPath))
485
                        Directory.CreateDirectory(localPath);
486
                }
487
                else
488
                {                    
489
                    //Retrieve the hashmap from the server
490
                    var serverHash = await client.GetHashMap(account, container, url);
491
                    //If it's a small file
492
                    if (serverHash.Hashes.Count == 1)
493
                        //Download it in one go
494
                        await
495
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
496
                        //Otherwise download it block by block
497
                    else
498
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
499

    
500
                    if (cloudFile.AllowedTo == "read")
501
                    {
502
                        var attributes = File.GetAttributes(localPath);
503
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
504
                    }
505
                }
506

    
507
                //Now we can store the object's metadata without worrying about ghost status entries
508
                StatusKeeper.StoreInfo(localPath, cloudFile);
509
                
510
            }
511
        }
512

    
513
        //Download a small file with a single GET operation
514
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
515
        {
516
            if (client == null)
517
                throw new ArgumentNullException("client");
518
            if (cloudFile==null)
519
                throw new ArgumentNullException("cloudFile");
520
            if (relativeUrl == null)
521
                throw new ArgumentNullException("relativeUrl");
522
            if (String.IsNullOrWhiteSpace(filePath))
523
                throw new ArgumentNullException("filePath");
524
            if (!Path.IsPathRooted(filePath))
525
                throw new ArgumentException("The localPath must be rooted", "filePath");
526
            Contract.EndContractBlock();
527

    
528
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
529
            //If the file already exists
530
            if (File.Exists(localPath))
531
            {
532
                //First check with MD5 as this is a small file
533
                var localMD5 = Signature.CalculateMD5(localPath);
534
                var cloudHash=serverHash.TopHash.ToHashString();
535
                if (localMD5==cloudHash)
536
                    return;
537
                //Then check with a treehash
538
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
539
                var localHash = localTreeHash.TopHash.ToHashString();
540
                if (localHash==cloudHash)
541
                    return;
542
            }
543
            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
544

    
545
            var fileAgent = GetFileAgent(accountInfo);
546
            //Calculate the relative file path for the new file
547
            var relativePath = relativeUrl.RelativeUriToFilePath();
548
            //The file will be stored in a temporary location while downloading with an extension .download
549
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
550
            //Make sure the target folder exists. DownloadFileTask will not create the folder
551
            var tempFolder = Path.GetDirectoryName(tempPath);
552
            if (!Directory.Exists(tempFolder))
553
                Directory.CreateDirectory(tempFolder);
554

    
555
            //Download the object to the temporary location
556
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
557

    
558
            //Create the local folder if it doesn't exist (necessary for shared objects)
559
            var localFolder = Path.GetDirectoryName(localPath);
560
            if (!Directory.Exists(localFolder))
561
                Directory.CreateDirectory(localFolder);            
562
            //And move it to its actual location once downloading is finished
563
            if (File.Exists(localPath))
564
                File.Replace(tempPath,localPath,null,true);
565
            else
566
                File.Move(tempPath,localPath);
567
            //Notify listeners that a local file has changed
568
            StatusNotification.NotifyChangedFile(localPath);
569

    
570
                       
571
        }
572

    
573
        //Download a file asynchronously using blocks
574
        public async Task DownloadWithBlocks(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath, TreeHash serverHash)
575
        {
576
            if (client == null)
577
                throw new ArgumentNullException("client");
578
            if (cloudFile == null)
579
                throw new ArgumentNullException("cloudFile");
580
            if (relativeUrl == null)
581
                throw new ArgumentNullException("relativeUrl");
582
            if (String.IsNullOrWhiteSpace(filePath))
583
                throw new ArgumentNullException("filePath");
584
            if (!Path.IsPathRooted(filePath))
585
                throw new ArgumentException("The filePath must be rooted", "filePath");
586
            if (serverHash == null)
587
                throw new ArgumentNullException("serverHash");
588
            Contract.EndContractBlock();
589
            
590
           var fileAgent = GetFileAgent(accountInfo);
591
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
592
            
593
            //Calculate the relative file path for the new file
594
            var relativePath = relativeUrl.RelativeUriToFilePath();
595
            var blockUpdater = new BlockUpdater(fileAgent.CachePath, localPath, relativePath, serverHash);
596

    
597
            
598
                        
599
            //Calculate the file's treehash
600
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
601
                
602
            //And compare it with the server's hash
603
            var upHashes = serverHash.GetHashesAsStrings();
604
            var localHashes = treeHash.HashDictionary;
605
            for (int i = 0; i < upHashes.Length; i++)
606
            {
607
                //For every non-matching hash
608
                var upHash = upHashes[i];
609
                if (!localHashes.ContainsKey(upHash))
610
                {
611
                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
612

    
613
                    if (blockUpdater.UseOrphan(i, upHash))
614
                    {
615
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
616
                        continue;
617
                    }
618
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
619
                    var start = i*serverHash.BlockSize;
620
                    //To download the last block just pass a null for the end of the range
621
                    long? end = null;
622
                    if (i < upHashes.Length - 1 )
623
                        end= ((i + 1)*serverHash.BlockSize) ;
624
                            
625
                    //Download the missing block
626
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
627

    
628
                    //and store it
629
                    blockUpdater.StoreBlock(i, block);
630

    
631

    
632
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
633
                }
634
            }
635

    
636
            //Want to avoid notifications if no changes were made
637
            var hasChanges = blockUpdater.HasBlocks;
638
            blockUpdater.Commit();
639
            
640
            if (hasChanges)
641
                //Notify listeners that a local file has changed
642
                StatusNotification.NotifyChangedFile(localPath);
643

    
644
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
645
        }
646

    
647

    
648
        private async Task UploadCloudFile(CloudAction action)
649
        {
650
            if (action == null)
651
                throw new ArgumentNullException("action");           
652
            Contract.EndContractBlock();
653

    
654
            try
655
            {                
656
                var accountInfo = action.AccountInfo;
657

    
658
                var fileInfo = action.LocalFile;
659

    
660
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
661
                    return;
662
                
663
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
664
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
665
                {
666
                    var parts = relativePath.Split('\\');
667
                    var accountName = parts[1];
668
                    var oldName = accountInfo.UserName;
669
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
670
                    var nameIndex = absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
671
                    var root = absoluteUri.Substring(0, nameIndex);
672

    
673
                    accountInfo = new AccountInfo
674
                    {
675
                        UserName = accountName,
676
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
677
                        StorageUri = new Uri(root + accountName),
678
                        BlockHash = accountInfo.BlockHash,
679
                        BlockSize = accountInfo.BlockSize,
680
                        Token = accountInfo.Token
681
                    };
682
                }
683

    
684

    
685
                var fullFileName = fileInfo.GetProperCapitalization();
686
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
687
                {
688
                    //Abort if the file is already being uploaded or downloaded
689
                    if (gate.Failed)
690
                        return;
691

    
692
                    var cloudFile = action.CloudFile;
693
                    var account = cloudFile.Account ?? accountInfo.UserName;
694

    
695
                    var client = new CloudFilesClient(accountInfo);                    
696
                    //Even if GetObjectInfo times out, we can proceed with the upload            
697
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
698

    
699
                    //If this is a read-only file, do not upload changes
700
                    if (info.AllowedTo == "read")
701
                        return;
702
                    
703
                    //TODO: Check how a directory hash is calculated -> All dirs seem to have the same hash
704
                    if (fileInfo is DirectoryInfo)
705
                    {
706
                        //If the directory doesn't exist the Hash property will be empty
707
                        if (String.IsNullOrWhiteSpace(info.Hash))
708
                            //Go on and create the directory
709
                            await client.PutObject(account, cloudFile.Container, cloudFile.Name, fullFileName, String.Empty, "application/directory");
710
                    }
711
                    else
712
                    {
713

    
714
                        var cloudHash = info.Hash.ToLower();
715

    
716
                        var hash = action.LocalHash.Value;
717
                        var topHash = action.TopHash.Value;
718

    
719
                        //If the file hashes match, abort the upload
720
                        if (hash == cloudHash || topHash == cloudHash)
721
                        {
722
                            //but store any metadata changes 
723
                            StatusKeeper.StoreInfo(fullFileName, info);
724
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
725
                            return;
726
                        }
727

    
728

    
729
                        //Mark the file as modified while we upload it
730
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
731
                        //And then upload it
732

    
733
                        //Upload even small files using the Hashmap. The server may already contain
734
                        //the relevant block
735

    
736
                        //First, calculate the tree hash
737
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
738
                                                                              accountInfo.BlockHash, 2);
739

    
740
                        await UploadWithHashMap(accountInfo, cloudFile, fileInfo as FileInfo, cloudFile.Name, treeHash);
741
                    }
742
                    //If everything succeeds, change the file and overlay status to normal
743
                    StatusKeeper.SetFileState(fullFileName, FileStatus.Unchanged, FileOverlayStatus.Normal);
744
                }
745
                //Notify the Shell to update the overlays
746
                NativeMethods.RaiseChangeNotification(fullFileName);
747
                StatusNotification.NotifyChangedFile(fullFileName);
748
            }
749
            catch (AggregateException ex)
750
            {
751
                var exc = ex.InnerException as WebException;
752
                if (exc == null)
753
                    throw ex.InnerException;
754
                if (HandleUploadWebException(action, exc)) 
755
                    return;
756
                throw;
757
            }
758
            catch (WebException ex)
759
            {
760
                if (HandleUploadWebException(action, ex))
761
                    return;
762
                throw;
763
            }
764
            catch (Exception ex)
765
            {
766
                Log.Error("Unexpected error while uploading file", ex);
767
                throw;
768
            }
769

    
770
        }
771

    
772

    
773

    
774
        private bool HandleUploadWebException(CloudAction action, WebException exc)
775
        {
776
            var response = exc.Response as HttpWebResponse;
777
            if (response == null)
778
                throw exc;
779
            if (response.StatusCode == HttpStatusCode.Unauthorized)
780
            {
781
                Log.Error("Not allowed to upload file", exc);
782
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
783
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
784
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
785
                return true;
786
            }
787
            return false;
788
        }
789

    
790
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
791
        {
792
            if (accountInfo == null)
793
                throw new ArgumentNullException("accountInfo");
794
            if (cloudFile==null)
795
                throw new ArgumentNullException("cloudFile");
796
            if (fileInfo == null)
797
                throw new ArgumentNullException("fileInfo");
798
            if (String.IsNullOrWhiteSpace(url))
799
                throw new ArgumentNullException(url);
800
            if (treeHash==null)
801
                throw new ArgumentNullException("treeHash");
802
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
803
                throw new ArgumentException("Invalid container","cloudFile");
804
            Contract.EndContractBlock();
805

    
806
            var fullFileName = fileInfo.GetProperCapitalization();
807

    
808
            var account = cloudFile.Account ?? accountInfo.UserName;
809
            var container = cloudFile.Container ;
810

    
811
            var client = new CloudFilesClient(accountInfo);
812
            //Send the hashmap to the server            
813
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
814
            //If the server returns no missing hashes, we are done
815
            while (missingHashes.Count > 0)
816
            {
817

    
818
                var buffer = new byte[accountInfo.BlockSize];
819
                foreach (var missingHash in missingHashes)
820
                {
821
                    //Find the proper block
822
                    var blockIndex = treeHash.HashDictionary[missingHash];
823
                    var offset = blockIndex*accountInfo.BlockSize;
824

    
825
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
826

    
827
                    try
828
                    {
829
                        //And upload the block                
830
                        await client.PostBlock(account, container, buffer, 0, read);
831
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
832
                    }
833
                    catch (Exception exc)
834
                    {
835
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
836
                    }
837

    
838
                }
839

    
840
                //Repeat until there are no more missing hashes                
841
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
842
            }
843
        }
844

    
845

    
846
    }
847

    
848
   
849

    
850

    
851
}