Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / StatusAgent.cs @ 14ecd267

History | View | Annotate | Download (26.1 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

    
46

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

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

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

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

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

    
108
       
109

    
110
        public void Stop()
111
        {
112
            _persistenceAgent.Stop();            
113
        }
114
       
115

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

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

    
143
            var pairs = currentFiles.Union(deletedFiles);
144

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

    
177
        private int UpdateStatusDirect(Guid id, FileStatus status)
178
        {
179
            using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
180
            {
181

    
182
                try
183
                {
184
                    
185
                    using (var connection = GetConnection())
186
                    using (
187
                        var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where Id = :id  ",
188
                                                        connection))
189
                    {                                                
190
                        command.Parameters.AddWithValue("fileStatus", status);
191

    
192
                        command.Parameters.AddWithValue("id", id);
193
                        
194
                        var affected = command.ExecuteNonQuery();
195
                        
196
                        return affected;
197
                    }
198

    
199
                }
200
                catch (Exception exc)
201
                {
202
                    Log.Error(exc.ToString());
203
                    throw;
204
                }
205
            }
206
        }
207
        
208
        private int UpdateStatusDirect(string path, FileStatus status)
209
        {
210
            using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
211
            {
212

    
213
                try
214
                {
215

    
216
                    
217
                    using (var connection = GetConnection())
218
                    using (
219
                        var command =
220
                            new SQLiteCommand("update FileState set FileStatus= :fileStatus where FilePath = :path ",
221
                                              connection))
222
                    {
223

    
224

    
225
                        command.Parameters.AddWithValue("fileStatus", status);
226

    
227
                        command.Parameters.AddWithValue("path", path.ToLower());
228
                        
229
                        var affected = command.ExecuteNonQuery();
230
                        return affected;
231
                    }
232
                }
233
                catch (Exception exc)
234
                {
235
                    Log.Error(exc.ToString());
236
                    throw;
237
                }
238
            }
239
        }
240

    
241
        private int UpdateStatusDirect(string absolutePath, FileStatus fileStatus, FileOverlayStatus overlayStatus)
242
        {
243
            using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
244
            {
245

    
246
                try
247
                {
248

    
249
                    
250
                    using (var connection = GetConnection())
251
                    using (
252
                        var command =
253
                            new SQLiteCommand(
254
                                "update FileState set OverlayStatus= :overlayStatus, FileStatus= :fileStatus where FilePath = :path  ",
255
                                connection))
256
                    {
257

    
258
                        command.Parameters.AddWithValue("path", absolutePath.ToLower());
259
                        command.Parameters.AddWithValue("fileStatus", fileStatus);
260
                        command.Parameters.AddWithValue("overlayStatus", overlayStatus);
261
                        
262
                        var affected = command.ExecuteNonQuery();
263
                        return affected;
264
                    }
265
                }
266
                catch (Exception exc)
267
                {
268
                    Log.Error(exc.ToString());
269
                    throw;
270
                }
271
            }
272
        }
273
        
274

    
275

    
276
        public string BlockHash { get; set; }
277

    
278
        public int BlockSize { get; set; }
279
        public void ChangeRoots(string oldPath, string newPath)
280
        {
281
            if (String.IsNullOrWhiteSpace(oldPath))
282
                throw new ArgumentNullException("oldPath");
283
            if (!Path.IsPathRooted(oldPath))
284
                throw new ArgumentException("oldPath must be an absolute path", "oldPath");
285
            if (string.IsNullOrWhiteSpace(newPath))
286
                throw new ArgumentNullException("newPath");
287
            if (!Path.IsPathRooted(newPath))
288
                throw new ArgumentException("newPath must be an absolute path", "newPath");
289
            Contract.EndContractBlock();
290

    
291
            FileState.ChangeRootPath(oldPath,newPath);
292

    
293
        }
294

    
295
        private PithosStatus _pithosStatus=PithosStatus.InSynch;       
296

    
297
        public void SetPithosStatus(PithosStatus status)
298
        {
299
            _pithosStatus = status;
300
        }
301

    
302
        public PithosStatus GetPithosStatus()
303
        {
304
            return _pithosStatus;
305
        }
306

    
307

    
308
        private readonly string _pithosDataPath;
309

    
310

    
311
        public FileState GetStateByFilePath(string path)
