Sfoglia il codice sorgente

fixed mysql crash on linux, changed disk info collecting, changed cpu load info on linux, fixed incorrect data on other system configurations

Veloe 2 anni fa
parent
commit
1487eebd6f

+ 191 - 27
VeloeMonitorDataCollector/DataCollector.cs

@@ -22,6 +22,16 @@ namespace VeloeMonitorDataCollector
         Serilog.ILogger _logger;
         
         Computer? _computerHardware;
+        float prevIdle = 0f;
+        float prevTotal = 0f;
+        List<DriveInfo> _drives;
+        Dictionary<string, int> _deviceLoadSensorIndex = new()
+        {
+            {"cpuload", -1},
+            {"ramavailable", -1},
+            {"ramused", -1},
+            {"ramload", -1}
+        };
         
         private List<IDataSendable> _sendToDb; //TODO and here
         
@@ -86,12 +96,13 @@ namespace VeloeMonitorDataCollector
                         case "MySQL":
                             try
                             {
-                                MySqlConnector mySqlDb = new MySqlConnector(dbSection, logger);
+                                var mySqlDb = new VeloeMonitorDataCollector.DatabaseConnectors.MySqlConnector(dbSection, logger);
                                 _sendToDb.Add(mySqlDb);
                             }
                             catch (Exception ex)
                             {
                                 logger.Warning("Database connector not confugured properly. It won't be added in working configuration.");
+                                logger.Error(ex.Message);
                             }
                             break;
 
@@ -104,6 +115,7 @@ namespace VeloeMonitorDataCollector
                             catch (Exception ex)
                             {
                                 logger.Warning("SignalR connector not confugured properly. It won't be added in working configuration.");
+                                logger.Error(ex.Message);
                             }
                             break;
 
@@ -163,12 +175,24 @@ namespace VeloeMonitorDataCollector
                 {
                     IsCpuEnabled = true,
                     IsMemoryEnabled = true,
-                    IsStorageEnabled = true,
                 };
+                _drives = new List<DriveInfo>();
+
+                DriveInfo[] allDrives = DriveInfo.GetDrives();
+
+                foreach (DriveInfo d in allDrives)
+                {
+                    if (d.IsReady == true && (d.DriveType is DriveType.Fixed or DriveType.Network) && d.TotalSize != 0 && !(d.Name.StartsWith("/boot") || d.Name.StartsWith("/dev")))
+                    {
+                        _drives.Add(d);                       
+                    }
+                }
 
                 _computerHardware.Open();
-                SetValuesTimeZero();    //why
-                
+                SetValuesTimeZero();    //no history
+
+                CreateHardwareInfoFile();
+
                 //check database table configuration
                 foreach (var database in _sendToDb)
                 {
@@ -281,6 +305,75 @@ namespace VeloeMonitorDataCollector
                 }
             }
         }
