2 using System.Collections.Generic;
3 using System.ComponentModel.Composition;
4 using System.Data.SQLite;
5 using System.Diagnostics;
6 using System.Diagnostics.Contracts;
9 using System.Threading;
10 using System.Threading.Tasks;
11 using Castle.ActiveRecord;
12 using Castle.ActiveRecord.Framework.Config;
13 using Pithos.Interfaces;
17 namespace Pithos.Core.Agents
19 [Export(typeof(IStatusChecker)),Export(typeof(IStatusKeeper))]
20 public class StatusAgent:IStatusChecker,IStatusKeeper
22 [System.ComponentModel.Composition.Import]
23 public IPithosSettings Settings { get; set; }
25 private Agent<Action> _persistenceAgent;
28 private static readonly ILog Log = LogManager.GetLogger("StatusAgent");
32 var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
33 _pithosDataPath = Path.Combine(appDataPath , "Pithos");
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();
41 if (!File.Exists(Path.Combine(_pithosDataPath ,"pithos.db")))
42 ActiveRecordStarter.CreateSchema();
45 private static InPlaceConfigurationSource GetConfiguration(string pithosDbPath)
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();
53 var properties = new Dictionary<string, string>
55 {"connection.driver_class", "NHibernate.Driver.SQLite20Driver"},
56 {"dialect", "NHibernate.Dialect.SQLiteDialect"},
57 {"connection.provider", "NHibernate.Connection.DriverConnectionProvider"},
59 "proxyfactory.factory_class",
60 "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
64 var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N", pithosDbPath);
65 properties.Add("connection.connection_string", connectionString);
67 var source = new InPlaceConfigurationSource();
68 source.Add(typeof (ActiveRecordBase), properties);
69 source.SetDebugFlag(false);
73 public void StartProcessing(CancellationToken token)
75 _persistenceAgent = Agent<Action>.Start(queue =>
80 var job = queue.Receive();
83 var action = job.Result;
88 catch (SQLiteException ex)
90 Log.ErrorFormat("[ERROR] SQL \n{0}", ex);
94 Log.ErrorFormat("[ERROR] STATE \n{0}", ex);
96 // ReSharper disable AccessToModifiedClosure
98 // ReSharper restore AccessToModifiedClosure
110 _persistenceAgent.Stop();
114 public void ProcessExistingFiles(IEnumerable<FileInfo> existingFiles)
116 if(existingFiles ==null)
117 throw new ArgumentNullException("existingFiles");
118 Contract.EndContractBlock();
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};
127 //To get the deleted files we must get the states that have no corresponding
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();
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 };
141 var pairs = currentFiles.Union(deletedFiles);
143 foreach(var pair in pairs)
145 var fileState = pair.State;
146 var file = pair.File;
147 if (fileState == null)
150 var fullPath = pair.File.FullName.ToLower();
151 var createState = FileState.CreateForAsync(fullPath, BlockSize, BlockHash);
152 createState.ContinueWith(state => _persistenceAgent.Post(state.Result.Create));
154 else if (file == null)
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));
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)
168 _persistenceAgent.Post(() => UpdateStatusDirect(fileState.Id, FileStatus.Modified));
175 private int UpdateStatusDirect(Guid id, FileStatus status)
180 var connectionString = GetConnectionString();
181 using (var connection = new SQLiteConnection(connectionString))
183 var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where Id = :id ",
186 command.Parameters.AddWithValue("fileStatus", status);
188 command.Parameters.AddWithValue("id", id);
190 var affected = command.ExecuteNonQuery();
194 catch (Exception exc)
196 Log.Error(exc.ToString());
202 private int UpdateStatusDirect(string path, FileStatus status)
207 var connectionString = GetConnectionString();
208 using (var connection = new SQLiteConnection(connectionString))
210 var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where FilePath = :path ",
213 command.Parameters.AddWithValue("fileStatus", status);
215 command.Parameters.AddWithValue("path", path.ToLower());
217 var affected = command.ExecuteNonQuery();
221 catch (Exception exc)
223 Log.Error(exc.ToString());
229 private int UpdateStatusDirect(string absolutePath, FileStatus fileStatus, FileOverlayStatus overlayStatus)
234 var connectionString = GetConnectionString();
235 using (var connection = new SQLiteConnection(connectionString))
237 var command = new SQLiteCommand("update FileState set OverlayStatus= :overlayStatus, FileStatus= :fileStatus where FilePath = :path ",
239 command.Parameters.AddWithValue("path", absolutePath.ToLower());
240 command.Parameters.AddWithValue("fileStatus", fileStatus);
241 command.Parameters.AddWithValue("overlayStatus", overlayStatus);
243 var affected = command.ExecuteNonQuery();
247 catch (Exception exc)
249 Log.Error(exc.ToString());
257 public string BlockHash { get; set; }
259 public int BlockSize { get; set; }
260 public void ChangeRoots(string oldPath, string newPath)
262 if (String.IsNullOrWhiteSpace(oldPath))
263 throw new ArgumentNullException("oldPath");
264 if (!Path.IsPathRooted(oldPath))
265 throw new ArgumentException("oldPath must be an absolute path", "oldPath");
266 if (string.IsNullOrWhiteSpace(newPath))
267 throw new ArgumentNullException("newPath");
268 if (!Path.IsPathRooted(newPath))
269 throw new ArgumentException("newPath must be an absolute path", "newPath");
270 Contract.EndContractBlock();
272 FileState.ChangeRootPath(oldPath,newPath);
276 private PithosStatus _pithosStatus=PithosStatus.InSynch;
278 public void SetPithosStatus(PithosStatus status)
280 _pithosStatus = status;
283 public PithosStatus GetPithosStatus()
285 return _pithosStatus;
289 private readonly string _pithosDataPath;
292 public FileOverlayStatus GetFileOverlayStatus(string path)
294 if (String.IsNullOrWhiteSpace(path))
295 throw new ArgumentNullException("path");
296 if (!Path.IsPathRooted(path))
297 throw new ArgumentException("The path must be rooted", "path");
298 Contract.EndContractBlock();
302 var connectionString = GetConnectionString();
303 using (var connection = new SQLiteConnection(connectionString))
305 var command = new SQLiteCommand("select OverlayStatus from FileState where FilePath=:path", connection);
306 command.Parameters.AddWithValue("path", path.ToLower());
308 var s = command.ExecuteScalar();
309 return (FileOverlayStatus) Convert.ToInt32(s);
311 var status = from state in FileState.Queryable
312 where state.FilePath ==path.ToLower()
313 select state.OverlayStatus;
314 return status.Any()? status.First():FileOverlayStatus.Unversioned;
316 catch (Exception exc)
318 Log.ErrorFormat(exc.ToString());
319 return FileOverlayStatus.Unversioned;
323 private string GetConnectionString()
325 var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N;Pooling=True;Default Isolation Level=ReadCommited", _pithosDataPath);
326 return connectionString;
329 public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
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();
337 _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path.ToLower(),overlayStatus));
340 /* public void RenameFileOverlayStatus(string oldPath, string newPath)
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();
352 _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
355 public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
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();
363 Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
364 Debug.Assert(!path.EndsWith(".ignore"));
366 _persistenceAgent.Post(() => UpdateStatusDirect(path.ToLower(), fileStatus, overlayStatus));
369 public void StoreInfo(string path,ObjectInfo objectInfo)
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();
379 _persistenceAgent.Post(() =>
381 var filePath = path.ToLower();
382 //Load the existing files state and set its properties in one session
383 using (new SessionScope())
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);
389 //Create a new empty state object if this is a new file
390 state = state ?? new FileState();
392 state.FilePath = filePath;
393 state.Checksum = objectInfo.Hash;
394 state.Version = objectInfo.Version;
395 state.VersionTimeStamp = objectInfo.VersionTimestamp;
397 state.FileStatus = FileStatus.Unchanged;
398 state.OverlayStatus = FileOverlayStatus.Normal;
409 public void SetFileStatus(string path, FileStatus status)
411 if (String.IsNullOrWhiteSpace(path))
412 throw new ArgumentNullException("path");
413 if (!Path.IsPathRooted(path))
414 throw new ArgumentException("The path must be rooted", "path");
415 Contract.EndContractBlock();
417 _persistenceAgent.Post(() => UpdateStatusDirect(path.ToLower(), status));
420 public FileStatus GetFileStatus(string path)
422 if (String.IsNullOrWhiteSpace(path))
423 throw new ArgumentNullException("path");
424 if (!Path.IsPathRooted(path))
425 throw new ArgumentException("The path must be rooted", "path");
426 Contract.EndContractBlock();
428 var connectionString = GetConnectionString();
429 using (var connection = new SQLiteConnection(connectionString))
431 var command = new SQLiteCommand("select FileStatus from FileState where FilePath=:path", connection);
432 command.Parameters.AddWithValue("path", path.ToLower());
434 var s = command.ExecuteScalar();
435 return (FileStatus)Convert.ToInt32(s);
438 var status = from r in FileState.Queryable
439 where r.FilePath == path.ToLower()
441 return status.Any()?status.First(): FileStatus.Missing;
444 public void ClearFileStatus(string path)
446 if (String.IsNullOrWhiteSpace(path))
447 throw new ArgumentNullException("path");
448 if (!Path.IsPathRooted(path))
449 throw new ArgumentException("The path must be rooted", "path");
450 Contract.EndContractBlock();
452 _persistenceAgent.Post(() => DeleteDirect(path));
455 private int DeleteDirect(string filePath)
460 var connectionString = GetConnectionString();
461 using (var connection = new SQLiteConnection(connectionString))
463 var command = new SQLiteCommand("delete FileState where FilePath = :path",
466 command.Parameters.AddWithValue("path", filePath.ToLower());
468 var affected = command.ExecuteNonQuery();
472 catch (Exception exc)
474 Log.Error(exc.ToString());
480 public void UpdateFileChecksum(string path, string checksum)
482 if (String.IsNullOrWhiteSpace(path))
483 throw new ArgumentNullException("path");
484 if (!Path.IsPathRooted(path))
485 throw new ArgumentException("The path must be rooted", "path");
486 Contract.EndContractBlock();
488 _persistenceAgent.Post(() => FileState.UpdateChecksum(path.ToLower(), checksum));