FlotsamAssetCache.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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")]
  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. if (m_AssetService == null)
  184. {
  185. m_AssetService = scene.RequestModuleInterface<IAssetService>();
  186. }
  187. }
  188. }
  189. public void RemoveRegion(Scene scene)
  190. {
  191. if (m_Enabled)
  192. {
  193. scene.UnregisterModuleInterface<IImprovedAssetCache>(this);
  194. m_Scenes.Remove(scene);
  195. }
  196. }
  197. public void RegionLoaded(Scene scene)
  198. {
  199. }
  200. ////////////////////////////////////////////////////////////
  201. // IImprovedAssetCache
  202. //
  203. private void UpdateMemoryCache(string key, AssetBase asset)
  204. {
  205. m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
  206. }
  207. private void UpdateFileCache(string key, AssetBase asset)
  208. {
  209. string filename = GetFileName(asset.ID);
  210. try
  211. {
  212. // If the file is already cached just update access time.
  213. if (File.Exists(filename))
  214. {
  215. lock (m_CurrentlyWriting)
  216. {
  217. if (!m_CurrentlyWriting.Contains(filename))
  218. File.SetLastAccessTime(filename, DateTime.Now);
  219. }
  220. }
  221. else
  222. {
  223. // Once we start writing, make sure we flag that we're writing
  224. // that object to the cache so that we don't try to write the
  225. // same file multiple times.
  226. lock (m_CurrentlyWriting)
  227. {
  228. #if WAIT_ON_INPROGRESS_REQUESTS
  229. if (m_CurrentlyWriting.ContainsKey(filename))
  230. {
  231. return;
  232. }
  233. else
  234. {
  235. m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
  236. }
  237. #else
  238. if (m_CurrentlyWriting.Contains(filename))
  239. {
  240. return;
  241. }
  242. else
  243. {
  244. m_CurrentlyWriting.Add(filename);
  245. }
  246. #endif
  247. }
  248. Util.FireAndForget(
  249. delegate { WriteFileCache(filename, asset); });
  250. }
  251. }
  252. catch (Exception e)
  253. {
  254. m_log.ErrorFormat(
  255. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  256. asset.ID, e.Message, e.StackTrace);
  257. }
  258. }
  259. public void Cache(AssetBase asset)
  260. {
  261. // TODO: Spawn this off to some seperate thread to do the actual writing
  262. if (asset != null)
  263. {
  264. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  265. if (m_MemoryCacheEnabled)
  266. UpdateMemoryCache(asset.ID, asset);
  267. if (m_FileCacheEnabled)
  268. UpdateFileCache(asset.ID, asset);
  269. }
  270. }
  271. /// <summary>
  272. /// Try to get an asset from the in-memory cache.
  273. /// </summary>
  274. /// <param name="id"></param>
  275. /// <returns></returns>
  276. private AssetBase GetFromMemoryCache(string id)
  277. {
  278. AssetBase asset = null;
  279. if (m_MemoryCache.TryGetValue(id, out asset))
  280. m_MemoryHits++;
  281. return asset;
  282. }
  283. /// <summary>
  284. /// Try to get an asset from the file cache.
  285. /// </summary>
  286. /// <param name="id"></param>
  287. /// <returns></returns>
  288. private AssetBase GetFromFileCache(string id)
  289. {
  290. AssetBase asset = null;
  291. string filename = GetFileName(id);
  292. if (File.Exists(filename))
  293. {
  294. FileStream stream = null;
  295. try
  296. {
  297. stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  298. BinaryFormatter bformatter = new BinaryFormatter();
  299. asset = (AssetBase)bformatter.Deserialize(stream);
  300. m_DiskHits++;
  301. }
  302. catch (System.Runtime.Serialization.SerializationException e)
  303. {
  304. m_log.ErrorFormat(
  305. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  306. filename, id, e.Message, e.StackTrace);
  307. // If there was a problem deserializing the asset, the asset may
  308. // either be corrupted OR was serialized under an old format
  309. // {different version of AssetBase} -- we should attempt to
  310. // delete it and re-cache
  311. File.Delete(filename);
  312. }
  313. catch (Exception e)
  314. {
  315. m_log.ErrorFormat(
  316. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  317. filename, id, e.Message, e.StackTrace);
  318. }
  319. finally
  320. {
  321. if (stream != null)
  322. stream.Close();
  323. }
  324. }
  325. #if WAIT_ON_INPROGRESS_REQUESTS
  326. // Check if we're already downloading this asset. If so, try to wait for it to
  327. // download.
  328. if (m_WaitOnInprogressTimeout > 0)
  329. {
  330. m_RequestsForInprogress++;
  331. ManualResetEvent waitEvent;
  332. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  333. {
  334. waitEvent.WaitOne(m_WaitOnInprogressTimeout);
  335. return Get(id);
  336. }
  337. }
  338. #else
  339. // Track how often we have the problem that an asset is requested while
  340. // it is still being downloaded by a previous request.
  341. if (m_CurrentlyWriting.Contains(filename))
  342. {
  343. m_RequestsForInprogress++;
  344. }
  345. #endif
  346. return asset;
  347. }
  348. public AssetBase Get(string id)
  349. {
  350. m_Requests++;
  351. AssetBase asset = null;
  352. if (m_MemoryCacheEnabled)
  353. asset = GetFromMemoryCache(id);
  354. if (asset == null && m_FileCacheEnabled)
  355. {
  356. asset = GetFromFileCache(id);
  357. if (m_MemoryCacheEnabled && asset != null)
  358. UpdateMemoryCache(id, asset);
  359. }
  360. if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
  361. {
  362. m_HitRateFile = (double)m_DiskHits / m_Requests * 100.0;
  363. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
  364. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Hit Rate {0}% for {1} requests", m_HitRateFile.ToString("0.00"), m_Requests);
  365. if (m_MemoryCacheEnabled)
  366. {
  367. m_HitRateMemory = (double)m_MemoryHits / m_Requests * 100.0;
  368. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Hit Rate {0}% for {1} requests", m_HitRateMemory.ToString("0.00"), m_Requests);
  369. }
  370. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} unnessesary requests due to requests for assets that are currently downloading.", m_RequestsForInprogress);
  371. }
  372. return asset;
  373. }
  374. public AssetBase GetCached(string id)
  375. {
  376. return Get(id);
  377. }
  378. public void Expire(string id)
  379. {
  380. if (m_LogLevel >= 2)
  381. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  382. try
  383. {
  384. if (m_FileCacheEnabled)
  385. {
  386. string filename = GetFileName(id);
  387. if (File.Exists(filename))
  388. {
  389. File.Delete(filename);
  390. }
  391. }
  392. if (m_MemoryCacheEnabled)
  393. m_MemoryCache.Remove(id);
  394. }
  395. catch (Exception e)
  396. {
  397. m_log.ErrorFormat(
  398. "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  399. id, e.Message, e.StackTrace);
  400. }
  401. }
  402. public void Clear()
  403. {
  404. if (m_LogLevel >= 2)
  405. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  406. if (m_FileCacheEnabled)
  407. {
  408. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  409. {
  410. Directory.Delete(dir);
  411. }
  412. }
  413. if (m_MemoryCacheEnabled)
  414. m_MemoryCache.Clear();
  415. }
  416. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  417. {
  418. if (m_LogLevel >= 2)
  419. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
  420. // Purge all files last accessed prior to this point
  421. DateTime purgeLine = DateTime.Now - m_FileExpiration;
  422. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  423. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  424. // such local assets if they have not been recently accessed.
  425. TouchAllSceneAssets(false);
  426. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  427. {
  428. CleanExpiredFiles(dir, purgeLine);
  429. }
  430. }
  431. /// <summary>
  432. /// Recurses through specified directory checking for asset files last
  433. /// accessed prior to the specified purge line and deletes them. Also
  434. /// removes empty tier directories.
  435. /// </summary>
  436. /// <param name="dir"></param>
  437. /// <param name="purgeLine"></param>
  438. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  439. {
  440. foreach (string file in Directory.GetFiles(dir))
  441. {
  442. if (File.GetLastAccessTime(file) < purgeLine)
  443. {
  444. File.Delete(file);
  445. }
  446. }
  447. // Recurse into lower tiers
  448. foreach (string subdir in Directory.GetDirectories(dir))
  449. {
  450. CleanExpiredFiles(subdir, purgeLine);
  451. }
  452. // Check if a tier directory is empty, if so, delete it
  453. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  454. if (dirSize == 0)
  455. {
  456. Directory.Delete(dir);
  457. }
  458. else if (dirSize >= m_CacheWarnAt)
  459. {
  460. m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration", dir, dirSize);
  461. }
  462. }
  463. /// <summary>
  464. /// Determines the filename for an AssetID stored in the file cache
  465. /// </summary>
  466. /// <param name="id"></param>
  467. /// <returns></returns>
  468. private string GetFileName(string id)
  469. {
  470. // Would it be faster to just hash the darn thing?
  471. foreach (char c in m_InvalidChars)
  472. {
  473. id = id.Replace(c, '_');
  474. }
  475. string path = m_CacheDirectory;
  476. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  477. {
  478. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  479. path = Path.Combine(path, pathPart);
  480. }
  481. return Path.Combine(path, id);
  482. }
  483. /// <summary>
  484. /// Writes a file to the file cache, creating any nessesary
  485. /// tier directories along the way
  486. /// </summary>
  487. /// <param name="filename"></param>
  488. /// <param name="asset"></param>
  489. private void WriteFileCache(string filename, AssetBase asset)
  490. {
  491. Stream stream = null;
  492. // Make sure the target cache directory exists
  493. string directory = Path.GetDirectoryName(filename);
  494. // Write file first to a temp name, so that it doesn't look
  495. // like it's already cached while it's still writing.
  496. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  497. try
  498. {
  499. try
  500. {
  501. if (!Directory.Exists(directory))
  502. {
  503. Directory.CreateDirectory(directory);
  504. }
  505. stream = File.Open(tempname, FileMode.Create);
  506. BinaryFormatter bformatter = new BinaryFormatter();
  507. bformatter.Serialize(stream, asset);
  508. }
  509. catch (IOException e)
  510. {
  511. m_log.ErrorFormat(
  512. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  513. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  514. return;
  515. }
  516. finally
  517. {
  518. if (stream != null)
  519. stream.Close();
  520. }
  521. try
  522. {
  523. // Now that it's written, rename it so that it can be found.
  524. //
  525. // File.Copy(tempname, filename, true);
  526. // File.Delete(tempname);
  527. //
  528. // For a brief period, this was done as a separate copy and then temporary file delete operation to
  529. // avoid an IOException caused by move if some competing thread had already written the file.
  530. // However, this causes exceptions on Windows when other threads attempt to read a file
  531. // which is still being copied. So instead, go back to moving the file and swallow any IOException.
  532. //
  533. // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
  534. // filesystem.
  535. File.Move(tempname, filename);
  536. if (m_LogLevel >= 2)
  537. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  538. }
  539. catch (IOException)
  540. {
  541. // If we see an IOException here it's likely that some other competing thread has written the
  542. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  543. // signally by the earlier temporary file writing code.
  544. }
  545. }
  546. finally
  547. {
  548. // Even if the write fails with an exception, we need to make sure
  549. // that we release the lock on that file, otherwise it'll never get
  550. // cached
  551. lock (m_CurrentlyWriting)
  552. {
  553. #if WAIT_ON_INPROGRESS_REQUESTS
  554. ManualResetEvent waitEvent;
  555. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  556. {
  557. m_CurrentlyWriting.Remove(filename);
  558. waitEvent.Set();
  559. }
  560. #else
  561. m_CurrentlyWriting.Remove(filename);
  562. #endif
  563. }
  564. }
  565. }
  566. /// <summary>
  567. /// Scan through the file cache, and return number of assets currently cached.
  568. /// </summary>
  569. /// <param name="dir"></param>
  570. /// <returns></returns>
  571. private int GetFileCacheCount(string dir)
  572. {
  573. int count = Directory.GetFiles(dir).Length;
  574. foreach (string subdir in Directory.GetDirectories(dir))
  575. {
  576. count += GetFileCacheCount(subdir);
  577. }
  578. return count;
  579. }
  580. /// <summary>
  581. /// This notes the last time the Region had a deep asset scan performed on it.
  582. /// </summary>
  583. /// <param name="RegionID"></param>
  584. private void StampRegionStatusFile(UUID RegionID)
  585. {
  586. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + RegionID.ToString() + ".fac");
  587. if (File.Exists(RegionCacheStatusFile))
  588. {
  589. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  590. }
  591. else
  592. {
  593. File.WriteAllText(RegionCacheStatusFile, "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  594. }
  595. }
  596. /// <summary>
  597. /// Iterates through all Scenes, doing a deep scan through assets
  598. /// to update the access time of all assets present in the scene or referenced by assets
  599. /// in the scene.
  600. /// </summary>
  601. /// <param name="storeUncached">
  602. /// If true, then assets scanned which are not found in cache are added to the cache.
  603. /// </param>
  604. /// <returns>Number of distinct asset references found in the scene.</returns>
  605. private int TouchAllSceneAssets(bool storeUncached)
  606. {
  607. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  608. Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
  609. foreach (Scene s in m_Scenes)
  610. {
  611. StampRegionStatusFile(s.RegionInfo.RegionID);
  612. s.ForEachSOG(delegate(SceneObjectGroup e)
  613. {
  614. gatherer.GatherAssetUuids(e, assets);
  615. });
  616. }
  617. foreach (UUID assetID in assets.Keys)
  618. {
  619. string filename = GetFileName(assetID.ToString());
  620. if (File.Exists(filename))
  621. {
  622. File.SetLastAccessTime(filename, DateTime.Now);
  623. }
  624. else if (storeUncached)
  625. {
  626. m_AssetService.Get(assetID.ToString());
  627. }
  628. }
  629. return assets.Keys.Count;
  630. }
  631. /// <summary>
  632. /// Deletes all cache contents
  633. /// </summary>
  634. private void ClearFileCache()
  635. {
  636. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  637. {
  638. try
  639. {
  640. Directory.Delete(dir, true);
  641. }
  642. catch (Exception e)
  643. {
  644. m_log.ErrorFormat(
  645. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  646. dir, m_CacheDirectory, e.Message, e.StackTrace);
  647. }
  648. }
  649. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  650. {
  651. try
  652. {
  653. File.Delete(file);
  654. }
  655. catch (Exception e)
  656. {
  657. m_log.ErrorFormat(
  658. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  659. file, m_CacheDirectory, e.Message, e.StackTrace);
  660. }
  661. }
  662. }
  663. #region Console Commands
  664. private void HandleConsoleCommand(string module, string[] cmdparams)
  665. {
  666. if (cmdparams.Length >= 2)
  667. {
  668. string cmd = cmdparams[1];
  669. switch (cmd)
  670. {
  671. case "status":
  672. if (m_MemoryCacheEnabled)
  673. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Cache : {0} assets", m_MemoryCache.Count);
  674. else
  675. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory cache disabled");
  676. if (m_FileCacheEnabled)
  677. {
  678. int fileCount = GetFileCacheCount(m_CacheDirectory);
  679. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Cache : {0} assets", fileCount);
  680. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  681. {
  682. m_log.Info("[FLOTSAM ASSET CACHE]: Deep scans have previously been performed on the following regions:");
  683. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  684. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  685. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  686. }
  687. }
  688. else
  689. {
  690. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache disabled");
  691. }
  692. break;
  693. case "clear":
  694. if (cmdparams.Length < 2)
  695. {
  696. m_log.Warn("[FLOTSAM ASSET CACHE]: Usage is fcache clear [file] [memory]");
  697. break;
  698. }
  699. bool clearMemory = false, clearFile = false;
  700. if (cmdparams.Length == 2)
  701. {
  702. clearMemory = true;
  703. clearFile = true;
  704. }
  705. foreach (string s in cmdparams)
  706. {
  707. if (s.ToLower() == "memory")
  708. clearMemory = true;
  709. else if (s.ToLower() == "file")
  710. clearFile = true;
  711. }
  712. if (clearMemory)
  713. {
  714. if (m_MemoryCacheEnabled)
  715. {
  716. m_MemoryCache.Clear();
  717. m_log.Info("[FLOTSAM ASSET CACHE]: Memory cache cleared.");
  718. }
  719. else
  720. {
  721. m_log.Info("[FLOTSAM ASSET CACHE]: Memory cache not enabled.");
  722. }
  723. }
  724. if (clearFile)
  725. {
  726. if (m_FileCacheEnabled)
  727. {
  728. ClearFileCache();
  729. m_log.Info("[FLOTSAM ASSET CACHE]: File cache cleared.");
  730. }
  731. else
  732. {
  733. m_log.Info("[FLOTSAM ASSET CACHE]: File cache not enabled.");
  734. }
  735. }
  736. break;
  737. case "assets":
  738. m_log.Info("[FLOTSAM ASSET CACHE]: Ensuring assets are cached for all scenes.");
  739. Util.FireAndForget(delegate {
  740. int assetReferenceTotal = TouchAllSceneAssets(true);
  741. m_log.InfoFormat(
  742. "[FLOTSAM ASSET CACHE]: Completed check with {0} assets.",
  743. assetReferenceTotal);
  744. });
  745. break;
  746. case "expire":
  747. if (cmdparams.Length < 3)
  748. {
  749. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Invalid parameters for Expire, please specify a valid date & time", cmd);
  750. break;
  751. }
  752. string s_expirationDate = "";
  753. DateTime expirationDate;
  754. if (cmdparams.Length > 3)
  755. {
  756. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  757. }
  758. else
  759. {
  760. s_expirationDate = cmdparams[2];
  761. }
  762. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  763. {
  764. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} is not a valid date & time", cmd);
  765. break;
  766. }
  767. if (m_FileCacheEnabled)
  768. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  769. else
  770. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache not active, not clearing.");
  771. break;
  772. default:
  773. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Unknown command {0}", cmd);
  774. break;
  775. }
  776. }
  777. else if (cmdparams.Length == 1)
  778. {
  779. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache status - Display cache status");
  780. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearmem - Remove all assets cached in memory");
  781. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearfile - Remove all assets cached on disk");
  782. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache cachescenes - Attempt a deep cache of all assets in all scenes");
  783. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache <datetime> - Purge assets older then the specified date & time");
  784. }
  785. }
  786. #endregion
  787. #region IAssetService Members
  788. public AssetMetadata GetMetadata(string id)
  789. {
  790. AssetBase asset = Get(id);
  791. return asset.Metadata;
  792. }
  793. public byte[] GetData(string id)
  794. {
  795. AssetBase asset = Get(id);
  796. return asset.Data;
  797. }
  798. public bool Get(string id, object sender, AssetRetrieved handler)
  799. {
  800. AssetBase asset = Get(id);
  801. handler(id, sender, asset);
  802. return true;
  803. }
  804. public string Store(AssetBase asset)
  805. {
  806. if (asset.FullID == UUID.Zero)
  807. {
  808. asset.FullID = UUID.Random();
  809. }
  810. Cache(asset);
  811. return asset.ID;
  812. }
  813. public bool UpdateContent(string id, byte[] data)
  814. {
  815. AssetBase asset = Get(id);
  816. asset.Data = data;
  817. Cache(asset);
  818. return true;
  819. }
  820. public bool Delete(string id)
  821. {
  822. Expire(id);
  823. return true;
  824. }
  825. #endregion
  826. }
  827. }