+
+        private void CreateHardwareInfoFile()
+        {
+            File.Create("sysinfo.txt").Close();
+
+            StreamWriter sw = File.AppendText("sysinfo.txt");
+
+            if (OperatingSystem.IsLinux())
+            {
+                var cpuLine = File
+                    .ReadAllLines("/proc/stat")
+                    .First()
+                    .Split(' ', StringSplitOptions.RemoveEmptyEntries)
+                    .Skip(1)
+                    .Select(float.Parse)
+                    .ToArray();
+
+                var idle = cpuLine[3];
+                var total = cpuLine.Sum();
+
+                var percent = 100 * (1.0f - (idle - prevIdle) / (total - prevTotal));
+                sw.WriteLine("CPU Load: {0}", percent);
+
+                prevIdle = idle;
+                prevTotal = total;
+
+            }
+
+            foreach (var hardware in _computerHardware.Hardware)
+            {
+                hardware.Update();
+                //foreach (var sensor in hardware.Sensors)
+                //    _logger.Warning("{0}: {1}", sensor.Name, sensor.Value);
+                sw.WriteLine(hardware.Name);
+                sw.WriteLine("  Type: {0}", hardware.HardwareType);
+                sw.WriteLine("  Type: {0}", hardware.Identifier);
+                sw.WriteLine("  Sensors:");
+                foreach (var sensor in hardware.Sensors)
+                {
+                    sw.WriteLine("    {0,-25}  {1,-15}  {2,-15}",sensor.Name, sensor.SensorType, sensor.Value);
+                }
+            }
+
+
+            foreach (DriveInfo d in DriveInfo.GetDrives())
+            {
+                if (d.IsReady == true && (d.DriveType is DriveType.Fixed or DriveType.Network) && d.TotalSize != 0 && !(d.Name.StartsWith("/boot") || d.Name.StartsWith("/dev")))
+                {
+                    sw.WriteLine("Drive {0}", d.Name);
+                    sw.WriteLine("  File type: {0}", d.DriveType);
+
+                    sw.WriteLine("  Volume label: {0}", d.VolumeLabel);
+                    sw.WriteLine("  File system: {0}", d.DriveFormat);
+                    sw.WriteLine(
+                        "  Available space to current user:{0, 15} bytes",
+                        d.AvailableFreeSpace);
+
+                    sw.WriteLine(
+                        "  Total available space:          {0, 15} bytes",
+                        d.TotalFreeSpace);
+
+                    sw.WriteLine(
+                        "  Total size of drive:            {0, 15} bytes ",
+                        d.TotalSize);
+                }
+            }
+
+            sw.Close();
+        }
         private Dictionary<string, float> UpdateHardware()
         {
             Dictionary<string, float> output = new Dictionary<string, float>();
@@ -288,31 +381,102 @@ namespace VeloeMonitorDataCollector
             if (_computerHardware is null)
                 return output;
 
+            if (OperatingSystem.IsLinux())
+            {
+                var cpuLine = File
+                    .ReadAllLines("/proc/stat")
+                    .First()
+                    .Split(' ', StringSplitOptions.RemoveEmptyEntries)
+                    .Skip(1)
+                    .Select(float.Parse)
+                    .ToArray();
+
+                var idle = cpuLine[3];
+                var total = cpuLine.Sum();
+
+                var percent = 100 * (1.0f - (idle - prevIdle) / (total - prevTotal));
+                //for the first calc number can be inf or nan
+                if (float.IsFinite(percent))
+                    output.Add("cpuload", percent);
+
+                prevIdle = idle;
+                prevTotal = total;
+
+            }
+
             foreach (var hardware in _computerHardware.Hardware)
             {
                 hardware.Update();
-                
-                if (hardware.HardwareType is HardwareType.Cpu)
-                    output.Add("cpuload", hardware.Sensors[8].Value.GetValueOrDefault());
-                if (hardware.HardwareType is HardwareType.Memory)
-                {
-                    output.Add("ramavailable", hardware.Sensors[1].Value.GetValueOrDefault());
-                    output.Add("ramused", hardware.Sensors[0].Value.GetValueOrDefault());
-                    output.Add("ramload", hardware.Sensors[2].Value.GetValueOrDefault());
-                }
+                //foreach (var sensor in hardware.Sensors)
+                //    _logger.Warning("{0}: {1}", sensor.Name, sensor.Value);
+   
+                if (hardware.HardwareType is HardwareType.Cpu && OperatingSystem.IsWindows())
+                    if (_deviceLoadSensorIndex["cpuload"] is not -1)
+                        output.Add("cpuload", hardware.Sensors[_deviceLoadSensorIndex["cpuload"]].Value.GetValueOrDefault());
+                    else
+                    {
+                        for(int i = 0; i < hardware.Sensors.Length; i++)
+                            if (hardware.Sensors[i].SensorType is SensorType.Load && hardware.Sensors[i].Name == "CPU Total")
+                            {
+                                output.Add("cpuload", hardware.Sensors[i].Value.GetValueOrDefault());
+                                _deviceLoadSensorIndex["cpuload"] = i;
+                            }
+                    }
 
-                if (hardware.HardwareType is HardwareType.Storage)
+                if (hardware.HardwareType is HardwareType.Memory)
                 {
-                    StringBuilder sb = new StringBuilder();
-                    foreach (char c in hardware.Name.ToLower())
+                    //output.Add("ramavailable", hardware.Sensors[1].Value.GetValueOrDefault());
+                    if (_deviceLoadSensorIndex["ramavailable"] is not -1)
+                        output.Add("ramavailable", hardware.Sensors[_deviceLoadSensorIndex["ramavailable"]].Value.GetValueOrDefault());
+                    else
                     {
-                        if (c is not (' ' or '/' or '-'))
-                        { sb.Append(c); }
+                        for (int i = 0; i < hardware.Sensors.Length; i++)
+                            if (hardware.Sensors[i].SensorType is SensorType.Data && hardware.Sensors[i].Name == "Memory Available")
+                            {
+                                output.Add("ramavailable", hardware.Sensors[i].Value.GetValueOrDefault());
+                                _deviceLoadSensorIndex["ramavailable"] = i;
+                            }
+                    }
+                    //output.Add("ramused", hardware.Sensors[0].Value.GetValueOrDefault());
+                    if (_deviceLoadSensorIndex["ramused"] is not -1)
+                        output.Add("ramused", hardware.Sensors[_deviceLoadSensorIndex["ramused"]].Value.GetValueOrDefault());
+                    else
+                    {
+                        for (int i = 0; i < hardware.Sensors.Length; i++)
+                            if (hardware.Sensors[i].SensorType is SensorType.Data && hardware.Sensors[i].Name == "Memory Used")
+                            {
+                                output.Add("ramused", hardware.Sensors[i].Value.GetValueOrDefault());
+                                _deviceLoadSensorIndex["ramused"] = i;
+                            }
+                    }
+                    //output.Add("ramload", hardware.Sensors[2].Value.GetValueOrDefault());
+                    if (_deviceLoadSensorIndex["ramload"] is not -1)
+                        output.Add("ramload", hardware.Sensors[_deviceLoadSensorIndex["ramload"]].Value.GetValueOrDefault());
+                    else
+                    {
+                        for (int i = 0; i < hardware.Sensors.Length; i++)
+                            if (hardware.Sensors[i].SensorType is SensorType.Load && hardware.Sensors[i].Name == "Memory")
+                            {
+                                output.Add("ramload", hardware.Sensors[i].Value.GetValueOrDefault());
+                                _deviceLoadSensorIndex["ramload"] = i;
+                            }
                     }
-                            
-                    output.Add(sb.ToString(), hardware.Sensors[1].Value.GetValueOrDefault());
                 }
+            }
+
+            for (int i = 0; i < _drives.Count; i++)
+            {
+                _drives[i] = new DriveInfo(_drives[i].Name);
+                var name = "";
                 
+                if (OperatingSystem.IsWindows())
+                    name = _drives[i].Name.ToLower().Replace(":\\", "").Replace('\\','_');
+                else
+                    if (_drives[i].Name == "/")
+                        name = "root_directory";
+                    else
+                        name = _drives[i].Name.ToLower().Replace('/','_');
+                output.Add(name , (float)_drives[i].TotalFreeSpace / _drives[i].TotalSize);
             }
             return output;
         }
