Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / PollAgent.cs @ c945b450

History | View | Annotate | Download (46.1 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PollAgent.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.Collections.Concurrent;
44
using System.ComponentModel.Composition;
45
using System.Diagnostics;
46
using System.Diagnostics.Contracts;
47
using System.IO;
48
using System.Linq.Expressions;
49
using System.Reflection;
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
    using System;
60
    using System.Collections.Generic;
61
    using System.Linq;
62

    
63
    [DebuggerDisplay("{FilePath} C:{C} L:{L} S:{S}")]
64
    public class StateTuple
65
    {
66
        public string FilePath { get; private set; }
67

    
68
        public string L
69
        {
70
            get { return FileState==null?null:FileState.Checksum; }
71
        }
72

    
73
        public string C { get; set; }
74

    
75
        public string S
76
        {
77
            get { return ObjectInfo== null ? null : ObjectInfo.Hash; }
78
        }
79

    
80
        private FileSystemInfo _fileInfo;
81
        public FileSystemInfo FileInfo
82
        {
83
            get { return _fileInfo; }
84
            set
85
            {
86
                _fileInfo = value;
87
                FilePath = value.FullName;
88
            }
89
        }
90

    
91
        public FileState FileState { get; set; }
92
        public ObjectInfo ObjectInfo{ get; set; }
93

    
94
        public StateTuple() { }
95

    
96
        public StateTuple(FileSystemInfo info)
97
        {
98
            FileInfo = info;
99
        }
100

    
101

    
102
    }
103

    
104

    
105
    /// <summary>
106
    /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all
107
    /// objects and compares it with a previously cached version to detect differences. 
108
    /// New files are downloaded, missing files are deleted from the local file system and common files are compared
109
    /// to determine the appropriate action
110
    /// </summary>
111
    [Export]
112
    public class PollAgent
113
    {
114
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
115

    
116
        [System.ComponentModel.Composition.Import]
117
        public IStatusKeeper StatusKeeper { get; set; }
118

    
119
        [System.ComponentModel.Composition.Import]
120
        public IPithosSettings Settings { get; set; }
121

    
122
        [System.ComponentModel.Composition.Import]
123
        public NetworkAgent NetworkAgent { get; set; }
124

    
125
        [System.ComponentModel.Composition.Import]
126
        public Selectives Selectives { get; set; }
127

    
128
        public IStatusNotification StatusNotification { get; set; }
129

    
130
        private CancellationTokenSource _currentOperationCancellation = new CancellationTokenSource();
131

    
132
        public void CancelCurrentOperation()
133
        {
134
            //What does it mean to cancel the current upload/download?
135
            //Obviously, the current operation will be cancelled by throwing
136
            //a cancellation exception.
137
            //
138
            //The default behavior is to retry any operations that throw.
139
            //Obviously this is not what we want in this situation.
140
            //The cancelled operation should NOT bea retried. 
141
            //
142
            //This can be done by catching the cancellation exception
143
            //and avoiding the retry.
144
            //
145

    
146
            //Have to reset the cancellation source - it is not possible to reset the source
147
            //Have to prevent a case where an operation requests a token from the old source
148
            var oldSource = Interlocked.Exchange(ref _currentOperationCancellation, new CancellationTokenSource());
149
            oldSource.Cancel();
150

    
151
        }
152

    
153
        public bool Pause
154
        {
155
            get {
156
                return _pause;
157
            }
158
            set {
159
                _pause = value;                
160
                if (!_pause)
161
                    _unPauseEvent.Set();
162
                else
163
                {
164
                    _unPauseEvent.Reset();
165
                }
166
            }
167
        }
168

    
169
        private bool _firstPoll = true;
170

    
171
        //The Sync Event signals a manual synchronisation
172
        private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
173

    
174
        private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
175

    
176
        private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
177
        private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();
178

    
179

    
180
        /// <summary>
181
        /// Start a manual synchronization
182
        /// </summary>
183
        public void SynchNow()
184
        {            
185
            _syncEvent.Set();
186
        }
187

    
188

    
189
        /// <summary>
190
        /// Remote files are polled periodically. Any changes are processed
191
        /// </summary>
192
        /// <param name="since"></param>
193
        /// <returns></returns>
194
        public async Task PollRemoteFiles(DateTime? since = null)
195
        {
196
            if (Log.IsDebugEnabled)
197
                Log.DebugFormat("Polling changes after [{0}]",since);
198

    
199
            Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");
200

    
201
            //GC.Collect();
202

    
203
            using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
204
            {
205
                //If this poll fails, we will retry with the same since value
206
                var nextSince = since;
207
                try
208
                {
209
                    await _unPauseEvent.WaitAsync();
210
                    UpdateStatus(PithosStatus.PollSyncing);
211

    
212
                    var tasks = from accountInfo in _accounts.Values
213
                                select ProcessAccountFiles(accountInfo, since);
214

    
215
                    var nextTimes=await TaskEx.WhenAll(tasks.ToList());
216

    
217
                    _firstPoll = false;
218
                    //Reschedule the poll with the current timestamp as a "since" value
219

    
220
                    if (nextTimes.Length>0)
221
                        nextSince = nextTimes.Min();
222
                    if (Log.IsDebugEnabled)
223
                        Log.DebugFormat("Next Poll at [{0}]",nextSince);
224
                }
225
                catch (Exception ex)
226
                {
227
                    Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);
228
                    //In case of failure retry with the same "since" value
229
                }
230

    
231
                UpdateStatus(PithosStatus.PollComplete);
232
                //The multiple try blocks are required because we can't have an await call
233
                //inside a finally block
234
                //TODO: Find a more elegant solution for reschedulling in the event of an exception
235
                try
236
                {
237
                    //Wait for the polling interval to pass or the Sync event to be signalled
238
                    nextSince = await WaitForScheduledOrManualPoll(nextSince);
239
                }
240
                finally
241
                {
242
                    //Ensure polling is scheduled even in case of error
243
                    TaskEx.Run(() => PollRemoteFiles(nextSince));                        
244
                }
245
            }
246
        }
247

    
248
        /// <summary>
249
        /// Wait for the polling period to expire or a manual sync request
250
        /// </summary>
251
        /// <param name="since"></param>
252
        /// <returns></returns>
253
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
254
        {
255
            var sync = _syncEvent.WaitAsync();
256
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken);
257
            
258
            var signaledTask = await TaskEx.WhenAny(sync, wait);
259
            
260
            //Pausing takes precedence over manual sync or awaiting
261
            _unPauseEvent.Wait();
262
            
263
            //Wait for network processing to finish before polling
264
            var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
265
            await TaskEx.WhenAll(signaledTask, pauseTask);
266

    
267
            //If polling is signalled by SynchNow, ignore the since tag
268
            if (sync.IsCompleted)
269
            {
270
                //TODO: Must convert to AutoReset
271
                _syncEvent.Reset();
272
                return null;
273
            }
274
            return since;
275
        }
