FlotsamAssetCache.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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.Linq;
  33. using System.Reflection;
  34. using System.Runtime.Serialization;
  35. using System.Runtime.Serialization.Formatters.Binary;
  36. using System.Threading;
  37. using System.Timers;
  38. using log4net;
  39. using Nini.Config;
  40. using Mono.Addins;
  41. using OpenMetaverse;
  42. using OpenSim.Framework;
  43. using OpenSim.Framework.Console;
  44. using OpenSim.Framework.Monitoring;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.Framework.Scenes;
  47. using OpenSim.Services.Interfaces;
  48. //[assembly: Addin("FlotsamAssetCache", "1.1")]
  49. //[assembly: AddinDependency("OpenSim", "0.8.1")]
  50. namespace OpenSim.Region.CoreModules.Asset
  51. {
  52. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
  53. public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService
  54. {
  55. private static readonly ILog m_log =
  56. LogManager.GetLogger(
  57. MethodBase.GetCurrentMethod().DeclaringType);
  58. private bool m_Enabled;
  59. private const string m_ModuleName = "FlotsamAssetCache";
  60. private const string m_DefaultCacheDirectory = "./assetcache";
  61. private string m_CacheDirectory = m_DefaultCacheDirectory;
  62. private readonly List<char> m_InvalidChars = new List<char>();
  63. private int m_LogLevel = 0;
  64. private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
  65. private static ulong m_Requests;
  66. private static ulong m_RequestsForInprogress;
  67. private static ulong m_DiskHits;
  68. private static ulong m_MemoryHits;
  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(key);
  208. try
  209. {
  210. // If the file is already cached, don't cache it, just touch it so access time is updated
  211. if (File.Exists(filename))
  212. {
  213. UpdateFileLastAccessTime(filename);
  214. }
  215. else
  216. {
  217. // Once we start writing, make sure we flag that we're writing
  218. // that object to the cache so that we don't try to write the
  219. // same file multiple times.
  220. lock (m_CurrentlyWriting)
  221. {
  222. #if WAIT_ON_INPROGRESS_REQUESTS
  223. if (m_CurrentlyWriting.ContainsKey(filename))
  224. {
  225. return;
  226. }
  227. else
  228. {
  229. m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
  230. }
  231. #else
  232. if (m_CurrentlyWriting.Contains(filename))
  233. {
  234. return;
  235. }
  236. else
  237. {
  238. m_CurrentlyWriting.Add(filename);
  239. }
  240. #endif
  241. }
  242. Util.FireAndForget(
  243. delegate { WriteFileCache(filename, asset); }, null, "FlotsamAssetCache.UpdateFileCache");
  244. }
  245. }
  246. catch (Exception e)
  247. {
  248. m_log.ErrorFormat(
  249. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  250. asset.ID, e.Message, e.StackTrace);
  251. }
  252. }
  253. public void Cache(AssetBase asset)
  254. {
  255. // TODO: Spawn this off to some seperate thread to do the actual writing
  256. if (asset != null)
  257. {
  258. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  259. if (m_MemoryCacheEnabled)
  260. UpdateMemoryCache(asset.ID, asset);
  261. if (m_FileCacheEnabled)
  262. UpdateFileCache(asset.ID, asset);
  263. }
  264. }
  265. /// <summary>
  266. /// Updates the cached file with the current time.
  267. /// </summary>
  268. /// <param name="filename">Filename.</param>
  269. /// <returns><c>true</c>, if the update was successful, false otherwise.</returns>
  270. private bool UpdateFileLastAccessTime(string filename)
  271. {
  272. try
  273. {
  274. File.SetLastAccessTime(filename, DateTime.Now);
  275. return true;
  276. }
  277. catch
  278. {
  279. return false;
  280. }
  281. }
  282. /// <summary>
  283. /// Try to get an asset from the in-memory cache.
  284. /// </summary>
  285. /// <param name="id"></param>
  286. /// <returns></returns>
  287. private AssetBase GetFromMemoryCache(string id)
  288. {
  289. AssetBase asset = null;
  290. if (m_MemoryCache.TryGetValue(id, out asset))
  291. m_MemoryHits++;
  292. return asset;
  293. }
  294. private bool CheckFromMemoryCache(string id)
  295. {
  296. return m_MemoryCache.Contains(id);
  297. }
  298. /// <summary>
  299. /// Try to get an asset from the file cache.
  300. /// </summary>
  301. /// <param name="id"></param>
  302. /// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
  303. private AssetBase GetFromFileCache(string id)
  304. {
  305. string filename = GetFileName(id);
  306. #if WAIT_ON_INPROGRESS_REQUESTS
  307. // Check if we're already downloading this asset. If so, try to wait for it to
  308. // download.
  309. if (m_WaitOnInprogressTimeout > 0)
  310. {
  311. m_RequestsForInprogress++;
  312. ManualResetEvent waitEvent;
  313. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  314. {
  315. waitEvent.WaitOne(m_WaitOnInprogressTimeout);
  316. return Get(id);
  317. }
  318. }
  319. #else
  320. // Track how often we have the problem that an asset is requested while
  321. // it is still being downloaded by a previous request.
  322. if (m_CurrentlyWriting.Contains(filename))
  323. {
  324. m_RequestsForInprogress++;
  325. return null;
  326. }
  327. #endif
  328. AssetBase asset = null;
  329. if (File.Exists(filename))
  330. {
  331. try
  332. {
  333. using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  334. {
  335. BinaryFormatter bformatter = new BinaryFormatter();
  336. asset = (AssetBase)bformatter.Deserialize(stream);
  337. m_DiskHits++;
  338. }
  339. }
  340. catch (System.Runtime.Serialization.SerializationException e)
  341. {
  342. m_log.WarnFormat(
  343. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  344. filename, id, e.Message, e.StackTrace);
  345. // If there was a problem deserializing the asset, the asset may
  346. // either be corrupted OR was serialized under an old format
  347. // {different version of AssetBase} -- we should attempt to
  348. // delete it and re-cache
  349. File.Delete(filename);
  350. }
  351. catch (Exception e)
  352. {
  353. m_log.WarnFormat(
  354. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  355. filename, id, e.Message, e.StackTrace);
  356. }
  357. }
  358. return asset;
  359. }
  360. private bool CheckFromFileCache(string id)
  361. {
  362. bool found = false;
  363. string filename = GetFileName(id);
  364. if (File.Exists(filename))
  365. {
  366. try
  367. {
  368. using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  369. {
  370. if (stream != null)
  371. found = true;
  372. }
  373. }
  374. catch (Exception e)
  375. {
  376. m_log.ErrorFormat(
  377. "[FLOTSAM ASSET CACHE]: Failed to check file {0} for asset {1}. Exception {2} {3}",
  378. filename, id, e.Message, e.StackTrace);
  379. }
  380. }
  381. return found;
  382. }
  383. public AssetBase Get(string id)
  384. {
  385. m_Requests++;
  386. AssetBase asset = null;
  387. if (m_MemoryCacheEnabled)
  388. asset = GetFromMemoryCache(id);
  389. if (asset == null && m_FileCacheEnabled)
  390. {
  391. asset = GetFromFileCache(id);
  392. if (m_MemoryCacheEnabled && asset != null)
  393. UpdateMemoryCache(id, asset);
  394. }
  395. if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
  396. {
  397. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
  398. GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l));
  399. }
  400. return asset;
  401. }
  402. public bool Check(string id)
  403. {
  404. if (m_MemoryCacheEnabled && CheckFromMemoryCache(id))
  405. return true;
  406. if (m_FileCacheEnabled && CheckFromFileCache(id))
  407. return true;
  408. return false;
  409. }
  410. public AssetBase GetCached(string id)
  411. {
  412. return Get(id);
  413. }
  414. public void Expire(string id)
  415. {
  416. if (m_LogLevel >= 2)
  417. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  418. try
  419. {
  420. if (m_FileCacheEnabled)
  421. {
  422. string filename = GetFileName(id);
  423. if (File.Exists(filename))
  424. {
  425. File.Delete(filename);
  426. }
  427. }
  428. if (m_MemoryCacheEnabled)
  429. m_MemoryCache.Remove(id);
  430. }
  431. catch (Exception e)
  432. {
  433. m_log.WarnFormat(
  434. "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  435. id, e.Message, e.StackTrace);
  436. }
  437. }
  438. public void Clear()
  439. {
  440. if (m_LogLevel >= 2)
  441. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  442. if (m_FileCacheEnabled)
  443. {
  444. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  445. {
  446. Directory.Delete(dir);
  447. }
  448. }
  449. if (m_MemoryCacheEnabled)
  450. m_MemoryCache.Clear();
  451. }
  452. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  453. {
  454. if (m_LogLevel >= 2)
  455. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
  456. // Purge all files last accessed prior to this point
  457. DateTime purgeLine = DateTime.Now - m_FileExpiration;
  458. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  459. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  460. // such local assets if they have not been recently accessed.
  461. TouchAllSceneAssets(false);
  462. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  463. {
  464. CleanExpiredFiles(dir, purgeLine);
  465. }
  466. }
  467. /// <summary>
  468. /// Recurses through specified directory checking for asset files last
  469. /// accessed prior to the specified purge line and deletes them. Also
  470. /// removes empty tier directories.
  471. /// </summary>
  472. /// <param name="dir"></param>
  473. /// <param name="purgeLine"></param>
  474. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  475. {
  476. try
  477. {
  478. foreach (string file in Directory.GetFiles(dir))
  479. {
  480. if (File.GetLastAccessTime(file) < purgeLine)
  481. {
  482. File.Delete(file);
  483. }
  484. }
  485. // Recurse into lower tiers
  486. foreach (string subdir in Directory.GetDirectories(dir))
  487. {
  488. CleanExpiredFiles(subdir, purgeLine);
  489. }
  490. // Check if a tier directory is empty, if so, delete it
  491. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  492. if (dirSize == 0)
  493. {
  494. Directory.Delete(dir);
  495. }
  496. else if (dirSize >= m_CacheWarnAt)
  497. {
  498. m_log.WarnFormat(
  499. "[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
  500. dir, dirSize);
  501. }
  502. }
  503. catch (DirectoryNotFoundException)
  504. {
  505. // If we get here, another node on the same box has
  506. // already removed the directory. Continue with next.
  507. }
  508. catch (Exception e)
  509. {
  510. m_log.Warn(
  511. string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
  512. }
  513. }
  514. /// <summary>
  515. /// Determines the filename for an AssetID stored in the file cache
  516. /// </summary>
  517. /// <param name="id"></param>
  518. /// <returns></returns>
  519. private string GetFileName(string id)
  520. {
  521. // Would it be faster to just hash the darn thing?
  522. foreach (char c in m_InvalidChars)
  523. {
  524. id = id.Replace(c, '_');
  525. }
  526. string path = m_CacheDirectory;
  527. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  528. {
  529. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  530. path = Path.Combine(path, pathPart);
  531. }
  532. return Path.Combine(path, id);
  533. }
  534. /// <summary>
  535. /// Writes a file to the file cache, creating any nessesary
  536. /// tier directories along the way
  537. /// </summary>
  538. /// <param name="filename"></param>
  539. /// <param name="asset"></param>
  540. private void WriteFileCache(string filename, AssetBase asset)
  541. {
  542. Stream stream = null;
  543. // Make sure the target cache directory exists
  544. string directory = Path.GetDirectoryName(filename);
  545. // Write file first to a temp name, so that it doesn't look
  546. // like it's already cached while it's still writing.
  547. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  548. try
  549. {
  550. try
  551. {
  552. if (!Directory.Exists(directory))
  553. {
  554. Directory.CreateDirectory(directory);
  555. }
  556. stream = File.Open(tempname, FileMode.Create);
  557. BinaryFormatter bformatter = new BinaryFormatter();
  558. bformatter.Serialize(stream, asset);
  559. }
  560. catch (IOException e)
  561. {
  562. m_log.WarnFormat(
  563. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  564. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  565. return;
  566. }
  567. finally
  568. {
  569. if (stream != null)
  570. stream.Close();
  571. }
  572. try
  573. {
  574. // Now that it's written, rename it so that it can be found.
  575. //
  576. // File.Copy(tempname, filename, true);
  577. // File.Delete(tempname);
  578. //
  579. // For a brief period, this was done as a separate copy and then temporary file delete operation to
  580. // avoid an IOException caused by move if some competing thread had already written the file.
  581. // However, this causes exceptions on Windows when other threads attempt to read a file
  582. // which is still being copied. So instead, go back to moving the file and swallow any IOException.
  583. //
  584. // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
  585. // filesystem.
  586. File.Move(tempname, filename);
  587. if (m_LogLevel >= 2)
  588. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  589. }
  590. catch (IOException)
  591. {
  592. // If we see an IOException here it's likely that some other competing thread has written the
  593. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  594. // signally by the earlier temporary file writing code.
  595. }
  596. }
  597. finally
  598. {
  599. // Even if the write fails with an exception, we need to make sure
  600. // that we release the lock on that file, otherwise it'll never get
  601. // cached
  602. lock (m_CurrentlyWriting)
  603. {
  604. #if WAIT_ON_INPROGRESS_REQUESTS
  605. ManualResetEvent waitEvent;
  606. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  607. {
  608. m_CurrentlyWriting.Remove(filename);
  609. waitEvent.Set();
  610. }
  611. #else
  612. m_CurrentlyWriting.Remove(filename);
  613. #endif
  614. }
  615. }
  616. }
  617. /// <summary>
  618. /// Scan through the file cache, and return number of assets currently cached.
  619. /// </summary>
  620. /// <param name="dir"></param>
  621. /// <returns></returns>
  622. private int GetFileCacheCount(string dir)
  623. {
  624. int count = Directory.GetFiles(dir).Length;
  625. foreach (string subdir in Directory.GetDirectories(dir))
  626. {
  627. count += GetFileCacheCount(subdir);
  628. }
  629. return count;
  630. }
  631. /// <summary>
  632. /// This notes the last time the Region had a deep asset scan performed on it.
  633. /// </summary>
  634. /// <param name="regionID"></param>
  635. private void StampRegionStatusFile(UUID regionID)
  636. {
  637. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
  638. try
  639. {
  640. if (File.Exists(RegionCacheStatusFile))
  641. {
  642. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  643. }
  644. else
  645. {
  646. File.WriteAllText(
  647. RegionCacheStatusFile,
  648. "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  649. }
  650. }
  651. catch (Exception e)
  652. {
  653. m_log.Warn(
  654. string.Format(
  655. "[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
  656. regionID),
  657. e);
  658. }
  659. }
  660. /// <summary>
  661. /// Iterates through all Scenes, doing a deep scan through assets
  662. /// to update the access time of all assets present in the scene or referenced by assets
  663. /// in the scene.
  664. /// </summary>
  665. /// <param name="storeUncached">
  666. /// If true, then assets scanned which are not found in cache are added to the cache.
  667. /// </param>
  668. /// <returns>Number of distinct asset references found in the scene.</returns>
  669. private int TouchAllSceneAssets(bool storeUncached)
  670. {
  671. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  672. Dictionary<UUID, bool> assetsFound = new Dictionary<UUID, bool>();
  673. foreach (Scene s in m_Scenes)
  674. {
  675. StampRegionStatusFile(s.RegionInfo.RegionID);
  676. s.ForEachSOG(delegate(SceneObjectGroup e)
  677. {
  678. gatherer.AddForInspection(e);
  679. gatherer.GatherAll();
  680. foreach (UUID assetID in gatherer.GatheredUuids.Keys)
  681. {
  682. if (!assetsFound.ContainsKey(assetID))
  683. {
  684. string filename = GetFileName(assetID.ToString());
  685. if (File.Exists(filename))
  686. {
  687. UpdateFileLastAccessTime(filename);
  688. }
  689. else if (storeUncached)
  690. {
  691. AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
  692. if (cachedAsset == null && gatherer.GatheredUuids[assetID] != (sbyte)AssetType.Unknown)
  693. assetsFound[assetID] = false;
  694. else
  695. assetsFound[assetID] = true;
  696. }
  697. }
  698. else if (!assetsFound[assetID])
  699. {
  700. m_log.DebugFormat(
  701. "[FLOTSAM ASSET CACHE]: Could not find asset {0}, type {1} referenced by object {2} at {3} in scene {4} when pre-caching all scene assets",
  702. assetID, gatherer.GatheredUuids[assetID], e.Name, e.AbsolutePosition, s.Name);
  703. }
  704. }
  705. gatherer.GatheredUuids.Clear();
  706. });
  707. }
  708. return assetsFound.Count;
  709. }
  710. /// <summary>
  711. /// Deletes all cache contents
  712. /// </summary>
  713. private void ClearFileCache()
  714. {
  715. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  716. {
  717. try
  718. {
  719. Directory.Delete(dir, true);
  720. }
  721. catch (Exception e)
  722. {
  723. m_log.WarnFormat(
  724. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  725. dir, m_CacheDirectory, e.Message, e.StackTrace);
  726. }
  727. }
  728. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  729. {
  730. try
  731. {
  732. File.Delete(file);
  733. }
  734. catch (Exception e)
  735. {
  736. m_log.WarnFormat(
  737. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  738. file, m_CacheDirectory, e.Message, e.StackTrace);
  739. }
  740. }
  741. }
  742. private List<string> GenerateCacheHitReport()
  743. {
  744. List<string> outputLines = new List<string>();
  745. double fileHitRate = (double)m_DiskHits / m_Requests * 100.0;
  746. outputLines.Add(
  747. string.Format("File Hit Rate: {0}% for {1} requests", fileHitRate.ToString("0.00"), m_Requests));
  748. if (m_MemoryCacheEnabled)
  749. {
  750. double memHitRate = (double)m_MemoryHits / m_Requests * 100.0;
  751. outputLines.Add(
  752. string.Format("Memory Hit Rate: {0}% for {1} requests", memHitRate.ToString("0.00"), m_Requests));
  753. }
  754. outputLines.Add(
  755. string.Format(
  756. "Unnecessary requests due to requests for assets that are currently downloading: {0}",
  757. m_RequestsForInprogress));
  758. return outputLines;
  759. }
  760. #region Console Commands
  761. private void HandleConsoleCommand(string module, string[] cmdparams)
  762. {
  763. ICommandConsole con = MainConsole.Instance;
  764. if (cmdparams.Length >= 2)
  765. {
  766. string cmd = cmdparams[1];
  767. switch (cmd)
  768. {
  769. case "status":
  770. if (m_MemoryCacheEnabled)
  771. con.OutputFormat("Memory Cache: {0} assets", m_MemoryCache.Count);
  772. else
  773. con.OutputFormat("Memory cache disabled");
  774. if (m_FileCacheEnabled)
  775. {
  776. int fileCount = GetFileCacheCount(m_CacheDirectory);
  777. con.OutputFormat("File Cache: {0} assets", fileCount);
  778. }
  779. else
  780. {
  781. con.Output("File cache disabled");
  782. }
  783. GenerateCacheHitReport().ForEach(l => con.Output(l));
  784. if (m_FileCacheEnabled)
  785. {
  786. con.Output("Deep scans have previously been performed on the following regions:");
  787. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  788. {
  789. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  790. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  791. con.OutputFormat("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  792. }
  793. }
  794. break;
  795. case "clear":
  796. if (cmdparams.Length < 2)
  797. {
  798. con.Output("Usage is fcache clear [file] [memory]");
  799. break;
  800. }
  801. bool clearMemory = false, clearFile = false;
  802. if (cmdparams.Length == 2)
  803. {
  804. clearMemory = true;
  805. clearFile = true;
  806. }
  807. foreach (string s in cmdparams)
  808. {
  809. if (s.ToLower() == "memory")
  810. clearMemory = true;
  811. else if (s.ToLower() == "file")
  812. clearFile = true;
  813. }
  814. if (clearMemory)
  815. {
  816. if (m_MemoryCacheEnabled)
  817. {
  818. m_MemoryCache.Clear();
  819. con.Output("Memory cache cleared.");
  820. }
  821. else
  822. {
  823. con.Output("Memory cache not enabled.");
  824. }
  825. }
  826. if (clearFile)
  827. {
  828. if (m_FileCacheEnabled)
  829. {
  830. ClearFileCache();
  831. con.Output("File cache cleared.");
  832. }
  833. else
  834. {
  835. con.Output("File cache not enabled.");
  836. }
  837. }
  838. break;
  839. case "assets":
  840. con.Output("Ensuring assets are cached for all scenes.");
  841. WorkManager.RunInThread(delegate
  842. {
  843. int assetReferenceTotal = TouchAllSceneAssets(true);
  844. con.OutputFormat("Completed check with {0} assets.", assetReferenceTotal);
  845. }, null, "TouchAllSceneAssets");
  846. break;
  847. case "expire":
  848. if (cmdparams.Length < 3)
  849. {
  850. con.OutputFormat("Invalid parameters for Expire, please specify a valid date & time", cmd);
  851. break;
  852. }
  853. string s_expirationDate = "";
  854. DateTime expirationDate;
  855. if (cmdparams.Length > 3)
  856. {
  857. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  858. }
  859. else
  860. {
  861. s_expirationDate = cmdparams[2];
  862. }
  863. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  864. {
  865. con.OutputFormat("{0} is not a valid date & time", cmd);
  866. break;
  867. }
  868. if (m_FileCacheEnabled)
  869. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  870. else
  871. con.OutputFormat("File cache not active, not clearing.");
  872. break;
  873. default:
  874. con.OutputFormat("Unknown command {0}", cmd);
  875. break;
  876. }
  877. }
  878. else if (cmdparams.Length == 1)
  879. {
  880. con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
  881. con.Output("fcache expire <datetime> - Purge assets older then the specified date & time");
  882. con.Output("fcache clear [file] [memory] - Remove cached assets");
  883. con.Output("fcache status - Display cache status");
  884. }
  885. }
  886. #endregion
  887. #region IAssetService Members
  888. public AssetMetadata GetMetadata(string id)
  889. {
  890. AssetBase asset = Get(id);
  891. return asset.Metadata;
  892. }
  893. public byte[] GetData(string id)
  894. {
  895. AssetBase asset = Get(id);
  896. return asset.Data;
  897. }
  898. public bool Get(string id, object sender, AssetRetrieved handler)
  899. {
  900. AssetBase asset = Get(id);
  901. handler(id, sender, asset);
  902. return true;
  903. }
  904. public bool[] AssetsExist(string[] ids)
  905. {
  906. bool[] exist = new bool[ids.Length];
  907. for (int i = 0; i < ids.Length; i++)
  908. {
  909. exist[i] = Check(ids[i]);
  910. }
  911. return exist;
  912. }
  913. public string Store(AssetBase asset)
  914. {
  915. if (asset.FullID == UUID.Zero)
  916. {
  917. asset.FullID = UUID.Random();
  918. }
  919. Cache(asset);
  920. return asset.ID;
  921. }
  922. public bool UpdateContent(string id, byte[] data)
  923. {
  924. AssetBase asset = Get(id);
  925. asset.Data = data;
  926. Cache(asset);
  927. return true;
  928. }
  929. public bool Delete(string id)
  930. {
  931. Expire(id);
  932. return true;
  933. }
  934. #endregion
  935. }
  936. }