aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ScriptEngine/Common/ScriptEngineBase/EventQueueManager.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/ScriptEngine/Common/ScriptEngineBase/EventQueueManager.cs')
-rw-r--r--OpenSim/Region/ScriptEngine/Common/ScriptEngineBase/EventQueueManager.cs447
1 files changed, 0 insertions, 447 deletions
diff --git a/OpenSim/Region/ScriptEngine/Common/ScriptEngineBase/EventQueueManager.cs b/OpenSim/Region/ScriptEngine/Common/ScriptEngineBase/EventQueueManager.cs
deleted file mode 100644
index b13ab21..0000000
--- a/OpenSim/Region/ScriptEngine/Common/ScriptEngineBase/EventQueueManager.cs
+++ /dev/null
@@ -1,447 +0,0 @@
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
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using OpenMetaverse;
32using OpenSim.Region.ScriptEngine.Shared;
33
34namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
35{
36 /// <summary>
37 /// EventQueueManager handles event queues
38 /// Events are queued and executed in separate thread
39 /// </summary>
40 [Serializable]
41 public class EventQueueManager : iScriptEngineFunctionModule
42 {
43 //
44 // Class is instanced in "ScriptEngine" and used by "EventManager" which is also instanced in "ScriptEngine".
45 //
46 // Class purpose is to queue and execute functions that are received by "EventManager":
47 // - allowing "EventManager" to release its event thread immediately, thus not interrupting server execution.
48 // - allowing us to prioritize and control execution of script functions.
49 // Class can use multiple threads for simultaneous execution. Mutexes are used for thread safety.
50 //
51 // 1. Hold an execution queue for scripts
52 // 2. Use threads to process queue, each thread executes one script function on each pass.
53 // 3. Catch any script error and process it
54 //
55 //
56 // Notes:
57 // * Current execution load balancing is optimized for 1 thread, and can cause unfair execute balancing between scripts.
58 // Not noticeable unless server is under high load.
59 //
60
61 public ScriptEngine m_ScriptEngine;
62
63 /// <summary>
64 /// List of threads (classes) processing event queue
65 /// Note that this may or may not be a reference to a static object depending on PrivateRegionThreads config setting.
66 /// </summary>
67 internal static List<EventQueueThreadClass> eventQueueThreads = new List<EventQueueThreadClass>(); // Thread pool that we work on
68 /// <summary>
69 /// Locking access to eventQueueThreads AND staticGlobalEventQueueThreads.
70 /// </summary>
71// private object eventQueueThreadsLock = new object();
72 // Static objects for referencing the objects above if we don't have private threads:
73 //internal static List<EventQueueThreadClass> staticEventQueueThreads; // A static reference used if we don't use private threads
74// internal static object staticEventQueueThreadsLock; // Statick lock object reference for same reason
75
76 /// <summary>
77 /// Global static list of all threads (classes) processing event queue -- used by max enforcment thread
78 /// </summary>
79 //private List<EventQueueThreadClass> staticGlobalEventQueueThreads = new List<EventQueueThreadClass>();
80
81 /// <summary>
82 /// Used internally to specify how many threads should exit gracefully
83 /// </summary>
84 public static int ThreadsToExit;
85 public static object ThreadsToExitLock = new object();
86
87
88 //public object queueLock = new object(); // Mutex lock object
89
90 /// <summary>
91 /// How many threads to process queue with
92 /// </summary>
93 internal static int numberOfThreads;
94
95 internal static int EventExecutionMaxQueueSize;
96
97 /// <summary>
98 /// Maximum time one function can use for execution before we perform a thread kill.
99 /// </summary>
100 private static int maxFunctionExecutionTimems
101 {
102 get { return (int)(maxFunctionExecutionTimens / 10000); }
103 set { maxFunctionExecutionTimens = value * 10000; }
104 }
105
106 /// <summary>
107 /// Contains nanoseconds version of maxFunctionExecutionTimems so that it matches time calculations better (performance reasons).
108 /// WARNING! ONLY UPDATE maxFunctionExecutionTimems, NEVER THIS DIRECTLY.
109 /// </summary>
110 public static long maxFunctionExecutionTimens;
111 /// <summary>
112 /// Enforce max execution time
113 /// </summary>
114 public static bool EnforceMaxExecutionTime;
115 /// <summary>
116 /// Kill script (unload) when it exceeds execution time
117 /// </summary>
118 private static bool KillScriptOnMaxFunctionExecutionTime;
119
120 /// <summary>
121 /// List of localID locks for mutex processing of script events
122 /// </summary>
123 private List<uint> objectLocks = new List<uint>();
124 private object tryLockLock = new object(); // Mutex lock object
125
126 /// <summary>
127 /// Queue containing events waiting to be executed
128 /// </summary>
129 public Queue<QueueItemStruct> eventQueue = new Queue<QueueItemStruct>();
130
131 #region " Queue structures "
132 /// <summary>
133 /// Queue item structure
134 /// </summary>
135 public struct QueueItemStruct
136 {
137 public uint localID;
138 public UUID itemID;
139 public string functionName;
140 public DetectParams[] llDetectParams;
141 public object[] param;
142 }
143
144 #endregion
145
146 #region " Initialization / Startup "
147 public EventQueueManager(ScriptEngine _ScriptEngine)
148 {
149 m_ScriptEngine = _ScriptEngine;
150
151 ReadConfig();
152 AdjustNumberOfScriptThreads();
153 }
154
155 public void ReadConfig()
156 {
157 // Refresh config
158 numberOfThreads = m_ScriptEngine.ScriptConfigSource.GetInt("NumberOfScriptThreads", 2);
159 maxFunctionExecutionTimems = m_ScriptEngine.ScriptConfigSource.GetInt("MaxEventExecutionTimeMs", 5000);
160 EnforceMaxExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("EnforceMaxEventExecutionTime", false);
161 KillScriptOnMaxFunctionExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("DeactivateScriptOnTimeout", false);
162 EventExecutionMaxQueueSize = m_ScriptEngine.ScriptConfigSource.GetInt("EventExecutionMaxQueueSize", 300);
163
164 // Now refresh config in all threads
165 lock (eventQueueThreads)
166 {
167 foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
168 {
169 EventQueueThread.ReadConfig();
170 }
171 }
172 }
173
174 #endregion
175
176 #region " Shutdown all threads "
177 ~EventQueueManager()
178 {
179 Stop();
180 }
181
182 private void Stop()
183 {
184 if (eventQueueThreads != null)
185 {
186 // Kill worker threads
187 lock (eventQueueThreads)
188 {
189 foreach (EventQueueThreadClass EventQueueThread in new ArrayList(eventQueueThreads))
190 {
191 AbortThreadClass(EventQueueThread);
192 }
193 //eventQueueThreads.Clear();
194 //staticGlobalEventQueueThreads.Clear();
195 }
196 }
197
198 // Remove all entries from our event queue
199 lock (eventQueue)
200 {
201 eventQueue.Clear();
202 }
203 }
204
205 #endregion
206
207 #region " Start / stop script execution threads (ThreadClasses) "
208 private void StartNewThreadClass()
209 {
210 EventQueueThreadClass eqtc = new EventQueueThreadClass();
211 eventQueueThreads.Add(eqtc);
212 //m_ScriptEngine.Log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Started new script execution thread. Current thread count: " + eventQueueThreads.Count);
213 }
214
215 private void AbortThreadClass(EventQueueThreadClass threadClass)
216 {
217 if (eventQueueThreads.Contains(threadClass))
218 eventQueueThreads.Remove(threadClass);
219
220 try
221 {
222 threadClass.Stop();
223 }
224 catch (Exception)
225 {
226 //m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: If you see this, could you please report it to Tedd:");
227 //m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: Script thread execution timeout kill ended in exception: " + ex.ToString());
228 }
229 //m_ScriptEngine.Log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Killed script execution thread. Remaining thread count: " + eventQueueThreads.Count);
230 }
231 #endregion
232
233 #region " Mutex locks for queue access "
234 /// <summary>
235 /// Try to get a mutex lock on localID
236 /// </summary>
237 /// <param name="localID"></param>
238 /// <returns></returns>
239 public bool TryLock(uint localID)
240 {
241 lock (tryLockLock)
242 {
243 if (objectLocks.Contains(localID) == true)
244 {
245 return false;
246 }
247 else
248 {
249 objectLocks.Add(localID);
250 return true;
251 }
252 }
253 }
254
255 /// <summary>
256 /// Release mutex lock on localID
257 /// </summary>
258 /// <param name="localID"></param>
259 public void ReleaseLock(uint localID)
260 {
261 lock (tryLockLock)
262 {
263 if (objectLocks.Contains(localID) == true)
264 {
265 objectLocks.Remove(localID);
266 }
267 }
268 }
269 #endregion
270
271 #region " Check execution queue for a specified Event"
272 /// <summary>
273 /// checks to see if a specified event type is already in the queue
274 /// </summary>
275 /// <param name="localID">Region object ID</param>
276 /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
277 /// <returns>true if event is found , false if not found</returns>
278 ///
279 public bool CheckEeventQueueForEvent(uint localID, string FunctionName)
280 {
281 if (eventQueue.Count > 0)
282 {
283 lock (eventQueue)
284 {
285 foreach (EventQueueManager.QueueItemStruct QIS in eventQueue)
286 {
287 if ((QIS.functionName == FunctionName) && (QIS.localID == localID))
288 return true;
289 }
290 }
291 }
292 return false;
293 }
294 #endregion
295
296 #region " Add events to execution queue "
297 /// <summary>
298 /// Add event to event execution queue
299 /// </summary>
300 /// <param name="localID">Region object ID</param>
301 /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
302 /// <param name="param">Array of parameters to match event mask</param>
303 public bool AddToObjectQueue(uint localID, string FunctionName, DetectParams[] qParams, params object[] param)
304 {
305 // Determine all scripts in Object and add to their queue
306 //myScriptEngine.log.Info("[" + ScriptEngineName + "]: EventQueueManager Adding localID: " + localID + ", FunctionName: " + FunctionName);
307
308 // Do we have any scripts in this object at all? If not, return
309 if (m_ScriptEngine.m_ScriptManager.Scripts.ContainsKey(localID) == false)
310 {
311 //Console.WriteLine("Event \String.Empty + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
312 return false;
313 }
314
315 List<UUID> scriptKeys =
316 m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
317
318 foreach (UUID itemID in scriptKeys)
319 {
320 // Add to each script in that object
321 // TODO: Some scripts may not subscribe to this event. Should we NOT add it? Does it matter?
322 AddToScriptQueue(localID, itemID, FunctionName, qParams, param);
323 }
324 return true;
325 }
326
327 /// <summary>
328 /// Add event to event execution queue
329 /// </summary>
330 /// <param name="localID">Region object ID</param>
331 /// <param name="itemID">Region script ID</param>
332 /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
333 /// <param name="param">Array of parameters to match event mask</param>
334 public bool AddToScriptQueue(uint localID, UUID itemID, string FunctionName, DetectParams[] qParams, params object[] param)
335 {
336 List<UUID> keylist = m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
337
338 if (!keylist.Contains(itemID)) // We don't manage that script
339 {
340 return false;
341 }
342
343 lock (eventQueue)
344 {
345 if (eventQueue.Count >= EventExecutionMaxQueueSize)
346 {
347 m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: ERROR: Event execution queue item count is at " + eventQueue.Count + ". Config variable \"EventExecutionMaxQueueSize\" is set to " + EventExecutionMaxQueueSize + ", so ignoring new event.");
348 m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: Event ignored: localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
349 return false;
350 }
351
352 // Create a structure and add data
353 QueueItemStruct QIS = new QueueItemStruct();
354 QIS.localID = localID;
355 QIS.itemID = itemID;
356 QIS.functionName = FunctionName;
357 QIS.llDetectParams = qParams;
358 QIS.param = param;
359
360 // Add it to queue
361 eventQueue.Enqueue(QIS);
362 }
363 return true;
364 }
365 #endregion
366
367 #region " Maintenance thread "
368
369 /// <summary>
370 /// Adjust number of script thread classes. It can start new, but if it needs to stop it will just set number of threads in "ThreadsToExit" and threads will have to exit themselves.
371 /// Called from MaintenanceThread
372 /// </summary>
373 public void AdjustNumberOfScriptThreads()
374 {
375 // Is there anything here for us to do?
376 if (eventQueueThreads.Count == numberOfThreads)
377 return;
378
379 lock (eventQueueThreads)
380 {
381 int diff = numberOfThreads - eventQueueThreads.Count;
382 // Positive number: Start
383 // Negative number: too many are running
384 if (diff > 0)
385 {
386 // We need to add more threads
387 for (int ThreadCount = eventQueueThreads.Count; ThreadCount < numberOfThreads; ThreadCount++)
388 {
389 StartNewThreadClass();
390 }
391 }
392 if (diff < 0)
393 {
394 // We need to kill some threads
395 lock (ThreadsToExitLock)
396 {
397 ThreadsToExit = Math.Abs(diff);
398 }
399 }
400 }
401 }
402
403 /// <summary>
404 /// Check if any thread class has been executing an event too long
405 /// </summary>
406 public void CheckScriptMaxExecTime()
407 {
408 // Iterate through all ScriptThreadClasses and check how long their current function has been executing
409 lock (eventQueueThreads)
410 {
411 foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
412 {
413 // Is thread currently executing anything?
414 if (EventQueueThread.InExecution)
415 {
416 // Has execution time expired?
417 if (DateTime.Now.Ticks - EventQueueThread.LastExecutionStarted >
418 maxFunctionExecutionTimens)
419 {
420 // Yes! We need to kill this thread!
421
422 // Set flag if script should be removed or not
423 EventQueueThread.KillCurrentScript = KillScriptOnMaxFunctionExecutionTime;
424
425 // Abort this thread
426 AbortThreadClass(EventQueueThread);
427
428 // We do not need to start another, MaintenenceThread will do that for us
429 //StartNewThreadClass();
430 }
431 }
432 }
433 }
434 }
435 #endregion
436
437 ///// <summary>
438 ///// If set to true then threads and stuff should try to make a graceful exit
439 ///// </summary>
440 //public bool PleaseShutdown
441 //{
442 // get { return _PleaseShutdown; }
443 // set { _PleaseShutdown = value; }
444 //}
445 //private bool _PleaseShutdown = false;
446 }
447}