EventQueueGetModule.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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.Net;
  31. using System.Reflection;
  32. using System.Text;
  33. using log4net;
  34. using Nini.Config;
  35. using Mono.Addins;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using Caps=OpenSim.Framework.Capabilities.Caps;
  43. namespace OpenSim.Region.ClientStack.Linden
  44. {
  45. public struct QueueItem
  46. {
  47. public int id;
  48. public OSDMap body;
  49. }
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EventQueueGetModule")]
  51. public partial class EventQueueGetModule : IEventQueue, INonSharedRegionModule
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. private static string LogHeader = "[EVENT QUEUE GET MODULE]";
  55. private const int KEEPALIVE = 60; // this could be larger now, but viewers expect it on opensim
  56. // we need to go back to close before viwers, or we may lose data
  57. private const int VIEWERKEEPALIVE = (KEEPALIVE - 1) * 1000; // do it shorter
  58. /// <value>
  59. /// Debug level.
  60. /// </value>
  61. public int DebugLevel { get; set; }
  62. protected Scene m_scene;
  63. private Dictionary<UUID, int> m_ids = new Dictionary<UUID, int>();
  64. private Dictionary<UUID, Queue<byte[]>> queues = new Dictionary<UUID, Queue<byte[]>>();
  65. private Dictionary<UUID, UUID> m_AvatarQueueUUIDMapping = new Dictionary<UUID, UUID>();
  66. #region INonSharedRegionModule methods
  67. public virtual void Initialise(IConfigSource config)
  68. {
  69. }
  70. public void AddRegion(Scene scene)
  71. {
  72. m_scene = scene;
  73. scene.RegisterModuleInterface<IEventQueue>(this);
  74. scene.EventManager.OnClientClosed += ClientClosed;
  75. scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  76. MainConsole.Instance.Commands.AddCommand(
  77. "Debug",
  78. false,
  79. "debug eq",
  80. "debug eq [0|1|2]",
  81. "Turn on event queue debugging\n"
  82. + " <= 0 - turns off all event queue logging\n"
  83. + " >= 1 - turns on event queue setup and outgoing event logging\n"
  84. + " >= 2 - turns on poll notification",
  85. HandleDebugEq);
  86. MainConsole.Instance.Commands.AddCommand(
  87. "Debug",
  88. false,
  89. "show eq",
  90. "show eq",
  91. "Show contents of event queues for logged in avatars. Used for debugging.",
  92. HandleShowEq);
  93. }
  94. public void RemoveRegion(Scene scene)
  95. {
  96. if (m_scene != scene)
  97. return;
  98. scene.EventManager.OnClientClosed -= ClientClosed;
  99. scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  100. scene.UnregisterModuleInterface<IEventQueue>(this);
  101. m_scene = null;
  102. }
  103. public void RegionLoaded(Scene scene)
  104. {
  105. }
  106. public virtual void Close()
  107. {
  108. }
  109. public virtual string Name
  110. {
  111. get { return "EventQueueGetModule"; }
  112. }
  113. public Type ReplaceableInterface
  114. {
  115. get { return null; }
  116. }
  117. #endregion
  118. protected void HandleDebugEq(string module, string[] args)
  119. {
  120. if (!(args.Length == 3 && int.TryParse(args[2], out int debugLevel)))
  121. {
  122. MainConsole.Instance.Output("Usage: debug eq [0|1|2]");
  123. }
  124. else
  125. {
  126. DebugLevel = debugLevel;
  127. MainConsole.Instance.Output(
  128. "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.RegionInfo.RegionName);
  129. }
  130. }
  131. protected void HandleShowEq(string module, string[] args)
  132. {
  133. MainConsole.Instance.Output("Events in Scene {0} agents queues :", m_scene.Name);
  134. lock (queues)
  135. {
  136. foreach (KeyValuePair<UUID, Queue<byte[]>> kvp in queues)
  137. {
  138. MainConsole.Instance.Output(" {0} {1}", kvp.Key, kvp.Value.Count);
  139. }
  140. }
  141. }
  142. /// <summary>
  143. /// Always returns a valid queue
  144. /// </summary>
  145. /// <param name="agentId"></param>
  146. /// <returns></returns>
  147. private Queue<byte[]> TryGetQueue(UUID agentId)
  148. {
  149. lock (queues)
  150. {
  151. if (queues.TryGetValue(agentId, out Queue<byte[]> queue))
  152. return queue;
  153. if (DebugLevel > 0)
  154. m_log.DebugFormat(
  155. "[EVENTQUEUE]: Adding new queue for agent {0} in region {1}",
  156. agentId, m_scene.RegionInfo.RegionName);
  157. queue = new Queue<byte[]>();
  158. queues[agentId] = queue;
  159. return queue;
  160. }
  161. }
  162. /// <summary>
  163. /// May return a null queue
  164. /// </summary>
  165. /// <param name="agentId"></param>
  166. /// <returns></returns>
  167. private Queue<byte[]> GetQueue(UUID agentId)
  168. {
  169. lock (queues)
  170. {
  171. if (queues.TryGetValue(agentId, out Queue<byte[]> queue))
  172. return queue;
  173. return null;
  174. }
  175. }
  176. #region IEventQueue Members
  177. //legacy
  178. public bool Enqueue(OSD data, UUID avatarID)
  179. {
  180. //m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
  181. try
  182. {
  183. Queue<byte[]> queue = GetQueue(avatarID);
  184. if (queue != null)
  185. {
  186. byte[] evData = Util.UTF8NBGetbytes(OSDParser.SerializeLLSDInnerXmlString(data));
  187. lock (queue)
  188. queue.Enqueue(evData);
  189. }
  190. else
  191. {
  192. m_log.WarnFormat(
  193. "[EVENTQUEUE]: (Enqueue) No queue found for agent {0} in region {1}",
  194. avatarID, m_scene.Name);
  195. }
  196. }
  197. catch (NullReferenceException e)
  198. {
  199. m_log.Error("[EVENTQUEUE] Caught exception: " + e);
  200. return false;
  201. }
  202. return true;
  203. }
  204. //legacy
  205. /*
  206. public bool Enqueue(string ev, UUID avatarID)
  207. {
  208. //m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
  209. try
  210. {
  211. Queue<byte[]> queue = GetQueue(avatarID);
  212. if (queue != null)
  213. {
  214. byte[] evData = Util.UTF8NBGetbytes(ev);
  215. lock (queue)
  216. queue.Enqueue(evData);
  217. }
  218. else
  219. {
  220. m_log.WarnFormat(
  221. "[EVENTQUEUE]: (Enqueue) No queue found for agent {0} in region {1}",
  222. avatarID, m_scene.Name);
  223. }
  224. }
  225. catch (NullReferenceException e)
  226. {
  227. m_log.Error("[EVENTQUEUE] Caught exception: " + e);
  228. return false;
  229. }
  230. return true;
  231. }
  232. */
  233. public bool Enqueue(byte[] evData, UUID avatarID)
  234. {
  235. //m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
  236. try
  237. {
  238. Queue<byte[]> queue = GetQueue(avatarID);
  239. if (queue != null)
  240. {
  241. lock (queue)
  242. queue.Enqueue(evData);
  243. }
  244. else
  245. {
  246. m_log.WarnFormat(
  247. "[EVENTQUEUE]: (Enqueue) No queue found for agent {0} in region {1}",
  248. avatarID, m_scene.Name);
  249. }
  250. }
  251. catch (NullReferenceException e)
  252. {
  253. m_log.Error("[EVENTQUEUE] Caught exception: " + e);
  254. return false;
  255. }
  256. return true;
  257. }
  258. public bool Enqueue(osUTF8 o, UUID avatarID)
  259. {
  260. //m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
  261. try
  262. {
  263. Queue<byte[]> queue = GetQueue(avatarID);
  264. if (queue != null)
  265. {
  266. lock (queue)
  267. queue.Enqueue(o.ToArray());
  268. }
  269. else
  270. {
  271. m_log.WarnFormat(
  272. "[EVENTQUEUE]: (Enqueue) No queue found for agent {0} in region {1}",
  273. avatarID, m_scene.Name);
  274. }
  275. }
  276. catch (NullReferenceException e)
  277. {
  278. m_log.Error("[EVENTQUEUE] Caught exception: " + e);
  279. return false;
  280. }
  281. return true;
  282. }
  283. #endregion
  284. private void ClientClosed(UUID agentID, Scene scene)
  285. {
  286. //m_log.DebugFormat("[EVENTQUEUE]: Closed client {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
  287. lock (queues)
  288. {
  289. queues.Remove(agentID);
  290. lock (m_AvatarQueueUUIDMapping)
  291. m_AvatarQueueUUIDMapping.Remove(agentID);
  292. lock (m_ids)
  293. m_ids.Remove(agentID);
  294. }
  295. // m_log.DebugFormat("[EVENTQUEUE]: Deleted queues for {0} in region {1}", agentID, m_scene.RegionInfo.RegionName);
  296. }
  297. /// <summary>
  298. /// Generate an Event Queue Get handler path for the given eqg uuid.
  299. /// </summary>
  300. /// <param name='eqgUuid'></param>
  301. private string GenerateEqgCapPath(UUID eqgUuid)
  302. {
  303. return string.Format("/CE/{0}", eqgUuid);
  304. }
  305. public void OnRegisterCaps(UUID agentID, Caps caps)
  306. {
  307. // Register an event queue for the client
  308. if (DebugLevel > 0)
  309. m_log.DebugFormat(
  310. "[EVENTQUEUE]: OnRegisterCaps: agentID {0} caps {1} region {2}",
  311. agentID, caps, m_scene.RegionInfo.RegionName);
  312. UUID eventQueueGetUUID;
  313. Queue<Byte[]> queue = null;
  314. lock (queues)
  315. {
  316. queues.TryGetValue(agentID, out queue);
  317. if (queue == null)
  318. {
  319. queue = new Queue<byte[]>();
  320. queues[agentID] = queue;
  321. lock (m_AvatarQueueUUIDMapping)
  322. {
  323. eventQueueGetUUID = UUID.Random();
  324. m_AvatarQueueUUIDMapping[agentID] = eventQueueGetUUID;
  325. lock (m_ids)
  326. {
  327. if (m_ids.ContainsKey(agentID))
  328. m_ids[agentID]++;
  329. else
  330. {
  331. Random rnd = new Random(Environment.TickCount);
  332. m_ids[agentID] = rnd.Next(30000000);
  333. }
  334. }
  335. }
  336. }
  337. else
  338. {
  339. queue.Enqueue(null);
  340. // reuse or not to reuse
  341. lock (m_AvatarQueueUUIDMapping)
  342. {
  343. // Its reuse caps path not queues those are been reused already
  344. if (m_AvatarQueueUUIDMapping.ContainsKey(agentID))
  345. {
  346. m_log.DebugFormat("[EVENTQUEUE]: Found Existing UUID!");
  347. eventQueueGetUUID = m_AvatarQueueUUIDMapping[agentID];
  348. lock (m_ids)
  349. {
  350. // change to negative numbers so they are changed at end of sending first marker
  351. // old data on a queue may be sent on a response for a new caps
  352. // but at least will be sent with coerent IDs
  353. if (m_ids.ContainsKey(agentID))
  354. m_ids[agentID] = -m_ids[agentID];
  355. else
  356. {
  357. Random rnd = new Random(Environment.TickCount);
  358. m_ids[agentID] = -rnd.Next(30000000);
  359. }
  360. }
  361. }
  362. else
  363. {
  364. eventQueueGetUUID = UUID.Random();
  365. m_AvatarQueueUUIDMapping[agentID] = eventQueueGetUUID;
  366. lock (m_ids)
  367. {
  368. if (m_ids.ContainsKey(agentID))
  369. m_ids[agentID]++;
  370. else
  371. {
  372. Random rnd = new Random(Environment.TickCount);
  373. m_ids.Add(agentID, rnd.Next(30000000));
  374. }
  375. }
  376. }
  377. }
  378. }
  379. }
  380. caps.RegisterPollHandler(
  381. "EventQueueGet",
  382. new PollServiceEventArgs(null, GenerateEqgCapPath(eventQueueGetUUID), HasEvents, GetEvents, NoEvents, Drop, agentID, VIEWERKEEPALIVE));
  383. }
  384. public bool HasEvents(UUID requestID, UUID agentID)
  385. {
  386. Queue<byte[]> queue = GetQueue(agentID);
  387. if (queue != null)
  388. {
  389. lock (queue)
  390. {
  391. //m_log.WarnFormat("POLLED FOR EVENTS BY {0} in {1} -- {2}", agentID, m_scene.RegionInfo.RegionName, queue.Count);
  392. return queue.Count > 0;
  393. }
  394. }
  395. //m_log.WarnFormat("POLLED FOR EVENTS BY {0} unknown agent", agentID);
  396. return true;
  397. }
  398. /// <summary>
  399. /// Logs a debug line for an outbound event queue message if appropriate.
  400. /// </summary>
  401. /// <param name='element'>Element containing message</param>
  402. private void LogOutboundDebugMessage(OSD element, UUID agentId)
  403. {
  404. if (element is OSDMap)
  405. {
  406. OSDMap ev = (OSDMap)element;
  407. m_log.DebugFormat(
  408. "Eq OUT {0,-30} to {1,-20} {2,-20}",
  409. ev["message"], m_scene.GetScenePresence(agentId).Name, m_scene.Name);
  410. }
  411. }
  412. public void Drop(UUID requestID, UUID pAgentId)
  413. {
  414. // do nothing, in last case http server will do it
  415. }
  416. private readonly byte[] EventHeader = osUTF8.GetASCIIBytes("<llsd><map><key>events</key><array>");
  417. public Hashtable GetEvents(UUID requestID, UUID pAgentId)
  418. {
  419. if (DebugLevel >= 2)
  420. m_log.WarnFormat("POLLED FOR EQ MESSAGES BY {0} in {1}", pAgentId, m_scene.Name);
  421. Queue<byte[]> queue = GetQueue(pAgentId);
  422. if (queue == null)
  423. return NoAgent(requestID, pAgentId);
  424. byte[] element = null;
  425. List<byte[]> elements;
  426. int totalSize = 0;
  427. int thisID = 0;
  428. bool negativeID = false;
  429. lock (queue)
  430. {
  431. if (queue.Count == 0)
  432. return NoEvents(requestID, pAgentId);
  433. lock (m_ids)
  434. thisID = m_ids[pAgentId];
  435. if (thisID < 0)
  436. {
  437. negativeID = true;
  438. thisID = -thisID;
  439. }
  440. elements = new List<byte[]>(queue.Count + 2) {EventHeader};
  441. while (queue.Count > 0)
  442. {
  443. element = queue.Dequeue();
  444. // add elements until a marker is found
  445. // so they get into a response
  446. if (element == null)
  447. break;
  448. if (DebugLevel > 0)
  449. LogOutboundDebugMessage(element, pAgentId);
  450. elements.Add(element);
  451. totalSize += element.Length;
  452. }
  453. }
  454. lock (m_ids)
  455. {
  456. if (element == null && negativeID)
  457. {
  458. Random rnd = new Random(Environment.TickCount);
  459. m_ids[pAgentId] = rnd.Next(30000000);
  460. }
  461. else
  462. m_ids[pAgentId] = thisID + 1;
  463. }
  464. if (totalSize == 0)
  465. return NoEvents(requestID, pAgentId);
  466. totalSize += EventHeader.Length;
  467. osUTF8 sb = OSUTF8Cached.Acquire();
  468. LLSDxmlEncode2.AddEndArray(sb); // events array
  469. LLSDxmlEncode2.AddElem("id", thisID, sb);
  470. LLSDxmlEncode2.AddEndMap(sb);
  471. element = LLSDxmlEncode2.EndToBytes(sb);
  472. elements.Add(element);
  473. totalSize += element.Length;
  474. Hashtable responsedata = new Hashtable
  475. {
  476. ["int_response_code"] = 200,
  477. ["content_type"] = "application/xml"
  478. };
  479. //temporary
  480. byte[] finalData = new byte[totalSize];
  481. int dst = 0;
  482. for(int i = 0; i < elements.Count; ++i)
  483. {
  484. byte[] src = elements[i];
  485. Array.Copy(src, 0, finalData, dst, src.Length);
  486. dst += src.Length;
  487. }
  488. responsedata["bin_response_data"] = finalData;
  489. responsedata["keepaliveTimeout"] = KEEPALIVE;
  490. return responsedata;
  491. }
  492. public Hashtable NoEvents(UUID requestID, UUID agentID)
  493. {
  494. Hashtable responsedata = new Hashtable();
  495. Queue<byte[]> queue = GetQueue(agentID);
  496. if (queue == null)
  497. {
  498. responsedata["int_response_code"] = (int)HttpStatusCode.NotFound;
  499. return responsedata;
  500. }
  501. responsedata["int_response_code"] = (int)HttpStatusCode.BadGateway;
  502. return responsedata;
  503. }
  504. public Hashtable NoAgent(UUID requestID, UUID agentID)
  505. {
  506. Hashtable responsedata = new Hashtable
  507. {
  508. ["int_response_code"] = (int)HttpStatusCode.NotFound
  509. };
  510. return responsedata;
  511. }
  512. }
  513. }