Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / PithosMonitor.cs @ c636df1f

History | View | Annotate | Download (20.6 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="PithosMonitor.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
using System;
43
using System.Collections.Generic;
44
using System.ComponentModel.Composition;
45
using System.Diagnostics.Contracts;
46
using System.IO;
47
using System.Linq;
48
using System.Threading;
49
using System.Threading.Tasks;
50
using Pithos.Core.Agents;
51
using Pithos.Interfaces;
52
using Pithos.Network;
53
using log4net;
54

    
55
namespace Pithos.Core
56
{
57
    [Export(typeof(PithosMonitor))]
58
    public class PithosMonitor:IDisposable
59
    {
60
        private int _blockSize;
61
        private string _blockHash;
62

    
63
        [Import]
64
        public IPithosSettings Settings{get;set;}
65

    
66
        private IStatusKeeper _statusKeeper;
67

    
68
        [Import]
69
        public IStatusKeeper StatusKeeper
70
        {
71
            get { return _statusKeeper; }
72
            set
73
            {
74
                _statusKeeper = value;
75
                FileAgent.StatusKeeper = value;
76
            }
77
        }
78

    
79

    
80
        private IPithosWorkflow _workflow;
81

    
82
        [Import]
83
        public IPithosWorkflow Workflow
84
        {
85
            get { return _workflow; }
86
            set
87
            {
88
                _workflow = value;
89
                FileAgent.Workflow = value;
90
            }
91
        }
92

    
93
        public ICloudClient CloudClient { get; set; }
94

    
95
        public IStatusNotification StatusNotification { get; set; }
96

    
97
        //[Import]
98
        public FileAgent FileAgent { get; private set; }
99

    
100
        private WorkflowAgent _workflowAgent;
101

    
102
        [Import]
103
        public WorkflowAgent WorkflowAgent
104
        {
105
            get { return _workflowAgent; }
106
            set
107
            {
108
                _workflowAgent = value;
109
                FileAgent.WorkflowAgent = value;
110
            }
111
        }
112
        
113
        [Import]
114
        public NetworkAgent NetworkAgent { get; set; }
115
        [Import]
116
        public PollAgent PollAgent { get; set; }       
117

    
118
        public string UserName { get; set; }
119
        private string _apiKey;
120
        public string ApiKey
121
        {
122
            get { return _apiKey; }
123
            set
124
            {
125
                _apiKey = value;
126
                if (_accountInfo != null)
127
                    _accountInfo.Token = value;
128
            }
129
        }
130

    
131
        private AccountInfo _accountInfo;
132
        
133
       
134

    
135

    
136
        private static readonly ILog Log = LogManager.GetLogger(typeof(PithosMonitor));
137

    
138

    
139
        public bool Pause
140
        {
141
            get { return FileAgent.Pause; }
142
            set
143
            {
144
                FileAgent.Pause = value;
145
                if (value)
146
                {
147
                    StatusKeeper.SetPithosStatus(PithosStatus.SyncPaused);
148
                    StatusNotification.NotifyChange("Paused");
149
                }
150
                else
151
                {
152
                    StatusKeeper.SetPithosStatus(PithosStatus.InSynch);
153
                    StatusNotification.NotifyChange("Synchronizing");
154
                }
155
            }
156
        }
157

    
158
        private string _rootPath;
159
        public string RootPath
160
        {
161
            get { return _rootPath; }
162
            set 
163
            {
164
                _rootPath = String.IsNullOrWhiteSpace(value) 
165
                    ? String.Empty 
166
                    : value.ToLower();
167
            }
168
        }
169

    
170

    
171
        CancellationTokenSource _cancellationSource;
172

    
173
        public PithosMonitor()
174
        {
175
            FileAgent = new FileAgent();
176

    
177
        }
178
        private bool _started;
179

    
180
        public void Start()
181
        {            
182
            if (String.IsNullOrWhiteSpace(ApiKey))
183
                throw new InvalidOperationException("The ApiKey is empty");
184
            if (String.IsNullOrWhiteSpace(UserName))
185
                throw new InvalidOperationException("The UserName is empty");
186
            if (String.IsNullOrWhiteSpace(AuthenticationUrl))
187
                throw new InvalidOperationException("The Authentication url is empty");
188
            Contract.EndContractBlock();
189

    
190
            //If the account doesn't have a valid path, don't start monitoring but don't throw either
191
            if (String.IsNullOrWhiteSpace(RootPath))
192
                //TODO; Warn user?
193
                return;
194

    
195
            WorkflowAgent.StatusNotification = StatusNotification;
196

    
197
            StatusNotification.NotifyChange("Starting");
198
            if (_started)
199
            {
200
                if (!_cancellationSource.IsCancellationRequested)
201
                    return;
202
            }
203
            _cancellationSource = new CancellationTokenSource();
204

    
205

    
206
            CloudClient = new CloudFilesClient(UserName, ApiKey)
207
                              {UsePithos = true, AuthenticationUrl = AuthenticationUrl};
208

    
209

    
210
            _accountInfo = CloudClient.Authenticate();            
211
            _accountInfo.SiteUri = AuthenticationUrl;
212
            _accountInfo.AccountPath = RootPath;
213

    
214

    
215
            var pithosFolder = Path.Combine(RootPath, FolderConstants.PithosContainer);
216
            if (!Directory.Exists(pithosFolder))
217
                Directory.CreateDirectory(pithosFolder);
218
            //Create the cache folder and ensure it is hidden
219
            CreateHiddenFolder(RootPath, FolderConstants.CacheFolder);
220

    
221
            var policy=CloudClient.GetAccountPolicies(_accountInfo);
222

    
223
            StatusNotification.NotifyAccount(policy);
224
            EnsurePithosContainers();
225
            
226
            StatusKeeper.BlockHash = _blockHash;
227
            StatusKeeper.BlockSize = _blockSize;
228
            
229
            StatusKeeper.StartProcessing(_cancellationSource.Token);
230
            IndexLocalFiles();
231
            //Extract the URIs from the string collection
232
            var settings = Settings.Accounts.First(s => s.AccountName == _accountInfo.UserName);
233
            var selectiveUrls=settings.SelectiveFolders.Cast<string>().Select(url => new Uri(url)).ToArray();
234

    
235
            SetSelectivePaths(selectiveUrls,null,null);
236
            
237
            StartWatcherAgent();
238

    
239
            StartNetworkAgent();
240
            
241
            WorkflowAgent.RestartInterruptedFiles(_accountInfo);
242
            _started = true;
243
        }
244

    
245
        private void EnsurePithosContainers()
246
        {
247

    
248
            //Create the two default containers if they are missing
249
            var pithosContainers = new List<string>{ FolderConstants.TrashContainer,FolderConstants.PithosContainer};
250
            foreach (var container in pithosContainers)
251
            {                
252
                var info=CloudClient.GetContainerInfo(UserName, container);
253
                if (info == ContainerInfo.Empty)
254
                {
255
                    CloudClient.CreateContainer(UserName, container);
256
                    info = CloudClient.GetContainerInfo(UserName, container);
257
                }
258
                _blockSize = info.BlockSize;
259
                _blockHash = info.BlockHash;
260
                _accountInfo.BlockSize = _blockSize;
261
                _accountInfo.BlockHash = _blockHash;
262
            }
263
        }
264

    
265
        public string AuthenticationUrl { get; set; }
266

    
267
        private void IndexLocalFiles()
268
        {
269
            StatusNotification.NotifyChange("Indexing Local Files");
270
            using (ThreadContext.Stacks["Monitor"].Push("Indexing local files"))
271
            {
272
                Log.Info("START");
273
                try
274
                {
275
                    var cachePath = Path.Combine(RootPath, FolderConstants.CacheFolder);
276
                    var directory = new DirectoryInfo(RootPath);
277
                    var files =
278
                        from file in directory.EnumerateFiles("*", SearchOption.AllDirectories)
279
                        where !file.FullName.StartsWith(cachePath, StringComparison.InvariantCultureIgnoreCase) &&
280
                              !file.Extension.Equals("ignore", StringComparison.InvariantCultureIgnoreCase)
281
                        select file;
282
                    StatusKeeper.ProcessExistingFiles(files);
283

    
284
                }
285
                catch (Exception exc)
286
                {
287
                    Log.Error("[ERROR]", exc);
288
                }
289
                finally
290
                {
291
                    Log.Info("[END]");
292
                }
293
            }
294
        }
295

    
296
        
297
  
298

    
299

    
300
       /* private void StartWorkflowAgent()
301
        {
302
            WorkflowAgent.StatusNotification = StatusNotification;
303

    
304
/*            //On Vista and up we can check for a network connection
305
            bool connected=Environment.OSVersion.Version.Major < 6 || NetworkListManager.IsConnectedToInternet;
306
            //If we are not connected retry later
307
            if (!connected)
308
            {
309
                Task.Factory.StartNewDelayed(10000, StartWorkflowAgent);
310
                return;
311
            }#1#
312

    
313
            try
314
            {
315
                WorkflowAgent.Start();                
316
            }
317
            catch (Exception)
318
            {
319
                //Faild to authenticate due to network or account error
320
                //Retry after a while
321
                Task.Factory.StartNewDelayed(10000, StartWorkflowAgent);
322
            }
323
        }*/
324

    
325
        internal class LocalFileComparer:EqualityComparer<CloudAction>
326
        {
327
            public override bool Equals(CloudAction x, CloudAction y)
328
            {
329
                if (x.Action != y.Action)
330
                    return false;
331
                if (x.LocalFile != null && y.LocalFile != null && !x.LocalFile.FullName.Equals(y.LocalFile.FullName))
332
                    return false;
333
                if (x.CloudFile != null && y.CloudFile != null )
334
                {
335
                    if (x.CloudFile.Hash == null & y.CloudFile.Hash != null)
336
                        return false;
337
                    if (x.CloudFile.Hash != null & y.CloudFile.Hash == null)
338
                        return false;
339
                    if (x.CloudFile.Hash == null & y.CloudFile.Hash == null)
340
                        return (x.CloudFile.Name == y.CloudFile.Name);
341
                    if (!x.CloudFile.Hash.Equals(y.CloudFile.Hash))
342
                        return false;
343
                }
344
                if (x.CloudFile == null ^ y.CloudFile == null ||
345
                    x.LocalFile == null ^ y.LocalFile == null)
346
                    return false;
347
                return true;
348
            }
349

    
350
            public override int GetHashCode(CloudAction obj)
351
            {
352
                if (obj == null)
353
                    return 0;
354
                var hash1 = (obj.LocalFile == null) ? int.MaxValue : obj.LocalFile.FullName.GetHashCode();
355
                var hash2 = (obj.CloudFile == null) ? int.MaxValue : (obj.CloudFile.Hash ?? obj.CloudFile.Name??"").GetHashCode();
356
                var hash3 = obj.Action.GetHashCode();
357
                return hash1 ^ hash2 & hash3;
358
            }
359
        }        
360

    
361
        private void StartNetworkAgent()
362
        {
363

    
364
            NetworkAgent.AddAccount(_accountInfo);
365

    
366
            NetworkAgent.StatusNotification = StatusNotification;
367
                        
368
            NetworkAgent.Start();
369

    
370
            PollAgent.AddAccount(_accountInfo);
371

    
372
            PollAgent.StatusNotification = StatusNotification;
373

    
374
            PollAgent.PollRemoteFiles();
375
        }
376

    
377
        //Make sure a hidden cache folder exists to store partial downloads
378
        private static void CreateHiddenFolder(string rootPath, string folderName)
379
        {
380
            if (String.IsNullOrWhiteSpace(rootPath))
381
                throw new ArgumentNullException("rootPath");
382
            if (!Path.IsPathRooted(rootPath))
383
                throw new ArgumentException("rootPath");
384
            if (String.IsNullOrWhiteSpace(folderName))
385
                throw new ArgumentNullException("folderName");
386
            Contract.EndContractBlock();
387

    
388
            var folder = Path.Combine(rootPath, folderName);
389
            if (!Directory.Exists(folder))
390
            {
391
                var info = Directory.CreateDirectory(folder);
392
                info.Attributes |= FileAttributes.Hidden;
393

    
394
                Log.InfoFormat("Created cache Folder: {0}", folder);
395
            }
396
            else
397
            {
398
                var info = new DirectoryInfo(folder);
399
                if ((info.Attributes & FileAttributes.Hidden) == 0)
400
                {
401
                    info.Attributes |= FileAttributes.Hidden;
402
                    Log.InfoFormat("Reset cache folder to hidden: {0}", folder);
403
                }                                
404
            }
405
        }
406

    
407
       
408

    
409

    
410
        private void StartWatcherAgent()
411
        {
412
            AgentLocator<FileAgent>.Register(FileAgent,RootPath);
413

    
414
            FileAgent.StatusKeeper = StatusKeeper;
415
            FileAgent.Workflow = Workflow;
416
            FileAgent.CachePath = Path.Combine(RootPath, FolderConstants.CacheFolder);
417
            FileAgent.Start(_accountInfo, RootPath);
418
        }
419

    
420
        public void Stop()
421
        {
422
            AgentLocator<FileAgent>.Remove(RootPath);
423

    
424
            if (FileAgent!=null)
425
                FileAgent.Stop();
426
            FileAgent = null;
427
        }
428

    
429

    
430
        ~PithosMonitor()
431
        {
432
            Dispose(false);
433
        }
434

    
435
        public void Dispose()
436
        {
437
            Dispose(true);
438
            GC.SuppressFinalize(this);
439
        }
440

    
441
        protected virtual void Dispose(bool disposing)
442
        {
443
            if (disposing)
444
            {
445
                Stop();
446
            }
447
        }
448

    
449

    
450
        public void MoveFileStates(string oldPath, string newPath)
451
        {
452
            if (String.IsNullOrWhiteSpace(oldPath))
453
                throw new ArgumentNullException("oldPath");
454
            if (!Path.IsPathRooted(oldPath))
455
                throw new ArgumentException("oldPath must be an absolute path","oldPath");
456
            if (string.IsNullOrWhiteSpace(newPath))
457
                throw new ArgumentNullException("newPath");
458
            if (!Path.IsPathRooted(newPath))
459
                throw new ArgumentException("newPath must be an absolute path","newPath");
460
            Contract.EndContractBlock();
461

    
462
            StatusKeeper.ChangeRoots(oldPath, newPath);
463
        }
464

    
465
        public void SetSelectivePaths(Uri[] uris,Uri[] added, Uri[] removed)
466
        {
467
            //Convert the uris to paths
468
            var selectivePaths = UrisToFilePaths(uris);
469
            
470
            FileAgent.SelectivePaths=selectivePaths;
471
            PollAgent.SetSyncUris(uris);
472
            
473
            var removedPaths = UrisToFilePaths(removed);
474
            UnversionSelectivePaths(removedPaths);
475

    
476
        }
477

    
478
        /// <summary>
479
        /// Mark all unselected paths as Unversioned
480
        /// </summary>
481
        /// <param name="removed"></param>
482
        private void UnversionSelectivePaths(List<string> removed)
483
        {
484
            if (removed == null)
485
                return;
486

    
487
            //Ensure we remove any file state below the deleted folders
488
            FileState.UnversionPaths(removed);
489
        }
490

    
491

    
492
        /// <summary>
493
        /// Return a list of absolute filepaths from a list of Uris
494
        /// </summary>
495
        /// <param name="uris"></param>
496
        /// <returns></returns>
497
        private List<string> UrisToFilePaths(IEnumerable<Uri> uris)
498
        {
499
            if (uris == null)
500
                return new List<string>();
501

    
502
            return (from uri in uris
503
                    let relativePath = _accountInfo.StorageUri
504
                        .MakeRelativeUri(uri)
505
                        .RelativeUriToFilePath()
506
                        //Trim the account name
507
                    select Path.Combine(RootPath, relativePath.After(_accountInfo.UserName + '\\'))).ToList();            
508
        }
509

    
510

    
511
        public ObjectInfo GetObjectInfo(string filePath)
512
        {
513
            if (String.IsNullOrWhiteSpace(filePath))
514
                throw new ArgumentNullException("filePath");
515
            Contract.EndContractBlock();
516

    
517
            var file=new FileInfo(filePath);
518
            string relativeUrl;//=file.AsRelativeUrlTo(this.RootPath);
519
            var relativePath = file.AsRelativeTo(RootPath);
520
            
521
            string accountName,container;
522
            
523
            var parts=relativePath.Split('\\');
524

    
525
            var accountInfo = _accountInfo;
526
            if (relativePath.StartsWith(FolderConstants.OthersFolder))
527
            {                
528
                accountName = parts[1];
529
                container = parts[2];
530
                relativeUrl = String.Join("/", parts.Splice(3));
531
                //Create the root URL for the target account
532
                var oldName = UserName;
533
                var absoluteUri =  _accountInfo.StorageUri.AbsoluteUri;
534
                var nameIndex=absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
535
                var root=absoluteUri.Substring(0, nameIndex);
536

    
537
                accountInfo = new AccountInfo
538
                {
539
                    UserName = accountName,
540
                    AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
541
                    StorageUri = new Uri(root + accountName),
542
                    BlockHash=accountInfo.BlockHash,
543
                    BlockSize=accountInfo.BlockSize,
544
                    Token=accountInfo.Token
545
                };
546
            }
547
            else
548
            {
549
                accountName = UserName;
550
                container = parts[0];
551
                relativeUrl = String.Join("/", parts.Splice(1));
552
            }
553
            
554
            var client = new CloudFilesClient(accountInfo);
555
            var objectInfo=client.GetObjectInfo(accountName, container, relativeUrl);
556
            return objectInfo;
557
        }
558
        
559
        public Task<ContainerInfo> GetContainerInfo(string filePath)
560
        {
561
            if (String.IsNullOrWhiteSpace(filePath))
562
                throw new ArgumentNullException("filePath");
563
            Contract.EndContractBlock();
564

    
565
            var file=new FileInfo(filePath);
566
            var relativePath = file.AsRelativeTo(RootPath);
567
            
568
            string accountName,container;
569
            
570
            var parts=relativePath.Split('\\');
571

    
572
            var accountInfo = _accountInfo;
573
            if (relativePath.StartsWith(FolderConstants.OthersFolder))
574
            {                
575
                accountName = parts[1];
576
                container = parts[2];                
577
                //Create the root URL for the target account
578
                var oldName = UserName;
579
                var absoluteUri =  _accountInfo.StorageUri.AbsoluteUri;
580
                var nameIndex=absoluteUri.IndexOf(oldName, StringComparison.Ordinal);
581
                var root=absoluteUri.Substring(0, nameIndex);
582

    
583
                accountInfo = new AccountInfo
584
                {
585
                    UserName = accountName,
586
                    AccountPath = Path.Combine(accountInfo.AccountPath, parts[0], parts[1]),
587
                    StorageUri = new Uri(root + accountName),
588
                    BlockHash=accountInfo.BlockHash,
589
                    BlockSize=accountInfo.BlockSize,
590
                    Token=accountInfo.Token
591
                };
592
            }
593
            else
594
            {
595
                accountName = UserName;
596
                container = parts[0];                
597
            }
598

    
599
            return Task.Factory.StartNew(() =>
600
            {
601
                var client = new CloudFilesClient(accountInfo);
602
                var containerInfo = client.GetContainerInfo(accountName, container);
603
                return containerInfo;
604
            });
605
        }
606
    }
607
}