DbFactory.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. using System.Reflection;
  2. using FluentResults;
  3. using InABox.Clients;
  4. using InABox.Configuration;
  5. using InABox.Core;
  6. using InABox.Scripting;
  7. namespace InABox.Database;
  8. public class DatabaseMetadata : BaseObject, IGlobalConfigurationSettings
  9. {
  10. public Guid DatabaseID { get; set; } = Guid.NewGuid();
  11. }
  12. public class DbLockedException : Exception
  13. {
  14. public DbLockedException(): base("Database is read-only due to PRS license expiry.") { }
  15. }
  16. public static class DbFactory
  17. {
  18. public static Dictionary<string, ScriptDocument> LoadedScripts = new();
  19. private static DatabaseMetadata MetaData { get; set; } = new();
  20. public static Guid ID
  21. {
  22. get => MetaData.DatabaseID;
  23. set
  24. {
  25. MetaData.DatabaseID = value;
  26. SaveMetadata();
  27. }
  28. }
  29. private static IProviderFactory? _providerFactory;
  30. public static IProviderFactory ProviderFactory
  31. {
  32. get => _providerFactory ?? throw new Exception("Provider is not set");
  33. set => _providerFactory = value;
  34. }
  35. public static bool IsProviderSet => _providerFactory is not null;
  36. public static string? ColorScheme { get; set; }
  37. public static byte[]? Logo { get; set; }
  38. // See notes in Request.DatabaseInfo class
  39. // Once RPC transport is stable, these settings need
  40. // to be removed
  41. public static int RestPort { get; set; }
  42. public static int RPCPort { get; set; }
  43. /// <summary>
  44. /// Return every <see cref="IPersistent"/> entity in <see cref="CoreUtils.Entities"/>.
  45. /// </summary>
  46. public static IEnumerable<Type> Entities => CoreUtils.Entities.Where(x => x.HasInterface<IPersistent>());
  47. public static Type[] Stores
  48. {
  49. get => stores;
  50. set => SetStoreTypes(value);
  51. }
  52. public static DateTime Expiry { get; set; }
  53. public static IProvider NewProvider(Logger logger) => ProviderFactory.NewProvider(logger);
  54. public static void Start()
  55. {
  56. CoreUtils.CheckLicensing();
  57. // Start the provider
  58. ProviderFactory.Types = Entities.Where(x =>
  59. x.IsClass
  60. && !x.IsGenericType
  61. && x.IsSubclassOf(typeof(Entity))
  62. ).ToArray();
  63. ProviderFactory.Start();
  64. CheckMetadata();
  65. if (!DataUpdater.MigrateDatabase())
  66. {
  67. throw new Exception("Database migration failed. Aborting startup");
  68. }
  69. DataUpdater.DoSpecificMigration(new VersionNumber(8, 13), new VersionNumber(8,14));
  70. //Load up your custom properties here!
  71. // Can't use clients (b/c we're inside the database layer already
  72. // but we can simply access the store directly :-)
  73. //CustomProperty[] props = FindStore<CustomProperty>("", "", "", "").Load(new Filter<CustomProperty>(x=>x.ID).IsNotEqualTo(Guid.Empty),null);
  74. var props = ProviderFactory.NewProvider(Logger.Main).Query<CustomProperty>().ToArray<CustomProperty>();
  75. DatabaseSchema.Load(props);
  76. AssertLicense();
  77. BeginLicenseCheckTimer();
  78. InitStores();
  79. LoadScripts();
  80. }
  81. #region MetaData
  82. private static void SaveMetadata()
  83. {
  84. var settings = new GlobalSettings
  85. {
  86. Section = nameof(DatabaseMetadata),
  87. Key = "",
  88. Contents = Serialization.Serialize(MetaData)
  89. };
  90. ProviderFactory.NewProvider(Logger.Main).Save(settings);
  91. }
  92. private static void CheckMetadata()
  93. {
  94. var result = ProviderFactory.NewProvider(Logger.Main).Query(new Filter<GlobalSettings>(x => x.Section).IsEqualTo(nameof(DatabaseMetadata)))
  95. .Rows.FirstOrDefault()?.ToObject<GlobalSettings>();
  96. var data = result is not null ? Serialization.Deserialize<DatabaseMetadata>(result.Contents) : null;
  97. if (data is null)
  98. {
  99. MetaData = new DatabaseMetadata();
  100. SaveMetadata();
  101. }
  102. else
  103. {
  104. MetaData = data;
  105. }
  106. }
  107. #endregion
  108. #region License
  109. private enum LicenseValidation
  110. {
  111. Valid,
  112. Missing,
  113. Expired,
  114. Corrupt,
  115. Tampered
  116. }
  117. private static LicenseValidation CheckLicenseValidity(out DateTime expiry)
  118. {
  119. var provider = ProviderFactory.NewProvider(Logger.New());
  120. expiry = DateTime.MinValue;
  121. var license = provider.Load<License>().FirstOrDefault();
  122. if (license is null)
  123. return LicenseValidation.Missing;
  124. if (!LicenseUtils.TryDecryptLicense(license.Data, out var licenseData, out var error))
  125. return LicenseValidation.Corrupt;
  126. if (!LicenseUtils.ValidateMacAddresses(licenseData.Addresses))
  127. return LicenseValidation.Tampered;
  128. var userTrackingItems = provider.Query(
  129. new Filter<UserTracking>(x => x.ID).InList(licenseData.UserTrackingItems),
  130. Columns.None<UserTracking>().Add(x => x.ID)
  131. , log: false
  132. ).Rows
  133. .Select(r => r.Get<UserTracking, Guid>(c => c.ID))
  134. .ToArray();
  135. foreach(var item in licenseData.UserTrackingItems)
  136. {
  137. if (!userTrackingItems.Contains(item))
  138. return LicenseValidation.Tampered;
  139. }
  140. expiry = licenseData.Expiry;
  141. if (licenseData.Expiry < DateTime.Now)
  142. return LicenseValidation.Expired;
  143. return LicenseValidation.Valid;
  144. }
  145. private static int _expiredLicenseCounter = 0;
  146. private static TimeSpan LicenseCheckInterval = TimeSpan.FromMinutes(10);
  147. private static bool _readOnly;
  148. public static bool IsReadOnly { get => _readOnly; }
  149. private static System.Timers.Timer LicenseTimer = new System.Timers.Timer(LicenseCheckInterval.TotalMilliseconds) { AutoReset = true };
  150. private static void LogRenew(string message)
  151. {
  152. LogImportant($"{message} Please renew your license before then, or your database will go into read-only mode; it will be locked for saving anything until you renew your license. For help with renewing your license, please see the documentation at https://prsdigital.com.au/wiki/index.php/License_Renewal.");
  153. }
  154. public static void LogReadOnly()
  155. {
  156. LogImportant($"Your database is in read-only mode; please renew your license to enable database updates.");
  157. }
  158. private static void LogLicenseExpiry(DateTime expiry)
  159. {
  160. if (expiry.Date == DateTime.Today)
  161. {
  162. LogRenew($"Your database license is expiring today at {expiry.TimeOfDay:HH:mm}!");
  163. return;
  164. }
  165. var diffInDays = (expiry - DateTime.Now).TotalDays;
  166. if(diffInDays < 1)
  167. {
  168. LogRenew($"Your database license will expire in less than a day, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  169. }
  170. else if(diffInDays < 3 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 1)
  171. {
  172. LogRenew($"Your database license will expire in less than three days, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  173. _expiredLicenseCounter = 0;
  174. }
  175. else if(diffInDays < 7 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 2)
  176. {
  177. LogRenew($"Your database license will expire in less than a week, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  178. _expiredLicenseCounter = 0;
  179. }
  180. ++_expiredLicenseCounter;
  181. }
  182. private static void BeginReadOnly()
  183. {
  184. if (!IsReadOnly)
  185. {
  186. LogImportant(
  187. "Your database is now in read-only mode, since your license is invalid; you will be unable to save any records to the database until you renew your license. For help with renewing your license, please see the documentation at https://prsdigital.com.au/wiki/index.php/License_Renewal.");
  188. _readOnly = true;
  189. }
  190. }
  191. private static void EndReadOnly()
  192. {
  193. if (IsReadOnly)
  194. {
  195. LogImportant("Valid license found; the database is no longer read-only.");
  196. _readOnly = false;
  197. }
  198. }
  199. private static void BeginLicenseCheckTimer()
  200. {
  201. LicenseTimer.Elapsed += LicenseTimer_Elapsed;
  202. LicenseTimer.Start();
  203. }
  204. private static void LicenseTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
  205. {
  206. AssertLicense();
  207. }
  208. public static void AssertLicense()
  209. {
  210. var result = CheckLicenseValidity(out DateTime expiry);
  211. switch (result)
  212. {
  213. case LicenseValidation.Valid:
  214. LogLicenseExpiry(expiry);
  215. EndReadOnly();
  216. break;
  217. case LicenseValidation.Missing:
  218. LogImportant("Database is unlicensed!");
  219. BeginReadOnly();
  220. break;
  221. case LicenseValidation.Expired:
  222. LogImportant("Database license has expired!");
  223. BeginReadOnly();
  224. break;
  225. case LicenseValidation.Corrupt:
  226. LogImportant("Database license is corrupt - you will need to renew your license.");
  227. BeginReadOnly();
  228. break;
  229. case LicenseValidation.Tampered:
  230. LogImportant("Database license has been tampered with - you will need to renew your license.");
  231. BeginReadOnly();
  232. break;
  233. }
  234. }
  235. #endregion
  236. #region Logging
  237. private static void LogInfo(string message)
  238. {
  239. Logger.Send(LogType.Information, "", message);
  240. }
  241. private static void LogImportant(string message)
  242. {
  243. Logger.Send(LogType.Important, "", message);
  244. }
  245. private static void LogError(string message)
  246. {
  247. Logger.Send(LogType.Error, "", message);
  248. }
  249. #endregion
  250. public static void InitStores()
  251. {
  252. foreach (var storetype in stores)
  253. {
  254. var store = (Activator.CreateInstance(storetype) as IStore)!;
  255. store.Provider = ProviderFactory.NewProvider(Logger.Main);
  256. store.Logger = Logger.Main;
  257. store.Init();
  258. }
  259. }
  260. public static IStore FindStore(Type type, Guid userguid, string userid, Platform platform, string version, Logger logger)
  261. {
  262. var defType = typeof(Store<>).MakeGenericType(type);
  263. Type? subType = Stores.Where(myType => myType.IsSubclassOf(defType)).FirstOrDefault();
  264. var store = (Activator.CreateInstance(subType ?? defType) as IStore)!;
  265. store.Provider = ProviderFactory.NewProvider(logger);
  266. store.UserGuid = userguid;
  267. store.UserID = userid;
  268. store.Platform = platform;
  269. store.Version = version;
  270. store.Logger = logger;
  271. return store;
  272. }
  273. public static IStore<TEntity> FindStore<TEntity>(Guid userguid, string userid, Platform platform, string version, Logger logger)
  274. where TEntity : Entity, new()
  275. {
  276. return (FindStore(typeof(TEntity), userguid, userid, platform, version, logger) as IStore<TEntity>)!;
  277. }
  278. private static CoreTable DoQueryMultipleQuery<TEntity>(
  279. IQueryDef query,
  280. Guid userguid, string userid, Platform platform, string version, Logger logger)
  281. where TEntity : Entity, new()
  282. {
  283. var store = FindStore<TEntity>(userguid, userid, platform, version, logger);
  284. return store.Query(query.Filter as Filter<TEntity>, query.Columns as Columns<TEntity>, query.SortOrder as SortOrder<TEntity>);
  285. }
  286. public static Dictionary<string, CoreTable> QueryMultiple(
  287. Dictionary<string, IQueryDef> queries,
  288. Guid userguid, string userid, Platform platform, string version, Logger logger)
  289. {
  290. var result = new Dictionary<string, CoreTable>();
  291. var queryMethod = typeof(DbFactory).GetMethod(nameof(DoQueryMultipleQuery), BindingFlags.NonPublic | BindingFlags.Static)!;
  292. var tasks = new List<Task>();
  293. foreach (var item in queries)
  294. tasks.Add(Task.Run(() =>
  295. {
  296. result[item.Key] = (queryMethod.MakeGenericMethod(item.Value.Type).Invoke(ProviderFactory, new object[]
  297. {
  298. item.Value,
  299. userguid, userid, platform, version, logger
  300. }) as CoreTable)!;
  301. }));
  302. Task.WaitAll(tasks.ToArray());
  303. return result;
  304. }
  305. #region Supported Types
  306. private class ModuleConfiguration : Dictionary<string, bool>, ILocalConfigurationSettings
  307. {
  308. }
  309. private static Type[]? _dbtypes;
  310. public static IEnumerable<string> SupportedTypes()
  311. {
  312. _dbtypes ??= LoadSupportedTypes();
  313. return _dbtypes.Select(x => x.EntityName().Replace(".", "_"));
  314. }
  315. private static Type[] LoadSupportedTypes()
  316. {
  317. var result = new List<Type>();
  318. var path = ProviderFactory.URL.ToLower();
  319. var config = new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Load();
  320. var bChanged = false;
  321. foreach (var type in Entities)
  322. {
  323. var key = type.EntityName();
  324. if (config.TryGetValue(key, out bool value))
  325. {
  326. if (value)
  327. //Logger.Send(LogType.Information, "", String.Format("{0} is enabled", key));
  328. result.Add(type);
  329. else
  330. Logger.Send(LogType.Information, "", string.Format("Entity [{0}] is disabled", key));
  331. }
  332. else
  333. {
  334. //Logger.Send(LogType.Information, "", String.Format("{0} does not exist - enabling", key));
  335. config[key] = true;
  336. result.Add(type);
  337. bChanged = true;
  338. }
  339. }
  340. if (bChanged)
  341. new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Save(config);
  342. return result.ToArray();
  343. }
  344. public static bool IsSupported<T>() where T : Entity
  345. {
  346. _dbtypes ??= LoadSupportedTypes();
  347. return _dbtypes.Contains(typeof(T));
  348. }
  349. #endregion
  350. //public static void OpenSession(bool write)
  351. //{
  352. // Provider.OpenSession(write);
  353. //}
  354. //public static void CloseSession()
  355. //{
  356. // Provider.CloseSession();
  357. //}
  358. #region Private Methods
  359. public static void LoadScripts()
  360. {
  361. Logger.Send(LogType.Information, "", "Loading Script Cache...");
  362. LoadedScripts.Clear();
  363. var scripts = ProviderFactory.NewProvider(Logger.Main).Load(
  364. new Filter<Script>
  365. (x => x.ScriptType).IsEqualTo(ScriptType.BeforeQuery)
  366. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterQuery)
  367. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeSave)
  368. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterSave)
  369. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeDelete)
  370. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterDelete)
  371. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterLoad)
  372. );
  373. foreach (var script in scripts)
  374. {
  375. var key = string.Format("{0} {1}", script.Section, script.ScriptType.ToString());
  376. var doc = new ScriptDocument(script.Code);
  377. if (doc.Compile())
  378. {
  379. Logger.Send(LogType.Information, "",
  380. string.Format("- {0}.{1} Compiled Successfully", script.Section, script.ScriptType.ToString()));
  381. LoadedScripts[key] = doc;
  382. }
  383. else
  384. {
  385. Logger.Send(LogType.Error, "",
  386. string.Format("- {0}.{1} Compile Exception:\n{2}", script.Section, script.ScriptType.ToString(), doc.Result));
  387. }
  388. }
  389. Logger.Send(LogType.Information, "", "Loading Script Cache Complete");
  390. }
  391. //private static Type[] entities = null;
  392. //private static void SetEntityTypes(Type[] types)
  393. //{
  394. // foreach (Type type in types)
  395. // {
  396. // if (!type.IsSubclassOf(typeof(Entity)))
  397. // throw new Exception(String.Format("{0} is not a valid entity", type.Name));
  398. // }
  399. // entities = types;
  400. //}
  401. private static Type[] stores = { };
  402. private static void SetStoreTypes(Type[] types)
  403. {
  404. types = types.Where(
  405. myType => myType.IsClass
  406. && !myType.IsAbstract
  407. && !myType.IsGenericType).ToArray();
  408. foreach (var type in types)
  409. if (!type.GetInterfaces().Contains(typeof(IStore)))
  410. throw new Exception(string.Format("{0} is not a valid store", type.Name));
  411. stores = types;
  412. }
  413. #endregion
  414. }