]>
git.ipfire.org Git - people/ms/nitsi.git/blob - machine.py
3 import xml
.etree
.ElementTree
as ET
7 from serial_connection
import serial_connection
14 logger
= logging
.getLogger("nitsi.machine")
17 def __init__(self
, libvirt_con
, vm_xml_file
, snapshot_xml_file
, image
, root_uid
, username
, password
):
18 self
.log
= logger
.getChild(os
.path
.basename(vm_xml_file
))
19 self
.con
= libvirt_con
21 with
open(vm_xml_file
) as fobj
:
22 self
.vm_xml
= fobj
.read()
23 except FileNotFoundError
as error
:
24 logger
.error("No such file: {}".format(vm_xml_file
))
27 self
.name
= self
.get_name()
28 except BaseException
as error
:
29 logger
.error("Could not get name of the machine: {}".format(vm_xml_file
))
32 self
.log
= logger
.getChild(self
.name
)
33 self
.log
.debug("Name of this machine is {}".format(self
.name
))
36 with
open(snapshot_xml_file
) as fobj
:
37 self
.snapshot_xml
= fobj
.read()
38 except FileNotFoundError
as error
:
39 self
.log
.error("No such file: {}".format(snapshot_xml_file
))
43 if not os
.path
.isfile(self
.image
):
44 self
.log
.error("No such file: {}".format(self
.image
))
46 self
.root_uid
= root_uid
47 self
.disk
= disk(image
)
49 self
.username
= username
50 self
.password
= password
53 self
.dom
= self
.con
.defineXML(self
.vm_xml
)
55 self
.log
.error("Could not define VM")
59 if self
.dom
.create() < 0:
60 self
.log
.error("Could not start VM")
65 if self
.dom
.shutdown() < 0:
66 self
.log
.error("Could not shutdown VM")
69 self
.log
.error("Domain is not running")
74 def create_snapshot(self
):
76 self
.snapshot
= self
.dom
.snapshotCreateXML(self
.snapshot_xml
)
79 self
.log
.error("Could not create snapshot")
82 def revert_snapshot(self
):
83 self
.dom
.revertToSnapshot(self
.snapshot
)
84 self
.snapshot
.delete()
88 state
, reason
= self
.dom
.state()
90 if state
== libvirt
.VIR_DOMAIN_RUNNING
:
95 def get_serial_device(self
):
97 if not self
.is_running():
100 xml_root
= ET
.fromstring(self
.dom
.XMLDesc(0))
102 elem
= xml_root
.find("./devices/serial/source")
103 return elem
.get("path")
106 xml_root
= ET
.fromstring(self
.vm_xml
)
108 elem
= xml_root
.find("./name")
111 def check_is_booted_up(self
):
112 serial_con
= serial_connection(self
.get_serial_device())
114 serial_con
.write("\n")
115 # This will block till the domain is booted up
122 self
.serial_con
= serial_connection(self
.get_serial_device(), username
=self
.username
)
123 self
.serial_con
.login(self
.password
)
124 except BaseException
as e
:
125 self
.log
.error("Could not connect to the domain via serial console")
128 return self
.serial_con
.command(cmd
)
130 def copy_in(self
, fr
, to
):
132 self
.disk
.mount(self
.root_uid
, "/")
133 self
.disk
.copy_in(fr
, to
)
134 except BaseException
as e
:
137 self
.disk
.umount("/")