GetMeshModule.cs 17 KB

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