AssetsRequest.cs 13 KB

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