HealthMonitor.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using System;
  17. using System.Net;
  18. using System.Threading;
  19. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  20. namespace Failover
  21. {
  22. class HealthMonitor : IDisposable
  23. {
  24. #region variables
  25. readonly IDnsServer _dnsServer;
  26. readonly IPAddress _address;
  27. readonly string _domain;
  28. readonly DnsResourceRecordType _type;
  29. readonly HealthCheck _healthCheck;
  30. readonly Timer _healthCheckTimer;
  31. const int HEALTH_CHECK_TIMER_INITIAL_INTERVAL = 1000;
  32. HealthCheckResponse _lastHealthCheckResponse;
  33. const int MONITOR_EXPIRY = 1 * 60 * 60 * 1000; //1 hour
  34. DateTime _lastHealthStatusCheckedOn;
  35. #endregion
  36. #region constructor
  37. public HealthMonitor(IDnsServer dnsServer, IPAddress address, HealthCheck healthCheck, Uri healthCheckUrl)
  38. {
  39. _dnsServer = dnsServer;
  40. _address = address;
  41. _healthCheck = healthCheck;
  42. _healthCheckTimer = new Timer(async delegate (object state)
  43. {
  44. try
  45. {
  46. if (_healthCheck is null)
  47. {
  48. _lastHealthCheckResponse = null;
  49. }
  50. else
  51. {
  52. HealthCheckResponse healthCheckResponse = await _healthCheck.IsHealthyAsync(_address, healthCheckUrl);
  53. bool statusChanged = false;
  54. bool maintenance = false;
  55. if (_lastHealthCheckResponse is null)
  56. {
  57. switch (healthCheckResponse.Status)
  58. {
  59. case HealthStatus.Failed:
  60. statusChanged = true;
  61. break;
  62. case HealthStatus.Maintenance:
  63. statusChanged = true;
  64. maintenance = true;
  65. break;
  66. }
  67. }
  68. else
  69. {
  70. if (_lastHealthCheckResponse.Status != healthCheckResponse.Status)
  71. {
  72. statusChanged = true;
  73. if ((_lastHealthCheckResponse.Status == HealthStatus.Maintenance) || (healthCheckResponse.Status == HealthStatus.Maintenance))
  74. maintenance = true;
  75. }
  76. }
  77. if (statusChanged)
  78. {
  79. switch (healthCheckResponse.Status)
  80. {
  81. case HealthStatus.Failed:
  82. _dnsServer.WriteLog("ALERT! Address [" + _address.ToString() + "] status is FAILED based on '" + _healthCheck.Name + "' health check. The failure reason is: " + healthCheckResponse.FailureReason);
  83. break;
  84. default:
  85. _dnsServer.WriteLog("ALERT! Address [" + _address.ToString() + "] status is " + healthCheckResponse.Status.ToString().ToUpper() + " based on '" + _healthCheck.Name + "' health check.");
  86. break;
  87. }
  88. if (healthCheckResponse.Exception is not null)
  89. _dnsServer.WriteLog(healthCheckResponse.Exception);
  90. if (!maintenance)
  91. {
  92. //avoid sending email alerts when switching from or to maintenance
  93. EmailAlert emailAlert = _healthCheck.EmailAlert;
  94. if (emailAlert is not null)
  95. _ = emailAlert.SendAlertAsync(_address, _healthCheck.Name, healthCheckResponse);
  96. }
  97. WebHook webHook = _healthCheck.WebHook;
  98. if (webHook is not null)
  99. _ = webHook.CallAsync(_address, _healthCheck.Name, healthCheckResponse);
  100. }
  101. _lastHealthCheckResponse = healthCheckResponse;
  102. }
  103. }
  104. catch (Exception ex)
  105. {
  106. _dnsServer.WriteLog(ex);
  107. if (_lastHealthCheckResponse is null)
  108. {
  109. EmailAlert emailAlert = _healthCheck.EmailAlert;
  110. if (emailAlert is not null)
  111. _ = emailAlert.SendAlertAsync(_address, _healthCheck.Name, ex);
  112. WebHook webHook = _healthCheck.WebHook;
  113. if (webHook is not null)
  114. _ = webHook.CallAsync(_address, _healthCheck.Name, ex);
  115. _lastHealthCheckResponse = new HealthCheckResponse(HealthStatus.Failed, ex.ToString(), ex);
  116. }
  117. else
  118. {
  119. _lastHealthCheckResponse = null;
  120. }
  121. }
  122. finally
  123. {
  124. if (!_disposed && (_healthCheck is not null))
  125. _healthCheckTimer.Change(_healthCheck.Interval, Timeout.Infinite);
  126. }
  127. }, null, Timeout.Infinite, Timeout.Infinite);
  128. _healthCheckTimer.Change(HEALTH_CHECK_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
  129. }
  130. public HealthMonitor(IDnsServer dnsServer, string domain, DnsResourceRecordType type, HealthCheck healthCheck, Uri healthCheckUrl)
  131. {
  132. _dnsServer = dnsServer;
  133. _domain = domain;
  134. _type = type;
  135. _healthCheck = healthCheck;
  136. _healthCheckTimer = new Timer(async delegate (object state)
  137. {
  138. try
  139. {
  140. if (_healthCheck is null)
  141. {
  142. _lastHealthCheckResponse = null;
  143. }
  144. else
  145. {
  146. HealthCheckResponse healthCheckResponse = await _healthCheck.IsHealthyAsync(_domain, _type, healthCheckUrl);
  147. bool statusChanged = false;
  148. bool maintenance = false;
  149. if (_lastHealthCheckResponse is null)
  150. {
  151. switch (healthCheckResponse.Status)
  152. {
  153. case HealthStatus.Failed:
  154. statusChanged = true;
  155. break;
  156. case HealthStatus.Maintenance:
  157. statusChanged = true;
  158. maintenance = true;
  159. break;
  160. }
  161. }
  162. else
  163. {
  164. if (_lastHealthCheckResponse.Status != healthCheckResponse.Status)
  165. {
  166. statusChanged = true;
  167. if ((_lastHealthCheckResponse.Status == HealthStatus.Maintenance) || (healthCheckResponse.Status == HealthStatus.Maintenance))
  168. maintenance = true;
  169. }
  170. }
  171. if (statusChanged)
  172. {
  173. switch (healthCheckResponse.Status)
  174. {
  175. case HealthStatus.Failed:
  176. _dnsServer.WriteLog("ALERT! Domain [" + _domain + "] type [" + _type.ToString() + "] status is FAILED based on '" + _healthCheck.Name + "' health check. The failure reason is: " + healthCheckResponse.FailureReason);
  177. break;
  178. default:
  179. _dnsServer.WriteLog("ALERT! Domain [" + _domain + "] type [" + _type.ToString() + "] status is " + healthCheckResponse.Status.ToString().ToUpper() + " based on '" + _healthCheck.Name + "' health check.");
  180. break;
  181. }
  182. if (healthCheckResponse.Exception is not null)
  183. _dnsServer.WriteLog(healthCheckResponse.Exception);
  184. if (!maintenance)
  185. {
  186. //avoid sending email alerts when switching from or to maintenance
  187. EmailAlert emailAlert = _healthCheck.EmailAlert;
  188. if (emailAlert is not null)
  189. _ = emailAlert.SendAlertAsync(_domain, _type, _healthCheck.Name, healthCheckResponse);
  190. }
  191. WebHook webHook = _healthCheck.WebHook;
  192. if (webHook is not null)
  193. _ = webHook.CallAsync(_domain, _type, _healthCheck.Name, healthCheckResponse);
  194. }
  195. _lastHealthCheckResponse = healthCheckResponse;
  196. }
  197. }
  198. catch (Exception ex)
  199. {
  200. _dnsServer.WriteLog(ex);
  201. if (_lastHealthCheckResponse is null)
  202. {
  203. EmailAlert emailAlert = _healthCheck.EmailAlert;
  204. if (emailAlert is not null)
  205. _ = emailAlert.SendAlertAsync(_domain, _type, _healthCheck.Name, ex);
  206. WebHook webHook = _healthCheck.WebHook;
  207. if (webHook is not null)
  208. _ = webHook.CallAsync(_domain, _type, _healthCheck.Name, ex);
  209. _lastHealthCheckResponse = new HealthCheckResponse(HealthStatus.Failed, ex.ToString(), ex);
  210. }
  211. else
  212. {
  213. _lastHealthCheckResponse = null;
  214. }
  215. }
  216. finally
  217. {
  218. if (!_disposed && (_healthCheck is not null))
  219. _healthCheckTimer.Change(_healthCheck.Interval, Timeout.Infinite);
  220. }
  221. }, null, Timeout.Infinite, Timeout.Infinite);
  222. _healthCheckTimer.Change(HEALTH_CHECK_TIMER_INITIAL_INTERVAL, Timeout.Infinite);
  223. }
  224. #endregion
  225. #region IDisposable
  226. bool _disposed;
  227. protected virtual void Dispose(bool disposing)
  228. {
  229. if (_disposed)
  230. return;
  231. if (disposing)
  232. {
  233. if (_healthCheckTimer is not null)
  234. _healthCheckTimer.Dispose();
  235. }
  236. _disposed = true;
  237. }
  238. public void Dispose()
  239. {
  240. Dispose(true);
  241. GC.SuppressFinalize(this);
  242. }
  243. #endregion
  244. #region public
  245. public bool IsExpired()
  246. {
  247. return DateTime.UtcNow > _lastHealthStatusCheckedOn.AddMilliseconds(MONITOR_EXPIRY);
  248. }
  249. public void SetUnderMaintenance()
  250. {
  251. _lastHealthCheckResponse = new HealthCheckResponse(HealthStatus.Maintenance);
  252. }
  253. #endregion
  254. #region properties
  255. public IPAddress Address
  256. { get { return _address; } }
  257. public HealthCheckResponse LastHealthCheckResponse
  258. {
  259. get
  260. {
  261. _lastHealthStatusCheckedOn = DateTime.UtcNow;
  262. if (_lastHealthCheckResponse is null)
  263. return new HealthCheckResponse(HealthStatus.Unknown);
  264. return _lastHealthCheckResponse;
  265. }
  266. }
  267. #endregion
  268. }
  269. }