Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (37.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
//TODO: Now there is a UUID tag. This can be used for renames/moves
44

    
45

    
46
using System;
47
using System.Collections.Concurrent;
48
using System.Collections.Generic;
49
using System.ComponentModel.Composition;
50
using System.Diagnostics;
51
using System.Diagnostics.Contracts;
52
using System.IO;
53
using System.Linq;
54
using System.Net;
55
using System.Threading;
56
using System.Threading.Tasks;
57
using System.Threading.Tasks.Dataflow;
58
using Castle.ActiveRecord;
59
using Pithos.Interfaces;
60
using Pithos.Network;
61
using log4net;
62

    
63
namespace Pithos.Core.Agents
64
{
65
    //TODO: Ensure all network operations use exact casing. Pithos is case sensitive
66
    [Export]
67
    public class NetworkAgent
68
    {
69
        private Agent<CloudAction> _agent;
70

    
71
        [System.ComponentModel.Composition.Import]
72
        private DeleteAgent _deleteAgent=new DeleteAgent();
73

    
74
        [System.ComponentModel.Composition.Import]
75
        public IStatusKeeper StatusKeeper { get; set; }
76
        
77
        public IStatusNotification StatusNotification { get; set; }
78

    
79
        private static readonly ILog Log = LogManager.GetLogger("NetworkAgent");
80

    
81
        private readonly ConcurrentBag<AccountInfo> _accounts = new ConcurrentBag<AccountInfo>();
82

    
83
        [System.ComponentModel.Composition.Import]
84
        public IPithosSettings Settings { get; set; }
85

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

    
91
        public AsyncManualResetEvent ProceedEvent
92
        {
93
            get { return _proceedEvent; }
94
        }
95

    
96

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

    
112
        }
113

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

    
122

    
123

    
124

    
125
            using (log4net.ThreadContext.Stacks["NETWORK"].Push("PROCESS"))
126
            {                
127
                Log.InfoFormat("[ACTION] Start Processing {0}", action);
128

    
129
                var cloudFile = action.CloudFile;
130
                var downloadPath = action.GetDownloadPath();
131

    
132
                try
133
                {
134
                    _proceedEvent.Reset();
135
                    UpdateStatus(PithosStatus.Syncing);
136
                    var accountInfo = action.AccountInfo;
137

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

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

    
220

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

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

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

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

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

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

    
254
        }
255

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

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

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

    
298
            var localFile = action.LocalFile;
299
            var cloudFile = action.CloudFile;
300
            var downloadPath=action.LocalFile.GetProperCapitalization();
301

    
302
            var cloudHash = cloudFile.Hash.ToLower();
303
            var previousCloudHash = cloudFile.PreviousHash.ToLower();
304
            var localHash = action.LocalHash.Value.ToLower();
305
            var topHash = action.TopHash.Value.ToLower();
306

    
307
            //At this point we know that an object has changed on the server and that a local
308
            //file already exists. We need to decide whether the file has only changed on 
309
            //the server or there is a conflicting change on the client.
310
            //
311
            
312
            //Not enough to compare only the local hashes (MD5), also have to compare the tophashes            
313
            //If any of the hashes match, we are done
314
            if ((cloudHash == localHash || cloudHash == topHash))
315
            {
316
                Log.InfoFormat("Skipping {0}, hashes match",downloadPath);
317
                return;
318
            }
319

    
320
            //The hashes DON'T match. We need to sync
321

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

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

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

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

    
356
            _deleteAgent.ProceedEvent.Wait();
357

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

    
387
        public IEnumerable<CloudAction> GetEnumerable()
388
        {
389
            return _agent.GetEnumerable();
390
        }
391

    
392
        public Task GetDeleteAwaiter()
393
        {
394
            return _deleteAgent.ProceedEvent.WaitAsync();
395
        }
396
        public CancellationToken CancellationToken
397
        {
398
            get { return _agent.CancellationToken; }
399
        }
400

    
401
        private static FileAgent GetFileAgent(AccountInfo accountInfo)
402
        {
403
            return AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
404
        }
405

    
406

    
407

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

    
438
            
439
            //The local file is already renamed
440
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Modified);
441

    
442

    
443
            var account = action.CloudFile.Account ?? accountInfo.UserName;
444
            var container = action.CloudFile.Container;
445
            
446
            var client = new CloudFilesClient(accountInfo);
447
            //TODO: What code is returned when the source file doesn't exist?
448
            client.MoveObject(account, container, action.OldCloudFile.Name, container, action.CloudFile.Name);
449

    
450
            StatusKeeper.SetFileStatus(newFilePath, FileStatus.Unchanged);
451
            StatusKeeper.SetFileOverlayStatus(newFilePath, FileOverlayStatus.Normal);
452
            NativeMethods.RaiseChangeNotification(newFilePath);
453
        }
454

    
455
        //Download a file.
456
        private async Task DownloadCloudFile(AccountInfo accountInfo, ObjectInfo cloudFile , string filePath)
457
        {
458
            if (accountInfo == null)
459
                throw new ArgumentNullException("accountInfo");
460
            if (cloudFile == null)
461
                throw new ArgumentNullException("cloudFile");
462
            if (String.IsNullOrWhiteSpace(cloudFile.Account))
463
                throw new ArgumentNullException("cloudFile");
464
            if (String.IsNullOrWhiteSpace(cloudFile.Container))
465
                throw new ArgumentNullException("cloudFile");
466
            if (String.IsNullOrWhiteSpace(filePath))
467
                throw new ArgumentNullException("filePath");
468
            if (!Path.IsPathRooted(filePath))
469
                throw new ArgumentException("The filePath must be rooted", "filePath");
470
            Contract.EndContractBlock();
471
            
472

    
473
            var localPath = Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
474
            var relativeUrl = new Uri(cloudFile.Name, UriKind.Relative);
475

    
476
            var url = relativeUrl.ToString();
477
            if (cloudFile.Name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase))
478
                return;
479

    
480

    
481
            //Are we already downloading or uploading the file? 
482
            using (var gate=NetworkGate.Acquire(localPath, NetworkOperation.Downloading))
483
            {
484
                if (gate.Failed)
485
                    return;
486
                
487
                var client = new CloudFilesClient(accountInfo);
488
                var account = cloudFile.Account;
489
                var container = cloudFile.Container;
490

    
491
                if (cloudFile.Content_Type == @"application/directory")
492
                {
493
                    if (!Directory.Exists(localPath))
494
                        Directory.CreateDirectory(localPath);
495
                }
496
                else
497
                {                    
498
                    //Retrieve the hashmap from the server
499
                    var serverHash = await client.GetHashMap(account, container, url);
500
                    //If it's a small file
501
                    if (serverHash.Hashes.Count == 1)
502
                        //Download it in one go
503
                        await
504
                            DownloadEntireFileAsync(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
505
                        //Otherwise download it block by block
506
                    else
507
                        await DownloadWithBlocks(accountInfo, client, cloudFile, relativeUrl, localPath, serverHash);
508

    
509
                    if (cloudFile.AllowedTo == "read")
510
                    {
511
                        var attributes = File.GetAttributes(localPath);
512
                        File.SetAttributes(localPath, attributes | FileAttributes.ReadOnly);                        
513
                    }
514
                }
515

    
516
                //Now we can store the object's metadata without worrying about ghost status entries
517
                StatusKeeper.StoreInfo(localPath, cloudFile);
518
                
519
            }
520
        }
521

    
522
        //Download a small file with a single GET operation
523
        private async Task DownloadEntireFileAsync(AccountInfo accountInfo, CloudFilesClient client, ObjectInfo cloudFile, Uri relativeUrl, string filePath,TreeHash serverHash)
524
        {
525
            if (client == null)
526
                throw new ArgumentNullException("client");
527
            if (cloudFile==null)
528
                throw new ArgumentNullException("cloudFile");
529
            if (relativeUrl == null)
530
                throw new ArgumentNullException("relativeUrl");
531
            if (String.IsNullOrWhiteSpace(filePath))
532
                throw new ArgumentNullException("filePath");
533
            if (!Path.IsPathRooted(filePath))
534
                throw new ArgumentException("The localPath must be rooted", "filePath");
535
            Contract.EndContractBlock();
536

    
537
            var localPath = Pithos.Interfaces.FileInfoExtensions.GetProperFilePathCapitalization(filePath);
538
            //If the file already exists
539
            if (File.Exists(localPath))
540
            {
541
                //First check with MD5 as this is a small file
542
                var localMD5 = Signature.CalculateMD5(localPath);
543
                var cloudHash=serverHash.TopHash.ToHashString();
544
                if (localMD5==cloudHash)
545
                    return;
546
                //Then check with a treehash
547
                var localTreeHash = Signature.CalculateTreeHash(localPath, serverHash.BlockSize, serverHash.BlockHash);
548
                var localHash = localTreeHash.TopHash.ToHashString();
549
                if (localHash==cloudHash)
550
                    return;
551
            }
552
            StatusNotification.Notify(new CloudNotification { Data = cloudFile });
553

    
554
            var fileAgent = GetFileAgent(accountInfo);
555
            //Calculate the relative file path for the new file
556
            var relativePath = relativeUrl.RelativeUriToFilePath();
557
            //The file will be stored in a temporary location while downloading with an extension .download
558
            var tempPath = Path.Combine(fileAgent.CachePath, relativePath + ".download");
559
            //Make sure the target folder exists. DownloadFileTask will not create the folder
560
            var tempFolder = Path.GetDirectoryName(tempPath);
561
            if (!Directory.Exists(tempFolder))
562
                Directory.CreateDirectory(tempFolder);
563

    
564
            //Download the object to the temporary location
565
            await client.GetObject(cloudFile.Account, cloudFile.Container, relativeUrl.ToString(), tempPath);
566

    
567
            //Create the local folder if it doesn't exist (necessary for shared objects)
568
            var localFolder = Path.GetDirectoryName(localPath);
569
            if (!Directory.Exists(localFolder))
570
                Directory.CreateDirectory(localFolder);            
571
            //And move it to its actual location once downloading is finished
572
            if (File.Exists(localPath))
573
                File.Replace(tempPath,localPath,null,true);
574
            else
575
                File.Move(tempPath,localPath);
576
            //Notify listeners that a local file has changed
577
            StatusNotification.NotifyChangedFile(localPath);
578

    
579
                       
580
        }
581

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

    
606
            
607
                        
608
            //Calculate the file's treehash
609
            var treeHash = await Signature.CalculateTreeHashAsync(localPath, serverHash.BlockSize, serverHash.BlockHash, 2);
610
                
611
            //And compare it with the server's hash
612
            var upHashes = serverHash.GetHashesAsStrings();
613
            var localHashes = treeHash.HashDictionary;
614
            for (int i = 0; i < upHashes.Length; i++)
615
            {
616
                //For every non-matching hash
617
                var upHash = upHashes[i];
618
                if (!localHashes.ContainsKey(upHash))
619
                {
620
                    StatusNotification.Notify(new CloudNotification { Data = cloudFile });
621

    
622
                    if (blockUpdater.UseOrphan(i, upHash))
623
                    {
624
                        Log.InfoFormat("[BLOCK GET] ORPHAN FOUND for {0} of {1} for {2}", i, upHashes.Length, localPath);
625
                        continue;
626
                    }
627
                    Log.InfoFormat("[BLOCK GET] START {0} of {1} for {2}", i, upHashes.Length, localPath);
628
                    var start = i*serverHash.BlockSize;
629
                    //To download the last block just pass a null for the end of the range
630
                    long? end = null;
631
                    if (i < upHashes.Length - 1 )
632
                        end= ((i + 1)*serverHash.BlockSize) ;
633
                            
634
                    //Download the missing block
635
                    var block = await client.GetBlock(cloudFile.Account, cloudFile.Container, relativeUrl, start, end);
636

    
637
                    //and store it
638
                    blockUpdater.StoreBlock(i, block);
639

    
640

    
641
                    Log.InfoFormat("[BLOCK GET] FINISH {0} of {1} for {2}", i, upHashes.Length, localPath);
642
                }
643
            }
644

    
645
            //Want to avoid notifications if no changes were made
646
            var hasChanges = blockUpdater.HasBlocks;
647
            blockUpdater.Commit();
648
            
649
            if (hasChanges)
650
                //Notify listeners that a local file has changed
651
                StatusNotification.NotifyChangedFile(localPath);
652

    
653
            Log.InfoFormat("[BLOCK GET] COMPLETE {0}", localPath);            
654
        }
