forked from wubbl0rz/VmChamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListCommand.cs
83 lines (67 loc) · 2.34 KB
/
ListCommand.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
using System.CommandLine;
using System.Net.NetworkInformation;
using ByteSizeLib;
using Spectre.Console;
using VmChamp;
public class ListCommand : Command
{
private readonly AppConfig _appConfig;
public ListCommand(AppConfig appConfig) : base("list", "list all existing vms")
{
_appConfig = appConfig;
var allVmDirectories = Directory.GetDirectories(appConfig.DataDir);
this.AddAlias("ps");
this.AddAlias("ls");
this.SetHandler(() =>
{
using var libvirtConnection = LibvirtConnection.CreateForSession();
var table = new Table();
table.AddColumn("VM");
table.AddColumn("User");
table.AddColumn("IP");
table.AddColumn("State");
table.AddColumn("Memory");
table.AddColumn("Disk");
table.AddColumn("vCPUs");
foreach (var vmDir in allVmDirectories)
{
var vmName = Path.GetFileName(vmDir);
var vmId = Interop.virDomainLookupByName(libvirtConnection.NativePtr, vmName);
var pinger = new Ping();
unsafe
{
var user = Helper.GetUserFromIso(vmDir);
var vmIpAddress = Interop.GetFirstIpById(vmId);
var stateInfo = new VirDomainInfo();
var blockInfo = new VirDomainBlockInfo();
Interop.virDomainGetInfo(vmId, &stateInfo);
Interop.virDomainGetBlockInfo(vmId, "vda", &blockInfo);
var pingAlive = "[grey]";
if (vmIpAddress is not null)
{
var pingReply = pinger.Send(vmIpAddress, 5);
pingAlive = pingReply.Status != IPStatus.Success ? "[red]" : "[green]";
}
var state = (VirDomainState)stateInfo.state;
var color = state switch
{
VirDomainState.Running => "[green]",
VirDomainState.Paused => "[yellow]",
_ => "[red]"
};
var curMemSize = ByteSize.FromKibiBytes(stateInfo.memory);
var curDiskSize = ByteSize.FromBytes(blockInfo.allocation);
var maxDiskSize = ByteSize.FromBytes(blockInfo.capacity);
table.AddRow(vmName,
user,
$"{pingAlive}{(vmIpAddress ?? "none")}[/]",
$"{color}{state}[/]",
$"{curMemSize:MiB}",
$"{curDiskSize:GiB}/{maxDiskSize:GiB}",
stateInfo.nrVirtCpu.ToString());
}
}
AnsiConsole.Write(table);
});
}
}