2 /* -----------------------------------------------------------------------
3 * <copyright file="StatusAgent.cs" company="GRNet">
5 * Copyright 2011-2012 GRNET S.A. All rights reserved.
7 * Redistribution and use in source and binary forms, with or
8 * without modification, are permitted provided that the following
11 * 1. Redistributions of source code must retain the above
12 * copyright notice, this list of conditions and the following
15 * 2. Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials
18 * provided with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * The views and conclusions contained in the software and
35 * documentation are those of the authors and should not be
36 * interpreted as representing official policies, either expressed
37 * or implied, of GRNET S.A.
39 * -----------------------------------------------------------------------
43 using System.Collections.Generic;
44 using System.ComponentModel.Composition;
45 using System.Data.SQLite;
46 using System.Diagnostics;
47 using System.Diagnostics.Contracts;
50 using System.Reflection;
52 using System.Threading;
53 using System.Threading.Tasks;
54 using Castle.ActiveRecord;
55 using Castle.ActiveRecord.Framework.Config;
56 using Pithos.Interfaces;
60 namespace Pithos.Core.Agents
62 [Export(typeof(IStatusChecker)),Export(typeof(IStatusKeeper))]
63 public class StatusAgent:IStatusChecker,IStatusKeeper
65 private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
67 [System.ComponentModel.Composition.Import]
68 public IPithosSettings Settings { get; set; }
70 private Agent<Action> _persistenceAgent;
76 var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
80 _pithosDataPath = Path.Combine(appDataPath , "GRNET");
81 if (!Directory.Exists(_pithosDataPath))
82 Directory.CreateDirectory(_pithosDataPath);
84 var dbPath = Path.Combine(_pithosDataPath, "pithos.db");
86 MigrateOldDb(dbPath, appDataPath);
88 var source = GetConfiguration(_pithosDataPath);
89 ActiveRecordStarter.Initialize(source,typeof(FileState),typeof(FileTag));
90 ActiveRecordStarter.UpdateSchema();
93 if (!File.Exists(dbPath))
94 ActiveRecordStarter.CreateSchema();
101 private static void MigrateOldDb(string dbPath, string appDataPath)
103 Contract.Requires(!String.IsNullOrWhiteSpace(dbPath));
104 Contract.Requires(!String.IsNullOrWhiteSpace(appDataPath));
106 var oldDbPath = Path.Combine(appDataPath, "Pithos", "pithos.db");
107 var oldDbInfo = new FileInfo(oldDbPath);
108 if (oldDbInfo.Exists && !File.Exists(dbPath))
110 var oldDirectory = oldDbInfo.Directory;
111 oldDbInfo.MoveTo(dbPath);
112 oldDirectory.Delete(true);
116 private void CreateTrigger()
118 using (var connection = GetConnection())
119 using (var triggerCommand = connection.CreateCommand())
121 var cmdText = new StringBuilder()
122 .AppendLine("CREATE TRIGGER IF NOT EXISTS update_last_modified UPDATE ON FileState FOR EACH ROW")
124 .AppendLine("UPDATE FileState SET Modified=datetime('now') WHERE Id=old.Id;")
126 .AppendLine("CREATE TRIGGER IF NOT EXISTS insert_last_modified INSERT ON FileState FOR EACH ROW")
128 .AppendLine("UPDATE FileState SET Modified=datetime('now') WHERE Id=new.Id;")
131 triggerCommand.CommandText = cmdText;
132 triggerCommand.ExecuteNonQuery();
137 private static InPlaceConfigurationSource GetConfiguration(string pithosDbPath)
139 if (String.IsNullOrWhiteSpace(pithosDbPath))
140 throw new ArgumentNullException("pithosDbPath");
141 if (!Path.IsPathRooted(pithosDbPath))
142 throw new ArgumentException("path must be a rooted path", "pithosDbPath");
143 Contract.EndContractBlock();
145 var properties = new Dictionary<string, string>
147 {"connection.driver_class", "NHibernate.Driver.SQLite20Driver"},
148 {"dialect", "NHibernate.Dialect.SQLiteDialect"},
149 {"connection.provider", "NHibernate.Connection.DriverConnectionProvider"},
151 "proxyfactory.factory_class",
152 "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"
156 var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N", pithosDbPath);
157 properties.Add("connection.connection_string", connectionString);
159 var source = new InPlaceConfigurationSource();
160 source.Add(typeof (ActiveRecordBase), properties);
161 source.SetDebugFlag(false);
165 public void StartProcessing(CancellationToken token)
167 _persistenceAgent = Agent<Action>.Start(queue =>
172 var job = queue.Receive();
173 job.ContinueWith(t =>
175 var action = job.Result;
180 catch (SQLiteException ex)
182 Log.ErrorFormat("[ERROR] SQL \n{0}", ex);
186 Log.ErrorFormat("[ERROR] STATE \n{0}", ex);
188 // ReSharper disable AccessToModifiedClosure
190 // ReSharper restore AccessToModifiedClosure
202 _persistenceAgent.Stop();
206 public void ProcessExistingFiles(IEnumerable<FileInfo> existingFiles)
208 if(existingFiles ==null)
209 throw new ArgumentNullException("existingFiles");
210 Contract.EndContractBlock();
212 //Find new or matching files with a left join to the stored states
213 var fileStates = FileState.Queryable;
214 var currentFiles=from file in existingFiles
215 join state in fileStates on file.FullName.ToLower() equals state.FilePath.ToLower() into gs
216 from substate in gs.DefaultIfEmpty()
217 select new {File = file, State = substate};
219 //To get the deleted files we must get the states that have no corresponding
221 //We can't use the File.Exists method inside a query, so we get all file paths from the states
222 var statePaths = (from state in fileStates
223 select new {state.Id, state.FilePath}).ToList();
225 var missingStates= (from path in statePaths
226 where !File.Exists(path.FilePath) && !Directory.Exists(path.FilePath)
227 select path.Id).ToList();
228 //Finally, retrieve the states that correspond to the deleted files
229 var deletedFiles = from state in fileStates
230 where missingStates.Contains(state.Id)
231 select new { File = default(FileInfo), State = state };
233 var pairs = currentFiles.Union(deletedFiles);
235 foreach(var pair in pairs)
237 var fileState = pair.State;
238 var file = pair.File;
239 if (fileState == null)
242 var fullPath = pair.File.FullName;
243 var createState = FileState.CreateForAsync(fullPath, BlockSize, BlockHash);
244 createState.ContinueWith(state => _persistenceAgent.Post(state.Result.Create));
246 else if (file == null)
248 //This file was deleted while we were down. We should mark it as deleted
249 //We have to go through UpdateStatus here because the state object we are using
250 //was created by a different ORM session.
251 _persistenceAgent.Post(()=> UpdateStatusDirect(fileState.Id, FileStatus.Deleted));
255 //This file has a matching state. Need to check for possible changes
256 var hashString = file.CalculateHash(BlockSize,BlockHash);
257 //If the hashes don't match the file was changed
258 if (fileState.Checksum != hashString)
260 _persistenceAgent.Post(() => UpdateStatusDirect(fileState.Id, FileStatus.Modified));
267 private int UpdateStatusDirect(Guid id, FileStatus status)
269 using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
275 using (var connection = GetConnection())
277 var command = new SQLiteCommand("update FileState set FileStatus= :fileStatus where Id = :id ",
280 command.Parameters.AddWithValue("fileStatus", status);
282 command.Parameters.AddWithValue("id", id);
284 var affected = command.ExecuteNonQuery();
290 catch (Exception exc)
292 Log.Error(exc.ToString());
298 private int UpdateStatusDirect(string path, FileStatus status)
300 using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
307 using (var connection = GetConnection())
310 new SQLiteCommand("update FileState set FileStatus= :fileStatus where FilePath = :path COLLATE NOCASE",
315 command.Parameters.AddWithValue("fileStatus", status);
317 command.Parameters.AddWithValue("path", path);
319 var affected = command.ExecuteNonQuery();
323 catch (Exception exc)
325 Log.Error(exc.ToString());
331 private int UpdateStatusDirect(string absolutePath, FileStatus fileStatus, FileOverlayStatus overlayStatus)
333 using (log4net.ThreadContext.Stacks["StatusAgent"].Push("UpdateStatusDirect"))
340 using (var connection = GetConnection())
344 "update FileState set OverlayStatus= :overlayStatus, FileStatus= :fileStatus where FilePath = :path COLLATE NOCASE ",
348 command.Parameters.AddWithValue("path", absolutePath);
349 command.Parameters.AddWithValue("fileStatus", fileStatus);
350 command.Parameters.AddWithValue("overlayStatus", overlayStatus);
352 var affected = command.ExecuteNonQuery();
356 catch (Exception exc)
358 Log.Error(exc.ToString());
366 public string BlockHash { get; set; }
368 public int BlockSize { get; set; }
369 public void ChangeRoots(string oldPath, string newPath)
371 if (String.IsNullOrWhiteSpace(oldPath))
372 throw new ArgumentNullException("oldPath");
373 if (!Path.IsPathRooted(oldPath))
374 throw new ArgumentException("oldPath must be an absolute path", "oldPath");
375 if (string.IsNullOrWhiteSpace(newPath))
376 throw new ArgumentNullException("newPath");
377 if (!Path.IsPathRooted(newPath))
378 throw new ArgumentException("newPath must be an absolute path", "newPath");
379 Contract.EndContractBlock();
381 FileState.ChangeRootPath(oldPath,newPath);
385 private PithosStatus _pithosStatus=PithosStatus.InSynch;
387 public void SetPithosStatus(PithosStatus status)
389 _pithosStatus = status;
392 public PithosStatus GetPithosStatus()
394 return _pithosStatus;
398 private readonly string _pithosDataPath;
401 public FileState GetStateByFilePath(string path)
403 if (String.IsNullOrWhiteSpace(path))
404 throw new ArgumentNullException("path");
405 if (!Path.IsPathRooted(path))
406 throw new ArgumentException("The path must be rooted", "path");
407 Contract.EndContractBlock();
412 using (var connection = GetConnection())
413 using (var command = new SQLiteCommand("select Id, FilePath, OverlayStatus,FileStatus ,Checksum ,Version ,VersionTimeStamp,IsShared ,SharedBy ,ShareWrite from FileState where FilePath=:path COLLATE NOCASE", connection))
416 command.Parameters.AddWithValue("path", path);
418 using (var reader = command.ExecuteReader())
422 //var values = new object[reader.FieldCount];
423 //reader.GetValues(values);
424 var state = new FileState
426 Id = reader.GetGuid(0),
427 FilePath = reader.IsDBNull(1)?"":reader.GetString(1),
428 OverlayStatus =reader.IsDBNull(2)?FileOverlayStatus.Unversioned: (FileOverlayStatus) reader.GetInt64(2),
429 FileStatus = reader.IsDBNull(3)?FileStatus.Missing:(FileStatus) reader.GetInt64(3),
430 Checksum = reader.IsDBNull(4)?"":reader.GetString(4),
431 Version = reader.IsDBNull(5)?default(long):reader.GetInt64(5),
432 VersionTimeStamp = reader.IsDBNull(6)?default(DateTime):reader.GetDateTime(6),
433 IsShared = !reader.IsDBNull(7) && reader.GetBoolean(7),
434 SharedBy = reader.IsDBNull(8)?"":reader.GetString(8),
435 ShareWrite = !reader.IsDBNull(9) && reader.GetBoolean(9)
438 var state = new FileState
440 Id = (Guid) values[0],
441 FilePath = (string) values[1],
442 OverlayStatus = (FileOverlayStatus) (long)values[2],
443 FileStatus = (FileStatus) (long)values[3],
444 Checksum = (string) values[4],
445 Version = (long?) values[5],
446 VersionTimeStamp = (DateTime?) values[6],
447 IsShared = (long)values[7] == 1,
448 SharedBy = (string) values[8],
449 ShareWrite = (long)values[9] == 1
462 catch (Exception exc)
464 Log.ErrorFormat(exc.ToString());
469 public FileOverlayStatus GetFileOverlayStatus(string path)
471 if (String.IsNullOrWhiteSpace(path))
472 throw new ArgumentNullException("path");
473 if (!Path.IsPathRooted(path))
474 throw new ArgumentException("The path must be rooted", "path");
475 Contract.EndContractBlock();
480 using (var connection = GetConnection())
481 using (var command = new SQLiteCommand("select OverlayStatus from FileState where FilePath=:path COLLATE NOCASE", connection))
484 command.Parameters.AddWithValue("path", path);
486 var s = command.ExecuteScalar();
487 return (FileOverlayStatus) Convert.ToInt32(s);
490 catch (Exception exc)
492 Log.ErrorFormat(exc.ToString());
493 return FileOverlayStatus.Unversioned;
497 private string GetConnectionString()
499 var connectionString = String.Format(@"Data Source={0}\pithos.db;Version=3;Enlist=N;Pooling=True", _pithosDataPath);
500 return connectionString;
503 private SQLiteConnection GetConnection()
505 var connectionString = GetConnectionString();
506 var connection = new SQLiteConnection(connectionString);
508 using(var cmd =connection.CreateCommand())
510 cmd.CommandText = "PRAGMA journal_mode=WAL";
511 cmd.ExecuteNonQuery();
516 public void SetFileOverlayStatus(string path, FileOverlayStatus overlayStatus)
518 if (String.IsNullOrWhiteSpace(path))
519 throw new ArgumentNullException("path");
520 if (!Path.IsPathRooted(path))
521 throw new ArgumentException("The path must be rooted","path");
522 Contract.EndContractBlock();
524 _persistenceAgent.Post(() => FileState.StoreOverlayStatus(path,overlayStatus));
527 /* public void RenameFileOverlayStatus(string oldPath, string newPath)
529 if (String.IsNullOrWhiteSpace(oldPath))
530 throw new ArgumentNullException("oldPath");
531 if (!Path.IsPathRooted(oldPath))
532 throw new ArgumentException("The oldPath must be rooted", "oldPath");
533 if (String.IsNullOrWhiteSpace(newPath))
534 throw new ArgumentNullException("newPath");
535 if (!Path.IsPathRooted(newPath))
536 throw new ArgumentException("The newPath must be rooted", "newPath");
537 Contract.EndContractBlock();
539 _persistenceAgent.Post(() =>FileState.RenameState(oldPath, newPath));
542 public void SetFileState(string path, FileStatus fileStatus, FileOverlayStatus overlayStatus)
544 if (String.IsNullOrWhiteSpace(path))
545 throw new ArgumentNullException("path");
546 if (!Path.IsPathRooted(path))
547 throw new ArgumentException("The path must be rooted", "path");
548 Contract.EndContractBlock();
550 Debug.Assert(!path.Contains(FolderConstants.CacheFolder));
551 Debug.Assert(!path.EndsWith(".ignore"));
553 _persistenceAgent.Post(() => UpdateStatusDirect(path, fileStatus, overlayStatus));
557 public void StoreInfo(string path,ObjectInfo objectInfo)
559 if (String.IsNullOrWhiteSpace(path))
560 throw new ArgumentNullException("path");
561 if (!Path.IsPathRooted(path))
562 throw new ArgumentException("The path must be rooted", "path");
563 if (objectInfo == null)
564 throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
565 Contract.EndContractBlock();
567 _persistenceAgent.Post(() =>
569 var filePath = path.ToLower();
570 //Load the existing files state and set its properties in one session
571 using (new SessionScope())
573 //Forgetting to use a sessionscope results in two sessions being created, one by
574 //FirstOrDefault and one by Save()
575 var state =FileState.FindByFilePath(filePath);
577 //Create a new empty state object if this is a new file
578 state = state ?? new FileState();
580 state.FilePath = filePath;
581 state.Checksum = objectInfo.Hash;
582 state.Version = objectInfo.Version;
583 state.VersionTimeStamp = objectInfo.VersionTimestamp;
585 state.FileStatus = FileStatus.Unchanged;
586 state.OverlayStatus = FileOverlayStatus.Normal;
597 public void StoreInfo(string path, ObjectInfo objectInfo)
599 if (String.IsNullOrWhiteSpace(path))
600 throw new ArgumentNullException("path");
601 if (!Path.IsPathRooted(path))
602 throw new ArgumentException("The path must be rooted", "path");
603 if (objectInfo == null)
604 throw new ArgumentNullException("objectInfo", "objectInfo can't be empty");
605 Contract.EndContractBlock();
607 _persistenceAgent.Post(() => StoreInfoDirect(path, objectInfo));
611 private void StoreInfoDirect(string path, ObjectInfo objectInfo)
616 using (var connection = GetConnection())
617 using (var command = new SQLiteCommand(connection))
619 if (StateExists(path, connection))
620 command.CommandText =
621 "update FileState set FileStatus= :fileStatus where FilePath = :path COLLATE NOCASE ";
624 command.CommandText =
625 "INSERT INTO FileState (Id,FilePath,Checksum,Version,VersionTimeStamp,FileStatus,OverlayStatus) VALUES (:id,:path,:checksum,:version,:versionTimeStamp,:fileStatus,:overlayStatus)";
626 command.Parameters.AddWithValue("id", Guid.NewGuid());
629 command.Parameters.AddWithValue("path", path);
630 command.Parameters.AddWithValue("checksum", objectInfo.Hash);
631 command.Parameters.AddWithValue("version", objectInfo.Version);
632 command.Parameters.AddWithValue("versionTimeStamp",
633 objectInfo.VersionTimestamp);
634 command.Parameters.AddWithValue("fileStatus", FileStatus.Unchanged);
635 command.Parameters.AddWithValue("overlayStatus",
636 FileOverlayStatus.Normal);
638 var affected = command.ExecuteNonQuery();
642 catch (Exception exc)
644 Log.Error(exc.ToString());
649 private bool StateExists(string filePath,SQLiteConnection connection)
651 using (var command = new SQLiteCommand("Select count(*) from FileState where FilePath=:path COLLATE NOCASE", connection))
653 command.Parameters.AddWithValue("path", filePath);
654 var result = command.ExecuteScalar();
655 return ((long)result >= 1);
660 public void SetFileStatus(string path, FileStatus status)
662 if (String.IsNullOrWhiteSpace(path))
663 throw new ArgumentNullException("path");
664 if (!Path.IsPathRooted(path))
665 throw new ArgumentException("The path must be rooted", "path");
666 Contract.EndContractBlock();
668 _persistenceAgent.Post(() => UpdateStatusDirect(path, status));
671 public FileStatus GetFileStatus(string path)
673 if (String.IsNullOrWhiteSpace(path))
674 throw new ArgumentNullException("path");
675 if (!Path.IsPathRooted(path))
676 throw new ArgumentException("The path must be rooted", "path");
677 Contract.EndContractBlock();
680 using (var connection = GetConnection())
682 var command = new SQLiteCommand("select FileStatus from FileState where FilePath=:path COLLATE NOCASE", connection);
683 command.Parameters.AddWithValue("path", path);
685 var statusValue = command.ExecuteScalar();
686 if (statusValue==null)
687 return FileStatus.Missing;
688 return (FileStatus)Convert.ToInt32(statusValue);
693 /// Deletes the status of the specified file
695 /// <param name="path"></param>
696 public void ClearFileStatus(string path)
698 if (String.IsNullOrWhiteSpace(path))
699 throw new ArgumentNullException("path");
700 if (!Path.IsPathRooted(path))
701 throw new ArgumentException("The path must be rooted", "path");
702 Contract.EndContractBlock();
704 _persistenceAgent.Post(() => DeleteDirect(path));
708 /// Deletes the status of the specified folder and all its contents
710 /// <param name="path"></param>
711 public void ClearFolderStatus(string path)
713 if (String.IsNullOrWhiteSpace(path))
714 throw new ArgumentNullException("path");
715 if (!Path.IsPathRooted(path))
716 throw new ArgumentException("The path must be rooted", "path");
717 Contract.EndContractBlock();
719 _persistenceAgent.Post(() => DeleteFolderDirect(path));
722 public IEnumerable<FileState> GetChildren(FileState fileState)
724 if (fileState == null)
725 throw new ArgumentNullException("fileState");
726 Contract.EndContractBlock();
728 var children = from state in FileState.Queryable
729 where state.FilePath.StartsWith(fileState.FilePath + "\\")
734 private int DeleteDirect(string filePath)
736 using (log4net.ThreadContext.Stacks["StatusAgent"].Push("DeleteDirect"))
743 using (var connection = GetConnection())
745 var command = new SQLiteCommand("delete from FileState where FilePath = :path COLLATE NOCASE",
748 command.Parameters.AddWithValue("path", filePath);
750 var affected = command.ExecuteNonQuery();
754 catch (Exception exc)
756 Log.Error(exc.ToString());
762 private int DeleteFolderDirect(string filePath)
764 using (log4net.ThreadContext.Stacks["StatusAgent"].Push("DeleteDirect"))
771 using (var connection = GetConnection())
773 var command = new SQLiteCommand("delete from FileState where FilePath = :path or FilePath like :path + '/%' COLLATE NOCASE",
776 command.Parameters.AddWithValue("path", filePath);
778 var affected = command.ExecuteNonQuery();
782 catch (Exception exc)
784 Log.Error(exc.ToString());
790 public void UpdateFileChecksum(string path, string checksum)
792 if (String.IsNullOrWhiteSpace(path))
793 throw new ArgumentNullException("path");
794 if (!Path.IsPathRooted(path))
795 throw new ArgumentException("The path must be rooted", "path");
796 Contract.EndContractBlock();
798 _persistenceAgent.Post(() => FileState.UpdateChecksum(path, checksum));