AssetServicesConnector.cs 22 KB

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