EventQueueGetModule.cs 19 KB

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