From 00f714cc276197e59a039879be36401c6201ae45 Mon Sep 17 00:00:00 2001 From: osiu97 Date: Thu, 10 Jan 2019 11:26:55 +0100 Subject: [PATCH] first version should work with vm discovery and data --- PVE-Zabbix.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++----- PVEApi.py | 32 ++++++++++++++++++++-- VM.py | 5 +++- 3 files changed, 100 insertions(+), 10 deletions(-) diff --git a/PVE-Zabbix.py b/PVE-Zabbix.py index 6df2514..f132587 100644 --- a/PVE-Zabbix.py +++ b/PVE-Zabbix.py @@ -1,21 +1,80 @@ from PVEApi import PVEApi +from argparse import ArgumentParser import json USERNAME = "zabbix@pve" PASSWORD = "zabbix" HOST = "172.16.3.11:8006" -NODE='h1' +NODE = 'h1' conn = PVEApi(HOST, USERNAME, PASSWORD) +parser = ArgumentParser() +parser.add_argument("node", choices=conn.get_node_list(), help="Choose node") +parser.add_argument("type", choices=['vm', 'cluster', 'node'], help='categories') +parser.add_argument("-l", "--list", dest='listing', action='store_true') +parser.add_argument("-n", "--name", dest='name') +args = parser.parse_args() -def get_vmnames(vmlist): - name_vmlist = [{"#VMNAME": vm.name} for vm in vmlist] + +def get_vmnames(vmlist, node, **kwargs): + """ + Get Virtual Machine Names for discovery + :param vmlist: list of VM class objects + :param node: node name with to filter VMs by + :param kwargs: used to accept command line parameters + :return: list of dicts in [{'#VMNAME': "$name"}] format + """ + name_vmlist = list() + for vm in vmlist: + if kwargs['name'] is None: + if vm.node == node: + name_vmlist.append({'#VMNAME': vm.name}) + elif kwargs['name'] is not None and kwargs['listing'] is True: + if vm.node == node and vm.name == kwargs['name']: + name_vmlist.append({'#VMNAME': vm.name}) return name_vmlist -def listofdicts_to_zabbix_json(list): - # TODO wrap in "data:[]" - zabbixjson=json.dumps(list) + +def get_vminfo(vmname): + """ + Get Virtual Machine data + :param vmname: Virtual machine name + :return: list od dicts with vm params + """ + vm_params = list() + vm = next(v for v in conn.get_cluster_vmlist() if v.name == vmname) + for param in dir(vm): + if not param.startswith('__'): + vm_params.append({'#' + param.upper(): vm.__getattribute__(param)}) + return vm_params + + +def listofdicts_to_zabbix_json(dlist): + """ + Converts list of dicts to JSON an wraps around 'data' + :param dlist: list of dicts you want to convert + :return: JSON string for zabbix-get + """ + dlist = {"data": dlist} + zabbixjson = json.dumps(dlist) return zabbixjson -print listofdicts_to_zabbix_json(get_vmnames(conn.get_cluster_vmlist())) \ No newline at end of file + +def exec_vm(**kwargs): + """ + Handles vm positional parameter + :param kwargs: handle cmd parametres + :return: + """ + if kwargs['name'] is not None and kwargs['listing'] is False: + print listofdicts_to_zabbix_json(get_vminfo(kwargs['name'])) + else: + print listofdicts_to_zabbix_json( + get_vmnames(conn.get_cluster_vmlist(), NODE, name=kwargs['name'], listing=kwargs['listing'])) + + +if args.type == "vm": + exec_vm(listing=args.listing, name=args.name) +else: + print args diff --git a/PVEApi.py b/PVEApi.py index b767ccd..6a1e01e 100644 --- a/PVEApi.py +++ b/PVEApi.py @@ -6,6 +6,13 @@ from VM import VM def get_auth(host, username, password): + """ + Handles ticket and csrf token collection for PVEApi class + :param host: ip of pve host with port + :param username: zabbix user + :param password: zabbix password + :return: list with csrf token and auth ticket + """ postdata = urllib.urlencode({'username': username, 'password': password}) url = "https://" + host + "/api2/json/access/ticket" req = urllib2.Request(url, postdata) @@ -15,29 +22,50 @@ def get_auth(host, username, password): class PVEApi(object): - + """Handle API Connection and authorization""" def __init__(self, host, username, password): + """ + Creates connection object + :param self: + :param host: ip of pve host with port + :param username: zabbix user + :param password: zabbix password + :return: + """ self.host = host self.url = "https://" + self.host + "/api2/json" self.csrftoken = get_auth(self.host, username, password)[0] self.ticket = get_auth(self.host, username, password)[1] def get_request(self, url): + """ + Handles adding auth ticket to API request + :param url: url to create request to + :return: request to handle with urlopen + """ req = urllib2.Request(url) req.add_header('Cookie', 'PVEAuthCookie=' + self.ticket) return req def get_node_list(self): + """ + Gets Node names from cluster data + :return: List of node names + """ url = self.url + '/nodes' response = json.load(urllib2.urlopen(self.get_request(url), context=ssl._create_unverified_context())) resources = response['data'] nodes = list() for node in resources: if type(node) is dict: - nodes.append(node[u'node']) + nodes.append(node[u'node'].encode("ascii")) return nodes def get_cluster_vmlist(self): + """ + Creates Virtual Machine List + :return: list of VM class objects + """ vmlist = list() for node in self.get_node_list(): url = self.url + '/nodes/' + node + '/qemu' diff --git a/VM.py b/VM.py index a550797..0df97d1 100644 --- a/VM.py +++ b/VM.py @@ -1,4 +1,7 @@ class VM(object): + """ + Proxmox Virtual Machine API Parameters + """ def __init__(self, node, name, status, uptime, diskread, diskwrite, memusage, pid, vmid, netin, netout, cpus, template, disk, cpuusage, maxdisk, maxmem): self.name = name @@ -20,4 +23,4 @@ class VM(object): self.maxmem = maxmem def __repr__(self): - return "<%s-%s:%s>" % (self.node,self.vmid, self.name) + return "<%s-%s:%s>" % (self.node, self.vmid, self.name)