Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / PollAgent.cs @ 4671d606

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

    
56
namespace Pithos.Core.Agents
57
{
58
    using System;
59
    using System.Collections.Generic;
60
    using System.Linq;
61

    
62
    /// <summary>
63
    /// PollAgent periodically polls the server to detect object changes. The agent retrieves a listing of all
64
    /// objects and compares it with a previously cached version to detect differences. 
65
    /// New files are downloaded, missing files are deleted from the local file system and common files are compared
66
    /// to determine the appropriate action
67
    /// </summary>
68
    [Export]
69
    public class PollAgent
70
    {
71
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
72

    
73
        [System.ComponentModel.Composition.Import]
74
        public IStatusKeeper StatusKeeper { get; set; }
75

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

    
79
        [System.ComponentModel.Composition.Import]
80
        public NetworkAgent NetworkAgent { get; set; }
81

    
82
        [System.ComponentModel.Composition.Import]
83
        public Selectives Selectives { get; set; }
84

    
85
        public IStatusNotification StatusNotification { get; set; }
86

    
87
        public bool Pause
88
        {
89
            get {
90
                return _pause;
91
            }
92
            set {
93
                _pause = value;                
94
                if (!_pause)
95
                    _unPauseEvent.Set();
96
                else
97
                {
98
                    _unPauseEvent.Reset();
99
                }
100
            }
101
        }
102

    
103
        private bool _firstPoll = true;
104

    
105
        //The Sync Event signals a manual synchronisation
106
        private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
107

    
108
        private readonly AsyncManualResetEvent _unPauseEvent = new AsyncManualResetEvent(true);
109

    
110
        private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
111
        private readonly ConcurrentDictionary<Uri, AccountInfo> _accounts = new ConcurrentDictionary<Uri,AccountInfo>();
112

    
113

    
114
        /// <summary>
115
        /// Start a manual synchronization
116
        /// </summary>
117
        public void SynchNow()
118
        {            
119
            _syncEvent.Set();
120
        }
121

    
122

    
123
        /// <summary>
124
        /// Remote files are polled periodically. Any changes are processed
125
        /// </summary>
126
        /// <param name="since"></param>
127
        /// <returns></returns>
128
        public async Task PollRemoteFiles(DateTime? since = null)
129
        {
130
            if (Log.IsDebugEnabled)
131
                Log.DebugFormat("Polling changes after [{0}]",since);
132

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

    
135
            GC.Collect();
136

    
137
            using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
138
            {
139
                //If this poll fails, we will retry with the same since value
140
                var nextSince = since;
141
                try
142
                {
143
                    await _unPauseEvent.WaitAsync();
144
                    UpdateStatus(PithosStatus.PollSyncing);
145

    
146
                    var tasks = from accountInfo in _accounts.Values
147
                                select ProcessAccountFiles(accountInfo, since);
148

    
149
                    var nextTimes=await TaskEx.WhenAll(tasks.ToList());
150

    
151
                    _firstPoll = false;
152
                    //Reschedule the poll with the current timestamp as a "since" value
153

    
154
                    if (nextTimes.Length>0)
155
                        nextSince = nextTimes.Min();
156
                    if (Log.IsDebugEnabled)
157
                        Log.DebugFormat("Next Poll at [{0}]",nextSince);
158
                }
159
                catch (Exception ex)
160
                {
161
                    Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);
162
                    //In case of failure retry with the same "since" value
163
                }
164

    
165
                UpdateStatus(PithosStatus.PollComplete);
166
                //The multiple try blocks are required because we can't have an await call
167
                //inside a finally block
168
                //TODO: Find a more elegant solution for reschedulling in the event of an exception
169
                try
170
                {
171
                    //Wait for the polling interval to pass or the Sync event to be signalled
172
                    nextSince = await WaitForScheduledOrManualPoll(nextSince);
173
                }
174
                finally
175
                {
176
                    //Ensure polling is scheduled even in case of error
177
                    TaskEx.Run(() => PollRemoteFiles(nextSince));                        
178
                }
179
            }
180
        }
181

    
182
        /// <summary>
183
        /// Wait for the polling period to expire or a manual sync request
184
        /// </summary>
185
        /// <param name="since"></param>
186
        /// <returns></returns>
187
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
188
        {
189
            var sync = _syncEvent.WaitAsync();
190
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken);
191
            
192
            var signaledTask = await TaskEx.WhenAny(sync, wait);
193
            
194
            //Pausing takes precedence over manual sync or awaiting
195
            _unPauseEvent.Wait();
196
            
197
            //Wait for network processing to finish before polling
198
            var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
199
            await TaskEx.WhenAll(signaledTask, pauseTask);
200

    
201
            //If polling is signalled by SynchNow, ignore the since tag
202
            if (sync.IsCompleted)
203
            {
204
                //TODO: Must convert to AutoReset
205
                _syncEvent.Reset();
206
                return null;
207
            }
208
            return since;
209
        }
