AssetsRequest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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, bool timedOut);
  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(false);
  131. return;
  132. }
  133. m_requestCallbackTimer.Enabled = true;
  134. foreach (KeyValuePair<UUID, AssetType> kvp in m_uuids)
  135. {
  136. // m_log.DebugFormat("[ARCHIVER]: Requesting asset {0}", kvp.Key);
  137. // m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback);
  138. AssetBase asset = m_assetService.Get(kvp.Key.ToString());
  139. PreAssetRequestCallback(kvp.Key.ToString(), kvp.Value, asset);
  140. }
  141. }
  142. protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args)
  143. {
  144. bool timedOut = true;
  145. try
  146. {
  147. lock (this)
  148. {
  149. // Take care of the possibilty that this thread started but was paused just outside the lock before
  150. // the final request came in (assuming that such a thing is possible)
  151. if (m_requestState == RequestState.Completed)
  152. {
  153. timedOut = false;
  154. return;
  155. }
  156. m_requestState = RequestState.Aborted;
  157. }
  158. // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure
  159. // case anyway.
  160. List<UUID> uuids = new List<UUID>();
  161. foreach (UUID uuid in m_uuids.Keys)
  162. {
  163. uuids.Add(uuid);
  164. }
  165. foreach (UUID uuid in m_foundAssetUuids)
  166. {
  167. uuids.Remove(uuid);
  168. }
  169. foreach (UUID uuid in m_notFoundAssetUuids)
  170. {
  171. uuids.Remove(uuid);
  172. }
  173. m_log.ErrorFormat(
  174. "[ARCHIVER]: Asset service failed to return information about {0} requested assets", uuids.Count);
  175. int i = 0;
  176. foreach (UUID uuid in uuids)
  177. {
  178. m_log.ErrorFormat("[ARCHIVER]: No information about asset {0} received", uuid);
  179. if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT)
  180. break;
  181. }
  182. if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT)
  183. m_log.ErrorFormat(
  184. "[ARCHIVER]: (... {0} more not shown)", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT);
  185. m_log.Error("[ARCHIVER]: Archive save aborted. PLEASE DO NOT USE THIS ARCHIVE, IT WILL BE INCOMPLETE.");
  186. }
  187. catch (Exception e)
  188. {
  189. m_log.ErrorFormat("[ARCHIVER]: Timeout handler exception {0}{1}", e.Message, e.StackTrace);
  190. }
  191. finally
  192. {
  193. if (timedOut)
  194. Util.FireAndForget(PerformAssetsRequestCallback, true);
  195. }
  196. }
  197. protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)
  198. {
  199. // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer
  200. if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)
  201. {
  202. AssetType type = (AssetType)assetType;
  203. m_log.InfoFormat("[ARCHIVER]: Rewriting broken asset type for {0} to {1}", fetchedAsset.ID, type);
  204. fetchedAsset.Type = (sbyte)type;
  205. }
  206. AssetRequestCallback(fetchedAssetID, this, fetchedAsset);
  207. }
  208. /// <summary>
  209. /// Called back by the asset cache when it has the asset
  210. /// </summary>
  211. /// <param name="assetID"></param>
  212. /// <param name="asset"></param>
  213. public void AssetRequestCallback(string id, object sender, AssetBase asset)
  214. {
  215. Culture.SetCurrentCulture();
  216. try
  217. {
  218. lock (this)
  219. {
  220. //m_log.DebugFormat("[ARCHIVER]: Received callback for asset {0}", id);
  221. m_requestCallbackTimer.Stop();
  222. if ((m_requestState == RequestState.Aborted) || (m_requestState == RequestState.Completed))
  223. {
  224. m_log.WarnFormat(
  225. "[ARCHIVER]: Received information about asset {0} while in state {1}. Ignoring.",
  226. id, m_requestState);
  227. return;
  228. }
  229. if (asset != null)
  230. {
  231. if (m_options.ContainsKey("verbose"))
  232. m_log.InfoFormat("[ARCHIVER]: Writing asset {0}", id);
  233. m_foundAssetUuids.Add(asset.FullID);
  234. m_assetsArchiver.WriteAsset(PostProcess(asset));
  235. }
  236. else
  237. {
  238. if (m_options.ContainsKey("verbose"))
  239. m_log.InfoFormat("[ARCHIVER]: Recording asset {0} as not found", id);
  240. m_notFoundAssetUuids.Add(new UUID(id));
  241. }
  242. if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count >= m_repliesRequired)
  243. {
  244. m_requestState = RequestState.Completed;
  245. m_log.DebugFormat(
  246. "[ARCHIVER]: Successfully added {0} assets ({1} assets not found but these may be expected invalid references)",
  247. m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);
  248. // We want to stop using the asset cache thread asap
  249. // as we now need to do the work of producing the rest of the archive
  250. Util.FireAndForget(PerformAssetsRequestCallback, false);
  251. }
  252. else
  253. {
  254. m_requestCallbackTimer.Start();
  255. }
  256. }
  257. }
  258. catch (Exception e)
  259. {
  260. m_log.ErrorFormat("[ARCHIVER]: AssetRequestCallback failed with {0}", e);
  261. }
  262. }
  263. /// <summary>
  264. /// Perform the callback on the original requester of the assets
  265. /// </summary>
  266. protected void PerformAssetsRequestCallback(object o)
  267. {
  268. Culture.SetCurrentCulture();
  269. Boolean timedOut = (Boolean)o;
  270. try
  271. {
  272. m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids, timedOut);
  273. }
  274. catch (Exception e)
  275. {
  276. m_log.ErrorFormat(
  277. "[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}", e);
  278. }
  279. }
  280. protected AssetBase PostProcess(AssetBase asset)
  281. {
  282. if (asset.Type == (sbyte)AssetType.Object && asset.Data != null && m_options.ContainsKey("home"))
  283. {
  284. //m_log.DebugFormat("[ARCHIVER]: Rewriting object data for {0}", asset.ID);
  285. string xml = ExternalRepresentationUtils.RewriteSOP(Utils.BytesToString(asset.Data), m_options["home"].ToString(), m_userAccountService, m_scopeID);
  286. asset.Data = Utils.StringToBytes(xml);
  287. }
  288. return asset;
  289. }
  290. }
  291. }