GetTextureModule.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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.Collections.Concurrent;
  31. using System.Reflection;
  32. using System.Threading;
  33. using log4net;
  34. using Nini.Config;
  35. using Mono.Addins;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Servers;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenSim.Services.Interfaces;
  43. using Caps = OpenSim.Framework.Capabilities.Caps;
  44. using OpenSim.Capabilities.Handlers;
  45. using OpenSim.Framework.Monitoring;
  46. namespace OpenSim.Region.ClientStack.Linden
  47. {
  48. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GetTextureModule")]
  49. public class GetTextureModule : INonSharedRegionModule
  50. {
  51. class APollRequest
  52. {
  53. public PollServiceTextureEventArgs thepoll;
  54. public UUID reqID;
  55. public Hashtable request;
  56. public bool send503;
  57. }
  58. public class APollResponse
  59. {
  60. public Hashtable response;
  61. public int bytes;
  62. }
  63. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  64. private Scene m_scene;
  65. private static GetTextureHandler m_getTextureHandler;
  66. private IAssetService m_assetService = null;
  67. private Dictionary<UUID, string> m_capsDict = new Dictionary<UUID, string>();
  68. private static Thread[] m_workerThreads = null;
  69. private static int m_NumberScenes = 0;
  70. private static BlockingCollection<APollRequest> m_queue = new BlockingCollection<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. }
  94. public void RemoveRegion(Scene s)
  95. {
  96. s.EventManager.OnRegisterCaps -= RegisterCaps;
  97. s.EventManager.OnDeregisterCaps -= DeregisterCaps;
  98. m_NumberScenes--;
  99. m_scene = null;
  100. }
  101. public void RegionLoaded(Scene s)
  102. {
  103. if(m_assetService == null)
  104. {
  105. m_assetService = s.RequestModuleInterface<IAssetService>();
  106. // We'll reuse the same handler for all requests.
  107. m_getTextureHandler = new GetTextureHandler(m_assetService);
  108. }
  109. s.EventManager.OnRegisterCaps += RegisterCaps;
  110. s.EventManager.OnDeregisterCaps += DeregisterCaps;
  111. m_NumberScenes++;
  112. if (m_workerThreads == null)
  113. {
  114. m_workerThreads = new Thread[2];
  115. for (uint i = 0; i < 2; i++)
  116. {
  117. m_workerThreads[i] = WorkManager.StartThread(DoTextureRequests,
  118. String.Format("GetTextureWorker{0}", i),
  119. ThreadPriority.Normal,
  120. true,
  121. false,
  122. null,
  123. int.MaxValue);
  124. }
  125. }
  126. }
  127. public void PostInitialise()
  128. {
  129. }
  130. public void Close()
  131. {
  132. if(m_NumberScenes <= 0 && m_workerThreads != null)
  133. {
  134. m_log.DebugFormat("[GetTextureModule] Closing");
  135. foreach (Thread t in m_workerThreads)
  136. Watchdog.AbortThread(t.ManagedThreadId);
  137. m_queue.Dispose();
  138. }
  139. }
  140. public string Name { get { return "GetTextureModule"; } }
  141. public Type ReplaceableInterface
  142. {
  143. get { return null; }
  144. }
  145. #endregion
  146. private class PollServiceTextureEventArgs : PollServiceEventArgs
  147. {
  148. private List<Hashtable> requests =
  149. new List<Hashtable>();
  150. private Dictionary<UUID, APollResponse> responses =
  151. new Dictionary<UUID, APollResponse>();
  152. private HashSet<UUID> dropedResponses = new HashSet<UUID>();
  153. private Scene m_scene;
  154. private ScenePresence m_presence;
  155. public PollServiceTextureEventArgs(UUID pId, Scene scene) :
  156. base(null, "", null, null, null, null, pId, int.MaxValue)
  157. {
  158. m_scene = scene;
  159. // x is request id, y is userid
  160. HasEvents = (x, y) =>
  161. {
  162. lock (responses)
  163. {
  164. APollResponse response;
  165. if (responses.TryGetValue(x, out response))
  166. {
  167. if (m_presence == null)
  168. m_presence = m_scene.GetScenePresence(pId);
  169. if (m_presence == null || m_presence.IsDeleted)
  170. return true;
  171. return m_presence.CapCanSendAsset(0, response.bytes);
  172. }
  173. return false;
  174. }
  175. };
  176. Drop = (x, y) =>
  177. {
  178. lock (responses)
  179. {
  180. responses.Remove(x);
  181. dropedResponses.Add(x);
  182. }
  183. };
  184. GetEvents = (x, y) =>
  185. {
  186. lock (responses)
  187. {
  188. try
  189. {
  190. return responses[x].response;
  191. }
  192. finally
  193. {
  194. responses.Remove(x);
  195. }
  196. }
  197. };
  198. // x is request id, y is request data hashtable
  199. Request = (x, y) =>
  200. {
  201. APollRequest reqinfo = new APollRequest();
  202. reqinfo.thepoll = this;
  203. reqinfo.reqID = x;
  204. reqinfo.request = y;
  205. reqinfo.send503 = false;
  206. lock (responses)
  207. {
  208. if (responses.Count > 0 && m_queue.Count > 32)
  209. reqinfo.send503 = true;
  210. }
  211. m_queue.Add(reqinfo);
  212. };
  213. // this should never happen except possible on shutdown
  214. NoEvents = (x, y) =>
  215. {
  216. /*
  217. lock (requests)
  218. {
  219. Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
  220. requests.Remove(request);
  221. }
  222. */
  223. Hashtable response = new Hashtable();
  224. response["int_response_code"] = 500;
  225. response["str_response_string"] = "timeout";
  226. response["content_type"] = "text/plain";
  227. response["keepalive"] = false;
  228. return response;
  229. };
  230. }
  231. public void Process(APollRequest requestinfo)
  232. {
  233. Hashtable response;
  234. UUID requestID = requestinfo.reqID;
  235. if(m_scene.ShuttingDown)
  236. return;
  237. lock (responses)
  238. {
  239. lock(dropedResponses)
  240. {
  241. if(dropedResponses.Contains(requestID))
  242. {
  243. dropedResponses.Remove(requestID);
  244. return;
  245. }
  246. }
  247. if (m_presence == null)
  248. m_presence = m_scene.GetScenePresence(Id);
  249. if (m_presence == null || m_presence.IsDeleted)
  250. requestinfo.send503 = true;
  251. if (requestinfo.send503)
  252. {
  253. response = new Hashtable();
  254. response["int_response_code"] = 503;
  255. response["str_response_string"] = "Throttled";
  256. response["content_type"] = "text/plain";
  257. response["keepalive"] = false;
  258. Hashtable headers = new Hashtable();
  259. headers["Retry-After"] = 20;
  260. response["headers"] = headers;
  261. responses[requestID] = new APollResponse() { bytes = 0, response = response };
  262. return;
  263. }
  264. }
  265. response = m_getTextureHandler.Handle(requestinfo.request);
  266. lock (responses)
  267. {
  268. lock(dropedResponses)
  269. {
  270. if(dropedResponses.Contains(requestID))
  271. {
  272. dropedResponses.Remove(requestID);
  273. return;
  274. }
  275. }
  276. responses[requestID] = new APollResponse()
  277. {
  278. bytes = (int) response["int_bytes"],
  279. response = response
  280. };
  281. }
  282. }
  283. }
  284. private void RegisterCaps(UUID agentID, Caps caps)
  285. {
  286. if (m_Url == "localhost")
  287. {
  288. string capUrl = "/CAPS/" + UUID.Random() + "/";
  289. // Register this as a poll service
  290. PollServiceTextureEventArgs args = new PollServiceTextureEventArgs(agentID, m_scene);
  291. args.Type = PollServiceEventArgs.EventType.Texture;
  292. MainServer.Instance.AddPollServiceHTTPHandler(capUrl, args);
  293. string hostName = m_scene.RegionInfo.ExternalHostName;
  294. uint port = (MainServer.Instance == null) ? 0 : MainServer.Instance.Port;
  295. string protocol = "http";
  296. if (MainServer.Instance.UseSSL)
  297. {
  298. hostName = MainServer.Instance.SSLCommonName;
  299. port = MainServer.Instance.SSLPort;
  300. protocol = "https";
  301. }
  302. IExternalCapsModule handler = m_scene.RequestModuleInterface<IExternalCapsModule>();
  303. if (handler != null)
  304. handler.RegisterExternalUserCapsHandler(agentID, caps, "GetTexture", capUrl);
  305. else
  306. caps.RegisterHandler("GetTexture", String.Format("{0}://{1}:{2}{3}", protocol, hostName, port, capUrl));
  307. m_pollservices[agentID] = args;
  308. m_capsDict[agentID] = capUrl;
  309. }
  310. else
  311. {
  312. caps.RegisterHandler("GetTexture", m_Url);
  313. }
  314. }
  315. private void DeregisterCaps(UUID agentID, Caps caps)
  316. {
  317. PollServiceTextureEventArgs args;
  318. MainServer.Instance.RemoveHTTPHandler("", m_Url);
  319. m_capsDict.Remove(agentID);
  320. if (m_pollservices.TryGetValue(agentID, out args))
  321. {
  322. m_pollservices.Remove(agentID);
  323. }
  324. }
  325. private static void DoTextureRequests()
  326. {
  327. APollRequest poolreq;
  328. while (m_NumberScenes > 0)
  329. {
  330. poolreq = null;
  331. if(!m_queue.TryTake(out poolreq, 4500) || poolreq == null)
  332. {
  333. Watchdog.UpdateThread();
  334. continue;
  335. }
  336. if(m_NumberScenes <= 0)
  337. break;
  338. Watchdog.UpdateThread();
  339. if(poolreq.reqID != UUID.Zero)
  340. poolreq.thepoll.Process(poolreq);
  341. }
  342. }
  343. }
  344. }