GetTextureModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. private int ExtractImageThrottle(byte[] pthrottles)
  127. {
  128. byte[] adjData;
  129. int pos = 0;
  130. if (!BitConverter.IsLittleEndian)
  131. {
  132. byte[] newData = new byte[7 * 4];
  133. Buffer.BlockCopy(pthrottles, 0, newData, 0, 7 * 4);
  134. for (int i = 0; i < 7; i++)
  135. Array.Reverse(newData, i * 4, 4);
  136. adjData = newData;
  137. }
  138. else
  139. {
  140. adjData = pthrottles;
  141. }
  142. pos = pos + 20;
  143. int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); //pos += 4;
  144. //int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f);
  145. return texture;
  146. }
  147. // 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.
  148. public void ThrottleUpdate(ScenePresence p)
  149. {
  150. byte[] throttles = p.ControllingClient.GetThrottlesPacked(1);
  151. UUID user = p.UUID;
  152. int imagethrottle = ExtractImageThrottle(throttles);
  153. PollServiceTextureEventArgs args;
  154. if (m_pollservices.TryGetValue(user,out args))
  155. {
  156. args.UpdateThrottle(imagethrottle);
  157. }
  158. }
  159. public void PostInitialise()
  160. {
  161. }
  162. public void Close()
  163. {
  164. if(m_NumberScenes <= 0 && m_workerThreads != null)
  165. {
  166. m_log.DebugFormat("[GetTextureModule] Closing");
  167. foreach (Thread t in m_workerThreads)
  168. Watchdog.AbortThread(t.ManagedThreadId);
  169. m_queue.Clear();
  170. }
  171. }
  172. public string Name { get { return "GetTextureModule"; } }
  173. public Type ReplaceableInterface
  174. {
  175. get { return null; }
  176. }
  177. #endregion
  178. private class PollServiceTextureEventArgs : PollServiceEventArgs
  179. {
  180. private List<Hashtable> requests =
  181. new List<Hashtable>();
  182. private Dictionary<UUID, aPollResponse> responses =
  183. new Dictionary<UUID, aPollResponse>();
  184. private Scene m_scene;
  185. private CapsDataThrottler m_throttler = new CapsDataThrottler(100000, 1400000,10000);
  186. public PollServiceTextureEventArgs(UUID pId, Scene scene) :
  187. base(null, "", null, null, null, pId, int.MaxValue)
  188. {
  189. m_scene = scene;
  190. // x is request id, y is userid
  191. HasEvents = (x, y) =>
  192. {
  193. lock (responses)
  194. {
  195. bool ret = m_throttler.hasEvents(x, responses);
  196. m_throttler.ProcessTime();
  197. return ret;
  198. }
  199. };
  200. GetEvents = (x, y) =>
  201. {
  202. lock (responses)
  203. {
  204. try
  205. {
  206. return responses[x].response;
  207. }
  208. finally
  209. {
  210. responses.Remove(x);
  211. }
  212. }
  213. };
  214. // x is request id, y is request data hashtable
  215. Request = (x, y) =>
  216. {
  217. aPollRequest reqinfo = new aPollRequest();
  218. reqinfo.thepoll = this;
  219. reqinfo.reqID = x;
  220. reqinfo.request = y;
  221. reqinfo.send503 = false;
  222. lock (responses)
  223. {
  224. if (responses.Count > 0)
  225. {
  226. if (m_queue.Count() >= 4)
  227. {
  228. // Never allow more than 4 fetches to wait
  229. reqinfo.send503 = true;
  230. }
  231. }
  232. }
  233. m_queue.Enqueue(reqinfo);
  234. };
  235. // this should never happen except possible on shutdown
  236. NoEvents = (x, y) =>
  237. {
  238. /*
  239. lock (requests)
  240. {
  241. Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
  242. requests.Remove(request);
  243. }
  244. */
  245. Hashtable response = new Hashtable();
  246. response["int_response_code"] = 500;
  247. response["str_response_string"] = "Script timeout";
  248. response["content_type"] = "text/plain";
  249. response["keepalive"] = false;
  250. response["reusecontext"] = false;
  251. return response;
  252. };
  253. }
  254. public void Process(aPollRequest requestinfo)
  255. {
  256. Hashtable response;
  257. UUID requestID = requestinfo.reqID;
  258. if(m_scene.ShuttingDown)
  259. return;
  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. lock (responses)
  272. responses[requestID] = new aPollResponse() {bytes = 0, response = response};
  273. return;
  274. }
  275. // If the avatar is gone, don't bother to get the texture
  276. if (m_scene.GetScenePresence(Id) == null)
  277. {
  278. response = new Hashtable();
  279. response["int_response_code"] = 500;
  280. response["str_response_string"] = "Script timeout";
  281. response["content_type"] = "text/plain";
  282. response["keepalive"] = false;
  283. response["reusecontext"] = false;
  284. lock (responses)
  285. responses[requestID] = new aPollResponse() {bytes = 0, response = response};
  286. return;
  287. }
  288. response = m_getTextureHandler.Handle(requestinfo.request);
  289. lock (responses)
  290. {
  291. responses[requestID] = new aPollResponse()
  292. {
  293. bytes = (int) response["int_bytes"],
  294. response = response
  295. };
  296. }
  297. m_throttler.ProcessTime();
  298. }
  299. internal void UpdateThrottle(int pimagethrottle)
  300. {
  301. m_throttler.ThrottleBytes = 2 * pimagethrottle;
  302. if(m_throttler.ThrottleBytes < 10000)
  303. m_throttler.ThrottleBytes = 10000;
  304. }
  305. }
  306. private void RegisterCaps(UUID agentID, Caps caps)
  307. {
  308. if (m_Url == "localhost")
  309. {
  310. string capUrl = "/CAPS/" + UUID.Random() + "/";
  311. // Register this as a poll service
  312. PollServiceTextureEventArgs args = new PollServiceTextureEventArgs(agentID, m_scene);
  313. args.Type = PollServiceEventArgs.EventType.Texture;
  314. MainServer.Instance.AddPollServiceHTTPHandler(capUrl, args);
  315. string hostName = m_scene.RegionInfo.ExternalHostName;
  316. uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
  317. string protocol = "http";
  318. if (MainServer.Instance.UseSSL)
  319. {
  320. hostName = MainServer.Instance.SSLCommonName;
  321. port = MainServer.Instance.SSLPort;
  322. protocol = "https";
  323. }
  324. IExternalCapsModule handler = m_scene.RequestModuleInterface<IExternalCapsModule>();
  325. if (handler != null)
  326. handler.RegisterExternalUserCapsHandler(agentID, caps, "GetTexture", capUrl);
  327. else
  328. caps.RegisterHandler("GetTexture", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
  329. m_pollservices[agentID] = args;
  330. m_capsDict[agentID] = capUrl;
  331. }
  332. else
  333. {
  334. caps.RegisterHandler("GetTexture", m_Url);
  335. }
  336. }
  337. private void DeregisterCaps(UUID agentID, Caps caps)
  338. {
  339. PollServiceTextureEventArgs args;
  340. MainServer.Instance.RemoveHTTPHandler("", m_Url);
  341. m_capsDict.Remove(agentID);
  342. if (m_pollservices.TryGetValue(agentID, out args))
  343. {
  344. m_pollservices.Remove(agentID);
  345. }
  346. }
  347. private static void DoTextureRequests()
  348. {
  349. while (true)
  350. {
  351. aPollRequest poolreq = m_queue.Dequeue(4500);
  352. Watchdog.UpdateThread();
  353. if(m_NumberScenes <= 0)
  354. return;
  355. if(poolreq.reqID != UUID.Zero)
  356. poolreq.thepoll.Process(poolreq);
  357. }
  358. }
  359. internal sealed class CapsDataThrottler
  360. {
  361. private volatile int currenttime = 0;
  362. private volatile int lastTimeElapsed = 0;
  363. private volatile int BytesSent = 0;
  364. public CapsDataThrottler(int pBytes, int max, int min)
  365. {
  366. ThrottleBytes = pBytes;
  367. if(ThrottleBytes < 10000)
  368. ThrottleBytes = 10000;
  369. lastTimeElapsed = Util.EnvironmentTickCount();
  370. }
  371. public bool hasEvents(UUID key, Dictionary<UUID, GetTextureModule.aPollResponse> responses)
  372. {
  373. PassTime();
  374. // Note, this is called IN LOCK
  375. bool haskey = responses.ContainsKey(key);
  376. if (!haskey)
  377. {
  378. return false;
  379. }
  380. GetTextureModule.aPollResponse response;
  381. if (responses.TryGetValue(key, out response))
  382. {
  383. // This is any error response
  384. if (response.bytes == 0)
  385. return true;
  386. // Normal
  387. if (BytesSent <= ThrottleBytes)
  388. {
  389. BytesSent += response.bytes;
  390. return true;
  391. }
  392. else
  393. {
  394. return false;
  395. }
  396. }
  397. return haskey;
  398. }
  399. public void ProcessTime()
  400. {
  401. PassTime();
  402. }
  403. private void PassTime()
  404. {
  405. currenttime = Util.EnvironmentTickCount();
  406. int timeElapsed = Util.EnvironmentTickCountSubtract(currenttime, lastTimeElapsed);
  407. //processTimeBasedActions(responses);
  408. if (timeElapsed >= 100)
  409. {
  410. lastTimeElapsed = currenttime;
  411. BytesSent -= (ThrottleBytes * timeElapsed / 1000);
  412. if (BytesSent < 0) BytesSent = 0;
  413. }
  414. }
  415. public int ThrottleBytes;
  416. }
  417. }
  418. }