AsyncCommandManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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.Threading;
  31. using OpenMetaverse;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Monitoring;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.ScriptEngine.Interfaces;
  36. using OpenSim.Region.ScriptEngine.Shared;
  37. using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
  38. using Timer=OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
  39. using System.Reflection;
  40. using log4net;
  41. namespace OpenSim.Region.ScriptEngine.Shared.Api
  42. {
  43. /// <summary>
  44. /// Handles LSL commands that takes long time and returns an event, for example timers, HTTP requests, etc.
  45. /// </summary>
  46. public class AsyncCommandManager
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private static Thread cmdHandlerThread;
  50. private static int cmdHandlerThreadCycleSleepms;
  51. private static int numInstances;
  52. /// <summary>
  53. /// Lock for reading/writing static components of AsyncCommandManager.
  54. /// </summary>
  55. /// <remarks>
  56. /// This lock exists so that multiple threads from different engines and/or different copies of the same engine
  57. /// are prevented from running non-thread safe code (e.g. read/write of lists) concurrently.
  58. /// </remarks>
  59. private static object staticLock = new object();
  60. private static List<IScriptEngine> m_ScriptEngines =
  61. new List<IScriptEngine>();
  62. public IScriptEngine m_ScriptEngine;
  63. private static Dictionary<IScriptEngine, Dataserver> m_Dataserver =
  64. new Dictionary<IScriptEngine, Dataserver>();
  65. private static Dictionary<IScriptEngine, Timer> m_Timer =
  66. new Dictionary<IScriptEngine, Timer>();
  67. private static Dictionary<IScriptEngine, Listener> m_Listener =
  68. new Dictionary<IScriptEngine, Listener>();
  69. private static Dictionary<IScriptEngine, HttpRequest> m_HttpRequest =
  70. new Dictionary<IScriptEngine, HttpRequest>();
  71. private static Dictionary<IScriptEngine, SensorRepeat> m_SensorRepeat =
  72. new Dictionary<IScriptEngine, SensorRepeat>();
  73. private static Dictionary<IScriptEngine, XmlRequest> m_XmlRequest =
  74. new Dictionary<IScriptEngine, XmlRequest>();
  75. public Dataserver DataserverPlugin
  76. {
  77. get
  78. {
  79. lock (staticLock)
  80. return m_Dataserver[m_ScriptEngine];
  81. }
  82. }
  83. public Timer TimerPlugin
  84. {
  85. get
  86. {
  87. lock (staticLock)
  88. return m_Timer[m_ScriptEngine];
  89. }
  90. }
  91. public HttpRequest HttpRequestPlugin
  92. {
  93. get
  94. {
  95. lock (staticLock)
  96. return m_HttpRequest[m_ScriptEngine];
  97. }
  98. }
  99. public Listener ListenerPlugin
  100. {
  101. get
  102. {
  103. lock (staticLock)
  104. return m_Listener[m_ScriptEngine];
  105. }
  106. }
  107. public SensorRepeat SensorRepeatPlugin
  108. {
  109. get
  110. {
  111. lock (staticLock)
  112. return m_SensorRepeat[m_ScriptEngine];
  113. }
  114. }
  115. public XmlRequest XmlRequestPlugin
  116. {
  117. get
  118. {
  119. lock (staticLock)
  120. return m_XmlRequest[m_ScriptEngine];
  121. }
  122. }
  123. public IScriptEngine[] ScriptEngines
  124. {
  125. get
  126. {
  127. lock (staticLock)
  128. return m_ScriptEngines.ToArray();
  129. }
  130. }
  131. public AsyncCommandManager(IScriptEngine _ScriptEngine)
  132. {
  133. m_ScriptEngine = _ScriptEngine;
  134. // If there is more than one scene in the simulator or multiple script engines are used on the same region
  135. // then more than one thread could arrive at this block of code simultaneously. However, it cannot be
  136. // executed concurrently both because concurrent list operations are not thread-safe and because of other
  137. // race conditions such as the later check of cmdHandlerThread == null.
  138. lock (staticLock)
  139. {
  140. if (m_ScriptEngines.Count == 0)
  141. ReadConfig();
  142. if (!m_ScriptEngines.Contains(m_ScriptEngine))
  143. m_ScriptEngines.Add(m_ScriptEngine);
  144. // Create instances of all plugins
  145. if (!m_Dataserver.ContainsKey(m_ScriptEngine))
  146. m_Dataserver[m_ScriptEngine] = new Dataserver(this);
  147. if (!m_Timer.ContainsKey(m_ScriptEngine))
  148. m_Timer[m_ScriptEngine] = new Timer(this);
  149. if (!m_HttpRequest.ContainsKey(m_ScriptEngine))
  150. m_HttpRequest[m_ScriptEngine] = new HttpRequest(this);
  151. if (!m_Listener.ContainsKey(m_ScriptEngine))
  152. m_Listener[m_ScriptEngine] = new Listener(this);
  153. if (!m_SensorRepeat.ContainsKey(m_ScriptEngine))
  154. m_SensorRepeat[m_ScriptEngine] = new SensorRepeat(this);
  155. if (!m_XmlRequest.ContainsKey(m_ScriptEngine))
  156. m_XmlRequest[m_ScriptEngine] = new XmlRequest(this);
  157. numInstances++;
  158. if (cmdHandlerThread == null)
  159. {
  160. cmdHandlerThread = WorkManager.StartThread(
  161. CmdHandlerThreadLoop, "AsyncLSLCmdHandlerThread");
  162. }
  163. }
  164. }
  165. private void ReadConfig()
  166. {
  167. // cmdHandlerThreadCycleSleepms = m_ScriptEngine.Config.GetInt("AsyncLLCommandLoopms", 100);
  168. // TODO: Make this sane again
  169. cmdHandlerThreadCycleSleepms = 100;
  170. }
  171. /*
  172. ~AsyncCommandManager()
  173. {
  174. // Shut down thread
  175. try
  176. {
  177. lock (staticLock)
  178. {
  179. numInstances--;
  180. if(numInstances > 0)
  181. return;
  182. if (cmdHandlerThread != null)
  183. {
  184. if (cmdHandlerThread.IsAlive == true)
  185. {
  186. cmdHandlerThread.Abort();
  187. //cmdHandlerThread.Join();
  188. cmdHandlerThread = null;
  189. }
  190. }
  191. }
  192. }
  193. catch
  194. {
  195. }
  196. }
  197. */
  198. /// <summary>
  199. /// Main loop for the manager thread
  200. /// </summary>
  201. private static void CmdHandlerThreadLoop()
  202. {
  203. bool running = true;
  204. while (running)
  205. {
  206. try
  207. {
  208. Thread.Sleep(cmdHandlerThreadCycleSleepms);
  209. Watchdog.UpdateThread();
  210. DoOneCmdHandlerPass();
  211. Watchdog.UpdateThread();
  212. }
  213. catch ( System.Threading.ThreadAbortException)
  214. {
  215. Thread.ResetAbort();
  216. running = false;
  217. }
  218. catch (Exception e)
  219. {
  220. m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
  221. }
  222. }
  223. }
  224. private static void DoOneCmdHandlerPass()
  225. {
  226. lock (staticLock)
  227. {
  228. // Check HttpRequests
  229. try { m_HttpRequest[m_ScriptEngines[0]].CheckHttpRequests(); } catch {}
  230. // Check XMLRPCRequests
  231. try { m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests(); } catch {}
  232. foreach (IScriptEngine s in m_ScriptEngines)
  233. {
  234. // Check Listeners
  235. try { m_Listener[s].CheckListeners(); } catch {}
  236. // Check timers
  237. try { m_Timer[s].CheckTimerEvents(); } catch {}
  238. // Check Sensors
  239. try { m_SensorRepeat[s].CheckSenseRepeaterEvents(); } catch {}
  240. // Check dataserver
  241. try { m_Dataserver[s].ExpireRequests(); } catch {}
  242. }
  243. }
  244. }
  245. /// <summary>
  246. /// Remove a specific script (and all its pending commands)
  247. /// </summary>
  248. /// <param name="localID"></param>
  249. /// <param name="itemID"></param>
  250. public static void RemoveScript(IScriptEngine engine, uint localID, UUID itemID)
  251. {
  252. // Remove a specific script
  253. // m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID);
  254. lock (staticLock)
  255. {
  256. // Remove dataserver events
  257. m_Dataserver[engine].RemoveEvents(localID, itemID);
  258. // Remove from: Timers
  259. m_Timer[engine].UnSetTimerEvents(localID, itemID);
  260. if(engine.World != null)
  261. {
  262. // Remove from: HttpRequest
  263. IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
  264. if (iHttpReq != null)
  265. iHttpReq.StopHttpRequest(localID, itemID);
  266. IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
  267. if (comms != null)
  268. comms.DeleteListener(itemID);
  269. IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
  270. if (xmlrpc != null)
  271. {
  272. xmlrpc.DeleteChannels(itemID);
  273. xmlrpc.CancelSRDRequests(itemID);
  274. }
  275. }
  276. // Remove Sensors
  277. m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
  278. }
  279. }
  280. public static void StateChange(IScriptEngine engine, uint localID, UUID itemID)
  281. {
  282. // Remove a specific script
  283. // Remove dataserver events
  284. m_Dataserver[engine].RemoveEvents(localID, itemID);
  285. IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
  286. if (comms != null)
  287. comms.DeleteListener(itemID);
  288. IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
  289. if (xmlrpc != null)
  290. {
  291. xmlrpc.DeleteChannels(itemID);
  292. xmlrpc.CancelSRDRequests(itemID);
  293. }
  294. // Remove Sensors
  295. m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
  296. }
  297. /// <summary>
  298. /// Get the sensor repeat plugin for this script engine.
  299. /// </summary>
  300. /// <param name="engine"></param>
  301. /// <returns></returns>
  302. public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
  303. {
  304. lock (staticLock)
  305. {
  306. if (m_SensorRepeat.ContainsKey(engine))
  307. return m_SensorRepeat[engine];
  308. else
  309. return null;
  310. }
  311. }
  312. /// <summary>
  313. /// Get the dataserver plugin for this script engine.
  314. /// </summary>
  315. /// <param name="engine"></param>
  316. /// <returns></returns>
  317. public static Dataserver GetDataserverPlugin(IScriptEngine engine)
  318. {
  319. lock (staticLock)
  320. {
  321. if (m_Dataserver.ContainsKey(engine))
  322. return m_Dataserver[engine];
  323. else
  324. return null;
  325. }
  326. }
  327. /// <summary>
  328. /// Get the timer plugin for this script engine.
  329. /// </summary>
  330. /// <param name="engine"></param>
  331. /// <returns></returns>
  332. public static Timer GetTimerPlugin(IScriptEngine engine)
  333. {
  334. lock (staticLock)
  335. {
  336. if (m_Timer.ContainsKey(engine))
  337. return m_Timer[engine];
  338. else
  339. return null;
  340. }
  341. }
  342. /// <summary>
  343. /// Get the listener plugin for this script engine.
  344. /// </summary>
  345. /// <param name="engine"></param>
  346. /// <returns></returns>
  347. public static Listener GetListenerPlugin(IScriptEngine engine)
  348. {
  349. lock (staticLock)
  350. {
  351. if (m_Listener.ContainsKey(engine))
  352. return m_Listener[engine];
  353. else
  354. return null;
  355. }
  356. }
  357. public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
  358. {
  359. List<Object> data = new List<Object>();
  360. lock (staticLock)
  361. {
  362. Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
  363. if (listeners.Length > 0)
  364. {
  365. data.Add("listener");
  366. data.Add(listeners.Length);
  367. data.AddRange(listeners);
  368. }
  369. Object[] timers=m_Timer[engine].GetSerializationData(itemID);
  370. if (timers.Length > 0)
  371. {
  372. data.Add("timer");
  373. data.Add(timers.Length);
  374. data.AddRange(timers);
  375. }
  376. Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
  377. if (sensors.Length > 0)
  378. {
  379. data.Add("sensor");
  380. data.Add(sensors.Length);
  381. data.AddRange(sensors);
  382. }
  383. }
  384. return data.ToArray();
  385. }
  386. public static void CreateFromData(IScriptEngine engine, uint localID,
  387. UUID itemID, UUID hostID, Object[] data)
  388. {
  389. int idx = 0;
  390. int len;
  391. while (idx < data.Length)
  392. {
  393. string type = data[idx].ToString();
  394. len = (int)data[idx+1];
  395. idx+=2;
  396. if (len > 0)
  397. {
  398. Object[] item = new Object[len];
  399. Array.Copy(data, idx, item, 0, len);
  400. idx+=len;
  401. lock (staticLock)
  402. {
  403. switch (type)
  404. {
  405. case "listener":
  406. m_Listener[engine].CreateFromData(localID, itemID,
  407. hostID, item);
  408. break;
  409. case "timer":
  410. m_Timer[engine].CreateFromData(localID, itemID,
  411. hostID, item);
  412. break;
  413. case "sensor":
  414. m_SensorRepeat[engine].CreateFromData(localID,
  415. itemID, hostID, item);
  416. break;
  417. }
  418. }
  419. }
  420. }
  421. }
  422. }
  423. }