xref: /kvmtool/builtin-stat.c (revision 4b1addaeed6f8c717b2b818e3f867829849d8e86)
1 #include <kvm/util.h>
2 #include <kvm/kvm-cmd.h>
3 #include <kvm/builtin-stat.h>
4 #include <kvm/kvm.h>
5 #include <kvm/parse-options.h>
6 #include <kvm/kvm-ipc.h>
7 
8 #include <stdio.h>
9 #include <string.h>
10 #include <signal.h>
11 
12 struct stat_cmd {
13 	u32 type;
14 	u32 len;
15 };
16 
17 static bool mem;
18 static bool all;
19 static int instance;
20 static const char *instance_name;
21 
22 static const char * const stat_usage[] = {
23 	"kvm stat [command] [--all] [-n name]",
24 	NULL
25 };
26 
27 static const struct option stat_options[] = {
28 	OPT_GROUP("Commands options:"),
29 	OPT_BOOLEAN('m', "memory", &mem, "Display memory statistics"),
30 	OPT_GROUP("Instance options:"),
31 	OPT_BOOLEAN('a', "all", &all, "All instances"),
32 	OPT_STRING('n', "name", &instance_name, "name", "Instance name"),
33 	OPT_END()
34 };
35 
36 static void parse_stat_options(int argc, const char **argv)
37 {
38 	while (argc != 0) {
39 		argc = parse_options(argc, argv, stat_options, stat_usage,
40 				PARSE_OPT_STOP_AT_NON_OPTION);
41 		if (argc != 0)
42 			kvm_stat_help();
43 	}
44 }
45 
46 void kvm_stat_help(void)
47 {
48 	usage_with_options(stat_usage, stat_options);
49 }
50 
51 static int do_memstat(const char *name, int sock)
52 {
53 	struct stat_cmd cmd = {KVM_IPC_STAT, 0};
54 	int r;
55 
56 	printf("Sending memstat command to %s, output should be on the targets' terminal.\n", name);
57 
58 	r = write(sock, &cmd, sizeof(cmd));
59 	if (r < 0)
60 		return r;
61 
62 	return 0;
63 }
64 
65 int kvm_cmd_stat(int argc, const char **argv, const char *prefix)
66 {
67 	parse_stat_options(argc, argv);
68 
69 	if (!mem)
70 		usage_with_options(stat_usage, stat_options);
71 
72 	if (mem && all)
73 		return kvm__enumerate_instances(do_memstat);
74 
75 	if (instance_name == NULL &&
76 	    instance == 0)
77 		kvm_stat_help();
78 
79 	if (instance_name)
80 		instance = kvm__get_sock_by_instance(instance_name);
81 
82 	if (instance <= 0)
83 		die("Failed locating instance");
84 
85 	if (mem)
86 		return do_memstat(instance_name, instance);
87 
88 	return 0;
89 }
90