FlotsamAssetCache.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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 Flotsam.RegionModules.AssetCache
  49. {
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  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 List<string> m_CurrentlyWriting = new List<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. private bool m_DeepScanBeforePurge;
  91. public FlotsamAssetCache()
  92. {
  93. m_InvalidChars.AddRange(Path.GetInvalidPathChars());
  94. m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
  95. }
  96. public Type ReplaceableInterface
  97. {
  98. get { return null; }
  99. }
  100. public string Name
  101. {
  102. get { return m_ModuleName; }
  103. }
  104. public void Initialise(IConfigSource source)
  105. {
  106. IConfig moduleConfig = source.Configs["Modules"];
  107. if (moduleConfig != null)
  108. {
  109. string name = moduleConfig.GetString("AssetCaching", String.Empty);
  110. if (name == Name)
  111. {
  112. m_MemoryCache = new ExpiringCache<string, AssetBase>();
  113. m_Enabled = true;
  114. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
  115. IConfig assetConfig = source.Configs["AssetCache"];
  116. if (assetConfig == null)
  117. {
  118. m_log.Debug(
  119. "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
  120. }
  121. else
  122. {
  123. m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
  124. m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
  125. m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
  126. m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
  127. #if WAIT_ON_INPROGRESS_REQUESTS
  128. m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
  129. #endif
  130. m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
  131. m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
  132. m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
  133. m_FileExpirationCleanupTimer
  134. = TimeSpan.FromHours(
  135. assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
  136. m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
  137. m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
  138. m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
  139. m_DeepScanBeforePurge = assetConfig.GetBoolean("DeepScanBeforePurge", m_DeepScanBeforePurge);
  140. }
  141. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
  142. if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
  143. {
  144. m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
  145. m_CacheCleanTimer.AutoReset = true;
  146. m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
  147. lock (m_CacheCleanTimer)
  148. m_CacheCleanTimer.Start();
  149. }
  150. if (m_CacheDirectoryTiers < 1)
  151. {
  152. m_CacheDirectoryTiers = 1;
  153. }
  154. else if (m_CacheDirectoryTiers > 3)
  155. {
  156. m_CacheDirectoryTiers = 3;
  157. }
  158. if (m_CacheDirectoryTierLen < 1)
  159. {
  160. m_CacheDirectoryTierLen = 1;
  161. }
  162. else if (m_CacheDirectoryTierLen > 4)
  163. {
  164. m_CacheDirectoryTierLen = 4;
  165. }
  166. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
  167. 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);
  168. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
  169. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
  170. }
  171. }
  172. }
  173. public void PostInitialise()
  174. {
  175. }
  176. public void Close()
  177. {
  178. }
  179. public void AddRegion(Scene scene)
  180. {
  181. if (m_Enabled)
  182. {
  183. scene.RegisterModuleInterface<IImprovedAssetCache>(this);
  184. m_Scenes.Add(scene);
  185. if (m_AssetService == null)
  186. {
  187. m_AssetService = scene.RequestModuleInterface<IAssetService>();
  188. }
  189. }
  190. }
  191. public void RemoveRegion(Scene scene)
  192. {
  193. if (m_Enabled)
  194. {
  195. scene.UnregisterModuleInterface<IImprovedAssetCache>(this);
  196. m_Scenes.Remove(scene);
  197. }
  198. }
  199. public void RegionLoaded(Scene scene)
  200. {
  201. }
  202. ////////////////////////////////////////////////////////////
  203. // IImprovedAssetCache
  204. //
  205. private void UpdateMemoryCache(string key, AssetBase asset)
  206. {
  207. m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
  208. }
  209. private void UpdateFileCache(string key, AssetBase asset)
  210. {
  211. string filename = GetFileName(asset.ID);
  212. try
  213. {
  214. // If the file is already cached, don't cache it, just touch it so access time is updated
  215. if (File.Exists(filename))
  216. {
  217. File.SetLastAccessTime(filename, DateTime.Now);
  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 optional deep scan at this point will ensure assets present in scenes,
  421. // or referenced by objects in the scene, but not recently accessed
  422. // are not purged.
  423. if (m_DeepScanBeforePurge)
  424. {
  425. CacheScenes();
  426. }
  427. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  428. {
  429. CleanExpiredFiles(dir, purgeLine);
  430. }
  431. }
  432. /// <summary>
  433. /// Recurses through specified directory checking for asset files last
  434. /// accessed prior to the specified purge line and deletes them. Also
  435. /// removes empty tier directories.
  436. /// </summary>
  437. /// <param name="dir"></param>
  438. /// <param name="purgeLine"></param>
  439. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  440. {
  441. foreach (string file in Directory.GetFiles(dir))
  442. {
  443. if (File.GetLastAccessTime(file) < purgeLine)
  444. {
  445. File.Delete(file);
  446. }
  447. }
  448. // Recurse into lower tiers
  449. foreach (string subdir in Directory.GetDirectories(dir))
  450. {
  451. CleanExpiredFiles(subdir, purgeLine);
  452. }
  453. // Check if a tier directory is empty, if so, delete it
  454. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  455. if (dirSize == 0)
  456. {
  457. Directory.Delete(dir);
  458. }
  459. else if (dirSize >= m_CacheWarnAt)
  460. {
  461. m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration", dir, dirSize);
  462. }
  463. }
  464. /// <summary>
  465. /// Determines the filename for an AssetID stored in the file cache
  466. /// </summary>
  467. /// <param name="id"></param>
  468. /// <returns></returns>
  469. private string GetFileName(string id)
  470. {
  471. // Would it be faster to just hash the darn thing?
  472. foreach (char c in m_InvalidChars)
  473. {
  474. id = id.Replace(c, '_');
  475. }
  476. string path = m_CacheDirectory;
  477. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  478. {
  479. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  480. path = Path.Combine(path, pathPart);
  481. }
  482. return Path.Combine(path, id);
  483. }
  484. /// <summary>
  485. /// Writes a file to the file cache, creating any nessesary
  486. /// tier directories along the way
  487. /// </summary>
  488. /// <param name="filename"></param>
  489. /// <param name="asset"></param>
  490. private void WriteFileCache(string filename, AssetBase asset)
  491. {
  492. Stream stream = null;
  493. // Make sure the target cache directory exists
  494. string directory = Path.GetDirectoryName(filename);
  495. // Write file first to a temp name, so that it doesn't look
  496. // like it's already cached while it's still writing.
  497. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  498. try
  499. {
  500. try
  501. {
  502. if (!Directory.Exists(directory))
  503. {
  504. Directory.CreateDirectory(directory);
  505. }
  506. stream = File.Open(tempname, FileMode.Create);
  507. BinaryFormatter bformatter = new BinaryFormatter();
  508. bformatter.Serialize(stream, asset);
  509. }
  510. catch (IOException e)
  511. {
  512. m_log.ErrorFormat(
  513. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  514. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  515. return;
  516. }
  517. finally
  518. {
  519. if (stream != null)
  520. stream.Close();
  521. }
  522. try
  523. {
  524. // Now that it's written, rename it so that it can be found.
  525. //
  526. // File.Copy(tempname, filename, true);
  527. // File.Delete(tempname);
  528. //
  529. // For a brief period, this was done as a separate copy and then temporary file delete operation to
  530. // avoid an IOException caused by move if some competing thread had already written the file.
  531. // However, this causes exceptions on Windows when other threads attempt to read a file
  532. // which is still being copied. So instead, go back to moving the file and swallow any IOException.
  533. //
  534. // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
  535. // filesystem.
  536. File.Move(tempname, filename);
  537. if (m_LogLevel >= 2)
  538. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  539. }
  540. catch (IOException)
  541. {
  542. // If we see an IOException here it's likely that some other competing thread has written the
  543. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  544. // signally by the earlier temporary file writing code.
  545. }
  546. }
  547. finally
  548. {
  549. // Even if the write fails with an exception, we need to make sure
  550. // that we release the lock on that file, otherwise it'll never get
  551. // cached
  552. lock (m_CurrentlyWriting)
  553. {
  554. #if WAIT_ON_INPROGRESS_REQUESTS
  555. ManualResetEvent waitEvent;
  556. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  557. {
  558. m_CurrentlyWriting.Remove(filename);
  559. waitEvent.Set();
  560. }
  561. #else
  562. m_CurrentlyWriting.Remove(filename);
  563. #endif
  564. }
  565. }
  566. }
  567. /// <summary>
  568. /// Scan through the file cache, and return number of assets currently cached.
  569. /// </summary>
  570. /// <param name="dir"></param>
  571. /// <returns></returns>
  572. private int GetFileCacheCount(string dir)
  573. {
  574. int count = Directory.GetFiles(dir).Length;
  575. foreach (string subdir in Directory.GetDirectories(dir))
  576. {
  577. count += GetFileCacheCount(subdir);
  578. }
  579. return count;
  580. }
  581. /// <summary>
  582. /// This notes the last time the Region had a deep asset scan performed on it.
  583. /// </summary>
  584. /// <param name="RegionID"></param>
  585. private void StampRegionStatusFile(UUID RegionID)
  586. {
  587. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + RegionID.ToString() + ".fac");
  588. if (File.Exists(RegionCacheStatusFile))
  589. {
  590. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  591. }
  592. else
  593. {
  594. File.WriteAllText(RegionCacheStatusFile, "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  595. }
  596. }
  597. /// <summary>
  598. /// Iterates through all Scenes, doing a deep scan through assets
  599. /// to cache all assets present in the scene or referenced by assets
  600. /// in the scene
  601. /// </summary>
  602. /// <returns></returns>
  603. private int CacheScenes()
  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
  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]: Caching all assets, in all scenes.");
  737. Util.FireAndForget(delegate {
  738. int assetsCached = CacheScenes();
  739. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Completed Scene Caching, {0} assets found.", assetsCached);
  740. });
  741. break;
  742. case "expire":
  743. if (cmdparams.Length < 3)
  744. {
  745. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Invalid parameters for Expire, please specify a valid date & time", cmd);
  746. break;
  747. }
  748. string s_expirationDate = "";
  749. DateTime expirationDate;
  750. if (cmdparams.Length > 3)
  751. {
  752. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  753. }
  754. else
  755. {
  756. s_expirationDate = cmdparams[2];
  757. }
  758. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  759. {
  760. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} is not a valid date & time", cmd);
  761. break;
  762. }
  763. if (m_FileCacheEnabled)
  764. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  765. else
  766. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache not active, not clearing.");
  767. break;
  768. default:
  769. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Unknown command {0}", cmd);
  770. break;
  771. }
  772. }
  773. else if (cmdparams.Length == 1)
  774. {
  775. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache status - Display cache status");
  776. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearmem - Remove all assets cached in memory");
  777. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearfile - Remove all assets cached on disk");
  778. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache cachescenes - Attempt a deep cache of all assets in all scenes");
  779. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache <datetime> - Purge assets older then the specified date & time");
  780. }
  781. }
  782. #endregion
  783. #region IAssetService Members
  784. public AssetMetadata GetMetadata(string id)
  785. {
  786. AssetBase asset = Get(id);
  787. return asset.Metadata;
  788. }
  789. public byte[] GetData(string id)
  790. {
  791. AssetBase asset = Get(id);
  792. return asset.Data;
  793. }
  794. public bool Get(string id, object sender, AssetRetrieved handler)
  795. {
  796. AssetBase asset = Get(id);
  797. handler(id, sender, asset);
  798. return true;
  799. }
  800. public string Store(AssetBase asset)
  801. {
  802. if (asset.FullID == UUID.Zero)
  803. {
  804. asset.FullID = UUID.Random();
  805. }
  806. Cache(asset);
  807. return asset.ID;
  808. }
  809. public bool UpdateContent(string id, byte[] data)
  810. {
  811. AssetBase asset = Get(id);
  812. asset.Data = data;
  813. Cache(asset);
  814. return true;
  815. }
  816. public bool Delete(string id)
  817. {
  818. Expire(id);
  819. return true;
  820. }
  821. #endregion
  822. }
  823. }