Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / PollAgent.cs @ 6bcdd8e2

History | View | Annotate | Download (25.9 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
        public IStatusNotification StatusNotification { get; set; }
83

    
84
        private bool _firstPoll = true;
85

    
86
        //The Sync Event signals a manual synchronisation
87
        private readonly AsyncManualResetEvent _syncEvent = new AsyncManualResetEvent();
88

    
89
        private readonly ConcurrentDictionary<string, DateTime> _lastSeen = new ConcurrentDictionary<string, DateTime>();
90
        private readonly ConcurrentDictionary<string, AccountInfo> _accounts = new ConcurrentDictionary<string,AccountInfo>();
91

    
92

    
93
        /// <summary>
94
        /// Start a manual synchronization
95
        /// </summary>
96
        public void SynchNow()
97
        {            
98
            _syncEvent.Set();
99
        }
100

    
101
        /// <summary>
102
        /// Remote files are polled periodically. Any changes are processed
103
        /// </summary>
104
        /// <param name="since"></param>
105
        /// <returns></returns>
106
        public async Task PollRemoteFiles(DateTime? since = null)
107
        {
108
            Debug.Assert(Thread.CurrentThread.IsBackground, "Polling Ended up in the main thread!");
109

    
110
            UpdateStatus(PithosStatus.Syncing);
111
            StatusNotification.Notify(new PollNotification());
112

    
113
            using (ThreadContext.Stacks["Retrieve Remote"].Push("All accounts"))
114
            {
115
                //If this poll fails, we will retry with the same since value
116
                var nextSince = since;
117
                try
118
                {
119
                    //Next time we will check for all changes since the current check minus 1 second
120
                    //This is done to ensure there are no discrepancies due to clock differences
121
                    var current = DateTime.Now.AddSeconds(-1);
122

    
123
                    var tasks = from accountInfo in _accounts.Values
124
                                select ProcessAccountFiles(accountInfo, since);
125

    
126
                    await TaskEx.WhenAll(tasks.ToList());
127

    
128
                    _firstPoll = false;
129
                    //Reschedule the poll with the current timestamp as a "since" value
130
                    nextSince = current;
131
                }
132
                catch (Exception ex)
133
                {
134
                    Log.ErrorFormat("Error while processing accounts\r\n{0}", ex);
135
                    //In case of failure retry with the same "since" value
136
                }
137

    
138
                UpdateStatus(PithosStatus.InSynch);
139
                //The multiple try blocks are required because we can't have an await call
140
                //inside a finally block
141
                //TODO: Find a more elegant solution for reschedulling in the event of an exception
142
                try
143
                {
144
                    //Wait for the polling interval to pass or the Sync event to be signalled
145
                    nextSince = await WaitForScheduledOrManualPoll(nextSince);
146
                }
147
                finally
148
                {
149
                    //Ensure polling is scheduled even in case of error
150
                    TaskEx.Run(() => PollRemoteFiles(nextSince));                        
151
                }
152
            }
153
        }
154

    
155
        /// <summary>
156
        /// Wait for the polling period to expire or a manual sync request
157
        /// </summary>
158
        /// <param name="since"></param>
159
        /// <returns></returns>
160
        private async Task<DateTime?> WaitForScheduledOrManualPoll(DateTime? since)
161
        {
162
            var sync = _syncEvent.WaitAsync();
163
            var wait = TaskEx.Delay(TimeSpan.FromSeconds(Settings.PollingInterval), NetworkAgent.CancellationToken);
164
            var signaledTask = await TaskEx.WhenAny(sync, wait);
165

    
166
            //Wait for network processing to finish before polling
167
            var pauseTask=NetworkAgent.ProceedEvent.WaitAsync();
168
            await TaskEx.WhenAll(signaledTask, pauseTask);
169

    
170
            //If polling is signalled by SynchNow, ignore the since tag
171
            if (sync.IsCompleted)
172
            {
173
                //TODO: Must convert to AutoReset
174
                _syncEvent.Reset();
175
                return null;
176
            }
177
            return since;
178
        }
179

    
180
        public async Task ProcessAccountFiles(AccountInfo accountInfo, DateTime? since = null)
181
        {
182
            if (accountInfo == null)
183
                throw new ArgumentNullException("accountInfo");
184
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
185
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
186
            Contract.EndContractBlock();
187

    
188

    
189
            using (log4net.ThreadContext.Stacks["Retrieve Remote"].Push(accountInfo.UserName))
190
            {
191
                await NetworkAgent.GetDeleteAwaiter();
192

    
193
                Log.Info("Scheduled");
194
                var client = new CloudFilesClient(accountInfo);
195

    
196
                //We don't need to check the trash container
197
                var containers = client.ListContainers(accountInfo.UserName)
198
                    .Where(c=>c.Name!="trash")
199
                    .ToList();
200

    
201

    
202
                CreateContainerFolders(accountInfo, containers);
203

    
204
                try
205
                {
206
                    //Wait for any deletions to finish
207
                    await NetworkAgent.GetDeleteAwaiter();
208
                    //Get the poll time now. We may miss some deletions but it's better to keep a file that was deleted
209
                    //than delete a file that was created while we were executing the poll                    
210

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

    
217
                    var listShared = Task<IList<ObjectInfo>>.Factory.StartNew(_ => 
218
                        client.ListSharedObjects(since), "shared");
219
                    listObjects.Add(listShared);
220
                    var listTasks = await Task.Factory.WhenAll(listObjects.ToArray());
221

    
222
                    using (log4net.ThreadContext.Stacks["SCHEDULE"].Push("Process Results"))
223
                    {
224
                        var dict = listTasks.ToDictionary(t => t.AsyncState);
225

    
226
                        //Get all non-trash objects. Remember, the container name is stored in AsyncState
227
                        var remoteObjects = from objectList in listTasks
228
                                            where (string)objectList.AsyncState != "trash"
229
                                            from obj in objectList.Result
230
                                            select obj;
231

    
232
                        var sharedObjects = dict["shared"].Result;
233

    
234
                        //DON'T process trashed files
235
                        //If some files are deleted and added again to a folder, they will be deleted
236
                        //even though they are new.
237
                        //We would have to check file dates and hashes to ensure that a trashed file
238
                        //can be deleted safely from the local hard drive.
239
                        /*
240
                        //Items with the same name, hash may be both in the container and the trash
241
                        //Don't delete items that exist in the container
242
                        var realTrash = from trash in trashObjects
243
                                        where
244
                                            !remoteObjects.Any(
245
                                                info => info.Name == trash.Name && info.Hash == trash.Hash)
246
                                        select trash;
247
                        ProcessTrashedFiles(accountInfo, realTrash);
248
*/
249

    
250
                        var cleanRemotes = (from info in remoteObjects.Union(sharedObjects)
251
                                            let name = info.Name??""
252
                                            where !name.EndsWith(".ignore", StringComparison.InvariantCultureIgnoreCase) &&
253
                                                  !name.StartsWith(FolderConstants.CacheFolder + "/",
254
                                                                   StringComparison.InvariantCultureIgnoreCase)
255
                                            select info).ToList();
256

    
257
                        var differencer = _differencer.PostSnapshot(accountInfo, cleanRemotes);
258

    
259
                        ProcessDeletedFiles(accountInfo, differencer.Deleted.FilterDirectlyBelow(SelectiveUris));
260

    
261
                        // @@@ NEED To add previous state here as well, To compare with previous hash
262

    
263
                        
264

    
265
                        //Create a list of actions from the remote files
266
                        var allActions = MovesToActions(accountInfo,differencer.Moved.FilterDirectlyBelow(SelectiveUris))
267
                                        .Union(
268
                                        ChangesToActions(accountInfo, differencer.Changed.FilterDirectlyBelow(SelectiveUris)))
269
                                        .Union(
270
                                        CreatesToActions(accountInfo, differencer.Created.FilterDirectlyBelow(SelectiveUris)));
271

    
272
                        //And remove those that are already being processed by the agent
273
                        var distinctActions = allActions
274
                            .Except(NetworkAgent.GetEnumerable(), new PithosMonitor.LocalFileComparer())
275
                            .ToList();
276

    
277
                        //Queue all the actions
278
                        foreach (var message in distinctActions)
279
                        {
280
                            NetworkAgent.Post(message);
281
                        }
282

    
283
                        Log.Info("[LISTENER] End Processing");
284
                    }
285
                }
286
                catch (Exception ex)
287
                {
288
                    Log.ErrorFormat("[FAIL] ListObjects for{0} in ProcessRemoteFiles with {1}", accountInfo.UserName, ex);
289
                    return;
290
                }
291

    
292
                Log.Info("[LISTENER] Finished");
293

    
294
            }
295
        }
296

    
297
        readonly AccountsDifferencer _differencer = new AccountsDifferencer();
298
        private List<Uri> _selectiveUris=new List<Uri>();
299

    
300
        /// <summary>
301
        /// Deletes local files that are not found in the list of cloud files
302
        /// </summary>
303
        /// <param name="accountInfo"></param>
304
        /// <param name="cloudFiles"></param>
305
        private void ProcessDeletedFiles(AccountInfo accountInfo, IEnumerable<ObjectInfo> cloudFiles)
306
        {
307
            if (accountInfo == null)
308
                throw new ArgumentNullException("accountInfo");
309
            if (String.IsNullOrWhiteSpace(accountInfo.AccountPath))
310
                throw new ArgumentException("The AccountInfo.AccountPath is empty", "accountInfo");
311
            if (cloudFiles == null)
312
                throw new ArgumentNullException("cloudFiles");
313
            Contract.EndContractBlock();
314

    
315
            //On the first run
316
            if (_firstPoll)
317
            {
318
                //Only consider files that are not being modified, ie they are in the Unchanged state            
319
                var deleteCandidates = FileState.Queryable.Where(state =>
320
                    state.FilePath.StartsWith(accountInfo.AccountPath)
321
                    && state.FileStatus == FileStatus.Unchanged).ToList();
322

    
323

    
324
                //TODO: filesToDelete must take into account the Others container            
325
                var filesToDelete = (from deleteCandidate in deleteCandidates
326
                                     let localFile = FileInfoExtensions.FromPath(deleteCandidate.FilePath)
327
                                     let relativeFilePath = localFile.AsRelativeTo(accountInfo.AccountPath)
328
                                     where
329
                                         !cloudFiles.Any(r => r.RelativeUrlToFilePath(accountInfo.UserName) == relativeFilePath)
330
                                     select localFile).ToList();
331

    
332

    
333

    
334
                //Set the status of missing files to Conflict
335
                foreach (var item in filesToDelete)
336
                {
337
                    //Try to acquire a gate on the file, to take into account files that have been dequeued
338
                    //and are being processed
339
                    using (var gate = NetworkGate.Acquire(item.FullName, NetworkOperation.Deleting))
340
                    {
341
                        if (gate.Failed)
342
                            continue;
343
                        StatusKeeper.SetFileState(item.FullName, FileStatus.Conflict, FileOverlayStatus.Deleted);
344
                    }
345
                }
346
                UpdateStatus(PithosStatus.HasConflicts);
347
                StatusNotification.NotifyConflicts(filesToDelete, String.Format("{0} local files are missing from Pithos, possibly because they were deleted", filesToDelete.Count));
348
                StatusNotification.NotifyForFiles(filesToDelete, String.Format("{0} files were deleted", filesToDelete.Count), TraceLevel.Info);
349
            }
350
            else
351
            {
352
                var deletedFiles = new List<FileSystemInfo>();
353
                foreach (var objectInfo in cloudFiles)
354
                {
355
                    Log.DebugFormat("Handle deleted [{0}]",objectInfo.Uri);
356
                    var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
357
                    var item = FileAgent.GetFileAgent(accountInfo).GetFileSystemInfo(relativePath);
358
                    Log.DebugFormat("Will delete [{0}] for [{1}]", item.FullName,objectInfo.Uri);
359
                    if (item.Exists)
360
                    {
361
                        if ((item.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
362
                        {
363
                            item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
364

    
365
                        }
366
                        var directory = item as DirectoryInfo;
367
                        if (directory!=null)
368
                            directory.Delete(true);
369
                        else
370
                            item.Delete();
371
                        Log.DebugFormat("Deleted [{0}] for [{1}]", item.FullName, objectInfo.Uri);
372
                        DateTime lastDate;
373
                        _lastSeen.TryRemove(item.FullName, out lastDate);
374
                        deletedFiles.Add(item);
375
                    }
376
                    StatusKeeper.SetFileState(item.FullName, FileStatus.Deleted, FileOverlayStatus.Deleted);
377
                }
378
                Log.InfoFormat("[{0}] files were deleted",deletedFiles.Count);
379
                StatusNotification.NotifyForFiles(deletedFiles, String.Format("{0} files were deleted", deletedFiles.Count), TraceLevel.Info);
380
            }
381

    
382
        }
383

    
384
        /// <summary>
385
        /// Creates a Sync action for each changed server file
386
        /// </summary>
387
        /// <param name="accountInfo"></param>
388
        /// <param name="changes"></param>
389
        /// <returns></returns>
390
        private IEnumerable<CloudAction> ChangesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> changes)
391
        {
392
            if (changes == null)
393
                throw new ArgumentNullException();
394
            Contract.EndContractBlock();
395
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
396

    
397
            //In order to avoid multiple iterations over the files, we iterate only once
398
            //over the remote files
399
            foreach (var objectInfo in changes)
400
            {
401
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
402
                //If a directory object already exists, we may need to sync it
403
                if (fileAgent.Exists(relativePath))
404
                {
405
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
406
                    //We don't need to sync directories
407
                    if (objectInfo.Content_Type == @"application/directory" && localFile is DirectoryInfo)
408
                        continue;
409
                    using (new SessionScope(FlushAction.Never))
410
                    {
411
                        var state = StatusKeeper.GetStateByFilePath(localFile.FullName);
412
                        _lastSeen[localFile.FullName] = DateTime.Now;
413
                        //Common files should be checked on a per-case basis to detect differences, which is newer
414

    
415
                        yield return new CloudAction(accountInfo, CloudActionType.MustSynch,
416
                                                     localFile, objectInfo, state, accountInfo.BlockSize,
417
                                                     accountInfo.BlockHash);
418
                    }
419
                }
420
                else
421
                {
422
                    //Remote files should be downloaded
423
                    yield return new CloudDownloadAction(accountInfo, objectInfo);
424
                }
425
            }
426
        }
427

    
428
        /// <summary>
429
        /// Creates a Local Move action for each moved server file
430
        /// </summary>
431
        /// <param name="accountInfo"></param>
432
        /// <param name="moves"></param>
433
        /// <returns></returns>
434
        private IEnumerable<CloudAction> MovesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> moves)
435
        {
436
            if (moves == null)
437
                throw new ArgumentNullException();
438
            Contract.EndContractBlock();
439
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
440

    
441
            //In order to avoid multiple iterations over the files, we iterate only once
442
            //over the remote files
443
            foreach (var objectInfo in moves)
444
            {
445
                var previousRelativepath = objectInfo.Previous.RelativeUrlToFilePath(accountInfo.UserName);
446
                //If the previous file already exists, we can execute a Move operation
447
                if (fileAgent.Exists(previousRelativepath))
448
                {
449
                    var previousFile = fileAgent.GetFileSystemInfo(previousRelativepath);
450
                    using (new SessionScope(FlushAction.Never))
451
                    {
452
                        var state = StatusKeeper.GetStateByFilePath(previousFile.FullName);
453
                        _lastSeen[previousFile.FullName] = DateTime.Now;
454

    
455
                        //For each moved object we need to move both the local file and update                                                
456
                        yield return new CloudAction(accountInfo, CloudActionType.RenameLocal,
457
                                                     previousFile, objectInfo, state, accountInfo.BlockSize,
458
                                                     accountInfo.BlockHash);
459
                        //For modified files, we need to download the changes as well
460
                        if (objectInfo.Hash!=objectInfo.PreviousHash)
461
                            yield return new CloudDownloadAction(accountInfo,objectInfo);
462
                    }
463
                }
464
                //If the previous file does not exist, we need to download it in the new location
465
                else
466
                {
467
                    //Remote files should be downloaded
468
                    yield return new CloudDownloadAction(accountInfo, objectInfo);
469
                }
470
            }
471
        }
472

    
473

    
474
        /// <summary>
475
        /// Creates a download action for each new server file
476
        /// </summary>
477
        /// <param name="accountInfo"></param>
478
        /// <param name="creates"></param>
479
        /// <returns></returns>
480
        private IEnumerable<CloudAction> CreatesToActions(AccountInfo accountInfo, IEnumerable<ObjectInfo> creates)
481
        {
482
            if (creates == null)
483
                throw new ArgumentNullException();
484
            Contract.EndContractBlock();
485
            var fileAgent = FileAgent.GetFileAgent(accountInfo);
486

    
487
            //In order to avoid multiple iterations over the files, we iterate only once
488
            //over the remote files
489
            foreach (var objectInfo in creates)
490
            {
491
                var relativePath = objectInfo.RelativeUrlToFilePath(accountInfo.UserName);
492
                //If the object already exists, we probably have a conflict
493
                if (fileAgent.Exists(relativePath))
494
                {
495
                    //If a directory object already exists, we don't need to perform any other action                    
496
                    var localFile = fileAgent.GetFileSystemInfo(relativePath);
497
                    StatusKeeper.SetFileState(localFile.FullName, FileStatus.Conflict, FileOverlayStatus.Conflict);
498
                }
499
                else
500
                {
501
                    //Remote files should be downloaded
502
                    yield return new CloudDownloadAction(accountInfo, objectInfo);
503
                }
504
            }
505
        }
506

    
507
        /// <summary>
508
        /// Notify the UI to update the visual status
509
        /// </summary>
510
        /// <param name="status"></param>
511
        private void UpdateStatus(PithosStatus status)
512
        {
513
            try
514
            {
515
                StatusKeeper.SetPithosStatus(status);
516
                StatusNotification.Notify(new Notification());
517
            }
518
            catch (Exception exc)
519
            {
520
                //Failure is not critical, just log it
521
                Log.Warn("Error while updating status", exc);
522
            }
523
        }
524

    
525
        private static void CreateContainerFolders(AccountInfo accountInfo, IEnumerable<ContainerInfo> containers)
526
        {
527
            var containerPaths = from container in containers
528
                                 let containerPath = Path.Combine(accountInfo.AccountPath, container.Name)
529
                                 where container.Name != FolderConstants.TrashContainer && !Directory.Exists(containerPath)
530
                                 select containerPath;
531

    
532
            foreach (var path in containerPaths)
533
            {
534
                Directory.CreateDirectory(path);
535
            }
536
        }
537

    
538
        public void SetSyncUris(Uri[] uris)
539
        {            
540
            SelectiveUris=uris.ToList();
541
        }
542

    
543
        protected List<Uri> SelectiveUris
544
        {
545
            get { return _selectiveUris;}
546
            set { _selectiveUris = value; }
547
        }
548

    
549
        public void AddAccount(AccountInfo accountInfo)
550
        {
551
            //Avoid adding a duplicate accountInfo
552
            _accounts.TryAdd(accountInfo.UserName, accountInfo);
553
        }
554

    
555
        public void RemoveAccount(AccountInfo accountInfo)
556
        {
557
            AccountInfo account;
558
            _accounts.TryRemove(accountInfo.UserName,out account);
559
        }
560
    }
561
}