Created
October 5, 2014 10:41
-
-
Save desaster/c99e6927b39024777c8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# {u'vms': [{u'memory': 0, | |
# u'name': u'honeydrive', | |
# u'ostype': u'hvm', | |
# u'state': 5, | |
# u'uuid': u'a14eb9b0-c5fc-d66a-0665-b32972a893e3'}, | |
# {u'memory': 0, | |
# u'name': u'dvx', | |
# u'ostype': u'hvm', | |
# u'state': 5, | |
# u'uuid': u'278e6e8f-954e-036b-fe07-966d75bee753'}, | |
# {u'memory': 1048576, | |
# u'name': u'honeyserver', | |
# u'ostype': u'hvm', | |
# u'state': 1, | |
# u'uuid': u'e9ba9b5f-2aa1-fe96-adc4-8f14e78e3bae'}, | |
from flask import Flask | |
import json | |
import mimerender | |
import libvirt | |
# by default, json doesn't serialize objects | |
class Serializer(object): | |
@staticmethod | |
def encode_obj(obj): | |
if isinstance(obj, object): | |
return obj.__dict__ | |
@staticmethod | |
def serialize(obj): | |
return json.dumps(obj, default=Serializer.encode_obj) | |
# this will be serialized in response | |
class VM(object): | |
name = None | |
ostype = None | |
uuid = None | |
memory = None | |
state = None | |
class VMFactory(object): | |
""" | |
Create a VM instance from libvirt data | |
""" | |
def create(self, domain): | |
vm = VM() | |
info = domain.info() | |
vm.name = domain.name() | |
vm.ostype = domain.OSType() | |
vm.uuid = domain.UUIDString() | |
vm.memory = info[2] | |
vm.state = info[0] | |
return vm | |
# this class exists so i can re-open connection if needed, or stuff like that | |
class libvirtConnection(object): | |
def __init__(self): | |
self.conn = None | |
def connect(self): | |
if self.conn is not None: | |
return | |
self.conn = libvirt.openReadOnly(None) | |
if self.conn == None: | |
raise Exception('Failed to open connection to the hypervisor') | |
def get_connection(self): | |
self.connect() | |
return self.conn | |
app = Flask(__name__) | |
lvconn = libvirtConnection() | |
mimerender = mimerender.FlaskMimeRender() | |
render_json = lambda **args: Serializer.serialize(args) | |
@app.route("/vms/") | |
@mimerender( | |
default = 'json', | |
json = render_json, | |
) | |
def get_vms(): | |
vms = [] | |
vmfactory = VMFactory() | |
for dom in lvconn.get_connection().listAllDomains(): | |
vm = vmfactory.create(dom) | |
vms.append(vm) | |
return {'vms': vms} | |
if __name__ == "__main__": | |
app.debug = True | |
app.run(host='0.0.0.0', port=8079) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment