AssetServicesConnector.cs 21 KB

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