2

i'm want to get the total bandwidth used by a kvm/libvirt VM in C (language). is there function in libvirt?

so, for example if a VM crosses 1TB then i would suspend its network.

Shashwat shagun
  • 121
  • 1
  • 6

2 Answers2

2

In the libvirt XML you need to look at the element to identify the backend device name. eg

<interface type='network'>
  <mac address='52:54:00:b4:fc:f2'/>
  <source network='default' bridge='virbr0'/>
  <target dev='vnet2'/>
  <model type='virtio'/>
  <alias name='net0'/>
  <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

here the backend is 'vnet2'. Once you have that you can invoke the C API virDomainInterfaceStats (or via a language binding of your choice) to get the rx/tx stats. As an example using virsh tool:

# virsh domifstat demo vnet2
vnet2 rx_bytes 5040490379
vnet2 rx_packets 3292604
vnet2 rx_errs 0
vnet2 rx_drop 0
vnet2 tx_bytes 167286952
vnet2 tx_packets 1859239
vnet2 tx_errs 0
vnet2 tx_drop 0
DanielB
  • 2,461
  • 1
  • 10
  • 13
  • hi does rx_bytes shows the total data used since VM was created or just the current bandwidth usage? – Shashwat shagun Sep 21 '17 at 19:55
  • 1
    It is a cumulative total since the interface was created. If you want to see usage timeslice, you have to call the API once, wait a while, call it a second time, and calculate the change in value & divide by number of seconds. This gives you bytes/second or packets/second – DanielB Sep 22 '17 at 16:41
0

When you start a KVM guest the host system creates a vnet interface for each individual network interface within the guest, for example vnet3 vnet4. After that you can monitor the send / received amount of those interfaces by polling the files on the host machine :

cat /sys/class/net/vnet3/statistics/rx_bytes
173110677
cat /sys/class/net/vnet3/statistics/tx_bytes
1640468389

Alternatively you can set up iptables rules with fwmark like in this tutorial :
http://www.tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.netfilter.html
and measure the stats with iptables, but I guess that would be too much of a hassle in C.

bocian85
  • 130
  • 2