FlotsamAssetCache.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // Uncomment to make asset Get requests for existing
  28. // #define WAIT_ON_INPROGRESS_REQUESTS
  29. using System;
  30. using System.IO;
  31. using System.Collections.Generic;
  32. using System.Reflection;
  33. using System.Runtime.Serialization;
  34. using System.Runtime.Serialization.Formatters.Binary;
  35. using System.Threading;
  36. using System.Timers;
  37. using log4net;
  38. using Nini.Config;
  39. using Mono.Addins;
  40. using OpenMetaverse;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Console;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Services.Interfaces;
  46. //[assembly: Addin("FlotsamAssetCache", "1.1")]
  47. //[assembly: AddinDependency("OpenSim", "0.5")]
  48. namespace OpenSim.Region.CoreModules.Asset
  49. {
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
  51. public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService
  52. {
  53. private static readonly ILog m_log =
  54. LogManager.GetLogger(
  55. MethodBase.GetCurrentMethod().DeclaringType);
  56. private bool m_Enabled;
  57. private const string m_ModuleName = "FlotsamAssetCache";
  58. private const string m_DefaultCacheDirectory = "./assetcache";
  59. private string m_CacheDirectory = m_DefaultCacheDirectory;
  60. private readonly List<char> m_InvalidChars = new List<char>();
  61. private int m_LogLevel = 0;
  62. private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
  63. private static ulong m_Requests;
  64. private static ulong m_RequestsForInprogress;
  65. private static ulong m_DiskHits;
  66. private static ulong m_MemoryHits;
  67. private static double m_HitRateMemory;
  68. private static double m_HitRateFile;
  69. #if WAIT_ON_INPROGRESS_REQUESTS
  70. private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
  71. private int m_WaitOnInprogressTimeout = 3000;
  72. #else
  73. private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
  74. #endif
  75. private bool m_FileCacheEnabled = true;
  76. private ExpiringCache<string, AssetBase> m_MemoryCache;
  77. private bool m_MemoryCacheEnabled = false;
  78. // Expiration is expressed in hours.
  79. private const double m_DefaultMemoryExpiration = 2;
  80. private const double m_DefaultFileExpiration = 48;
  81. private TimeSpan m_MemoryExpiration = TimeSpan.FromHours(m_DefaultMemoryExpiration);
  82. private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
  83. private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(0.166);
  84. private static int m_CacheDirectoryTiers = 1;
  85. private static int m_CacheDirectoryTierLen = 3;
  86. private static int m_CacheWarnAt = 30000;
  87. private System.Timers.Timer m_CacheCleanTimer;
  88. private IAssetService m_AssetService;
  89. private List<Scene> m_Scenes = new List<Scene>();
  90. public FlotsamAssetCache()
  91. {
  92. m_InvalidChars.AddRange(Path.GetInvalidPathChars());
  93. m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
  94. }
  95. public Type ReplaceableInterface
  96. {
  97. get { return null; }
  98. }
  99. public string Name
  100. {
  101. get { return m_ModuleName; }
  102. }
  103. public void Initialise(IConfigSource source)
  104. {
  105. IConfig moduleConfig = source.Configs["Modules"];
  106. if (moduleConfig != null)
  107. {
  108. string name = moduleConfig.GetString("AssetCaching", String.Empty);
  109. if (name == Name)
  110. {
  111. m_MemoryCache = new ExpiringCache<string, AssetBase>();
  112. m_Enabled = true;
  113. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
  114. IConfig assetConfig = source.Configs["AssetCache"];
  115. if (assetConfig == null)
  116. {
  117. m_log.Debug(
  118. "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
  119. }
  120. else
  121. {
  122. m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
  123. m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
  124. m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
  125. m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
  126. #if WAIT_ON_INPROGRESS_REQUESTS
  127. m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
  128. #endif
  129. m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
  130. m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
  131. m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
  132. m_FileExpirationCleanupTimer
  133. = TimeSpan.FromHours(
  134. assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
  135. m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
  136. m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
  137. m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
  138. }
  139. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
  140. if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
  141. {
  142. m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
  143. m_CacheCleanTimer.AutoReset = true;
  144. m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
  145. lock (m_CacheCleanTimer)
  146. m_CacheCleanTimer.Start();
  147. }
  148. if (m_CacheDirectoryTiers < 1)
  149. {
  150. m_CacheDirectoryTiers = 1;
  151. }
  152. else if (m_CacheDirectoryTiers > 3)
  153. {
  154. m_CacheDirectoryTiers = 3;
  155. }
  156. if (m_CacheDirectoryTierLen < 1)
  157. {
  158. m_CacheDirectoryTierLen = 1;
  159. }
  160. else if (m_CacheDirectoryTierLen > 4)
  161. {
  162. m_CacheDirectoryTierLen = 4;
  163. }
  164. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
  165. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the cache. If file or memory is specified then only this cache is cleared.", HandleConsoleCommand);
  166. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
  167. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
  168. }
  169. }
  170. }
  171. public void PostInitialise()
  172. {
  173. }
  174. public void Close()
  175. {
  176. }
  177. public void AddRegion(Scene scene)
  178. {
  179. if (m_Enabled)
  180. {
  181. scene.RegisterModuleInterface<IImprovedAssetCache>(this);
  182. m_Scenes.Add(scene);
  183. }
  184. }
  185. public void RemoveRegion(Scene scene)
  186. {
  187. if (m_Enabled)
  188. {
  189. scene.UnregisterModuleInterface<IImprovedAssetCache>(this);
  190. m_Scenes.Remove(scene);
  191. }
  192. }
  193. public void RegionLoaded(Scene scene)
  194. {
  195. if (m_Enabled && m_AssetService == null)
  196. m_AssetService = scene.RequestModuleInterface<IAssetService>();
  197. }
  198. ////////////////////////////////////////////////////////////
  199. // IImprovedAssetCache
  200. //
  201. private void UpdateMemoryCache(string key, AssetBase asset)
  202. {
  203. m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
  204. }
  205. private void UpdateFileCache(string key, AssetBase asset)
  206. {
  207. string filename = GetFileName(asset.ID);
  208. try
  209. {
  210. // If the file is already cached just update access time.
  211. if (File.Exists(filename))
  212. {
  213. lock (m_CurrentlyWriting)
  214. {
  215. if (!m_CurrentlyWriting.Contains(filename))
  216. File.SetLastAccessTime(filename, DateTime.Now);
  217. }
  218. }
  219. else
  220. {
  221. // Once we start writing, make sure we flag that we're writing
  222. // that object to the cache so that we don't try to write the
  223. // same file multiple times.
  224. lock (m_CurrentlyWriting)
  225. {
  226. #if WAIT_ON_INPROGRESS_REQUESTS
  227. if (m_CurrentlyWriting.ContainsKey(filename))
  228. {
  229. return;
  230. }
  231. else
  232. {
  233. m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
  234. }
  235. #else
  236. if (m_CurrentlyWriting.Contains(filename))
  237. {
  238. return;
  239. }
  240. else
  241. {
  242. m_CurrentlyWriting.Add(filename);
  243. }
  244. #endif
  245. }
  246. Util.FireAndForget(
  247. delegate { WriteFileCache(filename, asset); });
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. m_log.ErrorFormat(
  253. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  254. asset.ID, e.Message, e.StackTrace);
  255. }
  256. }
  257. public void Cache(AssetBase asset)
  258. {
  259. // TODO: Spawn this off to some seperate thread to do the actual writing
  260. if (asset != null)
  261. {
  262. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  263. if (m_MemoryCacheEnabled)
  264. UpdateMemoryCache(asset.ID, asset);
  265. if (m_FileCacheEnabled)
  266. UpdateFileCache(asset.ID, asset);
  267. }
  268. }
  269. /// <summary>
  270. /// Try to get an asset from the in-memory cache.
  271. /// </summary>
  272. /// <param name="id"></param>
  273. /// <returns></returns>
  274. private AssetBase GetFromMemoryCache(string id)
  275. {
  276. AssetBase asset = null;
  277. if (m_MemoryCache.TryGetValue(id, out asset))
  278. m_MemoryHits++;
  279. return asset;
  280. }
  281. /// <summary>
  282. /// Try to get an asset from the file cache.
  283. /// </summary>
  284. /// <param name="id"></param>
  285. /// <returns></returns>
  286. private AssetBase GetFromFileCache(string id)
  287. {
  288. AssetBase asset = null;
  289. string filename = GetFileName(id);
  290. if (File.Exists(filename))
  291. {
  292. FileStream stream = null;
  293. try
  294. {
  295. stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  296. BinaryFormatter bformatter = new BinaryFormatter();
  297. asset = (AssetBase)bformatter.Deserialize(stream);
  298. m_DiskHits++;
  299. }
  300. catch (System.Runtime.Serialization.SerializationException e)
  301. {
  302. m_log.ErrorFormat(
  303. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  304. filename, id, e.Message, e.StackTrace);
  305. // If there was a problem deserializing the asset, the asset may
  306. // either be corrupted OR was serialized under an old format
  307. // {different version of AssetBase} -- we should attempt to
  308. // delete it and re-cache
  309. File.Delete(filename);
  310. }
  311. catch (Exception e)
  312. {
  313. m_log.ErrorFormat(
  314. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  315. filename, id, e.Message, e.StackTrace);
  316. }
  317. finally
  318. {
  319. if (stream != null)
  320. stream.Close();
  321. }
  322. }
  323. #if WAIT_ON_INPROGRESS_REQUESTS
  324. // Check if we're already downloading this asset. If so, try to wait for it to
  325. // download.
  326. if (m_WaitOnInprogressTimeout > 0)
  327. {
  328. m_RequestsForInprogress++;
  329. ManualResetEvent waitEvent;
  330. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  331. {
  332. waitEvent.WaitOne(m_WaitOnInprogressTimeout);
  333. return Get(id);
  334. }
  335. }
  336. #else
  337. // Track how often we have the problem that an asset is requested while
  338. // it is still being downloaded by a previous request.
  339. if (m_CurrentlyWriting.Contains(filename))
  340. {
  341. m_RequestsForInprogress++;
  342. }
  343. #endif
  344. return asset;
  345. }
  346. public AssetBase Get(string id)
  347. {
  348. m_Requests++;
  349. AssetBase asset = null;
  350. if (m_MemoryCacheEnabled)
  351. asset = GetFromMemoryCache(id);
  352. if (asset == null && m_FileCacheEnabled)
  353. {
  354. asset = GetFromFileCache(id);
  355. if (m_MemoryCacheEnabled && asset != null)
  356. UpdateMemoryCache(id, asset);
  357. }
  358. if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
  359. {
  360. m_HitRateFile = (double)m_DiskHits / m_Requests * 100.0;
  361. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
  362. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Hit Rate {0}% for {1} requests", m_HitRateFile.ToString("0.00"), m_Requests);
  363. if (m_MemoryCacheEnabled)
  364. {
  365. m_HitRateMemory = (double)m_MemoryHits / m_Requests * 100.0;
  366. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Hit Rate {0}% for {1} requests", m_HitRateMemory.ToString("0.00"), m_Requests);
  367. }
  368. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} unnessesary requests due to requests for assets that are currently downloading.", m_RequestsForInprogress);
  369. }
  370. return asset;
  371. }
  372. public AssetBase GetCached(string id)
  373. {
  374. return Get(id);
  375. }
  376. public void Expire(string id)
  377. {
  378. if (m_LogLevel >= 2)
  379. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  380. try
  381. {
  382. if (m_FileCacheEnabled)
  383. {
  384. string filename = GetFileName(id);
  385. if (File.Exists(filename))
  386. {
  387. File.Delete(filename);
  388. }
  389. }
  390. if (m_MemoryCacheEnabled)
  391. m_MemoryCache.Remove(id);
  392. }
  393. catch (Exception e)
  394. {
  395. m_log.ErrorFormat(
  396. "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  397. id, e.Message, e.StackTrace);
  398. }
  399. }
  400. public void Clear()
  401. {
  402. if (m_LogLevel >= 2)
  403. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  404. if (m_FileCacheEnabled)
  405. {
  406. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  407. {
  408. Directory.Delete(dir);
  409. }
  410. }
  411. if (m_MemoryCacheEnabled)
  412. m_MemoryCache.Clear();
  413. }
  414. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  415. {
  416. if (m_LogLevel >= 2)
  417. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
  418. // Purge all files last accessed prior to this point
  419. DateTime purgeLine = DateTime.Now - m_FileExpiration;
  420. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  421. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  422. // such local assets if they have not been recently accessed.
  423. TouchAllSceneAssets(false);
  424. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  425. {
  426. CleanExpiredFiles(dir, purgeLine);
  427. }
  428. }
  429. /// <summary>
  430. /// Recurses through specified directory checking for asset files last
  431. /// accessed prior to the specified purge line and deletes them. Also
  432. /// removes empty tier directories.
  433. /// </summary>
  434. /// <param name="dir"></param>
  435. /// <param name="purgeLine"></param>
  436. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  437. {
  438. foreach (string file in Directory.GetFiles(dir))
  439. {
  440. if (File.GetLastAccessTime(file) < purgeLine)
  441. {
  442. File.Delete(file);
  443. }
  444. }
  445. // Recurse into lower tiers
  446. foreach (string subdir in Directory.GetDirectories(dir))
  447. {
  448. CleanExpiredFiles(subdir, purgeLine);
  449. }
  450. // Check if a tier directory is empty, if so, delete it
  451. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  452. if (dirSize == 0)
  453. {
  454. Directory.Delete(dir);
  455. }
  456. else if (dirSize >= m_CacheWarnAt)
  457. {
  458. m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration", dir, dirSize);
  459. }
  460. }
  461. /// <summary>
  462. /// Determines the filename for an AssetID stored in the file cache
  463. /// </summary>
  464. /// <param name="id"></param>
  465. /// <returns></returns>
  466. private string GetFileName(string id)
  467. {
  468. // Would it be faster to just hash the darn thing?
  469. foreach (char c in m_InvalidChars)
  470. {
  471. id = id.Replace(c, '_');
  472. }
  473. string path = m_CacheDirectory;
  474. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  475. {
  476. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  477. path = Path.Combine(path, pathPart);
  478. }
  479. return Path.Combine(path, id);
  480. }
  481. /// <summary>
  482. /// Writes a file to the file cache, creating any nessesary
  483. /// tier directories along the way
  484. /// </summary>
  485. /// <param name="filename"></param>
  486. /// <param name="asset"></param>
  487. private void WriteFileCache(string filename, AssetBase asset)
  488. {
  489. Stream stream = null;
  490. // Make sure the target cache directory exists
  491. string directory = Path.GetDirectoryName(filename);
  492. // Write file first to a temp name, so that it doesn't look
  493. // like it's already cached while it's still writing.
  494. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  495. try
  496. {
  497. try
  498. {
  499. if (!Directory.Exists(directory))
  500. {
  501. Directory.CreateDirectory(directory);
  502. }
  503. stream = File.Open(tempname, FileMode.Create);
  504. BinaryFormatter bformatter = new BinaryFormatter();
  505. bformatter.Serialize(stream, asset);
  506. }
  507. catch (IOException e)
  508. {
  509. m_log.ErrorFormat(
  510. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  511. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  512. return;
  513. }
  514. finally
  515. {
  516. if (stream != null)
  517. stream.Close();
  518. }
  519. try
  520. {
  521. // Now that it's written, rename it so that it can be found.
  522. //
  523. // File.Copy(tempname, filename, true);
  524. // File.Delete(tempname);
  525. //
  526. // For a brief period, this was done as a separate copy and then temporary file delete operation to
  527. // avoid an IOException caused by move if some competing thread had already written the file.
  528. // However, this causes exceptions on Windows when other threads attempt to read a file
  529. // which is still being copied. So instead, go back to moving the file and swallow any IOException.
  530. //
  531. // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
  532. // filesystem.
  533. File.Move(tempname, filename);
  534. if (m_LogLevel >= 2)
  535. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  536. }
  537. catch (IOException)
  538. {
  539. // If we see an IOException here it's likely that some other competing thread has written the
  540. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  541. // signally by the earlier temporary file writing code.
  542. }
  543. }
  544. finally
  545. {
  546. // Even if the write fails with an exception, we need to make sure
  547. // that we release the lock on that file, otherwise it'll never get
  548. // cached
  549. lock (m_CurrentlyWriting)
  550. {
  551. #if WAIT_ON_INPROGRESS_REQUESTS
  552. ManualResetEvent waitEvent;
  553. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  554. {
  555. m_CurrentlyWriting.Remove(filename);
  556. waitEvent.Set();
  557. }
  558. #else
  559. m_CurrentlyWriting.Remove(filename);
  560. #endif
  561. }
  562. }
  563. }
  564. /// <summary>
  565. /// Scan through the file cache, and return number of assets currently cached.
  566. /// </summary>
  567. /// <param name="dir"></param>
  568. /// <returns></returns>
  569. private int GetFileCacheCount(string dir)
  570. {
  571. int count = Directory.GetFiles(dir).Length;
  572. foreach (string subdir in Directory.GetDirectories(dir))
  573. {
  574. count += GetFileCacheCount(subdir);
  575. }
  576. return count;
  577. }
  578. /// <summary>
  579. /// This notes the last time the Region had a deep asset scan performed on it.
  580. /// </summary>
  581. /// <param name="RegionID"></param>
  582. private void StampRegionStatusFile(UUID RegionID)
  583. {
  584. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + RegionID.ToString() + ".fac");
  585. if (File.Exists(RegionCacheStatusFile))
  586. {
  587. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  588. }
  589. else
  590. {
  591. File.WriteAllText(RegionCacheStatusFile, "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  592. }
  593. }
  594. /// <summary>
  595. /// Iterates through all Scenes, doing a deep scan through assets
  596. /// to update the access time of all assets present in the scene or referenced by assets
  597. /// in the scene.
  598. /// </summary>
  599. /// <param name="storeUncached">
  600. /// If true, then assets scanned which are not found in cache are added to the cache.
  601. /// </param>
  602. /// <returns>Number of distinct asset references found in the scene.</returns>
  603. private int TouchAllSceneAssets(bool storeUncached)
  604. {
  605. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  606. Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
  607. foreach (Scene s in m_Scenes)
  608. {
  609. StampRegionStatusFile(s.RegionInfo.RegionID);
  610. s.ForEachSOG(delegate(SceneObjectGroup e)
  611. {
  612. gatherer.GatherAssetUuids(e, assets);
  613. });
  614. }
  615. foreach (UUID assetID in assets.Keys)
  616. {
  617. string filename = GetFileName(assetID.ToString());
  618. if (File.Exists(filename))
  619. {
  620. File.SetLastAccessTime(filename, DateTime.Now);
  621. }
  622. else if (storeUncached)
  623. {
  624. m_AssetService.Get(assetID.ToString());
  625. }
  626. }
  627. return assets.Keys.Count;
  628. }
  629. /// <summary>
  630. /// Deletes all cache contents
  631. /// </summary>
  632. private void ClearFileCache()
  633. {
  634. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  635. {
  636. try
  637. {
  638. Directory.Delete(dir, true);
  639. }
  640. catch (Exception e)
  641. {
  642. m_log.ErrorFormat(
  643. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  644. dir, m_CacheDirectory, e.Message, e.StackTrace);
  645. }
  646. }
  647. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  648. {
  649. try
  650. {
  651. File.Delete(file);
  652. }
  653. catch (Exception e)
  654. {
  655. m_log.ErrorFormat(
  656. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  657. file, m_CacheDirectory, e.Message, e.StackTrace);
  658. }
  659. }
  660. }
  661. #region Console Commands
  662. private void HandleConsoleCommand(string module, string[] cmdparams)
  663. {
  664. if (cmdparams.Length >= 2)
  665. {
  666. string cmd = cmdparams[1];
  667. switch (cmd)
  668. {
  669. case "status":
  670. if (m_MemoryCacheEnabled)
  671. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Cache : {0} assets", m_MemoryCache.Count);
  672. else
  673. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory cache disabled");
  674. if (m_FileCacheEnabled)
  675. {
  676. int fileCount = GetFileCacheCount(m_CacheDirectory);
  677. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Cache : {0} assets", fileCount);
  678. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  679. {
  680. m_log.Info("[FLOTSAM ASSET CACHE]: Deep scans have previously been performed on the following regions:");
  681. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  682. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  683. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  684. }
  685. }
  686. else
  687. {
  688. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache disabled");
  689. }
  690. break;
  691. case "clear":
  692. if (cmdparams.Length < 2)
  693. {
  694. m_log.Warn("[FLOTSAM ASSET CACHE]: Usage is fcache clear [file] [memory]");
  695. break;
  696. }
  697. bool clearMemory = false, clearFile = false;
  698. if (cmdparams.Length == 2)
  699. {
  700. clearMemory = true;
  701. clearFile = true;
  702. }
  703. foreach (string s in cmdparams)
  704. {
  705. if (s.ToLower() == "memory")
  706. clearMemory = true;
  707. else if (s.ToLower() == "file")
  708. clearFile = true;
  709. }
  710. if (clearMemory)
  711. {
  712. if (m_MemoryCacheEnabled)
  713. {
  714. m_MemoryCache.Clear();
  715. m_log.Info("[FLOTSAM ASSET CACHE]: Memory cache cleared.");
  716. }
  717. else
  718. {
  719. m_log.Info("[FLOTSAM ASSET CACHE]: Memory cache not enabled.");
  720. }
  721. }
  722. if (clearFile)
  723. {
  724. if (m_FileCacheEnabled)
  725. {
  726. ClearFileCache();
  727. m_log.Info("[FLOTSAM ASSET CACHE]: File cache cleared.");
  728. }
  729. else
  730. {
  731. m_log.Info("[FLOTSAM ASSET CACHE]: File cache not enabled.");
  732. }
  733. }
  734. break;
  735. case "assets":
  736. m_log.Info("[FLOTSAM ASSET CACHE]: Ensuring assets are cached for all scenes.");
  737. Util.FireAndForget(delegate {
  738. int assetReferenceTotal = TouchAllSceneAssets(true);
  739. m_log.InfoFormat(
  740. "[FLOTSAM ASSET CACHE]: Completed check with {0} assets.",
  741. assetReferenceTotal);
  742. });
  743. break;
  744. case "expire":
  745. if (cmdparams.Length < 3)
  746. {
  747. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Invalid parameters for Expire, please specify a valid date & time", cmd);
  748. break;
  749. }
  750. string s_expirationDate = "";
  751. DateTime expirationDate;
  752. if (cmdparams.Length > 3)
  753. {
  754. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  755. }
  756. else
  757. {
  758. s_expirationDate = cmdparams[2];
  759. }
  760. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  761. {
  762. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} is not a valid date & time", cmd);
  763. break;
  764. }
  765. if (m_FileCacheEnabled)
  766. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  767. else
  768. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache not active, not clearing.");
  769. break;
  770. default:
  771. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Unknown command {0}", cmd);
  772. break;
  773. }
  774. }
  775. else if (cmdparams.Length == 1)
  776. {
  777. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache status - Display cache status");
  778. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearmem - Remove all assets cached in memory");
  779. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearfile - Remove all assets cached on disk");
  780. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache cachescenes - Attempt a deep cache of all assets in all scenes");
  781. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache <datetime> - Purge assets older then the specified date & time");
  782. }
  783. }
  784. #endregion
  785. #region IAssetService Members
  786. public AssetMetadata GetMetadata(string id)
  787. {
  788. AssetBase asset = Get(id);
  789. return asset.Metadata;
  790. }
  791. public byte[] GetData(string id)
  792. {
  793. AssetBase asset = Get(id);
  794. return asset.Data;
  795. }
  796. public bool Get(string id, object sender, AssetRetrieved handler)
  797. {
  798. AssetBase asset = Get(id);
  799. handler(id, sender, asset);
  800. return true;
  801. }
  802. public string Store(AssetBase asset)
  803. {
  804. if (asset.FullID == UUID.Zero)
  805. {
  806. asset.FullID = UUID.Random();
  807. }
  808. Cache(asset);
  809. return asset.ID;
  810. }
  811. public bool UpdateContent(string id, byte[] data)
  812. {
  813. AssetBase asset = Get(id);
  814. asset.Data = data;
  815. Cache(asset);
  816. return true;
  817. }
  818. public bool Delete(string id)
  819. {
  820. Expire(id);
  821. return true;
  822. }
  823. #endregion
  824. }
  825. }