SimianAssetServiceConnector.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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.IO;
  30. using System.Net;
  31. using System.Reflection;
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using OpenSim.Services.Interfaces;
  39. using OpenMetaverse;
  40. using OpenMetaverse.StructuredData;
  41. namespace OpenSim.Services.Connectors.SimianGrid
  42. {
  43. /// <summary>
  44. /// Connects to the SimianGrid asset service
  45. /// </summary>
  46. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  47. public class SimianAssetServiceConnector : IAssetService, ISharedRegionModule
  48. {
  49. private static readonly ILog m_log =
  50. LogManager.GetLogger(
  51. MethodBase.GetCurrentMethod().DeclaringType);
  52. private static string ZeroID = UUID.Zero.ToString();
  53. private string m_serverUrl = String.Empty;
  54. private IImprovedAssetCache m_cache;
  55. #region ISharedRegionModule
  56. public Type ReplaceableInterface { get { return null; } }
  57. public void RegionLoaded(Scene scene)
  58. {
  59. if (m_cache == null)
  60. {
  61. IImprovedAssetCache cache = scene.RequestModuleInterface<IImprovedAssetCache>();
  62. if (cache is ISharedRegionModule)
  63. m_cache = cache;
  64. }
  65. }
  66. public void PostInitialise() { }
  67. public void Close() { }
  68. public SimianAssetServiceConnector() { }
  69. public string Name { get { return "SimianAssetServiceConnector"; } }
  70. public void AddRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.RegisterModuleInterface<IAssetService>(this); } }
  71. public void RemoveRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.UnregisterModuleInterface<IAssetService>(this); } }
  72. #endregion ISharedRegionModule
  73. public SimianAssetServiceConnector(IConfigSource source)
  74. {
  75. Initialise(source);
  76. }
  77. public void Initialise(IConfigSource source)
  78. {
  79. if (Simian.IsSimianEnabled(source, "AssetServices", this.Name))
  80. {
  81. IConfig gridConfig = source.Configs["AssetService"];
  82. if (gridConfig == null)
  83. {
  84. m_log.Error("[SIMIAN ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
  85. throw new Exception("Asset connector init error");
  86. }
  87. string serviceUrl = gridConfig.GetString("AssetServerURI");
  88. if (String.IsNullOrEmpty(serviceUrl))
  89. {
  90. m_log.Error("[SIMIAN ASSET CONNECTOR]: No AssetServerURI in section AssetService");
  91. throw new Exception("Asset connector init error");
  92. }
  93. if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
  94. serviceUrl = serviceUrl + '/';
  95. m_serverUrl = serviceUrl;
  96. }
  97. }
  98. #region IAssetService
  99. public AssetBase Get(string id)
  100. {
  101. // Cache fetch
  102. if (m_cache != null)
  103. {
  104. AssetBase asset = m_cache.Get(id);
  105. if (asset != null)
  106. return asset;
  107. }
  108. return GetRemote(id);
  109. }
  110. public AssetBase GetCached(string id)
  111. {
  112. if (m_cache != null)
  113. return m_cache.Get(id);
  114. return null;
  115. }
  116. /// <summary>
  117. /// Get an asset's metadata
  118. /// </summary>
  119. /// <param name="id"></param>
  120. /// <returns></returns>
  121. public AssetMetadata GetMetadata(string id)
  122. {
  123. AssetMetadata metadata = null;
  124. // Cache fetch
  125. if (m_cache != null)
  126. {
  127. AssetBase asset = m_cache.Get(id);
  128. if (asset != null)
  129. return asset.Metadata;
  130. }
  131. Uri url;
  132. // Determine if id is an absolute URL or a grid-relative UUID
  133. if (!Uri.TryCreate(id, UriKind.Absolute, out url))
  134. url = new Uri(m_serverUrl + id);
  135. try
  136. {
  137. HttpWebRequest request = UntrustedHttpWebRequest.Create(url);
  138. request.Method = "HEAD";
  139. using (WebResponse response = request.GetResponse())
  140. {
  141. using (Stream responseStream = response.GetResponseStream())
  142. {
  143. // Create the metadata object
  144. metadata = new AssetMetadata();
  145. metadata.ContentType = response.ContentType;
  146. metadata.ID = id;
  147. UUID uuid;
  148. if (UUID.TryParse(id, out uuid))
  149. metadata.FullID = uuid;
  150. string lastModifiedStr = response.Headers.Get("Last-Modified");
  151. if (!String.IsNullOrEmpty(lastModifiedStr))
  152. {
  153. DateTime lastModified;
  154. if (DateTime.TryParse(lastModifiedStr, out lastModified))
  155. metadata.CreationDate = lastModified;
  156. }
  157. }
  158. }
  159. }
  160. catch (Exception ex)
  161. {
  162. m_log.Warn("[SIMIAN ASSET CONNECTOR]: Asset GET from " + url + " failed: " + ex.Message);
  163. }
  164. return metadata;
  165. }
  166. public byte[] GetData(string id)
  167. {
  168. AssetBase asset = Get(id);
  169. if (asset != null)
  170. return asset.Data;
  171. return null;
  172. }
  173. /// <summary>
  174. /// Get an asset asynchronously
  175. /// </summary>
  176. /// <param name="id">The asset id</param>
  177. /// <param name="sender">Represents the requester. Passed back via the handler</param>
  178. /// <param name="handler">The handler to call back once the asset has been retrieved</param>
  179. /// <returns>True if the id was parseable, false otherwise</returns>
  180. public bool Get(string id, Object sender, AssetRetrieved handler)
  181. {
  182. // Cache fetch
  183. if (m_cache != null)
  184. {
  185. AssetBase asset = m_cache.Get(id);
  186. if (asset != null)
  187. {
  188. handler(id, sender, asset);
  189. return true;
  190. }
  191. }
  192. Util.FireAndForget(
  193. delegate(object o)
  194. {
  195. AssetBase asset = GetRemote(id);
  196. handler(id, sender, asset);
  197. }
  198. );
  199. return true;
  200. }
  201. /// <summary>
  202. /// Creates a new asset
  203. /// </summary>
  204. /// Returns a random ID if none is passed into it
  205. /// <param name="asset"></param>
  206. /// <returns></returns>
  207. public string Store(AssetBase asset)
  208. {
  209. bool storedInCache = false;
  210. string errorMessage = null;
  211. // AssetID handling
  212. if (String.IsNullOrEmpty(asset.ID) || asset.ID == ZeroID)
  213. {
  214. asset.FullID = UUID.Random();
  215. asset.ID = asset.FullID.ToString();
  216. }
  217. // Cache handling
  218. if (m_cache != null)
  219. {
  220. m_cache.Cache(asset);
  221. storedInCache = true;
  222. }
  223. // Local asset handling
  224. if (asset.Local)
  225. {
  226. if (!storedInCache)
  227. {
  228. m_log.Error("Cannot store local " + asset.Metadata.ContentType + " asset without an asset cache");
  229. asset.ID = null;
  230. asset.FullID = UUID.Zero;
  231. }
  232. return asset.ID;
  233. }
  234. // Distinguish public and private assets
  235. bool isPublic = true;
  236. switch ((AssetType)asset.Type)
  237. {
  238. case AssetType.CallingCard:
  239. case AssetType.Gesture:
  240. case AssetType.LSLBytecode:
  241. case AssetType.LSLText:
  242. isPublic = false;
  243. break;
  244. }
  245. // Make sure ContentType is set
  246. if (String.IsNullOrEmpty(asset.Metadata.ContentType))
  247. asset.Metadata.ContentType = SLUtil.SLAssetTypeToContentType(asset.Type);
  248. // Build the remote storage request
  249. List<MultipartForm.Element> postParameters = new List<MultipartForm.Element>()
  250. {
  251. new MultipartForm.Parameter("AssetID", asset.FullID.ToString()),
  252. new MultipartForm.Parameter("CreatorID", asset.Metadata.CreatorID),
  253. new MultipartForm.Parameter("Temporary", asset.Temporary ? "1" : "0"),
  254. new MultipartForm.Parameter("Public", isPublic ? "1" : "0"),
  255. new MultipartForm.File("Asset", asset.Name, asset.Metadata.ContentType, asset.Data)
  256. };
  257. // Make the remote storage request
  258. try
  259. {
  260. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl);
  261. HttpWebResponse response = MultipartForm.Post(request, postParameters);
  262. using (Stream responseStream = response.GetResponseStream())
  263. {
  264. string responseStr = null;
  265. try
  266. {
  267. responseStr = responseStream.GetStreamString();
  268. OSD responseOSD = OSDParser.Deserialize(responseStr);
  269. if (responseOSD.Type == OSDType.Map)
  270. {
  271. OSDMap responseMap = (OSDMap)responseOSD;
  272. if (responseMap["Success"].AsBoolean())
  273. return asset.ID;
  274. else
  275. errorMessage = "Upload failed: " + responseMap["Message"].AsString();
  276. }
  277. else
  278. {
  279. errorMessage = "Response format was invalid:\n" + responseStr;
  280. }
  281. }
  282. catch (Exception ex)
  283. {
  284. if (!String.IsNullOrEmpty(responseStr))
  285. errorMessage = "Failed to parse the response:\n" + responseStr;
  286. else
  287. errorMessage = "Failed to retrieve the response: " + ex.Message;
  288. }
  289. }
  290. }
  291. catch (WebException ex)
  292. {
  293. errorMessage = ex.Message;
  294. }
  295. m_log.WarnFormat("[SIMIAN ASSET CONNECTOR]: Failed to store asset \"{0}\" ({1}, {2}): {3}",
  296. asset.Name, asset.ID, asset.Metadata.ContentType, errorMessage);
  297. return null;
  298. }
  299. /// <summary>
  300. /// Update an asset's content
  301. /// </summary>
  302. /// Attachments and bare scripts need this!!
  303. /// <param name="id"> </param>
  304. /// <param name="data"></param>
  305. /// <returns></returns>
  306. public bool UpdateContent(string id, byte[] data)
  307. {
  308. AssetBase asset = Get(id);
  309. if (asset == null)
  310. {
  311. m_log.Warn("[SIMIAN ASSET CONNECTOR]: Failed to fetch asset " + id + " for updating");
  312. return false;
  313. }
  314. asset.Data = data;
  315. string result = Store(asset);
  316. return !String.IsNullOrEmpty(result);
  317. }
  318. /// <summary>
  319. /// Delete an asset
  320. /// </summary>
  321. /// <param name="id"></param>
  322. /// <returns></returns>
  323. public bool Delete(string id)
  324. {
  325. //string errorMessage = String.Empty;
  326. string url = m_serverUrl + id;
  327. if (m_cache != null)
  328. m_cache.Expire(id);
  329. try
  330. {
  331. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  332. request.Method = "DELETE";
  333. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  334. {
  335. if (response.StatusCode != HttpStatusCode.NoContent)
  336. {
  337. m_log.Warn("[SIMIAN ASSET CONNECTOR]: Unexpected response when deleting asset " + url + ": " +
  338. response.StatusCode + " (" + response.StatusDescription + ")");
  339. }
  340. }
  341. return true;
  342. }
  343. catch (Exception ex)
  344. {
  345. m_log.Warn("[SIMIAN ASSET CONNECTOR]: Failed to delete asset " + id + " from the asset service: " + ex.Message);
  346. return false;
  347. }
  348. }
  349. #endregion IAssetService
  350. private AssetBase GetRemote(string id)
  351. {
  352. AssetBase asset = null;
  353. Uri url;
  354. // Determine if id is an absolute URL or a grid-relative UUID
  355. if (!Uri.TryCreate(id, UriKind.Absolute, out url))
  356. url = new Uri(m_serverUrl + id);
  357. try
  358. {
  359. HttpWebRequest request = UntrustedHttpWebRequest.Create(url);
  360. using (WebResponse response = request.GetResponse())
  361. {
  362. using (Stream responseStream = response.GetResponseStream())
  363. {
  364. string creatorID = response.Headers.GetOne("X-Asset-Creator-Id") ?? String.Empty;
  365. // Create the asset object
  366. asset = new AssetBase(id, String.Empty, SLUtil.ContentTypeToSLAssetType(response.ContentType), creatorID);
  367. UUID assetID;
  368. if (UUID.TryParse(id, out assetID))
  369. asset.FullID = assetID;
  370. // Grab the asset data from the response stream
  371. using (MemoryStream stream = new MemoryStream())
  372. {
  373. responseStream.CopyTo(stream, Int32.MaxValue);
  374. asset.Data = stream.ToArray();
  375. }
  376. }
  377. }
  378. // Cache store
  379. if (m_cache != null && asset != null)
  380. m_cache.Cache(asset);
  381. return asset;
  382. }
  383. catch (Exception ex)
  384. {
  385. m_log.Warn("[SIMIAN ASSET CONNECTOR]: Asset GET from " + url + " failed: " + ex.Message);
  386. return null;
  387. }
  388. }
  389. }
  390. }