EventQueueGetModule.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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.Xml;
  34. using OpenMetaverse;
  35. using OpenMetaverse.StructuredData;
  36. using log4net;
  37. using Nini.Config;
  38. using Nwc.XmlRpc;
  39. using OpenSim.Framework;
  40. using OpenSim.Framework.Communications.Cache;
  41. using OpenSim.Framework.Communications.Capabilities;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Region.Environment.Interfaces;
  44. using OpenSim.Region.Interfaces;
  45. using OpenSim.Region.Environment.Scenes;
  46. using OSD = OpenMetaverse.StructuredData.OSD;
  47. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  48. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  49. using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
  50. using BlockingLLSDQueue = OpenSim.Framework.BlockingQueue<OpenMetaverse.StructuredData.OSD>;
  51. namespace OpenSim.Region.Environment.Modules.Framework
  52. {
  53. public struct QueueItem
  54. {
  55. public int id;
  56. public OSDMap body;
  57. }
  58. public class EventQueueGetModule : IEventQueue, IRegionModule
  59. {
  60. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  61. private Scene m_scene = null;
  62. private IConfigSource m_gConfig;
  63. bool enabledYN = false;
  64. private Dictionary<UUID, int> m_ids = new Dictionary<UUID, int>();
  65. private Dictionary<UUID, BlockingLLSDQueue> queues = new Dictionary<UUID, BlockingLLSDQueue>();
  66. private Dictionary<UUID, UUID> m_QueueUUIDAvatarMapping = new Dictionary<UUID, UUID>();
  67. private Dictionary<UUID, UUID> m_AvatarQueueUUIDMapping = new Dictionary<UUID, UUID>();
  68. #region IRegionModule methods
  69. public void Initialise(Scene scene, IConfigSource config)
  70. {
  71. m_gConfig = config;
  72. IConfig startupConfig = m_gConfig.Configs["Startup"];
  73. ReadConfigAndPopulate(scene, startupConfig, "Startup");
  74. if (enabledYN)
  75. {
  76. m_scene = scene;
  77. scene.RegisterModuleInterface<IEventQueue>(this);
  78. // Register fallback handler
  79. // Why does EQG Fail on region crossings!
  80. //scene.AddLLSDHandler("/CAPS/EQG/", EventQueueFallBack);
  81. scene.EventManager.OnNewClient += OnNewClient;
  82. // TODO: Leaving these open, or closing them when we
  83. // become a child is incorrect. It messes up TP in a big
  84. // way. CAPS/EQ need to be active as long as the UDP
  85. // circuit is there.
  86. scene.EventManager.OnClientClosed += ClientClosed;
  87. scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  88. scene.EventManager.OnMakeChildAgent += MakeChildAgent;
  89. scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  90. m_log.DebugFormat("[EVENTQUEUE]: Enabled EventQueueGetModule for region {0}", scene.RegionInfo.RegionName);
  91. }
  92. else
  93. {
  94. m_gConfig = null;
  95. }
  96. }
  97. private void ReadConfigAndPopulate(Scene scene, IConfig startupConfig, string p)
  98. {
  99. enabledYN = startupConfig.GetBoolean("EventQueue", true);
  100. }
  101. public void PostInitialise()
  102. {
  103. }
  104. public void Close()
  105. {
  106. }
  107. public string Name
  108. {
  109. get { return "EventQueueGetModule"; }
  110. }
  111. public bool IsSharedModule
  112. {
  113. get { return false; }
  114. }
  115. #endregion
  116. /// <summary>
  117. /// Always returns a valid queue
  118. /// </summary>
  119. /// <param name="agentId"></param>
  120. /// <returns></returns>
  121. private BlockingLLSDQueue TryGetQueue(UUID agentId)
  122. {
  123. lock (queues)
  124. {
  125. if (!queues.ContainsKey(agentId))
  126. {
  127. m_log.DebugFormat("[EVENTQUEUE]: Adding new queue for agent {0} in region {1}", agentId,
  128. 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. } catch(NullReferenceException e)
  161. {
  162. m_log.Debug("[EVENTQUEUE] Caught exception: " + e);
  163. return false;
  164. }
  165. return true;
  166. }
  167. #endregion
  168. private void OnNewClient(IClientAPI client)
  169. {
  170. client.OnLogout += ClientClosed;
  171. }
  172. private void ClientClosed(IClientAPI client)
  173. {
  174. ClientClosed(client.AgentId);
  175. }
  176. private void ClientClosed(UUID AgentID)
  177. {
  178. m_log.DebugFormat("[EVENTQUEUE]: Closed client {0} in region {1}", AgentID, m_scene.RegionInfo.RegionName);
  179. lock (queues)
  180. {
  181. queues.Remove(AgentID);
  182. }
  183. List<UUID> removeitems = new List<UUID>();
  184. lock (m_AvatarQueueUUIDMapping)
  185. {
  186. foreach (UUID ky in m_AvatarQueueUUIDMapping.Keys)
  187. {
  188. if (ky == AgentID)
  189. {
  190. removeitems.Add(ky);
  191. }
  192. }
  193. foreach (UUID ky in removeitems)
  194. {
  195. m_AvatarQueueUUIDMapping.Remove(ky);
  196. m_scene.RemoveHTTPHandler("","/CAPS/EQG/" + ky.ToString() + "/");
  197. m_log.Debug("[EVENTQUEUE]: Removing " + "/CAPS/EQG/" + ky.ToString() + "/");
  198. }
  199. }
  200. UUID searchval = UUID.Zero;
  201. removeitems.Clear();
  202. lock (m_QueueUUIDAvatarMapping)
  203. {
  204. foreach (UUID ky in m_QueueUUIDAvatarMapping.Keys)
  205. {
  206. searchval = m_QueueUUIDAvatarMapping[ky];
  207. if (searchval == AgentID)
  208. {
  209. removeitems.Add(ky);
  210. }
  211. }
  212. foreach (UUID ky in removeitems)
  213. m_QueueUUIDAvatarMapping.Remove(ky);
  214. }
  215. m_log.DebugFormat("[EVENTQUEUE]: Client {0} deregistered in region {1}.", AgentID, m_scene.RegionInfo.RegionName);
  216. }
  217. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  218. {
  219. m_log.DebugFormat("[EVENTQUEUE]: Avatar {0} entering parcel {1} in region {2}.",
  220. avatar.UUID, localLandID, m_scene.RegionInfo.RegionName);
  221. }
  222. private void MakeChildAgent(ScenePresence avatar)
  223. {
  224. //m_log.DebugFormat("[EVENTQUEUE]: Make Child agent {0} in region {1}.", avatar.UUID, m_scene.RegionInfo.RegionName);
  225. //lock (m_ids)
  226. // {
  227. //if (m_ids.ContainsKey(avatar.UUID))
  228. //{
  229. // close the event queue.
  230. //m_ids[avatar.UUID] = -1;
  231. //}
  232. //}
  233. }
  234. public void OnRegisterCaps(UUID agentID, Caps caps)
  235. {
  236. m_log.DebugFormat("[EVENTQUEUE] OnRegisterCaps: agentID {0} caps {1} region {2}", agentID, caps, m_scene.RegionInfo.RegionName);
  237. // Let's instantiate a Queue for this agent right now
  238. TryGetQueue(agentID);
  239. string capsBase = "/CAPS/EQG/";
  240. UUID EventQueueGetUUID = UUID.Zero;
  241. lock (m_AvatarQueueUUIDMapping)
  242. {
  243. // Reuse open queues. The client does!
  244. if (m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  245. {
  246. m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!");
  247. EventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID];
  248. }
  249. else
  250. {
  251. EventQueueGetUUID = UUID.Random();
  252. m_log.DebugFormat("[EVENTQUEUE]: Using random UUID!");
  253. }
  254. }
  255. lock (m_QueueUUIDAvatarMapping)
  256. {
  257. if (!m_QueueUUIDAvatarMapping.ContainsKey(EventQueueGetUUID))
  258. m_QueueUUIDAvatarMapping.Add(EventQueueGetUUID, agentID);
  259. }
  260. lock (m_AvatarQueueUUIDMapping)
  261. {
  262. if (!m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  263. m_AvatarQueueUUIDMapping.Add(agentID, EventQueueGetUUID);
  264. }
  265. m_log.DebugFormat("[EVENTQUEUE]: CAPS URL: {0}", capsBase + EventQueueGetUUID.ToString() + "/");
  266. // Register this as a caps handler
  267. caps.RegisterHandler("EventQueueGet",
  268. new RestHTTPHandler("POST", capsBase + EventQueueGetUUID.ToString() + "/",
  269. delegate(Hashtable m_dhttpMethod)
  270. {
  271. return ProcessQueue(m_dhttpMethod,agentID, caps);
  272. }));
  273. // This will persist this beyond the expiry of the caps handlers
  274. m_scene.AddHTTPHandler(capsBase + EventQueueGetUUID.ToString() + "/", EventQueuePath2);
  275. Random rnd = new Random(System.Environment.TickCount);
  276. lock (m_ids)
  277. {
  278. if (!m_ids.ContainsKey(agentID))
  279. m_ids.Add(agentID, rnd.Next(30000000));
  280. }
  281. }
  282. public Hashtable ProcessQueue(Hashtable request,UUID agentID, Caps caps)
  283. {
  284. // TODO: this has to be redone to not busy-wait (and block the thread),
  285. // TODO: as soon as we have a non-blocking way to handle HTTP-requests.
  286. // if (m_log.IsDebugEnabled)
  287. // {
  288. // String debug = "[EVENTQUEUE]: Got request for agent {0} in region {1} from thread {2}: [ ";
  289. // foreach (object key in request.Keys)
  290. // {
  291. // debug += key.ToString() + "=" + request[key].ToString() + " ";
  292. // }
  293. // m_log.DebugFormat(debug + " ]", agentID, m_scene.RegionInfo.RegionName, System.Threading.Thread.CurrentThread.Name);
  294. // }
  295. BlockingLLSDQueue queue = TryGetQueue(agentID);
  296. OSD element = queue.Dequeue(15000); // 15s timeout
  297. Hashtable responsedata = new Hashtable();
  298. int thisID = 0;
  299. lock (m_ids)
  300. thisID = m_ids[agentID];
  301. if (element == null)
  302. {
  303. //m_log.ErrorFormat("[EVENTQUEUE]: Nothing to process in " + m_scene.RegionInfo.RegionName);
  304. if (thisID == -1) // close-request
  305. {
  306. m_log.ErrorFormat("[EVENTQUEUE]: 404 in " + m_scene.RegionInfo.RegionName);
  307. responsedata["int_response_code"] = 404; //501; //410; //404;
  308. responsedata["content_type"] = "text/plain";
  309. responsedata["keepalive"] = false;
  310. responsedata["str_response_string"] = "Closed EQG";
  311. return responsedata;
  312. }
  313. responsedata["int_response_code"] = 502;
  314. responsedata["content_type"] = "text/plain";
  315. responsedata["keepalive"] = false;
  316. responsedata["str_response_string"] = "Upstream error: ";
  317. responsedata["error_status_text"] = "Upstream error:";
  318. responsedata["http_protocol_version"] = "HTTP/1.0";
  319. return responsedata;
  320. }
  321. OSDArray array = new OSDArray();
  322. if (element == null) // didn't have an event in 15s
  323. {
  324. // Send it a fake event to keep the client polling! It doesn't like 502s like the proxys say!
  325. array.Add(EventQueueHelper.KeepAliveEvent());
  326. m_log.DebugFormat("[EVENTQUEUE]: adding fake event for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
  327. }
  328. else
  329. {
  330. array.Add(element);
  331. while (queue.Count() > 0)
  332. {
  333. array.Add(queue.Dequeue(1));
  334. thisID++;
  335. }
  336. }
  337. OSDMap events = new OSDMap();
  338. events.Add("events", array);
  339. events.Add("id", new OSDInteger(thisID));
  340. lock (m_ids)
  341. {
  342. m_ids[agentID] = thisID + 1;
  343. }
  344. responsedata["int_response_code"] = 200;
  345. responsedata["content_type"] = "application/xml";
  346. responsedata["keepalive"] = false;
  347. responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(events);
  348. m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
  349. return responsedata;
  350. }
  351. public Hashtable EventQueuePath2(Hashtable request)
  352. {
  353. string capuuid = (string)request["uri"]; //path.Replace("/CAPS/EQG/","");
  354. // pull off the last "/" in the path.
  355. Hashtable responsedata = new Hashtable();
  356. capuuid = capuuid.Substring(0, capuuid.Length - 1);
  357. capuuid = capuuid.Replace("/CAPS/EQG/", "");
  358. UUID AvatarID = UUID.Zero;
  359. UUID capUUID = UUID.Zero;
  360. // parse the path and search for the avatar with it registered
  361. if (UUID.TryParse(capuuid, out capUUID))
  362. {
  363. lock (m_QueueUUIDAvatarMapping)
  364. {
  365. if (m_QueueUUIDAvatarMapping.ContainsKey(capUUID))
  366. {
  367. AvatarID = m_QueueUUIDAvatarMapping[capUUID];
  368. }
  369. }
  370. if (AvatarID != UUID.Zero)
  371. {
  372. // m_scene.GetCapsHandlerForUser will return null if the agent doesn't have a caps handler
  373. // registered
  374. return ProcessQueue(request, AvatarID, m_scene.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. }