312
        {
313
            if (String.IsNullOrWhiteSpace(path))
314
                throw new ArgumentNullException("path");
315
            if (!Path.IsPathRooted(path))
316
                throw new ArgumentException("The path must be rooted", "path");
317
            Contract.EndContractBlock();
318

    
319
            try
320
            {
321
                
322
                using (var connection = GetConnection())
323
                using (var command = new SQLiteCommand("select Id, FilePath, OverlayStatus,FileStatus ,Checksum   ,Version    ,VersionTimeStamp,IsShared   ,SharedBy   ,ShareWrite  from FileState where FilePath=:path", connection))
324
                {
325
                    
326
                    command.Parameters.AddWithValue("path", path.ToLower());
327
                    
328
                    using (var reader = command.ExecuteReader())
329
                    {
330
                        if (reader.Read())
331
                        {
332
                            //var values = new object[reader.FieldCount];
333
                            //reader.GetValues(values);
334
                            var state = new FileState
335
                                            {
336
                                                Id = reader.GetGuid(0),
337
                                                FilePath = reader.IsDBNull(1)?"":reader.GetString(1),
338
                                                OverlayStatus =reader.IsDBNull(2)?FileOverlayStatus.Unversioned: (FileOverlayStatus) reader.GetInt64(2),
339
                                                FileStatus = reader.IsDBNull(3)?FileStatus.Missing:(FileStatus) reader.GetInt64(3),
340
                                                Checksum = reader.IsDBNull(4)?"":reader.GetString(4),
341
                                                Version = reader.IsDBNull(5)?default(long):reader.GetInt64(5),
342
                                                VersionTimeStamp = reader.IsDBNull(6)?default(DateTime):reader.GetDateTime(6),
343
                                                IsShared = !reader.IsDBNull(7) && reader.GetBoolean(7),
344
                                                SharedBy = reader.IsDBNull(8)?"":reader.GetString(8),
345
                                                ShareWrite = !reader.IsDBNull(9) && reader.GetBoolean(9)
346
                                            };
347
/*
348
                            var state = new FileState
349
                                            {
350
                                                Id = (Guid) values[0],
351
                                                FilePath = (string) values[1],
352
                                                OverlayStatus = (FileOverlayStatus) (long)values[2],
353
                                                FileStatus = (FileStatus) (long)values[3],
354
                                                Checksum = (string) values[4],
355
                                                Version = (long?) values[5],
356
                                                VersionTimeStamp = (DateTime?) values[6],
357
                                                IsShared = (long)values[7] == 1,
358
                                                SharedBy = (string) values[8],
359
                                                ShareWrite = (long)values[9] == 1
360
                                            };
361
*/
362
                            return state;
363
                        }
364
                        else
365
                        {
366
                            return null;
367
                        }
368

    
369
                    }                    
370
                }
371
            }
372
            catch (Exception exc)
373
            {
374
                Log.ErrorFormat(exc.ToString());
375
                throw;
376
            }            
377
        }
378

    
379
        public FileOverlayStatus GetFileOverlayStatus(string path)
380
        {
381
            if (String.IsNullOrWhiteSpace(path))
382
                throw new ArgumentNullException("path");
383
            if (!Path.IsPathRooted(path))
384
                throw new ArgumentException("The path must be rooted", "path");
385
            Contract.EndContractBlock();
386

    
387
            try
388
            {
389
                
390
                using (var connection = GetConnection())
391
                using (var command = new SQLiteCommand("select OverlayStatus from FileState where FilePath=:path", connection))
392
                {
393
                    
394
                    command.Parameters.AddWithValue("path", path.ToLower());
395
                    
396
                    var s = command.ExecuteScalar();
397
                    return (FileOverlayStatus) Convert.ToInt32(s);
398
                }
399
            }
400
            catch (Exception exc)
401
            {
402
                Log.ErrorFormat(exc.ToString());
403
                return FileOverlayStatus.Unversioned;
404
            }
405
        }
406

    
407
        private string GetConnectionString()
408
        {
409
            var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N;Pooling=True", _pithosDataPath);
410
            return connectionString;
411
        }
412

    
413
        private SQLiteConnection GetConnection()
414
        {
415
            var connectionString = GetConnectionString();
416
            var connection = new SQLiteConnection(connectionString);
417
            connection.Open();
418
            using(var cmd =connection.CreateCommand())
419
            {
420
                cmd.CommandText = "PRAGMA journal_mode=WAL";
421
                cmd.ExecuteNonQuery();
422
            }
423
            return connection;
424
        }