655

    
656

    
657
        private async Task UploadCloudFile(CloudAction action)
658
        {
659
            if (action == null)
660
                throw new ArgumentNullException("action");           
661
            Contract.EndContractBlock();
662

    
663
            try
664
            {                
665
                var accountInfo = action.AccountInfo;
666

    
667
                var fileInfo = action.LocalFile;
668

    
669
                if (fileInfo.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase))
670
                    return;
671
                
672
                var relativePath = fileInfo.AsRelativeTo(accountInfo.AccountPath);
673
                if (relativePath.StartsWith(FolderConstants.OthersFolder))
674
                {
675
                    var parts = relativePath.Split('\\');
676
                    var accountName = parts[1];
677
                    var oldName = accountInfo.UserName;
678
                    var absoluteUri = accountInfo.StorageUri.AbsoluteUri;
679
                    var nameIndex = absoluteUri.IndexOf(oldName);
680
                    var root = absoluteUri.Substring(0, nameIndex);
681

    
682
                    accountInfo = new AccountInfo
683
                    {
684
                        UserName = accountName,
685
                        AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
686
                        StorageUri = new Uri(root + accountName),
687
                        BlockHash = accountInfo.BlockHash,
688
                        BlockSize = accountInfo.BlockSize,
689
                        Token = accountInfo.Token
690
                    };
691
                }
692

    
693

    
694
                var fullFileName = fileInfo.GetProperCapitalization();
695
                using (var gate = NetworkGate.Acquire(fullFileName, NetworkOperation.Uploading))
696
                {
697
                    //Abort if the file is already being uploaded or downloaded
698
                    if (gate.Failed)
699
                        return;
700

    
701
                    var cloudFile = action.CloudFile;
702
                    var account = cloudFile.Account ?? accountInfo.UserName;
703

    
704
                    var client = new CloudFilesClient(accountInfo);                    
705
                    //Even if GetObjectInfo times out, we can proceed with the upload            
706
                    var info = client.GetObjectInfo(account, cloudFile.Container, cloudFile.Name);
707

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

    
723
                        var cloudHash = info.Hash.ToLower();
724

    
725
                        var hash = action.LocalHash.Value;
726
                        var topHash = action.TopHash.Value;
727

    
728
                        //If the file hashes match, abort the upload
729
                        if (hash == cloudHash || topHash == cloudHash)
730
                        {
731
                            //but store any metadata changes 
732
                            StatusKeeper.StoreInfo(fullFileName, info);
733
                            Log.InfoFormat("Skip upload of {0}, hashes match", fullFileName);
734
                            return;
735
                        }
736

    
737

    
738
                        //Mark the file as modified while we upload it
739
                        StatusKeeper.SetFileOverlayStatus(fullFileName, FileOverlayStatus.Modified);
740
                        //And then upload it
741

    
742
                        //Upload even small files using the Hashmap. The server may already contain
743
                        //the relevant block
744

    
745
                        //First, calculate the tree hash
746
                        var treeHash = await Signature.CalculateTreeHashAsync(fullFileName, accountInfo.BlockSize,
747
                                                                              accountInfo.BlockHash, 2);
748

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

    
779
        }
780

    
781

    
782

    
783
        private bool HandleUploadWebException(CloudAction action, WebException exc)
784
        {
785
            var response = exc.Response as HttpWebResponse;
786
            if (response == null)
787
                throw exc;
788
            if (response.StatusCode == HttpStatusCode.Unauthorized)
789
            {
790
                Log.Error("Not allowed to upload file", exc);
791
                var message = String.Format("Not allowed to uplad file {0}", action.LocalFile.FullName);
792
                StatusKeeper.SetFileState(action.LocalFile.FullName, FileStatus.Unchanged, FileOverlayStatus.Normal);
793
                StatusNotification.NotifyChange(message, TraceLevel.Warning);
794
                return true;
795
            }
796
            return false;
797
        }
798

    
799
        public async Task UploadWithHashMap(AccountInfo accountInfo,ObjectInfo cloudFile,FileInfo fileInfo,string url,TreeHash treeHash)
800
        {
801
            if (accountInfo == null)
802
                throw new ArgumentNullException("accountInfo");
803
            if (cloudFile==null)
804
                throw new ArgumentNullException("cloudFile");
805
            if (fileInfo == null)
806
                throw new ArgumentNullException("fileInfo");
807
            if (String.IsNullOrWhiteSpace(url))
808
                throw new ArgumentNullException(url);
809
            if (treeHash==null)
810
                throw new ArgumentNullException("treeHash");
811
            if (String.IsNullOrWhiteSpace(cloudFile.Container) )
812
                throw new ArgumentException("Invalid container","cloudFile");
813
            Contract.EndContractBlock();
814

    
815
            var fullFileName = fileInfo.GetProperCapitalization();
816

    
817
            var account = cloudFile.Account ?? accountInfo.UserName;
818
            var container = cloudFile.Container ;
819

    
820
            var client = new CloudFilesClient(accountInfo);
821
            //Send the hashmap to the server            
822
            var missingHashes =  await client.PutHashMap(account, container, url, treeHash);
823
            //If the server returns no missing hashes, we are done
824
            while (missingHashes.Count > 0)
825
            {
826

    
827
                var buffer = new byte[accountInfo.BlockSize];
828
                foreach (var missingHash in missingHashes)
829
                {
830
                    //Find the proper block
831
                    var blockIndex = treeHash.HashDictionary[missingHash];
832
                    var offset = blockIndex*accountInfo.BlockSize;
833

    
834
                    var read = fileInfo.Read(buffer, offset, accountInfo.BlockSize);
835

    
836
                    try
837
                    {
838
                        //And upload the block                
839
                        await client.PostBlock(account, container, buffer, 0, read);
840
                        Log.InfoFormat("[BLOCK] Block {0} of {1} uploaded", blockIndex, fullFileName);
841
                    }
842
                    catch (Exception exc)
843
                    {
844
                        Log.ErrorFormat("[ERROR] uploading block {0} of {1}\n{2}", blockIndex, fullFileName, exc);
845
                    }
846

    
847
                }
848

    
849
                //Repeat until there are no more missing hashes                
850
                missingHashes = await client.PutHashMap(account, container, url, treeHash);
851
            }
852
        }
853

    
854

    
855
        public void AddAccount(AccountInfo accountInfo)
856
        {            
857
            if (!_accounts.Contains(accountInfo))
858
                _accounts.Add(accountInfo);
859
        }
860
    }
861

    
862
   
863

    
864

    
865
}