AssetsRequest.cs 14 KB

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