425

    
426
        public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
427
        {
428
            if (String.IsNullOrWhiteSpace(path))
429
                throw new ArgumentNullException("path");
430
            if (!Path.IsPathRooted(path))
431
                throw new ArgumentException("The path must be rooted","path");
432
            Contract.EndContractBlock();
433

    
434
            _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path.ToLower(),overlayStatus));
435
        }
436

    
437
       /* public void RenameFileOverlayStatus(string oldPath, string newPath)
438
        {
439
            if (String.IsNullOrWhiteSpace(oldPath))
440
                throw new ArgumentNullException("oldPath");
441
            if (!Path.IsPathRooted(oldPath))
442
                throw new ArgumentException("The oldPath must be rooted", "oldPath");
443
            if (String.IsNullOrWhiteSpace(newPath))
444
                throw new ArgumentNullException("newPath");
445
            if (!Path.IsPathRooted(newPath))
446
                throw new ArgumentException("The newPath must be rooted", "newPath");
447
            Contract.EndContractBlock();
448

    
449
            _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
450
        }*/
451

    
452
        public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
453
        {
454
            if (String.IsNullOrWhiteSpace(path))
455
                throw new ArgumentNullException("path");
456
            if (!Path.IsPathRooted(path))
457
                throw new ArgumentException("The path must be rooted", "path");
458
            Contract.EndContractBlock();
459

    
460
            Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
461
            Debug.Assert(!path.EndsWith(".ignore"));
462

    
463
            _persistenceAgent.Post(() => UpdateStatusDirect(path.ToLower(), fileStatus, overlayStatus));
464
        }
465

    
466
/*
467
        public void StoreInfo(string path,ObjectInfo objectInfo)
468
        {
469
            if (String.IsNullOrWhiteSpace(path))
470
                throw new ArgumentNullException("path");
471
            if (!Path.IsPathRooted(path))
472
                throw new ArgumentException("The path must be rooted", "path");            
473
            if (objectInfo == null)
474
                throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
475
            Contract.EndContractBlock();
476

    
477
            _persistenceAgent.Post(() =>
478
            {
479
                var filePath = path.ToLower();
480
                //Load the existing files state and set its properties in one session            
481
                using (new SessionScope())
482
                {
483
                    //Forgetting to use a sessionscope results in two sessions being created, one by 
484
                    //FirstOrDefault and one by Save()
485
                    var state =FileState.FindByFilePath(filePath);
486
                    
487
                    //Create a new empty state object if this is a new file
488
                    state = state ?? new FileState();
489

    
490
                    state.FilePath = filePath;
491
                    state.Checksum = objectInfo.Hash;
492
                    state.Version = objectInfo.Version;
493
                    state.VersionTimeStamp = objectInfo.VersionTimestamp;
494

    
495
                    state.FileStatus = FileStatus.Unchanged;
496
                    state.OverlayStatus = FileOverlayStatus.Normal;
497
                    
498
                  
499
                    //Do the save
500
                    state.Save();
501
                }
502
            });
503

    
504
        }
505
*/
506
        
507
        public void StoreInfo(string path, ObjectInfo objectInfo)
508
        {
509
            if (String.IsNullOrWhiteSpace(path))
510
                throw new ArgumentNullException("path");
511
            if (!Path.IsPathRooted(path))
512
                throw new ArgumentException("The path must be rooted", "path");
513
            if (objectInfo == null)
514
                throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
515
            Contract.EndContractBlock();
516

    
517
            _persistenceAgent.Post(() => StoreInfoDirect(path, objectInfo));
518

    
519
        }
520

    
521
        private void StoreInfoDirect(string path, ObjectInfo objectInfo)
