Add more stuff to the virtual_environ() class
[nitsi.git] / test.py
1 #!/usr/bin/python3
2
3 import serial
4
5 import re
6 from time import sleep
7 import sys
8
9 import libvirt
10
11 import xml.etree.ElementTree as ET
12
13 import os
14
15 import configparser
16
17 class log():
18     def __init__(self, log_level):
19         self.log_level = log_level
20
21     def debug(self, string):
22         if self.log_level >= 4:
23             print("DEBUG: {}".format(string))
24
25     def error(self, string):
26         print("ERROR: {}".format(string))
27
28 class libvirt_con():
29     def __init__(self, uri):
30         self.log = log(4)
31         self.uri = uri
32         self.connection = None
33
34     def get_domain_from_name(self, name):
35         dom = self.con.lookupByName(name)
36
37         if dom == None:
38             raise BaseException
39         return dom
40
41     @property
42     def con(self):
43         if self.connection == None:
44             try:
45                 self.connection = libvirt.open(self.uri)
46             except BaseException as error:
47                 self.log.error("Could not connect to: {}".format(self.uri))
48
49             self.log.debug("Connected to: {}".format(self.uri))
50             return self.connection
51
52         return self.connection
53
54
55 class vm():
56     def __init__(self, vm_xml_file, snapshot_xml_file, image, root_uid, username, password):
57         self.log = log(4)
58         self.con = libvirt_con("qemu:///system")
59         try:
60             with open(vm_xml_file) as fobj:
61                 self.vm_xml = fobj.read()
62         except FileNotFoundError as error:
63             self.log.error("No such file: {}".format(vm_xml_file))
64
65         try:
66             with open(snapshot_xml_file) as fobj:
67                 self.snapshot_xml = fobj.read()
68         except FileNotFoundError as error:
69             self.log.error("No such file: {}".format(snapshot_xml_file))
70
71         self.image = image
72
73         if not os.path.isfile(self.image):
74             self.log.error("No such file: {}".format(self.image))
75
76         self.root_uid = root_uid
77
78         self.username = username
79         self.password = password
80
81     def define(self):
82         self.dom = self.con.con.defineXML(self.vm_xml)
83         if self.dom == None:
84             self.log.error("Could not define VM")
85             raise BaseException
86
87     def start(self):
88         if self.dom.create() < 0:
89             self.log.error("Could not start VM")
90             raise BaseException
91
92     def shutdown(self):
93         if self.is_running():
94             if self.dom.shutdown() < 0:
95                 self.log.error("Could not shutdown VM")
96                 raise BaseException
97         else:
98             self.log.error("Domain is not running")
99
100     def undefine(self):
101         self.dom.undefine()
102
103     def create_snapshot(self):
104
105         self.snapshot = self.dom.snapshotCreateXML(self.snapshot_xml)
106
107         if not self.snapshot:
108             self.log.error("Could not create snapshot")
109             raise BaseException
110
111     def revert_snapshot(self):
112         self.dom.revertToSnapshot(self.snapshot)
113         self.snapshot.delete()
114
115     def is_running(self):
116
117         state, reason = self.dom.state()
118
119         if state == libvirt.VIR_DOMAIN_RUNNING:
120             return True
121         else:
122             return False
123
124     def get_serial_device(self):
125
126         if not self.is_running():
127             raise BaseException
128
129         xml_root = ET.fromstring(self.dom.XMLDesc(0))
130
131         elem = xml_root.find("./devices/serial/source")
132         return elem.get("path")
133
134     def check_is_booted_up(self):
135         serial_con = connection(self.get_serial_device())
136
137         serial_con.write("\n")
138         # This will block till the domain is booted up
139         serial_con.read(1)
140
141         #serial_con.close()
142
143     def login(self):
144         try:
145             self.serial_con = connection(self.get_serial_device(), username=self.username)
146             self.serial_con.login(self.password)
147         except BaseException as e:
148             self.log.error("Could not connect to the domain via serial console")
149
150     def cmd(self, cmd):
151         return self.serial_con.command(cmd)
152
153
154 class connection():
155     def __init__(self, device, username=None):
156         self.buffer = b""
157         self.back_at_prompt_pattern =  None
158         self.username = username
159         self.log = log(1)
160         self.con = serial.Serial(device)
161
162     def read(self, size=1):
163         if len(self.buffer) >= size:
164             # throw away first size bytes in buffer
165             data =  self.buffer[:size]
166             # Set the buffer to the non used bytes
167             self.buffer = self.buffer[size:]
168             return data
169         else:
170             data = self.buffer
171             # Set the size to the value we have to read now
172             size = size - len(self.buffer)
173             # Set the buffer empty
174             self.buffer = b""
175             return data + self.con.read(size)
176
177     def peek(self, size=1):
178         if len(self.buffer) <= size:
179             self.buffer += self.con.read(size=size - len(self.buffer))
180
181         return self.buffer[:size]
182
183     def readline(self):
184         self.log.debug(self.buffer)
185         self.buffer = self.buffer + self.con.read(self.con.in_waiting)
186         if b"\n" in self.buffer:
187             size = self.buffer.index(b"\n") + 1
188             self.log.debug("We have a whole line in the buffer")
189             self.log.debug(self.buffer)
190             self.log.debug("We split at {}".format(size))
191             data = self.buffer[:size]
192             self.buffer = self.buffer[size:]
193             self.log.debug(data)
194             self.log.debug(self.buffer)
195             return data
196
197         data = self.buffer
198         self.buffer = b""
199         return data + self.con.readline()
200
201     def back_at_prompt(self):
202         data = self.peek()
203         if not data == b"[":
204             return False
205
206         # We need to use self.in_waiting because with self.con.in_waiting we get
207         # not the complete string
208         size = len(self.buffer) + self.in_waiting
209         data = self.peek(size)
210
211
212         if self.back_at_prompt_pattern == None:
213             #self.back_at_prompt_pattern = r"^\[{}@.+\]#".format(self.username)
214             self.back_at_prompt_pattern = re.compile(r"^\[{}@.+\]#".format(self.username), re.MULTILINE)
215
216         if self.back_at_prompt_pattern.search(data.decode()):
217             return True
218         else:
219             return False
220
221     def log_console_line(self, line):
222         self.log.debug("Get in function log_console_line()")
223         sys.stdout.write(line)
224
225     @property
226     def in_waiting(self):
227         in_waiting_before = 0
228         sleep(0.5)
229
230         while in_waiting_before != self.con.in_waiting:
231             in_waiting_before = self.con.in_waiting
232             sleep(0.5)
233
234         return self.con.in_waiting
235
236
237     def readline2(self, pattern=None):
238         string = ""
239         string2 = b""
240         if pattern:
241             pattern = re.compile(pattern)
242
243         while 1:
244             char = self.con.read(1)
245             string = string + char.decode("utf-8")
246             string2 = string2 + char
247             #print(char)
248             print(char.decode("utf-8"), end="")
249
250             #print(string2)
251             if pattern and pattern.match(string):
252                #print("get here1")
253                #print(string2)
254                return {"string" : string, "return-code" : 1}
255
256             if char == b"\n":
257                 #print(char)
258                 #print(string2)
259                 #print("get here2")
260                 return {"return-code" : 0}
261
262     def check_logged_in(self, username):
263         pattern = "^\[" + username + "@.+\]#"
264         data = self.readline(pattern=pattern)
265         if data["return-code"] == 1:
266                 print("We are logged in")
267                 return True
268         else:
269             print("We are  not logged in")
270             return False
271
272     def login(self, password):
273         if self.username == None:
274             self.log.error("Username cannot be blank")
275             return False
276
277         # Hit enter to see what we get
278         self.con.write(b'\n')
279         # We get two new lines \r\n ?
280         data = self.readline()
281         self.log_console_line(data.decode())
282
283
284         if self.back_at_prompt():
285             self.log.debug("We are already logged in.")
286             return True
287
288         # Read all line till we get login:
289         while 1:
290             data = self.peek()
291             if not data.decode() == "l":
292                 self.log.debug("We get no l at the start")
293                 self.log_console_line(self.readline().decode())
294
295             # We need to use self.in_waiting because with self.con.in_waiting we get
296             # not the complete string
297             size = len(self.buffer) + self.in_waiting
298             data = self.peek(size)
299
300             pattern = r"^.*login: "
301             pattern = re.compile(pattern)
302
303             if pattern.search(data.decode()):
304                 break
305             else:
306                 self.log.debug("The pattern does not match")
307                 self.log_console_line(self.readline().decode())
308
309         # We can login
310         string = "{}\n".format(self.username)
311         self.con.write(string.encode())
312         self.con.flush()
313         # read the login out of the buffer
314         data = self.readline()
315         self.log.debug("This is the login:{}".format(data))
316         self.log_console_line(data.decode())
317
318         # We need to wait her till we get the full string "Password:"
319         #This is useless but self.in_waiting will wait the correct amount of time
320         size = self.in_waiting
321
322         string = "{}\n".format(password)
323         self.con.write(string.encode())
324         self.con.flush()
325         # Print the 'Password:' line
326         data = self.readline()
327         self.log_console_line(data.decode())
328
329         while not self.back_at_prompt():
330             # This will fail if the login failed so we need to look for the failed keyword
331             data = self.readline()
332             self.log_console_line(data.decode())
333
334         return True
335
336     def write(self, string):
337         self.log.debug(string)
338         self.con.write(string.encode())
339         self.con.flush()
340
341     def command(self, command):
342         self.write("{}\n".format(command))
343
344         # We need to read out the prompt for this command first
345         # If we do not do this we will break the loop immediately
346         # because the prompt for this command is still in the buffer
347         data = self.readline()
348         self.log_console_line(data.decode())
349
350         while not self.back_at_prompt():
351             data = self.readline()
352             self.log_console_line(data.decode())
353
354
355 # A class which define and undefine a virtual network based on an xml file
356 class network():
357     def __init__(self, network_xml_file):
358         self.log = log(4)
359         self.con = libvirt_con("qemu:///system")
360         try:
361             with open(network_xml_file) as fobj:
362                 self.network_xml = fobj.read()
363         except FileNotFoundError as error:
364             self.log.error("No such file: {}".format(vm_xml_file))
365
366     def define(self):
367         self.network = self.con.con.networkDefineXML(self.network_xml)
368
369         if network == None:
370             self.log.error("Failed to define virtual network")
371
372     def start(self):
373         self.network.create()
374
375     def undefine(self):
376         self.network.destroy()
377
378
379
380 class RecipeExeption(Exception):
381     pass
382
383
384
385 # Should read the test, check if the syntax are valid
386 # and return tuples with the ( host, command ) structure
387 class recipe():
388     def __init__(self, path):
389         self.log = log(4)
390         self.recipe_file = path
391         self._recipe = None
392
393         if not os.path.isfile(self.recipe_file):
394             self.log.error("No such file: {}".format(self.recipe_file))
395
396         try:
397             with open(self.recipe_file) as fobj:
398                 self.raw_recipe = fobj.readlines()
399         except FileNotFoundError as error:
400             self.log.error("No such file: {}".format(vm_xml_file))
401
402     @property
403     def recipe(self):
404         if not self._recipe:
405             self.parse()
406
407         return self._recipe
408
409     def parse(self):
410         self._recipe = []
411         i = 1
412         for line in self.raw_recipe:
413             raw_line = line.split(":")
414             if len(raw_line) < 2:
415                 self.log.error("Error parsing the recipe in line {}".format(i))
416                 raise RecipeExeption
417             cmd = raw_line[1]
418             raw_line = raw_line[0].strip().split(" ")
419             if len(raw_line) == 0:
420                 self.log.error("Failed to parse the recipe in line {}".format(i))
421                 raise RecipeExeption
422             elif len(raw_line) == 1:
423                 if raw_line[0] == "":
424                     self.log.error("Failed to parse the recipe in line {}".format(i))
425                     raise RecipeExeption
426                 machine = raw_line[0]
427                 extra = ""
428             elif len(raw_line) == 2:
429                 machine = raw_line[0]
430                 extra = raw_line[1]
431
432             self._recipe.append((machine.strip(), extra.strip(), cmd.strip()))
433             i = i + 1
434
435
436 class test():
437     def __init__(self, path):
438         self.log = log(4)
439         try:
440             self.path = os.path.abspath(path)
441         except BaseException as e:
442             self.log.error("Could not get absolute path")
443
444         self.log.debug(self.path)
445
446         self.settings_file = "{}/settings".format(self.path)
447         if not os.path.isfile(self.settings_file):
448             self.log.error("No such file: {}".format(self.settings_file))
449
450         self.recipe_file = "{}/recipe".format(self.path)
451         if not os.path.isfile(self.recipe_file):
452             self.log.error("No such file: {}".format(self.recipe_file))
453
454     def read_settings(self):
455         self.config = configparser.ConfigParser()
456         self.config.read(self.settings_file)
457         self.name = self.config["DEFAULT"]["Name"]
458         self.description = self.config["DEFAULT"]["Description"]
459
460         self.virtual_environ_name = self.config["VIRTUAL_ENVIRONMENT"]["Name"]
461         self.virtual_environ_path = self.config["VIRTUAL_ENVIRONMENT"]["Path"]
462         self.virtual_environ_path = os.path.normpath(self.path + "/" + self.virtual_environ_path)
463
464     def virtual_environ_setup(self):
465         self.virtual_environ = virtual_environ(self.virtual_environ_path)
466
467         self.virtual_networks = self.virtual_environ.get_networks()
468
469         self.virtual_machines = self.virtual_environ.get_machines()
470
471     def virtual_environ_start(self):
472         for name in self.virtual_environ.network_names:
473             self.virtual_networks[name].define()
474             self.virtual_networks[name].start()
475
476         for name in self.virtual_environ.machine_names:
477             self.virtual_machines[name].define()
478             self.virtual_machines[name].create_snapshot()
479             self.virtual_machines[name].start()
480
481         self.log.debug("Try to login on all machines")
482         for name in self.virtual_environ.machine_names:
483             self.virtual_machines[name].login()
484
485     def load_recipe(self):
486         try:
487             self.recipe = recipe(self.recipe_file)
488         except BaseException:
489             self.log.error("Failed to load recipe")
490             exit(1)
491
492     def run_recipe(self):
493         for line in self.recipe.recipe:
494             return_value = self.virtual_machines[line[0]].cmd(line[2])
495             if not return_value and line[1] == "":
496                 self.log.error("Failed to execute command '{}' on {}".format(line[2],line[0]))
497                 return False
498             elif return_value == True and line[1] == "!":
499                 self.log.error("Succeded to execute command '{}' on {}".format(line[2],line[0]))
500                 return False
501
502     def virtual_environ_stop(self):
503         for name in self.virtual_environ.machine_names:
504             self.virtual_machines[name].shutdown()
505             self.virtual_machines[name].revert_snapshot()
506             self.virtual_machines[name].undefine()
507
508         for name in self.virtual_environ.network_names:
509             self.virtual_networks[name].undefine()
510
511
512 # Should return all vms and networks in a list
513 # and should provide the path to the necessary xml files
514 class virtual_environ():
515     def __init__(self, path):
516         self.log = log(4)
517         try:
518             self.path = os.path.abspath(path)
519         except BaseException as e:
520             self.log.error("Could not get absolute path")
521
522         self.log.debug(self.path)
523
524         self.settings_file = "{}/settings".format(self.path)
525         if not os.path.isfile(self.settings_file):
526             self.log.error("No such file: {}".format(self.settings_file))
527
528         self.log.debug(self.settings_file)
529         self.config = configparser.ConfigParser()
530         self.config.read(self.settings_file)
531         self.name = self.config["DEFAULT"]["name"]
532         self.machines_string = self.config["DEFAULT"]["machines"]
533         self.networks_string = self.config["DEFAULT"]["networks"]
534
535         self.machines = []
536         for machine in self.machines_string.split(","):
537             self.machines.append(machine.strip())
538
539         self.networks = []
540         for network in self.networks_string.split(","):
541             self.networks.append(network.strip())
542
543         self.log.debug(self.machines)
544         self.log.debug(self.networks)
545
546     def get_networks(self):
547         networks = {}
548         for _network in self.networks:
549             self.log.debug(_network)
550             networks.setdefault(_network, network(os.path.normpath(self.path + "/" + self.config[_network]["xml_file"])))
551         return networks
552
553     def get_machines(self):
554         machines = {}
555         for _machine in self.machines:
556             self.log.debug(_machine)
557             machines.setdefault(_machine, vm(
558                 os.path.normpath(self.path + "/" + self.config[_machine]["xml_file"]),
559                 os.path.normpath(self.path + "/" + self.config[_machine]["snapshot_xml_file"]),
560                 self.config[_machine]["image"],
561                 self.config[_machine]["root_uid"],
562                 self.config[_machine]["username"],
563                 self.config[_machine]["password"]))
564
565         return machines
566
567     @property
568     def machine_names(self):
569         return self.machines
570
571     @property
572     def network_names(self):
573         return self.networks
574
575
576 if __name__ == "__main__":
577     import argparse
578
579     parser = argparse.ArgumentParser()
580
581     parser.add_argument("-d", "--directory", dest="dir")
582
583     args = parser.parse_args()
584
585     _recipe = recipe("/home/jonatan/python-testing-kvm/test/recipe")
586     currenttest = test(args.dir)
587     currenttest.read_settings()
588     currenttest.virtual_environ_setup()