GetTextureModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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);
  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. return ret;
  197. }
  198. };
  199. GetEvents = (x, y) =>
  200. {
  201. lock (responses)
  202. {
  203. try
  204. {
  205. return responses[x].response;
  206. }
  207. finally
  208. {
  209. responses.Remove(x);
  210. m_throttler.PassTime();
  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. m_throttler.PassTime();
  235. };
  236. // this should never happen except possible on shutdown
  237. NoEvents = (x, y) =>
  238. {
  239. /*
  240. lock (requests)
  241. {
  242. Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
  243. requests.Remove(request);
  244. }
  245. */
  246. Hashtable response = new Hashtable();
  247. response["int_response_code"] = 500;
  248. response["str_response_string"] = "Script timeout";
  249. response["content_type"] = "text/plain";
  250. response["keepalive"] = false;
  251. response["reusecontext"] = false;
  252. return response;
  253. };
  254. }
  255. public void Process(aPollRequest requestinfo)
  256. {
  257. Hashtable response;
  258. UUID requestID = requestinfo.reqID;
  259. if(m_scene.ShuttingDown)
  260. return;
  261. if (requestinfo.send503)
  262. {
  263. response = new Hashtable();
  264. response["int_response_code"] = 503;
  265. response["str_response_string"] = "Throttled";
  266. response["content_type"] = "text/plain";
  267. response["keepalive"] = false;
  268. response["reusecontext"] = false;
  269. Hashtable headers = new Hashtable();
  270. headers["Retry-After"] = 30;
  271. response["headers"] = headers;
  272. lock (responses)
  273. responses[requestID] = new aPollResponse() {bytes = 0, response = response};
  274. return;
  275. }
  276. // If the avatar is gone, don't bother to get the texture
  277. if (m_scene.GetScenePresence(Id) == null)
  278. {
  279. response = new Hashtable();
  280. response["int_response_code"] = 500;
  281. response["str_response_string"] = "Script timeout";
  282. response["content_type"] = "text/plain";
  283. response["keepalive"] = false;
  284. response["reusecontext"] = false;
  285. lock (responses)
  286. responses[requestID] = new aPollResponse() {bytes = 0, response = response};
  287. return;
  288. }
  289. response = m_getTextureHandler.Handle(requestinfo.request);
  290. lock (responses)
  291. {
  292. responses[requestID] = new aPollResponse()
  293. {
  294. bytes = (int) response["int_bytes"],
  295. response = response
  296. };
  297. }
  298. m_throttler.PassTime();
  299. }
  300. internal void UpdateThrottle(int pimagethrottle)
  301. {
  302. int tmp = 2 * pimagethrottle;
  303. if(tmp < 10000)
  304. tmp = 10000;
  305. m_throttler.ThrottleBytes = tmp;
  306. }
  307. }
  308. private void RegisterCaps(UUID agentID, Caps caps)
  309. {
  310. if (m_Url == "localhost")
  311. {
  312. string capUrl = "/CAPS/" + UUID.Random() + "/";
  313. // Register this as a poll service
  314. PollServiceTextureEventArgs args = new PollServiceTextureEventArgs(agentID, m_scene);
  315. args.Type = PollServiceEventArgs.EventType.Texture;
  316. MainServer.Instance.AddPollServiceHTTPHandler(capUrl, args);
  317. string hostName = m_scene.RegionInfo.ExternalHostName;
  318. uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
  319. string protocol = "http";
  320. if (MainServer.Instance.UseSSL)
  321. {
  322. hostName = MainServer.Instance.SSLCommonName;
  323. port = MainServer.Instance.SSLPort;
  324. protocol = "https";
  325. }
  326. IExternalCapsModule handler = m_scene.RequestModuleInterface<IExternalCapsModule>();
  327. if (handler != null)
  328. handler.RegisterExternalUserCapsHandler(agentID, caps, "GetTexture", capUrl);
  329. else
  330. caps.RegisterHandler("GetTexture", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
  331. m_pollservices[agentID] = args;
  332. m_capsDict[agentID] = capUrl;
  333. }
  334. else
  335. {
  336. caps.RegisterHandler("GetTexture", m_Url);
  337. }
  338. }
  339. private void DeregisterCaps(UUID agentID, Caps caps)
  340. {
  341. PollServiceTextureEventArgs args;
  342. MainServer.Instance.RemoveHTTPHandler("", m_Url);
  343. m_capsDict.Remove(agentID);
  344. if (m_pollservices.TryGetValue(agentID, out args))
  345. {
  346. m_pollservices.Remove(agentID);
  347. }
  348. }
  349. private static void DoTextureRequests()
  350. {
  351. while (true)
  352. {
  353. aPollRequest poolreq = m_queue.Dequeue(4500);
  354. Watchdog.UpdateThread();
  355. if(m_NumberScenes <= 0)
  356. return;
  357. if(poolreq.reqID != UUID.Zero)
  358. poolreq.thepoll.Process(poolreq);
  359. }
  360. }
  361. internal sealed class CapsDataThrottler
  362. {
  363. private double lastTimeElapsed = 0;
  364. private volatile int BytesSent = 0;
  365. public CapsDataThrottler(int pBytes)
  366. {
  367. if(pBytes < 10000)
  368. pBytes = 10000;
  369. ThrottleBytes = pBytes;
  370. lastTimeElapsed = Util.GetTimeStampMS();
  371. }
  372. public bool hasEvents(UUID key, Dictionary<UUID, GetTextureModule.aPollResponse> responses)
  373. {
  374. PassTime();
  375. // Note, this is called IN LOCK
  376. bool haskey = responses.ContainsKey(key);
  377. if (!haskey)
  378. {
  379. return false;
  380. }
  381. GetTextureModule.aPollResponse response;
  382. if (responses.TryGetValue(key, out response))
  383. {
  384. // This is any error response
  385. if (response.bytes == 0)
  386. return true;
  387. // Normal
  388. if (BytesSent <= ThrottleBytes)
  389. {
  390. BytesSent += response.bytes;
  391. return true;
  392. }
  393. else
  394. {
  395. return false;
  396. }
  397. }
  398. return haskey;
  399. }
  400. public void PassTime()
  401. {
  402. double currenttime = Util.GetTimeStampMS();
  403. double timeElapsed = currenttime - lastTimeElapsed;
  404. if(timeElapsed < 50.0)
  405. return;
  406. int add = (int)(ThrottleBytes * timeElapsed * 0.001);
  407. if (add >= 1000)
  408. {
  409. lastTimeElapsed = currenttime;
  410. BytesSent -= add;
  411. if (BytesSent < 0) BytesSent = 0;
  412. }
  413. }
  414. public int ThrottleBytes;
  415. }
  416. }
  417. }