522
        {
523
            try
524
            {
525
                
526
                using (var connection = GetConnection())
527
                using (var command = new SQLiteCommand(connection))
528
                {
529
                    if (StateExists(path, connection))
530
                        command.CommandText =
531
                            "update FileState set FileStatus= :fileStatus where FilePath = :path  ";
532
                    else
533
                    {
534
                        command.CommandText =
535
                            "INSERT INTO FileState (Id,FilePath,Checksum,Version,VersionTimeStamp,FileStatus,OverlayStatus) VALUES (:id,:path,:checksum,:version,:versionTimeStamp,:fileStatus,:overlayStatus)";
536
                        command.Parameters.AddWithValue("id", Guid.NewGuid());
537
                    }
538

    
539
                    command.Parameters.AddWithValue("path", path.ToLower());
540
                    command.Parameters.AddWithValue("checksum", objectInfo.Hash);
541
                    command.Parameters.AddWithValue("version", objectInfo.Version);
542
                    command.Parameters.AddWithValue("versionTimeStamp",
543
                                                    objectInfo.VersionTimestamp);
544
                    command.Parameters.AddWithValue("fileStatus", FileStatus.Unchanged);
545
                    command.Parameters.AddWithValue("overlayStatus",
546
                                                    FileOverlayStatus.Normal);
547

    
548
                    var affected = command.ExecuteNonQuery();
549
                    return;
550
                }
551
            }
552
            catch (Exception exc)
553
            {
554
                Log.Error(exc.ToString());
555
                throw;
556
            }
557
        }
558

    
559
        private bool StateExists(string filePath,SQLiteConnection connection)
560
        {
561
            using (var command = new SQLiteCommand("Select count(*) from FileState where FilePath=:path", connection))
562
            {
563
                command.Parameters.AddWithValue("path", filePath.ToLower());
564
                var result = command.ExecuteScalar();
565
                return ((long)result >= 1);
566
            }
567

    
568
        }
569

    
570
        public void SetFileStatus(string path, FileStatus status)
571
        {
572
            if (String.IsNullOrWhiteSpace(path))
573
                throw new ArgumentNullException("path");
574
            if (!Path.IsPathRooted(path))
575
                throw new ArgumentException("The path must be rooted", "path");
576
            Contract.EndContractBlock();
577
            
578
            _persistenceAgent.Post(() => UpdateStatusDirect(path.ToLower(), status));
579
        }
580

    
581
        public FileStatus GetFileStatus(string path)
582
        {
583
            if (String.IsNullOrWhiteSpace(path))
584
                throw new ArgumentNullException("path");
585
            if (!Path.IsPathRooted(path))
586
                throw new ArgumentException("The path must be rooted", "path");
587
            Contract.EndContractBlock();
588

    
589
            
590
            using (var connection = GetConnection())
591
            {
592
                var command = new SQLiteCommand("select FileStatus from FileState where FilePath=:path", connection);
593
                command.Parameters.AddWithValue("path", path.ToLower());
594
                
595
                var s = command.ExecuteScalar();
596
                return (FileStatus)Convert.ToInt32(s);
597
            }
598
        }
599

    
600
        public void ClearFileStatus(string path)
601
        {
602
            if (String.IsNullOrWhiteSpace(path))
603
                throw new ArgumentNullException("path");
604
            if (!Path.IsPathRooted(path))
605
                throw new ArgumentException("The path must be rooted", "path");
606
            Contract.EndContractBlock();
607

    
608
            _persistenceAgent.Post(() => DeleteDirect(path));   
609
        }
610

    
611
        private int DeleteDirect(string filePath)
612
        {
613
            using (log4net.ThreadContext.Stacks["StatusAgent"].Push("DeleteDirect"))
614
            {
615

    
616
                try
617
                {
618

    
619
                    
620
                    using (var connection = GetConnection())
621
                    {
622
                        var command = new SQLiteCommand("delete from FileState where FilePath = :path",
623
                                                        connection);
624

    
625
                        command.Parameters.AddWithValue("path", filePath.ToLower());
626
                        
627
                        var affected = command.ExecuteNonQuery();
628
                        return affected;
629
                    }
630
                }
631
                catch (Exception exc)
632
                {
633
                    Log.Error(exc.ToString());
634
                    throw;
635
                }
636
            }
637
        }
638

    
639
        public void UpdateFileChecksum(string path, string checksum)
640
        {
641
            if (String.IsNullOrWhiteSpace(path))
642
                throw new ArgumentNullException("path");
643
            if (!Path.IsPathRooted(path))
644
                throw new ArgumentException("The path must be rooted", "path");            
645
            Contract.EndContractBlock();
646

    
647
            _persistenceAgent.Post(() => FileState.UpdateChecksum(path.ToLower(), checksum));
648
        }
649

    
650
    }
651

    
652
   
653
}