210

    
211
        public async Task<DateTime?> ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)
212
        {
213
            if (accountInfo == null)
214
                throw new ArgumentNullException("accountInfo");
215
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
216
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
217
            Contract.EndContractBlock();
218

    
219

    
220
            using (ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
221
            {
222

    
223
                await NetworkAgent.GetDeleteAwaiter();
224

    
225
                Log.Info("Scheduled");
226
                var client = new CloudFilesClient(accountInfo);
227

    
228
                //We don't need to check the trash container
229
                var containers = client.ListContainers(accountInfo.UserName)
230
                    .Where(c=>c.Name!="trash")
231
                    .ToList();
232

    
233

    
234
                CreateContainerFolders(accountInfo, containers);
235

    
236
                //The nextSince time fallback time is the same as the current.
237
                //If polling succeeds, the next Since time will be the smallest of the maximum modification times
238
                //of the shared and account objects
239
                var nextSince = since;
240

    
241
                try
242
                {
243
                    //Wait for any deletions to finish
244
                    await NetworkAgent.GetDeleteAwaiter();
245
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
246
                    //than delete a file that was created while we were executing the poll                    
247

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

    
254
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => 
255
                        client.ListSharedObjects(since), "shared");
256
                    listObjects.Add(listShared);
257
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
258

    
259
                    using (ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
260
                    {
261
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
262

    
263
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
264
                        var remoteObjects = (from objectList in listTasks
265
                                            where (string)objectList.AsyncState != "trash"
266
                                            from obj in objectList.Result
267
                                            select obj).ToList();
268
                        
269
                        //Get the latest remote object modification date, only if it is after
270
                        //the original since date
271
                        nextSince = GetLatestDateAfter(nextSince, remoteObjects);
272

    
273
                        var sharedObjects = dict["shared"].Result;
274
                        nextSince = GetLatestDateBefore(nextSince, sharedObjects);
275

    
276
                        //DON'T process trashed files
277
                        //If some files are deleted and added again to a folder, they will be deleted
278
                        //even though they are new.
279
                        //We would have to check file dates and hashes to ensure that a trashed file
280
                        //can be deleted safely from the local hard drive.
281
                        /*
282
                        //Items with the same name, hash may be both in the container and the trash
283
                        //Don't delete items that exist in the container
284
                        var realTrash = from trash in trashObjects
285
                                        where
286
                                            !remoteObjects.Any(
287
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
288
                                        select trash;
289
                        ProcessTrashedFiles(accountInfo, realTrash);
290
*/
291

    
292
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
293
                                            let name = info.Name??""
294
                                            where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
295
                                                  !name.StartsWith(FolderConstants.CacheFolder + "/",
296
                                                                   StringComparison.InvariantCultureIgnoreCase)
297
                                            select info).ToList();
298

    
299
                        if (_firstPoll)
300
                            StatusKeeper.CleanupOrphanStates();
301
                        StatusKeeper.CleanupStaleStates(accountInfo, cleanRemotes);
302
                        
303
                        var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
304

    
305
                        var filterUris = Selectives.SelectiveUris[accountInfo.AccountKey];
306

    
307

    
308
                        //On the first run
309
                        if (_firstPoll)
310
                        {
311
                            MarkSuspectedDeletes(accountInfo, cleanRemotes);
312
                        }
313
                        ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(filterUris));
314

    
315
                        // @@@ NEED To add previous state here as well, To compare with previous hash
316

    
317
                        
318

    
319
                        //Create a list of actions from the remote files
320
                        
321
                        var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(filterUris))
322
                                        .Union(
323
                                        ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(filterUris)))
324
                                        .Union(
325
                                        CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(filterUris)));
326

    
327
                        //And remove those that are already being processed by the agent
328
                        var distinctActions = allActions
329
                            .Except(NetworkAgent.GetEnumerable(), new LocalFileComparer())
330
                            .ToList();
331

    
332
                        await _unPauseEvent.WaitAsync();
333
                        //Queue all the actions
