123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440 |
- /*
- Technitium DNS Server
- Copyright (C) 2024 Shreyas Zare (shreyas@technitium.com)
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
- using DnsServerCore.ApplicationCommon;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Net;
- using System.Text.Json;
- using System.Threading;
- using TechnitiumLibrary;
- using TechnitiumLibrary.Net;
- using TechnitiumLibrary.Net.Dns.ResourceRecords;
- namespace Failover
- {
- class HealthService : IDisposable
- {
- #region variables
- static HealthService _healthService;
- readonly IDnsServer _dnsServer;
- readonly ConcurrentDictionary<string, HealthCheck> _healthChecks = new ConcurrentDictionary<string, HealthCheck>(1, 5);
- readonly ConcurrentDictionary<string, EmailAlert> _emailAlerts = new ConcurrentDictionary<string, EmailAlert>(1, 2);
- readonly ConcurrentDictionary<string, WebHook> _webHooks = new ConcurrentDictionary<string, WebHook>(1, 2);
- readonly ConcurrentDictionary<NetworkAddress, bool> _underMaintenance = new ConcurrentDictionary<NetworkAddress, bool>();
- readonly ConcurrentDictionary<string, HealthMonitor> _healthMonitors = new ConcurrentDictionary<string, HealthMonitor>();
- readonly Timer _maintenanceTimer;
- const int MAINTENANCE_TIMER_INTERVAL = 15 * 60 * 1000; //15 mins
- #endregion
- #region constructor
- private HealthService(IDnsServer dnsServer)
- {
- _dnsServer = dnsServer;
- _maintenanceTimer = new Timer(delegate (object state)
- {
- try
- {
- foreach (KeyValuePair<string, HealthMonitor> healthMonitor in _healthMonitors)
- {
- if (healthMonitor.Value.IsExpired())
- {
- if (_healthMonitors.TryRemove(healthMonitor.Key, out HealthMonitor removedMonitor))
- removedMonitor.Dispose();
- }
- }
- }
- catch (Exception ex)
- {
- _dnsServer.WriteLog(ex);
- }
- finally
- {
- if (!_disposed)
- _maintenanceTimer.Change(MAINTENANCE_TIMER_INTERVAL, Timeout.Infinite);
- }
- }, null, Timeout.Infinite, Timeout.Infinite);
- _maintenanceTimer.Change(MAINTENANCE_TIMER_INTERVAL, Timeout.Infinite);
- }
- #endregion
- #region IDisposable
- bool _disposed;
- protected virtual void Dispose(bool disposing)
- {
- if (_disposed)
- return;
- if (disposing)
- {
- foreach (KeyValuePair<string, HealthCheck> healthCheck in _healthChecks)
- healthCheck.Value.Dispose();
- _healthChecks.Clear();
- foreach (KeyValuePair<string, EmailAlert> emailAlert in _emailAlerts)
- emailAlert.Value.Dispose();
- _emailAlerts.Clear();
- foreach (KeyValuePair<string, WebHook> webHook in _webHooks)
- webHook.Value.Dispose();
- _webHooks.Clear();
- foreach (KeyValuePair<string, HealthMonitor> healthMonitor in _healthMonitors)
- healthMonitor.Value.Dispose();
- _healthMonitors.Clear();
- }
- _disposed = true;
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- #endregion
- #region static
- public static HealthService Create(IDnsServer dnsServer)
- {
- if (_healthService is null)
- _healthService = new HealthService(dnsServer);
- return _healthService;
- }
- #endregion
- #region private
- private static string GetHealthMonitorKey(IPAddress address, string healthCheck, Uri healthCheckUrl)
- {
- //key: health-check|127.0.0.1
- //key: health-check|127.0.0.1|http://example.com/
- if (healthCheckUrl is null)
- return healthCheck + "|" + address.ToString();
- else
- return healthCheck + "|" + address.ToString() + "|" + healthCheckUrl.AbsoluteUri;
- }
- private static string GetHealthMonitorKey(string domain, DnsResourceRecordType type, string healthCheck, Uri healthCheckUrl)
- {
- //key: health-check|example.com|A
- //key: health-check|example.com|AAAA|http://example.com/
- if (healthCheckUrl is null)
- return healthCheck + "|" + domain + "|" + type.ToString();
- else
- return healthCheck + "|" + domain + "|" + type.ToString() + "|" + healthCheckUrl.AbsoluteUri;
- }
- private void RemoveHealthMonitor(string healthCheck)
- {
- foreach (KeyValuePair<string, HealthMonitor> healthMonitor in _healthMonitors)
- {
- if (healthMonitor.Key.StartsWith(healthCheck + "|"))
- {
- if (_healthMonitors.TryRemove(healthMonitor.Key, out HealthMonitor removedMonitor))
- removedMonitor.Dispose();
- }
- }
- }
- #endregion
- #region public
- public void Initialize(string config)
- {
- using JsonDocument jsonDocument = JsonDocument.Parse(config);
- JsonElement jsonConfig = jsonDocument.RootElement;
- //email alerts
- {
- JsonElement jsonEmailAlerts = jsonConfig.GetProperty("emailAlerts");
- //add or update email alerts
- foreach (JsonElement jsonEmailAlert in jsonEmailAlerts.EnumerateArray())
- {
- string name = jsonEmailAlert.GetPropertyValue("name", "default");
- if (_emailAlerts.TryGetValue(name, out EmailAlert existingEmailAlert))
- {
- //update
- existingEmailAlert.Reload(jsonEmailAlert);
- }
- else
- {
- //add
- EmailAlert emailAlert = new EmailAlert(this, jsonEmailAlert);
- _emailAlerts.TryAdd(emailAlert.Name, emailAlert);
- }
- }
- //remove email alerts that dont exists in config
- foreach (KeyValuePair<string, EmailAlert> emailAlert in _emailAlerts)
- {
- bool emailAlertExists = false;
- foreach (JsonElement jsonEmailAlert in jsonEmailAlerts.EnumerateArray())
- {
- string name = jsonEmailAlert.GetPropertyValue("name", "default");
- if (name == emailAlert.Key)
- {
- emailAlertExists = true;
- break;
- }
- }
- if (!emailAlertExists)
- {
- if (_emailAlerts.TryRemove(emailAlert.Key, out EmailAlert removedEmailAlert))
- removedEmailAlert.Dispose();
- }
- }
- }
- //web hooks
- {
- JsonElement jsonWebHooks = jsonConfig.GetProperty("webHooks");
- //add or update email alerts
- foreach (JsonElement jsonWebHook in jsonWebHooks.EnumerateArray())
- {
- string name = jsonWebHook.GetPropertyValue("name", "default");
- if (_webHooks.TryGetValue(name, out WebHook existingWebHook))
- {
- //update
- existingWebHook.Reload(jsonWebHook);
- }
- else
- {
- //add
- WebHook webHook = new WebHook(this, jsonWebHook);
- _webHooks.TryAdd(webHook.Name, webHook);
- }
- }
- //remove email alerts that dont exists in config
- foreach (KeyValuePair<string, WebHook> webHook in _webHooks)
- {
- bool webHookExists = false;
- foreach (JsonElement jsonWebHook in jsonWebHooks.EnumerateArray())
- {
- string name = jsonWebHook.GetPropertyValue("name", "default");
- if (name == webHook.Key)
- {
- webHookExists = true;
- break;
- }
- }
- if (!webHookExists)
- {
- if (_webHooks.TryRemove(webHook.Key, out WebHook removedWebHook))
- removedWebHook.Dispose();
- }
- }
- }
- //health checks
- {
- JsonElement jsonHealthChecks = jsonConfig.GetProperty("healthChecks");
- //add or update health checks
- foreach (JsonElement jsonHealthCheck in jsonHealthChecks.EnumerateArray())
- {
- string name = jsonHealthCheck.GetPropertyValue("name", "default");
- if (_healthChecks.TryGetValue(name, out HealthCheck existingHealthCheck))
- {
- //update
- existingHealthCheck.Reload(jsonHealthCheck);
- }
- else
- {
- //add
- HealthCheck healthCheck = new HealthCheck(this, jsonHealthCheck);
- _healthChecks.TryAdd(healthCheck.Name, healthCheck);
- }
- }
- //remove health checks that dont exists in config
- foreach (KeyValuePair<string, HealthCheck> healthCheck in _healthChecks)
- {
- bool healthCheckExists = false;
- foreach (JsonElement jsonHealthCheck in jsonHealthChecks.EnumerateArray())
- {
- string name = jsonHealthCheck.GetPropertyValue("name", "default");
- if (name == healthCheck.Key)
- {
- healthCheckExists = true;
- break;
- }
- }
- if (!healthCheckExists)
- {
- if (_healthChecks.TryRemove(healthCheck.Key, out HealthCheck removedHealthCheck))
- {
- //remove health monitors using this health check
- RemoveHealthMonitor(healthCheck.Key);
- removedHealthCheck.Dispose();
- }
- }
- }
- }
- //under maintenance networks
- _underMaintenance.Clear();
- if (jsonConfig.TryGetProperty("underMaintenance", out JsonElement jsonUnderMaintenance))
- {
- foreach (JsonElement jsonNetwork in jsonUnderMaintenance.EnumerateArray())
- {
- string network = jsonNetwork.GetProperty("network").GetString();
- bool enabled;
- if (jsonNetwork.TryGetProperty("enabled", out JsonElement jsonEnabled))
- enabled = jsonEnabled.GetBoolean();
- else if (jsonNetwork.TryGetProperty("enable", out JsonElement jsonEnable))
- enabled = jsonEnable.GetBoolean();
- else
- enabled = true;
- NetworkAddress umNetwork = NetworkAddress.Parse(network);
- if (_underMaintenance.TryAdd(umNetwork, enabled))
- {
- if (enabled)
- {
- foreach (KeyValuePair<string, HealthMonitor> healthMonitor in _healthMonitors)
- {
- HealthMonitor monitor = healthMonitor.Value;
- if (monitor.Address is null)
- continue;
- if (umNetwork.Contains(monitor.Address))
- monitor.SetUnderMaintenance();
- }
- }
- }
- }
- }
- }
- public HealthCheckResponse QueryStatus(IPAddress address, string healthCheck, Uri healthCheckUrl, bool tryAdd)
- {
- string healthMonitorKey = GetHealthMonitorKey(address, healthCheck, healthCheckUrl);
- if (_healthMonitors.TryGetValue(healthMonitorKey, out HealthMonitor monitor))
- return monitor.LastHealthCheckResponse;
- if (_healthChecks.TryGetValue(healthCheck, out HealthCheck existingHealthCheck))
- {
- if (tryAdd)
- {
- monitor = new HealthMonitor(_dnsServer, address, existingHealthCheck, healthCheckUrl);
- if (!_healthMonitors.TryAdd(healthMonitorKey, monitor))
- monitor.Dispose(); //failed to add first
- }
- return new HealthCheckResponse(HealthStatus.Unknown);
- }
- else
- {
- return new HealthCheckResponse(HealthStatus.Failed, "No such health check: " + healthCheck);
- }
- }
- public HealthCheckResponse QueryStatus(string domain, DnsResourceRecordType type, string healthCheck, Uri healthCheckUrl, bool tryAdd)
- {
- domain = domain.ToLowerInvariant();
- string healthMonitorKey = GetHealthMonitorKey(domain, type, healthCheck, healthCheckUrl);
- if (_healthMonitors.TryGetValue(healthMonitorKey, out HealthMonitor monitor))
- return monitor.LastHealthCheckResponse;
- if (_healthChecks.TryGetValue(healthCheck, out HealthCheck existingHealthCheck))
- {
- if (tryAdd)
- {
- monitor = new HealthMonitor(_dnsServer, domain, type, existingHealthCheck, healthCheckUrl);
- if (!_healthMonitors.TryAdd(healthMonitorKey, monitor))
- monitor.Dispose(); //failed to add first
- }
- return new HealthCheckResponse(HealthStatus.Unknown);
- }
- else
- {
- return new HealthCheckResponse(HealthStatus.Failed, "No such health check: " + healthCheck);
- }
- }
- #endregion
- #region properties
- public ConcurrentDictionary<string, HealthCheck> HealthChecks
- { get { return _healthChecks; } }
- public ConcurrentDictionary<string, EmailAlert> EmailAlerts
- { get { return _emailAlerts; } }
- public ConcurrentDictionary<string, WebHook> WebHooks
- { get { return _webHooks; } }
- public ConcurrentDictionary<NetworkAddress, bool> UnderMaintenance
- { get { return _underMaintenance; } }
- public IDnsServer DnsServer
- { get { return _dnsServer; } }
- #endregion
- }
- }
|