276

    
277
        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)
278
        {
279
            if (accountInfo == null)
280
                throw new ArgumentNullException("accountInfo");
281
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
282
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
283
            Contract.EndContractBlock();
284

    
285

    
286
            using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
287
            {
288

    
289
                await NetworkAgent.GetDeleteAwaiter();
290

    
291
                Log.Info("Scheduled");
292
                var client = new CloudFilesClient(accountInfo);
293

    
294
                //We don't need to check the trash container
295
                var containers = client.ListContainers(accountInfo.UserName)
296
                    .Where(c=>c.Name!="trash")
297
                    .ToList();
298

    
299

    
300
                CreateContainerFolders(accountInfo, containers);
301

    
302
                //The nextSince time fallback time is the same as the current.
303
                //If polling succeeds, the next Since time will be the smallest of the maximum modification times
304
                //of the shared and account objects
305
                var nextSince = since;
306

    
307
                try
308
                {
309
                    //Wait for any deletions to finish
310
                    await NetworkAgent.GetDeleteAwaiter();
311
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
312
                    //than delete a file that was created while we were executing the poll                    
313

    
314
                    //Get the list of server objects changed since the last check
315
                    //The name of the container is passed as state in order to create a dictionary of tasks in a subsequent step
316
                    var listObjects = (from container in containers
317
                                       select Task<IList<ObjectInfo>>.Factory.StartNew(_ =>
318
                                             client.ListObjects(accountInfo.UserName, container.Name, since), container.Name)).ToList();
319

    
320
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => 
321
                        client.ListSharedObjects(since), "shared");
322
                    listObjects.Add(listShared);
323
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
324

    
325
                    using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
326
                    {
327
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
328

    
329
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
330
                        var remoteObjects = (from objectList in listTasks
331
                                            where (string)objectList.AsyncState != "trash"
332
                                            from obj in objectList.Result
333
                                            orderby obj.Bytes ascending 
334
                                            select obj).ToList();
335
                        
336
                        //Get the latest remote object modification date, only if it is after
337
                        //the original since date
338
                        nextSince = GetLatestDateAfter(nextSince, remoteObjects);
339

    
340
                        var sharedObjects = dict["shared"].Result;
341
                        nextSince = GetLatestDateBefore(nextSince, sharedObjects);
342

    
343
                        //DON'T process trashed files
344
                        //If some files are deleted and added again to a folder, they will be deleted
345
                        //even though they are new.
346
                        //We would have to check file dates and hashes to ensure that a trashed file
347
                        //can be deleted safely from the local hard drive.
348
                        /*
349
                        //Items with the same name, hash may be both in the container and the trash
350
                        //Don't delete items that exist in the container
351
                        var realTrash = from trash in trashObjects
352
                                        where
353
                                            !remoteObjects.Any(
354
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
355
                                        select trash;
356
                        ProcessTrashedFiles(accountInfo, realTrash);
357
*/
358

    
359
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
360
                                            let name = info.Name??""
361
                                            where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
362
                                                  !name.StartsWith(FolderConstants.CacheFolder + "/",
363
                                                                   StringComparison.InvariantCultureIgnoreCase)
364
                                            select info).ToList();
365

    
366
                        if (_firstPoll)
367
                            StatusKeeper.CleanupOrphanStates();
368
                        StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes);
369
                        
370
                        //var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
371

    
372
                        var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey];
