AssetServicesConnector.cs 22 KB

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