Reputation: 11
Is there any way to get the cpu usage and memory usage of a vm in KVM without connecting to the guest through SSH? I mean, how does the Virtual Machine Manager get the CPU usage (graph)? I need the percentage of the cpu usage and memory as well. Does anyone know how to communicate with kvm through libvirt? I just really need to get the cpu usage and memory without SSH as much as possible.
Scenario: I am trying to build a set up that contains load balancer(host) + 3 servers(VMs) then it would notify me the cpu usage of the 3 servers so that if I need to provision another server, I would know when.
Thanks for you help. Really appreciate it.
Upvotes: 0
Views: 7784
Reputation: 311407
You can use the virDomainGetInfo function from libvirt to get information about the memory and cpu time consumed by a domain.
Here's a very simple example:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libvirt/libvirt.h>
int main(int argc, char **argv) {
virConnectPtr c;
virDomainPtr d;
virDomainInfo di;
int res;
int domid;
domid = atoi(argv[1]);
c = virConnectOpen(NULL);
d = virDomainLookupByID(c, domid);
res = virDomainGetInfo(d, &di);
printf("res = %d\n", res);
printf("memory used = %ld\n", di.memory);
printf("cpu time used = %ld\n", di.cpuTime);
}
UPDATE
I'm sure that if you examined the source for, e.g., virt-manager
, you will find that it uses exactly these functions to generate the various graphs to which you refer in your question. You can determine cpu "usage" by seeing how much the "cpu time" value changes over time.
If you're just looking for something like the % of the host cpu that domain is using, you can just use ps
. That is, if the corresponding qemu
process is 19650, you can run:
$ ps -p 19650 -o pid,%cpu
PID %CPU
19650 10.2
Upvotes: 2