1
0

FlotsamAssetCache.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. using OpenSim.Services.Interfaces;
  47. //[assembly: Addin("FlotsamAssetCache", "1.1")]
  48. //[assembly: AddinDependency("OpenSim", "0.5")]
  49. namespace OpenSim.Region.CoreModules.Asset
  50. {
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
  52. public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService
  53. {
  54. private static readonly ILog m_log =
  55. LogManager.GetLogger(
  56. MethodBase.GetCurrentMethod().DeclaringType);
  57. private bool m_Enabled;
  58. private const string m_ModuleName = "FlotsamAssetCache";
  59. private const string m_DefaultCacheDirectory = "./assetcache";
  60. private string m_CacheDirectory = m_DefaultCacheDirectory;
  61. private readonly List<char> m_InvalidChars = new List<char>();
  62. private int m_LogLevel = 0;
  63. private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
  64. private static ulong m_Requests;
  65. private static ulong m_RequestsForInprogress;
  66. private static ulong m_DiskHits;
  67. private static ulong m_MemoryHits;
  68. #if WAIT_ON_INPROGRESS_REQUESTS
  69. private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
  70. private int m_WaitOnInprogressTimeout = 3000;
  71. #else
  72. private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
  73. #endif
  74. private bool m_FileCacheEnabled = true;
  75. private ExpiringCache<string, AssetBase> m_MemoryCache;
  76. private bool m_MemoryCacheEnabled = false;
  77. // Expiration is expressed in hours.
  78. private const double m_DefaultMemoryExpiration = 2;
  79. private const double m_DefaultFileExpiration = 48;
  80. private TimeSpan m_MemoryExpiration = TimeSpan.FromHours(m_DefaultMemoryExpiration);
  81. private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
  82. private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(0.166);
  83. private static int m_CacheDirectoryTiers = 1;
  84. private static int m_CacheDirectoryTierLen = 3;
  85. private static int m_CacheWarnAt = 30000;
  86. private System.Timers.Timer m_CacheCleanTimer;
  87. private IAssetService m_AssetService;
  88. private List<Scene> m_Scenes = new List<Scene>();
  89. public FlotsamAssetCache()
  90. {
  91. m_InvalidChars.AddRange(Path.GetInvalidPathChars());
  92. m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
  93. }
  94. public Type ReplaceableInterface
  95. {
  96. get { return null; }
  97. }
  98. public string Name
  99. {
  100. get { return m_ModuleName; }
  101. }
  102. public void Initialise(IConfigSource source)
  103. {
  104. IConfig moduleConfig = source.Configs["Modules"];
  105. if (moduleConfig != null)
  106. {
  107. string name = moduleConfig.GetString("AssetCaching", String.Empty);
  108. if (name == Name)
  109. {
  110. m_MemoryCache = new ExpiringCache<string, AssetBase>();
  111. m_Enabled = true;
  112. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
  113. IConfig assetConfig = source.Configs["AssetCache"];
  114. if (assetConfig == null)
  115. {
  116. m_log.Debug(
  117. "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
  118. }
  119. else
  120. {
  121. m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
  122. m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
  123. m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
  124. m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
  125. #if WAIT_ON_INPROGRESS_REQUESTS
  126. m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
  127. #endif
  128. m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
  129. m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
  130. m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
  131. m_FileExpirationCleanupTimer
  132. = TimeSpan.FromHours(
  133. assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
  134. m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
  135. m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
  136. m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
  137. }
  138. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
  139. if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
  140. {
  141. m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
  142. m_CacheCleanTimer.AutoReset = true;
  143. m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
  144. lock (m_CacheCleanTimer)
  145. m_CacheCleanTimer.Start();
  146. }
  147. if (m_CacheDirectoryTiers < 1)
  148. {
  149. m_CacheDirectoryTiers = 1;
  150. }
  151. else if (m_CacheDirectoryTiers > 3)
  152. {
  153. m_CacheDirectoryTiers = 3;
  154. }
  155. if (m_CacheDirectoryTierLen < 1)
  156. {
  157. m_CacheDirectoryTierLen = 1;
  158. }
  159. else if (m_CacheDirectoryTierLen > 4)
  160. {
  161. m_CacheDirectoryTierLen = 4;
  162. }
  163. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
  164. 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);
  165. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
  166. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
  167. }
  168. }
  169. }
  170. public void PostInitialise()
  171. {
  172. }
  173. public void Close()
  174. {
  175. }
  176. public void AddRegion(Scene scene)
  177. {
  178. if (m_Enabled)
  179. {
  180. scene.RegisterModuleInterface<IImprovedAssetCache>(this);
  181. m_Scenes.Add(scene);
  182. }
  183. }
  184. public void RemoveRegion(Scene scene)
  185. {
  186. if (m_Enabled)
  187. {
  188. scene.UnregisterModuleInterface<IImprovedAssetCache>(this);
  189. m_Scenes.Remove(scene);
  190. }
  191. }
  192. public void RegionLoaded(Scene scene)
  193. {
  194. if (m_Enabled && m_AssetService == null)
  195. m_AssetService = scene.RequestModuleInterface<IAssetService>();
  196. }
  197. ////////////////////////////////////////////////////////////
  198. // IImprovedAssetCache
  199. //
  200. private void UpdateMemoryCache(string key, AssetBase asset)
  201. {
  202. m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
  203. }
  204. private void UpdateFileCache(string key, AssetBase asset)
  205. {
  206. string filename = GetFileName(asset.ID);
  207. try
  208. {
  209. // If the file is already cached just update access time.
  210. if (File.Exists(filename))
  211. {
  212. lock (m_CurrentlyWriting)
  213. {
  214. if (!m_CurrentlyWriting.Contains(filename))
  215. File.SetLastAccessTime(filename, DateTime.Now);
  216. }
  217. }
  218. else
  219. {
  220. // Once we start writing, make sure we flag that we're writing
  221. // that object to the cache so that we don't try to write the
  222. // same file multiple times.
  223. lock (m_CurrentlyWriting)
  224. {
  225. #if WAIT_ON_INPROGRESS_REQUESTS
  226. if (m_CurrentlyWriting.ContainsKey(filename))
  227. {
  228. return;
  229. }
  230. else
  231. {
  232. m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
  233. }
  234. #else
  235. if (m_CurrentlyWriting.Contains(filename))
  236. {
  237. return;
  238. }
  239. else
  240. {
  241. m_CurrentlyWriting.Add(filename);
  242. }
  243. #endif
  244. }
  245. Util.FireAndForget(
  246. delegate { WriteFileCache(filename, asset); });
  247. }
  248. }
  249. catch (Exception e)
  250. {
  251. m_log.WarnFormat(
  252. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  253. asset.ID, e.Message, e.StackTrace);
  254. }
  255. }
  256. public void Cache(AssetBase asset)
  257. {
  258. // TODO: Spawn this off to some seperate thread to do the actual writing
  259. if (asset != null)
  260. {
  261. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  262. if (m_MemoryCacheEnabled)
  263. UpdateMemoryCache(asset.ID, asset);
  264. if (m_FileCacheEnabled)
  265. UpdateFileCache(asset.ID, asset);
  266. }
  267. }
  268. /// <summary>
  269. /// Try to get an asset from the in-memory cache.
  270. /// </summary>
  271. /// <param name="id"></param>
  272. /// <returns></returns>
  273. private AssetBase GetFromMemoryCache(string id)
  274. {
  275. AssetBase asset = null;
  276. if (m_MemoryCache.TryGetValue(id, out asset))
  277. m_MemoryHits++;
  278. return asset;
  279. }
  280. /// <summary>
  281. /// Try to get an asset from the file cache.
  282. /// </summary>
  283. /// <param name="id"></param>
  284. /// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
  285. private AssetBase GetFromFileCache(string id)
  286. {
  287. string filename = GetFileName(id);
  288. #if WAIT_ON_INPROGRESS_REQUESTS
  289. // Check if we're already downloading this asset. If so, try to wait for it to
  290. // download.
  291. if (m_WaitOnInprogressTimeout > 0)
  292. {
  293. m_RequestsForInprogress++;
  294. ManualResetEvent waitEvent;
  295. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  296. {
  297. waitEvent.WaitOne(m_WaitOnInprogressTimeout);
  298. return Get(id);
  299. }
  300. }
  301. #else
  302. // Track how often we have the problem that an asset is requested while
  303. // it is still being downloaded by a previous request.
  304. if (m_CurrentlyWriting.Contains(filename))
  305. {
  306. m_RequestsForInprogress++;
  307. return null;
  308. }
  309. #endif
  310. AssetBase asset = null;
  311. if (File.Exists(filename))
  312. {
  313. FileStream stream = null;
  314. try
  315. {
  316. stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  317. BinaryFormatter bformatter = new BinaryFormatter();
  318. asset = (AssetBase)bformatter.Deserialize(stream);
  319. m_DiskHits++;
  320. }
  321. catch (System.Runtime.Serialization.SerializationException e)
  322. {
  323. m_log.WarnFormat(
  324. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  325. filename, id, e.Message, e.StackTrace);
  326. // If there was a problem deserializing the asset, the asset may
  327. // either be corrupted OR was serialized under an old format
  328. // {different version of AssetBase} -- we should attempt to
  329. // delete it and re-cache
  330. File.Delete(filename);
  331. }
  332. catch (Exception e)
  333. {
  334. m_log.WarnFormat(
  335. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  336. filename, id, e.Message, e.StackTrace);
  337. }
  338. finally
  339. {
  340. if (stream != null)
  341. stream.Close();
  342. }
  343. }
  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_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
  361. GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l));
  362. }
  363. return asset;
  364. }
  365. public AssetBase GetCached(string id)
  366. {
  367. return Get(id);
  368. }
  369. public void Expire(string id)
  370. {
  371. if (m_LogLevel >= 2)
  372. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  373. try
  374. {
  375. if (m_FileCacheEnabled)
  376. {
  377. string filename = GetFileName(id);
  378. if (File.Exists(filename))
  379. {
  380. File.Delete(filename);
  381. }
  382. }
  383. if (m_MemoryCacheEnabled)
  384. m_MemoryCache.Remove(id);
  385. }
  386. catch (Exception e)
  387. {
  388. m_log.WarnFormat(
  389. "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  390. id, e.Message, e.StackTrace);
  391. }
  392. }
  393. public void Clear()
  394. {
  395. if (m_LogLevel >= 2)
  396. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  397. if (m_FileCacheEnabled)
  398. {
  399. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  400. {
  401. Directory.Delete(dir);
  402. }
  403. }
  404. if (m_MemoryCacheEnabled)
  405. m_MemoryCache.Clear();
  406. }
  407. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  408. {
  409. if (m_LogLevel >= 2)
  410. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
  411. // Purge all files last accessed prior to this point
  412. DateTime purgeLine = DateTime.Now - m_FileExpiration;
  413. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  414. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  415. // such local assets if they have not been recently accessed.
  416. TouchAllSceneAssets(false);
  417. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  418. {
  419. CleanExpiredFiles(dir, purgeLine);
  420. }
  421. }
  422. /// <summary>
  423. /// Recurses through specified directory checking for asset files last
  424. /// accessed prior to the specified purge line and deletes them. Also
  425. /// removes empty tier directories.
  426. /// </summary>
  427. /// <param name="dir"></param>
  428. /// <param name="purgeLine"></param>
  429. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  430. {
  431. try
  432. {
  433. foreach (string file in Directory.GetFiles(dir))
  434. {
  435. if (File.GetLastAccessTime(file) < purgeLine)
  436. {
  437. File.Delete(file);
  438. }
  439. }
  440. // Recurse into lower tiers
  441. foreach (string subdir in Directory.GetDirectories(dir))
  442. {
  443. CleanExpiredFiles(subdir, purgeLine);
  444. }
  445. // Check if a tier directory is empty, if so, delete it
  446. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  447. if (dirSize == 0)
  448. {
  449. Directory.Delete(dir);
  450. }
  451. else if (dirSize >= m_CacheWarnAt)
  452. {
  453. m_log.WarnFormat(
  454. "[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
  455. dir, dirSize);
  456. }
  457. }
  458. catch (Exception e)
  459. {
  460. m_log.Warn(
  461. string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
  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.WarnFormat(
  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. try
  589. {
  590. if (File.Exists(RegionCacheStatusFile))
  591. {
  592. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  593. }
  594. else
  595. {
  596. File.WriteAllText(
  597. RegionCacheStatusFile,
  598. "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  599. }
  600. }
  601. catch (Exception e)
  602. {
  603. m_log.Warn(
  604. string.Format(
  605. "[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
  606. regionID),
  607. e);
  608. }
  609. }
  610. /// <summary>
  611. /// Iterates through all Scenes, doing a deep scan through assets
  612. /// to update the access time of all assets present in the scene or referenced by assets
  613. /// in the scene.
  614. /// </summary>
  615. /// <param name="storeUncached">
  616. /// If true, then assets scanned which are not found in cache are added to the cache.
  617. /// </param>
  618. /// <returns>Number of distinct asset references found in the scene.</returns>
  619. private int TouchAllSceneAssets(bool storeUncached)
  620. {
  621. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  622. HashSet<UUID> uniqueUuids = new HashSet<UUID>();
  623. Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
  624. foreach (Scene s in m_Scenes)
  625. {
  626. StampRegionStatusFile(s.RegionInfo.RegionID);
  627. s.ForEachSOG(delegate(SceneObjectGroup e)
  628. {
  629. gatherer.GatherAssetUuids(e, assets);
  630. foreach (UUID assetID in assets.Keys)
  631. {
  632. uniqueUuids.Add(assetID);
  633. string filename = GetFileName(assetID.ToString());
  634. if (File.Exists(filename))
  635. {
  636. File.SetLastAccessTime(filename, DateTime.Now);
  637. }
  638. else if (storeUncached)
  639. {
  640. AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
  641. if (cachedAsset == null && assets[assetID] != AssetType.Unknown)
  642. m_log.DebugFormat(
  643. "[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",
  644. assetID, assets[assetID], e.Name, e.AbsolutePosition, s.Name);
  645. }
  646. }
  647. assets.Clear();
  648. });
  649. }
  650. return uniqueUuids.Count;
  651. }
  652. /// <summary>
  653. /// Deletes all cache contents
  654. /// </summary>
  655. private void ClearFileCache()
  656. {
  657. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  658. {
  659. try
  660. {
  661. Directory.Delete(dir, true);
  662. }
  663. catch (Exception e)
  664. {
  665. m_log.WarnFormat(
  666. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  667. dir, m_CacheDirectory, e.Message, e.StackTrace);
  668. }
  669. }
  670. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  671. {
  672. try
  673. {
  674. File.Delete(file);
  675. }
  676. catch (Exception e)
  677. {
  678. m_log.WarnFormat(
  679. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  680. file, m_CacheDirectory, e.Message, e.StackTrace);
  681. }
  682. }
  683. }
  684. private List<string> GenerateCacheHitReport()
  685. {
  686. List<string> outputLines = new List<string>();
  687. double fileHitRate = (double)m_DiskHits / m_Requests * 100.0;
  688. outputLines.Add(
  689. string.Format("File Hit Rate: {0}% for {1} requests", fileHitRate.ToString("0.00"), m_Requests));
  690. if (m_MemoryCacheEnabled)
  691. {
  692. double memHitRate = (double)m_MemoryHits / m_Requests * 100.0;
  693. outputLines.Add(
  694. string.Format("Memory Hit Rate: {0}% for {1} requests", memHitRate.ToString("0.00"), m_Requests));
  695. }
  696. outputLines.Add(
  697. string.Format(
  698. "Unnecessary requests due to requests for assets that are currently downloading: {0}",
  699. m_RequestsForInprogress));
  700. return outputLines;
  701. }
  702. #region Console Commands
  703. private void HandleConsoleCommand(string module, string[] cmdparams)
  704. {
  705. ICommandConsole con = MainConsole.Instance;
  706. if (cmdparams.Length >= 2)
  707. {
  708. string cmd = cmdparams[1];
  709. switch (cmd)
  710. {
  711. case "status":
  712. if (m_MemoryCacheEnabled)
  713. con.OutputFormat("Memory Cache: {0} assets", m_MemoryCache.Count);
  714. else
  715. con.OutputFormat("Memory cache disabled");
  716. if (m_FileCacheEnabled)
  717. {
  718. int fileCount = GetFileCacheCount(m_CacheDirectory);
  719. con.OutputFormat("File Cache: {0} assets", fileCount);
  720. }
  721. else
  722. {
  723. con.Output("File cache disabled");
  724. }
  725. GenerateCacheHitReport().ForEach(l => con.Output(l));
  726. if (m_FileCacheEnabled)
  727. {
  728. con.Output("Deep scans have previously been performed on the following regions:");
  729. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  730. {
  731. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  732. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  733. con.OutputFormat("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  734. }
  735. }
  736. break;
  737. case "clear":
  738. if (cmdparams.Length < 2)
  739. {
  740. con.Output("Usage is fcache clear [file] [memory]");
  741. break;
  742. }
  743. bool clearMemory = false, clearFile = false;
  744. if (cmdparams.Length == 2)
  745. {
  746. clearMemory = true;
  747. clearFile = true;
  748. }
  749. foreach (string s in cmdparams)
  750. {
  751. if (s.ToLower() == "memory")
  752. clearMemory = true;
  753. else if (s.ToLower() == "file")
  754. clearFile = true;
  755. }
  756. if (clearMemory)
  757. {
  758. if (m_MemoryCacheEnabled)
  759. {
  760. m_MemoryCache.Clear();
  761. con.Output("Memory cache cleared.");
  762. }
  763. else
  764. {
  765. con.Output("Memory cache not enabled.");
  766. }
  767. }
  768. if (clearFile)
  769. {
  770. if (m_FileCacheEnabled)
  771. {
  772. ClearFileCache();
  773. con.Output("File cache cleared.");
  774. }
  775. else
  776. {
  777. con.Output("File cache not enabled.");
  778. }
  779. }
  780. break;
  781. case "assets":
  782. con.Output("Ensuring assets are cached for all scenes.");
  783. Util.FireAndForget(delegate {
  784. int assetReferenceTotal = TouchAllSceneAssets(true);
  785. con.OutputFormat("Completed check with {0} assets.", assetReferenceTotal);
  786. });
  787. break;
  788. case "expire":
  789. if (cmdparams.Length < 3)
  790. {
  791. con.OutputFormat("Invalid parameters for Expire, please specify a valid date & time", cmd);
  792. break;
  793. }
  794. string s_expirationDate = "";
  795. DateTime expirationDate;
  796. if (cmdparams.Length > 3)
  797. {
  798. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  799. }
  800. else
  801. {
  802. s_expirationDate = cmdparams[2];
  803. }
  804. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  805. {
  806. con.OutputFormat("{0} is not a valid date & time", cmd);
  807. break;
  808. }
  809. if (m_FileCacheEnabled)
  810. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  811. else
  812. con.OutputFormat("File cache not active, not clearing.");
  813. break;
  814. default:
  815. con.OutputFormat("Unknown command {0}", cmd);
  816. break;
  817. }
  818. }
  819. else if (cmdparams.Length == 1)
  820. {
  821. con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
  822. con.Output("fcache expire <datetime> - Purge assets older then the specified date & time");
  823. con.Output("fcache clear [file] [memory] - Remove cached assets");
  824. con.Output("fcache status - Display cache status");
  825. }
  826. }
  827. #endregion
  828. #region IAssetService Members
  829. public AssetMetadata GetMetadata(string id)
  830. {
  831. AssetBase asset = Get(id);
  832. return asset.Metadata;
  833. }
  834. public byte[] GetData(string id)
  835. {
  836. AssetBase asset = Get(id);
  837. return asset.Data;
  838. }
  839. public bool Get(string id, object sender, AssetRetrieved handler)
  840. {
  841. AssetBase asset = Get(id);
  842. handler(id, sender, asset);
  843. return true;
  844. }
  845. public string Store(AssetBase asset)
  846. {
  847. if (asset.FullID == UUID.Zero)
  848. {
  849. asset.FullID = UUID.Random();
  850. }
  851. Cache(asset);
  852. return asset.ID;
  853. }
  854. public bool UpdateContent(string id, byte[] data)
  855. {
  856. AssetBase asset = Get(id);
  857. asset.Data = data;
  858. Cache(asset);
  859. return true;
  860. }
  861. public bool Delete(string id)
  862. {
  863. Expire(id);
  864. return true;
  865. }
  866. #endregion
  867. }
  868. }