@@ -416,13 +580,13 @@ namespace VeloeMonitorDataCollector
                                 }
                                 catch (System.Net.Sockets.SocketException ex)
                                 {
-                                    _logger.Debug(ex.Message);
+                                    _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
                                 }
                             }
                         }
                         catch(System.Net.Sockets.SocketException ex)
                         {
-                            _logger.Debug(ex.Message);
+                            _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
                         }
                     }, _token));
 
@@ -455,13 +619,13 @@ namespace VeloeMonitorDataCollector
                                 }
                                 catch (System.Net.Sockets.SocketException ex)
                                 {
-                                    _logger.Debug(ex.Message);
+                                    _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
                                 }
                             }
                         }
                         catch (System.Net.Sockets.SocketException ex)
                         {
-                            _logger.Debug(ex.Message);
+                            _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
                         }
                     }, _token));
 
@@ -478,7 +642,7 @@ namespace VeloeMonitorDataCollector
             }
             catch (Exception ex)
             {
-                _logger.Debug(ex.Message);
+                _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
             }
 
             if (status != null)
@@ -515,12 +679,12 @@ namespace VeloeMonitorDataCollector
             }
             catch (TimeoutException ex)
             {
-                _logger.Debug($"{{0}}:{{1}} {ex.Message}", ip, port); 
+                _logger.Debug("{0}:{1} {2}", ip, port, ex.Message); 
                 return null;
             }
             catch (Exception ex)
             {
-                _logger.Debug(ex.Message);
+                _logger.Debug("{0}:{1} {2}", ip, port, ex.Message);
                 return null;
             }
         }

