Watchdog.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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.Monitoring
  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. public 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. /// <summary>
  75. /// Stat structure associated with this thread.
  76. /// </summary>
  77. public Stat Stat { get; set; }
  78. public ThreadWatchdogInfo(Thread thread, int timeout)
  79. {
  80. Thread = thread;
  81. Timeout = timeout;
  82. FirstTick = Environment.TickCount & Int32.MaxValue;
  83. LastTick = FirstTick;
  84. Stat
  85. = new Stat(
  86. thread.Name,
  87. string.Format("Last update of thread {0}", thread.Name),
  88. "",
  89. "ms",
  90. "server",
  91. "thread",
  92. StatType.Pull,
  93. MeasuresOfInterest.None,
  94. stat => stat.Value = Environment.TickCount & Int32.MaxValue - LastTick,
  95. StatVerbosity.Debug);
  96. StatsManager.RegisterStat(Stat);
  97. }
  98. public ThreadWatchdogInfo(ThreadWatchdogInfo previousTwi)
  99. {
  100. Thread = previousTwi.Thread;
  101. FirstTick = previousTwi.FirstTick;
  102. LastTick = previousTwi.LastTick;
  103. Timeout = previousTwi.Timeout;
  104. IsTimedOut = previousTwi.IsTimedOut;
  105. AlarmIfTimeout = previousTwi.AlarmIfTimeout;
  106. AlarmMethod = previousTwi.AlarmMethod;
  107. }
  108. public void Cleanup()
  109. {
  110. StatsManager.DeregisterStat(Stat);
  111. }
  112. }
  113. /// <summary>
  114. /// This event is called whenever a tracked thread is
  115. /// stopped or has not called UpdateThread() in time<
  116. /// /summary>
  117. public static event Action<ThreadWatchdogInfo> OnWatchdogTimeout;
  118. /// <summary>
  119. /// Is this watchdog active?
  120. /// </summary>
  121. public static bool Enabled
  122. {
  123. get { return m_enabled; }
  124. set
  125. {
  126. // m_log.DebugFormat("[MEMORY WATCHDOG]: Setting MemoryWatchdog.Enabled to {0}", value);
  127. if (value == m_enabled)
  128. return;
  129. m_enabled = value;
  130. if (m_enabled)
  131. {
  132. // Set now so we don't get alerted on the first run
  133. LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
  134. }
  135. m_watchdogTimer.Enabled = m_enabled;
  136. }
  137. }
  138. private static bool m_enabled;
  139. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  140. private static Dictionary<int, ThreadWatchdogInfo> m_threads;
  141. private static System.Timers.Timer m_watchdogTimer;
  142. /// <summary>
  143. /// Last time the watchdog thread ran.
  144. /// </summary>
  145. /// <remarks>
  146. /// Should run every WATCHDOG_INTERVAL_MS
  147. /// </remarks>
  148. public static int LastWatchdogThreadTick { get; private set; }
  149. static Watchdog()
  150. {
  151. m_threads = new Dictionary<int, ThreadWatchdogInfo>();
  152. m_watchdogTimer = new System.Timers.Timer(WATCHDOG_INTERVAL_MS);
  153. m_watchdogTimer.AutoReset = false;
  154. m_watchdogTimer.Elapsed += WatchdogTimerElapsed;
  155. }
  156. /// <summary>
  157. /// Start a new thread that is tracked by the watchdog timer.
  158. /// </summary>
  159. /// <param name="start">The method that will be executed in a new thread</param>
  160. /// <param name="name">A name to give to the new thread</param>
  161. /// <param name="priority">Priority to run the thread at</param>
  162. /// <param name="isBackground">True to run this thread as a background thread, otherwise false</param>
  163. /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
  164. /// <returns>The newly created Thread object</returns>
  165. public static Thread StartThread(
  166. ThreadStart start, string name, ThreadPriority priority, bool isBackground, bool alarmIfTimeout)
  167. {
  168. return StartThread(start, name, priority, isBackground, alarmIfTimeout, null, DEFAULT_WATCHDOG_TIMEOUT_MS);
  169. }
  170. /// <summary>
  171. /// Start a new thread that is tracked by the watchdog timer
  172. /// </summary>
  173. /// <param name="start">The method that will be executed in a new thread</param>
  174. /// <param name="name">A name to give to the new thread</param>
  175. /// <param name="priority">Priority to run the thread at</param>
  176. /// <param name="isBackground">True to run this thread as a background
  177. /// thread, otherwise false</param>
  178. /// <param name="alarmIfTimeout">Trigger an alarm function is we have timed out</param>
  179. /// <param name="alarmMethod">
  180. /// Alarm method to call if alarmIfTimeout is true and there is a timeout.
  181. /// Normally, this will just return some useful debugging information.
  182. /// </param>
  183. /// <param name="timeout">Number of milliseconds to wait until we issue a warning about timeout.</param>
  184. /// <returns>The newly created Thread object</returns>
  185. public static Thread StartThread(
  186. ThreadStart start, string name, ThreadPriority priority, bool isBackground,
  187. bool alarmIfTimeout, Func<string> alarmMethod, int timeout)
  188. {
  189. Thread thread = new Thread(start);
  190. thread.Name = name;
  191. thread.Priority = priority;
  192. thread.IsBackground = isBackground;
  193. ThreadWatchdogInfo twi
  194. = new ThreadWatchdogInfo(thread, timeout)
  195. { AlarmIfTimeout = alarmIfTimeout, AlarmMethod = alarmMethod };
  196. m_log.DebugFormat(
  197. "[WATCHDOG]: Started tracking thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId);
  198. lock (m_threads)
  199. m_threads.Add(twi.Thread.ManagedThreadId, twi);
  200. thread.Start();
  201. return thread;
  202. }
  203. /// <summary>
  204. /// Marks the current thread as alive
  205. /// </summary>
  206. public static void UpdateThread()
  207. {
  208. UpdateThread(Thread.CurrentThread.ManagedThreadId);
  209. }
  210. /// <summary>
  211. /// Stops watchdog tracking on the current thread
  212. /// </summary>
  213. /// <returns>
  214. /// True if the thread was removed from the list of tracked
  215. /// threads, otherwise false
  216. /// </returns>
  217. public static bool RemoveThread()
  218. {
  219. return RemoveThread(Thread.CurrentThread.ManagedThreadId);
  220. }
  221. private static bool RemoveThread(int threadID)
  222. {
  223. lock (m_threads)
  224. {
  225. ThreadWatchdogInfo twi;
  226. if (m_threads.TryGetValue(threadID, out twi))
  227. {
  228. m_log.DebugFormat(
  229. "[WATCHDOG]: Removing thread {0}, ID {1}", twi.Thread.Name, twi.Thread.ManagedThreadId);
  230. twi.Cleanup();
  231. m_threads.Remove(threadID);
  232. return true;
  233. }
  234. else
  235. {
  236. m_log.WarnFormat(
  237. "[WATCHDOG]: Requested to remove thread with ID {0} but this is not being monitored", threadID);
  238. return false;
  239. }
  240. }
  241. }
  242. public static bool AbortThread(int threadID)
  243. {
  244. lock (m_threads)
  245. {
  246. if (m_threads.ContainsKey(threadID))
  247. {
  248. ThreadWatchdogInfo twi = m_threads[threadID];
  249. twi.Thread.Abort();
  250. RemoveThread(threadID);
  251. return true;
  252. }
  253. else
  254. {
  255. return false;
  256. }
  257. }
  258. }
  259. private static void UpdateThread(int threadID)
  260. {
  261. ThreadWatchdogInfo threadInfo;
  262. // Although TryGetValue is not a thread safe operation, we use a try/catch here instead
  263. // of a lock for speed. Adding/removing threads is a very rare operation compared to
  264. // UpdateThread(), and a single UpdateThread() failure here and there won't break
  265. // anything
  266. try
  267. {
  268. if (m_threads.TryGetValue(threadID, out threadInfo))
  269. {
  270. threadInfo.LastTick = Environment.TickCount & Int32.MaxValue;
  271. threadInfo.IsTimedOut = false;
  272. }
  273. else
  274. {
  275. m_log.WarnFormat("[WATCHDOG]: Asked to update thread {0} which is not being monitored", threadID);
  276. }
  277. }
  278. catch { }
  279. }
  280. /// <summary>
  281. /// Get currently watched threads for diagnostic purposes
  282. /// </summary>
  283. /// <returns></returns>
  284. public static ThreadWatchdogInfo[] GetThreadsInfo()
  285. {
  286. lock (m_threads)
  287. return m_threads.Values.ToArray();
  288. }
  289. /// <summary>
  290. /// Return the current thread's watchdog info.
  291. /// </summary>
  292. /// <returns>The watchdog info. null if the thread isn't being monitored.</returns>
  293. public static ThreadWatchdogInfo GetCurrentThreadInfo()
  294. {
  295. lock (m_threads)
  296. {
  297. if (m_threads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
  298. return m_threads[Thread.CurrentThread.ManagedThreadId];
  299. }
  300. return null;
  301. }
  302. /// <summary>
  303. /// Check watched threads. Fire alarm if appropriate.
  304. /// </summary>
  305. /// <param name="sender"></param>
  306. /// <param name="e"></param>
  307. private static void WatchdogTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
  308. {
  309. int now = Environment.TickCount & Int32.MaxValue;
  310. int msElapsed = now - LastWatchdogThreadTick;
  311. if (msElapsed > WATCHDOG_INTERVAL_MS * 2)
  312. m_log.WarnFormat(
  313. "[WATCHDOG]: {0} ms since Watchdog last ran. Interval should be approximately {1} ms",
  314. msElapsed, WATCHDOG_INTERVAL_MS);
  315. LastWatchdogThreadTick = Environment.TickCount & Int32.MaxValue;
  316. Action<ThreadWatchdogInfo> callback = OnWatchdogTimeout;
  317. if (callback != null)
  318. {
  319. List<ThreadWatchdogInfo> callbackInfos = null;
  320. lock (m_threads)
  321. {
  322. foreach (ThreadWatchdogInfo threadInfo in m_threads.Values)
  323. {
  324. if (threadInfo.Thread.ThreadState == ThreadState.Stopped)
  325. {
  326. RemoveThread(threadInfo.Thread.ManagedThreadId);
  327. if (callbackInfos == null)
  328. callbackInfos = new List<ThreadWatchdogInfo>();
  329. callbackInfos.Add(threadInfo);
  330. }
  331. else if (!threadInfo.IsTimedOut && now - threadInfo.LastTick >= threadInfo.Timeout)
  332. {
  333. threadInfo.IsTimedOut = true;
  334. if (threadInfo.AlarmIfTimeout)
  335. {
  336. if (callbackInfos == null)
  337. callbackInfos = new List<ThreadWatchdogInfo>();
  338. // Send a copy of the watchdog info to prevent race conditions where the watchdog
  339. // thread updates the monitoring info after an alarm has been sent out.
  340. callbackInfos.Add(new ThreadWatchdogInfo(threadInfo));
  341. }
  342. }
  343. }
  344. }
  345. if (callbackInfos != null)
  346. foreach (ThreadWatchdogInfo callbackInfo in callbackInfos)
  347. callback(callbackInfo);
  348. }
  349. if (MemoryWatchdog.Enabled)
  350. MemoryWatchdog.Update();
  351. ChecksManager.CheckChecks();
  352. StatsManager.RecordStats();
  353. m_watchdogTimer.Start();
  354. }
  355. }
  356. }