AssetServicesConnector.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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.IO;
  32. using System.Reflection;
  33. using System.Timers;
  34. using Nini.Config;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Console;
  37. using OpenSim.Services.Interfaces;
  38. using OpenMetaverse;
  39. namespace OpenSim.Services.Connectors
  40. {
  41. public class AssetServicesConnector : BaseServiceConnector, IAssetService
  42. {
  43. private static readonly ILog m_log =
  44. LogManager.GetLogger(
  45. MethodBase.GetCurrentMethod().DeclaringType);
  46. private string m_ServerURI = String.Empty;
  47. private IImprovedAssetCache m_Cache = null;
  48. private int m_retryCounter;
  49. private Dictionary<int, List<AssetBase>> m_retryQueue = new Dictionary<int, List<AssetBase>>();
  50. private System.Timers.Timer m_retryTimer;
  51. private int m_maxAssetRequestConcurrency = 30;
  52. private delegate void AssetRetrievedEx(AssetBase asset);
  53. // Keeps track of concurrent requests for the same asset, so that it's only loaded once.
  54. // Maps: Asset ID -> Handlers which will be called when the asset has been loaded
  55. // private Dictionary<string, AssetRetrievedEx> m_AssetHandlers = new Dictionary<string, AssetRetrievedEx>();
  56. private Dictionary<string, List<AssetRetrievedEx>> m_AssetHandlers = new Dictionary<string, List<AssetRetrievedEx>>();
  57. private Dictionary<string, string> m_UriMap = new Dictionary<string, string>();
  58. private Thread[] m_fetchThreads;
  59. public int MaxAssetRequestConcurrency
  60. {
  61. get { return m_maxAssetRequestConcurrency; }
  62. set { m_maxAssetRequestConcurrency = value; }
  63. }
  64. public AssetServicesConnector()
  65. {
  66. }
  67. public AssetServicesConnector(string serverURI)
  68. {
  69. m_ServerURI = serverURI.TrimEnd('/');
  70. }
  71. public AssetServicesConnector(IConfigSource source)
  72. : base(source, "AssetService")
  73. {
  74. Initialise(source);
  75. }
  76. public virtual void Initialise(IConfigSource source)
  77. {
  78. IConfig netconfig = source.Configs["Network"];
  79. if (netconfig != null)
  80. m_maxAssetRequestConcurrency = netconfig.GetInt("MaxRequestConcurrency",m_maxAssetRequestConcurrency);
  81. IConfig assetConfig = source.Configs["AssetService"];
  82. if (assetConfig == null)
  83. {
  84. m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
  85. throw new Exception("Asset connector init error");
  86. }
  87. string serviceURI = assetConfig.GetString("AssetServerURI",
  88. String.Empty);
  89. m_ServerURI = serviceURI;
  90. if (serviceURI == String.Empty)
  91. {
  92. m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService");
  93. throw new Exception("Asset connector init error");
  94. }
  95. m_retryTimer = new System.Timers.Timer();
  96. m_retryTimer.Elapsed += new ElapsedEventHandler(retryCheck);
  97. m_retryTimer.Interval = 60000;
  98. Uri serverUri = new Uri(m_ServerURI);
  99. string groupHost = serverUri.Host;
  100. for (int i = 0 ; i < 256 ; i++)
  101. {
  102. string prefix = i.ToString("x2");
  103. groupHost = assetConfig.GetString("AssetServerHost_"+prefix, groupHost);
  104. m_UriMap[prefix] = groupHost;
  105. //m_log.DebugFormat("[ASSET]: Using {0} for prefix {1}", groupHost, prefix);
  106. }
  107. m_fetchThreads = new Thread[2];
  108. for (int i = 0 ; i < 2 ; i++)
  109. {
  110. m_fetchThreads[i] = new Thread(AssetRequestProcessor);
  111. m_fetchThreads[i].Start();
  112. }
  113. }
  114. private string MapServer(string id)
  115. {
  116. if (m_UriMap.Count == 0)
  117. return m_ServerURI;
  118. UriBuilder serverUri = new UriBuilder(m_ServerURI);
  119. string prefix = id.Substring(0, 2).ToLower();
  120. string host;
  121. // HG URLs will not be valid UUIDS
  122. if (m_UriMap.ContainsKey(prefix))
  123. host = m_UriMap[prefix];
  124. else
  125. host = m_UriMap["00"];
  126. serverUri.Host = host;
  127. // m_log.DebugFormat("[ASSET]: Using {0} for host name for prefix {1}", host, prefix);
  128. string ret = serverUri.Uri.AbsoluteUri;
  129. if (ret.EndsWith("/"))
  130. ret = ret.Substring(0, ret.Length - 1);
  131. return ret;
  132. }
  133. protected void retryCheck(object source, ElapsedEventArgs e)
  134. {
  135. m_retryCounter++;
  136. if (m_retryCounter > 60)
  137. m_retryCounter -= 60;
  138. List<int> keys = new List<int>();
  139. foreach (int a in m_retryQueue.Keys)
  140. {
  141. keys.Add(a);
  142. }
  143. foreach (int a in keys)
  144. {
  145. //We exponentially fall back on frequency until we reach one attempt per hour
  146. //The net result is that we end up in the queue for roughly 24 hours..
  147. //24 hours worth of assets could be a lot, so the hope is that the region admin
  148. //will have gotten the asset connector back online quickly!
  149. int timefactor = a ^ 2;
  150. if (timefactor > 60)
  151. {
  152. timefactor = 60;
  153. }
  154. //First, find out if we care about this timefactor
  155. if (timefactor % a == 0)
  156. {
  157. //Yes, we do!
  158. List<AssetBase> retrylist = m_retryQueue[a];
  159. m_retryQueue.Remove(a);
  160. foreach(AssetBase ass in retrylist)
  161. {
  162. Store(ass); //Store my ass. This function will put it back in the dictionary if it fails
  163. }
  164. }
  165. }
  166. if (m_retryQueue.Count == 0)
  167. {
  168. //It might only be one tick per minute, but I have
  169. //repented and abandoned my wasteful ways
  170. m_retryCounter = 0;
  171. m_retryTimer.Stop();
  172. }
  173. }
  174. protected void SetCache(IImprovedAssetCache cache)
  175. {
  176. m_Cache = cache;
  177. }
  178. public AssetBase Get(string id)
  179. {
  180. string uri = MapServer(id) + "/assets/" + id;
  181. AssetBase asset = null;
  182. if (m_Cache != null)
  183. asset = m_Cache.Get(id);
  184. if (asset == null || asset.Data == null || asset.Data.Length == 0)
  185. {
  186. // XXX: Commented out for now since this has either never been properly operational or not for some time
  187. // as m_maxAssetRequestConcurrency was being passed as the timeout, not a concurrency limiting option.
  188. // Wasn't noticed before because timeout wasn't actually used.
  189. // Not attempting concurrency setting for now as this omission was discovered in release candidate
  190. // phase for OpenSimulator 0.8. Need to revisit afterwards.
  191. // asset
  192. // = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>(
  193. // "GET", uri, 0, m_maxAssetRequestConcurrency);
  194. asset = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, m_Auth);
  195. if (m_Cache != null)
  196. m_Cache.Cache(asset);
  197. }
  198. return asset;
  199. }
  200. public AssetBase GetCached(string id)
  201. {
  202. // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Cache request for {0}", id);
  203. if (m_Cache != null)
  204. return m_Cache.Get(id);
  205. return null;
  206. }
  207. public AssetMetadata GetMetadata(string id)
  208. {
  209. if (m_Cache != null)
  210. {
  211. AssetBase fullAsset = m_Cache.Get(id);
  212. if (fullAsset != null)
  213. return fullAsset.Metadata;
  214. }
  215. string uri = MapServer(id) + "/assets/" + id + "/metadata";
  216. AssetMetadata asset = SynchronousRestObjectRequester.MakeRequest<int, AssetMetadata>("GET", uri, 0, m_Auth);
  217. return asset;
  218. }
  219. public byte[] GetData(string id)
  220. {
  221. if (m_Cache != null)
  222. {
  223. AssetBase fullAsset = m_Cache.Get(id);
  224. if (fullAsset != null)
  225. return fullAsset.Data;
  226. }
  227. using (RestClient rc = new RestClient(MapServer(id)))
  228. {
  229. rc.AddResourcePath("assets");
  230. rc.AddResourcePath(id);
  231. rc.AddResourcePath("data");
  232. rc.RequestMethod = "GET";
  233. using (Stream s = rc.Request(m_Auth))
  234. {
  235. if (s == null)
  236. return null;
  237. if (s.Length > 0)
  238. {
  239. byte[] ret = new byte[s.Length];
  240. s.Read(ret, 0, (int)s.Length);
  241. return ret;
  242. }
  243. }
  244. return null;
  245. }
  246. }
  247. private class QueuedAssetRequest
  248. {
  249. public string uri;
  250. public string id;
  251. }
  252. private OpenMetaverse.BlockingQueue<QueuedAssetRequest> m_requestQueue =
  253. new OpenMetaverse.BlockingQueue<QueuedAssetRequest>();
  254. private void AssetRequestProcessor()
  255. {
  256. QueuedAssetRequest r;
  257. while (true)
  258. {
  259. r = m_requestQueue.Dequeue();
  260. string uri = r.uri;
  261. string id = r.id;
  262. bool success = false;
  263. try
  264. {
  265. AssetBase a = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, 30000);
  266. if (a != null)
  267. {
  268. if (m_Cache != null)
  269. m_Cache.Cache(a);
  270. List<AssetRetrievedEx> handlers;
  271. lock (m_AssetHandlers)
  272. {
  273. handlers = m_AssetHandlers[id];
  274. m_AssetHandlers.Remove(id);
  275. }
  276. Util.FireAndForget(x =>
  277. {
  278. foreach (AssetRetrievedEx h in handlers)
  279. {
  280. // Util.FireAndForget(x =>
  281. // {
  282. try { h.Invoke(a); }
  283. catch { }
  284. // });
  285. }
  286. if (handlers != null)
  287. handlers.Clear();
  288. });
  289. // if (handlers != null)
  290. // handlers.Clear();
  291. success = true;
  292. }
  293. }
  294. finally
  295. {
  296. if (!success)
  297. {
  298. List<AssetRetrievedEx> handlers;
  299. lock (m_AssetHandlers)
  300. {
  301. handlers = m_AssetHandlers[id];
  302. m_AssetHandlers.Remove(id);
  303. }
  304. if (handlers != null)
  305. handlers.Clear();
  306. }
  307. }
  308. }
  309. }
  310. public bool Get(string id, Object sender, AssetRetrieved handler)
  311. {
  312. string uri = MapServer(id) + "/assets/" + id;
  313. AssetBase asset = null;
  314. if (m_Cache != null)
  315. asset = m_Cache.Get(id);
  316. if (asset == null || asset.Data == null || asset.Data.Length == 0)
  317. {
  318. lock (m_AssetHandlers)
  319. {
  320. AssetRetrievedEx handlerEx = new AssetRetrievedEx(delegate(AssetBase _asset) { handler(id, sender, _asset); });
  321. // AssetRetrievedEx handlers;
  322. List<AssetRetrievedEx> handlers;
  323. if (m_AssetHandlers.TryGetValue(id, out handlers))
  324. {
  325. // Someone else is already loading this asset. It will notify our handler when done.
  326. // handlers += handlerEx;
  327. handlers.Add(handlerEx);
  328. return true;
  329. }
  330. // Load the asset ourselves
  331. // handlers += handlerEx;
  332. handlers = new List<AssetRetrievedEx>();
  333. handlers.Add(handlerEx);
  334. m_AssetHandlers.Add(id, handlers);
  335. }
  336. QueuedAssetRequest request = new QueuedAssetRequest();
  337. request.id = id;
  338. request.uri = uri;
  339. m_requestQueue.Enqueue(request);
  340. }
  341. else
  342. {
  343. handler(id, sender, asset);
  344. }
  345. return true;
  346. }
  347. public virtual bool[] AssetsExist(string[] ids)
  348. {
  349. string uri = m_ServerURI + "/get_assets_exist";
  350. bool[] exist = null;
  351. try
  352. {
  353. exist = SynchronousRestObjectRequester.MakeRequest<string[], bool[]>("POST", uri, ids, m_Auth);
  354. }
  355. catch (Exception)
  356. {
  357. // This is most likely to happen because the server doesn't support this function,
  358. // so just silently return "doesn't exist" for all the assets.
  359. }
  360. if (exist == null)
  361. exist = new bool[ids.Length];
  362. return exist;
  363. }
  364. public string Store(AssetBase asset)
  365. {
  366. // Have to assign the asset ID here. This isn't likely to
  367. // trigger since current callers don't pass emtpy IDs
  368. // We need the asset ID to route the request to the proper
  369. // cluster member, so we can't have the server assign one.
  370. if (asset.ID == string.Empty)
  371. {
  372. if (asset.FullID == UUID.Zero)
  373. {
  374. asset.FullID = UUID.Random();
  375. }
  376. asset.ID = asset.FullID.ToString();
  377. }
  378. else if (asset.FullID == UUID.Zero)
  379. {
  380. UUID uuid = UUID.Zero;
  381. if (UUID.TryParse(asset.ID, out uuid))
  382. {
  383. asset.FullID = uuid;
  384. }
  385. else
  386. {
  387. asset.FullID = UUID.Random();
  388. }
  389. }
  390. if (m_Cache != null)
  391. m_Cache.Cache(asset);
  392. if (asset.Temporary || asset.Local)
  393. {
  394. return asset.ID;
  395. }
  396. string uri = MapServer(asset.FullID.ToString()) + "/assets/";
  397. string newID;
  398. try
  399. {
  400. newID = SynchronousRestObjectRequester.
  401. MakeRequest<AssetBase, string>("POST", uri, asset, 100000);
  402. if (newID == null || newID == "")
  403. {
  404. newID = UUID.Zero.ToString();
  405. }
  406. }
  407. catch (Exception e)
  408. {
  409. newID = UUID.Zero.ToString();
  410. }
  411. if (newID == UUID.Zero.ToString())
  412. {
  413. //The asset upload failed, put it in a queue for later
  414. asset.UploadAttempts++;
  415. if (asset.UploadAttempts > 30)
  416. {
  417. //By this stage we've been in the queue for a good few hours;
  418. //We're going to drop the asset.
  419. m_log.ErrorFormat("[Assets] Dropping asset {0} - Upload has been in the queue for too long.", asset.ID.ToString());
  420. }
  421. else
  422. {
  423. if (!m_retryQueue.ContainsKey(asset.UploadAttempts))
  424. {
  425. m_retryQueue.Add(asset.UploadAttempts, new List<AssetBase>());
  426. }
  427. List<AssetBase> m_queue = m_retryQueue[asset.UploadAttempts];
  428. m_queue.Add(asset);
  429. m_log.WarnFormat("[Assets] Upload failed: {0} - Requeuing asset for another run.", asset.ID.ToString());
  430. m_retryTimer.Start();
  431. }
  432. }
  433. else
  434. {
  435. if (asset.UploadAttempts > 0)
  436. {
  437. m_log.InfoFormat("[Assets] Upload of {0} succeeded after {1} failed attempts", asset.ID.ToString(), asset.UploadAttempts.ToString());
  438. }
  439. if (newID != String.Empty)
  440. {
  441. // Placing this here, so that this work with old asset servers that don't send any reply back
  442. // SynchronousRestObjectRequester returns somethins that is not an empty string
  443. if (newID != null)
  444. asset.ID = newID;
  445. if (m_Cache != null)
  446. m_Cache.Cache(asset);
  447. }
  448. }
  449. return asset.ID;
  450. }
  451. public bool UpdateContent(string id, byte[] data)
  452. {
  453. AssetBase asset = null;
  454. if (m_Cache != null)
  455. asset = m_Cache.Get(id);
  456. if (asset == null)
  457. {
  458. AssetMetadata metadata = GetMetadata(id);
  459. if (metadata == null)
  460. return false;
  461. asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString());
  462. asset.Metadata = metadata;
  463. }
  464. asset.Data = data;
  465. string uri = MapServer(id) + "/assets/" + id;
  466. if (SynchronousRestObjectRequester.MakeRequest<AssetBase, bool>("POST", uri, asset, m_Auth))
  467. {
  468. if (m_Cache != null)
  469. m_Cache.Cache(asset);
  470. return true;
  471. }
  472. return false;
  473. }
  474. public bool Delete(string id)
  475. {
  476. string uri = MapServer(id) + "/assets/" + id;
  477. if (SynchronousRestObjectRequester.MakeRequest<int, bool>("DELETE", uri, 0, m_Auth))
  478. {
  479. if (m_Cache != null)
  480. m_Cache.Expire(id);
  481. return true;
  482. }
  483. return false;
  484. }
  485. }
  486. }