Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / StatusAgent.cs @ 1b4a7550

History | View | Annotate | Download (23.3 kB)

1
using System;
2
using System.Collections.Generic;
3
using System.ComponentModel.Composition;
4
using System.Data.SQLite;
5
using System.Diagnostics;
6
using System.Diagnostics.Contracts;
7
using System.IO;
8
using System.Linq;
9
using System.Threading;
10
using System.Threading.Tasks;
11
using Castle.ActiveRecord;
12
using Castle.ActiveRecord.Framework.Config;
13
using Pithos.Interfaces;
14
using Pithos.Network;
15
using log4net;
16

    
17
namespace Pithos.Core.Agents
18
{
19
    [Export(typeof(IStatusChecker)),Export(typeof(IStatusKeeper))]
20
    public class StatusAgent:IStatusChecker,IStatusKeeper
21
    {
22
        [System.ComponentModel.Composition.Import]
23
        public IPithosSettings Settings { get; set; }
24

    
25
        private Agent<Action> _persistenceAgent;
26

    
27

    
28
        private static readonly ILog Log = LogManager.GetLogger("StatusAgent");
29

    
30
        public StatusAgent()
31
        {            
32
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
33
            _pithosDataPath = Path.Combine(appDataPath , "Pithos");
34

    
35
            if (!Directory.Exists(_pithosDataPath))
36
                Directory.CreateDirectory(_pithosDataPath);
37
            var source = GetConfiguration(_pithosDataPath);
38
            ActiveRecordStarter.Initialize(source,typeof(FileState),typeof(FileTag));
39
            ActiveRecordStarter.UpdateSchema();
40

    
41
            if (!File.Exists(Path.Combine(_pithosDataPath ,"pithos.db")))
42
                ActiveRecordStarter.CreateSchema();
43
        }        
44

    
45
        private static InPlaceConfigurationSource GetConfiguration(string pithosDbPath)
46
        {
47
            if (String.IsNullOrWhiteSpace(pithosDbPath))
48
                throw new ArgumentNullException("pithosDbPath");
49
            if (!Path.IsPathRooted(pithosDbPath))
50
                throw new ArgumentException("path must be a rooted path", "pithosDbPath");
51
            Contract.EndContractBlock();
52

    
53
            var properties = new Dictionary<string, string>
54
                                 {
55
                                     {"connection.driver_class", "NHibernate.Driver.SQLite20Driver"},
56
                                     {"dialect", "NHibernate.Dialect.SQLiteDialect"},
57
                                     {"connection.provider", "NHibernate.Connection.DriverConnectionProvider"},
58
                                     {
59
                                         "proxyfactory.factory_class",
60
                                         "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
61
                                         },
62
                                 };
63

    
64
            var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N", pithosDbPath);
65
            properties.Add("connection.connection_string", connectionString);
66

    
67
            var source = new InPlaceConfigurationSource();                        
68
            source.Add(typeof (ActiveRecordBase), properties);
69
            source.SetDebugFlag(false);            
70
            return source;
71
        }
72

    
73
        public void StartProcessing(CancellationToken token)
74
        {
75
            _persistenceAgent = Agent<Action>.Start(queue =>
76
            {
77
                Action loop = null;
78
                loop = () =>
79
                {
80
                    var job = queue.Receive();
81
                    job.ContinueWith(t =>
82
                    {
83
                        var action = job.Result;
84
                        try
85
                        {
86
                            action();
87
                        }
88
                        catch (SQLiteException ex)
89
                        {
90
                            Log.ErrorFormat("[ERROR] SQL \n{0}", ex);
91
                        }
92
                        catch (Exception ex)
93
                        {
94
                            Log.ErrorFormat("[ERROR] STATE \n{0}", ex);
95
                        }
96
// ReSharper disable AccessToModifiedClosure
97
                        queue.DoAsync(loop);
98
// ReSharper restore AccessToModifiedClosure
99
                    });
100
                };
101
                loop();
102
            });
103
            
104
        }
105

    
106
       
107

    
108
        public void Stop()
109
        {
110
            _persistenceAgent.Stop();            
111
        }
112
       
113

    
114
        public void ProcessExistingFiles(IEnumerable<FileInfo> existingFiles)
115
        {
116
            if(existingFiles  ==null)
117
                throw new ArgumentNullException("existingFiles");
118
            Contract.EndContractBlock();
119
            
120
            //Find new or matching files with a left join to the stored states
121
            var fileStates = FileState.Queryable;
122
            var currentFiles=from file in existingFiles
123
                      join state in fileStates on file.FullName.ToLower() equals state.FilePath.ToLower() into gs
124
                      from substate in gs.DefaultIfEmpty()
125
                               select new {File = file, State = substate};
126

    
127
            //To get the deleted files we must get the states that have no corresponding
128
            //files. 
129
            //We can't use the File.Exists method inside a query, so we get all file paths from the states
130
            var statePaths = (from state in fileStates
131
                             select new {state.Id, state.FilePath}).ToList();
132
            //and check each one
133
            var missingStates= (from path in statePaths
134
                                where !File.Exists(path.FilePath) && !Directory.Exists(path.FilePath)
135
                               select path.Id).ToList();
136
            //Finally, retrieve the states that correspond to the deleted files            
137
            var deletedFiles = from state in fileStates 
138
                        where missingStates.Contains(state.Id)
139
                        select new { File = default(FileInfo), State = state };
140

    
141
            var pairs = currentFiles.Union(deletedFiles);
142

    
143
            foreach(var pair in pairs)
144
            {
145
                var fileState = pair.State;
146
                var file = pair.File;
147
                if (fileState == null)
148
                {
149
                    //This is a new file
150
                    var fullPath = pair.File.FullName.ToLower();
151
                    var createState = FileState.CreateForAsync(fullPath, BlockSize, BlockHash);
152
                    createState.ContinueWith(state => _persistenceAgent.Post(state.Result.Create));
153
                }                
154
                else if (file == null)
155
                {
156
                    //This file was deleted while we were down. We should mark it as deleted
157
                    //We have to go through UpdateStatus here because the state object we are using
158
                    //was created by a different ORM session.
159
                    _persistenceAgent.Post(()=> UpdateStatusDirect(fileState.Id, FileStatus.Deleted));                    
160
                }
161
                else
162
                {
163
                    //This file has a matching state. Need to check for possible changes
164
                    var hashString = file.CalculateHash(BlockSize,BlockHash);
165
                    //If the hashes don't match the file was changed
166
                    if (fileState.Checksum != hashString)
167
                    {
168
                        _persistenceAgent.Post(() => UpdateStatusDirect(fileState.Id, FileStatus.Modified));
169
                    }                    
170
                }
171
            };            
172
         
173
        }
174

    
175
        private int UpdateStatusDirect(Guid id, FileStatus status)
176
        {
177
            try
178
            {
179

    
180
                var connectionString = GetConnectionString();
181
                using (var connection = new SQLiteConnection(connectionString))
182
                using (var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where Id = :id  ",
183
                                                    connection))
184
                {
185
                    
186

    
187
                    command.Parameters.AddWithValue("fileStatus", status);
188

    
189
                    command.Parameters.AddWithValue("id", id);
190
                    connection.Open();
191
                    var affected = command.ExecuteNonQuery();
192
                    return affected;
193
                }
194
            }
195
            catch (Exception exc)
196
            {
197
                Log.Error(exc.ToString());
198
                throw;
199
            }
200

    
201
        }
202
        
203
        private int UpdateStatusDirect(string path, FileStatus status)
204
        {
205
            try
206
            {
207

    
208
                var connectionString = GetConnectionString();
209
                using (var connection = new SQLiteConnection(connectionString))
210
                using (var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where FilePath = :path ",
211
                                                    connection))
212
                {
213
                    
214

    
215
                    command.Parameters.AddWithValue("fileStatus", status);
216

    
217
                    command.Parameters.AddWithValue("path", path.ToLower());
218
                    connection.Open();
219
                    var affected = command.ExecuteNonQuery();
220
                    return affected;
221
                }
222
            }
223
            catch (Exception exc)
224
            {
225
                Log.Error(exc.ToString());
226
                throw;
227
            }
228

    
229
        }