373

    
374

    
375
                        //Get the local files here                        
376
                        var agent = AgentLocator<FileAgent>.Get(accountInfo.AccountPath);
377

    
378
                        var files = LoadLocalFileTuples(accountInfo);
379

    
380
                        var states = FileState.Queryable.ToList();
381

    
382
                        var infos = (from remote in cleanRemotes
383
                                    let path = remote.RelativeUrlToFilePath(accountInfo.UserName)
384
                                    let info=agent.GetFileSystemInfo(path)
385
                                    select Tuple.Create(info.FullName,remote))
386
                                    .ToList();
387

    
388
                        var token = _currentOperationCancellation.Token;
389

    
390
                        var tuples = MergeSources(infos, files, states).ToList();
391

    
392
                        
393
                        foreach (var tuple in tuples)
394
                        {
395
                            await _unPauseEvent.WaitAsync();
396
                            
397
                            SyncSingleItem(accountInfo, tuple, agent, token);
398
                        }
399

    
400

    
401
                        //On the first run
402
/*
403
                        if (_firstPoll)
404
                        {
405
                            MarkSuspectedDeletes(accountInfo, cleanRemotes);
406
                        }
407
*/
408

    
409

    
410
                        Log.Info("[LISTENER] End Processing");
411
                    }
412
                }
413
                catch (Exception ex)
414
                {
415
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
416
                    return nextSince;
417
                }
418

    
419
                Log.Info("[LISTENER] Finished");
420
                return nextSince;
421
            }
422
        }
423

    
424
        private static List<Tuple<FileSystemInfo, string>> LoadLocalFileTuples(AccountInfo accountInfo)
425
        {
426
            using (ThreadContext.Stacks["Account Files Hashing"].Push(accountInfo.UserName))
427
            {
428

    
429
                var localInfos = AgentLocator<FileAgent>.Get(accountInfo.AccountPath).EnumerateFileSystemInfos();
430
                //Use the queue to retry locked file hashing
431
                var fileQueue = new Queue<FileSystemInfo>(localInfos);
432

    
433
                var results = new List<Tuple<FileSystemInfo, string>>();
434

    
435
                while (fileQueue.Count > 0)
436
                {
437
                    var file = fileQueue.Dequeue();
438
                    using (ThreadContext.Stacks["File"].Push(file.FullName))
439
                    {
440
                        try
441
                        {
442
                            var hash = (file is DirectoryInfo)
443
                                           ? "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
444
                                           : Signature.CalculateTreeHash(file, accountInfo.BlockSize,
445
                                                                         accountInfo.BlockHash)
446
                                                 .
447
                                                 TopHash.ToHashString();
448
                            results.Add(Tuple.Create(file, hash));
449
                        }
450
                        catch (IOException exc)
451
                        {
452
                            Log.WarnFormat("[HASH] File in use, will retry [{0}]", exc);
453
                            fileQueue.Enqueue(file);
454
                        }
455
                    }
456
                }
457

    
458
                return results;
459
            }
460
        }
