AsyncCommandManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 ScriptTimer=OpenSim.Region.ScriptEngine.Shared.Api.Plugins.ScriptTimer;
  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, ScriptTimer> m_ScriptTimer =
  66. new Dictionary<IScriptEngine, ScriptTimer>();
  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 ScriptTimer TimerPlugin
  84. {
  85. get
  86. {
  87. lock (staticLock)
  88. return m_ScriptTimer[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_ScriptTimer.ContainsKey(m_ScriptEngine))
  148. m_ScriptTimer[m_ScriptEngine] = new ScriptTimer(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. cmdHandlerThreadCycleSleepms = Utils.Clamp(cmdHandlerThreadCycleSleepms, 25, 250);
  169. }
  170. /*
  171. ~AsyncCommandManager()
  172. {
  173. // Shut down thread
  174. try
  175. {
  176. lock (staticLock)
  177. {
  178. numInstances--;
  179. if(numInstances > 0)
  180. return;
  181. if (cmdHandlerThread != null)
  182. {
  183. if (cmdHandlerThread.IsAlive == true)
  184. {
  185. cmdHandlerThread.Abort();
  186. //cmdHandlerThread.Join();
  187. cmdHandlerThread = null;
  188. }
  189. }
  190. }
  191. }
  192. catch
  193. {
  194. }
  195. }
  196. */
  197. /// <summary>
  198. /// Main loop for the manager thread
  199. /// </summary>
  200. private static void CmdHandlerThreadLoop()
  201. {
  202. bool running = true;
  203. while (running)
  204. {
  205. try
  206. {
  207. Thread.Sleep(cmdHandlerThreadCycleSleepms);
  208. Watchdog.UpdateThread();
  209. DoOneCmdHandlerPass();
  210. Watchdog.UpdateThread();
  211. }
  212. catch ( System.Threading.ThreadAbortException)
  213. {
  214. //Thread.ResetAbort();
  215. running = false;
  216. }
  217. catch (Exception e)
  218. {
  219. m_log.Error("[ASYNC COMMAND MANAGER]: Exception in command handler pass: ", e);
  220. }
  221. }
  222. }
  223. private static void DoOneCmdHandlerPass()
  224. {
  225. lock (staticLock)
  226. {
  227. // Check XMLRPCRequests
  228. try { m_XmlRequest[m_ScriptEngines[0]].CheckXMLRPCRequests(); } catch {}
  229. foreach (IScriptEngine s in m_ScriptEngines)
  230. {
  231. // Check HttpRequests
  232. try { m_HttpRequest[s].CheckHttpRequests(); } catch { }
  233. // Check ScriptTimers
  234. try { m_ScriptTimer[s].CheckTimerEvents(); } catch {}
  235. // Check Sensors
  236. try { m_SensorRepeat[s].CheckSenseRepeaterEvents(); } catch {}
  237. // Check dataserver
  238. try { m_Dataserver[s].ExpireRequests(); } catch {}
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// Remove a specific script (and all its pending commands)
  244. /// </summary>
  245. /// <param name="localID"></param>
  246. /// <param name="itemID"></param>
  247. public static void RemoveScript(IScriptEngine engine, uint localID, UUID itemID)
  248. {
  249. // Remove a specific script
  250. // m_log.DebugFormat("[ASYNC COMMAND MANAGER]: Removing facilities for script {0}", itemID);
  251. lock (staticLock)
  252. {
  253. // Remove dataserver events
  254. m_Dataserver[engine].RemoveEvents(localID, itemID);
  255. // Remove from: ScriptTimers
  256. m_ScriptTimer[engine].UnSetTimerEvents(localID, itemID);
  257. if(engine.World != null)
  258. {
  259. // Remove from: HttpRequest
  260. IHttpRequestModule iHttpReq = engine.World.RequestModuleInterface<IHttpRequestModule>();
  261. if (iHttpReq != null)
  262. iHttpReq.StopHttpRequest(localID, itemID);
  263. IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
  264. if (comms != null)
  265. comms.DeleteListener(itemID);
  266. IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
  267. if (xmlrpc != null)
  268. {
  269. xmlrpc.DeleteChannels(itemID);
  270. xmlrpc.CancelSRDRequests(itemID);
  271. }
  272. }
  273. // Remove Sensors
  274. m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
  275. }
  276. }
  277. public static void StateChange(IScriptEngine engine, uint localID, UUID itemID)
  278. {
  279. // Remove a specific script
  280. // Remove dataserver events
  281. m_Dataserver[engine].RemoveEvents(localID, itemID);
  282. IWorldComm comms = engine.World.RequestModuleInterface<IWorldComm>();
  283. if (comms != null)
  284. comms.DeleteListener(itemID);
  285. IXMLRPC xmlrpc = engine.World.RequestModuleInterface<IXMLRPC>();
  286. if (xmlrpc != null)
  287. {
  288. xmlrpc.DeleteChannels(itemID);
  289. xmlrpc.CancelSRDRequests(itemID);
  290. }
  291. // Remove Sensors
  292. m_SensorRepeat[engine].UnSetSenseRepeaterEvents(localID, itemID);
  293. }
  294. /// <summary>
  295. /// Get the sensor repeat plugin for this script engine.
  296. /// </summary>
  297. /// <param name="engine"></param>
  298. /// <returns></returns>
  299. public static SensorRepeat GetSensorRepeatPlugin(IScriptEngine engine)
  300. {
  301. lock (staticLock)
  302. {
  303. if (m_SensorRepeat.ContainsKey(engine))
  304. return m_SensorRepeat[engine];
  305. else
  306. return null;
  307. }
  308. }
  309. /// <summary>
  310. /// Get the dataserver plugin for this script engine.
  311. /// </summary>
  312. /// <param name="engine"></param>
  313. /// <returns></returns>
  314. public static Dataserver GetDataserverPlugin(IScriptEngine engine)
  315. {
  316. lock (staticLock)
  317. {
  318. if (m_Dataserver.ContainsKey(engine))
  319. return m_Dataserver[engine];
  320. else
  321. return null;
  322. }
  323. }
  324. /// <summary>
  325. /// Get the ScriptTimer plugin for this script engine.
  326. /// </summary>
  327. /// <param name="engine"></param>
  328. /// <returns></returns>
  329. public static ScriptTimer GetTimerPlugin(IScriptEngine engine)
  330. {
  331. lock (staticLock)
  332. {
  333. if (m_ScriptTimer.ContainsKey(engine))
  334. return m_ScriptTimer[engine];
  335. else
  336. return null;
  337. }
  338. }
  339. /// <summary>
  340. /// Get the listener plugin for this script engine.
  341. /// </summary>
  342. /// <param name="engine"></param>
  343. /// <returns></returns>
  344. public static Listener GetListenerPlugin(IScriptEngine engine)
  345. {
  346. lock (staticLock)
  347. {
  348. if (m_Listener.ContainsKey(engine))
  349. return m_Listener[engine];
  350. else
  351. return null;
  352. }
  353. }
  354. public static Object[] GetSerializationData(IScriptEngine engine, UUID itemID)
  355. {
  356. List<Object> data = new List<Object>();
  357. lock (staticLock)
  358. {
  359. Object[] listeners = m_Listener[engine].GetSerializationData(itemID);
  360. if (listeners.Length > 0)
  361. {
  362. data.Add("listener");
  363. data.Add(listeners.Length);
  364. data.AddRange(listeners);
  365. }
  366. Object[] ScriptTimers=m_ScriptTimer[engine].GetSerializationData(itemID);
  367. if (ScriptTimers.Length > 0)
  368. {
  369. data.Add("timer");
  370. data.Add(ScriptTimers.Length);
  371. data.AddRange(ScriptTimers);
  372. }
  373. Object[] sensors = m_SensorRepeat[engine].GetSerializationData(itemID);
  374. if (sensors.Length > 0)
  375. {
  376. data.Add("sensor");
  377. data.Add(sensors.Length);
  378. data.AddRange(sensors);
  379. }
  380. }
  381. return data.ToArray();
  382. }
  383. public static void CreateFromData(IScriptEngine engine, uint localID,
  384. UUID itemID, UUID hostID, Object[] data)
  385. {
  386. int idx = 0;
  387. int len;
  388. while (idx < data.Length)
  389. {
  390. string type = data[idx].ToString();
  391. len = (int)data[idx+1];
  392. idx+=2;
  393. if (len > 0)
  394. {
  395. Object[] item = new Object[len];
  396. Array.Copy(data, idx, item, 0, len);
  397. idx+=len;
  398. lock (staticLock)
  399. {
  400. switch (type)
  401. {
  402. case "listener":
  403. m_Listener[engine].CreateFromData(itemID, hostID, item);
  404. break;
  405. case "timer":
  406. m_ScriptTimer[engine].CreateFromData(localID, itemID, hostID, item);
  407. break;
  408. case "sensor":
  409. m_SensorRepeat[engine].CreateFromData(localID, itemID, hostID, item);
  410. break;
  411. }
  412. }
  413. }
  414. }
  415. }
  416. }
  417. }