-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinuxTelemetry.cs
More file actions
557 lines (498 loc) · 24.8 KB
/
Copy pathLinuxTelemetry.cs
File metadata and controls
557 lines (498 loc) · 24.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
using System.Diagnostics;
using System.Globalization;
using System.Net.Http.Json;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace TuringMonitor;
public record WeatherStats(float Temp, string IconId);
internal record WeatherCacheEntry(float Temp, string IconId, DateTime UpdatedAt);
[JsonSerializable(typeof(JsonElement))]
[JsonSerializable(typeof(WeatherCacheEntry))]
internal partial class WeatherJsonContext : JsonSerializerContext { }
public class LinuxTelemetry : ITelemetry
{
private readonly ILogger<LinuxTelemetry> _logger;
private long _lastUser, _lastNice, _lastSys, _lastIdle, _lastIo, _lastIrq, _lastSoft;
private string? _cpuTempPath;
private string? _cpuPowerPath;
private long _lastEnergyUj;
private DateTime _lastEnergyTime;
private string? _netInterface;
private long _lastNetInBytes, _lastNetOutBytes;
private DateTime _lastNetTime;
private readonly HttpClient _http;
private WeatherStats? _lastWeather;
private DateTime _lastWeatherUpdate = DateTime.MinValue;
private volatile bool _weatherFetching;
private int _weatherFetchAttempts;
private DateTime _nextAllowedFetch = DateTime.MinValue;
private string _weatherApi = "openmeteo";
private string? _openWeatherApiKey;
private string? _lastLoggedWeatherApi;
private volatile bool _openWeatherFailedPermanent;
// Persisted weather cache location. Prefer /var/lib/turing-monitor (FHS-canonical for service
// state); fall back to user home when not running as a service / not writable.
private static readonly string WeatherCacheFile = ResolveWeatherCacheFile();
private static string ResolveWeatherCacheFile()
{
var serviceDir = "/var/lib/turing-monitor";
try {
if (!Directory.Exists(serviceDir))
Directory.CreateDirectory(serviceDir);
// Quick writability probe
var probe = Path.Combine(serviceDir, ".wprobe");
File.WriteAllText(probe, "x");
File.Delete(probe);
return Path.Combine(serviceDir, "weather.json");
}
catch {
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (string.IsNullOrEmpty(home)) home = "/tmp";
return Path.Combine(home, ".turing-monitor-weather.json");
}
}
private const double WeatherCacheTtlMinutes = 30.0;
private const int WeatherMaxRetries = 5;
private static readonly TimeSpan[] WeatherRetryBackoff =
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(20),
TimeSpan.FromSeconds(40),
TimeSpan.FromSeconds(80)
};
private DateTime _lastGpuStatsTime = DateTime.MinValue;
private (float Load, float Temp, float Power, float VramUsed, float VramTotal) _lastGpuStats;
public string CpuName { get; private set; } = "Unknown CPU";
public string GpuName { get; private set; } = "Unknown GPU";
public string GpuModel { get; private set; } = "Unknown GPU";
public LinuxTelemetry(ILogger<LinuxTelemetry> logger, IOptions<TuringMonitorOptions>? options = null, HttpClient? http = null)
{
_logger = logger;
_http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
_openWeatherApiKey = options?.Value.OpenWeatherApiKey;
FindCpuTempPath();
FindCpuPowerPath();
FindActiveNetInterface();
SeedCpuUsage();
CpuName = GetCpuFriendlyName();
GpuName = GetGpuFullName();
GpuModel = GetGpuShortName(GpuName);
LoadPersistedWeather();
}
private void LoadPersistedWeather()
{
try {
if (!File.Exists(WeatherCacheFile)) return;
var entry = JsonSerializer.Deserialize(WeatherCacheFile, WeatherJsonContext.Default.WeatherCacheEntry);
if (entry == null) return;
var age = DateTime.Now - entry.UpdatedAt;
// Only reuse cache if it's less than 6h old (avoid showing very stale data forever)
if (age.TotalHours < 6) {
_lastWeather = new WeatherStats(entry.Temp, entry.IconId);
_lastWeatherUpdate = entry.UpdatedAt;
_logger.LogInformation("Restored persisted weather cache: {Temp}C {Icon} (age {Age:g})", entry.Temp, entry.IconId, age);
}
}
catch (Exception ex) {
_logger.LogDebug(ex, "Failed to load persisted weather cache");
}
}
private void PersistWeather()
{
if (_lastWeather == null) return;
try {
var entry = new WeatherCacheEntry(_lastWeather.Temp, _lastWeather.IconId, _lastWeatherUpdate);
var dir = Path.GetDirectoryName(WeatherCacheFile);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(WeatherCacheFile, JsonSerializer.Serialize(entry, WeatherJsonContext.Default.WeatherCacheEntry));
}
catch (Exception ex) {
_logger.LogDebug(ex, "Failed to persist weather cache");
}
}
public void ConfigureWeather(string api, string? key)
{
var normalized = (api ?? "openmeteo").Trim().ToLowerInvariant();
if (normalized != "openmeteo" && normalized != "openweather" && normalized != "openweathermap")
{
_logger.LogError("Unknown weather_api '{Api}'; using Open-Meteo. Valid: openmeteo, openweather, openweathermap", api);
normalized = "openmeteo";
}
if (normalized == "openweathermap") normalized = "openweather";
_weatherApi = normalized;
if (!string.IsNullOrEmpty(key)) _openWeatherApiKey = key;
if (_lastLoggedWeatherApi != _weatherApi)
{
_lastLoggedWeatherApi = _weatherApi;
_logger.LogInformation("Weather provider selected: {Provider}", _weatherApi);
}
}
public Task<WeatherStats> GetWeatherAsync(double lat, double lon)
{
var now = DateTime.Now;
// While a fetch with retries is in flight, just return current cached value
if (_weatherFetching)
return Task.FromResult(_lastWeather ?? new WeatherStats(0, "01d"));
// Decide when the next refresh should happen.
// If we have never successfully fetched, retry aggressively (every 5s the caller loop
// will land here, but we gate it via _nextAllowedFetch to honor the in-flight retry backoff).
if (_lastWeather == null) {
// No cached data yet: trigger fetch immediately if no retry backoff in effect
if (now >= _nextAllowedFetch) {
_weatherFetching = true;
bool useOpenWeather = ShouldUseOpenWeather();
_ = useOpenWeather
? FetchWithRetryAsync(lat, lon, FetchOpenWeatherAsync)
: FetchWithRetryAsync(lat, lon, FetchOpenMeteoAsync);
}
return Task.FromResult(_lastWeather ?? new WeatherStats(0, "01d"));
}
// We have a cached value: refresh on the 30-minute interval (continuous from last successful fetch)
if (now - _lastWeatherUpdate >= TimeSpan.FromMinutes(WeatherCacheTtlMinutes)) {
_weatherFetching = true;
bool useOpenWeather = ShouldUseOpenWeather();
_ = useOpenWeather
? FetchWithRetryAsync(lat, lon, FetchOpenWeatherAsync)
: FetchWithRetryAsync(lat, lon, FetchOpenMeteoAsync);
}
return Task.FromResult(_lastWeather);
}
private bool ShouldUseOpenWeather()
{
if (_weatherApi != "openweather" || _openWeatherFailedPermanent)
return false;
if (string.IsNullOrEmpty(_openWeatherApiKey)) {
_logger.LogError("OpenWeather selected but no API key found; falling back to Open-Meteo");
_openWeatherFailedPermanent = true;
return false;
}
return true;
}
// Fetch once with the configured retry + exponential backoff strategy.
// On the first success, caches the value and stops retrying.
// If all attempts fail, schedules the next allowed fetch using the last backoff delay
// so the outer loop does not spin tightly.
private async Task FetchWithRetryAsync(
double lat, double lon,
Func<double, double, Task<bool>> fetchOnce)
{
_weatherFetchAttempts = 0;
try {
for (int attempt = 0; attempt <= WeatherMaxRetries; attempt++) {
_weatherFetchAttempts = attempt;
try {
bool ok = await fetchOnce(lat, lon);
if (ok) {
// Success: persist + reset backoff gating
PersistWeather();
_nextAllowedFetch = DateTime.MinValue;
return;
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) {
_logger.LogDebug(ex, "Weather fetch attempt {Attempt}/{Max} failed", attempt + 1, WeatherMaxRetries + 1);
}
if (attempt < WeatherMaxRetries) {
var delay = WeatherRetryBackoff[Math.Min(attempt, WeatherRetryBackoff.Length - 1)];
_logger.LogDebug("Weather fetch retry {Attempt}/{Max}: backing off for {Delay:g}",
attempt + 2, WeatherMaxRetries + 1, delay);
await Task.Delay(delay);
}
}
// All retries exhausted: schedule next allowed fetch after the largest backoff
// so the caller loop does not hammer the API every second.
_nextAllowedFetch = DateTime.Now + WeatherRetryBackoff[^1];
_logger.LogWarning("Weather fetch failed after {Count} attempts; next attempt gated until {Until:g}",
WeatherMaxRetries + 1, _nextAllowedFetch);
}
catch (OperationCanceledException) { /* shutting down */ }
catch (Exception ex) {
_logger.LogError(ex, "Unexpected error in FetchWithRetryAsync");
_nextAllowedFetch = DateTime.Now + WeatherRetryBackoff[^1];
}
finally {
_weatherFetching = false;
}
}
// Returns true on success (cache updated), false on transient/any failure (caller will retry/backoff).
private async Task<bool> FetchOpenMeteoAsync(double lat, double lon)
{
try {
var url = $"https://api.open-meteo.com/v1/forecast?latitude={lat.ToString(CultureInfo.InvariantCulture)}&longitude={lon.ToString(CultureInfo.InvariantCulture)}¤t=temperature_2m,weather_code,is_day";
var response = await _http.GetFromJsonAsync(url, WeatherJsonContext.Default.JsonElement);
if (response.ValueKind != JsonValueKind.Undefined && response.TryGetProperty("current", out var current)) {
float temp = current.GetProperty("temperature_2m").GetSingle();
int wmo = current.GetProperty("weather_code").GetInt32();
int isDay = current.GetProperty("is_day").GetInt32();
string iconId = MapWmoToOwm(wmo, isDay == 1);
_lastWeather = new WeatherStats(temp, iconId);
_lastWeatherUpdate = DateTime.Now;
_logger.LogInformation("Open-Meteo weather fetched: {Temp}C {Icon}", temp, iconId);
return true;
}
_logger.LogWarning("Open-Meteo returned empty response");
return false;
}
catch (Exception ex) {
_logger.LogDebug(ex, "Open-Meteo fetch failed");
return false;
}
}
// Returns true on success, false on transient/any failure (caller will retry/backoff).
private async Task<bool> FetchOpenWeatherAsync(double lat, double lon)
{
try {
var url = $"https://api.openweathermap.org/data/2.5/weather?lat={lat.ToString(CultureInfo.InvariantCulture)}&lon={lon.ToString(CultureInfo.InvariantCulture)}&units=metric&appid={_openWeatherApiKey}";
using var resp = await _http.GetAsync(url);
if (resp.StatusCode == HttpStatusCode.Unauthorized) {
_logger.LogError("OpenWeather API key invalid (401); falling back to Open-Meteo permanently");
_openWeatherFailedPermanent = true;
// Immediate fallback to Open-Meteo for this attempt
return await FetchOpenMeteoAsync(lat, lon);
}
if ((int)resp.StatusCode >= 500) {
_logger.LogDebug("OpenWeather transient failure (HTTP {Status}); will retry", (int)resp.StatusCode);
return false;
}
resp.EnsureSuccessStatusCode();
var response = await resp.Content.ReadFromJsonAsync(WeatherJsonContext.Default.JsonElement);
if (response.ValueKind != JsonValueKind.Undefined) {
float temp = response.GetProperty("main").GetProperty("temp").GetSingle();
string iconId = response.GetProperty("weather")[0].GetProperty("icon").GetString() ?? "01d";
_lastWeather = new WeatherStats(temp, iconId);
_lastWeatherUpdate = DateTime.Now;
_logger.LogInformation("OpenWeather weather fetched: {Temp}C {Icon}", temp, iconId);
return true;
}
_logger.LogWarning("OpenWeather returned empty response");
return false;
}
catch (TaskCanceledException) {
_logger.LogDebug("OpenWeather transient failure (timeout); will retry");
return false;
}
catch (HttpRequestException ex) {
_logger.LogDebug("OpenWeather transient failure (network); will retry: {Msg}", ex.Message);
return false;
}
catch (Exception ex) {
_logger.LogDebug(ex, "OpenWeather transient failure; will retry");
return false;
}
}
private string MapWmoToOwm(int wmo, bool isDay)
{
string id = wmo switch {
0 => "01",
1 or 2 => "02",
3 => "03",
45 or 48 => "50",
51 or 53 or 55 or 56 or 57 => "09",
61 or 63 or 65 or 66 or 67 => "10",
71 or 73 or 75 or 77 => "13",
80 or 81 or 82 => "09",
85 or 86 => "13",
95 or 96 or 99 => "11",
_ => "01"
};
return id + (isDay ? "d" : "n");
}
public (float InMbps, float OutMbps) GetNetStats()
{
try {
if (_netInterface == null) return (0, 0);
var lines = File.ReadAllLines("/proc/net/dev");
var line = lines.FirstOrDefault(l => l.Trim().StartsWith(_netInterface + ":"));
if (line == null) return (0, 0);
var stats = line.Split(':')[1].Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
long currentIn = long.Parse(stats[0]), currentOut = long.Parse(stats[8]);
DateTime currentTime = DateTime.Now;
double diffSeconds = (currentTime - _lastNetTime).TotalSeconds;
if (diffSeconds <= 0) return (0, 0);
float inMbps = (float)(((currentIn - _lastNetInBytes) * 8) / 1024.0 / 1024.0 / diffSeconds);
float outMbps = (float)(((currentOut - _lastNetOutBytes) * 8) / 1024.0 / 1024.0 / diffSeconds);
_lastNetInBytes = currentIn; _lastNetOutBytes = currentOut; _lastNetTime = currentTime;
return (Math.Max(0, inMbps), Math.Max(0, outMbps));
}
catch (Exception ex) { _logger.LogWarning(ex, "GetNetStats failed"); return (0, 0); }
}
private string GetGpuFullName()
{
try {
var psi = new ProcessStartInfo("nvidia-smi", "--query-gpu=name --format=csv,noheader") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true };
using var proc = Process.Start(psi);
if (proc != null) {
if (!proc.WaitForExit(5000)) { try { proc.Kill(); } catch { } _logger.LogWarning("nvidia-smi (name) timed out"); return "NVIDIA GPU"; }
return proc.StandardOutput.ReadToEnd().Trim();
}
}
catch (Exception ex) { _logger.LogDebug(ex, "nvidia-smi not available for GPU name"); }
return "NVIDIA GPU";
}
private string GetGpuShortName(string fullName) => fullName.Replace("NVIDIA GeForce ", "").Replace("NVIDIA ", "").Replace("Graphics Card", "").Trim();
public (float Load, float Temp, float Power, float VramUsed, float VramTotal) GetGpuStats()
{
try {
if (DateTime.Now - _lastGpuStatsTime < TimeSpan.FromSeconds(3) && _lastGpuStatsTime != DateTime.MinValue)
return _lastGpuStats;
var psi = new ProcessStartInfo("nvidia-smi", "--query-gpu=utilization.gpu,temperature.gpu,power.draw,memory.used,memory.total --format=csv,noheader,nounits") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true };
using var proc = Process.Start(psi);
if (proc != null) {
if (!proc.WaitForExit(5000)) { try { proc.Kill(); } catch { } _logger.LogWarning("nvidia-smi (stats) timed out"); return (0, 0, 0, 0, 0); }
var output = proc.StandardOutput.ReadToEnd().Trim();
var parts = output.Split(',');
if (parts.Length >= 5) {
_lastGpuStats = (float.Parse(parts[0], CultureInfo.InvariantCulture), float.Parse(parts[1], CultureInfo.InvariantCulture), float.Parse(parts[2], CultureInfo.InvariantCulture), float.Parse(parts[3], CultureInfo.InvariantCulture), float.Parse(parts[4], CultureInfo.InvariantCulture));
_lastGpuStatsTime = DateTime.Now;
return _lastGpuStats;
}
}
}
catch (Exception ex) { _logger.LogWarning(ex, "GetGpuStats failed"); }
return (0, 0, 0, 0, 0);
}
private void FindCpuPowerPath()
{
try {
var path = "/sys/class/powercap/intel-rapl:0/energy_uj";
if (File.Exists(path)) { _cpuPowerPath = path; _lastEnergyUj = long.Parse(File.ReadAllText(path)); _lastEnergyTime = DateTime.Now; }
}
catch (Exception ex) { _logger.LogDebug(ex, "FindCpuPowerPath failed"); }
}
public float GetCpuPower()
{
try {
if (_cpuPowerPath == null) return 0;
long currentEnergy = long.Parse(File.ReadAllText(_cpuPowerPath));
DateTime currentTime = DateTime.Now;
double diffJoules = (currentEnergy - _lastEnergyUj) / 1_000_000.0;
double diffSeconds = (currentTime - _lastEnergyTime).TotalSeconds;
if (diffSeconds <= 0) return 0;
float watts = (float)(diffJoules / diffSeconds);
_lastEnergyUj = currentEnergy; _lastEnergyTime = currentTime;
return Math.Clamp(watts, 0, 500);
}
catch (Exception ex) { _logger.LogWarning(ex, "GetCpuPower failed"); return 0; }
}
public float GetCpuClock()
{
try {
var sysfs = "/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq";
if (File.Exists(sysfs))
return float.Parse(File.ReadAllText(sysfs).Trim(), CultureInfo.InvariantCulture) / 1000f;
var lines = File.ReadAllLines("/proc/cpuinfo");
return lines.Where(l => l.Contains("cpu MHz")).Select(l => { float.TryParse(l.Split(':')[1].Trim(), CultureInfo.InvariantCulture, out float mhz); return mhz; }).DefaultIfEmpty(0).Max();
}
catch (Exception ex) { _logger.LogWarning(ex, "GetCpuClock failed"); return 0; }
}
private string GetCpuFriendlyName()
{
try {
var lines = File.ReadAllLines("/proc/cpuinfo");
var modelLine = lines.FirstOrDefault(l => l.Contains("model name"));
if (modelLine != null) return modelLine.Split(':')[1].Trim().Replace("Processor", "").Replace("16-Core", "").Trim();
}
catch (Exception ex) { _logger.LogDebug(ex, "GetCpuFriendlyName failed"); }
return "Generic CPU";
}
private void FindCpuTempPath()
{
try {
var hwmonDir = "/sys/class/hwmon";
if (!Directory.Exists(hwmonDir)) return;
foreach (var dir in Directory.GetDirectories(hwmonDir)) {
var name = File.ReadAllText(Path.Combine(dir, "name")).Trim();
if (name == "k10temp" || name == "coretemp") { var tctl = Path.Combine(dir, "temp1_input"); if (File.Exists(tctl)) { _cpuTempPath = tctl; break; } }
}
}
catch (Exception ex) { _logger.LogDebug(ex, "FindCpuTempPath failed"); }
}
private void SeedCpuUsage()
{
try {
var lines = File.ReadAllLines("/proc/stat");
var cpuLine = lines.FirstOrDefault(l => l.StartsWith("cpu "));
if (cpuLine == null) return;
var parts = cpuLine.Split(' ', StringSplitOptions.RemoveEmptyEntries);
_lastUser = long.Parse(parts[1]); _lastNice = long.Parse(parts[2]); _lastSys = long.Parse(parts[3]);
_lastIdle = long.Parse(parts[4]); _lastIo = long.Parse(parts[5]); _lastIrq = long.Parse(parts[6]); _lastSoft = long.Parse(parts[7]);
}
catch (Exception ex) { _logger.LogDebug(ex, "SeedCpuUsage failed"); }
}
public float GetCpuUsage()
{
try {
var lines = File.ReadAllLines("/proc/stat");
var cpuLine = lines.FirstOrDefault(l => l.StartsWith("cpu "));
if (cpuLine == null) return 0;
var parts = cpuLine.Split(' ', StringSplitOptions.RemoveEmptyEntries);
long user = long.Parse(parts[1]), nice = long.Parse(parts[2]), sys = long.Parse(parts[3]), idle = long.Parse(parts[4]), iowait = long.Parse(parts[5]), irq = long.Parse(parts[6]), softirq = long.Parse(parts[7]);
long totalTime = user + nice + sys + idle + iowait + irq + softirq;
long idleTime = idle + iowait;
long totalDiff = totalTime - (_lastUser + _lastNice + _lastSys + _lastIdle + _lastIo + _lastIrq + _lastSoft);
long idleDiff = idleTime - (_lastIdle + _lastIo);
_lastUser = user; _lastNice = nice; _lastSys = sys; _lastIdle = idle; _lastIo = iowait; _lastIrq = irq; _lastSoft = softirq;
return totalDiff == 0 ? 0 : Math.Clamp((float)(totalDiff - idleDiff) / totalDiff * 100, 0, 100);
}
catch (Exception ex) { _logger.LogWarning(ex, "GetCpuUsage failed"); return 0; }
}
public (float UsedGb, float TotalGb) GetRamUsage()
{
try {
var lines = File.ReadAllLines("/proc/meminfo");
float total = 0, free = 0, buffers = 0, cached = 0;
foreach (var line in lines) {
if (total != 0 && free != 0 && buffers != 0 && cached != 0) break;
if (line.StartsWith("MemTotal:")) total = ParseKb(line);
else if (line.StartsWith("MemFree:")) free = ParseKb(line);
else if (line.StartsWith("Buffers:")) buffers = ParseKb(line);
else if (line.StartsWith("Cached:")) cached = ParseKb(line);
}
return ((total - (free + buffers + cached)) / 1024 / 1024, total / 1024 / 1024);
}
catch (Exception ex) { _logger.LogWarning(ex, "GetRamUsage failed"); return (0, 0); }
}
private void FindActiveNetInterface()
{
try {
var lines = File.ReadAllLines("/proc/net/dev");
foreach (var line in lines.Skip(2)) {
var parts = line.Split(':', StringSplitOptions.TrimEntries);
if (parts.Length < 2 || parts[0] == "lo") continue;
var operstatePath = $"/sys/class/net/{parts[0]}/operstate";
if (File.Exists(operstatePath)) {
var state = File.ReadAllText(operstatePath).Trim();
if (state != "up") continue;
}
_netInterface = parts[0];
var stats = parts[1].Split(' ', StringSplitOptions.RemoveEmptyEntries);
_lastNetInBytes = long.Parse(stats[0]); _lastNetOutBytes = long.Parse(stats[8]); _lastNetTime = DateTime.Now;
break;
}
}
catch (Exception ex) { _logger.LogDebug(ex, "FindActiveNetInterface failed"); }
}
private static float ParseKb(string line)
{
var span = line.AsSpan();
int start = 0;
while (start < span.Length && !char.IsDigit(span[start])) start++;
int end = start;
while (end < span.Length && char.IsDigit(span[end])) end++;
if (start < end && float.TryParse(span.Slice(start, end - start), CultureInfo.InvariantCulture, out float val)) return val;
return 0;
}
public float GetCpuTemp()
{
try {
return (_cpuTempPath != null && File.Exists(_cpuTempPath)) ? float.Parse(File.ReadAllText(_cpuTempPath), CultureInfo.InvariantCulture) / 1000 : 0;
}
catch (Exception ex) { _logger.LogWarning(ex, "GetCpuTemp failed"); return 0; }
}
}