+ 4 - 4
VeloeMonitorDataCollector/DatabaseConnectors/MySqlConnector.cs

@@ -3,7 +3,7 @@ using System.Text;
 using System.Text.Json;
 using Microsoft.Extensions.Configuration;
 using MinecraftStatus;
-using MySql.Data.MySqlClient;
+using MySqlConnector;
 using Serilog;
 using VeloeMonitorDataCollector.Dependencies;
 using VeloeMonitorDataCollector.Models;
@@ -254,7 +254,7 @@ namespace VeloeMonitorDataCollector.DatabaseConnectors
                 {
                     if (result.Read() is false)
                     {
-                        _logger.Error("End of table on column {0}/{1}",i,input.Count);
+                        _logger.Error("End of table on column {0}",i);
                         return false;
                     }
 
@@ -367,10 +367,10 @@ namespace VeloeMonitorDataCollector.DatabaseConnectors
             CultureInfo oldCultureInfo = CultureInfo.CurrentCulture;
             CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
             var cols = string.Join(',',data.Keys);
-            var values = string.Join(", @",data.Values);
+            var values = string.Join(", @",data.Keys);
             CultureInfo.CurrentCulture = oldCultureInfo;
 
-            var query = $"INSERT INTO hardware (date ,{cols}) VALUES (@date ,{values})";
+            var query = $"INSERT INTO hardware (date ,{cols}) VALUES (@date ,@{values})";
 
             //Console.WriteLine(query);
             command = new MySqlCommand(query, _connection);

+ 1 - 1
VeloeMonitorDataCollector/Dependencies/McStatus.cs

@@ -138,7 +138,7 @@ namespace MinecraftStatus
                 u.Client.ReceiveTimeout = 1000;
                 u.ExclusiveAddressUse = false;
                 u.Client.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, true);
-                u.Client.Bind(e);
+                //u.Client.Bind(e);
 
                 try
                 {

+ 0 - 9
VeloeMonitorDataCollector/Program.cs

@@ -17,16 +17,7 @@ var logger = new LoggerConfiguration()
    .WriteTo.Console(LogEventLevel.Debug)
    .WriteTo.File("logfile.log", LogEventLevel.Debug)// restricted... is Optional
    .CreateLogger();
-/*
-var status = new Gs3Status("192.168.1.86",5446).GetStatus();
 
-foreach (KeyValuePair<string, string> kvp in status.Info)
-{
-    Console.WriteLine(kvp.Key + " " + kvp.Value);
-}
-
-Console.ReadKey();
-*/
 try
 {
     DataCollector collector = new(configuration, logger);

+ 2 - 2
VeloeMonitorDataCollector/VeloeMonitorDataCollector.csproj

@@ -23,9 +23,10 @@
 
   <ItemGroup>
     <PackageReference Include="ClrHeapAllocationAnalyzer" Version="3.0.0" />
-    <PackageReference Include="LibreHardwareMonitorLib" Version="0.9.0" />
+    <PackageReference Include="LibreHardwareMonitorLib" Version="0.9.1" />
     <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
     <PackageReference Include="Microsoft.Extensions.Configuration.Ini" Version="6.0.0" />
+    <PackageReference Include="MySqlConnector" Version="2.2.0" />
     <PackageReference Include="Serilog.AspNetCore" Version="6.0.1" />
     <PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
     <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
@@ -33,7 +34,6 @@
       <PrivateAssets>all</PrivateAssets>
       <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
     </PackageReference>
-    <PackageReference Include="MySql.Data" Version="8.0.30" />
   </ItemGroup>
 
   <ItemGroup>