HealthCheck.cs 19 KB

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