AssetsRequest.cs 14 KB

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