EventQueueGetModule.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 OpenSim 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.Net;
  31. using System.Net.Sockets;
  32. using System.Reflection;
  33. using System.Threading;
  34. using System.Xml;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using log4net;
  38. using Nini.Config;
  39. using Nwc.XmlRpc;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Communications.Cache;
  42. using OpenSim.Framework.Communications.Capabilities;
  43. using OpenSim.Framework.Servers;
  44. using OpenSim.Region.Environment.Interfaces;
  45. using OpenSim.Region.Interfaces;
  46. using OpenSim.Region.Environment.Scenes;
  47. using OSD = OpenMetaverse.StructuredData.OSD;
  48. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  49. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  50. using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
  51. using BlockingLLSDQueue = OpenSim.Framework.BlockingQueue<OpenMetaverse.StructuredData.OSD>;
  52. namespace OpenSim.Region.Environment.Modules.Framework.EventQueue
  53. {
  54. public struct QueueItem
  55. {
  56. public int id;
  57. public OSDMap body;
  58. }
  59. public class EventQueueGetModule : IEventQueue, IRegionModule
  60. {
  61. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  62. private Scene m_scene = null;
  63. private IConfigSource m_gConfig;
  64. bool enabledYN = false;
  65. private Dictionary<UUID, int> m_ids = new Dictionary<UUID, int>();
  66. private Dictionary<UUID, BlockingLLSDQueue> queues = new Dictionary<UUID, BlockingLLSDQueue>();
  67. private Dictionary<UUID, UUID> m_QueueUUIDAvatarMapping = new Dictionary<UUID, UUID>();
  68. private Dictionary<UUID, UUID> m_AvatarQueueUUIDMapping = new Dictionary<UUID, UUID>();
  69. #region IRegionModule methods
  70. public void Initialise(Scene scene, IConfigSource config)
  71. {
  72. m_gConfig = config;
  73. IConfig startupConfig = m_gConfig.Configs["Startup"];
  74. ReadConfigAndPopulate(scene, startupConfig, "Startup");
  75. if (enabledYN)
  76. {
  77. m_scene = scene;
  78. scene.RegisterModuleInterface<IEventQueue>(this);
  79. // Register fallback handler
  80. // Why does EQG Fail on region crossings!
  81. //scene.CommsManager.HttpServer.AddLLSDHandler("/CAPS/EQG/", EventQueueFallBack);
  82. scene.EventManager.OnNewClient += OnNewClient;
  83. // TODO: Leaving these open, or closing them when we
  84. // become a child is incorrect. It messes up TP in a big
  85. // way. CAPS/EQ need to be active as long as the UDP
  86. // circuit is there.
  87. scene.EventManager.OnClientClosed += ClientClosed;
  88. scene.EventManager.OnMakeChildAgent += MakeChildAgent;
  89. scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  90. }
  91. else
  92. {
  93. m_gConfig = null;
  94. }
  95. }
  96. private void ReadConfigAndPopulate(Scene scene, IConfig startupConfig, string p)
  97. {
  98. enabledYN = startupConfig.GetBoolean("EventQueue", true);
  99. }
  100. public void PostInitialise()
  101. {
  102. }
  103. public void Close()
  104. {
  105. }
  106. public string Name
  107. {
  108. get { return "EventQueueGetModule"; }
  109. }
  110. public bool IsSharedModule
  111. {
  112. get { return false; }
  113. }
  114. #endregion
  115. /// <summary>
  116. /// Always returns a valid queue
  117. /// </summary>
  118. /// <param name="agentId"></param>
  119. /// <returns></returns>
  120. private BlockingLLSDQueue TryGetQueue(UUID agentId)
  121. {
  122. lock (queues)
  123. {
  124. if (!queues.ContainsKey(agentId))
  125. {
  126. m_log.DebugFormat(
  127. "[EVENTQUEUE]: Adding new queue for agent {0} in region {1}",
  128. agentId, m_scene.RegionInfo.RegionName);
  129. queues[agentId] = new BlockingLLSDQueue();
  130. }
  131. return queues[agentId];
  132. }
  133. }
  134. /// <summary>
  135. /// May return a null queue
  136. /// </summary>
  137. /// <param name="agentId"></param>
  138. /// <returns></returns>
  139. private BlockingLLSDQueue GetQueue(UUID agentId)
  140. {
  141. lock (queues)
  142. {
  143. if (queues.ContainsKey(agentId))
  144. {
  145. return queues[agentId];
  146. }
  147. else
  148. return null;
  149. }
  150. }
  151. #region IEventQueue Members
  152. public bool Enqueue(OSD ev, UUID avatarID)
  153. {
  154. //m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
  155. try
  156. {
  157. BlockingLLSDQueue queue = GetQueue(avatarID);
  158. if (queue != null)
  159. queue.Enqueue(ev);
  160. }
  161. catch(NullReferenceException e)
  162. {
  163. m_log.Error("[EVENTQUEUE] Caught exception: " + e);
  164. return false;
  165. }
  166. return true;
  167. }
  168. #endregion
  169. private void OnNewClient(IClientAPI client)
  170. {
  171. //client.OnLogout += ClientClosed;
  172. }
  173. // private void ClientClosed(IClientAPI client)
  174. // {
  175. // ClientClosed(client.AgentId);
  176. // }
  177. private void ClientClosed(UUID AgentID)
  178. {
  179. m_log.DebugFormat("[EVENTQUEUE]: Closed client {0} in region {1}", AgentID, m_scene.RegionInfo.RegionName);
  180. int count = 0;
  181. while (queues.ContainsKey(AgentID) && queues[AgentID].Count() > 0 && count++ < 5)
  182. {
  183. Thread.Sleep(1000);
  184. }
  185. lock (queues)
  186. {
  187. queues.Remove(AgentID);
  188. }
  189. List<UUID> removeitems = new List<UUID>();
  190. lock (m_AvatarQueueUUIDMapping)
  191. {
  192. foreach (UUID ky in m_AvatarQueueUUIDMapping.Keys)
  193. {
  194. if (ky == AgentID)
  195. {
  196. removeitems.Add(ky);
  197. }
  198. }
  199. foreach (UUID ky in removeitems)
  200. {
  201. m_AvatarQueueUUIDMapping.Remove(ky);
  202. m_scene.CommsManager.HttpServer.RemoveHTTPHandler("","/CAPS/EQG/" + ky.ToString() + "/");
  203. }
  204. }
  205. UUID searchval = UUID.Zero;
  206. removeitems.Clear();
  207. lock (m_QueueUUIDAvatarMapping)
  208. {
  209. foreach (UUID ky in m_QueueUUIDAvatarMapping.Keys)
  210. {
  211. searchval = m_QueueUUIDAvatarMapping[ky];
  212. if (searchval == AgentID)
  213. {
  214. removeitems.Add(ky);
  215. }
  216. }
  217. foreach (UUID ky in removeitems)
  218. m_QueueUUIDAvatarMapping.Remove(ky);
  219. }
  220. }
  221. private void MakeChildAgent(ScenePresence avatar)
  222. {
  223. //m_log.DebugFormat("[EVENTQUEUE]: Make Child agent {0} in region {1}.", avatar.UUID, m_scene.RegionInfo.RegionName);
  224. //lock (m_ids)
  225. // {
  226. //if (m_ids.ContainsKey(avatar.UUID))
  227. //{
  228. // close the event queue.
  229. //m_ids[avatar.UUID] = -1;
  230. //}
  231. //}
  232. }
  233. public void OnRegisterCaps(UUID agentID, Caps caps)
  234. {
  235. // Register an event queue for the client
  236. //m_log.DebugFormat(
  237. // "[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}",
  238. // agentID, caps, m_scene.RegionInfo.RegionName);
  239. // Let's instantiate a Queue for this agent right now
  240. TryGetQueue(agentID);
  241. string capsBase = "/CAPS/EQG/";
  242. UUID EventQueueGetUUID = UUID.Zero;
  243. lock (m_AvatarQueueUUIDMapping)
  244. {
  245. // Reuse open queues. The client does!
  246. if (m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  247. {
  248. m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!");
  249. EventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID];
  250. }
  251. else
  252. {
  253. EventQueueGetUUID = UUID.Random();
  254. //m_log.DebugFormat("[EVENTQUEUE]: Using random UUID!");
  255. }
  256. }
  257. lock (m_QueueUUIDAvatarMapping)
  258. {
  259. if (!m_QueueUUIDAvatarMapping.ContainsKey(EventQueueGetUUID))
  260. m_QueueUUIDAvatarMapping.Add(EventQueueGetUUID, agentID);
  261. }
  262. lock (m_AvatarQueueUUIDMapping)
  263. {
  264. if (!m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  265. m_AvatarQueueUUIDMapping.Add(agentID, EventQueueGetUUID);
  266. }
  267. // Register this as a caps handler
  268. caps.RegisterHandler("EventQueueGet",
  269. new RestHTTPHandler("POST", capsBase + EventQueueGetUUID.ToString() + "/",
  270. delegate(Hashtable m_dhttpMethod)
  271. {
  272. return ProcessQueue(m_dhttpMethod, agentID, caps);
  273. }));
  274. // This will persist this beyond the expiry of the caps handlers
  275. m_scene.CommsManager.HttpServer.AddHTTPHandler(
  276. capsBase + EventQueueGetUUID.ToString() + "/", EventQueuePath2);
  277. Random rnd = new Random(System.Environment.TickCount);
  278. lock (m_ids)
  279. {
  280. if (!m_ids.ContainsKey(agentID))
  281. m_ids.Add(agentID, rnd.Next(30000000));
  282. }
  283. }
  284. public Hashtable ProcessQueue(Hashtable request, UUID agentID, Caps caps)
  285. {
  286. // TODO: this has to be redone to not busy-wait (and block the thread),
  287. // TODO: as soon as we have a non-blocking way to handle HTTP-requests.
  288. // if (m_log.IsDebugEnabled)
  289. // {
  290. // String debug = "[EVENTQUEUE]: Got request for agent {0} in region {1} from thread {2}: [ ";
  291. // foreach (object key in request.Keys)
  292. // {
  293. // debug += key.ToString() + "=" + request[key].ToString() + " ";
  294. // }
  295. // m_log.DebugFormat(debug + " ]", agentID, m_scene.RegionInfo.RegionName, System.Threading.Thread.CurrentThread.Name);
  296. // }
  297. BlockingLLSDQueue queue = TryGetQueue(agentID);
  298. OSD element = queue.Dequeue(15000); // 15s timeout
  299. Hashtable responsedata = new Hashtable();
  300. int thisID = 0;
  301. lock (m_ids)
  302. thisID = m_ids[agentID];
  303. if (element == null)
  304. {
  305. //m_log.ErrorFormat("[EVENTQUEUE]: Nothing to process in " + m_scene.RegionInfo.RegionName);
  306. if (thisID == -1) // close-request
  307. {
  308. m_log.ErrorFormat("[EVENTQUEUE]: 404 in " + m_scene.RegionInfo.RegionName);
  309. responsedata["int_response_code"] = 404; //501; //410; //404;
  310. responsedata["content_type"] = "text/plain";
  311. responsedata["keepalive"] = false;
  312. responsedata["str_response_string"] = "Closed EQG";
  313. return responsedata;
  314. }
  315. responsedata["int_response_code"] = 502;
  316. responsedata["content_type"] = "text/plain";
  317. responsedata["keepalive"] = false;
  318. responsedata["str_response_string"] = "Upstream error: ";
  319. responsedata["error_status_text"] = "Upstream error:";
  320. responsedata["http_protocol_version"] = "HTTP/1.0";
  321. return responsedata;
  322. }
  323. OSDArray array = new OSDArray();
  324. if (element == null) // didn't have an event in 15s
  325. {
  326. // Send it a fake event to keep the client polling! It doesn't like 502s like the proxys say!
  327. array.Add(EventQueueHelper.KeepAliveEvent());
  328. m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
  329. }
  330. else
  331. {
  332. array.Add(element);
  333. while (queue.Count() > 0)
  334. {
  335. array.Add(queue.Dequeue(1));
  336. thisID++;
  337. }
  338. }
  339. OSDMap events = new OSDMap();
  340. events.Add("events", array);
  341. events.Add("id", new OSDInteger(thisID));
  342. lock (m_ids)
  343. {
  344. m_ids[agentID] = thisID + 1;
  345. }
  346. responsedata["int_response_code"] = 200;
  347. responsedata["content_type"] = "application/xml";
  348. responsedata["keepalive"] = false;
  349. responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
  350. //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
  351. return responsedata;
  352. }
  353. public Hashtable EventQueuePath2(Hashtable request)
  354. {
  355. string capuuid = (string)request["uri"]; //path.Replace("/CAPS/EQG/","");
  356. // pull off the last "/" in the path.
  357. Hashtable responsedata = new Hashtable();
  358. capuuid = capuuid.Substring(0, capuuid.Length - 1);
  359. capuuid = capuuid.Replace("/CAPS/EQG/", "");
  360. UUID AvatarID = UUID.Zero;
  361. UUID capUUID = UUID.Zero;
  362. // parse the path and search for the avatar with it registered
  363. if (UUID.TryParse(capuuid, out capUUID))
  364. {
  365. lock (m_QueueUUIDAvatarMapping)
  366. {
  367. if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
  368. {
  369. AvatarID = m_QueueUUIDAvatarMapping[capUUID];
  370. }
  371. }
  372. if (AvatarID != UUID.Zero)
  373. {
  374. // m_scene.GetCapsHandlerForUser will return null if the agent doesn't have a caps handler
  375. // registered
  376. return ProcessQueue(request, AvatarID, m_scene.GetCapsHandlerForUser(AvatarID));
  377. }
  378. else
  379. {
  380. responsedata["int_response_code"] = 404;
  381. responsedata["content_type"] = "text/plain";
  382. responsedata["keepalive"] = false;
  383. responsedata["str_response_string"] = "Not Found";
  384. responsedata["error_status_text"] = "Not Found";
  385. responsedata["http_protocol_version"] = "HTTP/1.0";
  386. return responsedata;
  387. // return 404
  388. }
  389. }
  390. else
  391. {
  392. responsedata["int_response_code"] = 404;
  393. responsedata["content_type"] = "text/plain";
  394. responsedata["keepalive"] = false;
  395. responsedata["str_response_string"] = "Not Found";
  396. responsedata["error_status_text"] = "Not Found";
  397. responsedata["http_protocol_version"] = "HTTP/1.0";
  398. return responsedata;
  399. // return 404
  400. }
  401. }
  402. public OSD EventQueueFallBack(string path, OSD request, string endpoint)
  403. {
  404. // This is a fallback element to keep the client from loosing EventQueueGet
  405. // Why does CAPS fail sometimes!?
  406. m_log.Warn("[EVENTQUEUE]: In the Fallback handler! We lost the Queue in the rest handler!");
  407. string capuuid = path.Replace("/CAPS/EQG/","");
  408. capuuid = capuuid.Substring(0, capuuid.Length - 1);
  409. // UUID AvatarID = UUID.Zero;
  410. UUID capUUID = UUID.Zero;
  411. if (UUID.TryParse(capuuid, out capUUID))
  412. {
  413. /* Don't remove this yet code cleaners!
  414. * Still testing this!
  415. *
  416. lock (m_QueueUUIDAvatarMapping)
  417. {
  418. if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
  419. {
  420. AvatarID = m_QueueUUIDAvatarMapping[capUUID];
  421. }
  422. }
  423. if (AvatarID != UUID.Zero)
  424. {
  425. // Repair the CAP!
  426. //OpenSim.Framework.Communications.Capabilities.Caps caps = m_scene.GetCapsHandlerForUser(AvatarID);
  427. //string capsBase = "/CAPS/EQG/";
  428. //caps.RegisterHandler("EventQueueGet",
  429. //new RestHTTPHandler("POST", capsBase + capUUID.ToString() + "/",
  430. //delegate(Hashtable m_dhttpMethod)
  431. //{
  432. // return ProcessQueue(m_dhttpMethod, AvatarID, caps);
  433. //}));
  434. // start new ID sequence.
  435. Random rnd = new Random(System.Environment.TickCount);
  436. lock (m_ids)
  437. {
  438. if (!m_ids.ContainsKey(AvatarID))
  439. m_ids.Add(AvatarID, rnd.Next(30000000));
  440. }
  441. int thisID = 0;
  442. lock (m_ids)
  443. thisID = m_ids[AvatarID];
  444. BlockingLLSDQueue queue = GetQueue(AvatarID);
  445. OSDArray array = new OSDArray();
  446. LLSD element = queue.Dequeue(15000); // 15s timeout
  447. if (element == null)
  448. {
  449. array.Add(EventQueueHelper.KeepAliveEvent());
  450. }
  451. else
  452. {
  453. array.Add(element);
  454. while (queue.Count() > 0)
  455. {
  456. array.Add(queue.Dequeue(1));
  457. thisID++;
  458. }
  459. }
  460. OSDMap events = new OSDMap();
  461. events.Add("events", array);
  462. events.Add("id", new LLSDInteger(thisID));
  463. lock (m_ids)
  464. {
  465. m_ids[AvatarID] = thisID + 1;
  466. }
  467. return events;
  468. }
  469. else
  470. {
  471. return new LLSD();
  472. }
  473. *
  474. */
  475. }
  476. else
  477. {
  478. //return new LLSD();
  479. }
  480. return new OSDString("shutdown404!");
  481. }
  482. }
  483. }