DataCollector.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. namespace VeloeMonitorDataCollector
  13. {
  14. public class DataCollector
  15. {
  16. private Dictionary<string, Task> _updaterTasks; //TODO i can use an array here
  17. CancellationToken _token;
  18. CancellationTokenSource _cancellationTokenSource;
  19. Serilog.ILogger _logger;
  20. Computer? _computerHardware;
  21. private List<IDataSendable> _sendToDb; //TODO and here
  22. //Exception thrown on checking values
  23. /// <exception cref="ArgumentNullException">when there is no value in INI file or this value is not declared.</exception>
  24. /// <exception cref="ArgumentOutOfRangeException">when value in INI file does not match in range. Example: Port value range is 1..65565]</exception>
  25. /// <exception cref="FormatException">when value can not be parsed to needed type. Expample: Port value can't be NaN</exception>
  26. /// <exception cref="OverflowException">when provided value caused overflowed return variable in parse method.</exception>
  27. public DataCollector(in IConfiguration data,in Serilog.ILogger logger)
  28. {
  29. _updaterTasks = new Dictionary<string, Task>();
  30. _cancellationTokenSource = new CancellationTokenSource();
  31. _token = _cancellationTokenSource.Token;
  32. _logger = logger;
  33. //ini file check
  34. //is it needed?
  35. if (!File.Exists("config.ini"))
  36. {
  37. File.WriteAllText("config.ini",
  38. "#hardware = true\n\n#[MySQL]\n#Ip = 127.0.0.1\n#Port = 8806\n#Username = User\n#Password = Password\n#Scheme = 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");
  39. throw new FileNotFoundException("config.ini does not exist! Default config was created as an example.");
  40. }
  41. //check read/write
  42. //is it needed
  43. FileStream config = File.Open("config.ini", FileMode.Open, FileAccess.ReadWrite);
  44. config.Close();
  45. config.Dispose();
  46. var hardware = data.GetSection("Hardware");
  47. //ini data validation
  48. if (hardware["hardware"] != "true" && hardware["hardware"] != "false" || hardware["hardware"] is null)
  49. {
  50. hardware["hardware"] = "false";
  51. }
  52. //configuring database connections
  53. var dbSections = data
  54. .GetChildren()
  55. .Where(section =>
  56. section.Path is ("MySQL" or "InfluxDB" or "TimescaleDB" or "WebSoket"))
  57. .ToArray();
  58. _sendToDb = new List<IDataSendable>();
  59. if (!dbSections.Any())
  60. {
  61. _logger.Information("No databases detected.");
  62. }
  63. else
  64. {
  65. foreach (var dbSection in dbSections)
  66. {
  67. //init db connections
  68. switch (dbSection.Path)
  69. {
  70. case "MySQL":
  71. try
  72. {
  73. MySqlConnector mySqlDb = new MySqlConnector(dbSection, logger);
  74. _sendToDb.Add(mySqlDb);
  75. }
  76. catch (Exception ex)
  77. {
  78. logger.Warning("Database connector not confugured properly. It won't be added in working configuration.");
  79. }
  80. break;
  81. case "WebSoket":
  82. try
  83. {
  84. SignalRConnector signalRWebApp = new(dbSection, logger);
  85. _sendToDb.Add(signalRWebApp);
  86. }
  87. catch (Exception ex)
  88. {
  89. logger.Warning("SignalR connector not confugured properly. It won't be added in working configuration.");
  90. }
  91. break;
  92. case "TimescaleDB":
  93. throw new NotImplementedException();
  94. case "InfluxDB":
  95. throw new NotImplementedException();
  96. }
  97. }
  98. }
  99. // checking params in game servers sections
  100. // configuring game servers
  101. var gameServersSections = data
  102. .GetChildren()
  103. .Where (section =>
  104. section.Key is not ("MySQL" or "InfluxDB" or"TimescaleDB" or "WebSoket" or "Hardware"))
  105. .ToArray();
  106. if (!gameServersSections.Any())
  107. {
  108. //add commented block with default example
  109. _logger.Information("No game servers detected.");
  110. }
  111. else
  112. foreach (var gameServer in gameServersSections)
  113. {
  114. //Console.WriteLine(gameServer.Key);
  115. if (gameServer["Ip"] == null ||
  116. gameServer["Port"] == null ||
  117. gameServer["Type"] == null)
  118. {
  119. throw new ArgumentNullException($"Some parameters for {gameServer.Key} are missing.");
  120. }
  121. if (!(Int32.Parse(gameServer["Port"]) is >= 1 and <= 65565))
  122. throw new ArgumentOutOfRangeException(gameServer["Port"]);
  123. foreach (char c in gameServer.Key)
  124. {
  125. if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')))
  126. {
  127. throw new ArgumentException($"Not allowed symbols in {gameServer.Key}. Only letters and numbers are allowed.");
  128. }
  129. }
  130. }
  131. // create task for hardware update
  132. if (bool.Parse(hardware["hardware"]))
  133. {
  134. _computerHardware = new Computer()
  135. {
  136. IsCpuEnabled = true,
  137. IsMemoryEnabled = true,
  138. IsStorageEnabled = true,
  139. };
  140. _computerHardware.Open();
  141. SetValuesTimeZero(); //why
  142. //check database table configuration
  143. foreach (var database in _sendToDb)
  144. {
  145. var hardwareConfiguration = UpdateHardware();
  146. if (database.CheckHardware(hardwareConfiguration) is false)
  147. {
  148. throw new Exception(
  149. "Table configuration for hardware is invalid. Repair it manually or drop table and restart program.");
  150. }
  151. }
  152. int updateIntervalHardware;
  153. if (!Int32.TryParse(hardware["updateIntervalHardware"], out updateIntervalHardware))
  154. {
  155. _logger.Warning("Unable to parse updateIntervalHardware. Used default value.");
  156. updateIntervalHardware = 1;
  157. }
  158. _updaterTasks.Add("hardware", new Task(async () =>
  159. {
  160. while (!_token.IsCancellationRequested)
  161. {
  162. //Console.WriteLine(_token.IsCancellationRequested);
  163. if (_sendToDb != null)
  164. foreach (var dbController in _sendToDb)
  165. {
  166. dbController.SendHardware(UpdateHardware());
  167. }
  168. await Task.Delay(TimeSpan.FromSeconds(updateIntervalHardware));
  169. }
  170. }, _token));
  171. }
  172. //create tasks for game servers updates
  173. foreach (var section in gameServersSections)
  174. {
  175. //check database table configuration
  176. foreach (var database in _sendToDb)
  177. { //Gamespy3 servers ignores it
  178. //Tablecheck in BuildUpdater method
  179. if (database.CheckGameServer(section.Key, section["Type"]) is false)
  180. {
  181. throw new Exception(
  182. $"Table {section.Key} configuration is invalid. Repair it manually or drop table and restart program.");
  183. }
  184. }
  185. int interval;
  186. if (!Int32.TryParse(section["updateInterval"], out interval))
  187. {
  188. _logger.Information("Unable to parse updateInterval. Used default value.");
  189. interval = 1;
  190. }
  191. BuildUpdater(section.Path,
  192. section["Ip"],
  193. Int32.Parse(section["Port"]),
  194. section["Type"], interval);
  195. }
  196. }
  197. public void Start()
  198. {
  199. foreach (var task in _updaterTasks)
  200. {
  201. _logger.Information("{0} started!",task.Key);
  202. task.Value.Start();
  203. }
  204. }
  205. public void Stop()
  206. {
  207. _cancellationTokenSource.Cancel();
  208. bool tasksStillActive = true;
  209. while (tasksStillActive)
  210. {
  211. tasksStillActive = false;
  212. foreach (var task in _updaterTasks)
  213. if (task.Value.Status == TaskStatus.Running) tasksStillActive = true;
  214. Task.Delay(TimeSpan.FromMilliseconds(250));
  215. }
  216. if (_computerHardware is not null)
  217. _computerHardware.Close();
  218. //wait to Tasks to end their execution
  219. //close all db connections
  220. foreach (var database in _sendToDb)
  221. {
  222. database.Close();
  223. }
  224. }
  225. private void SetValuesTimeZero()
  226. {
  227. if (_computerHardware is null)
  228. return;
  229. foreach (var hardware in _computerHardware.Hardware)
  230. {
  231. foreach (var sensor in hardware.Sensors)
  232. {
  233. sensor.ValuesTimeWindow = TimeSpan.Zero;
  234. }
  235. }
  236. }
  237. private Dictionary<string, float> UpdateHardware()
  238. {
  239. Dictionary<string, float> output = new Dictionary<string, float>();
  240. if (_computerHardware is null)
  241. return output;
  242. foreach (var hardware in _computerHardware.Hardware)
  243. {
  244. hardware.Update();
  245. if (hardware.HardwareType is HardwareType.Cpu)
  246. output.Add("cpuload", hardware.Sensors[8].Value.GetValueOrDefault());
  247. if (hardware.HardwareType is HardwareType.Memory)
  248. {
  249. output.Add("ramavailable", hardware.Sensors[1].Value.GetValueOrDefault());
  250. output.Add("ramused", hardware.Sensors[0].Value.GetValueOrDefault());
  251. output.Add("ramload", hardware.Sensors[2].Value.GetValueOrDefault());
  252. }
  253. if (hardware.HardwareType is HardwareType.Storage)
  254. {
  255. StringBuilder sb = new StringBuilder();
  256. foreach (char c in hardware.Name.ToLower())
  257. {
  258. if (c is not (' ' or '/' or '-'))
  259. { sb.Append(c); }
  260. }
  261. output.Add(sb.ToString(), hardware.Sensors[1].Value.GetValueOrDefault());
  262. }
  263. }
  264. return output;
  265. }
  266. private void BuildUpdater(string name ,string ip, int port, string type, int interval)
  267. {
  268. switch (type)
  269. {
  270. case "Minecraft":
  271. _updaterTasks.Add(name, new Task(async () => {
  272. while (!_token.IsCancellationRequested)
  273. {
  274. await Task.Delay(TimeSpan.FromSeconds(interval));
  275. var data = UpdateMinecraft(ip, port);
  276. //_logger.Debug("Updating {0}", name);
  277. if (data is null)
  278. continue;
  279. if (_sendToDb is null)
  280. continue;
  281. foreach (var dbController in _sendToDb)
  282. {
  283. //_logger.Debug("Sending {0}", name);
  284. dbController.SendMinecraft(data,name);
  285. }
  286. }
  287. }, _token));
  288. break;
  289. case "Steam":
  290. _updaterTasks.Add(name, new Task(async () => {
  291. while (!_token.IsCancellationRequested)
  292. {
  293. await Task.Delay(TimeSpan.FromSeconds(interval));
  294. var data = UpdateSteam(ip, port);
  295. if (data is null)
  296. continue;
  297. if (_sendToDb is null)
  298. continue;
  299. foreach (var dbController in _sendToDb)
  300. {
  301. dbController.SendSteam(data.Value,name);
  302. }
  303. }
  304. }, _token));
  305. break;
  306. case "Gamespy3":
  307. _updaterTasks.Add(name, new Task(async () => {
  308. try
  309. {
  310. Gs3Status server = new Gs3Status(ip, port);
  311. /*
  312. bool dataIsNull = true;
  313. while (dataIsNull && !_token.IsCancellationRequested)
  314. {
  315. var data = server.GetStatus();
  316. if (data is null)
  317. continue;
  318. if (_sendToDb is null)
  319. dataIsNull = false;
  320. foreach(var dbController in _sendToDb)
  321. {
  322. dbController.CheckGamespy3(data, name);
  323. }
  324. }
  325. */
  326. while (!_token.IsCancellationRequested)
  327. {
  328. await Task.Delay(TimeSpan.FromSeconds(interval));
  329. var data = server.GetStatus();
  330. if (data is null)
  331. continue;
  332. if (_sendToDb is null)
  333. continue;
  334. foreach (var dbController in _sendToDb)
  335. {
  336. dbController.SendGamespy3(data, name);
  337. }
  338. }
  339. }
  340. catch(System.Net.Sockets.SocketException ex)
  341. {
  342. _logger.Debug(ex.Message);
  343. }
  344. }, _token));
  345. break;
  346. }
  347. }
  348. private McStatus? UpdateMinecraft(string ip, int port)
  349. {
  350. McStatus? status = null;
  351. try
  352. {
  353. status = McStatus.GetStatus(ip, port);
  354. }
  355. catch (Exception ex)
  356. {
  357. _logger.Debug(ex.Message);
  358. }
  359. if (status != null)
  360. return status;
  361. return null;
  362. }
  363. private SteamData? UpdateSteam(string ip, int port)
  364. {
  365. IServerQuery serverQuery = new ServerQuery(ip, (ushort)port);
  366. try
  367. {
  368. SteamData output = new SteamData
  369. {
  370. ServerInfo = serverQuery.GetServerInfo(),
  371. Players = serverQuery.GetPlayers()
  372. };
  373. if (output.ServerInfo is null)
  374. return null;
  375. return output;
  376. }
  377. catch (Exception ex)
  378. {
  379. _logger.Debug(ex.Message);
  380. return null;
  381. }
  382. }
  383. }
  384. }