EventQueueGetModule.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. return ProcessQueue(request, AvatarID, m_scene.CapsModule.GetCapsHandlerForUser(AvatarID));
  375. }
  376. else
  377. {
  378. responsedata["int_response_code"] = 404;
  379. responsedata["content_type"] = "text/plain";
  380. responsedata["keepalive"] = false;
  381. responsedata["str_response_string"] = "Not Found";
  382. responsedata["error_status_text"] = "Not Found";
  383. responsedata["http_protocol_version"] = "HTTP/1.0";
  384. return responsedata;
  385. // return 404
  386. }
  387. }
  388. else
  389. {
  390. responsedata["int_response_code"] = 404;
  391. responsedata["content_type"] = "text/plain";
  392. responsedata["keepalive"] = false;
  393. responsedata["str_response_string"] = "Not Found";
  394. responsedata["error_status_text"] = "Not Found";
  395. responsedata["http_protocol_version"] = "HTTP/1.0";
  396. return responsedata;
  397. // return 404
  398. }
  399. }
  400. public OSD EventQueueFallBack(string path, OSD request, string endpoint)
  401. {
  402. // This is a fallback element to keep the client from loosing EventQueueGet
  403. // Why does CAPS fail sometimes!?
  404. m_log.Warn("[EVENTQUEUE]: In the Fallback handler! We lost the Queue in the rest handler!");
  405. string capuuid = path.Replace("/CAPS/EQG/","");
  406. capuuid = capuuid.Substring(0, capuuid.Length - 1);
  407. // UUID AvatarID = UUID.Zero;
  408. UUID capUUID = UUID.Zero;
  409. if (UUID.TryParse(capuuid, out capUUID))
  410. {
  411. /* Don't remove this yet code cleaners!
  412. * Still testing this!
  413. *
  414. lock (m_QueueUUIDAvatarMapping)
  415. {
  416. if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
  417. {
  418. AvatarID = m_QueueUUIDAvatarMapping[capUUID];
  419. }
  420. }
  421. if (AvatarID != UUID.Zero)
  422. {
  423. // Repair the CAP!
  424. //OpenSim.Framework.Communications.Capabilities.Caps caps = m_scene.GetCapsHandlerForUser(AvatarID);
  425. //string capsBase = "/CAPS/EQG/";
  426. //caps.RegisterHandler("EventQueueGet",
  427. //new RestHTTPHandler("POST", capsBase + capUUID.ToString() + "/",
  428. //delegate(Hashtable m_dhttpMethod)
  429. //{
  430. // return ProcessQueue(m_dhttpMethod, AvatarID, caps);
  431. //}));
  432. // start new ID sequence.
  433. Random rnd = new Random(System.Environment.TickCount);
  434. lock (m_ids)
  435. {
  436. if (!m_ids.ContainsKey(AvatarID))
  437. m_ids.Add(AvatarID, rnd.Next(30000000));
  438. }
  439. int thisID = 0;
  440. lock (m_ids)
  441. thisID = m_ids[AvatarID];
  442. BlockingLLSDQueue queue = GetQueue(AvatarID);
  443. OSDArray array = new OSDArray();
  444. LLSD element = queue.Dequeue(15000); // 15s timeout
  445. if (element == null)
  446. {
  447. array.Add(EventQueueHelper.KeepAliveEvent());
  448. }
  449. else
  450. {
  451. array.Add(element);
  452. while (queue.Count() > 0)
  453. {
  454. array.Add(queue.Dequeue(1));
  455. thisID++;
  456. }
  457. }
  458. OSDMap events = new OSDMap();
  459. events.Add("events", array);
  460. events.Add("id", new LLSDInteger(thisID));
  461. lock (m_ids)
  462. {
  463. m_ids[AvatarID] = thisID + 1;
  464. }
  465. return events;
  466. }
  467. else
  468. {
  469. return new LLSD();
  470. }
  471. *
  472. */
  473. }
  474. else
  475. {
  476. //return new LLSD();
  477. }
  478. return new OSDString("shutdown404!");
  479. }
  480. }
  481. }