FlotsamAssetCache.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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 (Exception e)
  504. {
  505. m_log.Warn(
  506. string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
  507. }
  508. }
  509. /// <summary>
  510. /// Determines the filename for an AssetID stored in the file cache
  511. /// </summary>
  512. /// <param name="id"></param>
  513. /// <returns></returns>
  514. private string GetFileName(string id)
  515. {
  516. // Would it be faster to just hash the darn thing?
  517. foreach (char c in m_InvalidChars)
  518. {
  519. id = id.Replace(c, '_');
  520. }
  521. string path = m_CacheDirectory;
  522. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  523. {
  524. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  525. path = Path.Combine(path, pathPart);
  526. }
  527. return Path.Combine(path, id);
  528. }
  529. /// <summary>
  530. /// Writes a file to the file cache, creating any nessesary
  531. /// tier directories along the way
  532. /// </summary>
  533. /// <param name="filename"></param>
  534. /// <param name="asset"></param>
  535. private void WriteFileCache(string filename, AssetBase asset)
  536. {
  537. Stream stream = null;
  538. // Make sure the target cache directory exists
  539. string directory = Path.GetDirectoryName(filename);
  540. // Write file first to a temp name, so that it doesn't look
  541. // like it's already cached while it's still writing.
  542. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  543. try
  544. {
  545. try
  546. {
  547. if (!Directory.Exists(directory))
  548. {
  549. Directory.CreateDirectory(directory);
  550. }
  551. stream = File.Open(tempname, FileMode.Create);
  552. BinaryFormatter bformatter = new BinaryFormatter();
  553. bformatter.Serialize(stream, asset);
  554. }
  555. catch (IOException e)
  556. {
  557. m_log.WarnFormat(
  558. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  559. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  560. return;
  561. }
  562. finally
  563. {
  564. if (stream != null)
  565. stream.Close();
  566. }
  567. try
  568. {
  569. // Now that it's written, rename it so that it can be found.
  570. //
  571. // File.Copy(tempname, filename, true);
  572. // File.Delete(tempname);
  573. //
  574. // For a brief period, this was done as a separate copy and then temporary file delete operation to
  575. // avoid an IOException caused by move if some competing thread had already written the file.
  576. // However, this causes exceptions on Windows when other threads attempt to read a file
  577. // which is still being copied. So instead, go back to moving the file and swallow any IOException.
  578. //
  579. // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
  580. // filesystem.
  581. File.Move(tempname, filename);
  582. if (m_LogLevel >= 2)
  583. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  584. }
  585. catch (IOException)
  586. {
  587. // If we see an IOException here it's likely that some other competing thread has written the
  588. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  589. // signally by the earlier temporary file writing code.
  590. }
  591. }
  592. finally
  593. {
  594. // Even if the write fails with an exception, we need to make sure
  595. // that we release the lock on that file, otherwise it'll never get
  596. // cached
  597. lock (m_CurrentlyWriting)
  598. {
  599. #if WAIT_ON_INPROGRESS_REQUESTS
  600. ManualResetEvent waitEvent;
  601. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  602. {
  603. m_CurrentlyWriting.Remove(filename);
  604. waitEvent.Set();
  605. }
  606. #else
  607. m_CurrentlyWriting.Remove(filename);
  608. #endif
  609. }
  610. }
  611. }
  612. /// <summary>
  613. /// Scan through the file cache, and return number of assets currently cached.
  614. /// </summary>
  615. /// <param name="dir"></param>
  616. /// <returns></returns>
  617. private int GetFileCacheCount(string dir)
  618. {
  619. int count = Directory.GetFiles(dir).Length;
  620. foreach (string subdir in Directory.GetDirectories(dir))
  621. {
  622. count += GetFileCacheCount(subdir);
  623. }
  624. return count;
  625. }
  626. /// <summary>
  627. /// This notes the last time the Region had a deep asset scan performed on it.
  628. /// </summary>
  629. /// <param name="regionID"></param>
  630. private void StampRegionStatusFile(UUID regionID)
  631. {
  632. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
  633. try
  634. {
  635. if (File.Exists(RegionCacheStatusFile))
  636. {
  637. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  638. }
  639. else
  640. {
  641. File.WriteAllText(
  642. RegionCacheStatusFile,
  643. "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  644. }
  645. }
  646. catch (Exception e)
  647. {
  648. m_log.Warn(
  649. string.Format(
  650. "[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
  651. regionID),
  652. e);
  653. }
  654. }
  655. /// <summary>
  656. /// Iterates through all Scenes, doing a deep scan through assets
  657. /// to update the access time of all assets present in the scene or referenced by assets
  658. /// in the scene.
  659. /// </summary>
  660. /// <param name="storeUncached">
  661. /// If true, then assets scanned which are not found in cache are added to the cache.
  662. /// </param>
  663. /// <returns>Number of distinct asset references found in the scene.</returns>
  664. private int TouchAllSceneAssets(bool storeUncached)
  665. {
  666. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  667. Dictionary<UUID, bool> assetsFound = new Dictionary<UUID, bool>();
  668. foreach (Scene s in m_Scenes)
  669. {
  670. StampRegionStatusFile(s.RegionInfo.RegionID);
  671. s.ForEachSOG(delegate(SceneObjectGroup e)
  672. {
  673. gatherer.AddForInspection(e);
  674. gatherer.GatherAll();
  675. foreach (UUID assetID in gatherer.GatheredUuids.Keys)
  676. {
  677. if (!assetsFound.ContainsKey(assetID))
  678. {
  679. string filename = GetFileName(assetID.ToString());
  680. if (File.Exists(filename))
  681. {
  682. UpdateFileLastAccessTime(filename);
  683. }
  684. else if (storeUncached)
  685. {
  686. AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
  687. if (cachedAsset == null && gatherer.GatheredUuids[assetID] != (sbyte)AssetType.Unknown)
  688. assetsFound[assetID] = false;
  689. else
  690. assetsFound[assetID] = true;
  691. }
  692. }
  693. else if (!assetsFound[assetID])
  694. {
  695. m_log.DebugFormat(
  696. "[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",
  697. assetID, gatherer.GatheredUuids[assetID], e.Name, e.AbsolutePosition, s.Name);
  698. }
  699. }
  700. gatherer.GatheredUuids.Clear();
  701. });
  702. }
  703. return assetsFound.Count;
  704. }
  705. /// <summary>
  706. /// Deletes all cache contents
  707. /// </summary>
  708. private void ClearFileCache()
  709. {
  710. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  711. {
  712. try
  713. {
  714. Directory.Delete(dir, true);
  715. }
  716. catch (Exception e)
  717. {
  718. m_log.WarnFormat(
  719. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  720. dir, m_CacheDirectory, e.Message, e.StackTrace);
  721. }
  722. }
  723. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  724. {
  725. try
  726. {
  727. File.Delete(file);
  728. }
  729. catch (Exception e)
  730. {
  731. m_log.WarnFormat(
  732. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  733. file, m_CacheDirectory, e.Message, e.StackTrace);
  734. }
  735. }
  736. }
  737. private List<string> GenerateCacheHitReport()
  738. {
  739. List<string> outputLines = new List<string>();
  740. double fileHitRate = (double)m_DiskHits / m_Requests * 100.0;
  741. outputLines.Add(
  742. string.Format("File Hit Rate: {0}% for {1} requests", fileHitRate.ToString("0.00"), m_Requests));
  743. if (m_MemoryCacheEnabled)
  744. {
  745. double memHitRate = (double)m_MemoryHits / m_Requests * 100.0;
  746. outputLines.Add(
  747. string.Format("Memory Hit Rate: {0}% for {1} requests", memHitRate.ToString("0.00"), m_Requests));
  748. }
  749. outputLines.Add(
  750. string.Format(
  751. "Unnecessary requests due to requests for assets that are currently downloading: {0}",
  752. m_RequestsForInprogress));
  753. return outputLines;
  754. }
  755. #region Console Commands
  756. private void HandleConsoleCommand(string module, string[] cmdparams)
  757. {
  758. ICommandConsole con = MainConsole.Instance;
  759. if (cmdparams.Length >= 2)
  760. {
  761. string cmd = cmdparams[1];
  762. switch (cmd)
  763. {
  764. case "status":
  765. if (m_MemoryCacheEnabled)
  766. con.OutputFormat("Memory Cache: {0} assets", m_MemoryCache.Count);
  767. else
  768. con.OutputFormat("Memory cache disabled");
  769. if (m_FileCacheEnabled)
  770. {
  771. int fileCount = GetFileCacheCount(m_CacheDirectory);
  772. con.OutputFormat("File Cache: {0} assets", fileCount);
  773. }
  774. else
  775. {
  776. con.Output("File cache disabled");
  777. }
  778. GenerateCacheHitReport().ForEach(l => con.Output(l));
  779. if (m_FileCacheEnabled)
  780. {
  781. con.Output("Deep scans have previously been performed on the following regions:");
  782. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  783. {
  784. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  785. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  786. con.OutputFormat("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  787. }
  788. }
  789. break;
  790. case "clear":
  791. if (cmdparams.Length < 2)
  792. {
  793. con.Output("Usage is fcache clear [file] [memory]");
  794. break;
  795. }
  796. bool clearMemory = false, clearFile = false;
  797. if (cmdparams.Length == 2)
  798. {
  799. clearMemory = true;
  800. clearFile = true;
  801. }
  802. foreach (string s in cmdparams)
  803. {
  804. if (s.ToLower() == "memory")
  805. clearMemory = true;
  806. else if (s.ToLower() == "file")
  807. clearFile = true;
  808. }
  809. if (clearMemory)
  810. {
  811. if (m_MemoryCacheEnabled)
  812. {
  813. m_MemoryCache.Clear();
  814. con.Output("Memory cache cleared.");
  815. }
  816. else
  817. {
  818. con.Output("Memory cache not enabled.");
  819. }
  820. }
  821. if (clearFile)
  822. {
  823. if (m_FileCacheEnabled)
  824. {
  825. ClearFileCache();
  826. con.Output("File cache cleared.");
  827. }
  828. else
  829. {
  830. con.Output("File cache not enabled.");
  831. }
  832. }
  833. break;
  834. case "assets":
  835. con.Output("Ensuring assets are cached for all scenes.");
  836. WorkManager.RunInThread(delegate
  837. {
  838. int assetReferenceTotal = TouchAllSceneAssets(true);
  839. con.OutputFormat("Completed check with {0} assets.", assetReferenceTotal);
  840. }, null, "TouchAllSceneAssets");
  841. break;
  842. case "expire":
  843. if (cmdparams.Length < 3)
  844. {
  845. con.OutputFormat("Invalid parameters for Expire, please specify a valid date & time", cmd);
  846. break;
  847. }
  848. string s_expirationDate = "";
  849. DateTime expirationDate;
  850. if (cmdparams.Length > 3)
  851. {
  852. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  853. }
  854. else
  855. {
  856. s_expirationDate = cmdparams[2];
  857. }
  858. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  859. {
  860. con.OutputFormat("{0} is not a valid date & time", cmd);
  861. break;
  862. }
  863. if (m_FileCacheEnabled)
  864. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  865. else
  866. con.OutputFormat("File cache not active, not clearing.");
  867. break;
  868. default:
  869. con.OutputFormat("Unknown command {0}", cmd);
  870. break;
  871. }
  872. }
  873. else if (cmdparams.Length == 1)
  874. {
  875. con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
  876. con.Output("fcache expire <datetime> - Purge assets older then the specified date & time");
  877. con.Output("fcache clear [file] [memory] - Remove cached assets");
  878. con.Output("fcache status - Display cache status");
  879. }
  880. }
  881. #endregion
  882. #region IAssetService Members
  883. public AssetMetadata GetMetadata(string id)
  884. {
  885. AssetBase asset = Get(id);
  886. return asset.Metadata;
  887. }
  888. public byte[] GetData(string id)
  889. {
  890. AssetBase asset = Get(id);
  891. return asset.Data;
  892. }
  893. public bool Get(string id, object sender, AssetRetrieved handler)
  894. {
  895. AssetBase asset = Get(id);
  896. handler(id, sender, asset);
  897. return true;
  898. }
  899. public bool[] AssetsExist(string[] ids)
  900. {
  901. bool[] exist = new bool[ids.Length];
  902. for (int i = 0; i < ids.Length; i++)
  903. {
  904. exist[i] = Check(ids[i]);
  905. }
  906. return exist;
  907. }
  908. public string Store(AssetBase asset)
  909. {
  910. if (asset.FullID == UUID.Zero)
  911. {
  912. asset.FullID = UUID.Random();
  913. }
  914. Cache(asset);
  915. return asset.ID;
  916. }
  917. public bool UpdateContent(string id, byte[] data)
  918. {
  919. AssetBase asset = Get(id);
  920. asset.Data = data;
  921. Cache(asset);
  922. return true;
  923. }
  924. public bool Delete(string id)
  925. {
  926. Expire(id);
  927. return true;
  928. }
  929. #endregion
  930. }
  931. }