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"
conn = PVEApi(HOST, USERNAME, PASSWORD)
nodelist = conn.get_node_list()
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("-l", "--list", dest='listing', action='store_true')
parser.add_argument("-n", "--name", dest='name')
parser.add_argument("-p", "--param", dest='param')
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
: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
:return: list of dicts in [{'#VMNAME': "$name"}] format
"""
name_vmlist = list()
for vm in vmlist:
if kwargs['name'] is None:
if vm.node == node:
if vm.node == vmnode.name:
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']:
if vm.node == vmnode.name and vm.name == kwargs['name']:
name_vmlist.append({'#VMNAME': vm.name})
return name_vmlist
@ -40,10 +45,10 @@ def get_vminfo(vmname, parameter=None):
"""
Get Virtual Machine data
: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
"""
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:
vm_params = vm.__getattribute__(parameter)
return vm_params
@ -61,14 +66,14 @@ def listofdicts_to_zabbix_json(dlist):
:param dlist: list of dicts you want to convert
:return: JSON string for zabbix-get
"""
newdlist=list()
newdlist = list()
for d in dlist:
for k,v in d.iteritems():
k = '{'+k+'}'
for k, v in d.iteritems():
k = '{' + k + '}'
newdict = {k: v}
newdlist.append(newdict)
newdlist = {"data": newdlist}
zabbixjson = json.dumps(newdlist,separators=(',', ':'))
zabbixjson = json.dumps(newdlist, separators=(',', ':'))
return zabbixjson
@ -79,10 +84,10 @@ def exec_vm(**kwargs):
:return:
"""
if kwargs['name'] is not None and kwargs['listing'] is False:
print get_vminfo(kwargs['name'],kwargs['param'])
print get_vminfo(kwargs['name'], kwargs['param'])
else:
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":

View File

@ -3,6 +3,7 @@ import urllib2
import ssl
import json
from VM import VM
from Node import Node
def get_auth(host, username, password):
@ -23,6 +24,7 @@ def get_auth(host, username, password):
class PVEApi(object):
"""Handle API Connection and authorization"""
def __init__(self, host, username, password):
"""
Creates connection object
@ -58,17 +60,18 @@ class PVEApi(object):
nodes = list()
for node in resources:
if type(node) is dict:
nodes.append(node[u'node'].encode("ascii"))
nodeobj = Node(node[u'node'].encode("ascii"))
nodes.append(nodeobj)
return nodes
def get_cluster_vmlist(self):
def get_cluster_vmlist(self, nodelist):
"""
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'
for node in nodelist:
url = self.url + '/nodes/' + node.name + '/qemu'
response = json.load(urllib2.urlopen(self.get_request(url), context=ssl._create_unverified_context()))
resources = response['data']
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,
template, disk, cpuusage, maxdisk, maxmem):
self.name = name
self.node = node
self.node = node.name
self.statusstr = status
self.status = 1 if self.statusstr == "running" else 0
self.uptime = uptime