DataCollector.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. using System.Text;
  2. using LibreHardwareMonitor.Hardware;
  3. using MinecraftStatus;
  4. using SteamQueryNet;
  5. using SteamQueryNet.Interfaces;
  6. using System.Text.Json;
  7. using Microsoft.Extensions.Configuration;
  8. using VeloeMonitorDataCollector.DatabaseConnectors;
  9. using VeloeMonitorDataCollector.Models;
  10. using Serilog;
  11. using VeloeMonitorDataCollector.Dependencies;
  12. using System.Globalization;
  13. using System.Net;
  14. namespace VeloeMonitorDataCollector
  15. {
  16. public class DataCollector
  17. {
  18. private Dictionary<string, Task> _updaterTasks; //TODO i can use an array here
  19. CancellationToken _token;
  20. CancellationTokenSource _cancellationTokenSource;
  21. Serilog.ILogger _logger;
  22. Computer? _computerHardware;
  23. float prevIdle = 0f;
  24. float prevTotal = 0f;
  25. List<DriveInfo> _drives;
  26. Dictionary<string, int> _deviceLoadSensorIndex = new()
  27. {
  28. {"cpuload", -1},
  29. {"ramavailable", -1},
  30. {"ramused", -1},
  31. {"ramload", -1}
  32. };
  33. private List<IDataSendable> _sendToDb; //TODO and here
  34. //Exception thrown on checking values
  35. /// <exception cref="ArgumentNullException">when there is no value in INI file or this value is not declared.</exception>
  36. /// <exception cref="ArgumentOutOfRangeException">when value in INI file does not match in range. Example: Port value range is 1..65565]</exception>
  37. /// <exception cref="FormatException">when value can not be parsed to needed type. Expample: Port value can't be NaN</exception>
  38. /// <exception cref="OverflowException">when provided value caused overflowed return variable in parse method.</exception>
  39. public DataCollector(in IConfiguration data,in Serilog.ILogger logger)
  40. {
  41. _updaterTasks = new Dictionary<string, Task>();
  42. _cancellationTokenSource = new CancellationTokenSource();
  43. _token = _cancellationTokenSource.Token;
  44. _logger = logger;
  45. //ini file check
  46. //is it needed?
  47. if (!File.Exists("config.ini"))
  48. {
  49. File.WriteAllText("config.ini",
  50. "#[Hardware]\n#hardware = true\n#hardwareUpdateInterval = true\n\n#[MySQL]\n#server = 127.0.0.1\n#port = 8806\n#uid = User\n#pwd = Password\n#database = values\n\n#[WebSoket]\n#url = http://192.168.1.2:5000\n\n#[MinecraftServer]\n#Ip = 127.0.0.1\n#Port = 25565\n#Type = Minecraft\n#updateInterval = 30\n\n#[SteamAPIServer]\n#Ip = 127.0.0.1\n#Port = 27015\n#Type = Steam\n#updateInterval = 30\n\n#[Gamespy3Server]\n#Ip = 127.0.0.1\n#Port = 5446\n#Type = Gamespy3\n#updateInterval = 30\n\n#[Gamespy2Server]\n#Ip = 127.0.0.1\n#Port = 10480\n#Type = Gamespy2\n#updateInterval = 30");
  51. throw new FileNotFoundException("config.ini does not exist! Default config was created as an example.");
  52. }
  53. //check read/write
  54. //is it needed
  55. FileStream config = File.Open("config.ini", FileMode.Open, FileAccess.ReadWrite);
  56. config.Close();
  57. config.Dispose();
  58. var hardware = data.GetSection("Hardware");
  59. //ini hardvare section validation
  60. if (hardware["hardware"] != "true" && hardware["hardware"] != "false" || hardware["hardware"] is null)
  61. {
  62. hardware["hardware"] = "false";
  63. }
  64. //configuring database connections
  65. var dbSections = data
  66. .GetChildren()
  67. .Where(section =>
  68. section.Path is ("MySQL" or "InfluxDB" or "TimescaleDB" or "WebSoket"))
  69. .ToArray();
  70. _sendToDb = new List<IDataSendable>();
  71. if (!dbSections.Any())
  72. {
  73. _logger.Information("No databases detected.");
  74. }
  75. else
  76. {
  77. foreach (var dbSection in dbSections)
  78. {
  79. //init db connections
  80. switch (dbSection.Path)
  81. {
  82. case "MySQL":
  83. try
  84. {
  85. var mySqlDb = new VeloeMonitorDataCollector.DatabaseConnectors.MySqlConnector(dbSection, logger);
  86. _sendToDb.Add(mySqlDb);
  87. }
  88. catch (Exception ex)
  89. {
  90. logger.Warning("Database connector not confugured properly. It won't be added in working configuration.");
  91. logger.Error(ex.Message);
  92. }
  93. break;
  94. case "WebSoket":
  95. try
  96. {
  97. SignalRConnector signalRWebApp = new(dbSection, logger);
  98. _sendToDb.Add(signalRWebApp);
  99. }
  100. catch (Exception ex)
  101. {
  102. logger.Warning("SignalR connector not confugured properly. It won't be added in working configuration.");
  103. logger.Error(ex.Message);
  104. }
  105. break;
  106. case "TimescaleDB":
  107. throw new NotImplementedException();
  108. case "InfluxDB":
  109. throw new NotImplementedException();
  110. }
  111. }
  112. }
  113. // checking params in game servers sections
  114. // configuring game servers
  115. var gameServersSections = data
  116. .GetChildren()
  117. .Where (section =>
  118. section.Key is not ("MySQL" or "InfluxDB" or"TimescaleDB" or "WebSoket" or "Hardware"))
  119. .ToArray();
  120. if (!gameServersSections.Any())
  121. {
  122. //add commented block with default example
  123. _logger.Information("No game servers detected.");
  124. }
  125. else
  126. foreach (var gameServer in gameServersSections)
  127. {
  128. //Console.WriteLine(gameServer.Key);
  129. if (gameServer["Ip"] == null ||
  130. gameServer["Port"] == null ||
  131. gameServer["Type"] == null)
  132. {
  133. throw new ArgumentNullException($"Some parameters for {gameServer.Key} are missing.");
  134. }
  135. if (!(Int32.Parse(gameServer["Port"]) is >= 1 and <= 65565))
  136. throw new ArgumentOutOfRangeException(gameServer["Port"]);
  137. foreach (char c in gameServer.Key)
  138. {
  139. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
  140. {
  141. throw new ArgumentException($"Not allowed symbols in {gameServer.Key}. Only letters and numbers are allowed.");
  142. }
  143. }
  144. }
  145. // create task for hardware update
  146. if (bool.Parse(hardware["hardware"]))
  147. {
  148. _computerHardware = new Computer()
  149. {
  150. IsCpuEnabled = true,
  151. IsMemoryEnabled = true,
  152. };
  153. _drives = new List<DriveInfo>();
  154. DriveInfo[] allDrives = DriveInfo.GetDrives();
  155. foreach (DriveInfo d in allDrives)
  156. {
  157. if (d.IsReady == true && (d.DriveType is DriveType.Fixed or DriveType.Network) && d.TotalSize != 0 && !(d.Name.StartsWith("/boot") || d.Name.StartsWith("/dev")))
  158. {
  159. _drives.Add(d);
  160. }
  161. }
  162. _computerHardware.Open();
  163. SetValuesTimeZero(); //no history
  164. CreateHardwareInfoFile();
  165. //check database table configuration
  166. foreach (var database in _sendToDb)
  167. {
  168. var hardwareConfiguration = UpdateHardware();
  169. if (database.CheckHardware(hardwareConfiguration) is false)
  170. {
  171. throw new Exception(
  172. "Table configuration for hardware is invalid. Repair it manually or drop table and restart program.");
  173. }
  174. }
  175. int updateIntervalHardware;
  176. if (!Int32.TryParse(hardware["updateIntervalHardware"], out updateIntervalHardware))
  177. {
  178. _logger.Warning("Unable to parse updateIntervalHardware. Used default value.");
  179. updateIntervalHardware = 1;
  180. }
  181. _updaterTasks.Add("hardware", new Task(async () =>
  182. {
  183. while (!_token.IsCancellationRequested)
  184. {
  185. //Console.WriteLine(_token.IsCancellationRequested);
  186. var data = UpdateHardware();
  187. if (_sendToDb != null)
  188. foreach (var dbController in _sendToDb)
  189. {
  190. dbController.SendHardware(data);
  191. }
  192. await Task.Delay(TimeSpan.FromSeconds(updateIntervalHardware));
  193. }
  194. }, _token));
  195. }
  196. //create tasks for game servers updates
  197. foreach (var section in gameServersSections)
  198. {
  199. //check database table configuration
  200. foreach (var database in _sendToDb)
  201. { //Gamespy3 servers ignores it
  202. //Tablecheck in BuildUpdater method
  203. if (database.CheckGameServer(section.Key, section["Type"]) is false)
  204. {
  205. throw new Exception(
  206. $"Table {section.Key} configuration is invalid. Repair it manually or drop table and restart program.");
  207. }
  208. }
  209. int interval;
  210. if (!Int32.TryParse(section["updateInterval"], out interval))
  211. {
  212. _logger.Information("Unable to parse updateInterval. Used default value.");
  213. interval = 1;
  214. }
  215. BuildUpdater(section.Path,
  216. section["Ip"],
  217. Int32.Parse(section["Port"]),
  218. section["Type"], interval);
  219. }
  220. }
  221. public void Start()
  222. {
  223. foreach (var task in _updaterTasks)
  224. {
  225. _logger.Information("{0} started!",task.Key);
  226. task.Value.Start();
  227. }
  228. }
  229. public void Stop()
  230. {
  231. _cancellationTokenSource.Cancel();
  232. bool tasksStillActive = true;
  233. while (tasksStillActive)
  234. {
  235. tasksStillActive = false;
  236. foreach (var task in _updaterTasks)
  237. if (task.Value.Status == TaskStatus.Running) tasksStillActive = true;
  238. Task.Delay(TimeSpan.FromMilliseconds(250));
  239. }
  240. if (_computerHardware is not null)
  241. _computerHardware.Close();
  242. //wait to Tasks to end their execution
  243. //close all db connections
  244. foreach (var database in _sendToDb)
  245. {
  246. database.Close();
  247. }
  248. }
  249. private void SetValuesTimeZero()
  250. {
  251. if (_computerHardware is null)
  252. return;
  253. foreach (var hardware in _computerHardware.Hardware)
  254. {
  255. foreach (var sensor in hardware.Sensors)
  256. {
  257. sensor.ValuesTimeWindow = TimeSpan.Zero;
  258. }
  259. }
  260. }
  261. private void CreateHardwareInfoFile()
  262. {
  263. File.Create("sysinfo.txt").Close();
  264. StreamWriter sw = File.AppendText("sysinfo.txt");
  265. foreach (var hardware in _computerHardware.Hardware)
  266. {
  267. hardware.Update();
  268. //foreach (var sensor in hardware.Sensors)
  269. // _logger.Warning("{0}: {1}", sensor.Name, sensor.Value);
  270. sw.WriteLine(hardware.Name);
  271. sw.WriteLine(" Type: {0}", hardware.HardwareType);
  272. sw.WriteLine(" Type: {0}", hardware.Identifier);
  273. sw.WriteLine(" Sensors:");
  274. foreach (var sensor in hardware.Sensors)
  275. {
  276. sw.WriteLine(" {0,-25} {1,-15} {2,-15}",sensor.Name, sensor.SensorType, sensor.Value);
  277. }
  278. }
  279. foreach (DriveInfo d in DriveInfo.GetDrives())
  280. {
  281. if (d.IsReady == true && (d.DriveType is DriveType.Fixed or DriveType.Network) && d.TotalSize != 0 && !(d.Name.StartsWith("/boot") || d.Name.StartsWith("/dev")))
  282. {
  283. sw.WriteLine("Drive {0}", d.Name);
  284. sw.WriteLine(" File type: {0}", d.DriveType);
  285. sw.WriteLine(" Volume label: {0}", d.VolumeLabel);
  286. sw.WriteLine(" File system: {0}", d.DriveFormat);
  287. sw.WriteLine(
  288. " Available space to current user:{0, 15} bytes",
  289. d.AvailableFreeSpace);
  290. sw.WriteLine(
  291. " Total available space: {0, 15} bytes",
  292. d.TotalFreeSpace);
  293. sw.WriteLine(
  294. " Total size of drive: {0, 15} bytes ",
  295. d.TotalSize);
  296. }
  297. }
  298. sw.Close();
  299. }
  300. private Dictionary<string, float> UpdateHardware()
  301. {
  302. Dictionary<string, float> output = new Dictionary<string, float>();
  303. if (_computerHardware is null)
  304. return output;
  305. foreach (var hardware in _computerHardware.Hardware)
  306. {
  307. hardware.Update();
  308. //foreach (var sensor in hardware.Sensors)
  309. // _logger.Warning("{0}: {1}", sensor.Name, sensor.Value);
  310. if (hardware.HardwareType is HardwareType.Cpu)
  311. if (_deviceLoadSensorIndex["cpuload"] is not -1)
  312. output.Add("cpuload", hardware.Sensors[_deviceLoadSensorIndex["cpuload"]].Value.GetValueOrDefault());
  313. else
  314. {
  315. for(int i = 0; i < hardware.Sensors.Length; i++)
  316. if (hardware.Sensors[i].SensorType is SensorType.Load && hardware.Sensors[i].Name == "CPU Total")
  317. {
  318. output.Add("cpuload", hardware.Sensors[i].Value.GetValueOrDefault());
  319. _deviceLoadSensorIndex["cpuload"] = i;
  320. }
  321. }
  322. if (hardware.HardwareType is HardwareType.Memory)
  323. {
  324. //output.Add("ramavailable", hardware.Sensors[1].Value.GetValueOrDefault());
  325. if (_deviceLoadSensorIndex["ramavailable"] is not -1)
  326. output.Add("ramavailable", hardware.Sensors[_deviceLoadSensorIndex["ramavailable"]].Value.GetValueOrDefault());
  327. else
  328. {
  329. for (int i = 0; i < hardware.Sensors.Length; i++)
  330. if (hardware.Sensors[i].SensorType is SensorType.Data && hardware.Sensors[i].Name == "Memory Available")
  331. {
  332. output.Add("ramavailable", hardware.Sensors[i].Value.GetValueOrDefault());
  333. _deviceLoadSensorIndex["ramavailable"] = i;
  334. }
  335. }
  336. //output.Add("ramused", hardware.Sensors[0].Value.GetValueOrDefault());
  337. if (_deviceLoadSensorIndex["ramused"] is not -1)
  338. output.Add("ramused", hardware.Sensors[_deviceLoadSensorIndex["ramused"]].Value.GetValueOrDefault());
  339. else
  340. {
  341. for (int i = 0; i < hardware.Sensors.Length; i++)
  342. if (hardware.Sensors[i].SensorType is SensorType.Data && hardware.Sensors[i].Name == "Memory Used")
  343. {
  344. output.Add("ramused", hardware.Sensors[i].Value.GetValueOrDefault());
  345. _deviceLoadSensorIndex["ramused"] = i;
  346. }
  347. }
  348. //output.Add("ramload", hardware.Sensors[2].Value.GetValueOrDefault());
  349. if (_deviceLoadSensorIndex["ramload"] is not -1)
  350. output.Add("ramload", hardware.Sensors[_deviceLoadSensorIndex["ramload"]].Value.GetValueOrDefault());
  351. else
  352. {
  353. for (int i = 0; i < hardware.Sensors.Length; i++)
  354. if (hardware.Sensors[i].SensorType is SensorType.Load && hardware.Sensors[i].Name == "Memory")
  355. {
  356. output.Add("ramload", hardware.Sensors[i].Value.GetValueOrDefault());
  357. _deviceLoadSensorIndex["ramload"] = i;
  358. }
  359. }
  360. }
  361. }
  362. for (int i = 0; i < _drives.Count; i++)
  363. {
  364. _drives[i] = new DriveInfo(_drives[i].Name);
  365. var name = "";
  366. if (OperatingSystem.IsWindows())
  367. name = _drives[i].Name.ToLower().Replace(":\\", "").Replace('\\','_');
  368. else
  369. if (_drives[i].Name == "/")
  370. name = "root_directory";
  371. else
  372. name = _drives[i].Name.ToLower().Replace('/','_');
  373. output.Add(name , (float)_drives[i].TotalFreeSpace / _drives[i].TotalSize);
  374. }
  375. return output;
  376. }
  377. private void BuildUpdater(string name ,string ip, int port, string type, int interval)
  378. {
  379. switch (type)
  380. {
  381. case "Minecraft":
  382. _updaterTasks.Add(name, new Task(async () => {
  383. while (!_token.IsCancellationRequested)
  384. {
  385. await Task.Delay(TimeSpan.FromSeconds(interval));
  386. McStatus? data = null;
  387. data = UpdateMinecraft(ip, port);
  388. if (data is null)
  389. continue;
  390. if (_sendToDb is null)
  391. continue;
  392. foreach (var dbController in _sendToDb)
  393. {
  394. //_logger.Debug("Sending {0}", name);
  395. dbController.SendMinecraft(data,name);
  396. }
  397. }
  398. }, _token));
  399. break;
  400. case "Steam":
  401. _updaterTasks.Add(name, new Task(async () => {
  402. while (!_token.IsCancellationRequested)
  403. {
  404. await Task.Delay(TimeSpan.FromSeconds(interval));
  405. SteamData? data = null;
  406. data = await UpdateSteam(ip, port, interval);
  407. if (data is null)
  408. continue;
  409. if (_sendToDb is null)
  410. continue;
  411. foreach (var dbController in _sendToDb)
  412. {
  413. dbController.SendSteam(data.Value,name);
  414. }
  415. }
  416. }, _token));
  417. break;
  418. case "Gamespy3":
  419. _updaterTasks.Add(name, new Task(async () => {
  420. try
  421. {
  422. Gs3Status server = new Gs3Status(ip, port);
  423. while (!_token.IsCancellationRequested)
  424. {
  425. try
  426. {
  427. await Task.Delay(TimeSpan.FromSeconds(interval));
  428. var data = server.GetStatus();
  429. if (data is null)
  430. continue;
  431. if (_sendToDb is null)
  432. continue;
  433. foreach (var dbController in _sendToDb)
  434. {
  435. dbController.SendGamespy3(data, name);
  436. }
  437. }
  438. catch (System.Net.Sockets.SocketException ex)
  439. {
  440. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  441. }
  442. }
  443. }
  444. catch(System.Net.Sockets.SocketException ex)
  445. {
  446. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  447. }
  448. }, _token));
  449. break;
  450. case "Gamespy2":
  451. _updaterTasks.Add(name, new Task(async () => {
  452. try
  453. {
  454. Gs2Status server = new Gs2Status(ip, port);
  455. while (!_token.IsCancellationRequested)
  456. {
  457. try
  458. {
  459. await Task.Delay(TimeSpan.FromSeconds(interval));
  460. var data = server.GetStatus();
  461. if (data is null)
  462. continue;
  463. if (_sendToDb is null)
  464. continue;
  465. foreach (var dbController in _sendToDb)
  466. {
  467. dbController.SendGamespy2(data, name);
  468. }
  469. }
  470. catch (System.Net.Sockets.SocketException ex)
  471. {
  472. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  473. }
  474. }
  475. }
  476. catch (System.Net.Sockets.SocketException ex)
  477. {
  478. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  479. }
  480. }, _token));
  481. break;
  482. case "Url":
  483. _updaterTasks.Add(name, new Task(async () => {
  484. try
  485. {
  486. while (!_token.IsCancellationRequested)
  487. {
  488. try
  489. {
  490. await Task.Delay(TimeSpan.FromSeconds(interval));
  491. _logger.Debug("Try to get http response");
  492. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ip);
  493. request.Headers.Add("Accept-Encoding", "gzip, deflate");
  494. request.Headers.Add("Accept-Language", "en-US,en;q=0.5");
  495. request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  496. request.AllowAutoRedirect = true; // find out if this site is up and don't follow a redirector
  497. request.Method = "HEAD";
  498. try
  499. {
  500. using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  501. if (response is null)
  502. continue;
  503. if (response.StatusCode != HttpStatusCode.OK)
  504. continue;
  505. if (_sendToDb is null)
  506. continue;
  507. foreach (var dbController in _sendToDb)
  508. {
  509. dbController.SendUrl(response, name);
  510. }
  511. }
  512. catch (Exception ex) {
  513. _logger.Warning("{0} {1}", ip, ex.Message);
  514. }
  515. }
  516. catch (WebException ex)
  517. {
  518. _logger.Debug("{0} {1}", ip, ex.Message);
  519. }
  520. }
  521. }
  522. catch (System.Net.Sockets.SocketException ex)
  523. {
  524. _logger.Debug("{0} {1}", ip, ex.Message);
  525. }
  526. }, _token));
  527. break;
  528. }
  529. }
  530. private McStatus? UpdateMinecraft(string ip, int port)
  531. {
  532. McStatus? status = null;
  533. try
  534. {
  535. status = McStatus.GetStatus(ip, port);
  536. }
  537. catch (Exception ex)
  538. {
  539. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  540. }
  541. if (status != null)
  542. return status;
  543. return null;
  544. }
  545. private async Task<SteamData?> UpdateSteam(string ip, int port, int interval)
  546. {
  547. ServerQuery serverQuery = new ServerQuery();
  548. try
  549. {
  550. serverQuery.SendTimeout = 2000;
  551. serverQuery.ReceiveTimeout = 2000;
  552. SteamData? output = null;
  553. serverQuery.Connect(ip, (ushort)port);
  554. var serverInfo = await serverQuery.GetServerInfoAsync();
  555. var serverPlayers = await serverQuery.GetPlayersAsync();
  556. output = new SteamData
  557. {
  558. ServerInfo = serverInfo,
  559. Players = serverPlayers
  560. };
  561. if (output is null)
  562. return null;
  563. return output;
  564. }
  565. catch (TimeoutException ex)
  566. {
  567. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  568. return null;
  569. }
  570. catch (Exception ex)
  571. {
  572. _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
  573. return null;
  574. }
  575. }
  576. }
  577. }