461

    
462
        private void SyncSingleItem(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)
463
        {
464
            Log.DebugFormat("Sync [{0}] C:[{1}] L:[{2}] S:[{3}]",tuple.FilePath,tuple.C,tuple.L,tuple.S);
465

    
466
            var localFilePath = tuple.FilePath;
467
            //Don't use the tuple info, it may have been deleted
468
            var localInfo = FileInfoExtensions.FromPath(localFilePath);
469

    
470
            // Local file unchanged? If both C and L are null, make sure it's because 
471
            //both the file is missing and the state checksum is not missing
472
            if (tuple.C == tuple.L && (localInfo.Exists || tuple.FileState==null))
473
            {
474
                //No local changes
475
                //Server unchanged?
476
                if (tuple.S == tuple.L)
477
                {
478
                    // No server changes
479
                    ;
480
                }
481
                else
482
                {
483
                    //Different from server
484
                    if (Selectives.IsSelected(accountInfo, localFilePath))
485
                    {
486
                        //Does the server file exist?
487
                        if (tuple.S == null)
488
                        {
489
                            //Server file doesn't exist
490
                            //deleteObjectFromLocal()
491
                            StatusKeeper.SetFileState(localFilePath, FileStatus.Deleted,
492
                                                      FileOverlayStatus.Deleted, "");
493
                            agent.Delete(localFilePath);
494
                            //updateRecord(Remove C, L)
495
                            StatusKeeper.ClearFileStatus(localFilePath);
496
                        }
497
                        else
498
                        {
499
                            //Server file exists
500
                            //downloadServerObject() // Result: L = S
501
                            StatusKeeper.SetFileState(localFilePath, FileStatus.Modified,
502
                                                      FileOverlayStatus.Modified, "");
503
                            NetworkAgent.Downloader.DownloadCloudFile(accountInfo,
504
                                                                            tuple.ObjectInfo,
505
                                                                            localFilePath, token).Wait(token);
506
                            //updateRecord( L = S )
507
                            StatusKeeper.UpdateFileChecksum(localFilePath, tuple.FileState==null?"":tuple.FileState.ShortHash,
508
                                                            tuple.ObjectInfo.Hash);
509

    
510
                            StatusKeeper.SetFileState(localFilePath, FileStatus.Unchanged,
511
                                                      FileOverlayStatus.Normal, "");
512
                        }
513
                    }
514
                }
515
            }
516
            else
517
            {
518
                //Local changes found
519

    
520
                //Server unchanged?
521
                if (tuple.S == tuple.L)
522
                {
523
                    //The FileAgent selective sync checks for new root folder files
524
                    if (!agent.Ignore(localFilePath))
525
                    {
526
                        if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null)
527
                        {
528
                            //deleteObjectFromServer()
529
                            DeleteCloudFile(accountInfo, tuple);
530
                            //updateRecord( Remove L, S)                  
531
                        }
532
                        else
533
                        {
534
                            //uploadLocalObject() // Result: S = C, L = S                        
535
                            var isUnselected = agent.IsUnselectedRootFolder(tuple.FilePath);
536

    
537
                            //Debug.Assert(tuple.FileState !=null);
538
                            var action = new CloudUploadAction(accountInfo, localInfo, tuple.FileState,
539
                                                               accountInfo.BlockSize, accountInfo.BlockHash,
540
                                                               "Poll", isUnselected);
541
                            NetworkAgent.Uploader.UploadCloudFile(action, token).Wait(token);
542

    
543

    
544
                            //updateRecord( S = C )
545
                            StatusKeeper.SetFileState(localFilePath, FileStatus.Unchanged,
546
                                                      FileOverlayStatus.Normal, "");
547
                            if (isUnselected)
548
                            {
549
                                ProcessChildren(accountInfo, tuple, agent, token);
550
                            }
551
                        }
552
                    }
553
                }
554
                else
555
                {
556
                    if (Selectives.IsSelected(accountInfo, localFilePath))
557
                    {
558
                        if (tuple.C == tuple.S)
559
                        {
560
                            // (Identical Changes) Result: L = S
561
                            //doNothing()
562
                            StatusKeeper.UpdateFileChecksum(localFilePath, tuple.FileState == null ? "" : tuple.FileState.ShortHash,
563
                                                            tuple.ObjectInfo.Hash);
564
                            StatusKeeper.SetFileState(localFilePath, FileStatus.Unchanged,
565
                                                      FileOverlayStatus.Normal, "");
566
                        }
567
                        else
568
                        {
569
                            if ((tuple.C == null || !localInfo.Exists) && tuple.ObjectInfo != null )
570
                            {
571
                                //deleteObjectFromServer()
572
                                DeleteCloudFile(accountInfo, tuple);
573
                                //updateRecord(Remove L, S)                  
574
                            }
575
                            else
576
                            {
577
                                ReportConflictForMismatch(localFilePath);
578
                                //identifyAsConflict() // Manual action required
579
                            }
580
                        }
581
                    }
582
                }
583
            }
