Watchdog.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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.Generic;
  29. using System.Linq;
  30. using System.Threading;
  31. using log4net;
  32. namespace OpenSim.Framework
  33. {
  34. /// <summary>
  35. /// Manages launching threads and keeping watch over them for timeouts
  36. /// </summary>
  37. public static class Watchdog
  38. {
  39. /// <summary>Timer interval in milliseconds for the watchdog timer</summary>
  40. const double WATCHDOG_INTERVAL_MS = 2500.0d;
  41. /// <summary>Default timeout in milliseconds before a thread is considered dead</summary>
  42. public const int DEFAULT_WATCHDOG_TIMEOUT_MS = 5000;
  43. [System.Diagnostics.DebuggerDisplay("{Thread.Name}")]
  44. public class ThreadWatchdogInfo
  45. {
  46. public Thread Thread { get; private set; }
  47. /// <summary>
  48. /// Approximate tick when this thread was started.
  49. /// </summary>
  50. /// <remarks>
  51. /// Not terribly good since this quickly wraps around.
  52. /// </remarks>
  53. public int FirstTick { get; private set; }
  54. /// <summary>
  55. /// Last time this heartbeat update was invoked
  56. /// </summary>
  57. public int LastTick { get; set; }
  58. /// <summary>
  59. /// Number of milliseconds before we notify that the thread is having a problem.
  60. /// </summary>
  61. public int Timeout { get; set; }
  62. /// <summary>
  63. /// Is this thread considered timed out?
  64. /// </summary>
  65. public bool IsTimedOut { get; set; }
  66. /// <summary>
  67. /// Will this thread trigger the alarm function if it has timed out?
  68. /// </summary>
  69. public bool AlarmIfTimeout { get; set; }
  70. /// <summary>
  71. /// Method execute if alarm goes off. If null then no alarm method is fired.
  72. /// </summary>
  73. public Func<string> AlarmMethod { get; set; }
  74. public ThreadWatchdogInfo(Thread thread, int timeout)
  75. {
  76. Thread = thread;
  77. Timeout = timeout;
  78. FirstTick = Environment.TickCount & Int32.MaxValue;
  79. LastTick = FirstTick;
  80. }
  81. }
  82. /// <summary>
  83. /// This event is called whenever a tracked thread is
  84. /// stopped or has not called UpdateThread() in time<
  85. /// /summary>
  86. public static event Action<ThreadWatchdogInfo> OnWatchdogTimeout;
  87. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  88. private static Dictionary<int, ThreadWatchdogInfo> m_threads;
  89. private static System.Timers.Timer m_watchdogTimer;
  90. /// <summary>
  91. /// Last time the watchdog thread ran.
  92. /// </summary>
  93. /// <remarks>
  94. /// Should run every WATCHDOG_INTERVAL_MS
  95. /// </remarks>
  96. public static int LastWatchdogThreadTick { get; private set; }
  97. static Watchdog()
  98. {
  99. m_threads = new Dictionary<int, ThreadWatchdogInfo>();
  100. m_watchdogTimer = new System.Timers.Timer(WATCHDOG_INTERVAL_MS);
  101. m_watchdogTimer.AutoReset = false;
  102. m_watchdogTimer.Elapsed += WatchdogTimerElapsed;
  103. // Set now so we don't get alerted on the first run
  104. LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
  105. m_watchdogTimer.Start();
  106. }
  107. /// <summary>
  108. /// Start a new thread that is tracked by the watchdog timer.
  109. /// </summary>
  110. /// <param name="start">The method that will be executed in a new thread</param>
  111. /// <param name="name">A name to give to the new thread</param>
  112. /// <param name="priority">Priority to run the thread at</param>
  113. /// <param name="isBackground">True to run this thread as a background thread, otherwise false</param>
  114. /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
  115. /// <returns>The newly created Thread object</returns>
  116. public static Thread StartThread(
  117. ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout)
  118. {
  119. return StartThread(start, name, priority, isBackground, alarmIfTimeout, null, DEFAULT_WATCHDOG_TIMEOUT_MS);
  120. }
  121. /// <summary>
  122. /// Start a new thread that is tracked by the watchdog timer
  123. /// </summary>
  124. /// <param name="start">The method that will be executed in a new thread</param>
  125. /// <param name="name">A name to give to the new thread</param>
  126. /// <param name="priority">Priority to run the thread at</param>
  127. /// <param name="isBackground">True to run this thread as a background
  128. /// thread, otherwise false</param>
  129. /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
  130. /// <param name="alarmMethod">
  131. /// Alarm method to call if alarmIfTimeout is true and there is a timeout.
  132. /// Normally, this will just return some useful debugging information.
  133. /// </param>
  134. /// <param name="timeout">Number of milliseconds to wait until we issue a warning about timeout.</param>
  135. /// <returns>The newly created Thread object</returns>
  136. public static Thread StartThread(
  137. ThreadStart start, string name, ThreadPriority priority, bool isBackground,
  138. bool alarmIfTimeout, Func<string> alarmMethod, int timeout)
  139. {
  140. Thread thread = new Thread(start);
  141. thread.Name = name;
  142. thread.Priority = priority;
  143. thread.IsBackground = isBackground;
  144. ThreadWatchdogInfo twi
  145. = new ThreadWatchdogInfo(thread, timeout)
  146. { AlarmIfTimeout = alarmIfTimeout, AlarmMethod = alarmMethod };
  147. m_log.DebugFormat(
  148. "[WATCHDOG]: Started tracking thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId);
  149. lock (m_threads)
  150. m_threads.Add(twi.Thread.ManagedThreadId, twi);
  151. thread.Start();
  152. return thread;
  153. }
  154. /// <summary>
  155. /// Marks the current thread as alive
  156. /// </summary>
  157. public static void UpdateThread()
  158. {
  159. UpdateThread(Thread.CurrentThread.ManagedThreadId);
  160. }
  161. /// <summary>
  162. /// Stops watchdog tracking on the current thread
  163. /// </summary>
  164. /// <returns>
  165. /// True if the thread was removed from the list of tracked
  166. /// threads, otherwise false
  167. /// </returns>
  168. public static bool RemoveThread()
  169. {
  170. return RemoveThread(Thread.CurrentThread.ManagedThreadId);
  171. }
  172. private static bool RemoveThread(int threadID)
  173. {
  174. lock (m_threads)
  175. return m_threads.Remove(threadID);
  176. }
  177. public static bool AbortThread(int threadID)
  178. {
  179. lock (m_threads)
  180. {
  181. if (m_threads.ContainsKey(threadID))
  182. {
  183. ThreadWatchdogInfo twi = m_threads[threadID];
  184. twi.Thread.Abort();
  185. RemoveThread(threadID);
  186. return true;
  187. }
  188. else
  189. {
  190. return false;
  191. }
  192. }
  193. }
  194. private static void UpdateThread(int threadID)
  195. {
  196. ThreadWatchdogInfo threadInfo;
  197. // Although TryGetValue is not a thread safe operation, we use a try/catch here instead
  198. // of a lock for speed. Adding/removing threads is a very rare operation compared to
  199. // UpdateThread(), and a single UpdateThread() failure here and there won't break
  200. // anything
  201. try
  202. {
  203. if (m_threads.TryGetValue(threadID, out threadInfo))
  204. {
  205. threadInfo.LastTick = Environment.TickCount & Int32.MaxValue;
  206. threadInfo.IsTimedOut = false;
  207. }
  208. else
  209. {
  210. m_log.WarnFormat("[WATCHDOG]: Asked to update thread {0} which is not being monitored", threadID);
  211. }
  212. }
  213. catch { }
  214. }
  215. /// <summary>
  216. /// Get currently watched threads for diagnostic purposes
  217. /// </summary>
  218. /// <returns></returns>
  219. public static ThreadWatchdogInfo[] GetThreadsInfo()
  220. {
  221. lock (m_threads)
  222. return m_threads.Values.ToArray();
  223. }
  224. /// <summary>
  225. /// Return the current thread's watchdog info.
  226. /// </summary>
  227. /// <returns>The watchdog info. null if the thread isn't being monitored.</returns>
  228. public static ThreadWatchdogInfo GetCurrentThreadInfo()
  229. {
  230. lock (m_threads)
  231. {
  232. if (m_threads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
  233. return m_threads[Thread.CurrentThread.ManagedThreadId];
  234. }
  235. return null;
  236. }
  237. /// <summary>
  238. /// Check watched threads. Fire alarm if appropriate.
  239. /// </summary>
  240. /// <param name="sender"></param>
  241. /// <param name="e"></param>
  242. private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
  243. {
  244. int now = Environment.TickCount & Int32.MaxValue;
  245. int msElapsed = now - LastWatchdogThreadTick;
  246. if (msElapsed > WATCHDOG_INTERVAL_MS * 2)
  247. m_log.WarnFormat(
  248. "[WATCHDOG]: {0} ms since Watchdog last ran. Interval should be approximately {1} ms",
  249. msElapsed, WATCHDOG_INTERVAL_MS);
  250. LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
  251. Action<ThreadWatchdogInfo> callback = OnWatchdogTimeout;
  252. if (callback != null)
  253. {
  254. List<ThreadWatchdogInfo> callbackInfos = null;
  255. lock (m_threads)
  256. {
  257. foreach (ThreadWatchdogInfo threadInfo in m_threads.Values)
  258. {
  259. if (threadInfo.Thread.ThreadState == ThreadState.Stopped)
  260. {
  261. RemoveThread(threadInfo.Thread.ManagedThreadId);
  262. if (callbackInfos == null)
  263. callbackInfos = new List<ThreadWatchdogInfo>();
  264. callbackInfos.Add(threadInfo);
  265. }
  266. else if (!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout)
  267. {
  268. threadInfo.IsTimedOut = true;
  269. if (threadInfo.AlarmIfTimeout)
  270. {
  271. if (callbackInfos == null)
  272. callbackInfos = new List<ThreadWatchdogInfo>();
  273. callbackInfos.Add(threadInfo);
  274. }
  275. }
  276. }
  277. }
  278. if (callbackInfos != null)
  279. foreach (ThreadWatchdogInfo callbackInfo in callbackInfos)
  280. callback(callbackInfo);
  281. }
  282. if (MemoryWatchdog.Enabled)
  283. MemoryWatchdog.Update();
  284. m_watchdogTimer.Start();
  285. }
  286. }
  287. }