AssetServicesConnector.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 log4net;
  28. using System;
  29. using System.Threading;
  30. using System.Collections.Generic;
  31. using System.Collections.Concurrent;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Timers;
  35. using Nini.Config;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Monitoring;
  38. using OpenSim.Framework.ServiceAuth;
  39. using OpenSim.Services.Interfaces;
  40. using OpenMetaverse;
  41. namespace OpenSim.Services.Connectors
  42. {
  43. public class AssetServicesConnector : BaseServiceConnector, IAssetService
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. protected IAssetCache m_Cache = null;
  47. public readonly object ConnectorLock = new object();
  48. private string m_ServerURI = string.Empty;
  49. private delegate void AssetRetrievedEx(AssetBase asset);
  50. // Keeps track of concurrent requests for the same asset, so that it's only loaded once.
  51. // Maps: Asset ID -> Handlers which will be called when the asset has been loaded
  52. private Dictionary<string, List<AssetRetrievedEx>> m_AssetHandlers = new Dictionary<string, List<AssetRetrievedEx>>();
  53. public AssetServicesConnector()
  54. {
  55. }
  56. public AssetServicesConnector(string serverURI)
  57. {
  58. m_ServerURI = serverURI.TrimEnd('/');
  59. }
  60. public AssetServicesConnector(IConfigSource source)
  61. {
  62. Initialise(source);
  63. }
  64. public virtual void Initialise(IConfigSource source)
  65. {
  66. IConfig netconfig = source.Configs["Network"];
  67. IConfig assetConfig = source.Configs["AssetService"];
  68. if (assetConfig == null)
  69. {
  70. m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
  71. throw new Exception("Asset connector init error");
  72. }
  73. m_ServerURI = assetConfig.GetString("AssetServerURI", string.Empty);
  74. if (string.IsNullOrEmpty(m_ServerURI))
  75. {
  76. if(netconfig != null)
  77. m_ServerURI = netconfig.GetString("asset_server_url", string.Empty);
  78. }
  79. if (string.IsNullOrEmpty(m_ServerURI))
  80. {
  81. m_log.Error("[ASSET CONNECTOR]: AssetServerURI not defined in section AssetService");
  82. throw new Exception("Asset connector init error");
  83. }
  84. OSHHTPHost m_GridAssetsURL = new OSHHTPHost(m_ServerURI, true);
  85. if(!m_GridAssetsURL.IsResolvedHost)
  86. {
  87. m_log.Error("[ASSET CONNECTOR]: Could not parse or resolve AssetServerURI");
  88. throw new Exception("Asset connector init error");
  89. }
  90. m_ServerURI = m_GridAssetsURL.URI;
  91. Initialise(source, "AssetService");
  92. }
  93. private int m_maxAssetRequestConcurrency = 8;
  94. public int MaxAssetRequestConcurrency
  95. {
  96. get { return m_maxAssetRequestConcurrency; }
  97. set { m_maxAssetRequestConcurrency = value; }
  98. }
  99. protected void SetCache(IAssetCache cache)
  100. {
  101. m_Cache = cache;
  102. }
  103. public AssetBase GetCached(string id)
  104. {
  105. AssetBase asset = null;
  106. if (m_Cache != null)
  107. {
  108. m_Cache.Get(id, out asset);
  109. }
  110. return asset;
  111. }
  112. public virtual AssetBase Get(string id)
  113. {
  114. AssetBase asset = null;
  115. if (m_Cache != null)
  116. {
  117. if (!m_Cache.Get(id, out asset))
  118. return null;
  119. }
  120. if (asset == null || asset.Data == null || asset.Data.Length == 0)
  121. {
  122. string uri = m_ServerURI + "/assets/" + id;
  123. asset = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, m_Auth);
  124. if (m_Cache != null)
  125. {
  126. if (asset != null)
  127. m_Cache.Cache(asset);
  128. else
  129. m_Cache.CacheNegative(id);
  130. }
  131. }
  132. return asset;
  133. }
  134. public AssetBase Get(string id, string ForeignAssetService)
  135. {
  136. return null;
  137. }
  138. public virtual AssetMetadata GetMetadata(string id)
  139. {
  140. if (m_Cache != null)
  141. {
  142. AssetBase fullAsset;
  143. if (!m_Cache.Get(id, out fullAsset))
  144. return null;
  145. if (fullAsset != null)
  146. return fullAsset.Metadata;
  147. }
  148. string uri =m_ServerURI + "/assets/" + id + "/metadata";
  149. AssetMetadata asset = SynchronousRestObjectRequester.MakeRequest<int, AssetMetadata>("GET", uri, 0, m_Auth);
  150. return asset;
  151. }
  152. public virtual byte[] GetData(string id)
  153. {
  154. if (m_Cache != null)
  155. {
  156. if (!m_Cache.Get(id, out AssetBase fullAsset))
  157. return null;
  158. if (fullAsset != null)
  159. return fullAsset.Data;
  160. }
  161. using (RestClient rc = new RestClient(m_ServerURI))
  162. {
  163. rc.AddResourcePath("assets/" + id + "/Data");
  164. rc.RequestMethod = "GET";
  165. using (MemoryStream s = rc.Request(m_Auth))
  166. {
  167. if (s == null || s.Length == 0)
  168. return null;
  169. return s.ToArray();
  170. }
  171. }
  172. }
  173. public virtual bool Get(string id, object sender, AssetRetrieved handler)
  174. {
  175. AssetBase asset = null;
  176. if (m_Cache != null)
  177. {
  178. if (!m_Cache.Get(id, out asset))
  179. return false;
  180. }
  181. if (asset == null)
  182. {
  183. string uri = m_ServerURI + "/assets/" + id;
  184. lock (m_AssetHandlers)
  185. {
  186. AssetRetrievedEx handlerEx = new AssetRetrievedEx(delegate (AssetBase _asset) { handler(id, sender, _asset); });
  187. List<AssetRetrievedEx> handlers;
  188. if (m_AssetHandlers.TryGetValue(id, out handlers))
  189. {
  190. // Someone else is already loading this asset. It will notify our handler when done.
  191. handlers.Add(handlerEx);
  192. return true;
  193. }
  194. handlers = new List<AssetRetrievedEx>();
  195. handlers.Add(handlerEx);
  196. m_AssetHandlers.Add(id, handlers);
  197. QueuedAssetRequest request = new QueuedAssetRequest();
  198. request.id = id;
  199. request.uri = uri;
  200. Util.FireAndForget(x =>
  201. {
  202. AssetRequestProcessor(request);
  203. });
  204. }
  205. }
  206. else
  207. {
  208. if (asset != null && (asset.Data == null || asset.Data.Length == 0))
  209. asset = null;
  210. handler(id, sender, asset);
  211. }
  212. return true;
  213. }
  214. private class QueuedAssetRequest
  215. {
  216. public string uri;
  217. public string id;
  218. }
  219. private void AssetRequestProcessor(QueuedAssetRequest r)
  220. {
  221. string id = r.id;
  222. try
  223. {
  224. AssetBase a = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", r.uri, 0, 30000, m_Auth);
  225. if (a != null && m_Cache != null)
  226. m_Cache.Cache(a);
  227. List<AssetRetrievedEx> handlers;
  228. lock (m_AssetHandlers)
  229. {
  230. handlers = m_AssetHandlers[id];
  231. m_AssetHandlers.Remove(id);
  232. }
  233. if(handlers != null)
  234. {
  235. foreach (AssetRetrievedEx h in handlers)
  236. {
  237. try { h.Invoke(a); }
  238. catch { }
  239. }
  240. handlers.Clear();
  241. }
  242. }
  243. catch { }
  244. }
  245. public virtual bool[] AssetsExist(string[] ids)
  246. {
  247. string uri = m_ServerURI + "/get_assets_exist";
  248. bool[] exist = null;
  249. try
  250. {
  251. exist = SynchronousRestObjectRequester.MakeRequest<string[], bool[]>("POST", uri, ids, m_Auth);
  252. }
  253. catch (Exception)
  254. {
  255. // This is most likely to happen because the server doesn't support this function,
  256. // so just silently return "doesn't exist" for all the assets.
  257. }
  258. if (exist == null)
  259. exist = new bool[ids.Length];
  260. return exist;
  261. }
  262. string stringUUIDZero = UUID.Zero.ToString();
  263. public virtual string Store(AssetBase asset)
  264. {
  265. // Have to assign the asset ID here. This isn't likely to
  266. // trigger since current callers don't pass emtpy IDs
  267. // We need the asset ID to route the request to the proper
  268. // cluster member, so we can't have the server assign one.
  269. if (asset.ID == string.Empty || asset.ID == stringUUIDZero)
  270. {
  271. if (asset.FullID == UUID.Zero)
  272. {
  273. asset.FullID = UUID.Random();
  274. }
  275. m_log.WarnFormat("[Assets] Zero ID: {0}",asset.Name);
  276. asset.ID = asset.FullID.ToString();
  277. }
  278. if (asset.FullID == UUID.Zero)
  279. {
  280. UUID uuid = UUID.Zero;
  281. if (UUID.TryParse(asset.ID, out uuid))
  282. {
  283. asset.FullID = uuid;
  284. }
  285. if(asset.FullID == UUID.Zero)
  286. {
  287. m_log.WarnFormat("[Assets] Zero IDs: {0}",asset.Name);
  288. asset.FullID = UUID.Random();
  289. asset.ID = asset.FullID.ToString();
  290. }
  291. }
  292. if (m_Cache != null)
  293. m_Cache.Cache(asset);
  294. if (asset.Temporary || asset.Local)
  295. {
  296. return asset.ID;
  297. }
  298. string uri = m_ServerURI + "/assets/";
  299. string newID = null;
  300. try
  301. {
  302. newID = SynchronousRestObjectRequester.MakeRequest<AssetBase, string>("POST", uri, asset, 10000, m_Auth);
  303. }
  304. catch
  305. {
  306. newID = null;
  307. }
  308. if (string.IsNullOrEmpty(newID) || newID == stringUUIDZero)
  309. {
  310. return string.Empty;
  311. }
  312. else
  313. {
  314. if (newID != asset.ID)
  315. {
  316. // Placing this here, so that this work with old asset servers that don't send any reply back
  317. // SynchronousRestObjectRequester returns somethins that is not an empty string
  318. asset.ID = newID;
  319. if (m_Cache != null)
  320. m_Cache.Cache(asset);
  321. }
  322. }
  323. return asset.ID;
  324. }
  325. public virtual bool UpdateContent(string id, byte[] data)
  326. {
  327. AssetBase asset = null;
  328. m_Cache?.Get(id, out asset);
  329. if (asset == null)
  330. {
  331. AssetMetadata metadata = GetMetadata(id);
  332. if (metadata == null)
  333. return false;
  334. asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString());
  335. asset.Metadata = metadata;
  336. }
  337. asset.Data = data;
  338. string uri = m_ServerURI + "/assets/" + id;
  339. if (SynchronousRestObjectRequester.MakeRequest<AssetBase, bool>("POST", uri, asset, m_Auth))
  340. {
  341. m_Cache?.Cache(asset, true);
  342. return true;
  343. }
  344. return false;
  345. }
  346. public virtual bool Delete(string id)
  347. {
  348. string uri = m_ServerURI + "/assets/" + id;
  349. if (SynchronousRestObjectRequester.MakeRequest<int, bool>("DELETE", uri, 0, m_Auth))
  350. {
  351. if (m_Cache != null)
  352. m_Cache.Expire(id);
  353. return true;
  354. }
  355. return false;
  356. }
  357. }
  358. }