agent/SWSCloudNode/qemu/__init__.py

231 lines
7 KiB
Python

# -*- coding: utf-8 -*-
import os
import libvirt
import subprocess
from SWSCloudNode.common import Common
class QEMU:
def __init__(self):
# qemu+ssh://root@laforge.usersys.redhat.com/system
self.conn = libvirt.open("qemu:///system")
def list(self):
names = self.conn.listDefinedDomains()
domains = map(self.conn.lookupByName, names)
ids = self.conn.listDomainsID()
running = map(self.conn.lookupByID, ids)
columns = 3
c = 0
n = 0
online = {}
offline = {}
for row in map(None, *[iter(domains)] * columns):
for domain in row:
if domain:
# print str(info(domain))
c += 1
offline[c] = self._info(domain)
for row in map(None, *[iter(running)] * columns):
for domain in row:
if domain:
n += 1
online[n] = self._info(domain)
return {
"online": online,
"offline": offline
}
def _info(self, dom):
states = {
libvirt.VIR_DOMAIN_NOSTATE: 'no state',
libvirt.VIR_DOMAIN_RUNNING: 'running',
libvirt.VIR_DOMAIN_BLOCKED: 'blocked on resource',
libvirt.VIR_DOMAIN_PAUSED: 'paused by user',
libvirt.VIR_DOMAIN_SHUTDOWN: 'being shut down',
libvirt.VIR_DOMAIN_SHUTOFF: 'shut off',
libvirt.VIR_DOMAIN_CRASHED: 'crashed',
}
[state, maxmem, mem, ncpu, cputime] = dom.info()
#return '%s is %s,' % (dom.name(), states.get(state, state))
return {
"hostname": dom.name(),
"info": {
"state": state,
"maxmem": maxmem,
"memory": mem,
"ncpu": ncpu,
"cputime": cputime
}
}
def start(self, hostname):
"""
Function VM Start
использует нативную библиотеку qemu
Params
:hostname: str
Return:
:bool:
"""
conn = libvirt.open("qemu:///system")
action = conn.lookupByName(hostname)
try:
action.create()
except:
print conn.virConnGetLastError()
return False
return True
def stop(self, hostname):
"""
функция остановки фиртуальной машины
использует
"""
conn = libvirt.open("qemu:///system")
action = conn.lookupByName(hostname)
try:
action.destroy()
except:
print conn.virConnGetLastError()
return False
return True
def restart(self, hostname):
"""
функция перезапуска виртуальной машины,
использует функции stop и start
"""
self.stop(hostname)
return self.start(hostname)
def delete(self, hostname):
"""
функция удаления виртуальной машины
"""
os.popen("/usr/bin/virsh shutdown %s" % hostname, "r")
os.popen("/usr/bin/virsh undefine %s" % hostname, "r")
os.popen("/bin/rm -r /var/lib/qemu/images/%s/" % hostname, "r")
return True
def __prepare(self, hostname):
# Create directory for new VM
# os.popen('mkdir -p /tmp/libvirt/%s/templates/libvirt' % hostname, "r")
subprocess.Popen([
# 'mkdir', '-p', '/var/lib/libvirt/images/%s/templates/qemu' % hostname
'mkdir', '-p', '/tmp/libvirt/%s/templates/libvirt' % hostname
],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Copy tempaltes
subprocess.Popen([
'cp', '/etc/vmbuilder/libvirt/*', '/tmp/libvirt/%s/templates/libvirt' % hostname],
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
# os.popen("cp /etc/vmbuilder/libvirt/* /tmp/libvirt/%s/templates/libvirt" % hostname)
# os.popen("cp vm/firstboot.sh /var/lib/qemu/images/%s/boot.sh" % hostname, "r")
os.popen("cp /etc/sws/cloud/firstboot.sh /tmp/libvirt/%s/boot.sh" % hostname, "r")
return True
def __storage(self, hostname, storage, swap=0):
# generate partition file
# Open new data file
# f = open("/var/lib/qemu/images/%s/partition" % hostname, "w")
f = open("/tmp/libvirt/%s/partition" % hostname, "w")
f.write("root %s\n" % storage)
if swap > 0:
# f.write("---\n" % swap)
f.write("swap %s\n" % swap)
f.close()
return True
def __ssh_key(self, hostname, sshkey):
f = open("/tmp/libvirt/%s/authorized_keys" % hostname, "w")
f.write(sshkey)
f.close()
return True
def create(self, cores, memory, storage, swap, hostname, ipv4, ipv4_gateway, dns1, dns2,
password, os_name, os_suite, interface, vm_id, ssh_key=None):
"""
функция создания виртуальной машины
"""
# self.__prepare(hostname)
self.__prepare(vm_id)
# generate partition file
# self.__storage(hostname, storage, swap)
if ssh_key:
# self.__ssh_key(hostname, ssh_key)
self.__ssh_key(vm_id, ssh_key)
# TODO: move to settings file
mirror = "http://ru.archive.ubuntu.com/ubuntu/"
c = [
"cd",
"/var/lib/libvirt/images;",
"/usr/bin/vmbuilder",
"kvm",
os_name,
"--suite=%s" % os_suite,
"--flavour=virtual",
"--arch=amd64",
"--mirror=%s" % mirror,
"-o",
"--libvirt=qemu:///system",
"--ip=%s" % ipv4,
"--gw=%s" % ipv4_gateway,
# PARTITIONING
# "--part=/var/lib/qemu/images/%s/partition" % values['hostname'],
"--rootsize=%s" % storage,
"--swapsize=%s" % swap,
"--templates=/tmp/libvirt/%s/templates/libvirt" % vm_id,
# USER
"--user=administrator",
"--name=administrator",
"--pass=%s" % password,
"--ssh-user-key=/tmp/libvirt/%s/authorized_keys" % vm_id,
"--lock-user",
"--rootpass=%s" % password,
"--ssh-key=/tmp/libvirt/%s/authorized_keys" % vm_id,
"--addpkg=linux-image-generic",
"--addpkg=vim-nox",
# "--addpkg=nano",
"--addpkg=unattended-upgrades",
"--addpkg=acpid",
# "--addpkg=fail2ban",
"--firstboot=/tmp/libvirt/%s/boot.sh" % vm_id,
"--mem=%s" % memory,
"--cpus=%s" % cores,
# "--hostname=%s" % hostname,
"--hostname=%s" % vm_id,
"--bridge=%s" % interface,
"--dns=%s" % dns1,
"--dns=%s" % dns2,
]
print ' '.join(c)
print ';;;'
print subprocess.call(' '.join(c), shell=True)
return True