12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123 |
- /*
- Technitium DNS Server
- Copyright (C) 2023 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.Globalization;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using TechnitiumLibrary.IO;
- using TechnitiumLibrary.Net;
- using TechnitiumLibrary.Net.Dns;
- using TechnitiumLibrary.Net.Dns.ResourceRecords;
- namespace DnsServerCore.Dns
- {
- public enum TopStatsType
- {
- Unknown = 0,
- TopClients = 1,
- TopDomains = 2,
- TopBlockedDomains = 3
- }
- public sealed class StatsManager : IDisposable
- {
- #region variables
- const int DAILY_STATS_FILE_TOP_LIMIT = 1000;
- readonly DnsServer _dnsServer;
- readonly string _statsFolder;
- 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_PERIODIC_INTERVAL = 10000;
- readonly BlockingCollection<StatsQueueItem> _queue = new BlockingCollection<StatsQueueItem>();
- readonly Thread _consumerThread;
- readonly Timer _statsCleanupTimer;
- int _maxStatFileDays = 0;
- const int STATS_CLEANUP_TIMER_INITIAL_INTERVAL = 60 * 1000;
- const int STATS_CLEANUP_TIMER_PERIODIC_INTERVAL = 60 * 60 * 1000;
- #endregion
- #region constructor
- public StatsManager(DnsServer dnsServer)
- {
- _dnsServer = dnsServer;
- _statsFolder = Path.Combine(dnsServer.ConfigFolder, "stats");
- if (!Directory.Exists(_statsFolder))
- Directory.CreateDirectory(_statsFolder);
- //load stats
- LoadLastHourStats();
- try
- {
- //do first maintenance
- DoMaintenance();
- }
- catch (Exception ex)
- {
- _dnsServer.LogManager?.Write(ex);
- }
- //start periodic maintenance timer
- _maintenanceTimer = new Timer(delegate (object state)
- {
- try
- {
- DoMaintenance();
- }
- catch (Exception ex)
- {
- _dnsServer.LogManager?.Write(ex);
- }
- }, null, MAINTENANCE_TIMER_INITIAL_INTERVAL, MAINTENANCE_TIMER_PERIODIC_INTERVAL);
- //stats consumer thread
- _consumerThread = new Thread(delegate ()
- {
- try
- {
- foreach (StatsQueueItem item in _queue.GetConsumingEnumerable())
- {
- StatCounter statCounter = _lastHourStatCounters[item._timestamp.Minute];
- if (statCounter is not null)
- {
- DnsQuestionRecord query;
- if (item._request.Question.Count > 0)
- query = item._request.Question[0];
- else
- query = null;
- DnsServerResponseType responseType;
- if (item._response.Tag is null)
- responseType = DnsServerResponseType.Recursive;
- else
- responseType = (DnsServerResponseType)item._response.Tag;
- statCounter.Update(query, item._response.RCODE, responseType, item._remoteEP.Address);
- }
- foreach (IDnsQueryLogger logger in _dnsServer.DnsApplicationManager.DnsQueryLoggers)
- {
- try
- {
- _ = logger.InsertLogAsync(item._timestamp, item._request, item._remoteEP, item._protocol, item._response);
- }
- catch (Exception ex)
- {
- LogManager log = dnsServer.LogManager;
- if (log is not null)
- log.Write(ex);
- }
- }
- }
- }
- catch (Exception ex)
- {
- _dnsServer.LogManager?.Write(ex);
- }
- });
- _consumerThread.Name = "Stats";
- _consumerThread.IsBackground = true;
- _consumerThread.Start();
- _statsCleanupTimer = new Timer(delegate (object state)
- {
- try
- {
- if (_maxStatFileDays < 1)
- return;
- DateTime cutoffDate = DateTime.UtcNow.AddDays(_maxStatFileDays * -1).Date;
- LogManager log = dnsServer.LogManager;
- //delete hourly logs
- {
- string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.stat");
- foreach (string hourlyStatsFile in hourlyStatsFiles)
- {
- string hourlyStatsFileName = Path.GetFileNameWithoutExtension(hourlyStatsFile);
- if (!DateTime.TryParseExact(hourlyStatsFileName, "yyyyMMddHH", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime hourlyStatsFileDate))
- continue;
- if (hourlyStatsFileDate < cutoffDate)
- {
- try
- {
- File.Delete(hourlyStatsFile);
- if (log != null)
- log.Write("StatsManager cleanup deleted the hourly stats file: " + hourlyStatsFile);
- }
- catch (Exception ex)
- {
- if (log != null)
- log.Write(ex);
- }
- }
- }
- }
- //delete daily logs
- {
- string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.dstat");
- foreach (string dailyStatsFile in dailyStatsFiles)
- {
- string dailyStatsFileName = Path.GetFileNameWithoutExtension(dailyStatsFile);
- if (!DateTime.TryParseExact(dailyStatsFileName, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime dailyStatsFileDate))
- continue;
- if (dailyStatsFileDate < cutoffDate)
- {
- try
- {
- File.Delete(dailyStatsFile);
- if (log != null)
- log.Write("StatsManager cleanup deleted the daily stats file: " + dailyStatsFile);
- }
- catch (Exception ex)
- {
- if (log != null)
- log.Write(ex);
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- _dnsServer.LogManager?.Write(ex);
- }
- });
- _statsCleanupTimer.Change(STATS_CLEANUP_TIMER_INITIAL_INTERVAL, STATS_CLEANUP_TIMER_PERIODIC_INTERVAL);
- }
- #endregion
- #region IDisposable
- bool _disposed;
- readonly object _disposeLock = new object();
- private 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()
- {
- try
- {
- 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];
- }
- }
- catch (Exception ex)
- {
- _dnsServer.LogManager?.Write(ex);
- }
- }
- 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 _);
- }
- //unload minute stats data from hourly stats cache for data older than last hour
- {
- DateTime lastHourThreshold = DateTime.UtcNow.AddHours(-1);
- lastHourThreshold = new DateTime(lastHourThreshold.Year, lastHourThreshold.Month, lastHourThreshold.Day, lastHourThreshold.Hour, 0, 0, DateTimeKind.Utc);
- foreach (KeyValuePair<DateTime, HourlyStats> item in _hourlyStatsCache)
- {
- if (item.Key < lastHourThreshold)
- item.Value.UnloadMinuteStats();
- }
- }
- //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)
- {
- LogManager log = _dnsServer.LogManager;
- if (log != null)
- 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));
- }
- //check if existing file could be truncated to avoid loading unnecessary data in memory
- if (dailyStats.Truncate(DAILY_STATS_FILE_TOP_LIMIT))
- SaveDailyStats(dailyDateTime, dailyStats); //save truncated file
- }
- catch (Exception ex)
- {
- LogManager log = _dnsServer.LogManager;
- if (log != null)
- 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)
- {
- _ = dailyStats.Truncate(DAILY_STATS_FILE_TOP_LIMIT);
- 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)
- {
- LogManager log = _dnsServer.LogManager;
- if (log != null)
- 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)
- {
- LogManager log = _dnsServer.LogManager;
- if (log != null)
- log.Write(ex);
- }
- }
- private void Flush()
- {
- //clear in memory stats
- for (int i = 0; i < _lastHourStatCountersCopy.Length; i++)
- _lastHourStatCountersCopy[i] = null;
- _hourlyStatsCache.Clear();
- _dailyStatsCache.Clear();
- }
- #endregion
- #region public
- public void ReloadStats()
- {
- Flush();
- LoadLastHourStats();
- }
- public void DeleteAllStats()
- {
- foreach (string hourlyStatsFile in Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly))
- {
- File.Delete(hourlyStatsFile);
- }
- foreach (string dailyStatsFile in Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly))
- {
- File.Delete(dailyStatsFile);
- }
- Flush();
- }
- public void QueueUpdate(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
- {
- _queue.Add(new StatsQueueItem(request, remoteEP, protocol, response));
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetLastHourMinuteWiseStats(bool utcFormat)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>(60);
- List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>(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;
- if (utcFormat)
- label = lastDateTime.AddMinutes(1).ToString("O");
- else
- label = lastDateTime.AddMinutes(1).ToLocalTime().ToString("HH:mm");
- StatCounter statCounter = _lastHourStatCountersCopy[lastDateTime.Minute];
- if ((statCounter != null) && statCounter.IsLocked)
- {
- totalStatCounter.Merge(statCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalServerFailure));
- totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalNxDomain));
- totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalClients));
- }
- else
- {
- totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, 0));
- }
- }
- Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
- {
- List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(10);
- stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
- stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
- 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(10));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetLastDayHourWiseStats(bool utcFormat)
- {
- return GetHourWiseStats(DateTime.UtcNow.AddHours(-24), 24, utcFormat);
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetLastWeekDayWiseStats(bool utcFormat)
- {
- return GetDayWiseStats(DateTime.UtcNow.AddDays(-7).Date, 7, utcFormat);
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetLastMonthDayWiseStats(bool utcFormat)
- {
- return GetDayWiseStats(DateTime.UtcNow.AddDays(-31).Date, 31, utcFormat);
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetLastYearMonthWiseStats(bool utcFormat)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>();
- 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;
- if (utcFormat)
- label = lastMonthDateTime.ToString("O");
- else
- 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, true);
- }
- totalStatCounter.Merge(monthlyStatCounter, true);
- totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalServerFailure));
- totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalNxDomain));
- totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
- {
- List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(6);
- stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
- stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
- 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(10));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetHourWiseStats(DateTime startDate, DateTime endDate, bool utcFormat)
- {
- int hours = Convert.ToInt32((endDate - startDate).TotalHours) + 1;
- if (hours < 24)
- hours = 24;
- return GetHourWiseStats(startDate, hours, utcFormat);
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetHourWiseStats(DateTime startDate, int hours, bool utcFormat)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>();
- for (int hour = 0; hour < hours; hour++)
- {
- DateTime lastDateTime = startDate.AddHours(hour);
- string label;
- if (utcFormat)
- label = lastDateTime.AddHours(1).ToString("O");
- else
- label = lastDateTime.AddHours(1).ToLocalTime().ToString("MM/dd HH") + ":00";
- HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
- StatCounter hourlyStatCounter = hourlyStats.HourStat;
- totalStatCounter.Merge(hourlyStatCounter);
- totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalServerFailure));
- totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalNxDomain));
- totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
- {
- List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(6);
- stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
- stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
- 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(10));
- return data;
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetDayWiseStats(DateTime startDate, DateTime endDate, bool utcFormat)
- {
- return GetDayWiseStats(startDate, Convert.ToInt32((endDate - startDate).TotalDays) + 1, utcFormat);
- }
- public Dictionary<string, List<KeyValuePair<string, long>>> GetDayWiseStats(DateTime startDate, int days, bool utcFormat)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>();
- List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>();
- for (int day = 0; day < days; day++) //days
- {
- DateTime lastDayDateTime = startDate.AddDays(day);
- string label;
- if (utcFormat)
- label = lastDayDateTime.ToString("O");
- else
- label = lastDayDateTime.ToLocalTime().ToString("MM/dd");
- StatCounter dailyStatCounter = LoadDailyStats(lastDayDateTime);
- totalStatCounter.Merge(dailyStatCounter, true);
- totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalQueries));
- totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalNoError));
- totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalServerFailure));
- totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalNxDomain));
- totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalRefused));
- totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalAuthoritative));
- totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalRecursive));
- totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalCached));
- totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalBlocked));
- totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalClients));
- }
- Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
- {
- List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(6);
- stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
- stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
- stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
- stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
- stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
- stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
- stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
- stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
- stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
- stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
- data.Add("stats", stats);
- }
- data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
- data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
- data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
- data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
- 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(10));
- return data;
- }
- public List<KeyValuePair<string, long>> GetLastHourTopStats(TopStatsType type, int limit)
- {
- 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);
- }
- switch (type)
- {
- case TopStatsType.TopDomains:
- return totalStatCounter.GetTopDomains(limit);
- case TopStatsType.TopBlockedDomains:
- return totalStatCounter.GetTopBlockedDomains(limit);
- case TopStatsType.TopClients:
- return totalStatCounter.GetTopClients(limit);
- default:
- throw new NotSupportedException();
- }
- }
- public List<KeyValuePair<string, long>> GetLastDayTopStats(TopStatsType type, int limit)
- {
- return GetHourWiseTopStats(DateTime.UtcNow.AddHours(-24), 24, type, limit);
- }
- public List<KeyValuePair<string, long>> GetLastWeekTopStats(TopStatsType type, int limit)
- {
- return GetDayWiseTopStats(DateTime.UtcNow.AddDays(-7).Date, 7, type, limit);
- }
- public List<KeyValuePair<string, long>> GetLastMonthTopStats(TopStatsType type, int limit)
- {
- return GetDayWiseTopStats(DateTime.UtcNow.AddDays(-31).Date, 31, type, limit);
- }
- public List<KeyValuePair<string, long>> GetLastYearTopStats(TopStatsType type, int limit)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- 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);
- 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, true);
- }
- totalStatCounter.Merge(monthlyStatCounter, true);
- }
- switch (type)
- {
- case TopStatsType.TopDomains:
- return totalStatCounter.GetTopDomains(limit);
- case TopStatsType.TopBlockedDomains:
- return totalStatCounter.GetTopBlockedDomains(limit);
- case TopStatsType.TopClients:
- return totalStatCounter.GetTopClients(limit);
- default:
- throw new NotSupportedException();
- }
- }
- public List<KeyValuePair<string, long>> GetHourWiseTopStats(DateTime startDate, DateTime endDate, TopStatsType type, int limit)
- {
- int hours = Convert.ToInt32((endDate - startDate).TotalHours) + 1;
- if (hours < 24)
- hours = 24;
- return GetHourWiseTopStats(startDate, hours, type, limit);
- }
- public List<KeyValuePair<string, long>> GetHourWiseTopStats(DateTime startDate, int hours, TopStatsType type, int limit)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- for (int hour = 0; hour < hours; hour++)
- {
- DateTime lastDateTime = startDate.AddHours(hour);
- HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
- StatCounter hourlyStatCounter = hourlyStats.HourStat;
- totalStatCounter.Merge(hourlyStatCounter);
- }
- switch (type)
- {
- case TopStatsType.TopDomains:
- return totalStatCounter.GetTopDomains(limit);
- case TopStatsType.TopBlockedDomains:
- return totalStatCounter.GetTopBlockedDomains(limit);
- case TopStatsType.TopClients:
- return totalStatCounter.GetTopClients(limit);
- default:
- throw new NotSupportedException();
- }
- }
- public List<KeyValuePair<string, long>> GetDayWiseTopStats(DateTime startDate, DateTime endDate, TopStatsType type, int limit)
- {
- return GetDayWiseTopStats(startDate, Convert.ToInt32((endDate - startDate).TotalDays) + 1, type, limit);
- }
- public List<KeyValuePair<string, long>> GetDayWiseTopStats(DateTime startDate, int days, TopStatsType type, int limit)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- for (int day = 0; day < days; day++) //days
- {
- DateTime lastDayDateTime = startDate.AddDays(day);
- StatCounter dailyStatCounter = LoadDailyStats(lastDayDateTime);
- totalStatCounter.Merge(dailyStatCounter, true);
- }
- switch (type)
- {
- case TopStatsType.TopDomains:
- return totalStatCounter.GetTopDomains(limit);
- case TopStatsType.TopBlockedDomains:
- return totalStatCounter.GetTopBlockedDomains(limit);
- case TopStatsType.TopClients:
- return totalStatCounter.GetTopClients(limit);
- default:
- throw new NotSupportedException();
- }
- }
- public List<KeyValuePair<DnsQuestionRecord, long>> 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);
- }
- public void GetLatestClientSubnetStats(int minutes, int ipv4PrefixLength, int ipv6PrefixLength, out IReadOnlyDictionary<IPAddress, long> clientSubnetStats, out IReadOnlyDictionary<IPAddress, long> errorClientSubnetStats)
- {
- StatCounter totalStatCounter = new StatCounter();
- totalStatCounter.Lock();
- DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(1 - minutes);
- lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
- for (int minute = 0; minute < minutes; minute++)
- {
- DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
- StatCounter statCounter = _lastHourStatCounters[lastDateTime.Minute];
- if (statCounter is not null)
- totalStatCounter.Merge(statCounter, false, true);
- }
- clientSubnetStats = totalStatCounter.GetClientSubnetStats(ipv4PrefixLength, ipv6PrefixLength);
- errorClientSubnetStats = totalStatCounter.GetErrorClientSubnetStats(ipv4PrefixLength, ipv6PrefixLength);
- }
- #endregion
- #region properties
- public int MaxStatFileDays
- {
- get { return _maxStatFileDays; }
- set { _maxStatFileDays = value; }
- }
- #endregion
- class HourlyStats
- {
- #region variables
- readonly StatCounter _hourStat; //calculated value
- 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 UnloadMinuteStats()
- {
- _minuteStats = null;
- }
- 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;
- long _totalQueries;
- long _totalNoError;
- long _totalServerFailure;
- long _totalNxDomain;
- long _totalRefused;
- long _totalAuthoritative;
- long _totalRecursive;
- long _totalCached;
- long _totalBlocked;
- long _totalClients;
- readonly ConcurrentDictionary<string, Counter> _queryDomains;
- readonly ConcurrentDictionary<string, Counter> _queryBlockedDomains;
- readonly ConcurrentDictionary<DnsResourceRecordType, Counter> _queryTypes;
- readonly ConcurrentDictionary<IPAddress, Counter> _clientIpAddresses; //includes all queries
- readonly ConcurrentDictionary<IPAddress, Counter> _errorIpAddresses; //includes REFUSED, FORMERR and SERVFAIL
- readonly ConcurrentDictionary<DnsQuestionRecord, Counter> _queries;
- bool _truncationFoundDuringMerge;
- long _totalClientsDailyStatsSummation;
- #endregion
- #region constructor
- public StatCounter()
- {
- _queryDomains = new ConcurrentDictionary<string, Counter>();
- _queryBlockedDomains = new ConcurrentDictionary<string, Counter>();
- _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>();
- _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>();
- _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>();
- _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>();
- }
- 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:
- case 4:
- case 5:
- case 6:
- _totalQueries = bR.ReadInt32();
- _totalNoError = bR.ReadInt32();
- _totalServerFailure = bR.ReadInt32();
- _totalNxDomain = 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();
- }
- if (version >= 6)
- _totalClients = bR.ReadInt32();
- {
- int count = bR.ReadInt32();
- _queryDomains = new ConcurrentDictionary<string, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queryDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt32()));
- }
- {
- int count = bR.ReadInt32();
- _queryBlockedDomains = new ConcurrentDictionary<string, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queryBlockedDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt32()));
- }
- {
- int count = bR.ReadInt32();
- _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queryTypes.TryAdd((DnsResourceRecordType)bR.ReadUInt16(), new Counter(bR.ReadInt32()));
- }
- {
- int count = bR.ReadInt32();
- _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _clientIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt32()));
- if (version < 6)
- _totalClients = count;
- }
- if (version >= 4)
- {
- int count = bR.ReadInt32();
- _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queries.TryAdd(new DnsQuestionRecord(bR.BaseStream), new Counter(bR.ReadInt32()));
- }
- else
- {
- _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>(1, 0);
- }
- if (version >= 5)
- {
- int count = bR.ReadInt32();
- _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _errorIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt32()));
- }
- else
- {
- _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, 0);
- }
- break;
- case 7:
- _totalQueries = bR.ReadInt64();
- _totalNoError = bR.ReadInt64();
- _totalServerFailure = bR.ReadInt64();
- _totalNxDomain = bR.ReadInt64();
- _totalRefused = bR.ReadInt64();
- _totalAuthoritative = bR.ReadInt64();
- _totalRecursive = bR.ReadInt64();
- _totalCached = bR.ReadInt64();
- _totalBlocked = bR.ReadInt64();
- _totalClients = bR.ReadInt64();
- {
- int count = bR.ReadInt32();
- _queryDomains = new ConcurrentDictionary<string, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queryDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt64()));
- }
- {
- int count = bR.ReadInt32();
- _queryBlockedDomains = new ConcurrentDictionary<string, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queryBlockedDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt64()));
- }
- {
- int count = bR.ReadInt32();
- _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queryTypes.TryAdd((DnsResourceRecordType)bR.ReadUInt16(), new Counter(bR.ReadInt64()));
- }
- {
- int count = bR.ReadInt32();
- _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _clientIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt64()));
- }
- {
- int count = bR.ReadInt32();
- _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _queries.TryAdd(new DnsQuestionRecord(bR.BaseStream), new Counter(bR.ReadInt64()));
- }
- {
- int count = bR.ReadInt32();
- _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
- for (int i = 0; i < count; i++)
- _errorIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt64()));
- }
- break;
- default:
- throw new InvalidDataException("StatCounter version not supported.");
- }
- _locked = true;
- }
- #endregion
- #region private
- private static List<KeyValuePair<string, long>> GetTopList(List<KeyValuePair<string, long>> list, int limit)
- {
- list.Sort(delegate (KeyValuePair<string, long> item1, KeyValuePair<string, long> 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, DnsResponseCode responseCode, DnsServerResponseType responseType, IPAddress clientIpAddress)
- {
- if (_locked)
- return;
- if (clientIpAddress.IsIPv4MappedToIPv6)
- clientIpAddress = clientIpAddress.MapToIPv4();
- Interlocked.Increment(ref _totalQueries);
- switch (responseCode)
- {
- case DnsResponseCode.NoError:
- if (query is not null)
- {
- switch (responseType)
- {
- case DnsServerResponseType.Blocked:
- case DnsServerResponseType.UpstreamBlocked:
- case DnsServerResponseType.CacheBlocked:
- //skip blocked domains
- break;
- default:
- _queryDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
- _queries.GetOrAdd(query, GetNewCounter).Increment();
- break;
- }
- }
- Interlocked.Increment(ref _totalNoError);
- break;
- case DnsResponseCode.ServerFailure:
- _errorIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
- Interlocked.Increment(ref _totalServerFailure);
- break;
- case DnsResponseCode.NxDomain:
- Interlocked.Increment(ref _totalNxDomain);
- break;
- case DnsResponseCode.Refused:
- _errorIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
- Interlocked.Increment(ref _totalRefused);
- break;
- case DnsResponseCode.FormatError:
- _errorIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
- break;
- }
- switch (responseType)
- {
- case DnsServerResponseType.Authoritative:
- Interlocked.Increment(ref _totalAuthoritative);
- break;
- case DnsServerResponseType.Recursive:
- Interlocked.Increment(ref _totalRecursive);
- break;
- case DnsServerResponseType.Cached:
- Interlocked.Increment(ref _totalCached);
- break;
- case DnsServerResponseType.Blocked:
- if (query is not null)
- _queryBlockedDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
- Interlocked.Increment(ref _totalBlocked);
- break;
- case DnsServerResponseType.UpstreamBlocked:
- Interlocked.Increment(ref _totalRecursive);
- if (query is not null)
- _queryBlockedDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
- Interlocked.Increment(ref _totalBlocked);
- break;
- case DnsServerResponseType.CacheBlocked:
- Interlocked.Increment(ref _totalCached);
- if (query is not null)
- _queryBlockedDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
- Interlocked.Increment(ref _totalBlocked);
- break;
- }
- if (query is not null)
- _queryTypes.GetOrAdd(query.Type, GetNewCounter).Increment();
- _clientIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
- _totalClients = _clientIpAddresses.Count;
- }
- public void Merge(StatCounter statCounter, bool isDailyStatCounter = false, bool skipLock = false)
- {
- if (!skipLock && (!_locked || !statCounter._locked))
- throw new DnsServerException("StatCounter must be locked.");
- _totalQueries += statCounter._totalQueries;
- _totalNoError += statCounter._totalNoError;
- _totalServerFailure += statCounter._totalServerFailure;
- _totalNxDomain += statCounter._totalNxDomain;
- _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<IPAddress, Counter> refusedIpAddress in statCounter._errorIpAddresses)
- _errorIpAddresses.GetOrAdd(refusedIpAddress.Key, GetNewCounter).Merge(refusedIpAddress.Value);
- foreach (KeyValuePair<DnsQuestionRecord, Counter> query in statCounter._queries)
- _queries.GetOrAdd(query.Key, GetNewCounter).Merge(query.Value);
- _totalClients = _clientIpAddresses.Count;
- _totalClientsDailyStatsSummation += statCounter._totalClients;
- if (isDailyStatCounter && (statCounter._totalClients > statCounter._clientIpAddresses.Count))
- _truncationFoundDuringMerge = true;
- }
- public bool Truncate(int limit)
- {
- bool truncated = false;
- if (_queryDomains.Count > limit)
- {
- List<KeyValuePair<string, Counter>> topDomains = new List<KeyValuePair<string, Counter>>(_queryDomains);
- _queryDomains.Clear();
- topDomains.Sort(delegate (KeyValuePair<string, Counter> item1, KeyValuePair<string, Counter> item2)
- {
- return item2.Value.Count.CompareTo(item1.Value.Count);
- });
- if (topDomains.Count > limit)
- topDomains.RemoveRange(limit, topDomains.Count - limit);
- foreach (KeyValuePair<string, Counter> item in topDomains)
- _queryDomains[item.Key] = item.Value;
- truncated = true;
- }
- if (_queryBlockedDomains.Count > limit)
- {
- List<KeyValuePair<string, Counter>> topBlockedDomains = new List<KeyValuePair<string, Counter>>(_queryBlockedDomains);
- _queryBlockedDomains.Clear();
- topBlockedDomains.Sort(delegate (KeyValuePair<string, Counter> item1, KeyValuePair<string, Counter> item2)
- {
- return item2.Value.Count.CompareTo(item1.Value.Count);
- });
- if (topBlockedDomains.Count > limit)
- topBlockedDomains.RemoveRange(limit, topBlockedDomains.Count - limit);
- foreach (KeyValuePair<string, Counter> item in topBlockedDomains)
- _queryBlockedDomains[item.Key] = item.Value;
- truncated = true;
- }
- if (_queryTypes.Count > limit)
- {
- List<KeyValuePair<DnsResourceRecordType, Counter>> queryTypes = new List<KeyValuePair<DnsResourceRecordType, Counter>>(_queryTypes);
- _queryTypes.Clear();
- queryTypes.Sort(delegate (KeyValuePair<DnsResourceRecordType, Counter> item1, KeyValuePair<DnsResourceRecordType, Counter> item2)
- {
- return item2.Value.Count.CompareTo(item1.Value.Count);
- });
- if (queryTypes.Count > limit)
- {
- long othersCount = 0;
- for (int i = limit; i < queryTypes.Count; i++)
- othersCount += queryTypes[i].Value.Count;
- queryTypes.RemoveRange(limit - 1, queryTypes.Count - (limit - 1));
- queryTypes.Add(new KeyValuePair<DnsResourceRecordType, Counter>(DnsResourceRecordType.Unknown, new Counter(othersCount)));
- }
- foreach (KeyValuePair<DnsResourceRecordType, Counter> item in queryTypes)
- _queryTypes[item.Key] = item.Value;
- truncated = true;
- }
- if (_clientIpAddresses.Count > limit)
- {
- List<KeyValuePair<IPAddress, Counter>> topClients = new List<KeyValuePair<IPAddress, Counter>>(_clientIpAddresses);
- _clientIpAddresses.Clear();
- topClients.Sort(delegate (KeyValuePair<IPAddress, Counter> item1, KeyValuePair<IPAddress, Counter> item2)
- {
- return item2.Value.Count.CompareTo(item1.Value.Count);
- });
- if (topClients.Count > limit)
- topClients.RemoveRange(limit, topClients.Count - limit);
- foreach (KeyValuePair<IPAddress, Counter> item in topClients)
- _clientIpAddresses[item.Key] = item.Value;
- truncated = true;
- }
- if (_errorIpAddresses.Count > limit)
- {
- List<KeyValuePair<IPAddress, Counter>> topErrorClients = new List<KeyValuePair<IPAddress, Counter>>(_errorIpAddresses);
- _errorIpAddresses.Clear();
- topErrorClients.Sort(delegate (KeyValuePair<IPAddress, Counter> item1, KeyValuePair<IPAddress, Counter> item2)
- {
- return item2.Value.Count.CompareTo(item1.Value.Count);
- });
- if (topErrorClients.Count > limit)
- topErrorClients.RemoveRange(limit, topErrorClients.Count - limit);
- foreach (KeyValuePair<IPAddress, Counter> item in topErrorClients)
- _errorIpAddresses[item.Key] = item.Value;
- truncated = true;
- }
- if (_queries.Count > limit)
- {
- //only last hour queries data is required for cache auto prefetching
- _queries.Clear();
- truncated = true;
- }
- return truncated;
- }
- public void WriteTo(BinaryWriter bW)
- {
- if (!_locked)
- throw new DnsServerException("StatCounter must be locked.");
- bW.Write(Encoding.ASCII.GetBytes("SC")); //format
- bW.Write((byte)7); //version
- bW.Write(_totalQueries);
- bW.Write(_totalNoError);
- bW.Write(_totalServerFailure);
- bW.Write(_totalNxDomain);
- bW.Write(_totalRefused);
- bW.Write(_totalAuthoritative);
- bW.Write(_totalRecursive);
- bW.Write(_totalCached);
- bW.Write(_totalBlocked);
- bW.Write(_totalClients);
- {
- 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);
- }
- }
- {
- bW.Write(_queries.Count);
- foreach (KeyValuePair<DnsQuestionRecord, Counter> query in _queries)
- {
- query.Key.WriteTo(bW.BaseStream, null);
- bW.Write(query.Value.Count);
- }
- }
- {
- bW.Write(_errorIpAddresses.Count);
- foreach (KeyValuePair<IPAddress, Counter> refusedIpAddress in _errorIpAddresses)
- {
- refusedIpAddress.Key.WriteTo(bW);
- bW.Write(refusedIpAddress.Value.Count);
- }
- }
- }
- public List<KeyValuePair<string, long>> GetTopDomains(int limit)
- {
- List<KeyValuePair<string, long>> topDomains = new List<KeyValuePair<string, long>>(_queryDomains.Count);
- foreach (KeyValuePair<string, Counter> item in _queryDomains)
- topDomains.Add(new KeyValuePair<string, long>(item.Key, item.Value.Count));
- return GetTopList(topDomains, limit);
- }
- public List<KeyValuePair<string, long>> GetTopBlockedDomains(int limit)
- {
- List<KeyValuePair<string, long>> topBlockedDomains = new List<KeyValuePair<string, long>>(_queryBlockedDomains.Count);
- foreach (KeyValuePair<string, Counter> item in _queryBlockedDomains)
- topBlockedDomains.Add(new KeyValuePair<string, long>(item.Key, item.Value.Count));
- return GetTopList(topBlockedDomains, limit);
- }
- public List<KeyValuePair<string, long>> GetTopClients(int limit)
- {
- List<KeyValuePair<string, long>> topClients = new List<KeyValuePair<string, long>>(_clientIpAddresses.Count);
- foreach (KeyValuePair<IPAddress, Counter> item in _clientIpAddresses)
- topClients.Add(new KeyValuePair<string, long>(item.Key.ToString(), item.Value.Count));
- return GetTopList(topClients, limit);
- }
- public List<KeyValuePair<string, long>> GetTopQueryTypes(int limit)
- {
- List<KeyValuePair<string, long>> queryTypes = new List<KeyValuePair<string, long>>(_queryTypes.Count);
- foreach (KeyValuePair<DnsResourceRecordType, Counter> item in _queryTypes)
- queryTypes.Add(new KeyValuePair<string, long>(item.Key.ToString(), item.Value.Count));
- queryTypes.Sort(delegate (KeyValuePair<string, long> item1, KeyValuePair<string, long> item2)
- {
- return item2.Value.CompareTo(item1.Value);
- });
- if (queryTypes.Count > limit)
- {
- long 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, long>("Others", othersCount));
- }
- return queryTypes;
- }
- public List<KeyValuePair<DnsQuestionRecord, long>> GetEligibleQueries(int minimumHits)
- {
- List<KeyValuePair<DnsQuestionRecord, long>> eligibleQueries = new List<KeyValuePair<DnsQuestionRecord, long>>(Convert.ToInt32(_queries.Count * 0.1));
- foreach (KeyValuePair<DnsQuestionRecord, Counter> item in _queries)
- {
- if (item.Value.Count >= minimumHits)
- eligibleQueries.Add(new KeyValuePair<DnsQuestionRecord, long>(item.Key, item.Value.Count));
- }
- return eligibleQueries;
- }
- public IReadOnlyDictionary<IPAddress, long> GetClientSubnetStats(int ipv4PrefixLength, int ipv6PrefixLength)
- {
- Dictionary<IPAddress, long> clientSubnetStats = new Dictionary<IPAddress, long>(_clientIpAddresses.Count);
- foreach (KeyValuePair<IPAddress, Counter> item in _clientIpAddresses)
- {
- IPAddress clientSubnet;
- switch (item.Key.AddressFamily)
- {
- case AddressFamily.InterNetwork:
- clientSubnet = item.Key.GetNetworkAddress(ipv4PrefixLength);
- break;
- case AddressFamily.InterNetworkV6:
- clientSubnet = item.Key.GetNetworkAddress(ipv6PrefixLength);
- break;
- default:
- throw new NotSupportedException("AddressFamily not supported.");
- }
- if (clientSubnetStats.TryGetValue(clientSubnet, out long existingValue))
- clientSubnetStats[clientSubnet] = existingValue + item.Value.Count;
- else
- clientSubnetStats.Add(clientSubnet, item.Value.Count);
- }
- return clientSubnetStats;
- }
- public IReadOnlyDictionary<IPAddress, long> GetErrorClientSubnetStats(int ipv4PrefixLength, int ipv6PrefixLength)
- {
- Dictionary<IPAddress, long> errorClientSubnetStats = new Dictionary<IPAddress, long>(_errorIpAddresses.Count);
- foreach (KeyValuePair<IPAddress, Counter> item in _errorIpAddresses)
- {
- IPAddress clientSubnet;
- switch (item.Key.AddressFamily)
- {
- case AddressFamily.InterNetwork:
- clientSubnet = item.Key.GetNetworkAddress(ipv4PrefixLength);
- break;
- case AddressFamily.InterNetworkV6:
- clientSubnet = item.Key.GetNetworkAddress(ipv6PrefixLength);
- break;
- default:
- throw new NotSupportedException("AddressFamily not supported.");
- }
- if (errorClientSubnetStats.TryGetValue(clientSubnet, out long existingValue))
- errorClientSubnetStats[clientSubnet] = existingValue + item.Value.Count;
- else
- errorClientSubnetStats.Add(clientSubnet, item.Value.Count);
- }
- return errorClientSubnetStats;
- }
- #endregion
- #region properties
- public bool IsLocked
- { get { return _locked; } }
- public long TotalQueries
- { get { return _totalQueries; } }
- public long TotalNoError
- { get { return _totalNoError; } }
- public long TotalServerFailure
- { get { return _totalServerFailure; } }
- public long TotalNxDomain
- { get { return _totalNxDomain; } }
- public long TotalRefused
- { get { return _totalRefused; } }
- public long TotalAuthoritative
- { get { return _totalAuthoritative; } }
- public long TotalRecursive
- { get { return _totalRecursive; } }
- public long TotalCached
- { get { return _totalCached; } }
- public long TotalBlocked
- { get { return _totalBlocked; } }
- public long TotalClients
- {
- get
- {
- if (_truncationFoundDuringMerge)
- return _totalClientsDailyStatsSummation;
- return _totalClients;
- }
- }
- #endregion
- class Counter
- {
- #region variables
- long _count;
- #endregion
- #region constructor
- public Counter()
- { }
- public Counter(long 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 long Count
- { get { return _count; } }
- #endregion
- }
- }
- class StatsQueueItem
- {
- #region variables
- public readonly DateTime _timestamp;
- public readonly DnsDatagram _request;
- public readonly IPEndPoint _remoteEP;
- public readonly DnsTransportProtocol _protocol;
- public readonly DnsDatagram _response;
- #endregion
- #region constructor
- public StatsQueueItem(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
- {
- _timestamp = DateTime.UtcNow;
- _request = request;
- _remoteEP = remoteEP;
- _protocol = protocol;
- _response = response;
- }
- #endregion
- }
- }
- }
|