Merge "Add openstack HA installer code with ansible for compass adapter"
[genesis.git] / fuel / deploy / environments / execution_environment.py
1 from lxml import etree
2
3 import common
4 from dha_adapters.libvirt_adapter import LibvirtAdapter
5
6 exec_cmd = common.exec_cmd
7 err = common.err
8 log = common.log
9 check_dir_exists = common.check_dir_exists
10 check_file_exists = common.check_file_exists
11 check_if_root = common.check_if_root
12
13 class ExecutionEnvironment(object):
14
15     def __init__(self, storage_dir, dha_file, root_dir):
16         self.storage_dir = storage_dir
17         self.dha = LibvirtAdapter(dha_file)
18         self.root_dir = root_dir
19         self.parser = etree.XMLParser(remove_blank_text=True)
20         self.fuel_node_id = self.dha.get_fuel_node_id()
21
22     def delete_vm(self, node_id):
23         vm_name = self.dha.get_node_property(node_id, 'libvirtName')
24         r, c = exec_cmd('virsh dumpxml %s' % vm_name, False)
25         if c:
26             return
27         self.undefine_vm_delete_disk(r, vm_name)
28
29     def undefine_vm_delete_disk(self, printout, vm_name):
30         disk_files = []
31         xml_dump = etree.fromstring(printout, self.parser)
32         disks = xml_dump.xpath('/domain/devices/disk')
33         for disk in disks:
34             sources = disk.xpath('source')
35             for source in sources:
36                 source_file = source.get('file')
37                 if source_file:
38                     disk_files.append(source_file)
39         log('Deleting VM %s with disks %s' % (vm_name, disk_files))
40         exec_cmd('virsh destroy %s' % vm_name, False)
41         exec_cmd('virsh undefine %s' % vm_name, False)
42         for file in disk_files:
43             exec_cmd('rm -f %s' % file)
44
45     def define_vm(self, vm_name, temp_vm_file, disk_path):
46         log('Creating VM %s with disks %s' % (vm_name, disk_path))
47         with open(temp_vm_file) as f:
48             vm_xml = etree.parse(f)
49         names = vm_xml.xpath('/domain/name')
50         for name in names:
51             name.text = vm_name
52         uuids = vm_xml.xpath('/domain/uuid')
53         for uuid in uuids:
54             uuid.getparent().remove(uuid)
55         disks = vm_xml.xpath('/domain/devices/disk')
56         for disk in disks:
57             if (disk.get('type') == 'file'
58                 and disk.get('device') == 'disk'):
59                 sources = disk.xpath('source')
60                 for source in sources:
61                     disk.remove(source)
62                 source = etree.Element('source')
63                 source.set('file', disk_path)
64                 disk.append(source)
65         with open(temp_vm_file, 'w') as f:
66             vm_xml.write(f, pretty_print=True, xml_declaration=True)
67         exec_cmd('virsh define %s' % temp_vm_file)