2024-06-28 12:06:36 +03:00

127 lines
3.6 KiB
C#

using Esiur.Core;
using Esiur.Data;
using Esiur.Resource;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Timers;
namespace AZ.Compute.Agent
{
[Resource]
public partial class Node
{
System.Timers.Timer timer;
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
NetworkInterface nic;
ulong totalNetworkBytes;
const double nicSpeed = 1 * 1024 * 1024; // 1 MBps
[Export] string id;
[Export] string ip;
[Export] float cpu;
[Export] float ram;
[Export] float network;
[Export] uint tasks;
[Export] uint cpuClock;
[Export] uint cpuMaxClock;
[Export] float networkSpeed;
[Export] Job[] jobs=new Job[0];
[Export]
public async AsyncReply<Job> Compute(string fileName, string arguments)
{
var psi = new ProcessStartInfo()
{
FileName = fileName,
Arguments = arguments
};
var p = Process.Start(psi);
var job = await Warehouse.New<Job>(fileName, null, this);
job.Process = p;
Jobs = jobs.Append(job).ToArray();
return job;
}
public Node()
{
Id = System.Environment.MachineName;
nic = NetworkInterface.GetAllNetworkInterfaces().Where(x => x.OperationalStatus == OperationalStatus.Up).First();
networkSpeed = (float)(nic.Speed / 1048576.0);
totalNetworkBytes = (ulong)nic.GetIPv4Statistics().BytesReceived + (ulong)nic.GetIPv4Statistics().BytesSent;
Ip = nic.GetIPProperties().UnicastAddresses.First(x=> x.Address.AddressFamily == AddressFamily.InterNetwork).Address.ToString();
using (ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'"))
{
cpuClock = (uint)(Mo["CurrentClockSpeed"]);
cpuMaxClock = (uint)(Mo["MaxClockSpeed"]);
}
//foreach (ManagementObject obj in new ManagementObjectSearcher("SELECT *, Name FROM Win32_Processor").Get())
//{
// double maxSpeed = Convert.ToDouble(obj["MaxClockSpeed"]) / 1000;
// double turboSpeed = maxSpeed * cpuValue / 100;
// return string.Format("{0} Running at {1:0.00}Ghz, Turbo Speed: {2:0.00}Ghz", obj["Name"], maxSpeed, turboSpeed);
//}
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
timer = new System.Timers.Timer();
timer.Elapsed += Timer_Elapsed;
timer.Interval = 5000;
timer.Start();
}
private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
{
try
{
var ntb = (ulong)nic.GetIPv4Statistics().BytesReceived + (ulong)nic.GetIPv4Statistics().BytesSent;
Network = (float)(((ntb - totalNetworkBytes) / 5.0) / nicSpeed);
totalNetworkBytes = ntb;
Cpu = cpuCounter.NextValue();
Ram = ramCounter.NextValue();
foreach (Job job in jobs)
{
job.Ram = (float)(job.Process.PeakWorkingSet64 / 1048576.0);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}