Projet

Général

Profil

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

root / plugins / libvirt / kvm_mem @ a7139bca

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

1
#!/usr/bin/env python3
2
# -*- coding: utf-8 -*-
3
# vim: set fileencoding=utf-8
4
#
5
# Munin plugin to show amount of memory used by vm
6
#
7
# Copyright Maxence Dunnewind, Rodolphe Quiédeville, Adrien Pujol
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
    base_config = """graph_title KVM Virtual Machine Memory usage
25
graph_vlabel Bytes
26
graph_category virtualization
27
graph_info This graph shows the current amount of memory used by virtual machines
28
graph_args --base 1024 -l 0"""
29
    print(base_config)
30
    for vm in vm_names:
31
        print("%s_mem.label %s" % (vm, vm))
32
        print("%s_mem.type GAUGE" % vm)
33
        print("%s_mem.draw %s" % (vm, "AREASTACK"))
34
        print("%s_mem.info memory used by virtual machine %s" % (vm, vm))
35

    
36

    
37
def clean_vm_name(vm_name):
38
    ''' Replace all special chars
39
    @param vm_name : a vm's name
40
    @return cleaned vm's name
41
    '''
42
    # suffix part defined in conf
43
    suffix = os.getenv('vmsuffix')
44
    if suffix:
45
        vm_name = re.sub(suffix,'',vm_name)
46

    
47
    # proxmox uses kvm with -name parameter
48
    parts = vm_name.split('\x00')
49
    if (parts[0].endswith('kvm')):
50
        try:
51
            return parts[parts.index('-name')+1]
52
        except ValueError:
53
            pass
54

    
55
    return re.sub(r"[^a-zA-Z0-9_]", "_", vm_name)
56

    
57
def fetch(vms):
58
    ''' Fetch values for a list of pids
59
    @param dictionary {kvm_pid: cleaned vm name}
60
    '''
61
    res = {}
62
    for pid in vms:
63
        try:
64
            cmdline = open("/proc/%s/cmdline" % pid, "r")
65
            amount = re.sub(r"^.*-m\x00(.*)\x00-smp.*$",r"\1", cmdline.readline())
66
            amount = int(amount) * 1024 * 1024
67
            print("%s_mem.value %s" % (vms[pid], amount))
68
        except:
69
            cmdline = open("/proc/%s/cmdline" % pid, "r")
70
            amount = re.sub(r"^.*-m\x00(\d+).*$",r"\1", cmdline.readline())
71
            amount = int(amount) * 1024 * 1024
72
            print("%s_mem.value %s" % (vms[pid], amount))
73

    
74
def detect_kvm():
75
    ''' Check if kvm is installed
76
    '''
77
    kvm = Popen("which kvm", shell=True, stdout=PIPE)
78
    kvm.communicate()
79
    return not bool(kvm.returncode)
80

    
81
def find_vm_names(pids):
82
    '''Find and clean vm names from pids
83
    @return a dictionary of {pids : cleaned vm name}
84
    '''
85
    result = {}
86
    for pid in pids:
87
        cmdline = open("/proc/%s/cmdline" % pid, "r")
88
        result[pid] = clean_vm_name(re.sub(r"^.*guest=([a-zA-Z0-9.-_-]*).*$",r"\1", cmdline.readline()))
89
    return result
90

    
91
def list_pids():
92
    ''' Find the pid of kvm processes
93
    @return a list of pids from running kvm
94
    '''
95
    pid = Popen("pidof qemu-kvm qemu-system-x86_64 kvm", shell=True, stdout=PIPE, text=True)
96
    return pid.communicate()[0].split()
97

    
98
if __name__ == "__main__":
99
    if len(sys.argv) > 1:
100
        if sys.argv[1] in ['autoconf', 'detect']:
101
            if detect_kvm():
102
                print("yes")
103
            else:
104
                print("no")
105
        elif sys.argv[1] == "config":
106
            config(find_vm_names(list_pids()).values())
107
        else:
108
            fetch(find_vm_names(list_pids()))
109
    else:
110
        fetch(find_vm_names(list_pids()))