AssetsRequest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.Collections.Generic;
  29. using System.Reflection;
  30. using System.Threading;
  31. using System.Timers;
  32. using log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Serialization;
  36. using OpenSim.Framework.Serialization.External;
  37. using OpenSim.Services.Interfaces;
  38. namespace OpenSim.Region.CoreModules.World.Archiver
  39. {
  40. /// <summary>
  41. /// Encapsulate the asynchronous requests for the assets required for an archive operation
  42. /// </summary>
  43. class AssetsRequest
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. enum RequestState
  47. {
  48. Initial,
  49. Running,
  50. Completed,
  51. Aborted
  52. };
  53. /// <value>
  54. /// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them
  55. /// from the asset service
  56. /// </value>
  57. protected const int TIMEOUT = 60 * 1000;
  58. /// <value>
  59. /// If a timeout does occur, limit the amount of UUID information put to the console.
  60. /// </value>
  61. protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3;
  62. protected System.Timers.Timer m_requestCallbackTimer;
  63. /// <value>
  64. /// State of this request
  65. /// </value>
  66. private RequestState m_requestState = RequestState.Initial;
  67. /// <value>
  68. /// uuids to request
  69. /// </value>
  70. protected IDictionary<UUID, AssetType> m_uuids;
  71. /// <value>
  72. /// Callback used when all the assets requested have been received.
  73. /// </value>
  74. protected AssetsRequestCallback m_assetsRequestCallback;
  75. /// <value>
  76. /// List of assets that were found. This will be passed back to the requester.
  77. /// </value>
  78. protected List<UUID> m_foundAssetUuids = new List<UUID>();
  79. /// <value>
  80. /// Maintain a list of assets that could not be found. This will be passed back to the requester.
  81. /// </value>
  82. protected List<UUID> m_notFoundAssetUuids = new List<UUID>();
  83. /// <value>
  84. /// Record the number of asset replies required so we know when we've finished
  85. /// </value>
  86. private int m_repliesRequired;
  87. /// <value>
  88. /// Asset service used to request the assets
  89. /// </value>
  90. protected IAssetService m_assetService;
  91. protected IUserAccountService m_userAccountService;
  92. protected UUID m_scopeID; // the grid ID
  93. protected AssetsArchiver m_assetsArchiver;
  94. protected Dictionary<string, object> m_options;
  95. protected internal AssetsRequest(
  96. AssetsArchiver assetsArchiver, IDictionary<UUID, AssetType> uuids,
  97. IAssetService assetService, IUserAccountService userService,
  98. UUID scope, Dictionary<string, object> options,
  99. AssetsRequestCallback assetsRequestCallback)
  100. {
  101. m_assetsArchiver = assetsArchiver;
  102. m_uuids = uuids;
  103. m_assetsRequestCallback = assetsRequestCallback;
  104. m_assetService = assetService;
  105. m_userAccountService = userService;
  106. m_scopeID = scope;
  107. m_options = options;
  108. m_repliesRequired = uuids.Count;
  109. m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT);
  110. m_requestCallbackTimer.AutoReset = false;
  111. m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout);
  112. }
  113. protected internal void Execute()
  114. {
  115. m_requestState = RequestState.Running;
  116. m_log.DebugFormat("[ARCHIVER]: AssetsRequest executed looking for {0} assets", m_repliesRequired);
  117. // We can stop here if there are no assets to fetch
  118. if (m_repliesRequired == 0)
  119. {
  120. m_requestState = RequestState.Completed;
  121. PerformAssetsRequestCallback(null);
  122. return;
  123. }
  124. foreach (KeyValuePair<UUID, AssetType> kvp in m_uuids)
  125. {
  126. m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback);
  127. }
  128. m_requestCallbackTimer.Enabled = true;
  129. }
  130. protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args)
  131. {
  132. try
  133. {
  134. lock (this)
  135. {
  136. // Take care of the possibilty that this thread started but was paused just outside the lock before
  137. // the final request came in (assuming that such a thing is possible)
  138. if (m_requestState == RequestState.Completed)
  139. return;
  140. m_requestState = RequestState.Aborted;
  141. }
  142. // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure
  143. // case anyway.
  144. List<UUID> uuids = new List<UUID>();
  145. foreach (UUID uuid in m_uuids.Keys)
  146. {
  147. uuids.Add(uuid);
  148. }
  149. foreach (UUID uuid in m_foundAssetUuids)
  150. {
  151. uuids.Remove(uuid);
  152. }
  153. foreach (UUID uuid in m_notFoundAssetUuids)
  154. {
  155. uuids.Remove(uuid);
  156. }
  157. m_log.ErrorFormat(
  158. "[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count);
  159. int i = 0;
  160. foreach (UUID uuid in uuids)
  161. {
  162. m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid);
  163. if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT)
  164. break;
  165. }
  166. if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT)
  167. m_log.ErrorFormat(
  168. "[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT);
  169. m_log.Error("[ARCHIVER]: Archive save aborted. PLEASE DO NOT USE THIS ARCHIVE, IT WILL BE INCOMPLETE.");
  170. }
  171. catch (Exception e)
  172. {
  173. m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}{1}", e.Message, e.StackTrace);
  174. }
  175. finally
  176. {
  177. m_assetsArchiver.ForceClose();
  178. }
  179. }
  180. protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)
  181. {
  182. // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
  183. if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)
  184. {
  185. AssetType type = (AssetType)assetType;
  186. m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, type);
  187. fetchedAsset.Type = (sbyte)type;
  188. }
  189. AssetRequestCallback(fetchedAssetID, this, fetchedAsset);
  190. }
  191. /// <summary>
  192. /// Called back by the asset cache when it has the asset
  193. /// </summary>
  194. /// <param name="assetID"></param>
  195. /// <param name="asset"></param>
  196. public void AssetRequestCallback(string id, object sender, AssetBase asset)
  197. {
  198. Culture.SetCurrentCulture();
  199. try
  200. {
  201. lock (this)
  202. {
  203. //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id);
  204. m_requestCallbackTimer.Stop();
  205. if (m_requestState == RequestState.Aborted)
  206. {
  207. m_log.WarnFormat(
  208. "[ARCHIVER]: Received information about asset {0} after archive save abortion. Ignoring.",
  209. id);
  210. return;
  211. }
  212. if (asset != null)
  213. {
  214. if (m_options.ContainsKey("verbose"))
  215. m_log.InfoFormat("[ARCHIVER]: Writing asset {0}", id);
  216. m_foundAssetUuids.Add(asset.FullID);
  217. m_assetsArchiver.WriteAsset(PostProcess(asset));
  218. }
  219. else
  220. {
  221. if (m_options.ContainsKey("verbose"))
  222. m_log.InfoFormat("[ARCHIVER]: Recording asset {0} as not found", id);
  223. m_notFoundAssetUuids.Add(new UUID(id));
  224. }
  225. if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count == m_repliesRequired)
  226. {
  227. m_requestState = RequestState.Completed;
  228. m_log.DebugFormat(
  229. "[ARCHIVER]: Successfully added {0} assets ({1} assets notified missing)",
  230. m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);
  231. // We want to stop using the asset cache thread asap
  232. // as we now need to do the work of producing the rest of the archive
  233. Util.FireAndForget(PerformAssetsRequestCallback);
  234. }
  235. else
  236. {
  237. m_requestCallbackTimer.Start();
  238. }
  239. }
  240. }
  241. catch (Exception e)
  242. {
  243. m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e);
  244. }
  245. }
  246. /// <summary>
  247. /// Perform the callback on the original requester of the assets
  248. /// </summary>
  249. protected void PerformAssetsRequestCallback(object o)
  250. {
  251. Culture.SetCurrentCulture();
  252. try
  253. {
  254. m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids);
  255. }
  256. catch (Exception e)
  257. {
  258. m_log.ErrorFormat(
  259. "[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}", e);
  260. }
  261. }
  262. protected AssetBase PostProcess(AssetBase asset)
  263. {
  264. if (asset.Type == (sbyte)AssetType.Object && asset.Data != null && m_options.ContainsKey("profile"))
  265. {
  266. //m_log.DebugFormat("[ARCHIVER]: Rewriting object data for {0}", asset.ID);
  267. string xml = ExternalRepresentationUtils.RewriteSOP(Utils.BytesToString(asset.Data), m_options["profile"].ToString(), m_userAccountService, m_scopeID);
  268. asset.Data = Utils.StringToBytes(xml);
  269. }
  270. return asset;
  271. }
  272. }
  273. }