GetMeshModule.cs 14 KB

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