HealthCheck.cs 18 KB

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