GetTextureModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Threading;
  32. using log4net;
  33. using Nini.Config;
  34. using Mono.Addins;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Servers;
  38. using OpenSim.Framework.Servers.HttpServer;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Services.Interfaces;
  42. using Caps = OpenSim.Framework.Capabilities.Caps;
  43. using OpenSim.Capabilities.Handlers;
  44. using OpenSim.Framework.Monitoring;
  45. namespace OpenSim.Region.ClientStack.Linden
  46. {
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GetTextureModule")]
  48. public class GetTextureModule : INonSharedRegionModule
  49. {
  50. struct aPollRequest
  51. {
  52. public PollServiceTextureEventArgs thepoll;
  53. public UUID reqID;
  54. public Hashtable request;
  55. public bool send503;
  56. }
  57. public class aPollResponse
  58. {
  59. public Hashtable response;
  60. public int bytes;
  61. }
  62. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  63. private Scene m_scene;
  64. private static GetTextureHandler m_getTextureHandler;
  65. private IAssetService m_assetService = null;
  66. private Dictionary<UUID, string> m_capsDict = new Dictionary<UUID, string>();
  67. private static Thread[] m_workerThreads = null;
  68. private static int m_NumberScenes = 0;
  69. private static OpenSim.Framework.BlockingQueue<aPollRequest> m_queue =
  70. new OpenSim.Framework.BlockingQueue<aPollRequest>();
  71. private Dictionary<UUID,PollServiceTextureEventArgs> m_pollservices = new Dictionary<UUID,PollServiceTextureEventArgs>();
  72. private string m_Url = "localhost";
  73. #region ISharedRegionModule Members
  74. public void Initialise(IConfigSource source)
  75. {
  76. IConfig config = source.Configs["ClientStack.LindenCaps"];
  77. if (config == null)
  78. return;
  79. /*
  80. m_URL = config.GetString("Cap_GetTexture", string.Empty);
  81. // Cap doesn't exist
  82. if (m_URL != string.Empty)
  83. {
  84. m_Enabled = true;
  85. m_RedirectURL = config.GetString("GetTextureRedirectURL");
  86. }
  87. */
  88. m_Url = config.GetString("Cap_GetTexture", "localhost");
  89. }
  90. public void AddRegion(Scene s)
  91. {
  92. m_scene = s;
  93. m_assetService = s.AssetService;
  94. }
  95. public void RemoveRegion(Scene s)
  96. {
  97. m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
  98. m_scene.EventManager.OnDeregisterCaps -= DeregisterCaps;
  99. m_scene.EventManager.OnThrottleUpdate -= ThrottleUpdate;
  100. m_NumberScenes--;
  101. m_scene = null;
  102. }
  103. public void RegionLoaded(Scene s)
  104. {
  105. // We'll reuse the same handler for all requests.
  106. m_getTextureHandler = new GetTextureHandler(m_assetService);
  107. m_scene.EventManager.OnRegisterCaps += RegisterCaps;
  108. m_scene.EventManager.OnDeregisterCaps += DeregisterCaps;
  109. m_scene.EventManager.OnThrottleUpdate += ThrottleUpdate;
  110. m_NumberScenes++;
  111. if (m_workerThreads == null)
  112. {
  113. m_workerThreads = new Thread[2];
  114. for (uint i = 0; i < 2; i++)
  115. {
  116. m_workerThreads[i] = WorkManager.StartThread(DoTextureRequests,
  117. String.Format("GetTextureWorker{0}", i),
  118. ThreadPriority.Normal,
  119. true,
  120. false,
  121. null,
  122. int.MaxValue);
  123. }
  124. }
  125. }
  126. // Now we know when the throttle is changed by the client in the case of a root agent or by a neighbor region in the case of a child agent.
  127. public void ThrottleUpdate(ScenePresence p)
  128. {
  129. byte[] throttles = p.ControllingClient.GetThrottlesPacked(1);
  130. UUID user = p.UUID;
  131. int imagethrottle = p.ControllingClient.GetAgentThrottleSilent((int)ThrottleOutPacketType.Texture);
  132. PollServiceTextureEventArgs args;
  133. if (m_pollservices.TryGetValue(user,out args))
  134. {
  135. args.UpdateThrottle(imagethrottle);
  136. }
  137. }
  138. public void PostInitialise()
  139. {
  140. }
  141. public void Close()
  142. {
  143. if(m_NumberScenes <= 0 && m_workerThreads != null)
  144. {
  145. m_log.DebugFormat("[GetTextureModule] Closing");
  146. foreach (Thread t in m_workerThreads)
  147. Watchdog.AbortThread(t.ManagedThreadId);
  148. m_queue.Clear();
  149. }
  150. }
  151. public string Name { get { return "GetTextureModule"; } }
  152. public Type ReplaceableInterface
  153. {
  154. get { return null; }
  155. }
  156. #endregion
  157. private class PollServiceTextureEventArgs : PollServiceEventArgs
  158. {
  159. private List<Hashtable> requests =
  160. new List<Hashtable>();
  161. private Dictionary<UUID, aPollResponse> responses =
  162. new Dictionary<UUID, aPollResponse>();
  163. private HashSet<UUID> dropedResponses = new HashSet<UUID>();
  164. private Scene m_scene;
  165. private CapsDataThrottler m_throttler;
  166. public PollServiceTextureEventArgs(UUID pId, Scene scene) :
  167. base(null, "", null, null, null, null, pId, int.MaxValue)
  168. {
  169. m_scene = scene;
  170. m_throttler = new CapsDataThrottler(100000);
  171. // x is request id, y is userid
  172. HasEvents = (x, y) =>
  173. {
  174. lock (responses)
  175. {
  176. bool ret = m_throttler.hasEvents(x, responses);
  177. return ret;
  178. }
  179. };
  180. Drop = (x, y) =>
  181. {
  182. lock (responses)
  183. {
  184. responses.Remove(x);
  185. dropedResponses.Add(x);
  186. }
  187. };
  188. GetEvents = (x, y) =>
  189. {
  190. lock (responses)
  191. {
  192. try
  193. {
  194. return responses[x].response;
  195. }
  196. finally
  197. {
  198. responses.Remove(x);
  199. m_throttler.PassTime();
  200. }
  201. }
  202. };
  203. // x is request id, y is request data hashtable
  204. Request = (x, y) =>
  205. {
  206. aPollRequest reqinfo = new aPollRequest();
  207. reqinfo.thepoll = this;
  208. reqinfo.reqID = x;
  209. reqinfo.request = y;
  210. reqinfo.send503 = false;
  211. lock (responses)
  212. {
  213. if (responses.Count > 0)
  214. {
  215. if (m_queue.Count() >= 4)
  216. {
  217. // Never allow more than 4 fetches to wait
  218. reqinfo.send503 = true;
  219. }
  220. }
  221. }
  222. m_queue.Enqueue(reqinfo);
  223. m_throttler.PassTime();
  224. };
  225. // this should never happen except possible on shutdown
  226. NoEvents = (x, y) =>
  227. {
  228. /*
  229. lock (requests)
  230. {
  231. Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
  232. requests.Remove(request);
  233. }
  234. */
  235. Hashtable response = new Hashtable();
  236. response["int_response_code"] = 500;
  237. response["str_response_string"] = "Script timeout";
  238. response["content_type"] = "text/plain";
  239. response["keepalive"] = false;
  240. response["reusecontext"] = false;
  241. return response;
  242. };
  243. }
  244. public void Process(aPollRequest requestinfo)
  245. {
  246. Hashtable response;
  247. UUID requestID = requestinfo.reqID;
  248. if(m_scene.ShuttingDown)
  249. return;
  250. lock (responses)
  251. {
  252. lock(dropedResponses)
  253. {
  254. if(dropedResponses.Contains(requestID))
  255. {
  256. dropedResponses.Remove(requestID);
  257. return;
  258. }
  259. }
  260. if (requestinfo.send503)
  261. {
  262. response = new Hashtable();
  263. response["int_response_code"] = 503;
  264. response["str_response_string"] = "Throttled";
  265. response["content_type"] = "text/plain";
  266. response["keepalive"] = false;
  267. response["reusecontext"] = false;
  268. Hashtable headers = new Hashtable();
  269. headers["Retry-After"] = 30;
  270. response["headers"] = headers;
  271. responses[requestID] = new aPollResponse() {bytes = 0, response = response};
  272. return;
  273. }
  274. // If the avatar is gone, don't bother to get the texture
  275. if (m_scene.GetScenePresence(Id) == null)
  276. {
  277. response = new Hashtable();
  278. response["int_response_code"] = 500;
  279. response["str_response_string"] = "Script timeout";
  280. response["content_type"] = "text/plain";
  281. response["keepalive"] = false;
  282. response["reusecontext"] = false;
  283. responses[requestID] = new aPollResponse() {bytes = 0, response = response};
  284. return;
  285. }
  286. }
  287. response = m_getTextureHandler.Handle(requestinfo.request);
  288. lock (responses)
  289. {
  290. lock(dropedResponses)
  291. {
  292. if(dropedResponses.Contains(requestID))
  293. {
  294. dropedResponses.Remove(requestID);
  295. m_throttler.PassTime();
  296. return;
  297. }
  298. }
  299. responses[requestID] = new aPollResponse()
  300. {
  301. bytes = (int) response["int_bytes"],
  302. response = response
  303. };
  304. }
  305. m_throttler.PassTime();
  306. }
  307. internal void UpdateThrottle(int pimagethrottle)
  308. {
  309. int tmp = 2 * pimagethrottle;
  310. if(tmp < 10000)
  311. tmp = 10000;
  312. m_throttler.ThrottleBytes = tmp;
  313. }
  314. }
  315. private void RegisterCaps(UUID agentID, Caps caps)
  316. {
  317. if (m_Url == "localhost")
  318. {
  319. string capUrl = "/CAPS/" + UUID.Random() + "/";
  320. // Register this as a poll service
  321. PollServiceTextureEventArgs args = new PollServiceTextureEventArgs(agentID, m_scene);
  322. args.Type = PollServiceEventArgs.EventType.Texture;
  323. MainServer.Instance.AddPollServiceHTTPHandler(capUrl, args);
  324. string hostName = m_scene.RegionInfo.ExternalHostName;
  325. uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
  326. string protocol = "http";
  327. if (MainServer.Instance.UseSSL)
  328. {
  329. hostName = MainServer.Instance.SSLCommonName;
  330. port = MainServer.Instance.SSLPort;
  331. protocol = "https";
  332. }
  333. IExternalCapsModule handler = m_scene.RequestModuleInterface<IExternalCapsModule>();
  334. if (handler != null)
  335. handler.RegisterExternalUserCapsHandler(agentID, caps, "GetTexture", capUrl);
  336. else
  337. caps.RegisterHandler("GetTexture", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
  338. m_pollservices[agentID] = args;
  339. m_capsDict[agentID] = capUrl;
  340. }
  341. else
  342. {
  343. caps.RegisterHandler("GetTexture", m_Url);
  344. }
  345. }
  346. private void DeregisterCaps(UUID agentID, Caps caps)
  347. {
  348. PollServiceTextureEventArgs args;
  349. MainServer.Instance.RemoveHTTPHandler("", m_Url);
  350. m_capsDict.Remove(agentID);
  351. if (m_pollservices.TryGetValue(agentID, out args))
  352. {
  353. m_pollservices.Remove(agentID);
  354. }
  355. }
  356. private static void DoTextureRequests()
  357. {
  358. while (true)
  359. {
  360. aPollRequest poolreq = m_queue.Dequeue(4500);
  361. Watchdog.UpdateThread();
  362. if(m_NumberScenes <= 0)
  363. return;
  364. if(poolreq.reqID != UUID.Zero)
  365. poolreq.thepoll.Process(poolreq);
  366. }
  367. }
  368. internal sealed class CapsDataThrottler
  369. {
  370. private double lastTimeElapsed = 0;
  371. private volatile int BytesSent = 0;
  372. public CapsDataThrottler(int pBytes)
  373. {
  374. if(pBytes < 10000)
  375. pBytes = 10000;
  376. ThrottleBytes = pBytes;
  377. lastTimeElapsed = Util.GetTimeStampMS();
  378. }
  379. public bool hasEvents(UUID key, Dictionary<UUID, GetTextureModule.aPollResponse> responses)
  380. {
  381. PassTime();
  382. // Note, this is called IN LOCK
  383. bool haskey = responses.ContainsKey(key);
  384. if (!haskey)
  385. {
  386. return false;
  387. }
  388. GetTextureModule.aPollResponse response;
  389. if (responses.TryGetValue(key, out response))
  390. {
  391. // This is any error response
  392. if (response.bytes == 0)
  393. return true;
  394. // Normal
  395. if (BytesSent <= ThrottleBytes)
  396. {
  397. BytesSent += response.bytes;
  398. return true;
  399. }
  400. else
  401. {
  402. return false;
  403. }
  404. }
  405. return haskey;
  406. }
  407. public void PassTime()
  408. {
  409. double currenttime = Util.GetTimeStampMS();
  410. double timeElapsed = currenttime - lastTimeElapsed;
  411. if(timeElapsed < 50.0)
  412. return;
  413. int add = (int)(ThrottleBytes * timeElapsed * 0.001);
  414. if (add >= 1000)
  415. {
  416. lastTimeElapsed = currenttime;
  417. BytesSent -= add;
  418. if (BytesSent < 0) BytesSent = 0;
  419. }
  420. }
  421. public int ThrottleBytes;
  422. }
  423. }
  424. }