584
        }
585

    
586
        private void DeleteCloudFile(AccountInfo accountInfo, StateTuple tuple)
587
        {
588
            StatusKeeper.SetFileState(tuple.FilePath, FileStatus.Deleted,
589
                                      FileOverlayStatus.Deleted, "");
590
            NetworkAgent.DeleteAgent.DeleteCloudFile(accountInfo, tuple.ObjectInfo);
591
            StatusKeeper.ClearFileStatus(tuple.FilePath);
592
        }
593

    
594
        private void ProcessChildren(AccountInfo accountInfo, StateTuple tuple, FileAgent agent, CancellationToken token)
595
        {
596

    
597
            var dirInfo = tuple.FileInfo as DirectoryInfo;
598
            var folderTuples = from folder in dirInfo.EnumerateDirectories("*", SearchOption.AllDirectories)
599
                               select new StateTuple(folder);
600
            var fileTuples = from file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories)
601
                             select new StateTuple(file);
602
            
603
            //Process folders first, to ensure folders appear on the sever as soon as possible
604
            folderTuples.ApplyAction(t => SyncSingleItem(accountInfo, t, agent, token));
605
            
606
            fileTuples.ApplyAction(t => SyncSingleItem(accountInfo, t, agent, token));
607
        }
608

    
609
        private static IEnumerable<StateTuple> MergeSources(
610
            IEnumerable<Tuple<string, ObjectInfo>> infos, 
611
            IEnumerable<Tuple<FileSystemInfo, string>> files, 
612
            IEnumerable<FileState> states)
613
        {
614
            var dct = new Dictionary<string, StateTuple>();
615
            foreach (var file in files)
616
            {
617
                var fsInfo = file.Item1;
618
                var fileHash = file.Item2;
619
                dct[fsInfo.FullName] = new StateTuple {FileInfo = fsInfo, C = fileHash};
620
            }
621
            foreach (var state in states)
622
            {
623
                StateTuple hashTuple;
624
                if (dct.TryGetValue(state.FilePath, out hashTuple))
625
                {
626
                    hashTuple.FileState = state;
627
                }
628
                else
629
                {
630
                    var fsInfo = FileInfoExtensions.FromPath(state.FilePath);
631
                    dct[state.FilePath] = new StateTuple {FileInfo = fsInfo, FileState = state};
632
                }
633
            }
634
            foreach (var info in infos)
635
            {
636
                StateTuple hashTuple;
637
                var filePath = info.Item1;
638
                var objectInfo = info.Item2;
639
                if (dct.TryGetValue(filePath, out hashTuple))
640
                {
641
                    hashTuple.ObjectInfo = objectInfo;
642
                }
643
                else
644
                {
645
                    var fsInfo = FileInfoExtensions.FromPath(filePath);
646
                    dct[filePath] = new StateTuple {FileInfo = fsInfo, ObjectInfo = objectInfo};
647
                }
648
            }
649
            return dct.Values;
650
        }
