Node to class and refactor

This commit is contained in:
Miłosz Stocki 2019-01-15 15:56:54 +01:00
parent 74be8431a8
commit 78761ad61c
Signed by: osiu97
GPG Key ID: E3D1D83FA04F51D6
4 changed files with 33 additions and 19 deletions

6
Node.py Normal file
View File

@ -0,0 +1,6 @@
class Node(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s' % self.name

View File

@ -7,31 +7,36 @@ PASSWORD = "zabbix"
HOST = "172.16.3.11:8006" HOST = "172.16.3.11:8006"
conn = PVEApi(HOST, USERNAME, PASSWORD) conn = PVEApi(HOST, USERNAME, PASSWORD)
nodelist = conn.get_node_list()
parser = ArgumentParser() parser = ArgumentParser()
parser.add_argument("node", choices=conn.get_node_list(), help="Choose node") # FIXME choose object from list of objects by name
parser.add_argument("node", help="Enter node name")
parser.add_argument("type", choices=['vm', 'cluster', 'node'], help='categories') parser.add_argument("type", choices=['vm', 'cluster', 'node'], help='categories')
parser.add_argument("-l", "--list", dest='listing', action='store_true') parser.add_argument("-l", "--list", dest='listing', action='store_true')
parser.add_argument("-n", "--name", dest='name') parser.add_argument("-n", "--name", dest='name')
parser.add_argument("-p", "--param", dest='param') parser.add_argument("-p", "--param", dest='param')
args = parser.parse_args() args = parser.parse_args()
NODE = args.node NODE = next((n for n in nodelist if n.name == args.node), None)
if NODE is None:
raise ValueError("No such Node found", "Valid nodes:", nodelist)
def get_vmnames(vmlist, node, **kwargs):
def get_vmnames(vmlist, vmnode, **kwargs):
""" """
Get Virtual Machine Names for discovery Get Virtual Machine Names for discovery
:param vmlist: list of VM class objects :param vmlist: list of VM class objects
:param node: node name with to filter VMs by :param vmnode: node name with to filter VMs by
:param kwargs: used to accept command line parameters :param kwargs: used to accept command line parameters
:return: list of dicts in [{'#VMNAME': "$name"}] format :return: list of dicts in [{'#VMNAME': "$name"}] format
""" """
name_vmlist = list() name_vmlist = list()
for vm in vmlist: for vm in vmlist:
if kwargs['name'] is None: if kwargs['name'] is None:
if vm.node == node: if vm.node == vmnode.name:
name_vmlist.append({'#VMNAME': vm.name}) name_vmlist.append({'#VMNAME': vm.name})
elif kwargs['name'] is not None and kwargs['listing'] is True: elif kwargs['name'] is not None and kwargs['listing'] is True:
if vm.node == node and vm.name == kwargs['name']: if vm.node == vmnode.name and vm.name == kwargs['name']:
name_vmlist.append({'#VMNAME': vm.name}) name_vmlist.append({'#VMNAME': vm.name})
return name_vmlist return name_vmlist
@ -40,10 +45,10 @@ def get_vminfo(vmname, parameter=None):
""" """
Get Virtual Machine data Get Virtual Machine data
:param vmname: Virtual machine name :param vmname: Virtual machine name
:param kwargs: handle vm params :param parameter: Specific VM stat e.g.: CPU Usage, use if you want to get one parameter for Zabbix
:return: list od dicts with vm params :return: list od dicts with vm params
""" """
vm = next(v for v in conn.get_cluster_vmlist() if v.name == vmname) vm = next(v for v in conn.get_cluster_vmlist(nodelist) if v.name == vmname)
if parameter is not None: if parameter is not None:
vm_params = vm.__getattribute__(parameter) vm_params = vm.__getattribute__(parameter)
return vm_params return vm_params
@ -82,7 +87,7 @@ def exec_vm(**kwargs):
print get_vminfo(kwargs['name'], kwargs['param']) print get_vminfo(kwargs['name'], kwargs['param'])
else: else:
print listofdicts_to_zabbix_json( print listofdicts_to_zabbix_json(
get_vmnames(conn.get_cluster_vmlist(), NODE, name=kwargs['name'], listing=kwargs['listing'])) get_vmnames(conn.get_cluster_vmlist(nodelist), NODE, name=kwargs['name'], listing=kwargs['listing']))
if args.type == "vm": if args.type == "vm":

View File

@ -3,6 +3,7 @@ import urllib2
import ssl import ssl
import json import json
from VM import VM from VM import VM
from Node import Node
def get_auth(host, username, password): def get_auth(host, username, password):
@ -23,6 +24,7 @@ def get_auth(host, username, password):
class PVEApi(object): class PVEApi(object):
"""Handle API Connection and authorization""" """Handle API Connection and authorization"""
def __init__(self, host, username, password): def __init__(self, host, username, password):
""" """
Creates connection object Creates connection object
@ -58,17 +60,18 @@ class PVEApi(object):
nodes = list() nodes = list()
for node in resources: for node in resources:
if type(node) is dict: if type(node) is dict:
nodes.append(node[u'node'].encode("ascii")) nodeobj = Node(node[u'node'].encode("ascii"))
nodes.append(nodeobj)
return nodes return nodes
def get_cluster_vmlist(self): def get_cluster_vmlist(self, nodelist):
""" """
Creates Virtual Machine List Creates Virtual Machine List
:return: list of VM class objects :return: list of VM class objects
""" """
vmlist = list() vmlist = list()
for node in self.get_node_list(): for node in nodelist:
url = self.url + '/nodes/' + node + '/qemu' url = self.url + '/nodes/' + node.name + '/qemu'
response = json.load(urllib2.urlopen(self.get_request(url), context=ssl._create_unverified_context())) response = json.load(urllib2.urlopen(self.get_request(url), context=ssl._create_unverified_context()))
resources = response['data'] resources = response['data']
for machine in resources: for machine in resources:

2
VM.py
View File

@ -5,7 +5,7 @@ class VM(object):
def __init__(self, node, name, status, uptime, diskread, diskwrite, memusage, pid, vmid, netin, netout, cpus, def __init__(self, node, name, status, uptime, diskread, diskwrite, memusage, pid, vmid, netin, netout, cpus,
template, disk, cpuusage, maxdisk, maxmem): template, disk, cpuusage, maxdisk, maxmem):
self.name = name self.name = name
self.node = node self.node = node.name
self.statusstr = status self.statusstr = status
self.status = 1 if self.statusstr == "running" else 0 self.status = 1 if self.statusstr == "running" else 0
self.uptime = uptime self.uptime = uptime