FlotsamAssetCache.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  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. using System;
  28. using System.IO;
  29. using System.Collections.Generic;
  30. using System.Linq;
  31. using System.Reflection;
  32. using System.Runtime.Serialization;
  33. using System.Runtime.Serialization.Formatters.Binary;
  34. using System.Text;
  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.Framework.Monitoring;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. using OpenSim.Server.Base;
  47. using OpenSim.Services.Interfaces;
  48. namespace OpenSim.Region.CoreModules.Asset
  49. {
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
  51. public class FlotsamAssetCache : ISharedRegionModule, IAssetCache, IAssetService
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType);
  54. private bool m_Enabled;
  55. private bool m_timerRunning;
  56. private bool m_cleanupRunning;
  57. private const string m_ModuleName = "FlotsamAssetCache";
  58. private const string m_DefaultCacheDirectory = "./assetcache";
  59. private string m_CacheDirectory = m_DefaultCacheDirectory;
  60. private string m_assetLoader;
  61. private string m_assetLoaderArgs;
  62. private readonly char[] m_InvalidChars;
  63. private int m_LogLevel = 0;
  64. private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
  65. private ulong m_Requests;
  66. private ulong m_RequestsForInprogress;
  67. private ulong m_DiskHits;
  68. private ulong m_MemoryHits;
  69. private ulong m_weakRefHits;
  70. private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
  71. private bool m_FileCacheEnabled = true;
  72. private ExpiringCache<string, AssetBase> m_MemoryCache;
  73. private bool m_MemoryCacheEnabled = false;
  74. private ExpiringCache<string, object> m_negativeCache;
  75. private bool m_negativeCacheEnabled = true;
  76. private bool m_negativeCacheSliding = false;
  77. // Expiration is expressed in hours.
  78. private double m_MemoryExpiration = 0.016;
  79. private const double m_DefaultFileExpiration = 48;
  80. // Negative cache is in seconds
  81. private int m_negativeExpiration = 120;
  82. private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
  83. private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(1.0);
  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. private object timerLock = new object();
  91. private Dictionary<string,WeakReference> weakAssetReferences = new Dictionary<string, WeakReference>();
  92. private object weakAssetReferencesLock = new object();
  93. private bool m_updateFileTimeOnCacheHit = false;
  94. public FlotsamAssetCache()
  95. {
  96. List<char> invalidChars = new List<char>();
  97. invalidChars.AddRange(Path.GetInvalidPathChars());
  98. invalidChars.AddRange(Path.GetInvalidFileNameChars());
  99. m_InvalidChars = invalidChars.ToArray();
  100. }
  101. private static JobEngine m_DiskWriterEngine = null;
  102. public Type ReplaceableInterface
  103. {
  104. get { return null; }
  105. }
  106. public string Name
  107. {
  108. get { return m_ModuleName; }
  109. }
  110. public void Initialise(IConfigSource source)
  111. {
  112. IConfig moduleConfig = source.Configs["Modules"];
  113. if (moduleConfig != null)
  114. {
  115. string name = moduleConfig.GetString("AssetCaching", String.Empty);
  116. if (name == Name)
  117. {
  118. m_MemoryCache = new ExpiringCache<string, AssetBase>();
  119. m_negativeCache = new ExpiringCache<string, object>();
  120. m_Enabled = true;
  121. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
  122. IConfig assetConfig = source.Configs["AssetCache"];
  123. if (assetConfig == null)
  124. {
  125. m_log.Debug(
  126. "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
  127. }
  128. else
  129. {
  130. m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
  131. m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
  132. m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
  133. m_MemoryExpiration = assetConfig.GetDouble("MemoryCacheTimeout", m_MemoryExpiration);
  134. m_MemoryExpiration *= 3600.0; // config in hours to seconds
  135. m_negativeCacheEnabled = assetConfig.GetBoolean("NegativeCacheEnabled", m_negativeCacheEnabled);
  136. m_negativeExpiration = assetConfig.GetInt("NegativeCacheTimeout", m_negativeExpiration);
  137. m_negativeCacheSliding = assetConfig.GetBoolean("NegativeCacheSliding", m_negativeCacheSliding);
  138. m_updateFileTimeOnCacheHit = assetConfig.GetBoolean("UpdateFileTimeOnCacheHit", m_updateFileTimeOnCacheHit);
  139. m_updateFileTimeOnCacheHit &= m_FileCacheEnabled;
  140. m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
  141. m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
  142. m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
  143. m_FileExpirationCleanupTimer
  144. = TimeSpan.FromHours(
  145. assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
  146. m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
  147. m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
  148. m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
  149. }
  150. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
  151. if (m_CacheDirectoryTiers < 1)
  152. m_CacheDirectoryTiers = 1;
  153. else if (m_CacheDirectoryTiers > 3)
  154. m_CacheDirectoryTiers = 3;
  155. if (m_CacheDirectoryTierLen < 1)
  156. m_CacheDirectoryTierLen = 1;
  157. else if (m_CacheDirectoryTierLen > 4)
  158. m_CacheDirectoryTierLen = 4;
  159. assetConfig = source.Configs["AssetService"];
  160. if(assetConfig != null)
  161. {
  162. m_assetLoader = assetConfig.GetString("DefaultAssetLoader", String.Empty);
  163. m_assetLoaderArgs = assetConfig.GetString("AssetLoaderArgs", string.Empty);
  164. if (string.IsNullOrWhiteSpace(m_assetLoaderArgs))
  165. m_assetLoader = string.Empty;
  166. }
  167. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
  168. 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);
  169. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
  170. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
  171. if (!string.IsNullOrWhiteSpace(m_assetLoader))
  172. {
  173. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache cachedefaultassets", "fcache cachedefaultassets", "loads local default assets to cache. This may override grid ones. use with care", HandleConsoleCommand);
  174. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache deletedefaultassets", "fcache deletedefaultassets", "deletes default local assets from cache so they can be refreshed from grid. use with care", HandleConsoleCommand);
  175. }
  176. }
  177. }
  178. }
  179. public void PostInitialise()
  180. {
  181. }
  182. public void Close()
  183. {
  184. }
  185. public void AddRegion(Scene scene)
  186. {
  187. if (m_Enabled)
  188. {
  189. scene.RegisterModuleInterface<IAssetCache>(this);
  190. m_Scenes.Add(scene);
  191. }
  192. }
  193. public void RemoveRegion(Scene scene)
  194. {
  195. if (m_Enabled)
  196. {
  197. scene.UnregisterModuleInterface<IAssetCache>(this);
  198. m_Scenes.Remove(scene);
  199. lock(timerLock)
  200. {
  201. if(m_timerRunning && m_Scenes.Count <= 0)
  202. {
  203. m_timerRunning = false;
  204. m_CacheCleanTimer.Stop();
  205. m_CacheCleanTimer.Close();
  206. if (m_FileCacheEnabled && m_DiskWriterEngine != null && m_DiskWriterEngine.IsRunning)
  207. m_DiskWriterEngine.Stop();
  208. }
  209. }
  210. }
  211. }
  212. public void RegionLoaded(Scene scene)
  213. {
  214. if (m_Enabled)
  215. {
  216. if(m_AssetService == null)
  217. m_AssetService = scene.RequestModuleInterface<IAssetService>();
  218. lock(timerLock)
  219. {
  220. if(!m_timerRunning)
  221. {
  222. if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
  223. {
  224. m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
  225. m_CacheCleanTimer.AutoReset = false;
  226. m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
  227. m_CacheCleanTimer.Start();
  228. m_timerRunning = true;
  229. }
  230. }
  231. if(m_DiskWriterEngine == null)
  232. {
  233. m_DiskWriterEngine = new JobEngine("FlotsamWriter", "FlotsamWriter");
  234. m_DiskWriterEngine.Start();
  235. }
  236. }
  237. }
  238. }
  239. ////////////////////////////////////////////////////////////
  240. // IAssetCache
  241. //
  242. private void UpdateWeakReference(string key, AssetBase asset)
  243. {
  244. WeakReference aref;
  245. lock(weakAssetReferencesLock)
  246. {
  247. if(weakAssetReferences.TryGetValue(key , out aref))
  248. aref.Target = asset;
  249. else
  250. weakAssetReferences[key] = new WeakReference(asset);
  251. }
  252. }
  253. private void UpdateMemoryCache(string key, AssetBase asset)
  254. {
  255. // NOTE DO NOT USE SLIDEEXPIRE option on current libomv
  256. m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
  257. }
  258. private void UpdateFileCache(string key, AssetBase asset, bool replace = false)
  259. {
  260. string filename = GetFileName(key);
  261. try
  262. {
  263. // If the file is already cached, don't cache it, just touch it so access time is updated
  264. if (!replace && File.Exists(filename))
  265. {
  266. UpdateFileLastAccessTime(filename);
  267. return;
  268. }
  269. // Once we start writing, make sure we flag that we're writing
  270. // that object to the cache so that we don't try to write the
  271. // same file multiple times.
  272. lock (m_CurrentlyWriting)
  273. {
  274. if (m_CurrentlyWriting.Contains(filename))
  275. return;
  276. else
  277. m_CurrentlyWriting.Add(filename);
  278. }
  279. // weakreferences should hold and return the asset while async write happens
  280. m_DiskWriterEngine?.QueueJob("", delegate { WriteFileCache(filename, asset, replace); });
  281. }
  282. catch (Exception e)
  283. {
  284. m_log.ErrorFormat(
  285. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  286. asset.ID, e.Message, e.StackTrace);
  287. }
  288. }
  289. public void Cache(AssetBase asset, bool replace = false)
  290. {
  291. // TODO: Spawn this off to some seperate thread to do the actual writing
  292. if (asset != null)
  293. {
  294. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  295. UpdateWeakReference(asset.ID, asset);
  296. if (m_MemoryCacheEnabled)
  297. UpdateMemoryCache(asset.ID, asset);
  298. if (m_FileCacheEnabled)
  299. UpdateFileCache(asset.ID, asset, replace);
  300. }
  301. }
  302. public void CacheNegative(string id)
  303. {
  304. if (m_negativeCacheEnabled)
  305. {
  306. if (m_negativeCacheSliding)
  307. m_negativeCache.AddOrUpdate(id, null, TimeSpan.FromSeconds(m_negativeExpiration));
  308. else
  309. m_negativeCache.AddOrUpdate(id, null, m_negativeExpiration);
  310. }
  311. }
  312. /// <summary>
  313. /// Updates the cached file with the current time.
  314. /// </summary>
  315. /// <param name="filename">Filename.</param>
  316. /// <returns><c>true</c>, if the update was successful, false otherwise.</returns>
  317. private bool UpdateFileLastAccessTime(string filename)
  318. {
  319. try
  320. {
  321. File.SetLastAccessTime(filename, DateTime.Now);
  322. return true;
  323. }
  324. catch
  325. {
  326. return false;
  327. }
  328. }
  329. private AssetBase GetFromWeakReference(string id)
  330. {
  331. AssetBase asset = null;
  332. lock(weakAssetReferencesLock)
  333. {
  334. if (weakAssetReferences.TryGetValue(id, out WeakReference aref))
  335. {
  336. asset = aref.Target as AssetBase;
  337. if(asset == null)
  338. weakAssetReferences.Remove(id);
  339. else
  340. m_weakRefHits++;
  341. }
  342. }
  343. return asset;
  344. }
  345. /// <summary>
  346. /// Try to get an asset from the in-memory cache.
  347. /// </summary>
  348. /// <param name="id"></param>
  349. /// <returns></returns>
  350. private AssetBase GetFromMemoryCache(string id)
  351. {
  352. AssetBase asset = null;
  353. if (m_MemoryCache.TryGetValue(id, out asset))
  354. m_MemoryHits++;
  355. return asset;
  356. }
  357. private bool CheckFromMemoryCache(string id)
  358. {
  359. return m_MemoryCache.Contains(id);
  360. }
  361. /// <summary>
  362. /// Try to get an asset from the file cache.
  363. /// </summary>
  364. /// <param name="id"></param>
  365. /// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
  366. private AssetBase GetFromFileCache(string id)
  367. {
  368. string filename = GetFileName(id);
  369. // Track how often we have the problem that an asset is requested while
  370. // it is still being downloaded by a previous request.
  371. if (m_CurrentlyWriting.Contains(filename))
  372. {
  373. m_RequestsForInprogress++;
  374. return null;
  375. }
  376. AssetBase asset = null;
  377. if (File.Exists(filename))
  378. {
  379. try
  380. {
  381. using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  382. {
  383. if (stream.Length == 0) // Empty file will trigger exception below
  384. return null;
  385. BinaryFormatter bformatter = new BinaryFormatter();
  386. asset = (AssetBase)bformatter.Deserialize(stream);
  387. m_DiskHits++;
  388. }
  389. }
  390. catch (System.Runtime.Serialization.SerializationException e)
  391. {
  392. m_log.WarnFormat(
  393. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  394. filename, id, e.Message, e.StackTrace);
  395. // If there was a problem deserializing the asset, the asset may
  396. // either be corrupted OR was serialized under an old format
  397. // {different version of AssetBase} -- we should attempt to
  398. // delete it and re-cache
  399. File.Delete(filename);
  400. }
  401. catch (Exception e)
  402. {
  403. m_log.WarnFormat(
  404. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  405. filename, id, e.Message, e.StackTrace);
  406. }
  407. }
  408. return asset;
  409. }
  410. private bool CheckFromFileCache(string id)
  411. {
  412. bool found = false;
  413. string filename = GetFileName(id);
  414. if (File.Exists(filename))
  415. {
  416. try
  417. {
  418. using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  419. {
  420. if (stream != null)
  421. found = true;
  422. }
  423. }
  424. catch (Exception e)
  425. {
  426. m_log.ErrorFormat(
  427. "[FLOTSAM ASSET CACHE]: Failed to check file {0} for asset {1}. Exception {2} {3}",
  428. filename, id, e.Message, e.StackTrace);
  429. }
  430. }
  431. return found;
  432. }
  433. // For IAssetService
  434. public AssetBase Get(string id)
  435. {
  436. AssetBase asset;
  437. Get(id, out asset);
  438. return asset;
  439. }
  440. public bool Get(string id, out AssetBase asset)
  441. {
  442. asset = null;
  443. m_Requests++;
  444. object dummy;
  445. if (m_negativeCache.TryGetValue(id, out dummy))
  446. {
  447. return false;
  448. }
  449. asset = GetFromWeakReference(id);
  450. if (asset != null && m_updateFileTimeOnCacheHit)
  451. {
  452. string filename = GetFileName(id);
  453. UpdateFileLastAccessTime(filename);
  454. }
  455. if (m_MemoryCacheEnabled && asset == null)
  456. {
  457. asset = GetFromMemoryCache(id);
  458. if(asset != null)
  459. {
  460. UpdateWeakReference(id,asset);
  461. if (m_updateFileTimeOnCacheHit)
  462. {
  463. string filename = GetFileName(id);
  464. UpdateFileLastAccessTime(filename);
  465. }
  466. }
  467. }
  468. if (asset == null && m_FileCacheEnabled)
  469. {
  470. asset = GetFromFileCache(id);
  471. if(asset != null)
  472. UpdateWeakReference(id,asset);
  473. }
  474. if (m_MemoryCacheEnabled && asset != null)
  475. UpdateMemoryCache(id, asset);
  476. if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
  477. {
  478. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
  479. GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l));
  480. }
  481. return true;
  482. }
  483. public bool Check(string id)
  484. {
  485. if (m_MemoryCacheEnabled && CheckFromMemoryCache(id))
  486. return true;
  487. if (m_FileCacheEnabled && CheckFromFileCache(id))
  488. return true;
  489. return false;
  490. }
  491. public AssetBase GetCached(string id)
  492. {
  493. AssetBase asset;
  494. Get(id, out asset);
  495. return asset;
  496. }
  497. public void Expire(string id)
  498. {
  499. if (m_LogLevel >= 2)
  500. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  501. try
  502. {
  503. lock (weakAssetReferencesLock)
  504. weakAssetReferences.Remove(id);
  505. if (m_FileCacheEnabled)
  506. {
  507. string filename = GetFileName(id);
  508. File.Delete(filename);
  509. }
  510. if (m_MemoryCacheEnabled)
  511. m_MemoryCache.Remove(id);
  512. }
  513. catch (Exception e)
  514. {
  515. m_log.WarnFormat(
  516. "[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  517. id, e.Message, e.StackTrace);
  518. }
  519. }
  520. public void Clear()
  521. {
  522. if (m_LogLevel >= 2)
  523. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  524. if (m_FileCacheEnabled && Directory.Exists(m_CacheDirectory))
  525. {
  526. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  527. {
  528. Directory.Delete(dir);
  529. }
  530. }
  531. if (m_MemoryCacheEnabled)
  532. m_MemoryCache = new ExpiringCache<string, AssetBase>();
  533. if (m_negativeCacheEnabled)
  534. m_negativeCache = new ExpiringCache<string, object>();
  535. lock(weakAssetReferencesLock)
  536. weakAssetReferences = new Dictionary<string, WeakReference>();
  537. }
  538. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  539. {
  540. if (m_LogLevel >= 2)
  541. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
  542. lock(timerLock)
  543. {
  544. if(!m_timerRunning || m_cleanupRunning)
  545. return;
  546. m_cleanupRunning = true;
  547. }
  548. // Purge all files last accessed prior to this point
  549. DateTime purgeLine = DateTime.Now - m_FileExpiration;
  550. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  551. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  552. // such local assets if they have not been recently accessed.
  553. TouchAllSceneAssets(false);
  554. if(Directory.Exists(m_CacheDirectory))
  555. {
  556. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  557. CleanExpiredFiles(dir, purgeLine);
  558. }
  559. lock(timerLock)
  560. {
  561. if(m_timerRunning)
  562. m_CacheCleanTimer.Start();
  563. m_cleanupRunning = false;
  564. }
  565. }
  566. /// <summary>
  567. /// Recurses through specified directory checking for asset files last
  568. /// accessed prior to the specified purge line and deletes them. Also
  569. /// removes empty tier directories.
  570. /// </summary>
  571. /// <param name="dir"></param>
  572. /// <param name="purgeLine"></param>
  573. private void CleanExpiredFiles(string dir, DateTime purgeLine)
  574. {
  575. try
  576. {
  577. if(!Directory.Exists(dir))
  578. return;
  579. foreach (string file in Directory.GetFiles(dir))
  580. {
  581. if (File.GetLastAccessTime(file) < purgeLine)
  582. {
  583. File.Delete(file);
  584. }
  585. }
  586. // Recurse into lower tiers
  587. foreach (string subdir in Directory.GetDirectories(dir))
  588. {
  589. CleanExpiredFiles(subdir, purgeLine);
  590. }
  591. // Check if a tier directory is empty, if so, delete it
  592. int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
  593. if (dirSize == 0)
  594. {
  595. Directory.Delete(dir);
  596. }
  597. else if (dirSize >= m_CacheWarnAt)
  598. {
  599. m_log.WarnFormat(
  600. "[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
  601. dir, dirSize);
  602. }
  603. }
  604. catch (DirectoryNotFoundException)
  605. {
  606. // If we get here, another node on the same box has
  607. // already removed the directory. Continue with next.
  608. }
  609. catch (Exception e)
  610. {
  611. m_log.Warn(
  612. string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
  613. }
  614. }
  615. /// <summary>
  616. /// Determines the filename for an AssetID stored in the file cache
  617. /// </summary>
  618. /// <param name="id"></param>
  619. /// <returns></returns>
  620. private string GetFileName(string id)
  621. {
  622. int indx = id.IndexOfAny(m_InvalidChars);
  623. if (indx >= 0)
  624. {
  625. int sublen = id.Length - indx;
  626. StringBuilder sb = new StringBuilder(id);
  627. for(int i = 0; i < m_InvalidChars.Length; ++i)
  628. {
  629. sb.Replace(m_InvalidChars[i], '_', indx, sublen);
  630. }
  631. id = sb.ToString();
  632. }
  633. string path = m_CacheDirectory;
  634. for (int p = 1; p <= m_CacheDirectoryTiers; p++)
  635. {
  636. string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
  637. path = Path.Combine(path, pathPart);
  638. }
  639. return Path.Combine(path, id);
  640. }
  641. /// <summary>
  642. /// Writes a file to the file cache, creating any nessesary
  643. /// tier directories along the way
  644. /// </summary>
  645. /// <param name="filename"></param>
  646. /// <param name="asset"></param>
  647. private void WriteFileCache(string filename, AssetBase asset, bool replace)
  648. {
  649. // Make sure the target cache directory exists
  650. string directory = Path.GetDirectoryName(filename);
  651. // Write file first to a temp name, so that it doesn't look
  652. // like it's already cached while it's still writing.
  653. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  654. try
  655. {
  656. try
  657. {
  658. if (!Directory.Exists(directory))
  659. {
  660. Directory.CreateDirectory(directory);
  661. }
  662. using(Stream stream = File.Open(tempname, FileMode.Create))
  663. {
  664. BinaryFormatter bformatter = new BinaryFormatter();
  665. bformatter.Serialize(stream, asset);
  666. stream.Flush();
  667. }
  668. }
  669. catch (IOException e)
  670. {
  671. m_log.WarnFormat(
  672. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  673. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  674. return;
  675. }
  676. catch (UnauthorizedAccessException)
  677. {
  678. }
  679. try
  680. {
  681. if(replace)
  682. File.Delete(filename);
  683. File.Move(tempname, filename);
  684. if (m_LogLevel >= 2)
  685. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
  686. }
  687. catch (IOException)
  688. {
  689. // If we see an IOException here it's likely that some other competing thread has written the
  690. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  691. // signally by the earlier temporary file writing code.
  692. }
  693. }
  694. finally
  695. {
  696. // Even if the write fails with an exception, we need to make sure
  697. // that we release the lock on that file, otherwise it'll never get
  698. // cached
  699. lock (m_CurrentlyWriting)
  700. {
  701. m_CurrentlyWriting.Remove(filename);
  702. }
  703. }
  704. }
  705. /// <summary>
  706. /// Scan through the file cache, and return number of assets currently cached.
  707. /// </summary>
  708. /// <param name="dir"></param>
  709. /// <returns></returns>
  710. private int GetFileCacheCount(string dir)
  711. {
  712. if(!Directory.Exists(dir))
  713. return 0;
  714. int count = Directory.GetFiles(dir).Length;
  715. foreach (string subdir in Directory.GetDirectories(dir))
  716. {
  717. count += GetFileCacheCount(subdir);
  718. }
  719. return count;
  720. }
  721. /// <summary>
  722. /// This notes the last time the Region had a deep asset scan performed on it.
  723. /// </summary>
  724. /// <param name="regionID"></param>
  725. private void StampRegionStatusFile(UUID regionID)
  726. {
  727. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
  728. try
  729. {
  730. if (File.Exists(RegionCacheStatusFile))
  731. {
  732. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  733. }
  734. else
  735. {
  736. File.WriteAllText(
  737. RegionCacheStatusFile,
  738. "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  739. }
  740. }
  741. catch (Exception e)
  742. {
  743. m_log.Warn(
  744. string.Format(
  745. "[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
  746. regionID),
  747. e);
  748. }
  749. }
  750. /// <summary>
  751. /// Iterates through all Scenes, doing a deep scan through assets
  752. /// to update the access time of all assets present in the scene or referenced by assets
  753. /// in the scene.
  754. /// </summary>
  755. /// <param name="storeUncached">
  756. /// If true, then assets scanned which are not found in cache are added to the cache.
  757. /// </param>
  758. /// <returns>Number of distinct asset references found in the scene.</returns>
  759. private int TouchAllSceneAssets(bool storeUncached)
  760. {
  761. UuidGatherer gatherer = new UuidGatherer(m_AssetService);
  762. Dictionary<UUID, bool> assetsFound = new Dictionary<UUID, bool>();
  763. foreach (Scene s in m_Scenes)
  764. {
  765. StampRegionStatusFile(s.RegionInfo.RegionID);
  766. s.ForEachSOG(delegate(SceneObjectGroup e)
  767. {
  768. if(!m_timerRunning && !storeUncached)
  769. return;
  770. gatherer.AddForInspection(e);
  771. gatherer.GatherAll();
  772. if(!m_timerRunning && !storeUncached)
  773. return;
  774. foreach (UUID assetID in gatherer.GatheredUuids.Keys)
  775. {
  776. if (!assetsFound.ContainsKey(assetID))
  777. {
  778. string filename = GetFileName(assetID.ToString());
  779. if (File.Exists(filename))
  780. {
  781. UpdateFileLastAccessTime(filename);
  782. assetsFound[assetID] = true;
  783. }
  784. else if (storeUncached)
  785. {
  786. AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
  787. if (cachedAsset == null && gatherer.GatheredUuids[assetID] != (sbyte)AssetType.Unknown)
  788. assetsFound[assetID] = false;
  789. else
  790. assetsFound[assetID] = true;
  791. }
  792. }
  793. else if (!assetsFound[assetID])
  794. {
  795. m_log.DebugFormat(
  796. "[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",
  797. assetID, gatherer.GatheredUuids[assetID], e.Name, e.AbsolutePosition, s.Name);
  798. }
  799. }
  800. gatherer.GatheredUuids.Clear();
  801. if(!m_timerRunning && !storeUncached)
  802. return;
  803. if(!storeUncached)
  804. Thread.Sleep(50);
  805. });
  806. if(!m_timerRunning && !storeUncached)
  807. break;
  808. }
  809. return assetsFound.Count;
  810. }
  811. /// <summary>
  812. /// Deletes all cache contents
  813. /// </summary>
  814. private void ClearFileCache()
  815. {
  816. if(!Directory.Exists(m_CacheDirectory))
  817. return;
  818. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  819. {
  820. try
  821. {
  822. Directory.Delete(dir, true);
  823. }
  824. catch (Exception e)
  825. {
  826. m_log.WarnFormat(
  827. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  828. dir, m_CacheDirectory, e.Message, e.StackTrace);
  829. }
  830. }
  831. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  832. {
  833. try
  834. {
  835. File.Delete(file);
  836. }
  837. catch (Exception e)
  838. {
  839. m_log.WarnFormat(
  840. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  841. file, m_CacheDirectory, e.Message, e.StackTrace);
  842. }
  843. }
  844. }
  845. private List<string> GenerateCacheHitReport()
  846. {
  847. List<string> outputLines = new List<string>();
  848. double invReq = 100.0 / m_Requests;
  849. double weakHitRate = m_weakRefHits * invReq;
  850. int weakEntriesAlive = 0;
  851. lock(weakAssetReferencesLock)
  852. {
  853. foreach(WeakReference aref in weakAssetReferences.Values)
  854. {
  855. if (aref.IsAlive)
  856. ++weakEntriesAlive;
  857. }
  858. }
  859. int weakEntries = weakAssetReferences.Count;
  860. double fileHitRate = m_DiskHits * invReq;
  861. double TotalHitRate = weakHitRate + fileHitRate;
  862. outputLines.Add(
  863. string.Format("Total requests: {0}", m_Requests));
  864. outputLines.Add(
  865. string.Format("unCollected Hit Rate: {0}% ({1} entries {2} alive)", weakHitRate.ToString("0.00"),weakEntries, weakEntriesAlive));
  866. outputLines.Add(
  867. string.Format("File Hit Rate: {0}%", fileHitRate.ToString("0.00")));
  868. if (m_MemoryCacheEnabled)
  869. {
  870. double HitRate = m_MemoryHits * invReq;
  871. outputLines.Add(
  872. string.Format("Memory Hit Rate: {0}%", HitRate.ToString("0.00")));
  873. TotalHitRate += HitRate;
  874. }
  875. outputLines.Add(
  876. string.Format("Total Hit Rate: {0}%", TotalHitRate.ToString("0.00")));
  877. outputLines.Add(
  878. string.Format(
  879. "Requests overlap during file writing: {0}", m_RequestsForInprogress));
  880. return outputLines;
  881. }
  882. #region Console Commands
  883. private void HandleConsoleCommand(string module, string[] cmdparams)
  884. {
  885. ICommandConsole con = MainConsole.Instance;
  886. if (cmdparams.Length >= 2)
  887. {
  888. string cmd = cmdparams[1];
  889. switch (cmd)
  890. {
  891. case "status":
  892. if (m_MemoryCacheEnabled)
  893. con.Output("Memory Cache: {0} assets", m_MemoryCache.Count);
  894. else
  895. con.Output("Memory cache disabled");
  896. if (m_FileCacheEnabled)
  897. {
  898. int fileCount = GetFileCacheCount(m_CacheDirectory);
  899. con.Output("File Cache: {0} assets", fileCount);
  900. }
  901. else
  902. {
  903. con.Output("File cache disabled");
  904. }
  905. GenerateCacheHitReport().ForEach(l => con.Output(l));
  906. if (m_FileCacheEnabled)
  907. {
  908. con.Output("Deep scans have previously been performed on the following regions:");
  909. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  910. {
  911. string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
  912. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  913. con.Output("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  914. }
  915. }
  916. break;
  917. case "clear":
  918. if (cmdparams.Length < 2)
  919. {
  920. con.Output("Usage is fcache clear [file] [memory]");
  921. break;
  922. }
  923. bool clearMemory = false, clearFile = false;
  924. if (cmdparams.Length == 2)
  925. {
  926. clearMemory = true;
  927. clearFile = true;
  928. }
  929. foreach (string s in cmdparams)
  930. {
  931. if (s.ToLower() == "memory")
  932. clearMemory = true;
  933. else if (s.ToLower() == "file")
  934. clearFile = true;
  935. }
  936. if (clearMemory)
  937. {
  938. if (m_MemoryCacheEnabled)
  939. {
  940. m_MemoryCache.Clear();
  941. con.Output("Memory cache cleared.");
  942. }
  943. else
  944. {
  945. con.Output("Memory cache not enabled.");
  946. }
  947. }
  948. if (clearFile)
  949. {
  950. if (m_FileCacheEnabled)
  951. {
  952. ClearFileCache();
  953. con.Output("File cache cleared.");
  954. }
  955. else
  956. {
  957. con.Output("File cache not enabled.");
  958. }
  959. }
  960. break;
  961. case "assets":
  962. lock(timerLock)
  963. {
  964. if(m_cleanupRunning)
  965. {
  966. con.Output("Flotsam assets check already running");
  967. return;
  968. }
  969. m_cleanupRunning = true;
  970. }
  971. con.Output("Flotsam Ensuring assets are cached for all scenes.");
  972. WorkManager.RunInThreadPool(delegate
  973. {
  974. bool wasRunning= false;
  975. lock(timerLock)
  976. {
  977. if(m_timerRunning)
  978. {
  979. m_CacheCleanTimer.Stop();
  980. m_timerRunning = false;
  981. wasRunning = true;
  982. Thread.Sleep(100);
  983. }
  984. }
  985. int assetReferenceTotal = TouchAllSceneAssets(true);
  986. GC.Collect();
  987. lock(timerLock)
  988. {
  989. if(wasRunning)
  990. {
  991. m_CacheCleanTimer.Start();
  992. m_timerRunning = true;
  993. }
  994. m_cleanupRunning = false;
  995. }
  996. con.Output("Completed check with {0} assets.", assetReferenceTotal);
  997. }, null, "TouchAllSceneAssets", false);
  998. break;
  999. case "expire":
  1000. if (cmdparams.Length < 3)
  1001. {
  1002. con.Output("Invalid parameters for Expire, please specify a valid date & time");
  1003. break;
  1004. }
  1005. string s_expirationDate = "";
  1006. DateTime expirationDate;
  1007. if (cmdparams.Length > 3)
  1008. {
  1009. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  1010. }
  1011. else
  1012. {
  1013. s_expirationDate = cmdparams[2];
  1014. }
  1015. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  1016. {
  1017. con.Output("{0} is not a valid date & time", cmd);
  1018. break;
  1019. }
  1020. if (m_FileCacheEnabled)
  1021. CleanExpiredFiles(m_CacheDirectory, expirationDate);
  1022. else
  1023. con.Output("File cache not active, not clearing.");
  1024. break;
  1025. case "cachedefaultassets":
  1026. HandleLoadDefaultAssets();
  1027. break;
  1028. case "deletedefaultassets":
  1029. HandleDeleteDefaultAssets();
  1030. break;
  1031. default:
  1032. con.Output("Unknown command {0}", cmd);
  1033. break;
  1034. }
  1035. }
  1036. else if (cmdparams.Length == 1)
  1037. {
  1038. con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
  1039. con.Output("fcache expire <datetime> - Purge assets older then the specified date & time");
  1040. con.Output("fcache clear [file] [memory] - Remove cached assets");
  1041. con.Output("fcache status - Display cache status");
  1042. con.Output("fcache cachedefaultassets - loads default assets to cache replacing existent ones, this may override grid assets. Use with care");
  1043. con.Output("fcache deletedefaultassets - deletes default local assets from cache so they can be refreshed from grid");
  1044. }
  1045. }
  1046. #endregion
  1047. #region IAssetService Members
  1048. public AssetMetadata GetMetadata(string id)
  1049. {
  1050. AssetBase asset;
  1051. Get(id, out asset);
  1052. if (asset == null)
  1053. return null;
  1054. return asset.Metadata;
  1055. }
  1056. public byte[] GetData(string id)
  1057. {
  1058. AssetBase asset;
  1059. Get(id, out asset);
  1060. if (asset == null)
  1061. return null;
  1062. return asset.Data;
  1063. }
  1064. public bool Get(string id, object sender, AssetRetrieved handler)
  1065. {
  1066. AssetBase asset;
  1067. if (!Get(id, out asset))
  1068. return false;
  1069. handler(id, sender, asset);
  1070. return true;
  1071. }
  1072. public bool[] AssetsExist(string[] ids)
  1073. {
  1074. bool[] exist = new bool[ids.Length];
  1075. for (int i = 0; i < ids.Length; i++)
  1076. {
  1077. exist[i] = Check(ids[i]);
  1078. }
  1079. return exist;
  1080. }
  1081. public string Store(AssetBase asset)
  1082. {
  1083. if (asset.FullID == UUID.Zero)
  1084. {
  1085. asset.FullID = UUID.Random();
  1086. }
  1087. Cache(asset);
  1088. return asset.ID;
  1089. }
  1090. public bool UpdateContent(string id, byte[] data)
  1091. {
  1092. AssetBase asset;
  1093. if (!Get(id, out asset))
  1094. return false;
  1095. asset.Data = data;
  1096. Cache(asset, true);
  1097. return true;
  1098. }
  1099. public bool Delete(string id)
  1100. {
  1101. Expire(id);
  1102. return true;
  1103. }
  1104. private void HandleLoadDefaultAssets()
  1105. {
  1106. if (string.IsNullOrWhiteSpace(m_assetLoader))
  1107. {
  1108. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not defined");
  1109. return;
  1110. }
  1111. IAssetLoader assetLoader = ServerUtils.LoadPlugin<IAssetLoader>(m_assetLoader, new object[] { });
  1112. if (assetLoader == null)
  1113. {
  1114. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not found");
  1115. return;
  1116. }
  1117. m_log.Info("[FLOTSAM ASSET CACHE] start loading local default assets");
  1118. int count = 0;
  1119. assetLoader.ForEachDefaultXmlAsset(
  1120. m_assetLoaderArgs,
  1121. delegate (AssetBase a)
  1122. {
  1123. Cache(a, true);
  1124. ++count;
  1125. });
  1126. m_log.InfoFormat("[FLOTSAM ASSET CACHE] loaded {0} local default assets", count);
  1127. }
  1128. private void HandleDeleteDefaultAssets()
  1129. {
  1130. if (string.IsNullOrWhiteSpace(m_assetLoader))
  1131. {
  1132. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not defined");
  1133. return;
  1134. }
  1135. IAssetLoader assetLoader = ServerUtils.LoadPlugin<IAssetLoader>(m_assetLoader, new object[] { });
  1136. if (assetLoader == null)
  1137. {
  1138. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not found");
  1139. return;
  1140. }
  1141. m_log.Info("[FLOTSAM ASSET CACHE] started deleting local default assets");
  1142. int count = 0;
  1143. assetLoader.ForEachDefaultXmlAsset(
  1144. m_assetLoaderArgs,
  1145. delegate (AssetBase a)
  1146. {
  1147. Expire(a.ID);
  1148. ++count;
  1149. });
  1150. m_log.InfoFormat("[FLOTSAM ASSET CACHE] deleted {0} local default assets", count);
  1151. }
  1152. #endregion
  1153. }
  1154. }