230

    
231
        private int UpdateStatusDirect(string absolutePath, FileStatus fileStatus, FileOverlayStatus overlayStatus)
232
        {
233
            try
234
            {
235

    
236
                var connectionString = GetConnectionString();
237
                using (var connection = new SQLiteConnection(connectionString))
238
                using (var command = new SQLiteCommand("update FileState set OverlayStatus= :overlayStatus, FileStatus= :fileStatus where FilePath = :path  ",
239
                                                    connection))
240
                {
241
                    
242
                    command.Parameters.AddWithValue("path", absolutePath.ToLower());
243
                    command.Parameters.AddWithValue("fileStatus", fileStatus);
244
                    command.Parameters.AddWithValue("overlayStatus", overlayStatus);
245
                    connection.Open();
246
                    var affected = command.ExecuteNonQuery();
247
                    return affected;
248
                }
249
            }
250
            catch (Exception exc)
251
            {
252
                Log.Error(exc.ToString());
253
                throw;
254
            }
255

    
256
        }
257
        
258

    
259

    
260
        public string BlockHash { get; set; }
261

    
262
        public int BlockSize { get; set; }
263
        public void ChangeRoots(string oldPath, string newPath)
264
        {
265
            if (String.IsNullOrWhiteSpace(oldPath))
266
                throw new ArgumentNullException("oldPath");
267
            if (!Path.IsPathRooted(oldPath))
268
                throw new ArgumentException("oldPath must be an absolute path", "oldPath");
269
            if (string.IsNullOrWhiteSpace(newPath))
270
                throw new ArgumentNullException("newPath");
271
            if (!Path.IsPathRooted(newPath))
272
                throw new ArgumentException("newPath must be an absolute path", "newPath");
273
            Contract.EndContractBlock();
274

    
275
            FileState.ChangeRootPath(oldPath,newPath);
276

    
277
        }
