StatsManager.cs 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  1. /*
  2. Technitium DNS Server
  3. Copyright (C) 2023 Shreyas Zare (shreyas@technitium.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. using DnsServerCore.ApplicationCommon;
  16. using System;
  17. using System.Collections.Concurrent;
  18. using System.Collections.Generic;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using System.Text;
  24. using System.Threading;
  25. using TechnitiumLibrary.IO;
  26. using TechnitiumLibrary.Net;
  27. using TechnitiumLibrary.Net.Dns;
  28. using TechnitiumLibrary.Net.Dns.ResourceRecords;
  29. namespace DnsServerCore.Dns
  30. {
  31. public enum TopStatsType
  32. {
  33. Unknown = 0,
  34. TopClients = 1,
  35. TopDomains = 2,
  36. TopBlockedDomains = 3
  37. }
  38. public sealed class StatsManager : IDisposable
  39. {
  40. #region variables
  41. const int DAILY_STATS_FILE_TOP_LIMIT = 1000;
  42. readonly DnsServer _dnsServer;
  43. readonly string _statsFolder;
  44. readonly StatCounter[] _lastHourStatCounters = new StatCounter[60];
  45. readonly StatCounter[] _lastHourStatCountersCopy = new StatCounter[60];
  46. readonly ConcurrentDictionary<DateTime, HourlyStats> _hourlyStatsCache = new ConcurrentDictionary<DateTime, HourlyStats>();
  47. readonly ConcurrentDictionary<DateTime, StatCounter> _dailyStatsCache = new ConcurrentDictionary<DateTime, StatCounter>();
  48. readonly Timer _maintenanceTimer;
  49. const int MAINTENANCE_TIMER_INITIAL_INTERVAL = 10000;
  50. const int MAINTENANCE_TIMER_PERIODIC_INTERVAL = 10000;
  51. readonly BlockingCollection<StatsQueueItem> _queue = new BlockingCollection<StatsQueueItem>();
  52. readonly Thread _consumerThread;
  53. readonly Timer _statsCleanupTimer;
  54. int _maxStatFileDays = 0;
  55. const int STATS_CLEANUP_TIMER_INITIAL_INTERVAL = 60 * 1000;
  56. const int STATS_CLEANUP_TIMER_PERIODIC_INTERVAL = 60 * 60 * 1000;
  57. #endregion
  58. #region constructor
  59. public StatsManager(DnsServer dnsServer)
  60. {
  61. _dnsServer = dnsServer;
  62. _statsFolder = Path.Combine(dnsServer.ConfigFolder, "stats");
  63. if (!Directory.Exists(_statsFolder))
  64. Directory.CreateDirectory(_statsFolder);
  65. //load stats
  66. LoadLastHourStats();
  67. try
  68. {
  69. //do first maintenance
  70. DoMaintenance();
  71. }
  72. catch (Exception ex)
  73. {
  74. _dnsServer.LogManager?.Write(ex);
  75. }
  76. //start periodic maintenance timer
  77. _maintenanceTimer = new Timer(delegate (object state)
  78. {
  79. try
  80. {
  81. DoMaintenance();
  82. }
  83. catch (Exception ex)
  84. {
  85. _dnsServer.LogManager?.Write(ex);
  86. }
  87. }, null, MAINTENANCE_TIMER_INITIAL_INTERVAL, MAINTENANCE_TIMER_PERIODIC_INTERVAL);
  88. //stats consumer thread
  89. _consumerThread = new Thread(delegate ()
  90. {
  91. try
  92. {
  93. foreach (StatsQueueItem item in _queue.GetConsumingEnumerable())
  94. {
  95. StatCounter statCounter = _lastHourStatCounters[item._timestamp.Minute];
  96. if (statCounter is not null)
  97. {
  98. DnsQuestionRecord query;
  99. if (item._request.Question.Count > 0)
  100. query = item._request.Question[0];
  101. else
  102. query = null;
  103. DnsServerResponseType responseType;
  104. if (item._response.Tag is null)
  105. responseType = DnsServerResponseType.Recursive;
  106. else
  107. responseType = (DnsServerResponseType)item._response.Tag;
  108. statCounter.Update(query, item._response.RCODE, responseType, item._remoteEP.Address);
  109. }
  110. foreach (IDnsQueryLogger logger in _dnsServer.DnsApplicationManager.DnsQueryLoggers)
  111. {
  112. try
  113. {
  114. _ = logger.InsertLogAsync(item._timestamp, item._request, item._remoteEP, item._protocol, item._response);
  115. }
  116. catch (Exception ex)
  117. {
  118. LogManager log = dnsServer.LogManager;
  119. if (log is not null)
  120. log.Write(ex);
  121. }
  122. }
  123. }
  124. }
  125. catch (Exception ex)
  126. {
  127. _dnsServer.LogManager?.Write(ex);
  128. }
  129. });
  130. _consumerThread.Name = "Stats";
  131. _consumerThread.IsBackground = true;
  132. _consumerThread.Start();
  133. _statsCleanupTimer = new Timer(delegate (object state)
  134. {
  135. try
  136. {
  137. if (_maxStatFileDays < 1)
  138. return;
  139. DateTime cutoffDate = DateTime.UtcNow.AddDays(_maxStatFileDays * -1).Date;
  140. LogManager log = dnsServer.LogManager;
  141. //delete hourly logs
  142. {
  143. string[] hourlyStatsFiles = Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.stat");
  144. foreach (string hourlyStatsFile in hourlyStatsFiles)
  145. {
  146. string hourlyStatsFileName = Path.GetFileNameWithoutExtension(hourlyStatsFile);
  147. if (!DateTime.TryParseExact(hourlyStatsFileName, "yyyyMMddHH", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime hourlyStatsFileDate))
  148. continue;
  149. if (hourlyStatsFileDate < cutoffDate)
  150. {
  151. try
  152. {
  153. File.Delete(hourlyStatsFile);
  154. if (log != null)
  155. log.Write("StatsManager cleanup deleted the hourly stats file: " + hourlyStatsFile);
  156. }
  157. catch (Exception ex)
  158. {
  159. if (log != null)
  160. log.Write(ex);
  161. }
  162. }
  163. }
  164. }
  165. //delete daily logs
  166. {
  167. string[] dailyStatsFiles = Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.dstat");
  168. foreach (string dailyStatsFile in dailyStatsFiles)
  169. {
  170. string dailyStatsFileName = Path.GetFileNameWithoutExtension(dailyStatsFile);
  171. if (!DateTime.TryParseExact(dailyStatsFileName, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime dailyStatsFileDate))
  172. continue;
  173. if (dailyStatsFileDate < cutoffDate)
  174. {
  175. try
  176. {
  177. File.Delete(dailyStatsFile);
  178. if (log != null)
  179. log.Write("StatsManager cleanup deleted the daily stats file: " + dailyStatsFile);
  180. }
  181. catch (Exception ex)
  182. {
  183. if (log != null)
  184. log.Write(ex);
  185. }
  186. }
  187. }
  188. }
  189. }
  190. catch (Exception ex)
  191. {
  192. _dnsServer.LogManager?.Write(ex);
  193. }
  194. });
  195. _statsCleanupTimer.Change(STATS_CLEANUP_TIMER_INITIAL_INTERVAL, STATS_CLEANUP_TIMER_PERIODIC_INTERVAL);
  196. }
  197. #endregion
  198. #region IDisposable
  199. bool _disposed;
  200. readonly object _disposeLock = new object();
  201. private void Dispose(bool disposing)
  202. {
  203. lock (_disposeLock)
  204. {
  205. if (_disposed)
  206. return;
  207. if (disposing)
  208. {
  209. if (_maintenanceTimer != null)
  210. _maintenanceTimer.Dispose();
  211. //do last maintenance
  212. DoMaintenance();
  213. }
  214. _disposed = true;
  215. }
  216. }
  217. public void Dispose()
  218. {
  219. Dispose(true);
  220. }
  221. #endregion
  222. #region private
  223. private void LoadLastHourStats()
  224. {
  225. try
  226. {
  227. DateTime currentDateTime = DateTime.UtcNow;
  228. DateTime lastHourDateTime = currentDateTime.AddMinutes(-60);
  229. HourlyStats lastHourlyStats = null;
  230. DateTime lastHourlyStatsDateTime = new DateTime();
  231. for (int i = 0; i < 60; i++)
  232. {
  233. DateTime lastDateTime = lastHourDateTime.AddMinutes(i);
  234. if ((lastHourlyStats == null) || (lastDateTime.Hour != lastHourlyStatsDateTime.Hour))
  235. {
  236. lastHourlyStats = LoadHourlyStats(lastDateTime);
  237. lastHourlyStatsDateTime = lastDateTime;
  238. }
  239. _lastHourStatCounters[lastDateTime.Minute] = lastHourlyStats.MinuteStats[lastDateTime.Minute];
  240. _lastHourStatCountersCopy[lastDateTime.Minute] = _lastHourStatCounters[lastDateTime.Minute];
  241. }
  242. }
  243. catch (Exception ex)
  244. {
  245. _dnsServer.LogManager?.Write(ex);
  246. }
  247. }
  248. private void DoMaintenance()
  249. {
  250. //load new stats counter 5 min ahead of current time
  251. DateTime currentDateTime = DateTime.UtcNow;
  252. for (int i = 0; i < 5; i++)
  253. {
  254. int minute = currentDateTime.AddMinutes(i).Minute;
  255. StatCounter statCounter = _lastHourStatCounters[minute];
  256. if ((statCounter == null) || statCounter.IsLocked)
  257. _lastHourStatCounters[minute] = new StatCounter();
  258. }
  259. //save data upto last 5 mins
  260. DateTime last5MinDateTime = currentDateTime.AddMinutes(-5);
  261. for (int i = 0; i < 5; i++)
  262. {
  263. DateTime lastDateTime = last5MinDateTime.AddMinutes(i);
  264. StatCounter lastStatCounter = _lastHourStatCounters[lastDateTime.Minute];
  265. if ((lastStatCounter != null) && !lastStatCounter.IsLocked)
  266. {
  267. //load hourly stats data
  268. HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
  269. //update hourly stats file
  270. lastStatCounter.Lock();
  271. hourlyStats.UpdateStat(lastDateTime, lastStatCounter);
  272. //save hourly stats
  273. SaveHourlyStats(lastDateTime, hourlyStats);
  274. //keep copy for api
  275. _lastHourStatCountersCopy[lastDateTime.Minute] = lastStatCounter;
  276. }
  277. }
  278. //load previous day stats to auto create daily stats file
  279. LoadDailyStats(currentDateTime.AddDays(-1));
  280. //remove old data from hourly stats cache
  281. {
  282. DateTime threshold = DateTime.UtcNow.AddHours(-24);
  283. threshold = new DateTime(threshold.Year, threshold.Month, threshold.Day, threshold.Hour, 0, 0, DateTimeKind.Utc);
  284. List<DateTime> _keysToRemove = new List<DateTime>();
  285. foreach (KeyValuePair<DateTime, HourlyStats> item in _hourlyStatsCache)
  286. {
  287. if (item.Key < threshold)
  288. _keysToRemove.Add(item.Key);
  289. }
  290. foreach (DateTime key in _keysToRemove)
  291. _hourlyStatsCache.TryRemove(key, out _);
  292. }
  293. //unload minute stats data from hourly stats cache for data older than last hour
  294. {
  295. DateTime lastHourThreshold = DateTime.UtcNow.AddHours(-1);
  296. lastHourThreshold = new DateTime(lastHourThreshold.Year, lastHourThreshold.Month, lastHourThreshold.Day, lastHourThreshold.Hour, 0, 0, DateTimeKind.Utc);
  297. foreach (KeyValuePair<DateTime, HourlyStats> item in _hourlyStatsCache)
  298. {
  299. if (item.Key < lastHourThreshold)
  300. item.Value.UnloadMinuteStats();
  301. }
  302. }
  303. //remove old data from daily stats cache
  304. {
  305. DateTime threshold = DateTime.UtcNow.AddMonths(-12);
  306. threshold = new DateTime(threshold.Year, threshold.Month, 1, 0, 0, 0, DateTimeKind.Utc);
  307. List<DateTime> _keysToRemove = new List<DateTime>();
  308. foreach (KeyValuePair<DateTime, StatCounter> item in _dailyStatsCache)
  309. {
  310. if (item.Key < threshold)
  311. _keysToRemove.Add(item.Key);
  312. }
  313. foreach (DateTime key in _keysToRemove)
  314. _dailyStatsCache.TryRemove(key, out _);
  315. }
  316. }
  317. private HourlyStats LoadHourlyStats(DateTime dateTime)
  318. {
  319. DateTime hourlyDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, 0, DateTimeKind.Utc);
  320. if (!_hourlyStatsCache.TryGetValue(hourlyDateTime, out HourlyStats hourlyStats))
  321. {
  322. string hourlyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMddHH") + ".stat");
  323. if (File.Exists(hourlyStatsFile))
  324. {
  325. try
  326. {
  327. using (FileStream fS = new FileStream(hourlyStatsFile, FileMode.Open, FileAccess.Read))
  328. {
  329. hourlyStats = new HourlyStats(new BinaryReader(fS));
  330. }
  331. }
  332. catch (Exception ex)
  333. {
  334. LogManager log = _dnsServer.LogManager;
  335. if (log != null)
  336. log.Write(ex);
  337. hourlyStats = new HourlyStats();
  338. }
  339. }
  340. else
  341. {
  342. hourlyStats = new HourlyStats();
  343. }
  344. if (!_hourlyStatsCache.TryAdd(hourlyDateTime, hourlyStats))
  345. {
  346. if (!_hourlyStatsCache.TryGetValue(hourlyDateTime, out hourlyStats))
  347. throw new DnsServerException("Unable to load hourly stats.");
  348. }
  349. }
  350. return hourlyStats;
  351. }
  352. private StatCounter LoadDailyStats(DateTime dateTime)
  353. {
  354. DateTime dailyDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, 0, DateTimeKind.Utc);
  355. if (!_dailyStatsCache.TryGetValue(dailyDateTime, out StatCounter dailyStats))
  356. {
  357. string dailyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMdd") + ".dstat");
  358. if (File.Exists(dailyStatsFile))
  359. {
  360. try
  361. {
  362. using (FileStream fS = new FileStream(dailyStatsFile, FileMode.Open, FileAccess.Read))
  363. {
  364. dailyStats = new StatCounter(new BinaryReader(fS));
  365. }
  366. //check if existing file could be truncated to avoid loading unnecessary data in memory
  367. if (dailyStats.Truncate(DAILY_STATS_FILE_TOP_LIMIT))
  368. SaveDailyStats(dailyDateTime, dailyStats); //save truncated file
  369. }
  370. catch (Exception ex)
  371. {
  372. LogManager log = _dnsServer.LogManager;
  373. if (log != null)
  374. log.Write(ex);
  375. }
  376. }
  377. if (dailyStats == null)
  378. {
  379. dailyStats = new StatCounter();
  380. dailyStats.Lock();
  381. for (int hour = 0; hour < 24; hour++) //hours
  382. {
  383. HourlyStats hourlyStats = LoadHourlyStats(dailyDateTime.AddHours(hour));
  384. dailyStats.Merge(hourlyStats.HourStat);
  385. }
  386. if (dailyStats.TotalQueries > 0)
  387. {
  388. _ = dailyStats.Truncate(DAILY_STATS_FILE_TOP_LIMIT);
  389. SaveDailyStats(dailyDateTime, dailyStats);
  390. }
  391. }
  392. if (!_dailyStatsCache.TryAdd(dailyDateTime, dailyStats))
  393. {
  394. if (!_dailyStatsCache.TryGetValue(dailyDateTime, out dailyStats))
  395. throw new DnsServerException("Unable to load daily stats.");
  396. }
  397. }
  398. return dailyStats;
  399. }
  400. private void SaveHourlyStats(DateTime dateTime, HourlyStats hourlyStats)
  401. {
  402. string hourlyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMddHH") + ".stat");
  403. try
  404. {
  405. using (FileStream fS = new FileStream(hourlyStatsFile, FileMode.Create, FileAccess.Write))
  406. {
  407. hourlyStats.WriteTo(new BinaryWriter(fS));
  408. }
  409. }
  410. catch (Exception ex)
  411. {
  412. LogManager log = _dnsServer.LogManager;
  413. if (log != null)
  414. log.Write(ex);
  415. }
  416. }
  417. private void SaveDailyStats(DateTime dateTime, StatCounter dailyStats)
  418. {
  419. string dailyStatsFile = Path.Combine(_statsFolder, dateTime.ToString("yyyyMMdd") + ".dstat");
  420. try
  421. {
  422. using (FileStream fS = new FileStream(dailyStatsFile, FileMode.Create, FileAccess.Write))
  423. {
  424. dailyStats.WriteTo(new BinaryWriter(fS));
  425. }
  426. }
  427. catch (Exception ex)
  428. {
  429. LogManager log = _dnsServer.LogManager;
  430. if (log != null)
  431. log.Write(ex);
  432. }
  433. }
  434. private void Flush()
  435. {
  436. //clear in memory stats
  437. for (int i = 0; i < _lastHourStatCountersCopy.Length; i++)
  438. _lastHourStatCountersCopy[i] = null;
  439. _hourlyStatsCache.Clear();
  440. _dailyStatsCache.Clear();
  441. }
  442. #endregion
  443. #region public
  444. public void ReloadStats()
  445. {
  446. Flush();
  447. LoadLastHourStats();
  448. }
  449. public void DeleteAllStats()
  450. {
  451. foreach (string hourlyStatsFile in Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.stat", SearchOption.TopDirectoryOnly))
  452. {
  453. File.Delete(hourlyStatsFile);
  454. }
  455. foreach (string dailyStatsFile in Directory.GetFiles(Path.Combine(_dnsServer.ConfigFolder, "stats"), "*.dstat", SearchOption.TopDirectoryOnly))
  456. {
  457. File.Delete(dailyStatsFile);
  458. }
  459. Flush();
  460. }
  461. public void QueueUpdate(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  462. {
  463. _queue.Add(new StatsQueueItem(request, remoteEP, protocol, response));
  464. }
  465. public Dictionary<string, List<KeyValuePair<string, long>>> GetLastHourMinuteWiseStats(bool utcFormat)
  466. {
  467. StatCounter totalStatCounter = new StatCounter();
  468. totalStatCounter.Lock();
  469. List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>(60);
  470. List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>(60);
  471. List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>(60);
  472. List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>(60);
  473. List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>(60);
  474. List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>(60);
  475. List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>(60);
  476. List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>(60);
  477. List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>(60);
  478. List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>(60);
  479. DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(-60);
  480. lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
  481. for (int minute = 0; minute < 60; minute++)
  482. {
  483. DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
  484. string label;
  485. if (utcFormat)
  486. label = lastDateTime.AddMinutes(1).ToString("O");
  487. else
  488. label = lastDateTime.AddMinutes(1).ToLocalTime().ToString("HH:mm");
  489. StatCounter statCounter = _lastHourStatCountersCopy[lastDateTime.Minute];
  490. if ((statCounter != null) && statCounter.IsLocked)
  491. {
  492. totalStatCounter.Merge(statCounter);
  493. totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalQueries));
  494. totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalNoError));
  495. totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalServerFailure));
  496. totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalNxDomain));
  497. totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalRefused));
  498. totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalAuthoritative));
  499. totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalRecursive));
  500. totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalCached));
  501. totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalBlocked));
  502. totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, statCounter.TotalClients));
  503. }
  504. else
  505. {
  506. totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  507. totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  508. totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, 0));
  509. totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  510. totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  511. totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  512. totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  513. totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  514. totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  515. totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, 0));
  516. }
  517. }
  518. Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
  519. {
  520. List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(10);
  521. stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
  522. stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
  523. stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
  524. stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
  525. stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
  526. stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
  527. stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
  528. stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
  529. stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
  530. stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
  531. data.Add("stats", stats);
  532. }
  533. data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
  534. data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
  535. data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
  536. data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
  537. data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
  538. data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
  539. data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
  540. data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
  541. data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
  542. data.Add("totalClientsPerInterval", totalClientsPerInterval);
  543. data.Add("topDomains", totalStatCounter.GetTopDomains(10));
  544. data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
  545. data.Add("topClients", totalStatCounter.GetTopClients(10));
  546. data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(10));
  547. return data;
  548. }
  549. public Dictionary<string, List<KeyValuePair<string, long>>> GetLastDayHourWiseStats(bool utcFormat)
  550. {
  551. return GetHourWiseStats(DateTime.UtcNow.AddHours(-24), 24, utcFormat);
  552. }
  553. public Dictionary<string, List<KeyValuePair<string, long>>> GetLastWeekDayWiseStats(bool utcFormat)
  554. {
  555. return GetDayWiseStats(DateTime.UtcNow.AddDays(-7).Date, 7, utcFormat);
  556. }
  557. public Dictionary<string, List<KeyValuePair<string, long>>> GetLastMonthDayWiseStats(bool utcFormat)
  558. {
  559. return GetDayWiseStats(DateTime.UtcNow.AddDays(-31).Date, 31, utcFormat);
  560. }
  561. public Dictionary<string, List<KeyValuePair<string, long>>> GetLastYearMonthWiseStats(bool utcFormat)
  562. {
  563. StatCounter totalStatCounter = new StatCounter();
  564. totalStatCounter.Lock();
  565. List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>();
  566. List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>();
  567. List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>();
  568. List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>();
  569. List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>();
  570. List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>();
  571. List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>();
  572. List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>();
  573. List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>();
  574. List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>();
  575. DateTime lastYearDateTime = DateTime.UtcNow.AddMonths(-12);
  576. lastYearDateTime = new DateTime(lastYearDateTime.Year, lastYearDateTime.Month, 1, 0, 0, 0, DateTimeKind.Utc);
  577. for (int month = 0; month < 12; month++) //months
  578. {
  579. StatCounter monthlyStatCounter = new StatCounter();
  580. monthlyStatCounter.Lock();
  581. DateTime lastMonthDateTime = lastYearDateTime.AddMonths(month);
  582. string label;
  583. if (utcFormat)
  584. label = lastMonthDateTime.ToString("O");
  585. else
  586. label = lastMonthDateTime.ToLocalTime().ToString("MM/yyyy");
  587. int days = DateTime.DaysInMonth(lastMonthDateTime.Year, lastMonthDateTime.Month);
  588. for (int day = 0; day < days; day++) //days
  589. {
  590. StatCounter dailyStatCounter = LoadDailyStats(lastMonthDateTime.AddDays(day));
  591. monthlyStatCounter.Merge(dailyStatCounter, true);
  592. }
  593. totalStatCounter.Merge(monthlyStatCounter, true);
  594. totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalQueries));
  595. totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalNoError));
  596. totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalServerFailure));
  597. totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalNxDomain));
  598. totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalRefused));
  599. totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalAuthoritative));
  600. totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalRecursive));
  601. totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalCached));
  602. totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalBlocked));
  603. totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, monthlyStatCounter.TotalClients));
  604. }
  605. Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
  606. {
  607. List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(6);
  608. stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
  609. stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
  610. stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
  611. stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
  612. stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
  613. stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
  614. stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
  615. stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
  616. stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
  617. stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
  618. data.Add("stats", stats);
  619. }
  620. data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
  621. data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
  622. data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
  623. data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
  624. data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
  625. data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
  626. data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
  627. data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
  628. data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
  629. data.Add("totalClientsPerInterval", totalClientsPerInterval);
  630. data.Add("topDomains", totalStatCounter.GetTopDomains(10));
  631. data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
  632. data.Add("topClients", totalStatCounter.GetTopClients(10));
  633. data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(10));
  634. return data;
  635. }
  636. public Dictionary<string, List<KeyValuePair<string, long>>> GetHourWiseStats(DateTime startDate, DateTime endDate, bool utcFormat)
  637. {
  638. int hours = Convert.ToInt32((endDate - startDate).TotalHours) + 1;
  639. if (hours < 24)
  640. hours = 24;
  641. return GetHourWiseStats(startDate, hours, utcFormat);
  642. }
  643. public Dictionary<string, List<KeyValuePair<string, long>>> GetHourWiseStats(DateTime startDate, int hours, bool utcFormat)
  644. {
  645. StatCounter totalStatCounter = new StatCounter();
  646. totalStatCounter.Lock();
  647. List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>();
  648. List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>();
  649. List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>();
  650. List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>();
  651. List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>();
  652. List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>();
  653. List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>();
  654. List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>();
  655. List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>();
  656. List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>();
  657. for (int hour = 0; hour < hours; hour++)
  658. {
  659. DateTime lastDateTime = startDate.AddHours(hour);
  660. string label;
  661. if (utcFormat)
  662. label = lastDateTime.AddHours(1).ToString("O");
  663. else
  664. label = lastDateTime.AddHours(1).ToLocalTime().ToString("MM/dd HH") + ":00";
  665. HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
  666. StatCounter hourlyStatCounter = hourlyStats.HourStat;
  667. totalStatCounter.Merge(hourlyStatCounter);
  668. totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalQueries));
  669. totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalNoError));
  670. totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalServerFailure));
  671. totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalNxDomain));
  672. totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalRefused));
  673. totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalAuthoritative));
  674. totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalRecursive));
  675. totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalCached));
  676. totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalBlocked));
  677. totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, hourlyStatCounter.TotalClients));
  678. }
  679. Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
  680. {
  681. List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(6);
  682. stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
  683. stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
  684. stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
  685. stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
  686. stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
  687. stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
  688. stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
  689. stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
  690. stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
  691. stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
  692. data.Add("stats", stats);
  693. }
  694. data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
  695. data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
  696. data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
  697. data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
  698. data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
  699. data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
  700. data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
  701. data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
  702. data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
  703. data.Add("totalClientsPerInterval", totalClientsPerInterval);
  704. data.Add("topDomains", totalStatCounter.GetTopDomains(10));
  705. data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
  706. data.Add("topClients", totalStatCounter.GetTopClients(10));
  707. data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(10));
  708. return data;
  709. }
  710. public Dictionary<string, List<KeyValuePair<string, long>>> GetDayWiseStats(DateTime startDate, DateTime endDate, bool utcFormat)
  711. {
  712. return GetDayWiseStats(startDate, Convert.ToInt32((endDate - startDate).TotalDays) + 1, utcFormat);
  713. }
  714. public Dictionary<string, List<KeyValuePair<string, long>>> GetDayWiseStats(DateTime startDate, int days, bool utcFormat)
  715. {
  716. StatCounter totalStatCounter = new StatCounter();
  717. totalStatCounter.Lock();
  718. List<KeyValuePair<string, long>> totalQueriesPerInterval = new List<KeyValuePair<string, long>>();
  719. List<KeyValuePair<string, long>> totalNoErrorPerInterval = new List<KeyValuePair<string, long>>();
  720. List<KeyValuePair<string, long>> totalServerFailurePerInterval = new List<KeyValuePair<string, long>>();
  721. List<KeyValuePair<string, long>> totalNxDomainPerInterval = new List<KeyValuePair<string, long>>();
  722. List<KeyValuePair<string, long>> totalRefusedPerInterval = new List<KeyValuePair<string, long>>();
  723. List<KeyValuePair<string, long>> totalAuthHitPerInterval = new List<KeyValuePair<string, long>>();
  724. List<KeyValuePair<string, long>> totalRecursionsPerInterval = new List<KeyValuePair<string, long>>();
  725. List<KeyValuePair<string, long>> totalCacheHitPerInterval = new List<KeyValuePair<string, long>>();
  726. List<KeyValuePair<string, long>> totalBlockedPerInterval = new List<KeyValuePair<string, long>>();
  727. List<KeyValuePair<string, long>> totalClientsPerInterval = new List<KeyValuePair<string, long>>();
  728. for (int day = 0; day < days; day++) //days
  729. {
  730. DateTime lastDayDateTime = startDate.AddDays(day);
  731. string label;
  732. if (utcFormat)
  733. label = lastDayDateTime.ToString("O");
  734. else
  735. label = lastDayDateTime.ToLocalTime().ToString("MM/dd");
  736. StatCounter dailyStatCounter = LoadDailyStats(lastDayDateTime);
  737. totalStatCounter.Merge(dailyStatCounter, true);
  738. totalQueriesPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalQueries));
  739. totalNoErrorPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalNoError));
  740. totalServerFailurePerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalServerFailure));
  741. totalNxDomainPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalNxDomain));
  742. totalRefusedPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalRefused));
  743. totalAuthHitPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalAuthoritative));
  744. totalRecursionsPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalRecursive));
  745. totalCacheHitPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalCached));
  746. totalBlockedPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalBlocked));
  747. totalClientsPerInterval.Add(new KeyValuePair<string, long>(label, dailyStatCounter.TotalClients));
  748. }
  749. Dictionary<string, List<KeyValuePair<string, long>>> data = new Dictionary<string, List<KeyValuePair<string, long>>>();
  750. {
  751. List<KeyValuePair<string, long>> stats = new List<KeyValuePair<string, long>>(6);
  752. stats.Add(new KeyValuePair<string, long>("totalQueries", totalStatCounter.TotalQueries));
  753. stats.Add(new KeyValuePair<string, long>("totalNoError", totalStatCounter.TotalNoError));
  754. stats.Add(new KeyValuePair<string, long>("totalServerFailure", totalStatCounter.TotalServerFailure));
  755. stats.Add(new KeyValuePair<string, long>("totalNxDomain", totalStatCounter.TotalNxDomain));
  756. stats.Add(new KeyValuePair<string, long>("totalRefused", totalStatCounter.TotalRefused));
  757. stats.Add(new KeyValuePair<string, long>("totalAuthoritative", totalStatCounter.TotalAuthoritative));
  758. stats.Add(new KeyValuePair<string, long>("totalRecursive", totalStatCounter.TotalRecursive));
  759. stats.Add(new KeyValuePair<string, long>("totalCached", totalStatCounter.TotalCached));
  760. stats.Add(new KeyValuePair<string, long>("totalBlocked", totalStatCounter.TotalBlocked));
  761. stats.Add(new KeyValuePair<string, long>("totalClients", totalStatCounter.TotalClients));
  762. data.Add("stats", stats);
  763. }
  764. data.Add("totalQueriesPerInterval", totalQueriesPerInterval);
  765. data.Add("totalNoErrorPerInterval", totalNoErrorPerInterval);
  766. data.Add("totalServerFailurePerInterval", totalServerFailurePerInterval);
  767. data.Add("totalNxDomainPerInterval", totalNxDomainPerInterval);
  768. data.Add("totalRefusedPerInterval", totalRefusedPerInterval);
  769. data.Add("totalAuthHitPerInterval", totalAuthHitPerInterval);
  770. data.Add("totalRecursionsPerInterval", totalRecursionsPerInterval);
  771. data.Add("totalCacheHitPerInterval", totalCacheHitPerInterval);
  772. data.Add("totalBlockedPerInterval", totalBlockedPerInterval);
  773. data.Add("totalClientsPerInterval", totalClientsPerInterval);
  774. data.Add("topDomains", totalStatCounter.GetTopDomains(10));
  775. data.Add("topBlockedDomains", totalStatCounter.GetTopBlockedDomains(10));
  776. data.Add("topClients", totalStatCounter.GetTopClients(10));
  777. data.Add("queryTypes", totalStatCounter.GetTopQueryTypes(10));
  778. return data;
  779. }
  780. public List<KeyValuePair<string, long>> GetLastHourTopStats(TopStatsType type, int limit)
  781. {
  782. StatCounter totalStatCounter = new StatCounter();
  783. totalStatCounter.Lock();
  784. DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(-60);
  785. lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
  786. for (int minute = 0; minute < 60; minute++)
  787. {
  788. DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
  789. StatCounter statCounter = _lastHourStatCountersCopy[lastDateTime.Minute];
  790. if ((statCounter != null) && statCounter.IsLocked)
  791. totalStatCounter.Merge(statCounter);
  792. }
  793. switch (type)
  794. {
  795. case TopStatsType.TopDomains:
  796. return totalStatCounter.GetTopDomains(limit);
  797. case TopStatsType.TopBlockedDomains:
  798. return totalStatCounter.GetTopBlockedDomains(limit);
  799. case TopStatsType.TopClients:
  800. return totalStatCounter.GetTopClients(limit);
  801. default:
  802. throw new NotSupportedException();
  803. }
  804. }
  805. public List<KeyValuePair<string, long>> GetLastDayTopStats(TopStatsType type, int limit)
  806. {
  807. return GetHourWiseTopStats(DateTime.UtcNow.AddHours(-24), 24, type, limit);
  808. }
  809. public List<KeyValuePair<string, long>> GetLastWeekTopStats(TopStatsType type, int limit)
  810. {
  811. return GetDayWiseTopStats(DateTime.UtcNow.AddDays(-7).Date, 7, type, limit);
  812. }
  813. public List<KeyValuePair<string, long>> GetLastMonthTopStats(TopStatsType type, int limit)
  814. {
  815. return GetDayWiseTopStats(DateTime.UtcNow.AddDays(-31).Date, 31, type, limit);
  816. }
  817. public List<KeyValuePair<string, long>> GetLastYearTopStats(TopStatsType type, int limit)
  818. {
  819. StatCounter totalStatCounter = new StatCounter();
  820. totalStatCounter.Lock();
  821. DateTime lastYearDateTime = DateTime.UtcNow.AddMonths(-12);
  822. lastYearDateTime = new DateTime(lastYearDateTime.Year, lastYearDateTime.Month, 1, 0, 0, 0, DateTimeKind.Utc);
  823. for (int month = 0; month < 12; month++) //months
  824. {
  825. StatCounter monthlyStatCounter = new StatCounter();
  826. monthlyStatCounter.Lock();
  827. DateTime lastMonthDateTime = lastYearDateTime.AddMonths(month);
  828. int days = DateTime.DaysInMonth(lastMonthDateTime.Year, lastMonthDateTime.Month);
  829. for (int day = 0; day < days; day++) //days
  830. {
  831. StatCounter dailyStatCounter = LoadDailyStats(lastMonthDateTime.AddDays(day));
  832. monthlyStatCounter.Merge(dailyStatCounter, true);
  833. }
  834. totalStatCounter.Merge(monthlyStatCounter, true);
  835. }
  836. switch (type)
  837. {
  838. case TopStatsType.TopDomains:
  839. return totalStatCounter.GetTopDomains(limit);
  840. case TopStatsType.TopBlockedDomains:
  841. return totalStatCounter.GetTopBlockedDomains(limit);
  842. case TopStatsType.TopClients:
  843. return totalStatCounter.GetTopClients(limit);
  844. default:
  845. throw new NotSupportedException();
  846. }
  847. }
  848. public List<KeyValuePair<string, long>> GetHourWiseTopStats(DateTime startDate, DateTime endDate, TopStatsType type, int limit)
  849. {
  850. int hours = Convert.ToInt32((endDate - startDate).TotalHours) + 1;
  851. if (hours < 24)
  852. hours = 24;
  853. return GetHourWiseTopStats(startDate, hours, type, limit);
  854. }
  855. public List<KeyValuePair<string, long>> GetHourWiseTopStats(DateTime startDate, int hours, TopStatsType type, int limit)
  856. {
  857. StatCounter totalStatCounter = new StatCounter();
  858. totalStatCounter.Lock();
  859. for (int hour = 0; hour < hours; hour++)
  860. {
  861. DateTime lastDateTime = startDate.AddHours(hour);
  862. HourlyStats hourlyStats = LoadHourlyStats(lastDateTime);
  863. StatCounter hourlyStatCounter = hourlyStats.HourStat;
  864. totalStatCounter.Merge(hourlyStatCounter);
  865. }
  866. switch (type)
  867. {
  868. case TopStatsType.TopDomains:
  869. return totalStatCounter.GetTopDomains(limit);
  870. case TopStatsType.TopBlockedDomains:
  871. return totalStatCounter.GetTopBlockedDomains(limit);
  872. case TopStatsType.TopClients:
  873. return totalStatCounter.GetTopClients(limit);
  874. default:
  875. throw new NotSupportedException();
  876. }
  877. }
  878. public List<KeyValuePair<string, long>> GetDayWiseTopStats(DateTime startDate, DateTime endDate, TopStatsType type, int limit)
  879. {
  880. return GetDayWiseTopStats(startDate, Convert.ToInt32((endDate - startDate).TotalDays) + 1, type, limit);
  881. }
  882. public List<KeyValuePair<string, long>> GetDayWiseTopStats(DateTime startDate, int days, TopStatsType type, int limit)
  883. {
  884. StatCounter totalStatCounter = new StatCounter();
  885. totalStatCounter.Lock();
  886. for (int day = 0; day < days; day++) //days
  887. {
  888. DateTime lastDayDateTime = startDate.AddDays(day);
  889. StatCounter dailyStatCounter = LoadDailyStats(lastDayDateTime);
  890. totalStatCounter.Merge(dailyStatCounter, true);
  891. }
  892. switch (type)
  893. {
  894. case TopStatsType.TopDomains:
  895. return totalStatCounter.GetTopDomains(limit);
  896. case TopStatsType.TopBlockedDomains:
  897. return totalStatCounter.GetTopBlockedDomains(limit);
  898. case TopStatsType.TopClients:
  899. return totalStatCounter.GetTopClients(limit);
  900. default:
  901. throw new NotSupportedException();
  902. }
  903. }
  904. public List<KeyValuePair<DnsQuestionRecord, long>> GetLastHourEligibleQueries(int minimumHitsPerHour)
  905. {
  906. StatCounter totalStatCounter = new StatCounter();
  907. totalStatCounter.Lock();
  908. DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(-60);
  909. lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
  910. for (int minute = 0; minute < 60; minute++)
  911. {
  912. DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
  913. StatCounter statCounter = _lastHourStatCountersCopy[lastDateTime.Minute];
  914. if ((statCounter != null) && statCounter.IsLocked)
  915. totalStatCounter.Merge(statCounter);
  916. }
  917. return totalStatCounter.GetEligibleQueries(minimumHitsPerHour);
  918. }
  919. public void GetLatestClientSubnetStats(int minutes, int ipv4PrefixLength, int ipv6PrefixLength, out IReadOnlyDictionary<IPAddress, long> clientSubnetStats, out IReadOnlyDictionary<IPAddress, long> errorClientSubnetStats)
  920. {
  921. StatCounter totalStatCounter = new StatCounter();
  922. totalStatCounter.Lock();
  923. DateTime lastHourDateTime = DateTime.UtcNow.AddMinutes(1 - minutes);
  924. lastHourDateTime = new DateTime(lastHourDateTime.Year, lastHourDateTime.Month, lastHourDateTime.Day, lastHourDateTime.Hour, lastHourDateTime.Minute, 0, DateTimeKind.Utc);
  925. for (int minute = 0; minute < minutes; minute++)
  926. {
  927. DateTime lastDateTime = lastHourDateTime.AddMinutes(minute);
  928. StatCounter statCounter = _lastHourStatCounters[lastDateTime.Minute];
  929. if (statCounter is not null)
  930. totalStatCounter.Merge(statCounter, false, true);
  931. }
  932. clientSubnetStats = totalStatCounter.GetClientSubnetStats(ipv4PrefixLength, ipv6PrefixLength);
  933. errorClientSubnetStats = totalStatCounter.GetErrorClientSubnetStats(ipv4PrefixLength, ipv6PrefixLength);
  934. }
  935. #endregion
  936. #region properties
  937. public int MaxStatFileDays
  938. {
  939. get { return _maxStatFileDays; }
  940. set { _maxStatFileDays = value; }
  941. }
  942. #endregion
  943. class HourlyStats
  944. {
  945. #region variables
  946. readonly StatCounter _hourStat; //calculated value
  947. StatCounter[] _minuteStats = new StatCounter[60];
  948. #endregion
  949. #region constructor
  950. public HourlyStats()
  951. {
  952. _hourStat = new StatCounter();
  953. _hourStat.Lock();
  954. }
  955. public HourlyStats(BinaryReader bR)
  956. {
  957. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "HS") //format
  958. throw new InvalidDataException("HourlyStats format is invalid.");
  959. byte version = bR.ReadByte();
  960. switch (version)
  961. {
  962. case 1:
  963. _hourStat = new StatCounter();
  964. _hourStat.Lock();
  965. for (int i = 0; i < _minuteStats.Length; i++)
  966. {
  967. _minuteStats[i] = new StatCounter(bR);
  968. _hourStat.Merge(_minuteStats[i]);
  969. }
  970. break;
  971. default:
  972. throw new InvalidDataException("HourlyStats version not supported.");
  973. }
  974. }
  975. #endregion
  976. #region public
  977. public void UpdateStat(DateTime dateTime, StatCounter minuteStat)
  978. {
  979. if (!minuteStat.IsLocked)
  980. throw new DnsServerException("StatCounter must be locked.");
  981. _hourStat.Merge(minuteStat);
  982. _minuteStats[dateTime.Minute] = minuteStat;
  983. }
  984. public void UnloadMinuteStats()
  985. {
  986. _minuteStats = null;
  987. }
  988. public void WriteTo(BinaryWriter bW)
  989. {
  990. bW.Write(Encoding.ASCII.GetBytes("HS")); //format
  991. bW.Write((byte)1); //version
  992. for (int i = 0; i < _minuteStats.Length; i++)
  993. {
  994. if (_minuteStats[i] == null)
  995. {
  996. _minuteStats[i] = new StatCounter();
  997. _minuteStats[i].Lock();
  998. }
  999. _minuteStats[i].WriteTo(bW);
  1000. }
  1001. }
  1002. #endregion
  1003. #region properties
  1004. public StatCounter HourStat
  1005. { get { return _hourStat; } }
  1006. public StatCounter[] MinuteStats
  1007. {
  1008. get { return _minuteStats; }
  1009. }
  1010. #endregion
  1011. }
  1012. class StatCounter
  1013. {
  1014. #region variables
  1015. volatile bool _locked;
  1016. long _totalQueries;
  1017. long _totalNoError;
  1018. long _totalServerFailure;
  1019. long _totalNxDomain;
  1020. long _totalRefused;
  1021. long _totalAuthoritative;
  1022. long _totalRecursive;
  1023. long _totalCached;
  1024. long _totalBlocked;
  1025. long _totalClients;
  1026. readonly ConcurrentDictionary<string, Counter> _queryDomains;
  1027. readonly ConcurrentDictionary<string, Counter> _queryBlockedDomains;
  1028. readonly ConcurrentDictionary<DnsResourceRecordType, Counter> _queryTypes;
  1029. readonly ConcurrentDictionary<IPAddress, Counter> _clientIpAddresses; //includes all queries
  1030. readonly ConcurrentDictionary<IPAddress, Counter> _errorIpAddresses; //includes REFUSED, FORMERR and SERVFAIL
  1031. readonly ConcurrentDictionary<DnsQuestionRecord, Counter> _queries;
  1032. bool _truncationFoundDuringMerge;
  1033. long _totalClientsDailyStatsSummation;
  1034. #endregion
  1035. #region constructor
  1036. public StatCounter()
  1037. {
  1038. _queryDomains = new ConcurrentDictionary<string, Counter>();
  1039. _queryBlockedDomains = new ConcurrentDictionary<string, Counter>();
  1040. _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>();
  1041. _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>();
  1042. _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>();
  1043. _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>();
  1044. }
  1045. public StatCounter(BinaryReader bR)
  1046. {
  1047. if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "SC") //format
  1048. throw new InvalidDataException("StatCounter format is invalid.");
  1049. byte version = bR.ReadByte();
  1050. switch (version)
  1051. {
  1052. case 1:
  1053. case 2:
  1054. case 3:
  1055. case 4:
  1056. case 5:
  1057. case 6:
  1058. _totalQueries = bR.ReadInt32();
  1059. _totalNoError = bR.ReadInt32();
  1060. _totalServerFailure = bR.ReadInt32();
  1061. _totalNxDomain = bR.ReadInt32();
  1062. _totalRefused = bR.ReadInt32();
  1063. if (version >= 3)
  1064. {
  1065. _totalAuthoritative = bR.ReadInt32();
  1066. _totalRecursive = bR.ReadInt32();
  1067. _totalCached = bR.ReadInt32();
  1068. _totalBlocked = bR.ReadInt32();
  1069. }
  1070. else
  1071. {
  1072. _totalBlocked = bR.ReadInt32();
  1073. if (version >= 2)
  1074. _totalCached = bR.ReadInt32();
  1075. }
  1076. if (version >= 6)
  1077. _totalClients = bR.ReadInt32();
  1078. {
  1079. int count = bR.ReadInt32();
  1080. _queryDomains = new ConcurrentDictionary<string, Counter>(1, count);
  1081. for (int i = 0; i < count; i++)
  1082. _queryDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt32()));
  1083. }
  1084. {
  1085. int count = bR.ReadInt32();
  1086. _queryBlockedDomains = new ConcurrentDictionary<string, Counter>(1, count);
  1087. for (int i = 0; i < count; i++)
  1088. _queryBlockedDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt32()));
  1089. }
  1090. {
  1091. int count = bR.ReadInt32();
  1092. _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>(1, count);
  1093. for (int i = 0; i < count; i++)
  1094. _queryTypes.TryAdd((DnsResourceRecordType)bR.ReadUInt16(), new Counter(bR.ReadInt32()));
  1095. }
  1096. {
  1097. int count = bR.ReadInt32();
  1098. _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
  1099. for (int i = 0; i < count; i++)
  1100. _clientIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt32()));
  1101. if (version < 6)
  1102. _totalClients = count;
  1103. }
  1104. if (version >= 4)
  1105. {
  1106. int count = bR.ReadInt32();
  1107. _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>(1, count);
  1108. for (int i = 0; i < count; i++)
  1109. _queries.TryAdd(new DnsQuestionRecord(bR.BaseStream), new Counter(bR.ReadInt32()));
  1110. }
  1111. else
  1112. {
  1113. _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>(1, 0);
  1114. }
  1115. if (version >= 5)
  1116. {
  1117. int count = bR.ReadInt32();
  1118. _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
  1119. for (int i = 0; i < count; i++)
  1120. _errorIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt32()));
  1121. }
  1122. else
  1123. {
  1124. _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, 0);
  1125. }
  1126. break;
  1127. case 7:
  1128. _totalQueries = bR.ReadInt64();
  1129. _totalNoError = bR.ReadInt64();
  1130. _totalServerFailure = bR.ReadInt64();
  1131. _totalNxDomain = bR.ReadInt64();
  1132. _totalRefused = bR.ReadInt64();
  1133. _totalAuthoritative = bR.ReadInt64();
  1134. _totalRecursive = bR.ReadInt64();
  1135. _totalCached = bR.ReadInt64();
  1136. _totalBlocked = bR.ReadInt64();
  1137. _totalClients = bR.ReadInt64();
  1138. {
  1139. int count = bR.ReadInt32();
  1140. _queryDomains = new ConcurrentDictionary<string, Counter>(1, count);
  1141. for (int i = 0; i < count; i++)
  1142. _queryDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt64()));
  1143. }
  1144. {
  1145. int count = bR.ReadInt32();
  1146. _queryBlockedDomains = new ConcurrentDictionary<string, Counter>(1, count);
  1147. for (int i = 0; i < count; i++)
  1148. _queryBlockedDomains.TryAdd(bR.ReadShortString(), new Counter(bR.ReadInt64()));
  1149. }
  1150. {
  1151. int count = bR.ReadInt32();
  1152. _queryTypes = new ConcurrentDictionary<DnsResourceRecordType, Counter>(1, count);
  1153. for (int i = 0; i < count; i++)
  1154. _queryTypes.TryAdd((DnsResourceRecordType)bR.ReadUInt16(), new Counter(bR.ReadInt64()));
  1155. }
  1156. {
  1157. int count = bR.ReadInt32();
  1158. _clientIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
  1159. for (int i = 0; i < count; i++)
  1160. _clientIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt64()));
  1161. }
  1162. {
  1163. int count = bR.ReadInt32();
  1164. _queries = new ConcurrentDictionary<DnsQuestionRecord, Counter>(1, count);
  1165. for (int i = 0; i < count; i++)
  1166. _queries.TryAdd(new DnsQuestionRecord(bR.BaseStream), new Counter(bR.ReadInt64()));
  1167. }
  1168. {
  1169. int count = bR.ReadInt32();
  1170. _errorIpAddresses = new ConcurrentDictionary<IPAddress, Counter>(1, count);
  1171. for (int i = 0; i < count; i++)
  1172. _errorIpAddresses.TryAdd(IPAddressExtensions.ReadFrom(bR), new Counter(bR.ReadInt64()));
  1173. }
  1174. break;
  1175. default:
  1176. throw new InvalidDataException("StatCounter version not supported.");
  1177. }
  1178. _locked = true;
  1179. }
  1180. #endregion
  1181. #region private
  1182. private static List<KeyValuePair<string, long>> GetTopList(List<KeyValuePair<string, long>> list, int limit)
  1183. {
  1184. list.Sort(delegate (KeyValuePair<string, long> item1, KeyValuePair<string, long> item2)
  1185. {
  1186. return item2.Value.CompareTo(item1.Value);
  1187. });
  1188. if (list.Count > limit)
  1189. list.RemoveRange(limit, list.Count - limit);
  1190. return list;
  1191. }
  1192. private static Counter GetNewCounter<T>(T key)
  1193. {
  1194. return new Counter();
  1195. }
  1196. #endregion
  1197. #region public
  1198. public void Lock()
  1199. {
  1200. _locked = true;
  1201. }
  1202. public void Update(DnsQuestionRecord query, DnsResponseCode responseCode, DnsServerResponseType responseType, IPAddress clientIpAddress)
  1203. {
  1204. if (_locked)
  1205. return;
  1206. if (clientIpAddress.IsIPv4MappedToIPv6)
  1207. clientIpAddress = clientIpAddress.MapToIPv4();
  1208. Interlocked.Increment(ref _totalQueries);
  1209. switch (responseCode)
  1210. {
  1211. case DnsResponseCode.NoError:
  1212. if (query is not null)
  1213. {
  1214. switch (responseType)
  1215. {
  1216. case DnsServerResponseType.Blocked:
  1217. case DnsServerResponseType.UpstreamBlocked:
  1218. case DnsServerResponseType.CacheBlocked:
  1219. //skip blocked domains
  1220. break;
  1221. default:
  1222. _queryDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
  1223. _queries.GetOrAdd(query, GetNewCounter).Increment();
  1224. break;
  1225. }
  1226. }
  1227. Interlocked.Increment(ref _totalNoError);
  1228. break;
  1229. case DnsResponseCode.ServerFailure:
  1230. _errorIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
  1231. Interlocked.Increment(ref _totalServerFailure);
  1232. break;
  1233. case DnsResponseCode.NxDomain:
  1234. Interlocked.Increment(ref _totalNxDomain);
  1235. break;
  1236. case DnsResponseCode.Refused:
  1237. _errorIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
  1238. Interlocked.Increment(ref _totalRefused);
  1239. break;
  1240. case DnsResponseCode.FormatError:
  1241. _errorIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
  1242. break;
  1243. }
  1244. switch (responseType)
  1245. {
  1246. case DnsServerResponseType.Authoritative:
  1247. Interlocked.Increment(ref _totalAuthoritative);
  1248. break;
  1249. case DnsServerResponseType.Recursive:
  1250. Interlocked.Increment(ref _totalRecursive);
  1251. break;
  1252. case DnsServerResponseType.Cached:
  1253. Interlocked.Increment(ref _totalCached);
  1254. break;
  1255. case DnsServerResponseType.Blocked:
  1256. if (query is not null)
  1257. _queryBlockedDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
  1258. Interlocked.Increment(ref _totalBlocked);
  1259. break;
  1260. case DnsServerResponseType.UpstreamBlocked:
  1261. Interlocked.Increment(ref _totalRecursive);
  1262. if (query is not null)
  1263. _queryBlockedDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
  1264. Interlocked.Increment(ref _totalBlocked);
  1265. break;
  1266. case DnsServerResponseType.CacheBlocked:
  1267. Interlocked.Increment(ref _totalCached);
  1268. if (query is not null)
  1269. _queryBlockedDomains.GetOrAdd(query.Name.ToLower(), GetNewCounter).Increment();
  1270. Interlocked.Increment(ref _totalBlocked);
  1271. break;
  1272. }
  1273. if (query is not null)
  1274. _queryTypes.GetOrAdd(query.Type, GetNewCounter).Increment();
  1275. _clientIpAddresses.GetOrAdd(clientIpAddress, GetNewCounter).Increment();
  1276. _totalClients = _clientIpAddresses.Count;
  1277. }
  1278. public void Merge(StatCounter statCounter, bool isDailyStatCounter = false, bool skipLock = false)
  1279. {
  1280. if (!skipLock && (!_locked || !statCounter._locked))
  1281. throw new DnsServerException("StatCounter must be locked.");
  1282. _totalQueries += statCounter._totalQueries;
  1283. _totalNoError += statCounter._totalNoError;
  1284. _totalServerFailure += statCounter._totalServerFailure;
  1285. _totalNxDomain += statCounter._totalNxDomain;
  1286. _totalRefused += statCounter._totalRefused;
  1287. _totalAuthoritative += statCounter._totalAuthoritative;
  1288. _totalRecursive += statCounter._totalRecursive;
  1289. _totalCached += statCounter._totalCached;
  1290. _totalBlocked += statCounter._totalBlocked;
  1291. foreach (KeyValuePair<string, Counter> queryDomain in statCounter._queryDomains)
  1292. _queryDomains.GetOrAdd(queryDomain.Key, GetNewCounter).Merge(queryDomain.Value);
  1293. foreach (KeyValuePair<string, Counter> queryBlockedDomain in statCounter._queryBlockedDomains)
  1294. _queryBlockedDomains.GetOrAdd(queryBlockedDomain.Key, GetNewCounter).Merge(queryBlockedDomain.Value);
  1295. foreach (KeyValuePair<DnsResourceRecordType, Counter> queryType in statCounter._queryTypes)
  1296. _queryTypes.GetOrAdd(queryType.Key, GetNewCounter).Merge(queryType.Value);
  1297. foreach (KeyValuePair<IPAddress, Counter> clientIpAddress in statCounter._clientIpAddresses)
  1298. _clientIpAddresses.GetOrAdd(clientIpAddress.Key, GetNewCounter).Merge(clientIpAddress.Value);
  1299. foreach (KeyValuePair<IPAddress, Counter> refusedIpAddress in statCounter._errorIpAddresses)
  1300. _errorIpAddresses.GetOrAdd(refusedIpAddress.Key, GetNewCounter).Merge(refusedIpAddress.Value);
  1301. foreach (KeyValuePair<DnsQuestionRecord, Counter> query in statCounter._queries)
  1302. _queries.GetOrAdd(query.Key, GetNewCounter).Merge(query.Value);
  1303. _totalClients = _clientIpAddresses.Count;
  1304. _totalClientsDailyStatsSummation += statCounter._totalClients;
  1305. if (isDailyStatCounter && (statCounter._totalClients > statCounter._clientIpAddresses.Count))
  1306. _truncationFoundDuringMerge = true;
  1307. }
  1308. public bool Truncate(int limit)
  1309. {
  1310. bool truncated = false;
  1311. if (_queryDomains.Count > limit)
  1312. {
  1313. List<KeyValuePair<string, Counter>> topDomains = new List<KeyValuePair<string, Counter>>(_queryDomains);
  1314. _queryDomains.Clear();
  1315. topDomains.Sort(delegate (KeyValuePair<string, Counter> item1, KeyValuePair<string, Counter> item2)
  1316. {
  1317. return item2.Value.Count.CompareTo(item1.Value.Count);
  1318. });
  1319. if (topDomains.Count > limit)
  1320. topDomains.RemoveRange(limit, topDomains.Count - limit);
  1321. foreach (KeyValuePair<string, Counter> item in topDomains)
  1322. _queryDomains[item.Key] = item.Value;
  1323. truncated = true;
  1324. }
  1325. if (_queryBlockedDomains.Count > limit)
  1326. {
  1327. List<KeyValuePair<string, Counter>> topBlockedDomains = new List<KeyValuePair<string, Counter>>(_queryBlockedDomains);
  1328. _queryBlockedDomains.Clear();
  1329. topBlockedDomains.Sort(delegate (KeyValuePair<string, Counter> item1, KeyValuePair<string, Counter> item2)
  1330. {
  1331. return item2.Value.Count.CompareTo(item1.Value.Count);
  1332. });
  1333. if (topBlockedDomains.Count > limit)
  1334. topBlockedDomains.RemoveRange(limit, topBlockedDomains.Count - limit);
  1335. foreach (KeyValuePair<string, Counter> item in topBlockedDomains)
  1336. _queryBlockedDomains[item.Key] = item.Value;
  1337. truncated = true;
  1338. }
  1339. if (_queryTypes.Count > limit)
  1340. {
  1341. List<KeyValuePair<DnsResourceRecordType, Counter>> queryTypes = new List<KeyValuePair<DnsResourceRecordType, Counter>>(_queryTypes);
  1342. _queryTypes.Clear();
  1343. queryTypes.Sort(delegate (KeyValuePair<DnsResourceRecordType, Counter> item1, KeyValuePair<DnsResourceRecordType, Counter> item2)
  1344. {
  1345. return item2.Value.Count.CompareTo(item1.Value.Count);
  1346. });
  1347. if (queryTypes.Count > limit)
  1348. {
  1349. long othersCount = 0;
  1350. for (int i = limit; i < queryTypes.Count; i++)
  1351. othersCount += queryTypes[i].Value.Count;
  1352. queryTypes.RemoveRange(limit - 1, queryTypes.Count - (limit - 1));
  1353. queryTypes.Add(new KeyValuePair<DnsResourceRecordType, Counter>(DnsResourceRecordType.Unknown, new Counter(othersCount)));
  1354. }
  1355. foreach (KeyValuePair<DnsResourceRecordType, Counter> item in queryTypes)
  1356. _queryTypes[item.Key] = item.Value;
  1357. truncated = true;
  1358. }
  1359. if (_clientIpAddresses.Count > limit)
  1360. {
  1361. List<KeyValuePair<IPAddress, Counter>> topClients = new List<KeyValuePair<IPAddress, Counter>>(_clientIpAddresses);
  1362. _clientIpAddresses.Clear();
  1363. topClients.Sort(delegate (KeyValuePair<IPAddress, Counter> item1, KeyValuePair<IPAddress, Counter> item2)
  1364. {
  1365. return item2.Value.Count.CompareTo(item1.Value.Count);
  1366. });
  1367. if (topClients.Count > limit)
  1368. topClients.RemoveRange(limit, topClients.Count - limit);
  1369. foreach (KeyValuePair<IPAddress, Counter> item in topClients)
  1370. _clientIpAddresses[item.Key] = item.Value;
  1371. truncated = true;
  1372. }
  1373. if (_errorIpAddresses.Count > limit)
  1374. {
  1375. List<KeyValuePair<IPAddress, Counter>> topErrorClients = new List<KeyValuePair<IPAddress, Counter>>(_errorIpAddresses);
  1376. _errorIpAddresses.Clear();
  1377. topErrorClients.Sort(delegate (KeyValuePair<IPAddress, Counter> item1, KeyValuePair<IPAddress, Counter> item2)
  1378. {
  1379. return item2.Value.Count.CompareTo(item1.Value.Count);
  1380. });
  1381. if (topErrorClients.Count > limit)
  1382. topErrorClients.RemoveRange(limit, topErrorClients.Count - limit);
  1383. foreach (KeyValuePair<IPAddress, Counter> item in topErrorClients)
  1384. _errorIpAddresses[item.Key] = item.Value;
  1385. truncated = true;
  1386. }
  1387. if (_queries.Count > limit)
  1388. {
  1389. //only last hour queries data is required for cache auto prefetching
  1390. _queries.Clear();
  1391. truncated = true;
  1392. }
  1393. return truncated;
  1394. }
  1395. public void WriteTo(BinaryWriter bW)
  1396. {
  1397. if (!_locked)
  1398. throw new DnsServerException("StatCounter must be locked.");
  1399. bW.Write(Encoding.ASCII.GetBytes("SC")); //format
  1400. bW.Write((byte)7); //version
  1401. bW.Write(_totalQueries);
  1402. bW.Write(_totalNoError);
  1403. bW.Write(_totalServerFailure);
  1404. bW.Write(_totalNxDomain);
  1405. bW.Write(_totalRefused);
  1406. bW.Write(_totalAuthoritative);
  1407. bW.Write(_totalRecursive);
  1408. bW.Write(_totalCached);
  1409. bW.Write(_totalBlocked);
  1410. bW.Write(_totalClients);
  1411. {
  1412. bW.Write(_queryDomains.Count);
  1413. foreach (KeyValuePair<string, Counter> queryDomain in _queryDomains)
  1414. {
  1415. bW.WriteShortString(queryDomain.Key);
  1416. bW.Write(queryDomain.Value.Count);
  1417. }
  1418. }
  1419. {
  1420. bW.Write(_queryBlockedDomains.Count);
  1421. foreach (KeyValuePair<string, Counter> queryBlockedDomain in _queryBlockedDomains)
  1422. {
  1423. bW.WriteShortString(queryBlockedDomain.Key);
  1424. bW.Write(queryBlockedDomain.Value.Count);
  1425. }
  1426. }
  1427. {
  1428. bW.Write(_queryTypes.Count);
  1429. foreach (KeyValuePair<DnsResourceRecordType, Counter> queryType in _queryTypes)
  1430. {
  1431. bW.Write((ushort)queryType.Key);
  1432. bW.Write(queryType.Value.Count);
  1433. }
  1434. }
  1435. {
  1436. bW.Write(_clientIpAddresses.Count);
  1437. foreach (KeyValuePair<IPAddress, Counter> clientIpAddress in _clientIpAddresses)
  1438. {
  1439. clientIpAddress.Key.WriteTo(bW);
  1440. bW.Write(clientIpAddress.Value.Count);
  1441. }
  1442. }
  1443. {
  1444. bW.Write(_queries.Count);
  1445. foreach (KeyValuePair<DnsQuestionRecord, Counter> query in _queries)
  1446. {
  1447. query.Key.WriteTo(bW.BaseStream, null);
  1448. bW.Write(query.Value.Count);
  1449. }
  1450. }
  1451. {
  1452. bW.Write(_errorIpAddresses.Count);
  1453. foreach (KeyValuePair<IPAddress, Counter> refusedIpAddress in _errorIpAddresses)
  1454. {
  1455. refusedIpAddress.Key.WriteTo(bW);
  1456. bW.Write(refusedIpAddress.Value.Count);
  1457. }
  1458. }
  1459. }
  1460. public List<KeyValuePair<string, long>> GetTopDomains(int limit)
  1461. {
  1462. List<KeyValuePair<string, long>> topDomains = new List<KeyValuePair<string, long>>(_queryDomains.Count);
  1463. foreach (KeyValuePair<string, Counter> item in _queryDomains)
  1464. topDomains.Add(new KeyValuePair<string, long>(item.Key, item.Value.Count));
  1465. return GetTopList(topDomains, limit);
  1466. }
  1467. public List<KeyValuePair<string, long>> GetTopBlockedDomains(int limit)
  1468. {
  1469. List<KeyValuePair<string, long>> topBlockedDomains = new List<KeyValuePair<string, long>>(_queryBlockedDomains.Count);
  1470. foreach (KeyValuePair<string, Counter> item in _queryBlockedDomains)
  1471. topBlockedDomains.Add(new KeyValuePair<string, long>(item.Key, item.Value.Count));
  1472. return GetTopList(topBlockedDomains, limit);
  1473. }
  1474. public List<KeyValuePair<string, long>> GetTopClients(int limit)
  1475. {
  1476. List<KeyValuePair<string, long>> topClients = new List<KeyValuePair<string, long>>(_clientIpAddresses.Count);
  1477. foreach (KeyValuePair<IPAddress, Counter> item in _clientIpAddresses)
  1478. topClients.Add(new KeyValuePair<string, long>(item.Key.ToString(), item.Value.Count));
  1479. return GetTopList(topClients, limit);
  1480. }
  1481. public List<KeyValuePair<string, long>> GetTopQueryTypes(int limit)
  1482. {
  1483. List<KeyValuePair<string, long>> queryTypes = new List<KeyValuePair<string, long>>(_queryTypes.Count);
  1484. foreach (KeyValuePair<DnsResourceRecordType, Counter> item in _queryTypes)
  1485. queryTypes.Add(new KeyValuePair<string, long>(item.Key.ToString(), item.Value.Count));
  1486. queryTypes.Sort(delegate (KeyValuePair<string, long> item1, KeyValuePair<string, long> item2)
  1487. {
  1488. return item2.Value.CompareTo(item1.Value);
  1489. });
  1490. if (queryTypes.Count > limit)
  1491. {
  1492. long othersCount = 0;
  1493. for (int i = limit; i < queryTypes.Count; i++)
  1494. othersCount += queryTypes[i].Value;
  1495. queryTypes.RemoveRange((limit - 1), queryTypes.Count - (limit - 1));
  1496. queryTypes.Add(new KeyValuePair<string, long>("Others", othersCount));
  1497. }
  1498. return queryTypes;
  1499. }
  1500. public List<KeyValuePair<DnsQuestionRecord, long>> GetEligibleQueries(int minimumHits)
  1501. {
  1502. List<KeyValuePair<DnsQuestionRecord, long>> eligibleQueries = new List<KeyValuePair<DnsQuestionRecord, long>>(Convert.ToInt32(_queries.Count * 0.1));
  1503. foreach (KeyValuePair<DnsQuestionRecord, Counter> item in _queries)
  1504. {
  1505. if (item.Value.Count >= minimumHits)
  1506. eligibleQueries.Add(new KeyValuePair<DnsQuestionRecord, long>(item.Key, item.Value.Count));
  1507. }
  1508. return eligibleQueries;
  1509. }
  1510. public IReadOnlyDictionary<IPAddress, long> GetClientSubnetStats(int ipv4PrefixLength, int ipv6PrefixLength)
  1511. {
  1512. Dictionary<IPAddress, long> clientSubnetStats = new Dictionary<IPAddress, long>(_clientIpAddresses.Count);
  1513. foreach (KeyValuePair<IPAddress, Counter> item in _clientIpAddresses)
  1514. {
  1515. IPAddress clientSubnet;
  1516. switch (item.Key.AddressFamily)
  1517. {
  1518. case AddressFamily.InterNetwork:
  1519. clientSubnet = item.Key.GetNetworkAddress(ipv4PrefixLength);
  1520. break;
  1521. case AddressFamily.InterNetworkV6:
  1522. clientSubnet = item.Key.GetNetworkAddress(ipv6PrefixLength);
  1523. break;
  1524. default:
  1525. throw new NotSupportedException("AddressFamily not supported.");
  1526. }
  1527. if (clientSubnetStats.TryGetValue(clientSubnet, out long existingValue))
  1528. clientSubnetStats[clientSubnet] = existingValue + item.Value.Count;
  1529. else
  1530. clientSubnetStats.Add(clientSubnet, item.Value.Count);
  1531. }
  1532. return clientSubnetStats;
  1533. }
  1534. public IReadOnlyDictionary<IPAddress, long> GetErrorClientSubnetStats(int ipv4PrefixLength, int ipv6PrefixLength)
  1535. {
  1536. Dictionary<IPAddress, long> errorClientSubnetStats = new Dictionary<IPAddress, long>(_errorIpAddresses.Count);
  1537. foreach (KeyValuePair<IPAddress, Counter> item in _errorIpAddresses)
  1538. {
  1539. IPAddress clientSubnet;
  1540. switch (item.Key.AddressFamily)
  1541. {
  1542. case AddressFamily.InterNetwork:
  1543. clientSubnet = item.Key.GetNetworkAddress(ipv4PrefixLength);
  1544. break;
  1545. case AddressFamily.InterNetworkV6:
  1546. clientSubnet = item.Key.GetNetworkAddress(ipv6PrefixLength);
  1547. break;
  1548. default:
  1549. throw new NotSupportedException("AddressFamily not supported.");
  1550. }
  1551. if (errorClientSubnetStats.TryGetValue(clientSubnet, out long existingValue))
  1552. errorClientSubnetStats[clientSubnet] = existingValue + item.Value.Count;
  1553. else
  1554. errorClientSubnetStats.Add(clientSubnet, item.Value.Count);
  1555. }
  1556. return errorClientSubnetStats;
  1557. }
  1558. #endregion
  1559. #region properties
  1560. public bool IsLocked
  1561. { get { return _locked; } }
  1562. public long TotalQueries
  1563. { get { return _totalQueries; } }
  1564. public long TotalNoError
  1565. { get { return _totalNoError; } }
  1566. public long TotalServerFailure
  1567. { get { return _totalServerFailure; } }
  1568. public long TotalNxDomain
  1569. { get { return _totalNxDomain; } }
  1570. public long TotalRefused
  1571. { get { return _totalRefused; } }
  1572. public long TotalAuthoritative
  1573. { get { return _totalAuthoritative; } }
  1574. public long TotalRecursive
  1575. { get { return _totalRecursive; } }
  1576. public long TotalCached
  1577. { get { return _totalCached; } }
  1578. public long TotalBlocked
  1579. { get { return _totalBlocked; } }
  1580. public long TotalClients
  1581. {
  1582. get
  1583. {
  1584. if (_truncationFoundDuringMerge)
  1585. return _totalClientsDailyStatsSummation;
  1586. return _totalClients;
  1587. }
  1588. }
  1589. #endregion
  1590. class Counter
  1591. {
  1592. #region variables
  1593. long _count;
  1594. #endregion
  1595. #region constructor
  1596. public Counter()
  1597. { }
  1598. public Counter(long count)
  1599. {
  1600. _count = count;
  1601. }
  1602. #endregion
  1603. #region public
  1604. public void Increment()
  1605. {
  1606. Interlocked.Increment(ref _count);
  1607. }
  1608. public void Merge(Counter counter)
  1609. {
  1610. _count += counter._count;
  1611. }
  1612. #endregion
  1613. #region properties
  1614. public long Count
  1615. { get { return _count; } }
  1616. #endregion
  1617. }
  1618. }
  1619. class StatsQueueItem
  1620. {
  1621. #region variables
  1622. public readonly DateTime _timestamp;
  1623. public readonly DnsDatagram _request;
  1624. public readonly IPEndPoint _remoteEP;
  1625. public readonly DnsTransportProtocol _protocol;
  1626. public readonly DnsDatagram _response;
  1627. #endregion
  1628. #region constructor
  1629. public StatsQueueItem(DnsDatagram request, IPEndPoint remoteEP, DnsTransportProtocol protocol, DnsDatagram response)
  1630. {
  1631. _timestamp = DateTime.UtcNow;
  1632. _request = request;
  1633. _remoteEP = remoteEP;
  1634. _protocol = protocol;
  1635. _response = response;
  1636. }
  1637. #endregion
  1638. }
  1639. }
  1640. }