CenomeAssetCache.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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.Reflection;
  29. using log4net;
  30. using Nini.Config;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.Framework.Interfaces;
  33. using OpenSim.Region.Framework.Scenes;
  34. namespace OpenSim.Region.CoreModules.Asset
  35. {
  36. /// <summary>
  37. /// Cenome memory asset cache.
  38. /// </summary>
  39. /// <remarks>
  40. /// <para>
  41. /// Cache is enabled by setting "AssetCaching" configuration to value "CenomeMemoryAssetCache".
  42. /// When cache is successfully enable log should have message
  43. /// "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = XXX bytes, MaxCount = XXX, ExpirationTime = XXX)".
  44. /// </para>
  45. /// <para>
  46. /// Cache's size is limited by two parameters:
  47. /// maximal allowed size in bytes and maximal allowed asset count. When new asset
  48. /// is added to cache that have achieved either size or count limitation, cache
  49. /// will automatically remove less recently used assets from cache. Additionally
  50. /// asset's lifetime is controlled by expiration time.
  51. /// </para>
  52. /// <para>
  53. /// <list type="table">
  54. /// <listheader>
  55. /// <term>Configuration</term>
  56. /// <description>Description</description>
  57. /// </listheader>
  58. /// <item>
  59. /// <term>MaxSize</term>
  60. /// <description>Maximal size of the cache in bytes. Default value: 128MB (134 217 728 bytes).</description>
  61. /// </item>
  62. /// <item>
  63. /// <term>MaxCount</term>
  64. /// <description>Maximal count of assets stored to cache. Default value: 4096 assets.</description>
  65. /// </item>
  66. /// <item>
  67. /// <term>ExpirationTime</term>
  68. /// <description>Asset's expiration time in minutes. Default value: 30 minutes.</description>
  69. /// </item>
  70. /// </list>
  71. /// </para>
  72. /// </remarks>
  73. /// <example>
  74. /// Enabling Cenome Asset Cache:
  75. /// <code>
  76. /// [Modules]
  77. /// AssetCaching = "CenomeMemoryAssetCache"
  78. /// </code>
  79. /// Setting size and expiration time limitations:
  80. /// <code>
  81. /// [AssetCache]
  82. /// ; 256 MB (default: 134217728)
  83. /// MaxSize = 268435456
  84. /// ; How many assets it is possible to store cache (default: 4096)
  85. /// MaxCount = 16384
  86. /// ; Expiration time - 1 hour (default: 30 minutes)
  87. /// ExpirationTime = 60
  88. /// </code>
  89. /// </example>
  90. public class CenomeMemoryAssetCache : IImprovedAssetCache, ISharedRegionModule
  91. {
  92. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  93. /// <summary>
  94. /// Cache's default maximal asset count.
  95. /// </summary>
  96. /// <remarks>
  97. /// <para>
  98. /// Assuming that average asset size is about 32768 bytes.
  99. /// </para>
  100. /// </remarks>
  101. public const int DefaultMaxCount = 4096;
  102. /// <summary>
  103. /// Default maximal size of the cache in bytes
  104. /// </summary>
  105. /// <remarks>
  106. /// <para>
  107. /// 128MB = 128 * 1024^2 = 134 217 728 bytes.
  108. /// </para>
  109. /// </remarks>
  110. public const long DefaultMaxSize = 134217728;
  111. /// <summary>
  112. /// Asset's default expiration time in the cache.
  113. /// </summary>
  114. public static readonly TimeSpan DefaultExpirationTime = TimeSpan.FromMinutes(30.0);
  115. /// <summary>
  116. /// Cache object.
  117. /// </summary>
  118. private ICnmCache<string, AssetBase> m_cache;
  119. /// <summary>
  120. /// Count of cache commands
  121. /// </summary>
  122. private int m_cachedCount;
  123. /// <summary>
  124. /// How many gets before dumping statistics
  125. /// </summary>
  126. /// <remarks>
  127. /// If 0 or less, then disabled.
  128. /// </remarks>
  129. private int m_debugEpoch;
  130. /// <summary>
  131. /// Is Cenome asset cache enabled.
  132. /// </summary>
  133. private bool m_enabled;
  134. /// <summary>
  135. /// Count of get requests
  136. /// </summary>
  137. private int m_getCount;
  138. /// <summary>
  139. /// How many hits
  140. /// </summary>
  141. private int m_hitCount;
  142. /// <summary>
  143. /// Initialize asset cache module, with custom parameters.
  144. /// </summary>
  145. /// <param name="maximalSize">
  146. /// Cache's maximal size in bytes.
  147. /// </param>
  148. /// <param name="maximalCount">
  149. /// Cache's maximal count of assets.
  150. /// </param>
  151. /// <param name="expirationTime">
  152. /// Asset's expiration time.
  153. /// </param>
  154. protected void Initialize(long maximalSize, int maximalCount, TimeSpan expirationTime)
  155. {
  156. if (maximalSize <= 0 || maximalCount <= 0)
  157. {
  158. //m_log.Debug("[ASSET CACHE]: Cenome asset cache is not enabled.");
  159. m_enabled = false;
  160. return;
  161. }
  162. if (expirationTime <= TimeSpan.Zero)
  163. {
  164. // Disable expiration time
  165. expirationTime = TimeSpan.MaxValue;
  166. }
  167. // Create cache and add synchronization wrapper over it
  168. m_cache =
  169. CnmSynchronizedCache<string, AssetBase>.Synchronized(new CnmMemoryCache<string, AssetBase>(
  170. maximalSize, maximalCount, expirationTime));
  171. m_enabled = true;
  172. m_log.DebugFormat(
  173. "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = {0} bytes, MaxCount = {1}, ExpirationTime = {2})",
  174. maximalSize,
  175. maximalCount,
  176. expirationTime);
  177. }
  178. #region IImprovedAssetCache Members
  179. /// <summary>
  180. /// Cache asset.
  181. /// </summary>
  182. /// <param name="asset">
  183. /// The asset that is being cached.
  184. /// </param>
  185. public void Cache(AssetBase asset)
  186. {
  187. if (asset != null)
  188. {
  189. // m_log.DebugFormat("[CENOME ASSET CACHE]: Caching asset {0}", asset.ID);
  190. long size = asset.Data != null ? asset.Data.Length : 1;
  191. m_cache.Set(asset.ID, asset, size);
  192. m_cachedCount++;
  193. }
  194. }
  195. /// <summary>
  196. /// Clear asset cache.
  197. /// </summary>
  198. public void Clear()
  199. {
  200. m_cache.Clear();
  201. }
  202. /// <summary>
  203. /// Expire (remove) asset stored to cache.
  204. /// </summary>
  205. /// <param name="id">
  206. /// The expired asset's id.
  207. /// </param>
  208. public void Expire(string id)
  209. {
  210. m_cache.Remove(id);
  211. }
  212. /// <summary>
  213. /// Get asset stored
  214. /// </summary>
  215. /// <param name="id">
  216. /// The asset's id.
  217. /// </param>
  218. /// <returns>
  219. /// Asset if it is found from cache; otherwise <see langword="null"/>.
  220. /// </returns>
  221. /// <remarks>
  222. /// <para>
  223. /// Caller should always check that is return value <see langword="null"/>.
  224. /// Cache doesn't guarantee in any situation that asset is stored to it.
  225. /// </para>
  226. /// </remarks>
  227. public AssetBase Get(string id)
  228. {
  229. m_getCount++;
  230. AssetBase assetBase;
  231. if (m_cache.TryGetValue(id, out assetBase))
  232. m_hitCount++;
  233. if (m_getCount == m_debugEpoch)
  234. {
  235. m_log.DebugFormat(
  236. "[ASSET CACHE]: Cached = {0}, Get = {1}, Hits = {2}%, Size = {3} bytes, Avg. A. Size = {4} bytes",
  237. m_cachedCount,
  238. m_getCount,
  239. ((double) m_hitCount / m_getCount) * 100.0,
  240. m_cache.Size,
  241. m_cache.Size / m_cache.Count);
  242. m_getCount = 0;
  243. m_hitCount = 0;
  244. m_cachedCount = 0;
  245. }
  246. // if (null == assetBase)
  247. // m_log.DebugFormat("[CENOME ASSET CACHE]: Asset {0} not in cache", id);
  248. return assetBase;
  249. }
  250. #endregion
  251. #region ISharedRegionModule Members
  252. /// <summary>
  253. /// Gets region module's name.
  254. /// </summary>
  255. public string Name
  256. {
  257. get { return "CenomeMemoryAssetCache"; }
  258. }
  259. public Type ReplaceableInterface
  260. {
  261. get { return null; }
  262. }
  263. /// <summary>
  264. /// New region is being added to server.
  265. /// </summary>
  266. /// <param name="scene">
  267. /// Region's scene.
  268. /// </param>
  269. public void AddRegion(Scene scene)
  270. {
  271. if (m_enabled)
  272. scene.RegisterModuleInterface<IImprovedAssetCache>(this);
  273. }
  274. /// <summary>
  275. /// Close region module.
  276. /// </summary>
  277. public void Close()
  278. {
  279. m_enabled = false;
  280. m_cache.Clear();
  281. m_cache = null;
  282. }
  283. /// <summary>
  284. /// Initialize region module.
  285. /// </summary>
  286. /// <param name="source">
  287. /// Configuration source.
  288. /// </param>
  289. public void Initialise(IConfigSource source)
  290. {
  291. m_cache = null;
  292. m_enabled = false;
  293. IConfig moduleConfig = source.Configs[ "Modules" ];
  294. if (moduleConfig == null)
  295. return;
  296. string name = moduleConfig.GetString("AssetCaching");
  297. //m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name);
  298. if (name != Name)
  299. return;
  300. long maxSize = DefaultMaxSize;
  301. int maxCount = DefaultMaxCount;
  302. TimeSpan expirationTime = DefaultExpirationTime;
  303. IConfig assetConfig = source.Configs["AssetCache"];
  304. if (assetConfig != null)
  305. {
  306. // Get optional configurations
  307. maxSize = assetConfig.GetLong("MaxSize", DefaultMaxSize);
  308. maxCount = assetConfig.GetInt("MaxCount", DefaultMaxCount);
  309. expirationTime =
  310. TimeSpan.FromMinutes(assetConfig.GetInt("ExpirationTime", (int)DefaultExpirationTime.TotalMinutes));
  311. // Debugging purposes only
  312. m_debugEpoch = assetConfig.GetInt("DebugEpoch", 0);
  313. }
  314. Initialize(maxSize, maxCount, expirationTime);
  315. }
  316. /// <summary>
  317. /// Initialization post handling.
  318. /// </summary>
  319. /// <remarks>
  320. /// <para>
  321. /// Modules can use this to initialize connection with other modules.
  322. /// </para>
  323. /// </remarks>
  324. public void PostInitialise()
  325. {
  326. }
  327. /// <summary>
  328. /// Region has been loaded.
  329. /// </summary>
  330. /// <param name="scene">
  331. /// Region's scene.
  332. /// </param>
  333. /// <remarks>
  334. /// <para>
  335. /// This is needed for all module types. Modules will register
  336. /// Interfaces with scene in AddScene, and will also need a means
  337. /// to access interfaces registered by other modules. Without
  338. /// this extra method, a module attempting to use another modules'
  339. /// interface would be successful only depending on load order,
  340. /// which can't be depended upon, or modules would need to resort
  341. /// to ugly kludges to attempt to request interfaces when needed
  342. /// and unnecessary caching logic repeated in all modules.
  343. /// The extra function stub is just that much cleaner.
  344. /// </para>
  345. /// </remarks>
  346. public void RegionLoaded(Scene scene)
  347. {
  348. }
  349. /// <summary>
  350. /// Region is being removed.
  351. /// </summary>
  352. /// <param name="scene">
  353. /// Region scene that is being removed.
  354. /// </param>
  355. public void RemoveRegion(Scene scene)
  356. {
  357. }
  358. #endregion
  359. }
  360. }