651

    
652
        /// <summary>
653
        /// Returns the latest LastModified date from the list of objects, but only if it is before
654
        /// than the threshold value
655
        /// </summary>
656
        /// <param name="threshold"></param>
657
        /// <param name="cloudObjects"></param>
658
        /// <returns></returns>
659
        private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)
660
        {
661
            DateTime? maxDate = null;
662
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
663
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
664
            if (maxDate == null || maxDate == DateTime.MinValue)
665
                return threshold;
666
            if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)
667
                return maxDate;
668
            return threshold;
669
        }
670

    
671
        /// <summary>
672
        /// Returns the latest LastModified date from the list of objects, but only if it is after
673
        /// the threshold value
674
        /// </summary>
675
        /// <param name="threshold"></param>
676
        /// <param name="cloudObjects"></param>
677
        /// <returns></returns>
678
        private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)
679
        {
680
            DateTime? maxDate = null;
681
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
682
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
683
            if (maxDate == null || maxDate == DateTime.MinValue)
684
                return threshold;
685
            if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)
686
                return maxDate;
687
            return threshold;
688
        }
689

    
690
        //readonly AccountsDifferencer _differencer = new AccountsDifferencer();
691
        private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();
692
        private bool _pause;
693

    
694
        /// <summary>
695
        /// Deletes local files that are not found in the list of cloud files
696
        /// </summary>
697
        /// <param name="accountInfo"></param>
698
        /// <param name="cloudFiles"></param>
699
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
700
        {
701
            if (accountInfo == null)
702
                throw new ArgumentNullException("accountInfo");
703
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
704
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
705
            if (cloudFiles == null)
706
                throw new ArgumentNullException("cloudFiles");
707
            Contract.EndContractBlock();
708

    
709
            var deletedFiles = new List<FileSystemInfo>();
710
            foreach (var objectInfo in cloudFiles)
711
            {
712
                if (Log.IsDebugEnabled)
713
                    Log.DebugFormat("Handle deleted [{0}]", objectInfo.Uri);
714
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
715
                var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
716
                if (Log.IsDebugEnabled)
717
                    Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName, objectInfo.Uri);
718
                if (item.Exists)
719
                {
720
                    if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
721
                    {
722
                        item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
723

    
724
                    }
725

    
726

    
727
                    Log.DebugFormat("Deleting {0}", item.FullName);
728

    
729
                    var directory = item as DirectoryInfo;
730
                    if (directory != null)
731
                        directory.Delete(true);
732
                    else
733
                        item.Delete();
734
                    Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);
735
                    DateTime lastDate;
736
                    _lastSeen.TryRemove(item.FullName, out lastDate);
737
                    deletedFiles.Add(item);
738
                }
739
                StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");
740
            }
741
            Log.InfoFormat("[{0}] files were deleted", deletedFiles.Count);
742
            StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count),
743
                                              TraceLevel.Info);
744

    
745
        }
746

    
747
        private void MarkSuspectedDeletes(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
748
        {
749
//Only consider files that are not being modified, ie they are in the Unchanged state            
750
            var deleteCandidates = FileState.Queryable.Where(state =>
751
                                                             state.FilePath.StartsWith(accountInfo.AccountPath)
752
                                                             && state.FileStatus == FileStatus.Unchanged).ToList();
753

    
754

    
755
            //TODO: filesToDelete must take into account the Others container            
756
            var filesToDelete = (from deleteCandidate in deleteCandidates
757
                                 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
758
                                 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
759
                                 where
760
                                     !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
761
                                 select localFile).ToList();
762

    
763

    
764
            //Set the status of missing files to Conflict
765
            foreach (var item in filesToDelete)
766
            {
767
                //Try to acquire a gate on the file, to take into account files that have been dequeued
768
                //and are being processed
769
                using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
770
                {
771
                    if (gate.Failed)
772
                        continue;
773
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,
774
                                              "Local file missing from server");
775
                }
776
            }
777
            UpdateStatus(PithosStatus.HasConflicts);
778
            StatusNotification.NotifyConflicts(filesToDelete,
779
                                               String.Format(
780
                                                   "{0} local files are missing from Pithos, possibly because they were deleted",
781
                                                   filesToDelete.Count));
782
            StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count),
783
                                              TraceLevel.Info);
