FlotsamAssetCache.cs 61 KB

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