Replaced object load and update with direct HQL execution to resolve database locks...
[pithos-ms-client] / trunk / Pithos.Core / Agents / StatusAgent.cs
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", 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             Parallel.ForEach(pairs, pair =>
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                     FileState.UpdateStatus(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                         FileState.UpdateStatus(fileState.Id, FileStatus.Modified);
169                     }                    
170                 }
171             });            
172          
173         }
174
175        
176
177
178         public string BlockHash { get; set; }
179
180         public int BlockSize { get; set; }
181         public void ChangeRoots(string oldPath, string newPath)
182         {
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();
192
193             FileState.ChangeRootPath(oldPath,newPath);
194
195         }
196
197         private PithosStatus _pithosStatus=PithosStatus.InSynch;       
198
199         public void SetPithosStatus(PithosStatus status)
200         {
201             _pithosStatus = status;
202         }
203
204         public PithosStatus GetPithosStatus()
205         {
206             return _pithosStatus;
207         }
208
209
210         private readonly string _pithosDataPath;
211
212
213         public FileOverlayStatus GetFileOverlayStatus(string path)
214         {
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();
220
221             try
222             {
223
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;
228             }
229             catch (Exception exc)
230             {
231                 Log.ErrorFormat(exc.ToString());
232                 return FileOverlayStatus.Unversioned;
233             }
234         }
235
236         public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
237         {
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();
243
244             _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path.ToLower(),overlayStatus));
245         }
246
247        /* public void RenameFileOverlayStatus(string oldPath, string newPath)
248         {
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();
258
259             _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
260         }*/
261
262         public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
263         {
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();
269
270             Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
271             Debug.Assert(!path.EndsWith(".ignore"));
272
273             _persistenceAgent.Post(() => FileState.UpdateStatus(path.ToLower(), fileStatus, overlayStatus));
274         }
275
276         public void StoreInfo(string path,ObjectInfo objectInfo)
277         {
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();
285
286             _persistenceAgent.Post(() =>
287             {
288                 var filePath = path.ToLower();
289                 //Load the existing files state and set its properties in one session            
290                 using (new SessionScope())
291                 {
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);
295                     
296                     //Create a new empty state object if this is a new file
297                     state = state ?? new FileState();
298
299                     state.FilePath = filePath;
300                     state.Checksum = objectInfo.Hash;
301                     state.Version = objectInfo.Version;
302                     state.VersionTimeStamp = objectInfo.VersionTimestamp;
303
304                     state.FileStatus = FileStatus.Unchanged;
305                     state.OverlayStatus = FileOverlayStatus.Normal;
306                     
307                   
308                     //Do the save
309                     state.Save();
310                 }
311             });
312
313         }
314
315         
316         public void SetFileStatus(string path, FileStatus status)
317         {
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();
323
324             _persistenceAgent.Post(() => FileState.UpdateStatus(path.ToLower(), status));
325         }
326
327         public FileStatus GetFileStatus(string path)
328         {
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();
334
335             var status = from r in FileState.Queryable
336                      where r.FilePath == path.ToLower()
337                      select r.FileStatus;                        
338             return status.Any()?status.First(): FileStatus.Missing;
339         }
340
341         public void ClearFileStatus(string path)
342         {
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();
348             
349             _persistenceAgent.Post(() => FileState.DeleteByFilePath(path));   
350         }
351
352         public void UpdateFileChecksum(string path, string checksum)
353         {
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();
359
360             _persistenceAgent.Post(() => FileState.UpdateChecksum(path.ToLower(), checksum));
361         }
362
363     }
364
365    
366 }