278

    
279
        private PithosStatus _pithosStatus=PithosStatus.InSynch;       
280

    
281
        public void SetPithosStatus(PithosStatus status)
282
        {
283
            _pithosStatus = status;
284
        }
285

    
286
        public PithosStatus GetPithosStatus()
287
        {
288
            return _pithosStatus;
289
        }
290

    
291

    
292
        private readonly string _pithosDataPath;
293

    
294

    
295
        public FileOverlayStatus GetFileOverlayStatus(string path)
296
        {
297
            if (String.IsNullOrWhiteSpace(path))
298
                throw new ArgumentNullException("path");
299
            if (!Path.IsPathRooted(path))
300
                throw new ArgumentException("The path must be rooted", "path");
301
            Contract.EndContractBlock();
302

    
303
            try
304
            {
305
                var connectionString = GetConnectionString();
306
                using (var connection = new SQLiteConnection(connectionString))
307
                using (var command = new SQLiteCommand("select OverlayStatus from FileState where FilePath=:path", connection))
308
                {
309
                    
310
                    command.Parameters.AddWithValue("path", path.ToLower());
311
                    connection.Open();
312
                    var s = command.ExecuteScalar();
313
                    return (FileOverlayStatus) Convert.ToInt32(s);
314
                }
315
            }
316
            catch (Exception exc)
317
            {
318
                Log.ErrorFormat(exc.ToString());
319
                return FileOverlayStatus.Unversioned;
320
            }
321
        }
322

    
323
        private string GetConnectionString()
324
        {
325
            var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N;Pooling=True;Default Isolation Level=ReadCommited", _pithosDataPath);
326
            return connectionString;
327
        }
328

    
329
        public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
330
        {
331
            if (String.IsNullOrWhiteSpace(path))
332
                throw new ArgumentNullException("path");
333
            if (!Path.IsPathRooted(path))
334
                throw new ArgumentException("The path must be rooted","path");
335
            Contract.EndContractBlock();
336

    
337
            _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path.ToLower(),overlayStatus));
338
        }
