FlotsamAssetCache.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. // Uncomment to make asset Get requests for existing
  28. // #define WAIT_ON_INPROGRESS_REQUESTS
  29. using System;
  30. using System.IO;
  31. using System.Collections.Generic;
  32. using System.Reflection;
  33. using System.Runtime.Serialization;
  34. using System.Runtime.Serialization.Formatters.Binary;
  35. using System.Threading;
  36. using System.Timers;
  37. using log4net;
  38. using Nini.Config;
  39. using Mono.Addins;
  40. using OpenMetaverse;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Console;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Services.Interfaces;
  46. //[assembly: Addin("FlotsamAssetCache", "1.1")]
  47. //[assembly: AddinDependency("OpenSim", "0.5")]
  48. namespace OpenSim.Region.CoreModules.Asset
  49. {
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
  51. public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService
  52. {
  53. private static readonly ILog m_log =
  54. LogManager.GetLogger(
  55. MethodBase.GetCurrentMethod().DeclaringType);
  56. private bool m_Enabled;
  57. private const string m_ModuleName = "FlotsamAssetCache";
  58. private const string m_DefaultCacheDirectory = "./assetcache";
  59. private string m_CacheDirectory = m_DefaultCacheDirectory;
  60. private readonly List<char> m_InvalidChars = new List<char>();
  61. private int m_LogLevel = 0;
  62. private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
  63. private static ulong m_Requests;
  64. private static ulong m_RequestsForInprogress;
  65. private static ulong m_DiskHits;
  66. private static ulong m_MemoryHits;
  67. private static double m_HitRateMemory;
  68. private static double m_HitRateFile;
  69. #if WAIT_ON_INPROGRESS_REQUESTS
  70. private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
  71. private int m_WaitOnInprogressTimeout = 3000;
  72. #else
  73. private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
  74. #endif
  75. private bool m_FileCacheEnabled = true;
  76. private ExpiringCache<string, AssetBase> m_MemoryCache;
  77. private bool m_MemoryCacheEnabled = false;
  78. // Expiration is expressed in hours.
  79. private const double m_DefaultMemoryExpiration = 2;
  80. private const double m_DefaultFileExpiration = 48;
  81. private TimeSpan m_MemoryExpiration = TimeSpan.FromHours(m_DefaultMemoryExpiration);
  82. private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
  83. private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(0.166);
  84. private static int m_CacheDirectoryTiers = 1;
  85. private static int m_CacheDirectoryTierLen = 3;
  86. private static int m_CacheWarnAt = 30000;
  87. private System.Timers.Timer m_CacheCleanTimer;
  88. private IAssetService m_AssetService;
  89. private List<Scene> m_Scenes = new List<Scene>();
  90. public FlotsamAssetCache()
  91. {
  92. m_InvalidChars.AddRange(Path.GetInvalidPathChars());
  93. m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
  94. }
  95. public Type ReplaceableInterface
  96. {
  97. get { return null; }
  98. }
  99. public string Name
  100. {
  101. get { return m_ModuleName; }
  102. }
  103. public void Initialise(IConfigSource source)
  104. {
  105. IConfig moduleConfig = source.Configs["Modules"];
  106. if (moduleConfig != null)
  107. {
  108. string name = moduleConfig.GetString("AssetCaching", String.Empty);
  109. if (name == Name)
  110. {
  111. m_MemoryCache = new ExpiringCache<string, AssetBase>();
  112. m_Enabled = true;
  113. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
  114. IConfig assetConfig = source.Configs["AssetCache"];
  115. if (assetConfig == null)
  116. {
  117. m_log.Debug(
  118. "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
  119. }
  120. else
  121. {
  122. m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
  123. m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
  124. m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
  125. m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
  126. #if WAIT_ON_INPROGRESS_REQUESTS
  127. m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
  128. #endif
  129. m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
  130. m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
  131. m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
  132. m_FileExpirationCleanupTimer
  133. = TimeSpan.FromHours(
  134. assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
  135. m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
  136. m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
  137. m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
  138. }
  139. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
  140. if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
  141. {
  142. m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
  143. m_CacheCleanTimer.AutoReset = true;
  144. m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
  145. lock (m_CacheCleanTimer)
  146. m_CacheCleanTimer.Start();
  147. }
  148. if (m_CacheDirectoryTiers < 1)
  149. {
  150. m_CacheDirectoryTiers = 1;
  151. }
  152. else if (m_CacheDirectoryTiers > 3)
  153. {
  154. m_CacheDirectoryTiers = 3;
  155. }
  156. if (m_CacheDirectoryTierLen < 1)
  157. {
  158. m_CacheDirectoryTierLen = 1;
  159. }
  160. else if (m_CacheDirectoryTierLen > 4)
  161. {
  162. m_CacheDirectoryTierLen = 4;
  163. }
  164. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
  165. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the cache. If file or memory is specified then only this cache is cleared.", HandleConsoleCommand);
  166. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
  167. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
  168. }
  169. }
  170. }
  171. public void PostInitialise()
  172. {
  173. }
  174. public void Close()
  175. {
  176. }
  177. public void AddRegion(Scene scene)
  178. {
  179. if (m_Enabled)
  180. {
  181. scene.RegisterModuleInterface<IImprovedAssetCache>(this);
  182. m_Scenes.Add(scene);
  183. }
  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(asset.ID);
  208. try
  209. {
  210. // If the file is already cached just update access time.
  211. if (File.Exists(filename))
  212. {
  213. lock (m_CurrentlyWriting)
  214. {
  215. if (!m_CurrentlyWriting.Contains(filename))
  216. File.SetLastAccessTime(filename, DateTime.Now);
  217. }
  218. }
  219. else
  220. {
  221. // Once we start writing, make sure we flag that we're writing
  222. // that object to the cache so that we don't try to write the
  223. // same file multiple times.
  224. lock (m_CurrentlyWriting)
  225. {
  226. #if WAIT_ON_INPROGRESS_REQUESTS
  227. if (m_CurrentlyWriting.ContainsKey(filename))
  228. {
  229. return;
  230. }
  231. else
  232. {
  233. m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
  234. }
  235. #else
  236. if (m_CurrentlyWriting.Contains(filename))
  237. {
  238. return;
  239. }
  240. else
  241. {
  242. m_CurrentlyWriting.Add(filename);
  243. }
  244. #endif
  245. }
  246. Util.FireAndForget(
  247. delegate { WriteFileCache(filename, asset); });
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. m_log.WarnFormat(
  253. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  254. asset.ID, e.Message, e.StackTrace);
  255. }
  256. }
  257. public void Cache(AssetBase asset)
  258. {
  259. // TODO: Spawn this off to some seperate thread to do the actual writing
  260. if (asset != null)
  261. {
  262. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  263. if (m_MemoryCacheEnabled)
  264. UpdateMemoryCache(asset.ID, asset);
  265. if (m_FileCacheEnabled)
  266. UpdateFileCache(asset.ID, asset);
  267. }
  268. }
  269. /// <summary>
  270. /// Try to get an asset from the in-memory cache.
  271. /// </summary>
  272. /// <param name="id"></param>
  273. /// <returns></returns>
  274. private AssetBase GetFromMemoryCache(string id)
  275. {
  276. AssetBase asset = null;
  277. if (m_MemoryCache.TryGetValue(id, out asset))
  278. m_MemoryHits++;
  279. return asset;
  280. }
  281. /// <summary>
  282. /// Try to get an asset from the file cache.
  283. /// </summary>
  284. /// <param name="id"></param>
  285. /// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
  286. private AssetBase GetFromFileCache(string id)
  287. {
  288. string filename = GetFileName(id);
  289. #if WAIT_ON_INPROGRESS_REQUESTS
  290. // Check if we're already downloading this asset. If so, try to wait for it to
  291. // download.
  292. if (m_WaitOnInprogressTimeout > 0)
  293. {
  294. m_RequestsForInprogress++;
  295. ManualResetEvent waitEvent;
  296. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  297. {
  298. waitEvent.WaitOne(m_WaitOnInprogressTimeout);
  299. return Get(id);
  300. }
  301. }
  302. #else
  303. // Track how often we have the problem that an asset is requested while
  304. // it is still being downloaded by a previous request.
  305. if (m_CurrentlyWriting.Contains(filename))
  306. {
  307. m_RequestsForInprogress++;
  308. return null;
  309. }
  310. #endif
  311. AssetBase asset = null;
  312. if (File.Exists(filename))
  313. {
  314. FileStream stream = null;
  315. try
  316. {
  317. stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
  318. BinaryFormatter bformatter = new BinaryFormatter();
  319. asset = (AssetBase)bformatter.Deserialize(stream);
  320. m_DiskHits++;
  321. }
  322. catch (System.Runtime.Serialization.SerializationException e)
  323. {
  324. m_log.WarnFormat(
  325. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  326. filename, id, e.Message, e.StackTrace);
  327. // If there was a problem deserializing the asset, the asset may
  328. // either be corrupted OR was serialized under an old format
  329. // {different version of AssetBase} -- we should attempt to
  330. // delete it and re-cache
  331. File.Delete(filename);
  332. }
  333. catch (Exception e)
  334. {
  335. m_log.WarnFormat(
  336. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  337. filename, id, e.Message, e.StackTrace);
  338. }
  339. finally
  340. {
  341. if (stream != null)
  342. stream.Close();
  343. }
  344. }
  345. return asset;
  346. }
  347. public AssetBase Get(string id)
  348. {
  349. m_Requests++;
  350. AssetBase asset = null;
  351. if (m_MemoryCacheEnabled)
  352. asset = GetFromMemoryCache(id);
  353. if (asset == null && m_FileCacheEnabled)
  354. {
  355. asset = GetFromFileCache(id);
  356. if (m_MemoryCacheEnabled && asset != null)
  357. UpdateMemoryCache(id, asset);
  358. }
  359. if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
  360. {
  361. m_HitRateFile = (double)m_DiskHits / m_Requests * 100.0;
  362. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
  363. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Hit Rate {0}% for {1} requests", m_HitRateFile.ToString("0.00"), m_Requests);
  364. if (m_MemoryCacheEnabled)
  365. {
  366. m_HitRateMemory = (double)m_MemoryHits / m_Requests * 100.0;
  367. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Hit Rate {0}% for {1} requests", m_HitRateMemory.ToString("0.00"), m_Requests);
  368. }
  369. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} unnessesary requests due to requests for assets that are currently downloading.", m_RequestsForInprogress);
  370. }
  371. return asset;
  372. }
  373. public AssetBase GetCached(string id)
  374. {
  375. return Get(id);
  376. }
  377. public void Expire(string id)
  378. {
  379. if (m_LogLevel >= 2)
  380. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  381. try
  382. {
  383. if (m_FileCacheEnabled)
  384. {
  385. string filename = GetFileName(id);
  386. if (File.Exists(filename))
  387. {
  388. File.Delete(filename);
  389. }
  390. }
  391. if (m_MemoryCacheEnabled)
  392. m_MemoryCache.Remove(id);
  393. }
  394. catch (Exception e)
  395. {
  396. m_log.WarnFormat(
  397. "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  398. id, e.Message, e.StackTrace);
  399. }
  400. }
  401. public void Clear()
  402. {
  403. if (m_LogLevel >= 2)
  404. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  405. if (m_FileCacheEnabled)
  406. {
  407. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  408. {
  409. Directory.Delete(dir);
  410. }
  411. }
  412. if (m_MemoryCacheEnabled)
  413. m_MemoryCache.Clear();
  414. }
  415. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  416. {
  417. if (m_LogLevel >= 2)
  418. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
  419. // Purge all files last accessed prior to this point
  420. DateTime purgeLine = DateTime.Now - m_FileExpiration;
  421. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  422. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  423. // such local assets if they have not been recently accessed.
  424. TouchAllSceneAssets(false);
  425. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  426. {
  427. CleanExpiredFiles(dir, purgeLine);
  428. }
  429. }
  430. /// <summary>
  431. /// Recurses through specified directory checking for asset files last
  432. /// accessed prior to the specified purge line and deletes them. Also
  433. /// removes empty tier directories.
  434. /// </summary>
  435. /// <param name="dir"></param>
  436. /// <param name="purgeLine"></param>
  437. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  438. {
  439. try
  440. {
  441. foreach (string file in Directory.GetFiles(dir))
  442. {
  443. if (File.GetLastAccessTime(file) < purgeLine)
  444. {
  445. File.Delete(file);
  446. }
  447. }
  448. // Recurse into lower tiers
  449. foreach (string subdir in Directory.GetDirectories(dir))
  450. {
  451. CleanExpiredFiles(subdir, purgeLine);
  452. }
  453. // Check if a tier directory is empty, if so, delete it
  454. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  455. if (dirSize == 0)
  456. {
  457. Directory.Delete(dir);
  458. }
  459. else if (dirSize >= m_CacheWarnAt)
  460. {
  461. m_log.WarnFormat(
  462. "[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
  463. dir, dirSize);
  464. }
  465. }
  466. catch (Exception e)
  467. {
  468. m_log.Warn(
  469. string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
  470. }
  471. }
  472. /// <summary>
  473. /// Determines the filename for an AssetID stored in the file cache
  474. /// </summary>
  475. /// <param name="id"></param>
  476. /// <returns></returns>
  477. private string GetFileName(string id)
  478. {
  479. // Would it be faster to just hash the darn thing?
  480. foreach (char c in m_InvalidChars)
  481. {
  482. id = id.Replace(c, '_');
  483. }
  484. string path = m_CacheDirectory;
  485. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  486. {
  487. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  488. path = Path.Combine(path, pathPart);
  489. }
  490. return Path.Combine(path, id);
  491. }
  492. /// <summary>
  493. /// Writes a file to the file cache, creating any nessesary
  494. /// tier directories along the way
  495. /// </summary>
  496. /// <param name="filename"></param>
  497. /// <param name="asset"></param>
  498. private void WriteFileCache(string filename, AssetBase asset)
  499. {
  500. Stream stream = null;
  501. // Make sure the target cache directory exists
  502. string directory = Path.GetDirectoryName(filename);
  503. // Write file first to a temp name, so that it doesn't look
  504. // like it's already cached while it's still writing.
  505. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  506. try
  507. {
  508. try
  509. {
  510. if (!Directory.Exists(directory))
  511. {
  512. Directory.CreateDirectory(directory);
  513. }
  514. stream = File.Open(tempname, FileMode.Create);
  515. BinaryFormatter bformatter = new BinaryFormatter();
  516. bformatter.Serialize(stream, asset);
  517. }
  518. catch (IOException e)
  519. {
  520. m_log.WarnFormat(
  521. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  522. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  523. return;
  524. }
  525. finally
  526. {
  527. if (stream != null)
  528. stream.Close();
  529. }
  530. try
  531. {
  532. // Now that it's written, rename it so that it can be found.
  533. //
  534. // File.Copy(tempname, filename, true);
  535. // File.Delete(tempname);
  536. //
  537. // For a brief period, this was done as a separate copy and then temporary file delete operation to
  538. // avoid an IOException caused by move if some competing thread had already written the file.
  539. // However, this causes exceptions on Windows when other threads attempt to read a file
  540. // which is still being copied. So instead, go back to moving the file and swallow any IOException.
  541. //
  542. // This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
  543. // filesystem.
  544. File.Move(tempname, filename);
  545. if (m_LogLevel >= 2)
  546. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  547. }
  548. catch (IOException)
  549. {
  550. // If we see an IOException here it's likely that some other competing thread has written the
  551. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  552. // signally by the earlier temporary file writing code.
  553. }
  554. }
  555. finally
  556. {
  557. // Even if the write fails with an exception, we need to make sure
  558. // that we release the lock on that file, otherwise it'll never get
  559. // cached
  560. lock (m_CurrentlyWriting)
  561. {
  562. #if WAIT_ON_INPROGRESS_REQUESTS
  563. ManualResetEvent waitEvent;
  564. if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
  565. {
  566. m_CurrentlyWriting.Remove(filename);
  567. waitEvent.Set();
  568. }
  569. #else
  570. m_CurrentlyWriting.Remove(filename);
  571. #endif
  572. }
  573. }
  574. }
  575. /// <summary>
  576. /// Scan through the file cache, and return number of assets currently cached.
  577. /// </summary>
  578. /// <param name="dir"></param>
  579. /// <returns></returns>
  580. private int GetFileCacheCount(string dir)
  581. {
  582. int count = Directory.GetFiles(dir).Length;
  583. foreach (string subdir in Directory.GetDirectories(dir))
  584. {
  585. count += GetFileCacheCount(subdir);
  586. }
  587. return count;
  588. }
  589. /// <summary>
  590. /// This notes the last time the Region had a deep asset scan performed on it.
  591. /// </summary>
  592. /// <param name="regionID"></param>
  593. private void StampRegionStatusFile(UUID regionID)
  594. {
  595. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
  596. try
  597. {
  598. if (File.Exists(RegionCacheStatusFile))
  599. {
  600. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  601. }
  602. else
  603. {
  604. File.WriteAllText(
  605. RegionCacheStatusFile,
  606. "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  607. }
  608. }
  609. catch (Exception e)
  610. {
  611. m_log.Warn(
  612. string.Format(
  613. "[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
  614. regionID),
  615. e);
  616. }
  617. }
  618. /// <summary>
  619. /// Iterates through all Scenes, doing a deep scan through assets
  620. /// to update the access time of all assets present in the scene or referenced by assets
  621. /// in the scene.
  622. /// </summary>
  623. /// <param name="storeUncached">
  624. /// If true, then assets scanned which are not found in cache are added to the cache.
  625. /// </param>
  626. /// <returns>Number of distinct asset references found in the scene.</returns>
  627. private int TouchAllSceneAssets(bool storeUncached)
  628. {
  629. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  630. HashSet<UUID> uniqueUuids = new HashSet<UUID>();
  631. Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
  632. foreach (Scene s in m_Scenes)
  633. {
  634. StampRegionStatusFile(s.RegionInfo.RegionID);
  635. s.ForEachSOG(delegate(SceneObjectGroup e)
  636. {
  637. gatherer.GatherAssetUuids(e, assets);
  638. foreach (UUID assetID in assets.Keys)
  639. {
  640. uniqueUuids.Add(assetID);
  641. string filename = GetFileName(assetID.ToString());
  642. if (File.Exists(filename))
  643. {
  644. File.SetLastAccessTime(filename, DateTime.Now);
  645. }
  646. else if (storeUncached)
  647. {
  648. AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
  649. if (cachedAsset == null && assets[assetID] != AssetType.Unknown)
  650. m_log.DebugFormat(
  651. "[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",
  652. assetID, assets[assetID], e.Name, e.AbsolutePosition, s.Name);
  653. }
  654. }
  655. assets.Clear();
  656. });
  657. }
  658. return uniqueUuids.Count;
  659. }
  660. /// <summary>
  661. /// Deletes all cache contents
  662. /// </summary>
  663. private void ClearFileCache()
  664. {
  665. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  666. {
  667. try
  668. {
  669. Directory.Delete(dir, true);
  670. }
  671. catch (Exception e)
  672. {
  673. m_log.WarnFormat(
  674. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  675. dir, m_CacheDirectory, e.Message, e.StackTrace);
  676. }
  677. }
  678. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  679. {
  680. try
  681. {
  682. File.Delete(file);
  683. }
  684. catch (Exception e)
  685. {
  686. m_log.WarnFormat(
  687. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  688. file, m_CacheDirectory, e.Message, e.StackTrace);
  689. }
  690. }
  691. }
  692. #region Console Commands
  693. private void HandleConsoleCommand(string module, string[] cmdparams)
  694. {
  695. if (cmdparams.Length >= 2)
  696. {
  697. string cmd = cmdparams[1];
  698. switch (cmd)
  699. {
  700. case "status":
  701. if (m_MemoryCacheEnabled)
  702. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Cache : {0} assets", m_MemoryCache.Count);
  703. else
  704. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory cache disabled");
  705. if (m_FileCacheEnabled)
  706. {
  707. int fileCount = GetFileCacheCount(m_CacheDirectory);
  708. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Cache : {0} assets", fileCount);
  709. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  710. {
  711. m_log.Info("[FLOTSAM ASSET CACHE]: Deep scans have previously been performed on the following regions:");
  712. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  713. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  714. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  715. }
  716. }
  717. else
  718. {
  719. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache disabled");
  720. }
  721. break;
  722. case "clear":
  723. if (cmdparams.Length < 2)
  724. {
  725. m_log.Warn("[FLOTSAM ASSET CACHE]: Usage is fcache clear [file] [memory]");
  726. break;
  727. }
  728. bool clearMemory = false, clearFile = false;
  729. if (cmdparams.Length == 2)
  730. {
  731. clearMemory = true;
  732. clearFile = true;
  733. }
  734. foreach (string s in cmdparams)
  735. {
  736. if (s.ToLower() == "memory")
  737. clearMemory = true;
  738. else if (s.ToLower() == "file")
  739. clearFile = true;
  740. }
  741. if (clearMemory)
  742. {
  743. if (m_MemoryCacheEnabled)
  744. {
  745. m_MemoryCache.Clear();
  746. m_log.Info("[FLOTSAM ASSET CACHE]: Memory cache cleared.");
  747. }
  748. else
  749. {
  750. m_log.Info("[FLOTSAM ASSET CACHE]: Memory cache not enabled.");
  751. }
  752. }
  753. if (clearFile)
  754. {
  755. if (m_FileCacheEnabled)
  756. {
  757. ClearFileCache();
  758. m_log.Info("[FLOTSAM ASSET CACHE]: File cache cleared.");
  759. }
  760. else
  761. {
  762. m_log.Info("[FLOTSAM ASSET CACHE]: File cache not enabled.");
  763. }
  764. }
  765. break;
  766. case "assets":
  767. m_log.Info("[FLOTSAM ASSET CACHE]: Ensuring assets are cached for all scenes.");
  768. Util.FireAndForget(delegate {
  769. int assetReferenceTotal = TouchAllSceneAssets(true);
  770. m_log.InfoFormat(
  771. "[FLOTSAM ASSET CACHE]: Completed check with {0} assets.",
  772. assetReferenceTotal);
  773. });
  774. break;
  775. case "expire":
  776. if (cmdparams.Length < 3)
  777. {
  778. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Invalid parameters for Expire, please specify a valid date & time", cmd);
  779. break;
  780. }
  781. string s_expirationDate = "";
  782. DateTime expirationDate;
  783. if (cmdparams.Length > 3)
  784. {
  785. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  786. }
  787. else
  788. {
  789. s_expirationDate = cmdparams[2];
  790. }
  791. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  792. {
  793. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} is not a valid date & time", cmd);
  794. break;
  795. }
  796. if (m_FileCacheEnabled)
  797. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  798. else
  799. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File cache not active, not clearing.");
  800. break;
  801. default:
  802. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Unknown command {0}", cmd);
  803. break;
  804. }
  805. }
  806. else if (cmdparams.Length == 1)
  807. {
  808. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache status - Display cache status");
  809. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearmem - Remove all assets cached in memory");
  810. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache clearfile - Remove all assets cached on disk");
  811. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache cachescenes - Attempt a deep cache of all assets in all scenes");
  812. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: fcache <datetime> - Purge assets older then the specified date & time");
  813. }
  814. }
  815. #endregion
  816. #region IAssetService Members
  817. public AssetMetadata GetMetadata(string id)
  818. {
  819. AssetBase asset = Get(id);
  820. return asset.Metadata;
  821. }
  822. public byte[] GetData(string id)
  823. {
  824. AssetBase asset = Get(id);
  825. return asset.Data;
  826. }
  827. public bool Get(string id, object sender, AssetRetrieved handler)
  828. {
  829. AssetBase asset = Get(id);
  830. handler(id, sender, asset);
  831. return true;
  832. }
  833. public string Store(AssetBase asset)
  834. {
  835. if (asset.FullID == UUID.Zero)
  836. {
  837. asset.FullID = UUID.Random();
  838. }
  839. Cache(asset);
  840. return asset.ID;
  841. }
  842. public bool UpdateContent(string id, byte[] data)
  843. {
  844. AssetBase asset = Get(id);
  845. asset.Data = data;
  846. Cache(asset);
  847. return true;
  848. }
  849. public bool Delete(string id)
  850. {
  851. Expire(id);
  852. return true;
  853. }
  854. #endregion
  855. }
  856. }