784
        }
785

    
786
        private void ReportConflictForMismatch(string localFilePath)
787
        {
788
            if (String.IsNullOrWhiteSpace(localFilePath))
789
                throw new ArgumentNullException("localFilePath");
790
            Contract.EndContractBlock();
791

    
792
            StatusKeeper.SetFileState(localFilePath, FileStatus.Conflict, FileOverlayStatus.Conflict, "File changed at the server");
793
            UpdateStatus(PithosStatus.HasConflicts);
794
            var message = String.Format("Conflict detected for file {0}", localFilePath);
795
            Log.Warn(message);
796
            StatusNotification.NotifyChange(message, TraceLevel.Warning);
797
        }
798

    
799

    
800

    
801
        /// <summary>
802
        /// Creates a Sync action for each changed server file
803
        /// </summary>
804
        /// <param name="accountInfo"></param>
805
        /// <param name="changes"></param>
806
        /// <returns></returns>
807
        private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)
808
        {
809
            if (changes == null)
810
                throw new ArgumentNullException();
811
            Contract.EndContractBlock();
812
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
813

    
814
            //In order to avoid multiple iterations over the files, we iterate only once
815
            //over the remote files
816
            foreach (var objectInfo in changes)
817
            {
818
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
819
                //If a directory object already exists, we may need to sync it
820
                if (fileAgent.Exists(relativePath))
821
                {
822
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
823
                    //We don't need to sync directories
824
                    if (objectInfo.IsDirectory && localFile is DirectoryInfo)
825
                        continue;
826
                    using (new SessionScope(FlushAction.Never))
827
                    {
828
                        var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
829
                        _lastSeen[localFile.FullName] = DateTime.Now;
830
                        //Common files should be checked on a per-case basis to detect differences, which is newer
831

    
832
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
833
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
834
                                                     accountInfo.BlockHash,"Poll Changes");
835
                    }
836
                }
837
                else
838
                {
839
                    //Remote files should be downloaded
840
                    yield return new CloudDownloadAction(accountInfo, objectInfo,"Poll Changes");
841
                }
842
            }
843
        }
844

    
845
        /// <summary>
846
        /// Creates a Local Move action for each moved server file
847
        /// </summary>
848
        /// <param name="accountInfo"></param>
849
        /// <param name="moves"></param>
850
        /// <returns></returns>
851
        private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)
852
        {
853
            if (moves == null)
854
                throw new ArgumentNullException();
855
            Contract.EndContractBlock();
856
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
857

    
858
            //In order to avoid multiple iterations over the files, we iterate only once
859
            //over the remote files
860
            foreach (var objectInfo in moves)
861
            {
862
                var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);
863
                //If the previous file already exists, we can execute a Move operation
864
                if (fileAgent.Exists(previousRelativepath))
865
                {
866
                    var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
867
                    using (new SessionScope(FlushAction.Never))
868
                    {
869
                        var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);
870
                        _lastSeen[previousFile.FullName] = DateTime.Now;
871

    
872
                        //For each moved object we need to move both the local file and update                                                
873
                        yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,
874
                                                     previousFile, objectInfo, state, accountInfo.BlockSize,
875
                                                     accountInfo.BlockHash,"Poll Moves");
876
                        //For modified files, we need to download the changes as well
877
                        if (objectInfo.Hash!=objectInfo.PreviousHash)
878
                            yield return new CloudDownloadAction(accountInfo,objectInfo, "Poll Moves");
879
                    }
880
                }
881
                //If the previous file does not exist, we need to download it in the new location
882
                else
883
                {
884
                    //Remote files should be downloaded
885
                    yield return new CloudDownloadAction(accountInfo, objectInfo, "Poll Moves");
886
                }
887
            }
888
        }
889

    
890

    
891
        /// <summary>
892
        /// Creates a download action for each new server file
893
        /// </summary>
894
        /// <param name="accountInfo"></param>
895
        /// <param name="creates"></param>
896
        /// <returns></returns>
897
        private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)