339

    
340
       /* public void RenameFileOverlayStatus(string oldPath, string newPath)
341
        {
342
            if (String.IsNullOrWhiteSpace(oldPath))
343
                throw new ArgumentNullException("oldPath");
344
            if (!Path.IsPathRooted(oldPath))
345
                throw new ArgumentException("The oldPath must be rooted", "oldPath");
346
            if (String.IsNullOrWhiteSpace(newPath))
347
                throw new ArgumentNullException("newPath");
348
            if (!Path.IsPathRooted(newPath))
349
                throw new ArgumentException("The newPath must be rooted", "newPath");
350
            Contract.EndContractBlock();
351

    
352
            _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
353
        }*/
354

    
355
        public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
356
        {
357
            if (String.IsNullOrWhiteSpace(path))
358
                throw new ArgumentNullException("path");
359
            if (!Path.IsPathRooted(path))
360
                throw new ArgumentException("The path must be rooted", "path");
361
            Contract.EndContractBlock();
362

    
363
            Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
364
            Debug.Assert(!path.EndsWith(".ignore"));
365

    
366
            _persistenceAgent.Post(() => UpdateStatusDirect(path.ToLower(), fileStatus, overlayStatus));
367
        }
368

    
369
        public void StoreInfo(string path,ObjectInfo objectInfo)
370
        {
371
            if (String.IsNullOrWhiteSpace(path))
372
                throw new ArgumentNullException("path");
373
            if (!Path.IsPathRooted(path))
374
                throw new ArgumentException("The path must be rooted", "path");            
375
            if (objectInfo == null)
376
                throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
377
            Contract.EndContractBlock();
378

    
379
            _persistenceAgent.Post(() =>
380
            {
381
                var filePath = path.ToLower();
382
                //Load the existing files state and set its properties in one session            
383
                using (new SessionScope())
384
                {
385
                    //Forgetting to use a sessionscope results in two sessions being created, one by 
386
                    //FirstOrDefault and one by Save()
387
                    var state =FileState.FindByFilePath(filePath);
388
                    
389
                    //Create a new empty state object if this is a new file
390
                    state = state ?? new FileState();
391

    
392
                    state.FilePath = filePath;
393
                    state.Checksum = objectInfo.Hash;
394
                    state.Version = objectInfo.Version;
395
                    state.VersionTimeStamp = objectInfo.VersionTimestamp;
396

    
397
                    state.FileStatus = FileStatus.Unchanged;
398
                    state.OverlayStatus = FileOverlayStatus.Normal;
399
                    
400
                  
401
                    //Do the save
402
                    state.Save();
403
                }
404
            });
405

    
406
        }
407
        public void StoreInfoDirect(string path, ObjectInfo objectInfo)
408
        {
409
            if (String.IsNullOrWhiteSpace(path))
410
                throw new ArgumentNullException("path");
411
            if (!Path.IsPathRooted(path))
412
                throw new ArgumentException("The path must be rooted", "path");
413
            if (objectInfo == null)
414
                throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
415
            Contract.EndContractBlock();
416

    
417
            _persistenceAgent.Post(() =>
418
                                       {
419
                                           try
420
                                           {
421

    
422
                                               var connectionString = GetConnectionString();
423
                                               using (var connection = new SQLiteConnection(connectionString))
424
                                               {
425
                                                   if (StateExists(path))
426
                                                   var command =
427
                                                       new SQLiteCommand(
428
                                                           "update FileState set FileStatus= :fileStatus where Id = :id  ",
429
                                                           connection);
430

    
431
                                                   
432
                                                   var filePath = path.ToLower();
433
                                                   //Load the existing files state and set its properties in one session            
434
                                                   using (new SessionScope())
435
                                                   {
436
                                                       //Forgetting to use a sessionscope results in two sessions being created, one by 
437
                                                       //FirstOrDefault and one by Save()
438
                                                       var state = FileState.FindByFilePath(filePath);
439

    
440
                                                       //Create a new empty state object if this is a new file
441
                                                       state = state ?? new FileState();
442

    
443
                                                       state.FilePath = filePath;
444
                                                       state.Checksum = objectInfo.Hash;
445
                                                       state.Version = objectInfo.Version;
446
                                                       state.VersionTimeStamp = objectInfo.VersionTimestamp;
447

    
448
                                                       state.FileStatus = FileStatus.Unchanged;
449
                                                       state.OverlayStatus = FileOverlayStatus.Normal;
450

    
451

    
452
                                                       //Do the save
453
                                                       state.Save();
454
                                                   }
455

    
456

    
457
                                                   command.Parameters.AddWithValue("fileStatus", status);
458

    
459
                                                   command.Parameters.AddWithValue("id", id);
460
                                                   connection.Open();
461
                                                   var affected = command.ExecuteNonQuery();
462
                                                   return;
463
                                               }
464
                                           }
465
                                           catch (Exception exc)
466
                                           {
467
                                               Log.Error(exc.ToString());
468
                                               throw;
469
                                           }
470

    
471
                                       });
472

    
473
        }
