123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437 |
- /*
- Technitium DNS Server
- Copyright (C) 2020 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 System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Threading;
- using TechnitiumLibrary.IO;
- using TechnitiumLibrary.Net;
- using TechnitiumLibrary.Net.Dns;
- namespace DnsServerCore.Dns
- {
- public enum StatsResponseCode
- {
- NoError = 1,
- ServerFailure = 2,
- NameError = 3,
- Refused = 4
- }
- public enum StatsResponseType
- {
- Authoritative = 1,
- Recursive = 2,
- Cached = 3,
- Blocked = 4
- }
- public class StatsManager : IDisposable
- {
- #region variables
- readonly string _statsFolder;
- readonly LogManager _log;
- readonly StatCounter[] _lastHourStatCounters = new StatCounter[60];
- readonly StatCounter[] _lastHourStatCountersCopy = new StatCounter[60];
- readonly ConcurrentDictionary<DateTime, HourlyStats> _hourlyStatsCache = new ConcurrentDictionary<DateTime, HourlyStats>();
- readonly ConcurrentDictionary<DateTime, StatCounter> _dailyStatsCache = new ConcurrentDictionary<DateTime, StatCounter>();
- readonly Timer _maintenanceTimer;
- const int MAINTENANCE_TIMER_INITIAL_INTERVAL = 10000;
- const int MAINTENANCE_TIMER_INTERVAL = 10000;
- readonly BlockingCollection<StatsQueueItem> _queue = new BlockingCollection<StatsQueueItem>();
- readonly Thread _consumerThread;
- #endregion
- #region constructor
- public StatsManager(string statsFolder, LogManager log)
- {
- _statsFolder = statsFolder;
- _log = log;
- //load stats
- LoadLastHourStats();
- //do first maintenance
- DoMaintenance();
- //start periodic maintenance timer
- _maintenanceTimer = new Timer(delegate (object state)
- {
- try
- {
- DoMaintenance();
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }, null, MAINTENANCE_TIMER_INITIAL_INTERVAL, MAINTENANCE_TIMER_INTERVAL);
- //stats consumer thread
- _consumerThread = new Thread(delegate ()
- {
- try
- {
- foreach (StatsQueueItem item in _queue.GetConsumingEnumerable())
- {
- StatCounter statCounter = _lastHourStatCounters[item._dateTime.Minute];
- if (statCounter != null)
- statCounter.Update(item._query, item._responseCode, item._responseType, item._clientIpAddress);
- }
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- });
- _consumerThread.Name = "Stats";
- _consumerThread.IsBackground = true;
- _consumerThread.Start();
- }
- #endregion
- #region IDisposable
- private bool _disposed = false;
- private readonly object _disposeLock = new object();
- protected virtual void Dispose(bool disposing)
- {
- lock (_disposeLock)
- {
- if (_disposed)
- return;
- if (disposing)
- {
- if (_maintenanceTimer != null)
- _maintenanceTimer.Dispose();
- //do last maintenance
- DoMaintenance();
- }
- _disposed = true;
- }
- }
- public void Dispose()
- {
- Dispose(true);
- }
- #endregion
- #region private
- private void LoadLastHourStats()
- {
- DateTime currentDateTime = DateTime.UtcNow;
- DateTime lastHourDateTime = currentDateTime.AddMinutes(-60);
- HourlyStats lastHourlyStats = null;
- DateTime lastHourlyStatsDateTime = new DateTime();
- for (int i = 0; i < 60; i++)
- {
- DateTime lastDateTime = lastHourDateTime.AddMinutes(i);
- if ((lastHourlyStats == null) || (lastDateTime.Hour != lastHourlyStatsDateTime.Hour))
- {
- lastHourlyStats = LoadHourlyStats(lastDateTime);
- lastHourlyStatsDateTime = lastDateTime;
- }
- _lastHourStatCounters[lastDateTime.Minute] = lastHourlyStats.MinuteStats[lastDateTime.Minute];
- _lastHourStatCountersCopy[lastDateTime.Minute] = _lastHourStatCounters[lastDateTime.Minute];
- }
- }
- private void DoMaintenance()
- {
- //load new stats counter 5 min ahead of current time
- DateTime currentDateTime = DateTime.UtcNow;
- for (int i = 0; i < 5; i++)
- {
- int minute = currentDateTime.AddMinutes(i).Minute;
- StatCounter statCounter = _lastHourStatCounters[minute];
- if ((statCounter == null) || statCounter.IsLocked)
- _lastHourStatCounters[minute] = new StatCounter();
- }
- //save data upto last 5 mins
- DateTime last5MinDateTime = currentDateTime.AddMinutes(-5);
- for (int i = 0; i < 5; i++)
- {
- DateTime lastDateTime = last5MinDateTime.AddMinutes(i);
- StatCounter lastStatCounter = _lastHourStatCounters[lastDateTime.Minute];
- if ((lastStatCounter != null) && !lastStatCounter.IsLocked)
- {
- //load hourly stats data
- HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
- //update hourly stats file
- lastStatCounter.Lock();
- hourlyStats.UpdateStat(lastDateTime, lastStatCounter);
- //save hourly stats
- SaveHourlyStats(lastDateTime, hourlyStats);
- //keep copy for api
- _lastHourStatCountersCopy[lastDateTime.Minute] = lastStatCounter;
- }
- }
- //load previous day stats to auto create daily stats file
- LoadDailyStats(currentDateTime.AddDays(-1));
- //remove old data from hourly stats cache
- {
- DateTime threshold = DateTime.UtcNow.AddHours(-24);
- threshold = new DateTime(threshold.Year, threshold.Month, threshold.Day, threshold.Hour, 0, 0, DateTimeKind.Utc);
- List<DateTime> _keysToRemove = new List<DateTime>();
- foreach (KeyValuePair<DateTime, HourlyStats> item in _hourlyStatsCache)
- {
- if (item.Key < threshold)
- _keysToRemove.Add(item.Key);
- }
- foreach (DateTime key in _keysToRemove)
- _hourlyStatsCache.TryRemove(key, out _);
- }
- //remove old data from daily stats cache
- {
- DateTime threshold = DateTime.UtcNow.AddMonths(-12);
- threshold = new DateTime(threshold.Year, threshold.Month, 1, 0, 0, 0, DateTimeKind.Utc);
- List<DateTime> _keysToRemove = new List<DateTime>();
- foreach (KeyValuePair<DateTime, StatCounter> item in _dailyStatsCache)
- {
- if (item.Key < threshold)
- _keysToRemove.Add(item.Key);
- }
- foreach (DateTime key in _keysToRemove)
- _dailyStatsCache.TryRemove(key, out _);
- }
- }
- private HourlyStats LoadHourlyStats(DateTime dateTime)
- {
- DateTime hourlyDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, 0, DateTimeKind.Utc);
- if (!_hourlyStatsCache.TryGetValue(hourlyDateTime, out HourlyStats hourlyStats))
- {
- string hourlyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMddHH") + ".stat");
- if (File.Exists(hourlyStatsFile))
- {
- try
- {
- using (FileStream fS = new FileStream(hourlyStatsFile, FileMode.Open, FileAccess.Read))
- {
- hourlyStats = new HourlyStats(new BinaryReader(fS));
- }
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- hourlyStats = new HourlyStats();
- }
- }
- else
- {
- hourlyStats = new HourlyStats();
- }
- if (!_hourlyStatsCache.TryAdd(hourlyDateTime, hourlyStats))
- {
- if (!_hourlyStatsCache.TryGetValue(hourlyDateTime, out hourlyStats))
- throw new DnsServerException("Unable to load hourly stats.");
- }
- }
- return hourlyStats;
- }
- private StatCounter LoadDailyStats(DateTime dateTime)
- {
- DateTime dailyDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0, DateTimeKind.Utc);
- if (!_dailyStatsCache.TryGetValue(dailyDateTime, out StatCounter dailyStats))
- {
- string dailyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMdd") + ".dstat");
- if (File.Exists(dailyStatsFile))
- {
- try
- {
- using (FileStream fS = new FileStream(dailyStatsFile, FileMode.Open, FileAccess.Read))
- {
- dailyStats = new StatCounter(new BinaryReader(fS));
- }
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- if (dailyStats == null)
- {
- dailyStats = new StatCounter();
- dailyStats.Lock();
- for (int hour = 0; hour < 24; hour++) //hours
- {
- HourlyStats hourlyStats = LoadHourlyStats(dailyDateTime.AddHours(hour));
- dailyStats.Merge(hourlyStats.HourStat);
- }
- if (dailyStats.TotalQueries > 0)
- SaveDailyStats(dailyDateTime, dailyStats);
- }
- if (!_dailyStatsCache.TryAdd(dailyDateTime, dailyStats))
- {
- if (!_dailyStatsCache.TryGetValue(dailyDateTime, out dailyStats))
- throw new DnsServerException("Unable to load daily stats.");
- }
- }
- return dailyStats;
- }
- private void SaveHourlyStats(DateTime dateTime, HourlyStats hourlyStats)
- {
- string hourlyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMddHH") + ".stat");
- try
- {
- using (FileStream fS = new FileStream(hourlyStatsFile, FileMode.Create, FileAccess.Write))
- {
- hourlyStats.WriteTo(new BinaryWriter(fS));
- }
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- private void SaveDailyStats(DateTime dateTime, StatCounter dailyStats)
- {
- string dailyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMdd") + ".dstat");
- try
- {
- using (FileStream fS = new FileStream(dailyStatsFile, FileMode.Create, FileAccess.Write))
- {
- dailyStats.WriteTo(new BinaryWriter(fS));
- }
- }
- catch (Exception ex)
- {
- _log.Write(ex);
- }
- }
- #endregion
- #region public
- public void Update(DnsDatagram response, IPAddress clientIpAddress)
- {
- StatsResponseCode responseCode;
- switch (response.RCODE)
- {
- case DnsResponseCode.NoError:
- responseCode = StatsResponseCode.NoError;
- break;
- case DnsResponseCode.ServerFailure:
- responseCode = StatsResponseCode.ServerFailure;
- break;
- case DnsResponseCode.NameError:
- responseCode = StatsResponseCode.NameError;
- break;
- case DnsResponseCode.Refused:
- responseCode = StatsResponseCode.Refused;
- break;
- default:
- return;
- }
- StatsResponseType responseType;
- if (response.Tag == null)
- responseType = StatsResponseType.Recursive;
- else
- responseType = (StatsResponseType)response.Tag;
- StatsQueueItem item;
- if (response.QDCOUNT > 0)
- item = new StatsQueueItem(response.Question[0], responseCode, responseType, clientIpAddress);
- else
- item = new StatsQueueItem(new DnsQuestionRecord("", DnsResourceRecordType.ANY, DnsClass.IN), responseCode, responseType, clientIpAddress);
- _queue.Add(item);
- }
- public Dictionary<string, List<KeyValuePair<string, int>>> GetLastHourStats()
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, int>> totalQueriesPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalNoErrorPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalServerFailurePerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalNameErrorPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalRefusedPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalAuthHitPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalRecursionsPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalCacheHitPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalBlockedPerInterval = new List<KeyValuePair<string, int>>(60);
- List<KeyValuePair<string, int>> totalClientsPerInterval = new List<KeyValuePair<string, int>>(60);
- DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(-60);
- lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
- for (int minute = 0; minute < 60; minute++)
- {
- DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
- string label = lastDateTime.ToLocalTime().ToString("HH:mm");
- StatCounter statCounter = _lastHourStatCountersCopy[lastDateTime.Minute];
- if ((statCounter != null) && statCounter.IsLocked)
- {
- totalStatCounter.Merge(statCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalServerFailure));
- totalNameErrorPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalNameError));
- totalRefusedPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, int>(label, statCounter.TotalClients));
- }
- else
- {
- totalQueriesPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalNameErrorPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalRefusedPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalBlockedPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- totalClientsPerInterval.Add(new KeyValuePair<string, int>(label, 0));
- }
- }
- Dictionary<string, List<KeyValuePair<string, int>>> data = new Dictionary<string, List<KeyValuePair<string, int>>>();
- {
- List<KeyValuePair<string, int>> stats = new List<KeyValuePair<string, int>>(10);
- stats.Add(new KeyValuePair<string, int>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, int>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, int>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, int>("totalNameError", totalStatCounter.TotalNameError));
- stats.Add(new KeyValuePair<string, int>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, int>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, int>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, int>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, int>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, int>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNameErrorPerInterval", totalNameErrorPerInterval);
- data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
- data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
- data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
- data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
- data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
- data.Add("totalClientsPerInterval", totalClientsPerInterval);
- data.Add("topDomains", totalStatCounter.GetTopDomains(10));
- data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
- data.Add("topClients", totalStatCounter.GetTopClients(10));
- data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(5));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, int>>> GetLastDayStats()
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, int>> totalQueriesPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNoErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalServerFailurePerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNameErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRefusedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalAuthHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRecursionsPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalCacheHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalBlockedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalClientsPerInterval = new List<KeyValuePair<string, int>>();
- DateTime lastDayDateTime = DateTime.UtcNow.AddHours(-24);
- lastDayDateTime = new DateTime(lastDayDateTime.Year, lastDayDateTime.Month, lastDayDateTime.Day, lastDayDateTime.Hour, 0, 0, DateTimeKind.Utc);
- for (int hour = 0; hour < 24; hour++)
- {
- DateTime lastDateTime = lastDayDateTime.AddHours(hour);
- string label = lastDateTime.ToLocalTime().ToString("MM/dd HH") + ":00";
- HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
- StatCounter hourlyStatCounter = hourlyStats.HourStat;
- totalStatCounter.Merge(hourlyStatCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalServerFailure));
- totalNameErrorPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalNameError));
- totalRefusedPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, int>(label, hourlyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, int>>> data = new Dictionary<string, List<KeyValuePair<string, int>>>();
- {
- List<KeyValuePair<string, int>> stats = new List<KeyValuePair<string, int>>(6);
- stats.Add(new KeyValuePair<string, int>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, int>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, int>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, int>("totalNameError", totalStatCounter.TotalNameError));
- stats.Add(new KeyValuePair<string, int>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, int>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, int>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, int>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, int>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, int>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNameErrorPerInterval", totalNameErrorPerInterval);
- data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
- data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
- data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
- data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
- data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
- data.Add("totalClientsPerInterval", totalClientsPerInterval);
- data.Add("topDomains", totalStatCounter.GetTopDomains(10));
- data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
- data.Add("topClients", totalStatCounter.GetTopClients(10));
- data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(5));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, int>>> GetLastWeekStats()
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, int>> totalQueriesPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNoErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalServerFailurePerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNameErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRefusedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalAuthHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRecursionsPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalCacheHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalBlockedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalClientsPerInterval = new List<KeyValuePair<string, int>>();
- DateTime lastWeekDateTime = DateTime.UtcNow.AddDays(-7);
- lastWeekDateTime = new DateTime(lastWeekDateTime.Year, lastWeekDateTime.Month, lastWeekDateTime.Day, 0, 0, 0, DateTimeKind.Utc);
- for (int day = 0; day < 7; day++) //days
- {
- DateTime lastDayDateTime = lastWeekDateTime.AddDays(day);
- string label = lastDayDateTime.ToLocalTime().ToString("MM/dd");
- StatCounter dailyStatCounter = LoadDailyStats(lastDayDateTime);
- totalStatCounter.Merge(dailyStatCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalServerFailure));
- totalNameErrorPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalNameError));
- totalRefusedPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, int>>> data = new Dictionary<string, List<KeyValuePair<string, int>>>();
- {
- List<KeyValuePair<string, int>> stats = new List<KeyValuePair<string, int>>(6);
- stats.Add(new KeyValuePair<string, int>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, int>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, int>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, int>("totalNameError", totalStatCounter.TotalNameError));
- stats.Add(new KeyValuePair<string, int>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, int>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, int>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, int>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, int>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, int>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNameErrorPerInterval", totalNameErrorPerInterval);
- data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
- data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
- data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
- data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
- data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
- data.Add("totalClientsPerInterval", totalClientsPerInterval);
- data.Add("topDomains", totalStatCounter.GetTopDomains(10));
- data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
- data.Add("topClients", totalStatCounter.GetTopClients(10));
- data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(5));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, int>>> GetLastMonthStats()
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, int>> totalQueriesPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNoErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalServerFailurePerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNameErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRefusedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalAuthHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRecursionsPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalCacheHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalBlockedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalClientsPerInterval = new List<KeyValuePair<string, int>>();
- DateTime lastMonthDateTime = DateTime.UtcNow.AddDays(-31);
- lastMonthDateTime = new DateTime(lastMonthDateTime.Year, lastMonthDateTime.Month, lastMonthDateTime.Day, 0, 0, 0, DateTimeKind.Utc);
- for (int day = 0; day < 31; day++) //days
- {
- DateTime lastDayDateTime = lastMonthDateTime.AddDays(day);
- string label = lastDayDateTime.ToLocalTime().ToString("MM/dd");
- StatCounter dailyStatCounter = LoadDailyStats(lastDayDateTime);
- totalStatCounter.Merge(dailyStatCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalServerFailure));
- totalNameErrorPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalNameError));
- totalRefusedPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, int>(label, dailyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, int>>> data = new Dictionary<string, List<KeyValuePair<string, int>>>();
- {
- List<KeyValuePair<string, int>> stats = new List<KeyValuePair<string, int>>(6);
- stats.Add(new KeyValuePair<string, int>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, int>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, int>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, int>("totalNameError", totalStatCounter.TotalNameError));
- stats.Add(new KeyValuePair<string, int>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, int>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, int>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, int>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, int>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, int>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNameErrorPerInterval", totalNameErrorPerInterval);
- data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
- data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
- data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
- data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
- data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
- data.Add("totalClientsPerInterval", totalClientsPerInterval);
- data.Add("topDomains", totalStatCounter.GetTopDomains(10));
- data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
- data.Add("topClients", totalStatCounter.GetTopClients(10));
- data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(5));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, int>>> GetLastYearStats()
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, int>> totalQueriesPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNoErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalServerFailurePerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalNameErrorPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRefusedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalAuthHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalRecursionsPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalCacheHitPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalBlockedPerInterval = new List<KeyValuePair<string, int>>();
- List<KeyValuePair<string, int>> totalClientsPerInterval = new List<KeyValuePair<string, int>>();
- DateTime lastYearDateTime = DateTime.UtcNow.AddMonths(-12);
- lastYearDateTime = new DateTime(lastYearDateTime.Year, lastYearDateTime.Month, 1, 0, 0, 0, DateTimeKind.Utc);
- for (int month = 0; month < 12; month++) //months
- {
- StatCounter monthlyStatCounter = new StatCounter();
- monthlyStatCounter.Lock();
- DateTime lastMonthDateTime = lastYearDateTime.AddMonths(month);
- string label = lastMonthDateTime.ToLocalTime().ToString("MM/yyyy");
- int days = DateTime.DaysInMonth(lastMonthDateTime.Year, lastMonthDateTime.Month);
- for (int day = 0; day < days; day++) //days
- {
- StatCounter dailyStatCounter = LoadDailyStats(lastMonthDateTime.AddDays(day));
- monthlyStatCounter.Merge(dailyStatCounter);
- }
- totalStatCounter.Merge(monthlyStatCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalServerFailure));
- totalNameErrorPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalNameError));
- totalRefusedPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, int>(label, monthlyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, int>>> data = new Dictionary<string, List<KeyValuePair<string, int>>>();
- {
- List<KeyValuePair<string, int>> stats = new List<KeyValuePair<string, int>>(6);
- stats.Add(new KeyValuePair<string, int>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, int>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, int>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, int>("totalNameError", totalStatCounter.TotalNameError));
- stats.Add(new KeyValuePair<string, int>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, int>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, int>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, int>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, int>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, int>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNameErrorPerInterval", totalNameErrorPerInterval);
- data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
- data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
- data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
- data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
- data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
- data.Add("totalClientsPerInterval", totalClientsPerInterval);
- data.Add("topDomains", totalStatCounter.GetTopDomains(10));
- data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
- data.Add("topClients", totalStatCounter.GetTopClients(10));
- data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(5));
- return data;
- }
- public List<KeyValuePair<DnsQuestionRecord, int>> GetLastHourEligibleQueries(int minimumHitsPerHour)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(-60);
- lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
- for (int minute = 0; minute < 60; minute++)
- {
- DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
- StatCounter statCounter = _lastHourStatCountersCopy[lastDateTime.Minute];
- if ((statCounter != null) && statCounter.IsLocked)
- totalStatCounter.Merge(statCounter);
- }
- return totalStatCounter.GetEligibleQueries(minimumHitsPerHour);
- }
- #endregion
- class HourlyStats
- {
- #region variables
- readonly StatCounter _hourStat; //calculated value
- readonly StatCounter[] _minuteStats = new StatCounter[60];
- #endregion
- #region constructor
- public HourlyStats()
- {
- _hourStat = new StatCounter();
- _hourStat.Lock();
- }
- public HourlyStats(BinaryReader bR)
- {
- if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "HS") //format
- throw new InvalidDataException("HourlyStats format is invalid.");
- byte version = bR.ReadByte();
- switch (version)
- {
- case 1:
- _hourStat = new StatCounter();
- _hourStat.Lock();
- for (int i = 0; i < _minuteStats.Length; i++)
- {
- _minuteStats[i] = new StatCounter(bR);
- _hourStat.Merge(_minuteStats[i]);
- }
- break;
- default:
- throw new InvalidDataException("HourlyStats version not supported.");
- }
- }
- #endregion
- #region public
- public void UpdateStat(DateTime dateTime, StatCounter minuteStat)
- {
- if (!minuteStat.IsLocked)
- throw new DnsServerException("StatCounter must be locked.");
- _hourStat.Merge(minuteStat);
- _minuteStats[dateTime.Minute] = minuteStat;
- }
- public void WriteTo(BinaryWriter bW)
- {
- bW.Write(Encoding.ASCII.GetBytes("HS")); //format
- bW.Write((byte)1); //version
- for (int i = 0; i < _minuteStats.Length; i++)
- {
- if (_minuteStats[i] == null)
- {
- _minuteStats[i] = new StatCounter();
- _minuteStats[i].Lock();
- }
- _minuteStats[i].WriteTo(bW);
- }
- }
- #endregion
- #region properties
- public StatCounter HourStat
- { get { return _hourStat; } }
- public StatCounter[] MinuteStats
- {
- get { return _minuteStats; }
- }
- #endregion
- }
- class StatCounter
- {
- #region variables
- volatile bool _locked;
- int _totalQueries;
- int _totalNoError;
- int _totalServerFailure;
- int _totalNameError;
- int _totalRefused;
- int _totalAuthoritative;
- int _totalRecursive;
- int _totalCached;
- int _totalBlocked;
- readonly ConcurrentDictionary<string, Counter> _queryDomains = new ConcurrentDictionary<string, Counter>();
- readonly ConcurrentDictionary<string, Counter> _queryBlockedDomains = new ConcurrentDictionary<string, Counter>();
- readonly ConcurrentDictionary<DnsResourceRecordType, Counter> _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>();
- readonly ConcurrentDictionary<IPAddress, Counter> _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>();
- readonly ConcurrentDictionary<DnsQuestionRecord, Counter> _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>();
- #endregion
- #region constructor
- public StatCounter()
- { }
- public StatCounter(BinaryReader bR)
- {
- if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "SC") //format
- throw new InvalidDataException("StatCounter format is invalid.");
- byte version = bR.ReadByte();
- switch (version)
- {
- case 1:
- case 2:
- case 3:
- _totalQueries = bR.ReadInt32();
- _totalNoError = bR.ReadInt32();
- _totalServerFailure = bR.ReadInt32();
- _totalNameError = bR.ReadInt32();
- _totalRefused = bR.ReadInt32();
- if (version >= 3)
- {
- _totalAuthoritative = bR.ReadInt32();
- _totalRecursive = bR.ReadInt32();
- _totalCached = bR.ReadInt32();
- _totalBlocked = bR.ReadInt32();
- }
- else
- {
- _totalBlocked = bR.ReadInt32();
- if (version >= 2)
- _totalCached = bR.ReadInt32();
- }
- {
- int count = bR.ReadInt32();
- for (int i = 0; i < count; i++)
- _queryDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt32()));
- }
- {
- int count = bR.ReadInt32();
- for (int i = 0; i < count; i++)
- _queryBlockedDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt32()));
- }
- {
- int count = bR.ReadInt32();
- for (int i = 0; i < count; i++)
- _queryTypes.TryAdd((DnsResourceRecordType)bR.ReadUInt16(), new Counter(bR.ReadInt32()));
- }
- {
- int count = bR.ReadInt32();
- for (int i = 0; i < count; i++)
- _clientIpAddresses.TryAdd(IPAddressExtension.Parse(bR), new Counter(bR.ReadInt32()));
- }
- break;
- default:
- throw new InvalidDataException("StatCounter version not supported.");
- }
- _locked = true;
- }
- #endregion
- #region private
- private static List<KeyValuePair<string, int>> GetTopList(List<KeyValuePair<string, int>> list, int limit)
- {
- list.Sort(delegate (KeyValuePair<string, int> item1, KeyValuePair<string, int> item2)
- {
- return item2.Value.CompareTo(item1.Value);
- });
- if (list.Count > limit)
- list.RemoveRange(limit, list.Count - limit);
- return list;
- }
- private static Counter GetNewCounter<T>(T key)
- {
- return new Counter();
- }
- #endregion
- #region public
- public void Lock()
- {
- _locked = true;
- }
- public void Update(DnsQuestionRecord query, StatsResponseCode responseCode, StatsResponseType responseType, IPAddress clientIpAddress)
- {
- if (_locked)
- return;
- if (clientIpAddress.IsIPv4MappedToIPv6)
- clientIpAddress = clientIpAddress.MapToIPv4();
- string domain = query.Name.ToLower();
- Interlocked.Increment(ref _totalQueries);
- switch (responseCode)
- {
- case StatsResponseCode.NoError:
- if (responseType != StatsResponseType.Blocked) //skip blocked domains
- {
- _queryDomains.GetOrAdd(domain, GetNewCounter).Increment();
- _queries.GetOrAdd(query, GetNewCounter).Increment();
- }
- Interlocked.Increment(ref _totalNoError);
- break;
- case StatsResponseCode.ServerFailure:
- Interlocked.Increment(ref _totalServerFailure);
- break;
- case StatsResponseCode.NameError:
- Interlocked.Increment(ref _totalNameError);
- break;
- case StatsResponseCode.Refused:
- Interlocked.Increment(ref _totalRefused);
- break;
- }
- switch (responseType)
- {
- case StatsResponseType.Authoritative:
- Interlocked.Increment(ref _totalAuthoritative);
- break;
- case StatsResponseType.Recursive: //recursion
- Interlocked.Increment(ref _totalRecursive);
- break;
- case StatsResponseType.Cached:
- Interlocked.Increment(ref _totalCached);
- break;
- case StatsResponseType.Blocked:
- _queryBlockedDomains.GetOrAdd(domain, GetNewCounter).Increment();
- Interlocked.Increment(ref _totalBlocked);
- break;
- }
- _queryTypes.GetOrAdd(query.Type, GetNewCounter).Increment();
- _clientIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
- }
- public void Merge(StatCounter statCounter)
- {
- if (!_locked || !statCounter._locked)
- throw new DnsServerException("StatCounter must be locked.");
- _totalQueries += statCounter._totalQueries;
- _totalNoError += statCounter._totalNoError;
- _totalServerFailure += statCounter._totalServerFailure;
- _totalNameError += statCounter._totalNameError;
- _totalRefused += statCounter._totalRefused;
- _totalAuthoritative += statCounter._totalAuthoritative;
- _totalRecursive += statCounter._totalRecursive;
- _totalCached += statCounter._totalCached;
- _totalBlocked += statCounter._totalBlocked;
- foreach (KeyValuePair<string, Counter> queryDomain in statCounter._queryDomains)
- _queryDomains.GetOrAdd(queryDomain.Key, GetNewCounter).Merge(queryDomain.Value);
- foreach (KeyValuePair<string, Counter> queryBlockedDomain in statCounter._queryBlockedDomains)
- _queryBlockedDomains.GetOrAdd(queryBlockedDomain.Key, GetNewCounter).Merge(queryBlockedDomain.Value);
- foreach (KeyValuePair<DnsResourceRecordType, Counter> queryType in statCounter._queryTypes)
- _queryTypes.GetOrAdd(queryType.Key, GetNewCounter).Merge(queryType.Value);
- foreach (KeyValuePair<IPAddress, Counter> clientIpAddress in statCounter._clientIpAddresses)
- _clientIpAddresses.GetOrAdd(clientIpAddress.Key, GetNewCounter).Merge(clientIpAddress.Value);
- foreach (KeyValuePair<DnsQuestionRecord, Counter> query in statCounter._queries)
- _queries.GetOrAdd(query.Key, GetNewCounter).Merge(query.Value);
- }
- public void WriteTo(BinaryWriter bW)
- {
- if (!_locked)
- throw new DnsServerException("StatCounter must be locked.");
- bW.Write(Encoding.ASCII.GetBytes("SC")); //format
- bW.Write((byte)3); //version
- bW.Write(_totalQueries);
- bW.Write(_totalNoError);
- bW.Write(_totalServerFailure);
- bW.Write(_totalNameError);
- bW.Write(_totalRefused);
- bW.Write(_totalAuthoritative);
- bW.Write(_totalRecursive);
- bW.Write(_totalCached);
- bW.Write(_totalBlocked);
- {
- bW.Write(_queryDomains.Count);
- foreach (KeyValuePair<string, Counter> queryDomain in _queryDomains)
- {
- bW.WriteShortString(queryDomain.Key);
- bW.Write(queryDomain.Value.Count);
- }
- }
- {
- bW.Write(_queryBlockedDomains.Count);
- foreach (KeyValuePair<string, Counter> queryBlockedDomain in _queryBlockedDomains)
- {
- bW.WriteShortString(queryBlockedDomain.Key);
- bW.Write(queryBlockedDomain.Value.Count);
- }
- }
- {
- bW.Write(_queryTypes.Count);
- foreach (KeyValuePair<DnsResourceRecordType, Counter> queryType in _queryTypes)
- {
- bW.Write((ushort)queryType.Key);
- bW.Write(queryType.Value.Count);
- }
- }
- {
- bW.Write(_clientIpAddresses.Count);
- foreach (KeyValuePair<IPAddress, Counter> clientIpAddress in _clientIpAddresses)
- {
- clientIpAddress.Key.WriteTo(bW);
- bW.Write(clientIpAddress.Value.Count);
- }
- }
- }
- public List<KeyValuePair<string, int>> GetTopDomains(int limit)
- {
- List<KeyValuePair<string, int>> topDomains = new List<KeyValuePair<string, int>>(10);
- foreach (KeyValuePair<string, Counter> item in _queryDomains)
- topDomains.Add(new KeyValuePair<string, int>(item.Key, item.Value.Count));
- return GetTopList(topDomains, limit);
- }
- public List<KeyValuePair<string, int>> GetTopBlockedDomains(int limit)
- {
- List<KeyValuePair<string, int>> topBlockedDomains = new List<KeyValuePair<string, int>>(10);
- foreach (KeyValuePair<string, Counter> item in _queryBlockedDomains)
- topBlockedDomains.Add(new KeyValuePair<string, int>(item.Key, item.Value.Count));
- return GetTopList(topBlockedDomains, limit);
- }
- public List<KeyValuePair<string, int>> GetTopClients(int limit)
- {
- List<KeyValuePair<string, int>> topClients = new List<KeyValuePair<string, int>>(10);
- foreach (KeyValuePair<IPAddress, Counter> item in _clientIpAddresses)
- topClients.Add(new KeyValuePair<string, int>(item.Key.ToString(), item.Value.Count));
- return GetTopList(topClients, limit);
- }
- public List<KeyValuePair<string, int>> GetTopQueryTypes(int limit)
- {
- List<KeyValuePair<string, int>> queryTypes = new List<KeyValuePair<string, int>>(10);
- foreach (KeyValuePair<DnsResourceRecordType, Counter> item in _queryTypes)
- queryTypes.Add(new KeyValuePair<string, int>(item.Key.ToString(), item.Value.Count));
- queryTypes.Sort(delegate (KeyValuePair<string, int> item1, KeyValuePair<string, int> item2)
- {
- return item2.Value.CompareTo(item1.Value);
- });
- if (queryTypes.Count > limit)
- {
- int othersCount = 0;
- for (int i = limit; i < queryTypes.Count; i++)
- othersCount += queryTypes[i].Value;
- queryTypes.RemoveRange((limit - 1), queryTypes.Count - (limit - 1));
- queryTypes.Add(new KeyValuePair<string, int>("Others", othersCount));
- }
- return queryTypes;
- }
- public List<KeyValuePair<DnsQuestionRecord, int>> GetEligibleQueries(int minimumHits)
- {
- List<KeyValuePair<DnsQuestionRecord, int>> eligibleQueries = new List<KeyValuePair<DnsQuestionRecord, int>>(100);
- foreach (KeyValuePair<DnsQuestionRecord, Counter> item in _queries)
- {
- if (item.Value.Count >= minimumHits)
- eligibleQueries.Add(new KeyValuePair<DnsQuestionRecord, int>(item.Key, item.Value.Count));
- }
- return eligibleQueries;
- }
- #endregion
- #region properties
- public bool IsLocked
- { get { return _locked; } }
- public int TotalQueries
- { get { return _totalQueries; } }
- public int TotalNoError
- { get { return _totalNoError; } }
- public int TotalServerFailure
- { get { return _totalServerFailure; } }
- public int TotalNameError
- { get { return _totalNameError; } }
- public int TotalRefused
- { get { return _totalRefused; } }
- public int TotalAuthoritative
- { get { return _totalAuthoritative; } }
- public int TotalRecursive
- { get { return _totalRecursive; } }
- public int TotalCached
- { get { return _totalCached; } }
- public int TotalBlocked
- { get { return _totalBlocked; } }
- public int TotalClients
- { get { return _clientIpAddresses.Count; } }
- #endregion
- class Counter
- {
- #region variables
- int _count;
- #endregion
- #region constructor
- public Counter()
- { }
- public Counter(int count)
- {
- _count = count;
- }
- #endregion
- #region public
- public void Increment()
- {
- Interlocked.Increment(ref _count);
- }
- public void Merge(Counter counter)
- {
- _count += counter._count;
- }
- #endregion
- #region properties
- public int Count
- { get { return _count; } }
- #endregion
- }
- }
- class StatsQueueItem
- {
- #region variables
- public readonly DateTime _dateTime;
- public readonly DnsQuestionRecord _query;
- public readonly StatsResponseCode _responseCode;
- public readonly StatsResponseType _responseType;
- public readonly IPAddress _clientIpAddress;
- #endregion
- #region constructor
- public StatsQueueItem(DnsQuestionRecord query, StatsResponseCode responseCode, StatsResponseType responseType, IPAddress clientIpAddress)
- {
- _dateTime = DateTime.UtcNow;
- _query = query;
- _responseCode = responseCode;
- _responseType = responseType;
- _clientIpAddress = clientIpAddress;
- }
- #endregion
- }
- }
- }
|