334
                        foreach (var message in distinctActions)
335
                        {
336
                            NetworkAgent.Post(message);
337
                        }
338

    
339
                        Log.Info("[LISTENER] End Processing");
340
                    }
341
                }
342
                catch (Exception ex)
343
                {
344
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
345
                    return nextSince;
346
                }
347

    
348
                Log.Info("[LISTENER] Finished");
349
                return nextSince;
350
            }
351
        }
352

    
353
        /// <summary>
354
        /// Returns the latest LastModified date from the list of objects, but only if it is before
355
        /// than the threshold value
356
        /// </summary>
357
        /// <param name="threshold"></param>
358
        /// <param name="cloudObjects"></param>
359
        /// <returns></returns>
360
        private static DateTime? GetLatestDateBefore(DateTime? threshold, IList<ObjectInfo> cloudObjects)
361
        {
362
            DateTime? maxDate = null;
363
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
364
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
365
            if (maxDate == null || maxDate == DateTime.MinValue)
366
                return threshold;
367
            if (threshold == null || threshold == DateTime.MinValue || threshold > maxDate)
368
                return maxDate;
369
            return threshold;
370
        }
371

    
372
        /// <summary>
373
        /// Returns the latest LastModified date from the list of objects, but only if it is after
374
        /// the threshold value
375
        /// </summary>
376
        /// <param name="threshold"></param>
377
        /// <param name="cloudObjects"></param>
378
        /// <returns></returns>
379
        private static DateTime? GetLatestDateAfter(DateTime? threshold, IList<ObjectInfo> cloudObjects)
380
        {
381
            DateTime? maxDate = null;
382
            if (cloudObjects!=null &&  cloudObjects.Count > 0)
383
                maxDate = cloudObjects.Max(obj => obj.Last_Modified);
384
            if (maxDate == null || maxDate == DateTime.MinValue)
385
                return threshold;
386
            if (threshold == null || threshold == DateTime.MinValue || threshold < maxDate)
387
                return maxDate;
388
            return threshold;
389
        }
390

    
391
        readonly AccountsDifferencer _differencer = new AccountsDifferencer();
392
        private Dictionary<Uri, List<Uri>> _selectiveUris = new Dictionary<Uri, List<Uri>>();
393
        private bool _pause;
394

    
395
        /// <summary>
396
        /// Deletes local files that are not found in the list of cloud files
397
        /// </summary>
398
        /// <param name="accountInfo"></param>
399
        /// <param name="cloudFiles"></param>
400
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
401
        {
402
            if (accountInfo == null)
403
                throw new ArgumentNullException("accountInfo");
404
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
405
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
406
            if (cloudFiles == null)
407
                throw new ArgumentNullException("cloudFiles");
408
            Contract.EndContractBlock();
409

    
410
            var deletedFiles = new List<FileSystemInfo>();
411
            foreach (var objectInfo in cloudFiles)
412
            {
413
                if (Log.IsDebugEnabled)
414
                    Log.DebugFormat("Handle deleted [{0}]", objectInfo.Uri);
415
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
416
                var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
417
                if (Log.IsDebugEnabled)
418
                    Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName, objectInfo.Uri);
419
                if (item.Exists)
420
                {
421
                    if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
422
                    {
423
                        item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
424

    
425
                    }
426

    
427

    
428
                    Log.DebugFormat("Deleting {0}", item.FullName);
429

    
430
                    var directory = item as DirectoryInfo;
431
                    if (directory != null)
432
                        directory.Delete(true);
433
                    else
434
                        item.Delete();
435
                    Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);
436
                    DateTime lastDate;
437
                    _lastSeen.TryRemove(item.FullName, out lastDate);
438
                    deletedFiles.Add(item);
439
                }
440
                StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted, "File Deleted");
441
            }
442
            Log.InfoFormat("[{0}] files were deleted", deletedFiles.Count);
443
            StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count),
444
                                              TraceLevel.Info);
445

    
446
        }
