Commit 6eeb5839 by Zoltan Karsa

arguments parser

parent 49a28fd7
import libvirt import libvirt
import sys import sys, getopt, os
import uuid import uuid
from jinja2 import Environment, select_autoescape, FileSystemLoader from jinja2 import Environment, select_autoescape, FileSystemLoader
import subprocess import subprocess
from utils import fwd_port, show_ip from utils import fwd_port, show_ip
try:
conn = libvirt.open("qemu:///system")
except libvirt.libvirtError:
print('Failed to open connection to the hypervisor')
sys.exit(1)
file_loader = FileSystemLoader('templates') file_loader = FileSystemLoader('templates')
env = Environment(autoescape=select_autoescape( env = Environment(autoescape=select_autoescape(
...@@ -33,65 +27,103 @@ params = { ...@@ -33,65 +27,103 @@ params = {
"boot_menu": "yes", "boot_menu": "yes",
} }
template = env.get_template("demovm.xml") def start_vm(params):
vmxml = template.render( template = env.get_template("demovm.xml")
**params
)
print(vmxml) vmxml = template.render(
**params
)
input("Correct? ") print(vmxml)
id = params["uuid"] input("Correct? ")
bus = params["mdev_bus"]
vgpu = params["vgpu_type"]
if params["vgpu"]:
print("Allocating VGPU instance for the VM")
try: try:
subprocess.run([f"sudo bash create_vgpu.sh {id} {bus} {vgpu}"], check=True, shell=True, stderr=subprocess.STDOUT) conn = libvirt.open("qemu:///system")
except subprocess.CalledProcessError as e: except libvirt.libvirtError:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) print('Failed to open connection to the hypervisor')
sys.exit(1)
try:
dom = conn.defineXML(vmxml) id = params["uuid"]
if not dom:
raise SystemExit("Failed to define a domain from an XML definition") if params["vgpu"]:
print("Start VM") bus = params["mdev_bus"]
if dom.create() < 0: vgpu = params["vgpu_type"]
raise SystemExit("Can not boot guest domain") print("Allocating VGPU instance for the VM")
except libvirt.libvirtError: try:
print('Failed to find the main domain') subprocess.run([f"sudo bash create_vgpu.sh {id} {bus} {vgpu}"], check=True, shell=True, stderr=subprocess.STDOUT)
sys.exit(1) except subprocess.CalledProcessError as e:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
print("Domain 0: id %d running %s" % (dom.ID(), dom.OSType()))
print(dom.info())
print("Type stop, to shutdown vm!")
cmd = input()
while cmd != "stop":
cmdarr = cmd.split()
if cmdarr[0] == "fwd":
fwd_port(dom, int(cmdarr[1]), int(cmdarr[2]))
elif cmdarr[0] == "showip":
show_ip(dom)
cmd = input()
try: try:
print("Stop VM") dom = conn.defineXML(vmxml)
if dom.destroy() < 0: if not dom:
raise SystemExit("Can not stop guest domain") raise SystemExit("Failed to define a domain from an XML definition")
except libvirt.libvirtError: print("Start VM")
print('Failed to find the main domain') if dom.create() < 0:
sys.exit(1) raise SystemExit("Can not boot guest domain")
except libvirt.libvirtError:
print('Failed to find the main domain')
sys.exit(1)
print("Domain 0: id %d running %s" % (dom.ID(), dom.OSType()))
print(dom.info())
print("Type stop, to shutdown vm!")
cmd = input()
while cmd != "stop":
cmdarr = cmd.split()
if cmdarr[0] == "fwd":
fwd_port(dom, int(cmdarr[1]), int(cmdarr[2]))
elif cmdarr[0] == "showip":
show_ip(dom)
cmd = input()
if params["vgpu"]:
print("Deallocating VGPU instance from the VM")
try: try:
subprocess.run([f"sudo bash remove_vgpu.sh {id} {bus} {vgpu}"], check=True, shell=True, stderr=subprocess.STDOUT) print("Stop VM")
except subprocess.CalledProcessError as e: if dom.destroy() < 0:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) raise SystemExit("Can not stop guest domain")
except libvirt.libvirtError:
print('Failed to find the main domain')
sys.exit(1)
if params["vgpu"]:
print("Deallocating VGPU instance from the VM")
try:
subprocess.run([f"sudo bash remove_vgpu.sh {id} {bus} {vgpu}"], check=True, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
conn.close()
\ No newline at end of file conn.close()
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "gbmcd:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
sys.exit(2)
for o, a in opts:
if o in ("-m", "--mem"):
params["ram"] = int(a)
elif o in ("-g", "--gpu"):
params["vgpu"] = True
params["vgpu_type"] = a
elif o in ("-b", "--boot"):
params["boot_iso"] = True
params["iso"] = a
if not os.path.isfile(a):
raise RuntimeError("The attached boot iso is not a file or not exists")
elif o in ("-c", "--cpu"):
params["vcpu"] = int(a)
elif o in ("-d", "--disk"):
params["disk"] = a
if not os.path.isfile(a):
raise RuntimeError("The attached disk is not a file or not exists")
else:
assert False, "unhandled option"
start_vm(params)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment