]> git.ipfire.org Git - nitsi.git/blobdiff - test.py
Add a working virtual environment config
[nitsi.git] / test.py
diff --git a/test.py b/test.py
index d2a6d97907e32e7516087d4edaf55f8185567da5..9df1bd1fdbc0ef88bb0cdd8e79f00d713c5dd9d8 100755 (executable)
--- a/test.py
+++ b/test.py
@@ -10,7 +10,6 @@ import libvirt
 
 import xml.etree.ElementTree as ET
 
-import inspect
 import os
 
 import configparser
@@ -54,7 +53,7 @@ class libvirt_con():
 
 
 class vm():
-    def __init__(self, vm_xml_file, snapshot_xml_file, image, root_uid):
+    def __init__(self, vm_xml_file, snapshot_xml_file, image, root_uid, username, password):
         self.log = log(4)
         self.con = libvirt_con("qemu:///system")
         try:
@@ -76,6 +75,9 @@ class vm():
 
         self.root_uid = root_uid
 
+        self.username = username
+        self.password = password
+
     def define(self):
         self.dom = self.con.con.defineXML(self.vm_xml)
         if self.dom == None:
@@ -107,9 +109,8 @@ class vm():
             raise BaseException
 
     def revert_snapshot(self):
-        print(inspect.getmembers(self.dom, predicate=inspect.ismethod))
         self.dom.revertToSnapshot(self.snapshot)
-        #self.dom.SnapshotDelete(self.snapshot)
+        self.snapshot.delete()
 
     def is_running(self):
 
@@ -139,10 +140,10 @@ class vm():
 
         #serial_con.close()
 
-    def login(self, username, password):
+    def login(self):
         try:
-            self.serial_con = connection(self.get_serial_device(), username="root")
-            self.serial_con.login("25814@root")
+            self.serial_con = connection(self.get_serial_device(), username=self.username)
+            self.serial_con.login(self.password)
         except BaseException as e:
             self.log.error("Could not connect to the domain via serial console")
 
@@ -353,9 +354,33 @@ class connection():
 
 # A class which define and undefine a virtual network based on an xml file
 class network():
-    def __init__(self, path):
+    def __init__(self, network_xml_file):
         self.log = log(4)
-        self.log.debug("Path is: {}".format(path))
+        self.con = libvirt_con("qemu:///system")
+        try:
+            with open(network_xml_file) as fobj:
+                self.network_xml = fobj.read()
+        except FileNotFoundError as error:
+            self.log.error("No such file: {}".format(vm_xml_file))
+
+    def define(self):
+        self.network = self.con.con.networkDefineXML(self.network_xml)
+
+        if network == None:
+            self.log.error("Failed to define virtual network")
+
+    def start(self):
+        self.network.create()
+
+    def undefine(self):
+        self.network.destroy()
+
+
+
+class RecipeExeption(Exception):
+    pass
+
+
 
 # Should read the test, check if the syntax are valid
 # and return tuples with the ( host, command ) structure
@@ -363,6 +388,8 @@ class recipe():
     def __init__(self, path):
         self.log = log(4)
         self.recipe_file = path
+        self._recipe = None
+
         if not os.path.isfile(self.recipe_file):
             self.log.error("No such file: {}".format(self.recipe_file))
 
@@ -372,8 +399,38 @@ class recipe():
         except FileNotFoundError as error:
             self.log.error("No such file: {}".format(vm_xml_file))
 
+    @property
+    def recipe(self):
+        if not self._recipe:
+            self.parse()
+
+        return self._recipe
+
+    def parse(self):
+        self._recipe = []
+        i = 1
         for line in self.raw_recipe:
-            print(line)
+            raw_line = line.split(":")
+            if len(raw_line) < 2:
+                self.log.error("Error parsing the recipe in line {}".format(i))
+                raise RecipeExeption
+            cmd = raw_line[1]
+            raw_line = raw_line[0].strip().split(" ")
+            if len(raw_line) == 0:
+                self.log.error("Failed to parse the recipe in line {}".format(i))
+                raise RecipeExeption
+            elif len(raw_line) == 1:
+                if raw_line[0] == "":
+                    self.log.error("Failed to parse the recipe in line {}".format(i))
+                    raise RecipeExeption
+                machine = raw_line[0]
+                extra = ""
+            elif len(raw_line) == 2:
+                machine = raw_line[0]
+                extra = raw_line[1]
+
+            self._recipe.append((machine.strip(), extra.strip(), cmd.strip()))
+            i = i + 1
 
 
 class test():
@@ -412,16 +469,44 @@ class test():
         self.virtual_machines = self.virtual_environ.get_machines()
 
     def virtual_environ_start(self):
-        pass
+        for name in self.virtual_environ.network_names:
+            self.virtual_networks[name].define()
+            self.virtual_networks[name].start()
 
-    def load_recipe(self):
-        pass
+        for name in self.virtual_environ.machine_names:
+            self.virtual_machines[name].define()
+            self.virtual_machines[name].create_snapshot()
+            self.virtual_machines[name].start()
 
-    def run_recipe():
-        pass
+        self.log.debug("Try to login on all machines")
+        for name in self.virtual_environ.machine_names:
+            self.virtual_machines[name].login()
 
-    def virtual_environ_stop():
-        pass
+    def load_recipe(self):
+        try:
+            self.recipe = recipe(self.recipe_file)
+        except BaseException:
+            self.log.error("Failed to load recipe")
+            exit(1)
+
+    def run_recipe(self):
+        for line in self.recipe.recipe:
+            return_value = self.virtual_machines[line[0]].cmd(line[2])
+            if not return_value and line[1] == "":
+                self.log.error("Failed to execute command '{}' on {}".format(line[2],line[0]))
+                return False
+            elif return_value == True and line[1] == "!":
+                self.log.error("Succeded to execute command '{}' on {}".format(line[2],line[0]))
+                return False
+
+    def virtual_environ_stop(self):
+        for name in self.virtual_environ.machine_names:
+            self.virtual_machines[name].shutdown()
+            self.virtual_machines[name].revert_snapshot()
+            self.virtual_machines[name].undefine()
+
+        for name in self.virtual_environ.network_names:
+            self.virtual_networks[name].undefine()
 
 
 # Should return all vms and networks in a list
@@ -471,10 +556,22 @@ class virtual_environ():
             self.log.debug(_machine)
             machines.setdefault(_machine, vm(
                 os.path.normpath(self.path + "/" + self.config[_machine]["xml_file"]),
-                os.path.normpath(self.path + "/" + self.config[_machine]["snapshot_xml_file"])))
+                os.path.normpath(self.path + "/" + self.config[_machine]["snapshot_xml_file"]),
+                self.config[_machine]["image"],
+                self.config[_machine]["root_uid"],
+                self.config[_machine]["username"],
+                self.config[_machine]["password"]))
 
         return machines
 
+    @property
+    def machine_names(self):
+        return self.machines
+
+    @property
+    def network_names(self):
+        return self.networks
+
 
 if __name__ == "__main__":
     import argparse
@@ -485,7 +582,10 @@ if __name__ == "__main__":
 
     args = parser.parse_args()
 
-    _recipe = recipe("/home/jonatan/python-testing-kvm/test/recipe")
     currenttest = test(args.dir)
     currenttest.read_settings()
-    currenttest.virtual_environ_setup()
\ No newline at end of file
+    currenttest.virtual_environ_setup()
+    currenttest.load_recipe()
+    currenttest.virtual_environ_start()
+    currenttest.run_recipe()
+    currenttest.virtual_environ_stop()
\ No newline at end of file