0
votes

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.

1
You're probably going to get better answers on serverfault.com, and they might be about SNMP. Good luck. - Anders R. Bystrup
Will check that out. Thanks @AndersR.Bystrup! - user3752288
With KVM virtualization, every virtual machine is simply a process in the host's process list, so top or other "standard" tools will tell you CPU/memory usage for that process/VM. If you want graphs, nmon may be a good place to start. - twalberg
Thanks for the info @twalberg. But I'm just really interested in getting the CPU usage of the VMs. Is there a way to extract the cpu usage from the command line (through the top command)? Or an easier way to understand my question would be, how does KVM produces the graph of cpu usage? Thanks again. Appreciate it! - user3752288

1 Answers

2
votes

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