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", 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 Parallel.ForEach(pairs, pair =>
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 FileState.UpdateStatus(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 FileState.UpdateStatus(fileState.Id, FileStatus.Modified);
178 public string BlockHash { get; set; }
180 public int BlockSize { get; set; }
181 public void ChangeRoots(string oldPath, string newPath)
183 if (String.IsNullOrWhiteSpace(oldPath))
184 throw new ArgumentNullException("oldPath");
185 if (!Path.IsPathRooted(oldPath))
186 throw new ArgumentException("oldPath must be an absolute path", "oldPath");
187 if (string.IsNullOrWhiteSpace(newPath))
188 throw new ArgumentNullException("newPath");
189 if (!Path.IsPathRooted(newPath))
190 throw new ArgumentException("newPath must be an absolute path", "newPath");
191 Contract.EndContractBlock();
193 FileState.ChangeRootPath(oldPath,newPath);
197 private PithosStatus _pithosStatus=PithosStatus.InSynch;
199 public void SetPithosStatus(PithosStatus status)
201 _pithosStatus = status;
204 public PithosStatus GetPithosStatus()
206 return _pithosStatus;
210 private readonly string _pithosDataPath;
213 public FileOverlayStatus GetFileOverlayStatus(string path)
215 if (String.IsNullOrWhiteSpace(path))
216 throw new ArgumentNullException("path");
217 if (!Path.IsPathRooted(path))
218 throw new ArgumentException("The path must be rooted", "path");
219 Contract.EndContractBlock();
224 var status = from state in FileState.Queryable
225 where state.FilePath ==path.ToLower()
226 select state.OverlayStatus;
227 return status.Any()? status.First():FileOverlayStatus.Unversioned;
229 catch (Exception exc)
231 Log.ErrorFormat(exc.ToString());
232 return FileOverlayStatus.Unversioned;
236 public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
238 if (String.IsNullOrWhiteSpace(path))
239 throw new ArgumentNullException("path");
240 if (!Path.IsPathRooted(path))
241 throw new ArgumentException("The path must be rooted","path");
242 Contract.EndContractBlock();
244 _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path.ToLower(),overlayStatus));
247 /* public void RenameFileOverlayStatus(string oldPath, string newPath)
249 if (String.IsNullOrWhiteSpace(oldPath))
250 throw new ArgumentNullException("oldPath");
251 if (!Path.IsPathRooted(oldPath))
252 throw new ArgumentException("The oldPath must be rooted", "oldPath");
253 if (String.IsNullOrWhiteSpace(newPath))
254 throw new ArgumentNullException("newPath");
255 if (!Path.IsPathRooted(newPath))
256 throw new ArgumentException("The newPath must be rooted", "newPath");
257 Contract.EndContractBlock();
259 _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
262 public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
264 if (String.IsNullOrWhiteSpace(path))
265 throw new ArgumentNullException("path");
266 if (!Path.IsPathRooted(path))
267 throw new ArgumentException("The path must be rooted", "path");
268 Contract.EndContractBlock();
270 Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
271 Debug.Assert(!path.EndsWith(".ignore"));
273 _persistenceAgent.Post(() => FileState.UpdateStatus(path.ToLower(), fileStatus, overlayStatus));
276 public void StoreInfo(string path,ObjectInfo objectInfo)
278 if (String.IsNullOrWhiteSpace(path))
279 throw new ArgumentNullException("path");
280 if (!Path.IsPathRooted(path))
281 throw new ArgumentException("The path must be rooted", "path");
282 if (objectInfo == null)
283 throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
284 Contract.EndContractBlock();
286 _persistenceAgent.Post(() =>
288 var filePath = path.ToLower();
289 //Load the existing files state and set its properties in one session
290 using (new SessionScope())
292 //Forgetting to use a sessionscope results in two sessions being created, one by
293 //FirstOrDefault and one by Save()
294 var state =FileState.FindByFilePath(filePath);
296 //Create a new empty state object if this is a new file
297 state = state ?? new FileState();
299 state.FilePath = filePath;
300 state.Checksum = objectInfo.Hash;
301 state.Version = objectInfo.Version;
302 state.VersionTimeStamp = objectInfo.VersionTimestamp;
304 state.FileStatus = FileStatus.Unchanged;
305 state.OverlayStatus = FileOverlayStatus.Normal;
316 public void SetFileStatus(string path, FileStatus status)
318 if (String.IsNullOrWhiteSpace(path))
319 throw new ArgumentNullException("path");
320 if (!Path.IsPathRooted(path))
321 throw new ArgumentException("The path must be rooted", "path");
322 Contract.EndContractBlock();
324 _persistenceAgent.Post(() => FileState.UpdateStatus(path.ToLower(), status));
327 public FileStatus GetFileStatus(string path)
329 if (String.IsNullOrWhiteSpace(path))
330 throw new ArgumentNullException("path");
331 if (!Path.IsPathRooted(path))
332 throw new ArgumentException("The path must be rooted", "path");
333 Contract.EndContractBlock();
335 var status = from r in FileState.Queryable
336 where r.FilePath == path.ToLower()
338 return status.Any()?status.First(): FileStatus.Missing;
341 public void ClearFileStatus(string path)
343 if (String.IsNullOrWhiteSpace(path))
344 throw new ArgumentNullException("path");
345 if (!Path.IsPathRooted(path))
346 throw new ArgumentException("The path must be rooted", "path");
347 Contract.EndContractBlock();
349 _persistenceAgent.Post(() => FileState.DeleteByFilePath(path));
352 public void UpdateFileChecksum(string path, string checksum)
354 if (String.IsNullOrWhiteSpace(path))
355 throw new ArgumentNullException("path");
356 if (!Path.IsPathRooted(path))
357 throw new ArgumentException("The path must be rooted", "path");
358 Contract.EndContractBlock();
360 _persistenceAgent.Post(() => FileState.UpdateChecksum(path.ToLower(), checksum));