EventQueueGetModule.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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
  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.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.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  89. scene.EventManager.OnMakeChildAgent += MakeChildAgent;
  90. scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  91. m_log.DebugFormat("[EVENTQUEUE]: Enabled EventQueueGetModule for region {0}", scene.RegionInfo.RegionName);
  92. }
  93. else
  94. {
  95. m_gConfig = null;
  96. }
  97. }
  98. private void ReadConfigAndPopulate(Scene scene, IConfig startupConfig, string p)
  99. {
  100. enabledYN = startupConfig.GetBoolean("EventQueue", true);
  101. }
  102. public void PostInitialise()
  103. {
  104. }
  105. public void Close()
  106. {
  107. }
  108. public string Name
  109. {
  110. get { return "EventQueueGetModule"; }
  111. }
  112. public bool IsSharedModule
  113. {
  114. get { return false; }
  115. }
  116. #endregion
  117. /// <summary>
  118. /// Always returns a valid queue
  119. /// </summary>
  120. /// <param name="agentId"></param>
  121. /// <returns></returns>
  122. private BlockingLLSDQueue TryGetQueue(UUID agentId)
  123. {
  124. lock (queues)
  125. {
  126. if (!queues.ContainsKey(agentId))
  127. {
  128. m_log.DebugFormat("[EVENTQUEUE]: Adding new queue for agent {0} in region {1}", agentId,
  129. m_scene.RegionInfo.RegionName);
  130. queues[agentId] = new BlockingLLSDQueue();
  131. }
  132. return queues[agentId];
  133. }
  134. }
  135. /// <summary>
  136. /// May return a null queue
  137. /// </summary>
  138. /// <param name="agentId"></param>
  139. /// <returns></returns>
  140. private BlockingLLSDQueue GetQueue(UUID agentId)
  141. {
  142. lock (queues)
  143. {
  144. if (queues.ContainsKey(agentId))
  145. {
  146. return queues[agentId];
  147. }
  148. else
  149. return null;
  150. }
  151. }
  152. #region IEventQueue Members
  153. public bool Enqueue(OSD ev, UUID avatarID)
  154. {
  155. m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
  156. try
  157. {
  158. BlockingLLSDQueue queue = GetQueue(avatarID);
  159. if (queue != null)
  160. queue.Enqueue(ev);
  161. } catch(NullReferenceException e)
  162. {
  163. m_log.Debug("[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.RemoveHTTPHandler("","/CAPS/EQG/" + ky.ToString() + "/");
  203. m_log.Debug("[EVENTQUEUE]: Removing " + "/CAPS/EQG/" + ky.ToString() + "/");
  204. }
  205. }
  206. UUID searchval = UUID.Zero;
  207. removeitems.Clear();
  208. lock (m_QueueUUIDAvatarMapping)
  209. {
  210. foreach (UUID ky in m_QueueUUIDAvatarMapping.Keys)
  211. {
  212. searchval = m_QueueUUIDAvatarMapping[ky];
  213. if (searchval == AgentID)
  214. {
  215. removeitems.Add(ky);
  216. }
  217. }
  218. foreach (UUID ky in removeitems)
  219. m_QueueUUIDAvatarMapping.Remove(ky);
  220. }
  221. m_log.DebugFormat("[EVENTQUEUE]: Client {0} deregistered in region {1}.", AgentID, m_scene.RegionInfo.RegionName);
  222. }
  223. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  224. {
  225. m_log.DebugFormat("[EVENTQUEUE]: Avatar {0} entering parcel {1} in region {2}.",
  226. avatar.UUID, localLandID, m_scene.RegionInfo.RegionName);
  227. }
  228. private void MakeChildAgent(ScenePresence avatar)
  229. {
  230. //m_log.DebugFormat("[EVENTQUEUE]: Make Child agent {0} in region {1}.", avatar.UUID, m_scene.RegionInfo.RegionName);
  231. //lock (m_ids)
  232. // {
  233. //if (m_ids.ContainsKey(avatar.UUID))
  234. //{
  235. // close the event queue.
  236. //m_ids[avatar.UUID] = -1;
  237. //}
  238. //}
  239. }
  240. public void OnRegisterCaps(UUID agentID, Caps caps)
  241. {
  242. m_log.DebugFormat("[EVENTQUEUE] OnRegisterCaps: agentID {0} caps {1} region {2}", agentID, caps, m_scene.RegionInfo.RegionName);
  243. // Let's instantiate a Queue for this agent right now
  244. TryGetQueue(agentID);
  245. string capsBase = "/CAPS/EQG/";
  246. UUID EventQueueGetUUID = UUID.Zero;
  247. lock (m_AvatarQueueUUIDMapping)
  248. {
  249. // Reuse open queues. The client does!
  250. if (m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  251. {
  252. m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!");
  253. EventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID];
  254. }
  255. else
  256. {
  257. EventQueueGetUUID = UUID.Random();
  258. m_log.DebugFormat("[EVENTQUEUE]: Using random UUID!");
  259. }
  260. }
  261. lock (m_QueueUUIDAvatarMapping)
  262. {
  263. if (!m_QueueUUIDAvatarMapping.ContainsKey(EventQueueGetUUID))
  264. m_QueueUUIDAvatarMapping.Add(EventQueueGetUUID, agentID);
  265. }
  266. lock (m_AvatarQueueUUIDMapping)
  267. {
  268. if (!m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  269. m_AvatarQueueUUIDMapping.Add(agentID, EventQueueGetUUID);
  270. }
  271. m_log.DebugFormat("[EVENTQUEUE]: CAPS URL: {0}", capsBase + EventQueueGetUUID.ToString() + "/");
  272. // Register this as a caps handler
  273. caps.RegisterHandler("EventQueueGet",
  274. new RestHTTPHandler("POST", capsBase + EventQueueGetUUID.ToString() + "/",
  275. delegate(Hashtable m_dhttpMethod)
  276. {
  277. return ProcessQueue(m_dhttpMethod,agentID, caps);
  278. }));
  279. // This will persist this beyond the expiry of the caps handlers
  280. m_scene.AddHTTPHandler(capsBase + EventQueueGetUUID.ToString() + "/", EventQueuePath2);
  281. Random rnd = new Random(System.Environment.TickCount);
  282. lock (m_ids)
  283. {
  284. if (!m_ids.ContainsKey(agentID))
  285. m_ids.Add(agentID, rnd.Next(30000000));
  286. }
  287. }
  288. public Hashtable ProcessQueue(Hashtable request,UUID agentID, Caps caps)
  289. {
  290. // TODO: this has to be redone to not busy-wait (and block the thread),
  291. // TODO: as soon as we have a non-blocking way to handle HTTP-requests.
  292. // if (m_log.IsDebugEnabled)
  293. // {
  294. // String debug = "[EVENTQUEUE]: Got request for agent {0} in region {1} from thread {2}: [ ";
  295. // foreach (object key in request.Keys)
  296. // {
  297. // debug += key.ToString() + "=" + request[key].ToString() + " ";
  298. // }
  299. // m_log.DebugFormat(debug + " ]", agentID, m_scene.RegionInfo.RegionName, System.Threading.Thread.CurrentThread.Name);
  300. // }
  301. BlockingLLSDQueue queue = TryGetQueue(agentID);
  302. OSD element = queue.Dequeue(15000); // 15s timeout
  303. Hashtable responsedata = new Hashtable();
  304. int thisID = 0;
  305. lock (m_ids)
  306. thisID = m_ids[agentID];
  307. if (element == null)
  308. {
  309. //m_log.ErrorFormat("[EVENTQUEUE]: Nothing to process in " + m_scene.RegionInfo.RegionName);
  310. if (thisID == -1) // close-request
  311. {
  312. m_log.ErrorFormat("[EVENTQUEUE]: 404 in " + m_scene.RegionInfo.RegionName);
  313. responsedata["int_response_code"] = 404; //501; //410; //404;
  314. responsedata["content_type"] = "text/plain";
  315. responsedata["keepalive"] = false;
  316. responsedata["str_response_string"] = "Closed EQG";
  317. return responsedata;
  318. }
  319. responsedata["int_response_code"] = 502;
  320. responsedata["content_type"] = "text/plain";
  321. responsedata["keepalive"] = false;
  322. responsedata["str_response_string"] = "Upstream error: ";
  323. responsedata["error_status_text"] = "Upstream error:";
  324. responsedata["http_protocol_version"] = "HTTP/1.0";
  325. return responsedata;
  326. }
  327. OSDArray array = new OSDArray();
  328. if (element == null) // didn't have an event in 15s
  329. {
  330. // Send it a fake event to keep the client polling! It doesn't like 502s like the proxys say!
  331. array.Add(EventQueueHelper.KeepAliveEvent());
  332. m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
  333. }
  334. else
  335. {
  336. array.Add(element);
  337. while (queue.Count() > 0)
  338. {
  339. array.Add(queue.Dequeue(1));
  340. thisID++;
  341. }
  342. }
  343. OSDMap events = new OSDMap();
  344. events.Add("events", array);
  345. events.Add("id", new OSDInteger(thisID));
  346. lock (m_ids)
  347. {
  348. m_ids[agentID] = thisID + 1;
  349. }
  350. responsedata["int_response_code"] = 200;
  351. responsedata["content_type"] = "application/xml";
  352. responsedata["keepalive"] = false;
  353. responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
  354. m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
  355. return responsedata;
  356. }
  357. public Hashtable EventQueuePath2(Hashtable request)
  358. {
  359. string capuuid = (string)request["uri"]; //path.Replace("/CAPS/EQG/","");
  360. // pull off the last "/" in the path.
  361. Hashtable responsedata = new Hashtable();
  362. capuuid = capuuid.Substring(0, capuuid.Length - 1);
  363. capuuid = capuuid.Replace("/CAPS/EQG/", "");
  364. UUID AvatarID = UUID.Zero;
  365. UUID capUUID = UUID.Zero;
  366. // parse the path and search for the avatar with it registered
  367. if (UUID.TryParse(capuuid, out capUUID))
  368. {
  369. lock (m_QueueUUIDAvatarMapping)
  370. {
  371. if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
  372. {
  373. AvatarID = m_QueueUUIDAvatarMapping[capUUID];
  374. }
  375. }
  376. if (AvatarID != UUID.Zero)
  377. {
  378. // m_scene.GetCapsHandlerForUser will return null if the agent doesn't have a caps handler
  379. // registered
  380. return ProcessQueue(request, AvatarID, m_scene.GetCapsHandlerForUser(AvatarID));
  381. }
  382. else
  383. {
  384. responsedata["int_response_code"] = 404;
  385. responsedata["content_type"] = "text/plain";
  386. responsedata["keepalive"] = false;
  387. responsedata["str_response_string"] = "Not Found";
  388. responsedata["error_status_text"] = "Not Found";
  389. responsedata["http_protocol_version"] = "HTTP/1.0";
  390. return responsedata;
  391. // return 404
  392. }
  393. }
  394. else
  395. {
  396. responsedata["int_response_code"] = 404;
  397. responsedata["content_type"] = "text/plain";
  398. responsedata["keepalive"] = false;
  399. responsedata["str_response_string"] = "Not Found";
  400. responsedata["error_status_text"] = "Not Found";
  401. responsedata["http_protocol_version"] = "HTTP/1.0";
  402. return responsedata;
  403. // return 404
  404. }
  405. }
  406. public OSD EventQueueFallBack(string path, OSD request, string endpoint)
  407. {
  408. // This is a fallback element to keep the client from loosing EventQueueGet
  409. // Why does CAPS fail sometimes!?
  410. m_log.Warn("[EVENTQUEUE]: In the Fallback handler! We lost the Queue in the rest handler!");
  411. string capuuid = path.Replace("/CAPS/EQG/","");
  412. capuuid = capuuid.Substring(0, capuuid.Length - 1);
  413. // UUID AvatarID = UUID.Zero;
  414. UUID capUUID = UUID.Zero;
  415. if (UUID.TryParse(capuuid, out capUUID))
  416. {
  417. /* Don't remove this yet code cleaners!
  418. * Still testing this!
  419. *
  420. lock (m_QueueUUIDAvatarMapping)
  421. {
  422. if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
  423. {
  424. AvatarID = m_QueueUUIDAvatarMapping[capUUID];
  425. }
  426. }
  427. if (AvatarID != UUID.Zero)
  428. {
  429. // Repair the CAP!
  430. //OpenSim.Framework.Communications.Capabilities.Caps caps = m_scene.GetCapsHandlerForUser(AvatarID);
  431. //string capsBase = "/CAPS/EQG/";
  432. //caps.RegisterHandler("EventQueueGet",
  433. //new RestHTTPHandler("POST", capsBase + capUUID.ToString() + "/",
  434. //delegate(Hashtable m_dhttpMethod)
  435. //{
  436. // return ProcessQueue(m_dhttpMethod, AvatarID, caps);
  437. //}));
  438. // start new ID sequence.
  439. Random rnd = new Random(System.Environment.TickCount);
  440. lock (m_ids)
  441. {
  442. if (!m_ids.ContainsKey(AvatarID))
  443. m_ids.Add(AvatarID, rnd.Next(30000000));
  444. }
  445. int thisID = 0;
  446. lock (m_ids)
  447. thisID = m_ids[AvatarID];
  448. BlockingLLSDQueue queue = GetQueue(AvatarID);
  449. OSDArray array = new OSDArray();
  450. LLSD element = queue.Dequeue(15000); // 15s timeout
  451. if (element == null)
  452. {
  453. array.Add(EventQueueHelper.KeepAliveEvent());
  454. }
  455. else
  456. {
  457. array.Add(element);
  458. while (queue.Count() > 0)
  459. {
  460. array.Add(queue.Dequeue(1));
  461. thisID++;
  462. }
  463. }
  464. OSDMap events = new OSDMap();
  465. events.Add("events", array);
  466. events.Add("id", new LLSDInteger(thisID));
  467. lock (m_ids)
  468. {
  469. m_ids[AvatarID] = thisID + 1;
  470. }
  471. return events;
  472. }
  473. else
  474. {
  475. return new LLSD();
  476. }
  477. *
  478. */
  479. }
  480. else
  481. {
  482. //return new LLSD();
  483. }
  484. return new OSDString("shutdown404!");
  485. }
  486. }
  487. }