-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMemoryMetrics.cs
88 lines (71 loc) · 2.57 KB
/
MemoryMetrics.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace SystemUsage
{
public class MemoryMetrics
{
public double Total;
public double Used;
public double Free;
}
public class MemoryMetricsClient
{
public MemoryMetrics GetMetrics()
{
if (IsUnix())
{
return GetUnixMetrics();
}
return GetWindowsMetrics();
}
private bool IsUnix()
{
var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ||
RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
return isUnix;
}
private MemoryMetrics GetWindowsMetrics()
{
var output = "";
var info = new ProcessStartInfo();
info.FileName = "wmic";
info.Arguments = "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value";
info.RedirectStandardOutput = true;
using (var process = Process.Start(info))
{
output = process.StandardOutput.ReadToEnd();
}
var lines = output.Trim().Split("\n");
var freeMemoryParts = lines[0].Split("=", StringSplitOptions.RemoveEmptyEntries);
var totalMemoryParts = lines[1].Split("=", StringSplitOptions.RemoveEmptyEntries);
var metrics = new MemoryMetrics();
metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
metrics.Used = metrics.Total - metrics.Free;
return metrics;
}
private MemoryMetrics GetUnixMetrics()
{
var output = "";
var info = new ProcessStartInfo("df -Bm > text");
info.FileName = "/bin/bash";
info.Arguments = "-c \"df -Bm > text\"";
info.RedirectStandardOutput = true;
using (var process = Process.Start(info))
{
output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
}
var lines = output.Split("\n");
var memory = lines[1].Split(" ", StringSplitOptions.RemoveEmptyEntries);
var metrics = new MemoryMetrics();
metrics.Total = double.Parse(memory[1]);
metrics.Used = double.Parse(memory[2]);
metrics.Free = double.Parse(memory[3]);
return metrics;
}
}
}