完善上传系统状态信息接口

This commit is contained in:
huangxianguo 2024-09-10 11:59:34 +08:00
parent 5dfbdfee5e
commit d199ff7f7f
4 changed files with 118 additions and 48 deletions

View File

@ -2,9 +2,8 @@
using MasstransferCommon.Events;
using MasstransferCommon.Scheduler;
using MasstransferCommunicate.Mqtt.Client;
using MasstransferExporter.DataExporter;
using MasstransferExporter.DataExporter.Model;
using MasstransferExporter.Init;
using MasstransferExporter.StatExporter;
using MasstransferInfrastructure.Database.Sqlite;
using MasstransferInfrastructure.Mqtt.Model;
using Serilog;
@ -39,8 +38,9 @@ class Program
// 启动完成后,广播启动通知
EventBus<bool>.Publish(EventType.StartUp, true);
DelayScheduler.Delay(async () => await StrikeRecordService.ReportStrikeRecord(),
TimeSpan.FromSeconds(5));
DelayScheduler.Delay(async () => await SystemStatExporter.ExportSystemStat(),
TimeSpan.FromSeconds(3));
// 启动与主程序的通信
// ProcessHelper.Init();

View File

@ -1,4 +1,4 @@
namespace MasstransferExporter.Stat.DTO;
namespace MasstransferExporter.StatExporter.Model;
/// <summary>
/// CPU 负载信息
@ -7,5 +7,5 @@ public class CpuLoad
{
public int Core { get; set; }
public int Usage { get; set; }
public float Usage { get; set; }
}

View File

@ -1,6 +1,28 @@
namespace MasstransferExporter.Stat.DTO;
using Newtonsoft.Json;
namespace MasstransferExporter.StatExporter.Model;
public class SystemStat
{
[JsonProperty("timestamp")] public DateTime Timestamp { get; set; }
[JsonProperty("cpuUsage")] public double CpuUsage { get; set; }
[JsonProperty("memoryUsage")] public double MemoryUsage { get; set; }
[JsonProperty("memoryTotal")] public double MemoryTotal { get; set; }
[JsonProperty("memoryFree")] public double MemoryFree { get; set; }
[JsonProperty("diskTotal")] public double DiskTotal { get; set; }
[JsonProperty("diskUsage")] public double DiskUsage { get; set; }
[JsonProperty("diskFree")] public double DiskFree { get; set; }
[JsonProperty("uploadRate")] public double UploadRate { get; set; }
[JsonProperty("downloadRate")] public double DownloadRate { get; set; }
[JsonProperty("networkLatency")] public double NetworkLatency { get; set; }
}

View File

@ -1,8 +1,10 @@
using System.Management;
using System.Diagnostics;
using System.Management;
using System.Net.NetworkInformation;
using MasstransferCommon.Utils;
using MasstransferCommon.Model.Constant;
using MasstransferCommunicate.Mqtt.Client;
using MasstransferExporter.Stat.DTO;
using Serilog;
using MasstransferExporter.StatExporter.Model;
namespace MasstransferExporter.StatExporter;
@ -15,24 +17,33 @@ public class SystemStatExporter
/// <summary>
/// 收集系统状态信息
/// </summary>
public static void Collect()
public static async Task ExportSystemStat()
{
try
{
var osInfo = CollectOsInformation();
var cpuLoad = CollectCpuStat();
var memoryStat = CollectMemoryStat();
var diskStat = CollectDiskStat();
var cpuLoad = CollectCpuStat();
var memoryStat = CollectMemoryStat();
var diskStats = CollectDiskStat();
Console.WriteLine(JsonUtil.ToJson(osInfo));
Console.WriteLine(JsonUtil.ToJson(cpuLoad));
Console.WriteLine(JsonUtil.ToJson(memoryStat));
Console.WriteLine(JsonUtil.ToJson(diskStat));
}
catch (Exception e)
var speed = MeasureNetworkSpeed();
var latency = GetNetworkLatency();
var stat = new SystemStat
{
Log.Error(e, "收集系统状态信息失败");
}
Timestamp = DateTime.Now,
CpuUsage = cpuLoad.Usage,
MemoryUsage = memoryStat.UsedMemory,
MemoryTotal = memoryStat.TotalMemory,
MemoryFree = memoryStat.AvailableMemory,
DiskTotal = diskStats.Sum(disk => disk.Total),
DiskUsage = diskStats.Sum(disk => disk.Used),
DiskFree = diskStats.Sum(disk => disk.Free),
UploadRate = speed.Item1,
DownloadRate = speed.Item2,
NetworkLatency = latency
};
// 将结果上传到云端
await MessageQueueHelper.Publish(Topics.ReportSystemStat, stat);
}
/// <summary>
@ -59,6 +70,7 @@ public class SystemStatExporter
};
}
/// <summary>
/// 收集CPU信息
/// </summary>
@ -69,16 +81,16 @@ public class SystemStatExporter
{
Core = Environment.ProcessorCount
};
// 获取每个处理器的使用率
var searcher = new ManagementObjectSearcher("select * from Win32_Processor");
foreach (var item in searcher.Get())
{
var loadPercentage = item["LoadPercentage"];
if (loadPercentage != null)
{
cpuLoad.Usage = (ushort)loadPercentage;
}
}
using var totalCpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
// 初始化计数器
totalCpuCounter.NextValue();
// 等待一秒以获取准确的读取值
Thread.Sleep(1000);
// 获取总 CPU 使用率
var totalCpuUsage = totalCpuCounter.NextValue();
cpuLoad.Usage = totalCpuUsage;
return cpuLoad;
}
@ -126,28 +138,64 @@ public class SystemStatExporter
}).ToList();
}
/// <summary>
/// 收集网络信息
/// </summary>
private static void CollectNetworkStat()
{
}
/// <summary>
/// 统计获取网络延时
/// </summary>
/// <param name="host"></param>
private static long GetNetworkLatency(string host)
private static long GetNetworkLatency()
{
try
{
var ping = new Ping();
var reply = ping.Send(host);
return reply.Status == IPStatus.Success ? reply.RoundtripTime : 999;
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces)
{
if (adapter.OperationalStatus != OperationalStatus.Up) continue;
var properties = adapter.GetIPProperties();
var dns = properties.DnsAddresses;
if (dns.Count <= 0) continue;
foreach (var host in dns)
{
var ping = new Ping();
var reply = ping.Send(host.MapToIPv4());
return reply.Status == IPStatus.Success ? reply.RoundtripTime : 999;
}
}
}
catch (Exception _)
{
return 999;
// ignored
}
return 999;
}
private static (double, double) MeasureNetworkSpeed()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces)
{
if (adapter.OperationalStatus != OperationalStatus.Up) continue;
var startReceivedBytes = adapter.GetIPv4Statistics().BytesReceived;
var startSentBytes = adapter.GetIPv4Statistics().BytesSent;
long totalReceivedBytes = 0;
long totalSentBytes = 0;
var times = 0;
while (times < 5)
{
var statistics = adapter.GetIPv4Statistics();
totalReceivedBytes = totalReceivedBytes + statistics.BytesReceived - startReceivedBytes;
totalSentBytes = totalSentBytes + statistics.BytesSent - startSentBytes;
Thread.Sleep(1000);
times++;
}
return (totalReceivedBytes / 5.0 / 1024.0 / 1024.0,
totalSentBytes / 5.0 / 1024.0 / 1024.0);
}
return (0, 0);
}
}