447

    
448
        private void MarkSuspectedDeletes(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
449
        {
450
//Only consider files that are not being modified, ie they are in the Unchanged state            
451
            var deleteCandidates = FileState.Queryable.Where(state =>
452
                                                             state.FilePath.StartsWith(accountInfo.AccountPath)
453
                                                             && state.FileStatus == FileStatus.Unchanged).ToList();
454

    
455

    
456
            //TODO: filesToDelete must take into account the Others container            
457
            var filesToDelete = (from deleteCandidate in deleteCandidates
458
                                 let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
459
                                 let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
460
                                 where
461
                                     !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
462
                                 select localFile).ToList();
463

    
464

    
465
            //Set the status of missing files to Conflict
466
            foreach (var item in filesToDelete)
467
            {
468
                //Try to acquire a gate on the file, to take into account files that have been dequeued
469
                //and are being processed
470
                using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
471
                {
472
                    if (gate.Failed)
473
                        continue;
474
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted,
475
                                              "Local file missing from server");
476
                }
477
            }
478
            UpdateStatus(PithosStatus.HasConflicts);
479
            StatusNotification.NotifyConflicts(filesToDelete,
480
                                               String.Format(
481
                                                   "{0} local files are missing from Pithos, possibly because they were deleted",
482
                                                   filesToDelete.Count));
483
            StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count),
484
                                              TraceLevel.Info);
485
        }
486

    
487
        /// <summary>
488
        /// Creates a Sync action for each changed server file
489
        /// </summary>
490
        /// <param name="accountInfo"></param>
491
        /// <param name="changes"></param>
492
        /// <returns></returns>
493
        private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)
494
        {
495
            if (changes == null)
496
                throw new ArgumentNullException();
497
            Contract.EndContractBlock();
498
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
499

    
500
            //In order to avoid multiple iterations over the files, we iterate only once
501
            //over the remote files
502
            foreach (var objectInfo in changes)
503
            {
504
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
505
                //If a directory object already exists, we may need to sync it
506
                if (fileAgent.Exists(relativePath))
507
                {
508
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
509
                    //We don't need to sync directories
510
                    if (objectInfo.IsDirectory && localFile is DirectoryInfo)
511
                        continue;
512
                    using (new SessionScope(FlushAction.Never))
513
                    {
514
                        var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
515
                        _lastSeen[localFile.FullName] = DateTime.Now;
516
                        //Common files should be checked on a per-case basis to detect differences, which is newer
517

    
518
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
519
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
520
                                                     accountInfo.BlockHash,"Poll Changes");
521
                    }
522
                }
523
                else
524
                {
525
                    //Remote files should be downloaded
526
                    yield return new CloudDownloadAction(accountInfo, objectInfo,"Poll Changes");
527
                }
528
            }
529
        }
530

    
531
        /// <summary>
532
        /// Creates a Local Move action for each moved server file
533
        /// </summary>
534
        /// <param name="accountInfo"></param>
535
        /// <param name="moves"></param>
536
        /// <returns></returns>
537
        private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)
538
        {
539
            if (moves == null)
540
                throw new ArgumentNullException();
541
            Contract.EndContractBlock();
542
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
543

    
544
            //In order to avoid multiple iterations over the files, we iterate only once
545
            //over the remote files
546
            foreach (var objectInfo in moves)
547
            {
548
                var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);
549
                //If the previous file already exists, we can execute a Move operation
550
                if (fileAgent.Exists(previousRelativepath))
551
                {
552
                    var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
553
                    using (new SessionScope(FlushAction.Never))
554
                    {
555
                        var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);
556
                        _lastSeen[previousFile.FullName] = DateTime.Now;
557

    
558
                        //For each moved object we need to move both the local file and update                                                
559
                        yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,
560
                                                     previousFile, objectInfo, state, accountInfo.BlockSize,
561
                                                     accountInfo.BlockHash,"Poll Moves");
562
                        //For modified files, we need to download the changes as well
563
                        if (objectInfo.Hash!=objectInfo.PreviousHash)
564
                            yield return new CloudDownloadAction(accountInfo,objectInfo, "Poll Moves");
565
                    }
566
                }
567
                //If the previous file does not exist, we need to download it in the new location
568
                else
569
                {
570
                    //Remote files should be downloaded
571
                    yield return new CloudDownloadAction(accountInfo, objectInfo, "Poll Moves");
572
                }
573
            }
574
        }
575

    
576

    
577
        /// <summary>
578
        /// Creates a download action for each new server file
579
        /// </summary>
580
        /// <param name="accountInfo"></param>
581
        /// <param name="creates"></param>
582
        /// <returns></returns>
583
        private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)