474

    
475
        private bool StateExists(string filePath,SQLiteConnection connection)
476
        {
477
            using(var command=new SQLiteCommand("Select count(*) from FileState where FilePath=:path",connection))
478
            {
479
                command.Parameters.AddWithValue("path", filePath.ToLower());
480
                var result=command.ExecuteScalar();
481
                    new SQLiteCommand(
482
                        "update FileState set FileStatus= :fileStatus where Id = :id  ",
483
                        connection);
484

    
485
                                                   
486
            
487
        }
488

    
489
        public void SetFileStatus(string path, FileStatus status)
490
        {
491
            if (String.IsNullOrWhiteSpace(path))
492
                throw new ArgumentNullException("path");
493
            if (!Path.IsPathRooted(path))
494
                throw new ArgumentException("The path must be rooted", "path");
495
            Contract.EndContractBlock();
496
            
497
            _persistenceAgent.Post(() => UpdateStatusDirect(path.ToLower(), status));
498
        }
499

    
500
        public FileStatus GetFileStatus(string path)
501
        {
502
            if (String.IsNullOrWhiteSpace(path))
503
                throw new ArgumentNullException("path");
504
            if (!Path.IsPathRooted(path))
505
                throw new ArgumentException("The path must be rooted", "path");
506
            Contract.EndContractBlock();
507

    
508
            var connectionString = GetConnectionString();
509
            using (var connection = new SQLiteConnection(connectionString))
510
            {
511
                var command = new SQLiteCommand("select FileStatus from FileState where FilePath=:path", connection);
512
                command.Parameters.AddWithValue("path", path.ToLower());
513
                connection.Open();
514
                var s = command.ExecuteScalar();
515
                return (FileStatus)Convert.ToInt32(s);
516
            }
517
        }
518

    
519
        public void ClearFileStatus(string path)
520
        {
521
            if (String.IsNullOrWhiteSpace(path))
522
                throw new ArgumentNullException("path");
523
            if (!Path.IsPathRooted(path))
524
                throw new ArgumentException("The path must be rooted", "path");
525
            Contract.EndContractBlock();
526

    
527
            _persistenceAgent.Post(() => DeleteDirect(path));   
528
        }
529

    
530
        private int DeleteDirect(string filePath)
531
        {
532
            try
533
            {
534

    
535
                var connectionString = GetConnectionString();
536
                using (var connection = new SQLiteConnection(connectionString))
537
                {
538
                    var command = new SQLiteCommand("delete FileState where FilePath = :path",
539
                                                    connection);
540

    
541
                    command.Parameters.AddWithValue("path", filePath.ToLower());
542
                    connection.Open();
543
                    var affected = command.ExecuteNonQuery();
544
                    return affected;
545
                }
546
            }
547
            catch (Exception exc)
548
            {
549
                Log.Error(exc.ToString());
550
                throw;
551
            }
552

    
553
        }
554

    
555
        public void UpdateFileChecksum(string path, string checksum)
556
        {
557
            if (String.IsNullOrWhiteSpace(path))
558
                throw new ArgumentNullException("path");
559
            if (!Path.IsPathRooted(path))
560
                throw new ArgumentException("The path must be rooted", "path");            
561
            Contract.EndContractBlock();
562

    
563
            _persistenceAgent.Post(() => FileState.UpdateChecksum(path.ToLower(), checksum));
564
        }
565

    
566
    }
567

    
568
   
569
}