Skip to content

Instantly share code, notes, and snippets.

@frgaudet
Created March 24, 2016 13:37
Show Gist options
  • Save frgaudet/5669778757e773676b43 to your computer and use it in GitHub Desktop.
Save frgaudet/5669778757e773676b43 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# coding=utf-8
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# <http://www.gnu.org/licenses/>.
#
# This program is a proof-of-concept : it parse a qemu domain, and create in your Zabbix server a corresponding host
# with an item (CPU time) and the corresponding graph. The polling process isn't included here.
#
# F-Gaudet 2016
import urllib2
import json
import argparse
import sys
import os
import logging
try:
import libvirt
except ImportError:
libvirt = None
# Define logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
def authenticate(url, username, password):
values = {"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": username,
"password": password
},
"id": 1
}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
response = urllib2.urlopen(req, data)
output = json.loads(response.read())
try:
message = output['result']
except:
message = output['error']['data']
logger.error(json.dumps(message))
exit (1)
return output['result']
def hostExists(url, auth, instance, uuid):
values = {
"jsonrpc": "2.0",
"method": "host.exists",
"params": {
"host": uuid
},
"auth": auth,
"id": 1
}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
try:
message = output['result']
if 'true' in json.dumps(message):
return True
except:
message = output['error']['data']
logger.error(json.dumps(message))
def hostCreate(url, auth, instance, uuid):
values = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": uuid,
"interfaces": [
{
"type": 2,
"main": 1,
"useip": 0,
"ip": "",
"dns": instance,
"port": "10050"
}
],
"groups": [
{
"groupid": "6"
}
],
"inventory_mode": 0,
"inventory": {
"tag": uuid
}
},
"auth": auth,
"id": 1
}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
try:
message = output['result']['hostids'][0]
return message
except:
message = output['error']['data']
logger.error(json.dumps(message))
exit(1)
def itemCpuCreate(url, auth, hostid):
values = {
"jsonrpc": "2.0",
"method": "item.create",
"params": {
"name": "Total CPU",
"key_": "system.kvm.guest.cpu",
"hostid": hostid,
"type": 2,
"value_type": 0,
"delay": 30
},
"auth": auth,
"id": 1
}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
try:
message = output['result']['itemids'][0]
return message
except:
message = output['error']['data']
logger.error(json.dumps(message))
exit(1)
def graphCreate(url, auth, itemid, title):
values = {
"jsonrpc": "2.0",
"method": "graph.create",
"params": {
"name": title,
"width": 900,
"height": 200,
"gitems": [
{
"itemid": itemid,
"color": "00AA00"
}
]
},
"auth": auth,
"id": 1
}
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
try:
message = output['result']['graphids'][0]
return message
except:
message = output['error']['data']
logger.error(json.dumps(message))
exit(1)
if __name__ == '__main__':
url = 'http://zabbix-server/zabbix/api_jsonrpc.php'
username = "Admin"
password = "zabbix"
if libvirt is None:
logger.error('Unable to import libvirt')
exit(1)
auth = authenticate(url, username, password)
conn = libvirt.openReadOnly("qemu:///system")
# Parse all instances within a domain
for dom in [conn.lookupByID(n) for n in conn.listDomainsID()]:
if not hostExists(url, auth, dom.name(), dom.UUIDString()):
# Host creation
hostid = hostCreate(url, auth, dom.name(), dom.UUIDString())
# Create CPU item
itemid=itemCpuCreate(url, auth, hostid)
# Create CPU Graph
graphCreate(url, auth, itemid, "Total CPU Time")
logger.info('All Good')
else:
logger.error('Host already exists')
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment