HealthCheck.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2022 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 System;
  16. using System.Collections.Generic;
  17. using System.Net;
  18. using System.Net.Http;
  19. using System.Net.NetworkInformation;
  20. using System.Net.Sockets;
  21. using System.Text.Json;
  22. using System.Threading.Tasks;
  23. using TechnitiumLibrary;
  24. using TechnitiumLibrary.Net;
  25. using TechnitiumLibrary.Net.Dns;
  26. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  27. using TechnitiumLibrary.Net.Proxy;
  28. namespace Failover
  29. {
  30. enum HealthCheckType
  31. {
  32. Unknown = 0,
  33. Ping = 1,
  34. Tcp = 2,
  35. Http = 3,
  36. Https = 4
  37. }
  38. class HealthCheck : IDisposable
  39. {
  40. #region variables
  41. const string HTTP_HEALTH_CHECK_USER_AGENT = "DNS Failover App (Technitium DNS Server)";
  42. readonly HealthService _service;
  43. readonly string _name;
  44. HealthCheckType _type;
  45. int _interval;
  46. int _retries;
  47. int _timeout;
  48. int _port;
  49. Uri _url;
  50. EmailAlert _emailAlert;
  51. WebHook _webHook;
  52. SocketsHttpHandler _httpHandler;
  53. HttpClient _httpClient;
  54. #endregion
  55. #region constructor
  56. public HealthCheck(HealthService service, JsonElement jsonHealthCheck)
  57. {
  58. _service = service;
  59. _name = jsonHealthCheck.GetPropertyValue("name", "default");
  60. Reload(jsonHealthCheck);
  61. }
  62. #endregion
  63. #region IDisposable
  64. bool _disposed;
  65. protected virtual void Dispose(bool disposing)
  66. {
  67. if (_disposed)
  68. return;
  69. if (disposing)
  70. {
  71. if (_httpClient != null)
  72. {
  73. _httpClient.Dispose();
  74. _httpClient = null;
  75. }
  76. if (_httpHandler != null)
  77. {
  78. _httpHandler.Dispose();
  79. _httpHandler = null;
  80. }
  81. }
  82. _disposed = true;
  83. }
  84. public void Dispose()
  85. {
  86. Dispose(true);
  87. GC.SuppressFinalize(this);
  88. }
  89. #endregion
  90. #region private
  91. private void ConditionalHttpReload()
  92. {
  93. switch (_type)
  94. {
  95. case HealthCheckType.Http:
  96. case HealthCheckType.Https:
  97. bool handlerChanged = false;
  98. NetProxy proxy = _service.DnsServer.Proxy;
  99. if (_httpHandler is null)
  100. {
  101. SocketsHttpHandler httpHandler = new SocketsHttpHandler();
  102. httpHandler.ConnectTimeout = TimeSpan.FromMilliseconds(_timeout);
  103. httpHandler.PooledConnectionIdleTimeout = TimeSpan.FromMilliseconds(Math.Max(10000, _timeout));
  104. httpHandler.Proxy = proxy;
  105. httpHandler.UseProxy = proxy is not null;
  106. httpHandler.AllowAutoRedirect = true;
  107. httpHandler.MaxAutomaticRedirections = 10;
  108. _httpHandler = httpHandler;
  109. handlerChanged = true;
  110. }
  111. else
  112. {
  113. if ((_httpHandler.ConnectTimeout.TotalMilliseconds != _timeout) || (_httpHandler.Proxy != proxy))
  114. {
  115. SocketsHttpHandler httpHandler = new SocketsHttpHandler();
  116. httpHandler.ConnectTimeout = TimeSpan.FromMilliseconds(_timeout);
  117. httpHandler.PooledConnectionIdleTimeout = TimeSpan.FromMilliseconds(Math.Max(10000, _timeout));
  118. httpHandler.Proxy = proxy;
  119. httpHandler.UseProxy = proxy is not null;
  120. httpHandler.AllowAutoRedirect = true;
  121. httpHandler.MaxAutomaticRedirections = 10;
  122. SocketsHttpHandler oldHttpHandler = _httpHandler;
  123. _httpHandler = httpHandler;
  124. handlerChanged = true;
  125. oldHttpHandler.Dispose();
  126. }
  127. }
  128. if (_httpClient is null)
  129. {
  130. HttpClient httpClient = new HttpClient(_httpHandler);
  131. httpClient.Timeout = TimeSpan.FromMilliseconds(_timeout);
  132. httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(HTTP_HEALTH_CHECK_USER_AGENT);
  133. httpClient.DefaultRequestHeaders.ConnectionClose = true;
  134. _httpClient = httpClient;
  135. }
  136. else
  137. {
  138. if (handlerChanged || (_httpClient.Timeout.TotalMilliseconds != _timeout))
  139. {
  140. HttpClient httpClient = new HttpClient(_httpHandler);
  141. httpClient.Timeout = TimeSpan.FromMilliseconds(_timeout);
  142. httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(HTTP_HEALTH_CHECK_USER_AGENT);
  143. httpClient.DefaultRequestHeaders.ConnectionClose = true;
  144. HttpClient oldHttpClient = _httpClient;
  145. _httpClient = httpClient;
  146. oldHttpClient.Dispose();
  147. }
  148. }
  149. break;
  150. default:
  151. if (_httpClient != null)
  152. {
  153. _httpClient.Dispose();
  154. _httpClient = null;
  155. }
  156. if (_httpHandler != null)
  157. {
  158. _httpHandler.Dispose();
  159. _httpHandler = null;
  160. }
  161. break;
  162. }
  163. }
  164. #endregion
  165. #region public
  166. public void Reload(JsonElement jsonHealthCheck)
  167. {
  168. _type = Enum.Parse<HealthCheckType>(jsonHealthCheck.GetPropertyValue("type", "Tcp"), true);
  169. _interval = jsonHealthCheck.GetPropertyValue("interval", 60) * 1000;
  170. _retries = jsonHealthCheck.GetPropertyValue("retries", 3);
  171. _timeout = jsonHealthCheck.GetPropertyValue("timeout", 10) * 1000;
  172. _port = jsonHealthCheck.GetPropertyValue("port", 80);
  173. if (jsonHealthCheck.TryGetProperty("url", out JsonElement jsonUrl) && (jsonUrl.ValueKind != JsonValueKind.Null))
  174. _url = new Uri(jsonUrl.GetString());
  175. else
  176. _url = null;
  177. if (jsonHealthCheck.TryGetProperty("emailAlert", out JsonElement jsonEmailAlert) && _service.EmailAlerts.TryGetValue(jsonEmailAlert.GetString(), out EmailAlert emailAlert))
  178. _emailAlert = emailAlert;
  179. else
  180. _emailAlert = null;
  181. if (jsonHealthCheck.TryGetProperty("webHook", out JsonElement jsonWebHook) && _service.WebHooks.TryGetValue(jsonWebHook.GetString(), out WebHook webHook))
  182. _webHook = webHook;
  183. else
  184. _webHook = null;
  185. ConditionalHttpReload();
  186. }
  187. public async Task<HealthCheckResponse> IsHealthyAsync(string domain, DnsResourceRecordType type, Uri healthCheckUrl)
  188. {
  189. switch (type)
  190. {
  191. case DnsResourceRecordType.A:
  192. {
  193. DnsDatagram response = await _service.DnsServer.DirectQueryAsync(new DnsQuestionRecord(domain, type, DnsClass.IN));
  194. if ((response is null) || (response.Answer.Count == 0))
  195. return new HealthCheckResponse(HealthStatus.Failed, "Failed to resolve address.");
  196. IReadOnlyList<IPAddress> addresses = DnsClient.ParseResponseA(response);
  197. if (addresses.Count > 0)
  198. {
  199. HealthCheckResponse lastResponse = null;
  200. foreach (IPAddress address in addresses)
  201. {
  202. lastResponse = await IsHealthyAsync(address, healthCheckUrl);
  203. if (lastResponse.Status == HealthStatus.Healthy)
  204. return lastResponse;
  205. }
  206. return lastResponse;
  207. }
  208. return new HealthCheckResponse(HealthStatus.Failed, "Failed to resolve address.");
  209. }
  210. case DnsResourceRecordType.AAAA:
  211. {
  212. DnsDatagram response = await _service.DnsServer.DirectQueryAsync(new DnsQuestionRecord(domain, type, DnsClass.IN));
  213. if ((response is null) || (response.Answer.Count == 0))
  214. return new HealthCheckResponse(HealthStatus.Failed, "Failed to resolve address.");
  215. IReadOnlyList<IPAddress> addresses = DnsClient.ParseResponseAAAA(response);
  216. if (addresses.Count > 0)
  217. {
  218. HealthCheckResponse lastResponse = null;
  219. foreach (IPAddress address in addresses)
  220. {
  221. lastResponse = await IsHealthyAsync(address, healthCheckUrl);
  222. if (lastResponse.Status == HealthStatus.Healthy)
  223. return lastResponse;
  224. }
  225. return lastResponse;
  226. }
  227. return new HealthCheckResponse(HealthStatus.Failed, "Failed to resolve address.");
  228. }
  229. default:
  230. return new HealthCheckResponse(HealthStatus.Failed, "Not supported.");
  231. }
  232. }
  233. public async Task<HealthCheckResponse> IsHealthyAsync(IPAddress address, Uri healthCheckUrl)
  234. {
  235. foreach (KeyValuePair<NetworkAddress, bool> network in _service.UnderMaintenance)
  236. {
  237. if (network.Key.Contains(address))
  238. {
  239. if (network.Value)
  240. return new HealthCheckResponse(HealthStatus.Maintenance);
  241. break;
  242. }
  243. }
  244. switch (_type)
  245. {
  246. case HealthCheckType.Ping:
  247. {
  248. if (_service.DnsServer.Proxy != null)
  249. throw new NotSupportedException("Health check type 'ping' is not supported over proxy.");
  250. using (Ping ping = new Ping())
  251. {
  252. string lastReason;
  253. int retry = 0;
  254. do
  255. {
  256. PingReply reply = await ping.SendPingAsync(address, _timeout);
  257. if (reply.Status == IPStatus.Success)
  258. return new HealthCheckResponse(HealthStatus.Healthy);
  259. lastReason = reply.Status.ToString();
  260. }
  261. while (++retry < _retries);
  262. return new HealthCheckResponse(HealthStatus.Failed, lastReason);
  263. }
  264. }
  265. case HealthCheckType.Tcp:
  266. {
  267. Exception lastException;
  268. string lastReason = null;
  269. int retry = 0;
  270. do
  271. {
  272. try
  273. {
  274. NetProxy proxy = _service.DnsServer.Proxy;
  275. if (proxy is null)
  276. {
  277. using (Socket socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
  278. {
  279. await socket.ConnectAsync(address, _port).WithTimeout(_timeout);
  280. }
  281. }
  282. else
  283. {
  284. using (Socket socket = await proxy.ConnectAsync(new IPEndPoint(address, _port)).WithTimeout(_timeout))
  285. {
  286. //do nothing
  287. }
  288. }
  289. return new HealthCheckResponse(HealthStatus.Healthy);
  290. }
  291. catch (TimeoutException ex)
  292. {
  293. lastReason = "Connection timed out.";
  294. lastException = ex;
  295. }
  296. catch (SocketException ex)
  297. {
  298. lastReason = ex.Message;
  299. lastException = ex;
  300. }
  301. catch (Exception ex)
  302. {
  303. lastException = ex;
  304. }
  305. }
  306. while (++retry < _retries);
  307. return new HealthCheckResponse(HealthStatus.Failed, lastReason, lastException);
  308. }
  309. case HealthCheckType.Http:
  310. case HealthCheckType.Https:
  311. {
  312. ConditionalHttpReload();
  313. Exception lastException;
  314. string lastReason = null;
  315. int retry = 0;
  316. do
  317. {
  318. try
  319. {
  320. Uri url;
  321. if (_url is null)
  322. url = healthCheckUrl;
  323. else
  324. url = _url;
  325. if (url is null)
  326. return new HealthCheckResponse(HealthStatus.Failed, "Missing health check URL in APP record as well as in app config.");
  327. if (_type == HealthCheckType.Http)
  328. {
  329. if (url.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
  330. url = new Uri("http://" + url.Host + (url.IsDefaultPort ? "" : ":" + url.Port) + url.PathAndQuery);
  331. }
  332. else
  333. {
  334. if (url.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
  335. url = new Uri("https://" + url.Host + (url.IsDefaultPort ? "" : ":" + url.Port) + url.PathAndQuery);
  336. }
  337. IPEndPoint ep = new IPEndPoint(address, url.Port);
  338. Uri queryUri = new Uri(url.Scheme + "://" + ep.ToString() + url.PathAndQuery);
  339. HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, queryUri);
  340. if (url.IsDefaultPort)
  341. httpRequest.Headers.Host = url.Host;
  342. else
  343. httpRequest.Headers.Host = url.Host + ":" + url.Port;
  344. HttpResponseMessage httpResponse = await _httpClient.SendAsync(httpRequest);
  345. if (httpResponse.IsSuccessStatusCode)
  346. return new HealthCheckResponse(HealthStatus.Healthy);
  347. return new HealthCheckResponse(HealthStatus.Failed, "Received HTTP status code: " + (int)httpResponse.StatusCode + " " + httpResponse.StatusCode.ToString() + "; URL: " + url.AbsoluteUri);
  348. }
  349. catch (TaskCanceledException ex)
  350. {
  351. lastReason = "Connection timed out.";
  352. lastException = ex;
  353. }
  354. catch (HttpRequestException ex)
  355. {
  356. lastReason = ex.Message;
  357. lastException = ex;
  358. }
  359. catch (Exception ex)
  360. {
  361. lastException = ex;
  362. }
  363. }
  364. while (++retry < _retries);
  365. return new HealthCheckResponse(HealthStatus.Failed, lastReason, lastException);
  366. }
  367. default:
  368. throw new NotSupportedException();
  369. }
  370. }
  371. #endregion
  372. #region properties
  373. public string Name
  374. { get { return _name; } }
  375. public HealthCheckType Type
  376. { get { return _type; } }
  377. public int Interval
  378. { get { return _interval; } }
  379. public int Retries
  380. { get { return _retries; } }
  381. public int Timeout
  382. { get { return _timeout; } }
  383. public int Port
  384. { get { return _port; } }
  385. public Uri Url
  386. { get { return _url; } }
  387. public EmailAlert EmailAlert
  388. { get { return _emailAlert; } }
  389. public WebHook WebHook
  390. { get { return _webHook; } }
  391. #endregion
  392. }
  393. }