584
        {
585
            if (creates == null)
586
                throw new ArgumentNullException();
587
            Contract.EndContractBlock();
588
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
589

    
590
            //In order to avoid multiple iterations over the files, we iterate only once
591
            //over the remote files
592
            foreach (var objectInfo in creates)
593
            {
594
                if (Log.IsDebugEnabled)
595
                    Log.DebugFormat("[NEW INFO] {0}",objectInfo.Uri);
596

    
597
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
598

    
599
                //If the object already exists, we should check before uploading or downloading
600
                if (fileAgent.Exists(relativePath))
601
                {
602
                    var localFile= fileAgent.GetFileSystemInfo(relativePath);
603
                    var state = StatusKeeper.GetStateByFilePath(localFile.WithProperCapitalization().FullName);
604
                    yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
605
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
606
                                                     accountInfo.BlockHash,"Poll Creates");                    
607
                }
608
                else
609
                {
610
                    //Remote files should be downloaded
611
                    yield return new CloudDownloadAction(accountInfo, objectInfo,"Poll Creates");
612
                }
613

    
614
            }
615
        }
616

    
617
        /// <summary>
618
        /// Notify the UI to update the visual status
619
        /// </summary>
620
        /// <param name="status"></param>
621
        private void UpdateStatus(PithosStatus status)
622
        {
623
            try
624
            {
625
                StatusNotification.SetPithosStatus(status);
626
                //StatusNotification.Notify(new Notification());
627
            }
628
            catch (Exception exc)
629
            {
630
                //Failure is not critical, just log it
631
                Log.Warn("Error while updating status", exc);
632
            }
633
        }
634

    
635
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
636
        {
637
            var containerPaths = from container in containers
638
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
639
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
640
                                 select containerPath;
641

    
642
            foreach (var path in containerPaths)
643
            {
644
                Directory.CreateDirectory(path);
645
            }
646
        }
647

    
648
        public void AddAccount(AccountInfo accountInfo)
649
        {
650
            //Avoid adding a duplicate accountInfo
651
            _accounts.TryAdd(accountInfo.AccountKey, accountInfo);
652
        }
653

    
654
        public void RemoveAccount(AccountInfo accountInfo)
655
        {
656
            AccountInfo account;
657
            _accounts.TryRemove(accountInfo.AccountKey, out account);
658
            SnapshotDifferencer differencer;
659
            _differencer.Differencers.TryRemove(accountInfo.AccountKey, out differencer);
660
        }
661

    
662
        public void SetSelectivePaths(AccountInfo accountInfo,Uri[] added, Uri[] removed)
663
        {
664
            AbortRemovedPaths(accountInfo,removed);
665
            DownloadNewPaths(accountInfo,added);
666
        }
667

    
668
        private void DownloadNewPaths(AccountInfo accountInfo, Uri[] added)
669
        {
670
            var client = new CloudFilesClient(accountInfo);
671
            foreach (var folderUri in added)
672
            {
673
                try
674
                {
675

    
676
                    string account;
677
                    string container;
678
                    var segmentsCount = folderUri.Segments.Length;
679
                    //Is this an account URL?
680
                    if (segmentsCount < 3)
681
                        continue;
682
                    //Is this a container or  folder URL?
683
                    if (segmentsCount == 3)
684
                    {
685
                        account = folderUri.Segments[1].TrimEnd('/');
686
                        container = folderUri.Segments[2].TrimEnd('/');
687
                    }
688
                    else
689
                    {
690
                        account = folderUri.Segments[2].TrimEnd('/');
691
                        container = folderUri.Segments[3].TrimEnd('/');
692
                    }
693
                    IList<ObjectInfo> items;
694
                    if (segmentsCount > 3)
695
                    {
696
                        //List folder
697
                        var folder = String.Join("", folderUri.Segments.Splice(4));
698
                        items = client.ListObjects(account, container, folder);
699
                    }
700
                    else
701
                    {
702
                        //List container
703
                        items = client.ListObjects(account, container);
704
                    }
705
                    var actions = CreatesToActions(accountInfo, items);
706
                    foreach (var action in actions)
707
                    {
708
                        NetworkAgent.Post(action);
709
                    }
710
                }
711
                catch (Exception exc)
712
                {
713
                    Log.WarnFormat("Listing of new selective path [{0}] failed with \r\n{1}", folderUri, exc);
714
                }
715
            }
716

    
717
            //Need to get a listing of each of the URLs, then post them to the NetworkAgent
718
            //CreatesToActions(accountInfo,)
719

    
720
/*            NetworkAgent.Post();*/
721
        }
722

    
723
        private void AbortRemovedPaths(AccountInfo accountInfo, Uri[] removed)
724
        {
725
            /*this.NetworkAgent.*/
726
        }
727
    }
728
}