898
        {
899
            if (creates == null)
900
                throw new ArgumentNullException();
901
            Contract.EndContractBlock();
902
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
903

    
904
            //In order to avoid multiple iterations over the files, we iterate only once
905
            //over the remote files
906
            foreach (var objectInfo in creates)
907
            {
908
                if (Log.IsDebugEnabled)
909
                    Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);
910

    
911
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
912

    
913
                //If the object already exists, we should check before uploading or downloading
914
                if (fileAgent.Exists(relativePath))
915
                {
916
                    var localFile= fileAgent.GetFileSystemInfo(relativePath);
917
                    var state = StatusKeeper.GetStateByFilePath(localFile.WithProperCapitalization().FullName);
918
                    yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
919
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
920
                                                     accountInfo.BlockHash,"Poll Creates");                    
921
                }
922
                else
923
                {
924
                    //Remote files should be downloaded
925
                    yield return new CloudDownloadAction(accountInfo, objectInfo,"Poll Creates");
926
                }
927

    
928
            }
929
        }
930

    
931
        /// <summary>
932
        /// Notify the UI to update the visual status
933
        /// </summary>
934
        /// <param name="status"></param>
935
        private void UpdateStatus(PithosStatus status)
936
        {
937
            try
938
            {
939
                StatusNotification.SetPithosStatus(status);
940
                //StatusNotification.Notify(new Notification());
941
            }
942
            catch (Exception exc)
943
            {
944
                //Failure is not critical, just log it
945
                Log.Warn("Error while updating status", exc);
946
            }
947
        }
948

    
949
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
950
        {
951
            var containerPaths = from container in containers
952
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
953
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
954
                                 select containerPath;
955

    
956
            foreach (var path in containerPaths)
957
            {
958
                Directory.CreateDirectory(path);
959
            }
960
        }
961

    
962
        public void AddAccount(AccountInfo accountInfo)
963
        {
964
            //Avoid adding a duplicate accountInfo
965
            _accounts.TryAdd(accountInfo.AccountKey, accountInfo);
966
        }
967

    
968
        public void RemoveAccount(AccountInfo accountInfo)
969
        {
970
            AccountInfo account;
971
            _accounts.TryRemove(accountInfo.AccountKey, out account);
972
/*
973
            SnapshotDifferencer differencer;
974
            _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);
975
*/
976
        }
977

    
978
        public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)
979
        {
980
            AbortRemovedPaths(accountInfo,removed);
981
            DownloadNewPaths(accountInfo,added);
982
        }
983

    
984
        private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)
985
        {
986
            var client = new CloudFilesClient(accountInfo);
987
            foreach (var folderUri in added)
988
            {
989
                try
990
                {
991

    
992
                    string account;
993
                    string container;
994
                    var segmentsCount = folderUri.Segments.Length;
995
                    //Is this an account URL?
996
                    if (segmentsCount < 3)
997
                        continue;
998
                    //Is this a container or  folder URL?
999
                    if (segmentsCount == 3)
1000
                    {
1001
                        account = folderUri.Segments[1].TrimEnd('/');
1002
                        container = folderUri.Segments[2].TrimEnd('/');
1003
                    }
1004
                    else
1005
                    {
1006
                        account = folderUri.Segments[2].TrimEnd('/');
1007
                        container = folderUri.Segments[3].TrimEnd('/');
1008
                    }
1009
                    IList<ObjectInfo> items;
1010
                    if (segmentsCount > 3)
1011
                    {
1012
                        //List folder
1013
                        var folder = String.Join("", folderUri.Segments.Splice(4));
1014
                        items = client.ListObjects(account, container, folder);
1015
                    }
1016
                    else
1017
                    {
1018
                        //List container
1019
                        items = client.ListObjects(account, container);
1020
                    }
1021
                    var actions = CreatesToActions(accountInfo, items);
1022
                    foreach (var action in actions)
1023
                    {
1024
                        NetworkAgent.Post(action);
1025
                    }
1026
                }
1027
                catch (Exception exc)
1028
                {
1029
                    Log.WarnFormat("Listing of new selective path [{0}] failed with \r\n{1}", folderUri, exc);
1030
                }
1031
            }
1032

    
1033
            //Need to get a listing of each of the URLs, then post them to the NetworkAgent
1034
            //CreatesToActions(accountInfo,)
1035

    
1036
/*            NetworkAgent.Post();*/
1037
        }
1038

    
1039
        private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)
1040
        {
1041
            /*this.NetworkAgent.*/
1042
        }
1043
    }
1044
}