AssetServicesConnector.cs 22 KB

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