1
0
Fork 0
mirror of https://github.com/munin-monitoring/contrib.git synced 2025-07-22 02:51:03 +00:00

Plugin kvm_cpu: migrate to Python3, format documentation

This commit is contained in:
Lars Kruse 2020-11-26 00:13:12 +01:00
parent 0d055149cc
commit bde90ba910
2 changed files with 65 additions and 41 deletions

View file

@ -1,27 +1,53 @@
#!/usr/bin/env python #!/usr/bin/env python3
# -*- coding: utf-8 -*- """
# vim: set fileencoding=utf-8 =encoding utf8
#
# Munin plugin to show CPU used by vm
#
# Copyright Maxence Dunnewind, Rodolphe Quiédeville
#
# License : GPLv3
#
# parsed environment variables:
# vmsuffix: part of vm name to be removed
#
#%# capabilities=autoconf
#%# family=contrib
import re, os, sys =head1 NAME
kvm_cpu - show CPU usage of VM
=head1 CONFIGURATION
Parsed environment variables:
vmsuffix: part of VM name to be removed
=head1 LICENSE
GPLv3
SPDX-License-Identifier: GPL-3.0-only
=head1 AUTHORS
Maxence Dunnewind
Rodolphe Quiédeville
=head1 MAGIC MARKERS
#%# capabilities=autoconf
#%# family=contrib
=cut
"""
import os
import re
import sys
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
def config(vm_names): def config(vm_names):
''' Print the plugin's config ''' Print the plugin's config
@param vm_names : a list of "cleaned" vms' name @param vm_names : a list of "cleaned" vms' name
''' '''
percent = len(filter(lambda x: x[0:3] == 'cpu' and x[3] != ' ', open('/proc/stat', 'r').readlines())) * 100 percent = 100 * len(
filter(lambda x: x[0:3] == 'cpu' and x[3] != ' ', open('/proc/stat', 'r').readlines()))
base_config = """graph_title KVM Virtual Machine CPU usage base_config = """graph_title KVM Virtual Machine CPU usage
graph_vlabel %% graph_vlabel %%
@ -30,15 +56,13 @@ graph_scale no
graph_period second graph_period second
graph_info This graph shows the current CPU used by virtual machines graph_info This graph shows the current CPU used by virtual machines
graph_args --base 1000 -r --lower-limit 0 --upper-limit %d""" % percent graph_args --base 1000 -r --lower-limit 0 --upper-limit %d""" % percent
print base_config print(base_config)
draw = "AREA"
for vm in vm_names: for vm in vm_names:
print "%s_cpu.label %s" % (vm, vm) print("%s_cpu.label %s" % (vm, vm))
print "%s_cpu.min 0" % vm print("%s_cpu.min 0" % vm)
print "%s_cpu.type DERIVE" % vm print("%s_cpu.type DERIVE" % vm)
print "%s_cpu.draw %s" % (vm, draw) print("%s_cpu.draw AREASTACK" % vm)
print "%s_cpu.info percent of cpu time used by virtual machine" % vm print("%s_cpu.info percent of cpu time used by virtual machine" % vm)
draw = "STACK"
def clean_vm_name(vm_name): def clean_vm_name(vm_name):
@ -46,29 +70,27 @@ def clean_vm_name(vm_name):
@param vm_name : a vm's name @param vm_name : a vm's name
@return cleaned vm's name @return cleaned vm's name
''' '''
# suffix part defined in conf # suffix part defined in conf
suffix = os.getenv('vmsuffix') suffix = os.getenv('vmsuffix')
if suffix: if suffix:
vm_name = re.sub(suffix,'',vm_name) vm_name = re.sub(suffix, '', vm_name)
# proxmox uses kvm with -name parameter # proxmox uses kvm with -name parameter
parts = vm_name.split('\x00') parts = vm_name.split('\x00')
if (parts[0].endswith('kvm')): if parts[0].endswith('kvm'):
try: try:
return parts[parts.index('-name')+1] return parts[parts.index('-name') + 1]
except ValueError: except ValueError:
pass pass
return re.sub(r"[^a-zA-Z0-9_]", "_", vm_name) return re.sub(r"[^a-zA-Z0-9_]", "_", vm_name)
def detect_kvm(): def detect_kvm():
''' Check if kvm is installed ''' Check if kvm is installed '''
'''
kvm = Popen("which kvm", shell=True, stdout=PIPE) kvm = Popen("which kvm", shell=True, stdout=PIPE)
kvm.communicate() kvm.communicate()
return not bool(kvm.returncode) return not bool(kvm.returncode)
def find_vm_names(pids): def find_vm_names(pids):
'''Find and clean vm names from pids '''Find and clean vm names from pids
@return a dictionary of {pids : cleaned vm name} @return a dictionary of {pids : cleaned vm name}
@ -76,9 +98,11 @@ def find_vm_names(pids):
result = {} result = {}
for pid in pids: for pid in pids:
cmdline = open("/proc/%s/cmdline" % pid, "r") cmdline = open("/proc/%s/cmdline" % pid, "r")
result[pid] = clean_vm_name(re.sub(r"^.*guest=([a-zA-Z0-9.-_-]*).*$",r"\1", cmdline.readline())) result[pid] = clean_vm_name(
re.sub(r"^.*guest=([a-zA-Z0-9.-_-]*).*$", r"\1", cmdline.readline()))
return result return result
def list_pids(): def list_pids():
''' Find the pid of kvm processes ''' Find the pid of kvm processes
@return a list of pids from running kvm @return a list of pids from running kvm
@ -86,25 +110,26 @@ def list_pids():
pid = Popen("pidof qemu-kvm qemu-system-x86_64 kvm", shell=True, stdout=PIPE) pid = Popen("pidof qemu-kvm qemu-system-x86_64 kvm", shell=True, stdout=PIPE)
return pid.communicate()[0].split() return pid.communicate()[0].split()
def fetch(vms): def fetch(vms):
''' Fetch values for a list of pids ''' Fetch values for a list of pids
@param dictionary {kvm_pid: cleaned vm name} @param dictionary {kvm_pid: cleaned vm name}
''' '''
for ( pid, name ) in vms.iteritems(): for pid, name in vms.items():
( user, system ) = open("/proc/%s/stat" % pid, 'r').readline().split(' ')[13:15] user, system = open("/proc/%s/stat" % pid, 'r').readline().split(' ')[13:15]
print '%s_cpu.value %d' % ( name, int(user) + int(system) ) print('%s_cpu.value %d' % (name, int(user) + int(system)))
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) > 1: if len(sys.argv) > 1:
if sys.argv[1] in ['autoconf', 'detect']: if sys.argv[1] in ['autoconf', 'detect']:
if detect_kvm(): if detect_kvm():
print "yes" print("yes")
else: else:
print "no" print("no")
elif sys.argv[1] == "config": elif sys.argv[1] == "config":
config(find_vm_names(list_pids()).values()) config(find_vm_names(list_pids()).values())
else: else:
fetch(find_vm_names(list_pids())) fetch(find_vm_names(list_pids()))
else: else:
fetch(find_vm_names(list_pids())) fetch(find_vm_names(list_pids()))

View file

@ -170,7 +170,6 @@ plugins/jmx/plugin/jmx_
plugins/jvm/jstat__gccount plugins/jvm/jstat__gccount
plugins/jvm/jstat__gctime plugins/jvm/jstat__gctime
plugins/jvm/jstat__heap plugins/jvm/jstat__heap
plugins/libvirt/kvm_cpu
plugins/libvirt/kvm_io plugins/libvirt/kvm_io
plugins/libvirt/kvm_mem plugins/libvirt/kvm_mem
plugins/libvirt/kvm_net plugins/libvirt/kvm_net