HGAssetMapper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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.Text;
  31. using log4net;
  32. using OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Framework.Serialization.External;
  35. using OpenSim.Region.Framework.Scenes;
  36. using OpenSim.Services.Interfaces;
  37. namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
  38. {
  39. public class HGAssetMapper
  40. {
  41. #region Fields
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. // This maps between inventory server urls and inventory server clients
  44. // private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
  45. private Scene m_scene;
  46. private string m_HomeURI;
  47. #endregion
  48. #region Constructor
  49. public HGAssetMapper(Scene scene, string homeURL)
  50. {
  51. m_scene = scene;
  52. m_HomeURI = homeURL;
  53. }
  54. #endregion
  55. #region Internal functions
  56. private AssetMetadata FetchMetadata(string url, UUID assetID)
  57. {
  58. if (string.IsNullOrEmpty(url))
  59. return null;
  60. if (!url.EndsWith("/") && !url.EndsWith("="))
  61. url = url + "/";
  62. AssetMetadata meta = m_scene.AssetService.GetMetadata(url + assetID.ToString());
  63. if (meta != null)
  64. m_log.DebugFormat("[HG ASSET MAPPER]: Fetched metadata for asset {0} of type {1} from {2} ", assetID, meta.Type, url);
  65. else
  66. m_log.DebugFormat("[HG ASSET MAPPER]: Unable to fetched metadata for asset {0} from {1} ", assetID, url);
  67. return meta;
  68. }
  69. private AssetBase FetchAsset(string url, UUID assetID)
  70. {
  71. // Test if it's already here
  72. AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
  73. if (asset == null)
  74. {
  75. if (string.IsNullOrEmpty(url))
  76. return null;
  77. if (!url.EndsWith("/") && !url.EndsWith("="))
  78. url = url + "/";
  79. asset = m_scene.AssetService.Get(url + assetID.ToString());
  80. //if (asset != null)
  81. // m_log.DebugFormat("[HG ASSET MAPPER]: Fetched asset {0} of type {1} from {2} ", assetID, asset.Metadata.Type, url);
  82. //else
  83. // m_log.DebugFormat("[HG ASSET MAPPER]: Unable to fetch asset {0} from {1} ", assetID, url);
  84. }
  85. return asset;
  86. }
  87. public bool PostAsset(string url, AssetBase asset, bool verbose = true)
  88. {
  89. if (asset == null)
  90. {
  91. m_log.Warn("[HG ASSET MAPPER]: Tried to post asset to remote server, but asset not in local cache.");
  92. return false;
  93. }
  94. if (string.IsNullOrEmpty(url))
  95. return false;
  96. if (!url.EndsWith("/") && !url.EndsWith("="))
  97. url = url + "/";
  98. // See long comment in AssetCache.AddAsset
  99. if (asset.Temporary || asset.Local)
  100. return true;
  101. // We need to copy the asset into a new asset, because
  102. // we need to set its ID to be URL+UUID, so that the
  103. // HGAssetService dispatches it to the remote grid.
  104. // It's not pretty, but the best that can be done while
  105. // not having a global naming infrastructure
  106. AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type, asset.Metadata.CreatorID);
  107. Copy(asset, asset1);
  108. asset1.ID = url + asset.ID;
  109. AdjustIdentifiers(asset1.Metadata);
  110. if (asset1.Metadata.Type == (sbyte)AssetType.Object)
  111. asset1.Data = AdjustIdentifiers(asset.Data);
  112. else
  113. asset1.Data = asset.Data;
  114. string id = m_scene.AssetService.Store(asset1);
  115. if (String.IsNullOrEmpty(id))
  116. {
  117. if (verbose)
  118. m_log.DebugFormat("[HG ASSET MAPPER]: Asset server {0} did not accept {1}", url, asset.ID);
  119. return false;
  120. }
  121. if (verbose)
  122. m_log.DebugFormat("[HG ASSET MAPPER]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
  123. return true;
  124. }
  125. private void Copy(AssetBase from, AssetBase to)
  126. {
  127. //to.Data = from.Data; // don't copy this, it's copied elsewhere
  128. to.Description = from.Description;
  129. to.FullID = from.FullID;
  130. to.ID = from.ID;
  131. to.Local = from.Local;
  132. to.Name = from.Name;
  133. to.Temporary = from.Temporary;
  134. to.Type = from.Type;
  135. }
  136. private void AdjustIdentifiers(AssetMetadata meta)
  137. {
  138. if (!string.IsNullOrEmpty(meta.CreatorID))
  139. {
  140. if(UUID.TryParse(meta.CreatorID, out UUID uuid))
  141. {
  142. UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
  143. if (creator != null)
  144. meta.CreatorID = m_HomeURI + ";" + creator.FirstName + " " + creator.LastName;
  145. }
  146. }
  147. }
  148. protected byte[] AdjustIdentifiers(byte[] data)
  149. {
  150. string xml = Utils.BytesToString(data);
  151. return Utils.StringToBytes(RewriteSOP(xml));
  152. }
  153. protected string RewriteSOP(string xmlData)
  154. {
  155. // Console.WriteLine("Input XML [{0}]", xmlData);
  156. return ExternalRepresentationUtils.RewriteSOP(xmlData, m_scene.Name, m_HomeURI, m_scene.UserAccountService, m_scene.RegionInfo.ScopeID);
  157. }
  158. // TODO: unused
  159. // private void Dump(Dictionary<UUID, bool> lst)
  160. // {
  161. // m_log.Debug("XXX -------- UUID DUMP ------- XXX");
  162. // foreach (KeyValuePair<UUID, bool> kvp in lst)
  163. // m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")");
  164. // m_log.Debug("XXX -------- UUID DUMP ------- XXX");
  165. // }
  166. #endregion
  167. #region Public interface
  168. public void Get(UUID assetID, UUID ownerID, string userAssetURL)
  169. {
  170. // Get the item from the remote asset server onto the local AssetService
  171. AssetMetadata meta = FetchMetadata(userAssetURL, assetID);
  172. if (meta == null)
  173. return;
  174. // The act of gathering UUIDs downloads some assets from the remote server
  175. // but not all...
  176. HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, userAssetURL);
  177. uuidGatherer.AddForInspection(assetID);
  178. uuidGatherer.GatherAll();
  179. m_log.DebugFormat("[HG ASSET MAPPER]: Preparing to get {0} assets", uuidGatherer.GatheredUuids.Count);
  180. bool success = true;
  181. foreach (UUID uuid in uuidGatherer.GatheredUuids.Keys)
  182. if (FetchAsset(userAssetURL, uuid) == null)
  183. success = false;
  184. // maybe all pieces got here...
  185. if (!success)
  186. m_log.DebugFormat("[HG ASSET MAPPER]: Problems getting item {0} from asset server {1}", assetID, userAssetURL);
  187. else
  188. m_log.DebugFormat("[HG ASSET MAPPER]: Successfully got item {0} from asset server {1}", assetID, userAssetURL);
  189. }
  190. public void Post(UUID assetID, UUID ownerID, string userAssetURL)
  191. {
  192. AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
  193. if (asset == null)
  194. {
  195. m_log.DebugFormat("[HG ASSET MAPPER POST]: Something wrong with asset {0}, it could not be found", assetID);
  196. return;
  197. }
  198. m_log.DebugFormat("[HG ASSET MAPPER POST]: Starting to send asset {0} to asset server {1}", assetID, userAssetURL);
  199. // Find all the embedded assets
  200. HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, string.Empty);
  201. uuidGatherer.AddForInspection(asset.FullID);
  202. uuidGatherer.GatherAll(true);
  203. // Check which assets already exist in the destination server
  204. string url = userAssetURL;
  205. if (!url.EndsWith("/") && !url.EndsWith("="))
  206. url = url + "/";
  207. string[] remoteAssetIDs = new string[uuidGatherer.GatheredUuids.Count];
  208. int i = 0;
  209. foreach (UUID id in uuidGatherer.GatheredUuids.Keys)
  210. remoteAssetIDs[i++] = url + id.ToString();
  211. bool[] exist;
  212. try
  213. {
  214. exist = m_scene.AssetService.AssetsExist(remoteAssetIDs);
  215. }
  216. catch
  217. {
  218. m_log.DebugFormat("[HG ASSET MAPPER POST]: Problems sending asset {0} to asset server {1}", assetID, userAssetURL);
  219. return;
  220. }
  221. var existSet = new HashSet<string>();
  222. i = 0;
  223. foreach (UUID id in uuidGatherer.GatheredUuids.Keys)
  224. {
  225. if (exist[i])
  226. existSet.Add(id.ToString());
  227. ++i;
  228. }
  229. // Send only those assets which don't already exist in the destination server
  230. bool success = true;
  231. var notFound = new List<string>();
  232. var posted = new List<string>();
  233. foreach (UUID uuid in uuidGatherer.GatheredUuids.Keys)
  234. {
  235. string idstr = uuid.ToString();
  236. if (existSet.Contains(idstr))
  237. continue;
  238. asset = m_scene.AssetService.Get(idstr);
  239. if (asset == null)
  240. {
  241. notFound.Add(idstr);
  242. continue;
  243. }
  244. try
  245. {
  246. bool b = PostAsset(userAssetURL, asset, false);
  247. if(b)
  248. posted.Add(idstr);
  249. success &= b;
  250. }
  251. catch (Exception e)
  252. {
  253. m_log.Error(
  254. string.Format(
  255. "[HG ASSET MAPPER POST]: Failed to post asset {0} (type {1}, length {2}) referenced from {3} to {4} with exception ",
  256. asset.ID, asset.Type, asset.Data.Length, assetID, userAssetURL),
  257. e);
  258. // For debugging purposes for now we will continue to throw the exception up the stack as was already happening. However, after
  259. // debugging we may want to simply report the failure if we can tell this is due to a failure
  260. // with a particular asset and not a destination network failure where all asset posts will fail (and
  261. // generate large amounts of log spam).
  262. throw e;
  263. }
  264. }
  265. StringBuilder sb = null;
  266. if (notFound.Count > 0)
  267. {
  268. if (sb == null)
  269. sb = new StringBuilder(512);
  270. i = notFound.Count;
  271. sb.Append("[HG ASSET MAPPER POST]: Missing assets:\n\t");
  272. for (int j = 0; j < notFound.Count; ++j)
  273. {
  274. sb.Append(notFound[j]);
  275. if (i < j)
  276. sb.Append(',');
  277. }
  278. m_log.Debug(sb.ToString());
  279. sb.Clear();
  280. }
  281. if (existSet.Count > 0)
  282. {
  283. if (sb == null)
  284. sb = new StringBuilder(512);
  285. i = existSet.Count;
  286. sb.Append("[HG ASSET MAPPER POST]: Already at destination server:\n\t");
  287. foreach (UUID id in existSet)
  288. {
  289. sb.Append(id);
  290. if (--i > 0)
  291. sb.Append(',');
  292. }
  293. m_log.Debug(sb.ToString());
  294. sb.Clear();
  295. }
  296. if (posted.Count > 0)
  297. {
  298. if (sb == null)
  299. sb = new StringBuilder(512);
  300. i = posted.Count;
  301. sb.Append("[HG ASSET MAPPER POST]: Posted assets:\n\t");
  302. for (int j = 0; j < posted.Count; ++j)
  303. {
  304. sb.Append(posted[j]);
  305. if (i < j)
  306. sb.Append(',');
  307. }
  308. m_log.Debug(sb.ToString());
  309. }
  310. if (!success)
  311. m_log.DebugFormat("[HG ASSET MAPPER POST]: Problems sending asset {0} to asset server {1}", assetID, userAssetURL);
  312. else
  313. m_log.DebugFormat("[HG ASSET MAPPER POST]: Successfully sent asset {0} to asset server {1}", assetID, userAssetURL);
  314. }
  315. #endregion
  316. }
  317. }