Projet

Général

Profil

Paste
Télécharger au format
Statistiques
| Branche: | Révision:

root / plugins / libvirt / kvm_cpu @ a7139bca

Historique | Voir | Annoter | Télécharger (3,13 ko)

1 a7139bca Lars Kruse
#!/usr/bin/env python
2 dda92e9b Rodolphe Qui?deville
# -*- coding: utf-8 -*-
3
# vim: set fileencoding=utf-8
4
#
5
# Munin plugin to show CPU used by vm
6
#
7
# Copyright Maxence Dunnewind, Rodolphe Quiédeville
8
#
9
# License : GPLv3
10
#
11
# parsed environment variables:
12
# vmsuffix: part of vm name to be removed
13
#
14
#%# capabilities=autoconf
15
#%# family=contrib
16
17
import re, os, sys
18
from subprocess import Popen, PIPE
19
20
def config(vm_names):
21
    ''' Print the plugin's config
22
    @param vm_names : a list of "cleaned" vms' name
23
    '''
24 e78a1590 loic
    percent = len(filter(lambda x: x[0:3] == 'cpu' and x[3] != ' ', open('/proc/stat', 'r').readlines())) * 100
25
26 dda92e9b Rodolphe Qui?deville
    base_config = """graph_title KVM Virtual Machine CPU usage
27 e78a1590 loic
graph_vlabel %%
28 33e95e6f Lars Kruse
graph_category virtualization
29 e78a1590 loic
graph_scale no
30
graph_period second
31 dda92e9b Rodolphe Qui?deville
graph_info This graph shows the current CPU used by virtual machines
32 e78a1590 loic
graph_args --base 1000 -r --lower-limit 0 --upper-limit %d""" % percent
33 dda92e9b Rodolphe Qui?deville
    print base_config
34
    draw = "AREA"
35
    for vm in vm_names:
36
        print "%s_cpu.label %s" % (vm, vm)
37
        print "%s_cpu.min 0" % vm
38 e78a1590 loic
        print "%s_cpu.type DERIVE" % vm
39 dda92e9b Rodolphe Qui?deville
        print "%s_cpu.draw %s" % (vm, draw)
40
        print "%s_cpu.info percent of cpu time used by virtual machine" % vm
41
	draw = "STACK"
42
43
44
def clean_vm_name(vm_name):
45
    ''' Replace all special chars
46
    @param vm_name : a vm's name
47
    @return cleaned vm's name
48
    '''
49
50
    # suffix part defined in conf
51
    suffix = os.getenv('vmsuffix')
52
    if suffix:
53
        vm_name = re.sub(suffix,'',vm_name)
54
55 225a9156 Bianco Veigel
    # proxmox uses kvm with -name parameter
56 113008b0 Bianco Veigel
    parts = vm_name.split('\x00')
57
    if (parts[0].endswith('kvm')):
58
        try:
59
            return parts[parts.index('-name')+1]
60
        except ValueError:
61
            pass
62
63 dda92e9b Rodolphe Qui?deville
    return re.sub(r"[^a-zA-Z0-9_]", "_", vm_name)
64
65
def detect_kvm():
66
    ''' Check if kvm is installed
67
    '''
68
    kvm = Popen("which kvm", shell=True, stdout=PIPE)
69
    kvm.communicate()
70
    return not bool(kvm.returncode)
71
72
def find_vm_names(pids):
73
    '''Find and clean vm names from pids
74 8713eb37 Lars Kruse
    @return a dictionary of {pids : cleaned vm name}
75 dda92e9b Rodolphe Qui?deville
    '''
76
    result = {}
77
    for pid in pids:
78
        cmdline = open("/proc/%s/cmdline" % pid, "r")
79 c4a08bfa Benoît S
        result[pid] = clean_vm_name(re.sub(r"^.*guest=([a-zA-Z0-9.-_-]*).*$",r"\1", cmdline.readline()))
80 dda92e9b Rodolphe Qui?deville
    return result
81 17f78427 Lars Kruse
82 dda92e9b Rodolphe Qui?deville
def list_pids():
83
    ''' Find the pid of kvm processes
84
    @return a list of pids from running kvm
85
    '''
86 621744a6 Jan Egil Vestbø
    pid = Popen("pidof qemu-kvm qemu-system-x86_64 kvm", shell=True, stdout=PIPE)
87 dda92e9b Rodolphe Qui?deville
    return pid.communicate()[0].split()
88
89
def fetch(vms):
90
    ''' Fetch values for a list of pids
91 8713eb37 Lars Kruse
    @param dictionary {kvm_pid: cleaned vm name}
92 dda92e9b Rodolphe Qui?deville
    '''
93 e78a1590 loic
    for ( pid, name ) in vms.iteritems():
94
        ( user, system ) = open("/proc/%s/stat" % pid, 'r').readline().split(' ')[13:15]
95
        print '%s_cpu.value %d' % ( name, int(user) + int(system) )
96 17f78427 Lars Kruse
97 dda92e9b Rodolphe Qui?deville
if __name__ == "__main__":
98
    if len(sys.argv) > 1:
99
        if sys.argv[1] in ['autoconf', 'detect']:
100
            if detect_kvm():
101
                print "yes"
102
            else:
103
                print "no"
104
        elif sys.argv[1] == "config":
105
            config(find_vm_names(list_pids()).values())
106
        else:
107
            fetch(find_vm_names(list_pids()))
108
    else:
109
        fetch(find_vm_names(list_pids()))