d8570729211d10fb0ca8b02e3c15d7becbdd7313
[nitsi.git] / virtual_environ.py
1 #!/usr/bin/python3
2
3 from machine import machine
4
5 from network import network
6
7 import os
8 import configparser
9 import libvirt
10
11 # Should return all vms and networks in a list
12 # and should provide the path to the necessary xml files
13 class virtual_environ():
14     def __init__(self, path):
15         self.log = log(4)
16         try:
17             self.path = os.path.abspath(path)
18         except BaseException as e:
19             self.log.error("Could not get absolute path")
20
21         self.log.debug(self.path)
22
23         self.settings_file = "{}/settings".format(self.path)
24         if not os.path.isfile(self.settings_file):
25             self.log.error("No such file: {}".format(self.settings_file))
26
27         self.log.debug(self.settings_file)
28         self.config = configparser.ConfigParser()
29         self.config.read(self.settings_file)
30         self.name = self.config["DEFAULT"]["name"]
31         self.machines_string = self.config["DEFAULT"]["machines"]
32         self.networks_string = self.config["DEFAULT"]["networks"]
33
34         self.machines = []
35         for machine in self.machines_string.split(","):
36             self.machines.append(machine.strip())
37
38         self.networks = []
39         for network in self.networks_string.split(","):
40             self.networks.append(network.strip())
41
42         self.log.debug(self.machines)
43         self.log.debug(self.networks)
44
45         self.uri = self.config["DEFAULT"]["uri"]
46
47         try:
48             self.con = libvirt.open(self.uri)
49         except BaseException as error:
50             self.log.error("Could not connect to: {}".format(self.uri))
51
52         self.log.debug("Connected to: {}".format(self.uri))
53
54     def get_networks(self):
55         networks = {}
56         for _network in self.networks:
57             self.log.debug(_network)
58             networks.setdefault(_network, network(self.con, os.path.normpath(self.path + "/" + self.config[_network]["xml_file"])))
59         return networks
60
61     def get_machines(self):
62         machines = {}
63         for _machine in self.machines:
64             self.log.debug(_machine)
65             machines.setdefault(_machine, machine(
66                 self.con,
67                 os.path.normpath(self.path + "/" + self.config[_machine]["xml_file"]),
68                 os.path.normpath(self.path + "/" + self.config[_machine]["snapshot_xml_file"]),
69                 self.config[_machine]["image"],
70                 self.config[_machine]["root_uid"],
71                 self.config[_machine]["username"],
72                 self.config[_machine]["password"]))
73
74         return machines
75
76     @property
77     def machine_names(self):
78         return self.machines
79
80     @property
81     def network_names(self):
82         return self.networks