FlotsamAssetCache.cs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  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.Collections.Concurrent;
  31. using System.Reflection;
  32. using System.Runtime.Serialization.Formatters.Binary;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Timers;
  36. using log4net;
  37. using Nini.Config;
  38. using Mono.Addins;
  39. using OpenMetaverse;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Monitoring;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes;
  44. using OpenSim.Server.Base;
  45. using OpenSim.Services.Interfaces;
  46. namespace OpenSim.Region.CoreModules.Asset
  47. {
  48. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
  49. public class FlotsamAssetCache : ISharedRegionModule, IAssetCache, IAssetService
  50. {
  51. private struct WriteAssetInfo
  52. {
  53. public string filename;
  54. public AssetBase asset;
  55. public bool replace;
  56. }
  57. private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType);
  58. private bool m_Enabled;
  59. private bool m_timerRunning;
  60. private bool m_cleanupRunning;
  61. private const string m_ModuleName = "FlotsamAssetCache";
  62. private string m_CacheDirectory = "assetcache";
  63. private string m_assetLoader;
  64. private string m_assetLoaderArgs;
  65. private readonly char[] m_InvalidChars;
  66. private int m_LogLevel = 0;
  67. private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
  68. private ulong m_Requests;
  69. private ulong m_RequestsForInprogress;
  70. private ulong m_DiskHits;
  71. private ulong m_MemoryHits;
  72. private ulong m_weakRefHits;
  73. private static HashSet<string> m_CurrentlyWriting = new HashSet<string>();
  74. private static ObjectJobEngine m_assetFileWriteWorker = null;
  75. private static HashSet<string> m_defaultAssets = new HashSet<string>();
  76. private bool m_FileCacheEnabled = true;
  77. private ExpiringCacheOS<string, AssetBase> m_MemoryCache;
  78. private bool m_MemoryCacheEnabled = false;
  79. private ExpiringKey<string> m_negativeCache;
  80. private bool m_negativeCacheEnabled = true;
  81. // Expiration is expressed in hours.
  82. private double m_MemoryExpiration = 0.016;
  83. private const double m_DefaultFileExpiration = 48;
  84. // Negative cache is in seconds
  85. private int m_negativeExpiration = 120;
  86. private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
  87. private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(1.0);
  88. private static int m_CacheDirectoryTiers = 1;
  89. private static int m_CacheDirectoryTierLen = 3;
  90. private static int m_CacheWarnAt = 30000;
  91. private System.Timers.Timer m_CacheCleanTimer;
  92. private IAssetService m_AssetService;
  93. private List<Scene> m_Scenes = new List<Scene>();
  94. private readonly object timerLock = new object();
  95. private Dictionary<string,WeakReference> weakAssetReferences = new Dictionary<string, WeakReference>();
  96. private readonly object weakAssetReferencesLock = new object();
  97. private static bool m_updateFileTimeOnCacheHit = false;
  98. private static ExpiringKey<string> m_lastFileAccessTimeChange = null;
  99. public FlotsamAssetCache()
  100. {
  101. List<char> invalidChars = new List<char>();
  102. invalidChars.AddRange(Path.GetInvalidPathChars());
  103. invalidChars.AddRange(Path.GetInvalidFileNameChars());
  104. m_InvalidChars = invalidChars.ToArray();
  105. }
  106. public Type ReplaceableInterface
  107. {
  108. get { return null; }
  109. }
  110. public string Name
  111. {
  112. get { return m_ModuleName; }
  113. }
  114. public void Initialise(IConfigSource source)
  115. {
  116. IConfig moduleConfig = source.Configs["Modules"];
  117. if (moduleConfig != null)
  118. {
  119. string name = moduleConfig.GetString("AssetCaching", String.Empty);
  120. if (name == Name)
  121. {
  122. m_negativeCache = new ExpiringKey<string>(2000);
  123. m_Enabled = true;
  124. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
  125. IConfig assetConfig = source.Configs["AssetCache"];
  126. if (assetConfig == null)
  127. {
  128. m_log.Debug(
  129. "[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
  130. }
  131. else
  132. {
  133. m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
  134. m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_CacheDirectory);
  135. m_CacheDirectory = Path.GetFullPath(m_CacheDirectory);
  136. m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
  137. m_MemoryExpiration = assetConfig.GetDouble("MemoryCacheTimeout", m_MemoryExpiration);
  138. m_MemoryExpiration *= 3600.0; // config in hours to seconds
  139. m_negativeCacheEnabled = assetConfig.GetBoolean("NegativeCacheEnabled", m_negativeCacheEnabled);
  140. m_negativeExpiration = assetConfig.GetInt("NegativeCacheTimeout", m_negativeExpiration);
  141. m_updateFileTimeOnCacheHit = assetConfig.GetBoolean("UpdateFileTimeOnCacheHit", m_updateFileTimeOnCacheHit);
  142. m_updateFileTimeOnCacheHit &= m_FileCacheEnabled;
  143. m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
  144. m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
  145. m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
  146. m_FileExpirationCleanupTimer = TimeSpan.FromHours(
  147. assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
  148. m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
  149. m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
  150. m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
  151. }
  152. if(m_updateFileTimeOnCacheHit)
  153. m_lastFileAccessTimeChange = new ExpiringKey<string>(300000);
  154. if(m_MemoryCacheEnabled)
  155. m_MemoryCache = new ExpiringCacheOS<string, AssetBase>((int)m_MemoryExpiration * 500);
  156. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
  157. if (m_CacheDirectoryTiers < 1)
  158. m_CacheDirectoryTiers = 1;
  159. else if (m_CacheDirectoryTiers > 3)
  160. m_CacheDirectoryTiers = 3;
  161. if (m_CacheDirectoryTierLen < 1)
  162. m_CacheDirectoryTierLen = 1;
  163. else if (m_CacheDirectoryTierLen > 4)
  164. m_CacheDirectoryTierLen = 4;
  165. m_negativeExpiration *= 1000;
  166. assetConfig = source.Configs["AssetService"];
  167. if(assetConfig != null)
  168. {
  169. m_assetLoader = assetConfig.GetString("DefaultAssetLoader", String.Empty);
  170. m_assetLoaderArgs = assetConfig.GetString("AssetLoaderArgs", string.Empty);
  171. if (string.IsNullOrWhiteSpace(m_assetLoaderArgs))
  172. m_assetLoader = string.Empty;
  173. }
  174. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
  175. 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);
  176. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
  177. MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime(mm/dd/YYYY)>", "Purge cached assets older than the specified date/time", HandleConsoleCommand);
  178. if (!string.IsNullOrWhiteSpace(m_assetLoader))
  179. {
  180. 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);
  181. 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);
  182. }
  183. }
  184. }
  185. }
  186. public void PostInitialise()
  187. {
  188. }
  189. public void Close()
  190. {
  191. if(m_Scenes.Count <= 0)
  192. {
  193. lock (timerLock)
  194. {
  195. m_cleanupRunning = false;
  196. if (m_timerRunning)
  197. {
  198. m_timerRunning = false;
  199. m_CacheCleanTimer.Stop();
  200. m_CacheCleanTimer.Close();
  201. }
  202. if (m_assetFileWriteWorker != null)
  203. {
  204. m_assetFileWriteWorker.Dispose();
  205. m_assetFileWriteWorker = null;
  206. }
  207. }
  208. }
  209. }
  210. public void AddRegion(Scene scene)
  211. {
  212. if (m_Enabled)
  213. {
  214. scene.RegisterModuleInterface<IAssetCache>(this);
  215. m_Scenes.Add(scene);
  216. }
  217. }
  218. public void RemoveRegion(Scene scene)
  219. {
  220. if (m_Enabled)
  221. {
  222. scene.UnregisterModuleInterface<IAssetCache>(this);
  223. m_Scenes.Remove(scene);
  224. lock(timerLock)
  225. {
  226. if(m_Scenes.Count <= 0)
  227. {
  228. m_cleanupRunning = false;
  229. if (m_timerRunning)
  230. {
  231. m_timerRunning = false;
  232. m_CacheCleanTimer.Stop();
  233. m_CacheCleanTimer.Close();
  234. }
  235. if (m_assetFileWriteWorker != null)
  236. {
  237. m_assetFileWriteWorker.Dispose();
  238. m_assetFileWriteWorker = null;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. public void RegionLoaded(Scene scene)
  245. {
  246. if (m_Enabled)
  247. {
  248. if(m_AssetService == null)
  249. m_AssetService = scene.RequestModuleInterface<IAssetService>();
  250. lock(timerLock)
  251. {
  252. if(!m_timerRunning)
  253. {
  254. if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
  255. {
  256. m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds)
  257. {
  258. AutoReset = false
  259. };
  260. m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
  261. m_CacheCleanTimer.Start();
  262. m_timerRunning = true;
  263. }
  264. }
  265. if (m_FileCacheEnabled && m_assetFileWriteWorker == null)
  266. {
  267. m_assetFileWriteWorker = new ObjectJobEngine(ProcessWrites, "FloatsamCacheWriter", 1000, 1);
  268. }
  269. if (!string.IsNullOrWhiteSpace(m_assetLoader) && scene.RegionInfo.RegionID == m_Scenes[0].RegionInfo.RegionID)
  270. {
  271. IAssetLoader assetLoader = ServerUtils.LoadPlugin<IAssetLoader>(m_assetLoader, new object[] { });
  272. if (assetLoader != null)
  273. {
  274. HashSet<string> ids = new HashSet<string>();
  275. assetLoader.ForEachDefaultXmlAsset(
  276. m_assetLoaderArgs,
  277. delegate (AssetBase a)
  278. {
  279. Cache(a, true);
  280. ids.Add(a.ID);
  281. });
  282. m_defaultAssets = ids;
  283. }
  284. }
  285. }
  286. }
  287. }
  288. private void ProcessWrites(object o)
  289. {
  290. try
  291. {
  292. WriteAssetInfo wai = (WriteAssetInfo)o;
  293. WriteFileCache(wai.filename, wai.asset, wai.replace);
  294. wai.asset = null;
  295. Thread.Yield();
  296. }
  297. catch { }
  298. }
  299. ////////////////////////////////////////////////////////////
  300. // IAssetCache
  301. //
  302. private void UpdateWeakReference(string key, AssetBase asset)
  303. {
  304. lock(weakAssetReferencesLock)
  305. {
  306. if(weakAssetReferences.TryGetValue(key , out WeakReference aref))
  307. aref.Target = asset;
  308. else
  309. weakAssetReferences[key] = new WeakReference(asset);
  310. }
  311. }
  312. private void UpdateMemoryCache(string key, AssetBase asset)
  313. {
  314. m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
  315. }
  316. private void UpdateFileCache(string key, AssetBase asset, bool replace = false)
  317. {
  318. if(m_assetFileWriteWorker == null)
  319. return;
  320. string filename = GetFileName(key);
  321. try
  322. {
  323. // Once we start writing, make sure we flag that we're writing
  324. // that object to the cache so that we don't try to write the
  325. // same file multiple times.
  326. lock (m_CurrentlyWriting)
  327. {
  328. if (m_CurrentlyWriting.Contains(filename))
  329. return;
  330. else
  331. m_CurrentlyWriting.Add(filename);
  332. }
  333. if (m_assetFileWriteWorker != null)
  334. {
  335. WriteAssetInfo wai = new WriteAssetInfo()
  336. {
  337. filename = filename,
  338. asset = asset,
  339. replace = replace
  340. };
  341. m_assetFileWriteWorker.Enqueue(wai);
  342. }
  343. }
  344. catch (Exception e)
  345. {
  346. m_log.ErrorFormat(
  347. "[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
  348. asset.ID, e.Message, e.StackTrace);
  349. }
  350. }
  351. public void Cache(AssetBase asset, bool replace = false)
  352. {
  353. if (asset != null)
  354. {
  355. //m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
  356. UpdateWeakReference(asset.ID, asset);
  357. if (m_MemoryCacheEnabled)
  358. UpdateMemoryCache(asset.ID, asset);
  359. if (m_FileCacheEnabled)
  360. UpdateFileCache(asset.ID, asset, replace);
  361. if (m_negativeCacheEnabled)
  362. m_negativeCache.Remove(asset.ID);
  363. }
  364. }
  365. public void CacheNegative(string id)
  366. {
  367. if (m_negativeCacheEnabled)
  368. m_negativeCache.Add(id, m_negativeExpiration);
  369. }
  370. /// <summary>
  371. /// Updates the cached file with the current time.
  372. /// </summary>
  373. /// <param name="filename">Filename.</param>
  374. /// <returns><c>true</c>, if the update was successful, false otherwise.</returns>
  375. private static bool CheckUpdateFileLastAccessTime(string filename)
  376. {
  377. try
  378. {
  379. File.SetLastAccessTime(filename, DateTime.Now);
  380. if(m_lastFileAccessTimeChange != null)
  381. m_lastFileAccessTimeChange.Add(filename, 900000);
  382. return true;
  383. }
  384. catch (FileNotFoundException)
  385. {
  386. return false;
  387. }
  388. catch
  389. {
  390. return true; // ignore other errors
  391. }
  392. }
  393. private static void UpdateFileLastAccessTime(string filename)
  394. {
  395. try
  396. {
  397. if(!m_lastFileAccessTimeChange.ContainsKey(filename))
  398. {
  399. File.SetLastAccessTime(filename, DateTime.Now);
  400. m_lastFileAccessTimeChange.Add(filename, 900000);
  401. }
  402. }
  403. catch
  404. {
  405. }
  406. }
  407. private AssetBase GetFromWeakReference(string id)
  408. {
  409. AssetBase asset = null;
  410. lock(weakAssetReferencesLock)
  411. {
  412. if (weakAssetReferences.TryGetValue(id, out WeakReference aref))
  413. {
  414. asset = aref.Target as AssetBase;
  415. if(asset == null)
  416. weakAssetReferences.Remove(id);
  417. else
  418. m_weakRefHits++;
  419. }
  420. }
  421. return asset;
  422. }
  423. /// <summary>
  424. /// Try to get an asset from the in-memory cache.
  425. /// </summary>
  426. /// <param name="id"></param>
  427. /// <returns></returns>
  428. private AssetBase GetFromMemoryCache(string id)
  429. {
  430. if (m_MemoryCache.TryGetValue(id, out AssetBase asset))
  431. {
  432. m_MemoryHits++;
  433. return asset;
  434. }
  435. return null;
  436. }
  437. private bool CheckFromMemoryCache(string id)
  438. {
  439. return m_MemoryCache.Contains(id);
  440. }
  441. /// <summary>
  442. /// Try to get an asset from the file cache.
  443. /// </summary>
  444. /// <param name="id"></param>
  445. /// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
  446. private AssetBase GetFromFileCache(string id)
  447. {
  448. string filename = GetFileName(id);
  449. // Track how often we have the problem that an asset is requested while
  450. // it is still being downloaded by a previous request.
  451. if (m_CurrentlyWriting.Contains(filename))
  452. {
  453. m_RequestsForInprogress++;
  454. return null;
  455. }
  456. AssetBase asset = null;
  457. try
  458. {
  459. using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
  460. {
  461. if (stream.Length == 0) // Empty file will trigger exception below
  462. return null;
  463. BinaryFormatter bformatter = new BinaryFormatter();
  464. asset = (AssetBase)bformatter.Deserialize(stream);
  465. m_DiskHits++;
  466. }
  467. }
  468. catch (FileNotFoundException)
  469. {
  470. }
  471. catch (DirectoryNotFoundException)
  472. {
  473. }
  474. catch (System.Runtime.Serialization.SerializationException e)
  475. {
  476. m_log.WarnFormat(
  477. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  478. filename, id, e.Message, e.StackTrace);
  479. // If there was a problem deserializing the asset, the asset may
  480. // either be corrupted OR was serialized under an old format
  481. // {different version of AssetBase} -- we should attempt to
  482. // delete it and re-cache
  483. File.Delete(filename);
  484. }
  485. catch (Exception e)
  486. {
  487. m_log.WarnFormat(
  488. "[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
  489. filename, id, e.Message, e.StackTrace);
  490. }
  491. return asset;
  492. }
  493. private bool CheckFromFileCache(string id)
  494. {
  495. try
  496. {
  497. return File.Exists(GetFileName(id));
  498. }
  499. catch
  500. {
  501. }
  502. return false;
  503. }
  504. // For IAssetService
  505. public AssetBase Get(string id)
  506. {
  507. Get(id, out AssetBase asset);
  508. return asset;
  509. }
  510. public AssetBase Get(string id, string ForeignAssetService, bool dummy)
  511. {
  512. return null;
  513. }
  514. public bool Get(string id, out AssetBase asset)
  515. {
  516. asset = null;
  517. m_Requests++;
  518. if (id.Equals(UUID.ZeroString))
  519. return false;
  520. if (m_negativeCache.ContainsKey(id))
  521. return false;
  522. asset = GetFromWeakReference(id);
  523. if (asset != null)
  524. {
  525. if(m_updateFileTimeOnCacheHit)
  526. {
  527. string filename = GetFileName(id);
  528. UpdateFileLastAccessTime(filename);
  529. }
  530. if (m_MemoryCacheEnabled)
  531. UpdateMemoryCache(id, asset);
  532. return true;
  533. }
  534. if (m_MemoryCacheEnabled)
  535. {
  536. asset = GetFromMemoryCache(id);
  537. if(asset != null)
  538. {
  539. UpdateWeakReference(id,asset);
  540. if (m_updateFileTimeOnCacheHit)
  541. {
  542. string filename = GetFileName(id);
  543. UpdateFileLastAccessTime(filename);
  544. }
  545. return true;
  546. }
  547. }
  548. if (m_FileCacheEnabled)
  549. {
  550. asset = GetFromFileCache(id);
  551. if(asset != null)
  552. {
  553. UpdateWeakReference(id,asset);
  554. if (m_MemoryCacheEnabled)
  555. UpdateMemoryCache(id, asset);
  556. }
  557. }
  558. return true;
  559. }
  560. public bool GetFromMemory(string id, out AssetBase asset)
  561. {
  562. asset = null;
  563. m_Requests++;
  564. if (id.Equals(Util.UUIDZeroString))
  565. return false;
  566. if (m_negativeCache.ContainsKey(id))
  567. return false;
  568. asset = GetFromWeakReference(id);
  569. if (asset != null)
  570. {
  571. if (m_updateFileTimeOnCacheHit)
  572. {
  573. string filename = GetFileName(id);
  574. UpdateFileLastAccessTime(filename);
  575. }
  576. if (m_MemoryCacheEnabled)
  577. UpdateMemoryCache(id, asset);
  578. return true;
  579. }
  580. if (m_MemoryCacheEnabled)
  581. {
  582. asset = GetFromMemoryCache(id);
  583. if (asset != null)
  584. {
  585. UpdateWeakReference(id, asset);
  586. if (m_updateFileTimeOnCacheHit)
  587. {
  588. string filename = GetFileName(id);
  589. UpdateFileLastAccessTime(filename);
  590. }
  591. return true;
  592. }
  593. }
  594. return true;
  595. }
  596. public bool Check(string id)
  597. {
  598. if(GetFromWeakReference(id) != null)
  599. return true;
  600. if (m_MemoryCacheEnabled && CheckFromMemoryCache(id))
  601. return true;
  602. if (m_FileCacheEnabled && CheckFromFileCache(id))
  603. return true;
  604. return false;
  605. }
  606. // does not check negative cache
  607. public AssetBase GetCached(string id)
  608. {
  609. AssetBase asset = null;
  610. m_Requests++;
  611. asset = GetFromWeakReference(id);
  612. if (asset != null)
  613. {
  614. if (m_updateFileTimeOnCacheHit)
  615. {
  616. string filename = GetFileName(id);
  617. UpdateFileLastAccessTime(filename);
  618. }
  619. if (m_MemoryCacheEnabled)
  620. UpdateMemoryCache(id, asset);
  621. return asset;
  622. }
  623. if (m_MemoryCacheEnabled)
  624. {
  625. asset = GetFromMemoryCache(id);
  626. if (asset != null)
  627. {
  628. UpdateWeakReference(id, asset);
  629. if (m_updateFileTimeOnCacheHit)
  630. {
  631. string filename = GetFileName(id);
  632. UpdateFileLastAccessTime(filename);
  633. }
  634. return asset;
  635. }
  636. }
  637. if (m_FileCacheEnabled)
  638. {
  639. asset = GetFromFileCache(id);
  640. if (asset != null)
  641. {
  642. UpdateWeakReference(id, asset);
  643. if (m_MemoryCacheEnabled)
  644. UpdateMemoryCache(id, asset);
  645. }
  646. }
  647. return asset;
  648. }
  649. public void Expire(string id)
  650. {
  651. if (m_LogLevel >= 2)
  652. m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
  653. try
  654. {
  655. lock (weakAssetReferencesLock)
  656. weakAssetReferences.Remove(id);
  657. if (m_MemoryCacheEnabled)
  658. m_MemoryCache.Remove(id);
  659. if (m_negativeCacheEnabled)
  660. m_negativeCache.Remove(id);
  661. if (m_FileCacheEnabled)
  662. {
  663. string filename = GetFileName(id);
  664. File.Delete(filename);
  665. }
  666. }
  667. catch (Exception e)
  668. {
  669. if (m_LogLevel >= 2)
  670. m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
  671. id, e.Message, e.StackTrace);
  672. }
  673. }
  674. public void Clear()
  675. {
  676. if (m_LogLevel >= 2)
  677. m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
  678. if (m_FileCacheEnabled && Directory.Exists(m_CacheDirectory))
  679. {
  680. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  681. {
  682. try
  683. {
  684. Directory.Delete(dir, true);
  685. }
  686. catch { }
  687. }
  688. }
  689. if (m_MemoryCacheEnabled)
  690. {
  691. m_MemoryCache.Dispose();
  692. m_MemoryCache = new ExpiringCacheOS<string, AssetBase>((int)m_MemoryExpiration * 500);
  693. }
  694. if (m_negativeCacheEnabled)
  695. {
  696. m_negativeCache.Dispose();
  697. m_negativeCache = new ExpiringKey<string>(2000);
  698. }
  699. lock (weakAssetReferencesLock)
  700. weakAssetReferences = new Dictionary<string, WeakReference>();
  701. }
  702. private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
  703. {
  704. lock (timerLock)
  705. {
  706. if (!m_timerRunning || m_cleanupRunning || !Directory.Exists(m_CacheDirectory))
  707. return;
  708. m_cleanupRunning = true;
  709. }
  710. // Purge all files last accessed prior to this point
  711. DoCleanExpiredFiles(DateTime.Now - m_FileExpiration);
  712. }
  713. private void DoCleanExpiredFiles(DateTime purgeLine)
  714. {
  715. long heap = 0;
  716. //if (m_LogLevel >= 2)
  717. {
  718. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Start background expiring files older than {0}.", purgeLine);
  719. heap = GC.GetTotalMemory(false);
  720. }
  721. // An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
  722. // before cleaning up expired files we must scan the objects in the scene to make sure that we retain
  723. // such local assets if they have not been recently accessed.
  724. Dictionary<UUID,sbyte> gids = gatherSceneAssets();
  725. int cooldown = 0;
  726. m_log.Info("[FLOTSAM ASSET CACHE] start asset files expire");
  727. foreach (string subdir in Directory.GetDirectories(m_CacheDirectory))
  728. {
  729. if(!m_cleanupRunning)
  730. break;
  731. cooldown = CleanExpiredFiles(subdir, gids, purgeLine, cooldown);
  732. if (++cooldown >= 10)
  733. {
  734. Thread.Sleep(120);
  735. cooldown = 0;
  736. }
  737. }
  738. gids = null;
  739. lock (timerLock)
  740. {
  741. if (m_timerRunning)
  742. m_CacheCleanTimer.Start();
  743. m_cleanupRunning = false;
  744. }
  745. //if (m_LogLevel >= 2)
  746. {
  747. heap = GC.GetTotalMemory(false) - heap;
  748. double fheap = Math.Round((double)(heap / (1024 * 1024)), 3);
  749. m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Finished expiring files, heap delta: {0}MB.", fheap);
  750. }
  751. }
  752. /// <summary>
  753. /// Recurses through specified directory checking for asset files last
  754. /// accessed prior to the specified purge line and deletes them. Also
  755. /// removes empty tier directories.
  756. /// </summary>
  757. /// <param name="dir"></param>
  758. /// <param name="purgeTimeline"></param>
  759. private int CleanExpiredFiles(string dir, Dictionary<UUID, sbyte> gids, DateTime purgeTimeline, int cooldown)
  760. {
  761. try
  762. {
  763. if (!m_cleanupRunning)
  764. return cooldown;
  765. int dirSize = 0;
  766. // Recurse into lower tiers
  767. foreach (string subdir in Directory.GetDirectories(dir))
  768. {
  769. if (!m_cleanupRunning)
  770. return cooldown;
  771. ++dirSize;
  772. cooldown = CleanExpiredFiles(subdir, gids, purgeTimeline, cooldown);
  773. if (++cooldown > 10)
  774. {
  775. Thread.Sleep(60);
  776. cooldown = 0;
  777. }
  778. }
  779. foreach (string file in Directory.GetFiles(dir))
  780. {
  781. if (!m_cleanupRunning)
  782. return cooldown;
  783. ++dirSize;
  784. string id = Path.GetFileName(file);
  785. if (string.IsNullOrEmpty(id))
  786. continue; //??
  787. if (m_defaultAssets.Contains(id) ||(UUID.TryParse(id, out UUID uid) && gids.ContainsKey(uid)))
  788. {
  789. ++cooldown;
  790. continue;
  791. }
  792. if (File.GetLastAccessTime(file) < purgeTimeline)
  793. {
  794. try
  795. {
  796. File.Delete(file);
  797. lock (weakAssetReferencesLock)
  798. weakAssetReferences.Remove(id);
  799. }
  800. catch { }
  801. cooldown += 5;
  802. --dirSize;
  803. }
  804. if (++cooldown >= 20)
  805. {
  806. Thread.Sleep(60);
  807. cooldown = 0;
  808. }
  809. }
  810. // Check if a tier directory is empty, if so, delete it
  811. if (m_cleanupRunning && dirSize == 0)
  812. {
  813. try
  814. {
  815. Directory.Delete(dir);
  816. }
  817. catch { }
  818. cooldown += 5;
  819. if (cooldown >= 20)
  820. {
  821. Thread.Sleep(60);
  822. cooldown = 0;
  823. }
  824. }
  825. else if (dirSize >= m_CacheWarnAt)
  826. {
  827. m_log.WarnFormat(
  828. "[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
  829. dir, dirSize);
  830. }
  831. }
  832. catch (DirectoryNotFoundException)
  833. {
  834. // If we get here, another node on the same box has
  835. // already removed the directory. Continue with next.
  836. }
  837. catch (Exception e)
  838. {
  839. m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception {1}", dir, e.Message);
  840. }
  841. return cooldown;
  842. }
  843. /// <summary>
  844. /// Determines the filename for an AssetID stored in the file cache
  845. /// </summary>
  846. /// <param name="id"></param>
  847. /// <returns></returns>
  848. private string GetFileName(string id)
  849. {
  850. StringBuilder sb = osStringBuilderCache.Acquire();
  851. int indx = id.IndexOfAny(m_InvalidChars);
  852. if (indx >= 0)
  853. {
  854. sb.Append(id);
  855. int sublen = id.Length - indx;
  856. for(int i = 0; i < m_InvalidChars.Length; ++i)
  857. {
  858. sb.Replace(m_InvalidChars[i], '_', indx, sublen);
  859. }
  860. id = sb.ToString();
  861. sb.Clear();
  862. }
  863. if(m_CacheDirectoryTiers == 1)
  864. {
  865. sb.Append(id.Substring(0, m_CacheDirectoryTierLen));
  866. sb.Append(Path.DirectorySeparatorChar);
  867. }
  868. else
  869. {
  870. for (int p = 0; p < m_CacheDirectoryTiers * m_CacheDirectoryTierLen; p += m_CacheDirectoryTierLen)
  871. {
  872. sb.Append(id.Substring(p, m_CacheDirectoryTierLen));
  873. sb.Append(Path.DirectorySeparatorChar);
  874. }
  875. }
  876. sb.Append(id);
  877. return Path.Combine(m_CacheDirectory, osStringBuilderCache.GetStringAndRelease(sb));
  878. }
  879. /// <summary>
  880. /// Writes a file to the file cache, creating any necessary
  881. /// tier directories along the way
  882. /// </summary>
  883. /// <param name="filename"></param>
  884. /// <param name="asset"></param>
  885. private static void WriteFileCache(string filename, AssetBase asset, bool replace)
  886. {
  887. try
  888. {
  889. // If the file is already cached, don't cache it, just touch it so access time is updated
  890. if (!replace && File.Exists(filename))
  891. {
  892. if (m_updateFileTimeOnCacheHit)
  893. UpdateFileLastAccessTime(filename);
  894. return;
  895. }
  896. string directory = Path.GetDirectoryName(filename);
  897. string tempname = Path.Combine(directory, Path.GetRandomFileName());
  898. try
  899. {
  900. if (!Directory.Exists(directory))
  901. {
  902. Directory.CreateDirectory(directory);
  903. }
  904. using (Stream stream = File.Open(tempname, FileMode.Create))
  905. {
  906. BinaryFormatter bformatter = new BinaryFormatter();
  907. bformatter.Serialize(stream, asset);
  908. stream.Flush();
  909. }
  910. if(m_lastFileAccessTimeChange != null)
  911. m_lastFileAccessTimeChange.Add(filename, 900000);
  912. }
  913. catch (IOException e)
  914. {
  915. m_log.WarnFormat(
  916. "[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
  917. asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
  918. return;
  919. }
  920. catch (UnauthorizedAccessException)
  921. {
  922. }
  923. try
  924. {
  925. if(replace)
  926. File.Delete(filename);
  927. File.Move(tempname, filename);
  928. }
  929. catch
  930. {
  931. try
  932. {
  933. File.Delete(tempname);
  934. }
  935. catch{ }
  936. // If we see an IOException here it's likely that some other competing thread has written the
  937. // cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
  938. // signally by the earlier temporary file writing code.
  939. }
  940. }
  941. finally
  942. {
  943. // Even if the write fails with an exception, we need to make sure
  944. // that we release the lock on that file, otherwise it'll never get
  945. // cached
  946. lock (m_CurrentlyWriting)
  947. {
  948. m_CurrentlyWriting.Remove(filename);
  949. }
  950. }
  951. }
  952. /// <summary>
  953. /// Scan through the file cache, and return number of assets currently cached.
  954. /// </summary>
  955. /// <param name="dir"></param>
  956. /// <returns></returns>
  957. private int GetFileCacheCount(string dir)
  958. {
  959. try
  960. {
  961. int count = 0;
  962. int cooldown = 0;
  963. foreach (string subdir in Directory.GetDirectories(dir))
  964. {
  965. count += GetFileCacheCount(subdir);
  966. ++cooldown;
  967. if(cooldown > 50)
  968. {
  969. Thread.Sleep(100);
  970. cooldown = 0;
  971. }
  972. }
  973. return count + Directory.GetFiles(dir).Length;
  974. }
  975. catch
  976. {
  977. return 0;
  978. }
  979. }
  980. /// <summary>
  981. /// This notes the last time the Region had a deep asset scan performed on it.
  982. /// </summary>
  983. /// <param name="regionID"></param>
  984. private void StampRegionStatusFile(UUID regionID)
  985. {
  986. string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
  987. try
  988. {
  989. if (File.Exists(RegionCacheStatusFile))
  990. {
  991. File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
  992. }
  993. else
  994. {
  995. File.WriteAllText(
  996. RegionCacheStatusFile,
  997. "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
  998. }
  999. }
  1000. catch (Exception e)
  1001. {
  1002. m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception {1}",
  1003. regionID, e. Message);
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// Iterates through all Scenes, doing a deep scan through assets
  1008. /// to update the access time of all assets present in the scene or referenced by assets
  1009. /// in the scene.
  1010. /// </summary>
  1011. /// <param name="tryGetUncached">
  1012. /// If true, then assets scanned which are not found in cache are added to the cache.
  1013. /// </param>
  1014. /// <returns>Number of distinct asset references found in the scene.</returns>
  1015. private int TouchAllSceneAssets(bool tryGetUncached)
  1016. {
  1017. m_log.Info("[FLOTSAM ASSET CACHE] start touch files of assets in use");
  1018. Dictionary<UUID,sbyte> gatheredids = gatherSceneAssets();
  1019. int cooldown = 0;
  1020. foreach(UUID id in gatheredids.Keys)
  1021. {
  1022. if (!m_cleanupRunning)
  1023. break;
  1024. string idstr = id.ToString();
  1025. if (!CheckUpdateFileLastAccessTime(GetFileName(idstr)) && tryGetUncached)
  1026. {
  1027. cooldown += 5;
  1028. m_AssetService.Get(idstr);
  1029. }
  1030. if (++cooldown > 50)
  1031. {
  1032. Thread.Sleep(50);
  1033. cooldown = 0;
  1034. }
  1035. }
  1036. return gatheredids.Count;
  1037. }
  1038. private Dictionary<UUID, sbyte> gatherSceneAssets()
  1039. {
  1040. m_log.Info("[FLOTSAM ASSET CACHE] gather assets in use");
  1041. Dictionary<UUID, sbyte> gatheredids = new Dictionary<UUID, sbyte>();
  1042. UuidGatherer gatherer = new UuidGatherer(m_AssetService, gatheredids);
  1043. int cooldown = 0;
  1044. foreach (Scene s in m_Scenes)
  1045. {
  1046. gatherer.AddGathered(s.RegionInfo.RegionSettings.TerrainTexture1, (sbyte)AssetType.Texture);
  1047. gatherer.AddGathered(s.RegionInfo.RegionSettings.TerrainTexture2, (sbyte)AssetType.Texture);
  1048. gatherer.AddGathered(s.RegionInfo.RegionSettings.TerrainTexture3, (sbyte)AssetType.Texture);
  1049. gatherer.AddGathered(s.RegionInfo.RegionSettings.TerrainTexture4, (sbyte)AssetType.Texture);
  1050. gatherer.AddGathered(s.RegionInfo.RegionSettings.TerrainImageID, (sbyte)AssetType.Texture);
  1051. if (s.RegionEnvironment != null)
  1052. s.RegionEnvironment.GatherAssets(gatheredids);
  1053. if (s.LandChannel != null)
  1054. {
  1055. List<ILandObject> landObjects = s.LandChannel.AllParcels();
  1056. foreach (ILandObject lo in landObjects)
  1057. {
  1058. if (lo.LandData != null && lo.LandData.Environment != null)
  1059. lo.LandData.Environment.GatherAssets(gatheredids);
  1060. }
  1061. }
  1062. EntityBase[] entities = s.Entities.GetEntities();
  1063. for (int i = 0; i < entities.Length; ++i)
  1064. {
  1065. if (!m_cleanupRunning)
  1066. break;
  1067. EntityBase entity = entities[i];
  1068. if (entity is SceneObjectGroup)
  1069. {
  1070. SceneObjectGroup e = entity as SceneObjectGroup;
  1071. if (e == null || e.IsDeleted)
  1072. continue;
  1073. gatherer.AddForInspection(e);
  1074. while (gatherer.GatherNext())
  1075. {
  1076. if (++cooldown > 50)
  1077. {
  1078. Thread.Sleep(60);
  1079. cooldown = 0;
  1080. }
  1081. }
  1082. if (++cooldown > 25)
  1083. {
  1084. Thread.Sleep(60);
  1085. cooldown = 0;
  1086. }
  1087. }
  1088. else if( entity is ScenePresence)
  1089. {
  1090. ScenePresence sp = entity as ScenePresence;
  1091. if (sp == null || sp.IsChildAgent || sp.IsDeleted || sp.Appearance == null)
  1092. continue;
  1093. Primitive.TextureEntry Texture = sp.Appearance.Texture;
  1094. if (Texture == null)
  1095. continue;
  1096. Primitive.TextureEntryFace[] FaceTextures = Texture.FaceTextures;
  1097. if (FaceTextures == null)
  1098. continue;
  1099. for (int it = 0; it < AvatarAppearance.BAKE_INDICES.Length; it++)
  1100. {
  1101. int idx = AvatarAppearance.BAKE_INDICES[it];
  1102. if(idx < FaceTextures.Length)
  1103. {
  1104. Primitive.TextureEntryFace face = FaceTextures[idx];
  1105. if (face == null)
  1106. continue;
  1107. if (face.TextureID.IsZero() || face.TextureID.Equals(AppearanceManager.DEFAULT_AVATAR_TEXTURE))
  1108. continue;
  1109. gatherer.AddGathered(face.TextureID, (sbyte)AssetType.Texture);
  1110. }
  1111. }
  1112. }
  1113. }
  1114. entities = null;
  1115. if (!m_cleanupRunning)
  1116. break;
  1117. StampRegionStatusFile(s.RegionInfo.RegionID);
  1118. }
  1119. gatherer.GatherAll();
  1120. gatherer.FailedUUIDs.Clear();
  1121. gatherer.UncertainAssetsUUIDs.Clear();
  1122. gatherer = null;
  1123. m_log.InfoFormat("[FLOTSAM ASSET CACHE] found {0} possible assets in use (including {1} default assets)",
  1124. gatheredids.Count + m_defaultAssets.Count, m_defaultAssets.Count);
  1125. return gatheredids;
  1126. }
  1127. /// <summary>
  1128. /// Deletes all cache contents
  1129. /// </summary>
  1130. private void ClearFileCache()
  1131. {
  1132. if(!Directory.Exists(m_CacheDirectory))
  1133. return;
  1134. foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
  1135. {
  1136. try
  1137. {
  1138. Directory.Delete(dir, true);
  1139. }
  1140. catch (Exception e)
  1141. {
  1142. m_log.WarnFormat(
  1143. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
  1144. dir, m_CacheDirectory, e.Message, e.StackTrace);
  1145. }
  1146. }
  1147. foreach (string file in Directory.GetFiles(m_CacheDirectory))
  1148. {
  1149. try
  1150. {
  1151. File.Delete(file);
  1152. }
  1153. catch (Exception e)
  1154. {
  1155. m_log.WarnFormat(
  1156. "[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
  1157. file, m_CacheDirectory, e.Message, e.StackTrace);
  1158. }
  1159. }
  1160. }
  1161. private List<string> GenerateCacheHitReport()
  1162. {
  1163. List<string> outputLines = new List<string>();
  1164. double invReq = 100.0 / m_Requests;
  1165. double weakHitRate = m_weakRefHits * invReq;
  1166. int weakEntriesAlive = 0;
  1167. lock(weakAssetReferencesLock)
  1168. {
  1169. foreach(WeakReference aref in weakAssetReferences.Values)
  1170. {
  1171. if (aref.IsAlive)
  1172. ++weakEntriesAlive;
  1173. }
  1174. }
  1175. int weakEntries = weakAssetReferences.Count;
  1176. double fileHitRate = m_DiskHits * invReq;
  1177. double TotalHitRate = weakHitRate + fileHitRate;
  1178. outputLines.Add(
  1179. string.Format("Total requests: {0}", m_Requests));
  1180. outputLines.Add(
  1181. string.Format("unCollected Hit Rate: {0}% ({1} entries {2} alive)", weakHitRate.ToString("0.00"),weakEntries, weakEntriesAlive));
  1182. outputLines.Add(
  1183. string.Format("File Hit Rate: {0}%", fileHitRate.ToString("0.00")));
  1184. if (m_MemoryCacheEnabled)
  1185. {
  1186. double HitRate = m_MemoryHits * invReq;
  1187. outputLines.Add(
  1188. string.Format("Memory Hit Rate: {0}%", HitRate.ToString("0.00")));
  1189. TotalHitRate += HitRate;
  1190. }
  1191. outputLines.Add(
  1192. string.Format("Total Hit Rate: {0}%", TotalHitRate.ToString("0.00")));
  1193. outputLines.Add(
  1194. string.Format(
  1195. "Requests overlap during file writing: {0}", m_RequestsForInprogress));
  1196. return outputLines;
  1197. }
  1198. #region Console Commands
  1199. private void HandleConsoleCommand(string module, string[] cmdparams)
  1200. {
  1201. ICommandConsole con = MainConsole.Instance;
  1202. if (cmdparams.Length >= 2)
  1203. {
  1204. string cmd = cmdparams[1];
  1205. switch (cmd)
  1206. {
  1207. case "status":
  1208. {
  1209. WorkManager.RunInThreadPool(delegate
  1210. {
  1211. if (m_MemoryCacheEnabled)
  1212. con.Output("[FLOTSAM ASSET CACHE] Memory Cache: {0} assets", m_MemoryCache.Count);
  1213. else
  1214. con.Output("[FLOTSAM ASSET CACHE] Memory cache disabled");
  1215. if (m_FileCacheEnabled)
  1216. {
  1217. bool doingscan;
  1218. lock (timerLock)
  1219. {
  1220. doingscan = m_cleanupRunning;
  1221. }
  1222. if(doingscan)
  1223. {
  1224. con.Output("[FLOTSAM ASSET CACHE] a deep scan is in progress, skipping file cache assets count");
  1225. }
  1226. else
  1227. {
  1228. con.Output("[FLOTSAM ASSET CACHE] counting file cache assets");
  1229. int fileCount = GetFileCacheCount(m_CacheDirectory);
  1230. con.Output("[FLOTSAM ASSET CACHE] File Cache: {0} assets", fileCount);
  1231. }
  1232. }
  1233. else
  1234. {
  1235. con.Output("[FLOTSAM ASSET CACHE] File cache disabled");
  1236. }
  1237. GenerateCacheHitReport().ForEach(l => con.Output(l));
  1238. if (m_FileCacheEnabled)
  1239. {
  1240. con.Output("[FLOTSAM ASSET CACHE] Deep scans have previously been performed on the following regions:");
  1241. foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
  1242. {
  1243. int start = s.IndexOf('_');
  1244. int end = s.IndexOf('.');
  1245. if(start > 0 && end > 0)
  1246. {
  1247. string RegionID = s.Substring(start + 1, end - start);
  1248. DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
  1249. con.Output("[FLOTSAM ASSET CACHE] Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
  1250. }
  1251. }
  1252. }
  1253. }, null, "CacheStatus", false);
  1254. break;
  1255. }
  1256. case "clear":
  1257. if (cmdparams.Length < 2)
  1258. {
  1259. con.Output("Usage is fcache clear [file] [memory]");
  1260. break;
  1261. }
  1262. bool clearMemory = false, clearFile = false;
  1263. if (cmdparams.Length == 2)
  1264. {
  1265. clearMemory = true;
  1266. clearFile = true;
  1267. }
  1268. foreach (string s in cmdparams)
  1269. {
  1270. if (s.ToLower() == "memory")
  1271. clearMemory = true;
  1272. else if (s.ToLower() == "file")
  1273. clearFile = true;
  1274. }
  1275. if (clearMemory)
  1276. {
  1277. if (m_MemoryCacheEnabled)
  1278. {
  1279. m_MemoryCache.Clear();
  1280. con.Output("Memory cache cleared.");
  1281. }
  1282. else
  1283. {
  1284. con.Output("Memory cache not enabled.");
  1285. }
  1286. }
  1287. if (clearFile)
  1288. {
  1289. if (m_FileCacheEnabled)
  1290. {
  1291. ClearFileCache();
  1292. con.Output("File cache cleared.");
  1293. }
  1294. else
  1295. {
  1296. con.Output("File cache not enabled.");
  1297. }
  1298. }
  1299. break;
  1300. case "assets":
  1301. lock (timerLock)
  1302. {
  1303. if (m_cleanupRunning)
  1304. {
  1305. con.Output("Flotsam assets check already running");
  1306. return;
  1307. }
  1308. m_cleanupRunning = true;
  1309. }
  1310. con.Output("Flotsam Ensuring assets are cached for all scenes.");
  1311. WorkManager.RunInThreadPool(delegate
  1312. {
  1313. bool wasRunning= false;
  1314. lock(timerLock)
  1315. {
  1316. if(m_timerRunning)
  1317. {
  1318. m_CacheCleanTimer.Stop();
  1319. m_timerRunning = false;
  1320. wasRunning = true;
  1321. }
  1322. }
  1323. if (wasRunning)
  1324. Thread.Sleep(120);
  1325. int assetReferenceTotal = TouchAllSceneAssets(true);
  1326. lock(timerLock)
  1327. {
  1328. if(wasRunning)
  1329. {
  1330. m_CacheCleanTimer.Start();
  1331. m_timerRunning = true;
  1332. }
  1333. m_cleanupRunning = false;
  1334. }
  1335. con.Output("Completed check with {0} assets.", assetReferenceTotal);
  1336. }, null, "TouchAllSceneAssets", false);
  1337. break;
  1338. case "expire":
  1339. lock (timerLock)
  1340. {
  1341. if (m_cleanupRunning)
  1342. {
  1343. con.Output("Flotsam assets check already running");
  1344. return;
  1345. }
  1346. m_cleanupRunning = true;
  1347. }
  1348. if (cmdparams.Length < 3)
  1349. {
  1350. con.Output("Invalid parameters for Expire, please specify a valid date & time");
  1351. m_cleanupRunning = false;
  1352. break;
  1353. }
  1354. string s_expirationDate = "";
  1355. DateTime expirationDate;
  1356. if (cmdparams.Length > 3)
  1357. {
  1358. s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
  1359. }
  1360. else
  1361. {
  1362. s_expirationDate = cmdparams[2];
  1363. }
  1364. if(s_expirationDate.Equals("now", StringComparison.InvariantCultureIgnoreCase))
  1365. expirationDate = DateTime.Now;
  1366. else
  1367. {
  1368. if (!DateTime.TryParse(s_expirationDate, out expirationDate))
  1369. {
  1370. con.Output("{0} is not a valid date & time", cmd);
  1371. m_cleanupRunning = false;
  1372. break;
  1373. }
  1374. if (expirationDate >= DateTime.Now)
  1375. {
  1376. con.Output("{0} date & time must be in past", cmd);
  1377. m_cleanupRunning = false;
  1378. break;
  1379. }
  1380. }
  1381. if (m_FileCacheEnabled)
  1382. {
  1383. WorkManager.RunInThreadPool(delegate
  1384. {
  1385. bool wasRunning = false;
  1386. lock (timerLock)
  1387. {
  1388. if (m_timerRunning)
  1389. {
  1390. m_CacheCleanTimer.Stop();
  1391. m_timerRunning = false;
  1392. wasRunning = true;
  1393. }
  1394. }
  1395. if(wasRunning)
  1396. Thread.Sleep(120);
  1397. DoCleanExpiredFiles(expirationDate);
  1398. lock (timerLock)
  1399. {
  1400. if (wasRunning)
  1401. {
  1402. m_CacheCleanTimer.Start();
  1403. m_timerRunning = true;
  1404. }
  1405. m_cleanupRunning = false;
  1406. }
  1407. }, null, "ExpireSceneAssets", false);
  1408. }
  1409. else
  1410. con.Output("File cache not active, not clearing.");
  1411. break;
  1412. case "cachedefaultassets":
  1413. HandleLoadDefaultAssets();
  1414. break;
  1415. case "deletedefaultassets":
  1416. HandleDeleteDefaultAssets();
  1417. break;
  1418. default:
  1419. con.Output("Unknown command {0}", cmd);
  1420. break;
  1421. }
  1422. }
  1423. else if (cmdparams.Length == 1)
  1424. {
  1425. con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
  1426. con.Output("fcache expire <datetime> - Purge assets older than the specified date & time");
  1427. con.Output("fcache clear [file] [memory] - Remove cached assets");
  1428. con.Output("fcache status - Display cache status");
  1429. con.Output("fcache cachedefaultassets - loads default assets to cache replacing existent ones, this may override grid assets. Use with care");
  1430. con.Output("fcache deletedefaultassets - deletes default local assets from cache so they can be refreshed from grid");
  1431. }
  1432. }
  1433. #endregion
  1434. #region IAssetService Members
  1435. public AssetMetadata GetMetadata(string id)
  1436. {
  1437. Get(id, out AssetBase asset);
  1438. if (asset == null)
  1439. return null;
  1440. return asset.Metadata;
  1441. }
  1442. public byte[] GetData(string id)
  1443. {
  1444. Get(id, out AssetBase asset);
  1445. if (asset == null)
  1446. return null;
  1447. return asset.Data;
  1448. }
  1449. public bool Get(string id, object sender, AssetRetrieved handler)
  1450. {
  1451. if (!Get(id, out AssetBase asset))
  1452. return false;
  1453. handler(id, sender, asset);
  1454. return true;
  1455. }
  1456. public void Get(string id, string ForeignAssetService, bool StoreOnLocalGrid, SimpleAssetRetrieved callBack)
  1457. {
  1458. }
  1459. public bool[] AssetsExist(string[] ids)
  1460. {
  1461. bool[] exist = new bool[ids.Length];
  1462. for (int i = 0; i < ids.Length; i++)
  1463. {
  1464. exist[i] = Check(ids[i]);
  1465. }
  1466. return exist;
  1467. }
  1468. public string Store(AssetBase asset)
  1469. {
  1470. if (asset.FullID.IsZero())
  1471. {
  1472. asset.FullID = UUID.Random();
  1473. }
  1474. Cache(asset);
  1475. return asset.ID;
  1476. }
  1477. public bool UpdateContent(string id, byte[] data)
  1478. {
  1479. if (!Get(id, out AssetBase asset))
  1480. return false;
  1481. asset.Data = data;
  1482. Cache(asset, true);
  1483. return true;
  1484. }
  1485. public bool Delete(string id)
  1486. {
  1487. Expire(id);
  1488. return true;
  1489. }
  1490. private void HandleLoadDefaultAssets()
  1491. {
  1492. if (string.IsNullOrWhiteSpace(m_assetLoader))
  1493. {
  1494. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not defined");
  1495. return;
  1496. }
  1497. IAssetLoader assetLoader = ServerUtils.LoadPlugin<IAssetLoader>(m_assetLoader, new object[] { });
  1498. if (assetLoader == null)
  1499. {
  1500. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not found");
  1501. return;
  1502. }
  1503. m_log.Info("[FLOTSAM ASSET CACHE] start loading local default assets");
  1504. int count = 0;
  1505. HashSet<string> ids = new HashSet<string>();
  1506. assetLoader.ForEachDefaultXmlAsset(
  1507. m_assetLoaderArgs,
  1508. delegate (AssetBase a)
  1509. {
  1510. Cache(a, true);
  1511. ids.Add(a.ID);
  1512. ++count;
  1513. });
  1514. m_defaultAssets = ids;
  1515. m_log.InfoFormat("[FLOTSAM ASSET CACHE] loaded {0} local default assets", count);
  1516. }
  1517. private void HandleDeleteDefaultAssets()
  1518. {
  1519. if (string.IsNullOrWhiteSpace(m_assetLoader))
  1520. {
  1521. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not defined");
  1522. return;
  1523. }
  1524. IAssetLoader assetLoader = ServerUtils.LoadPlugin<IAssetLoader>(m_assetLoader, new object[] { });
  1525. if (assetLoader == null)
  1526. {
  1527. m_log.Info("[FLOTSAM ASSET CACHE] default assets loader not found");
  1528. return;
  1529. }
  1530. m_log.Info("[FLOTSAM ASSET CACHE] started deleting local default assets");
  1531. int count = 0;
  1532. assetLoader.ForEachDefaultXmlAsset(
  1533. m_assetLoaderArgs,
  1534. delegate (AssetBase a)
  1535. {
  1536. Expire(a.ID);
  1537. ++count;
  1538. });
  1539. m_defaultAssets = new HashSet<string>();
  1540. m_log.InfoFormat("[FLOTSAM ASSET CACHE] deleted {0} local default assets", count);
  1541. }
  1542. #endregion
  1543. }
  1544. }