Merge "add a complete cleanup scripts for compass"
[genesis.git] / fuel / deploy / environments / virtual_fuel.py
1 from lxml import etree
2
3 import common
4 from execution_environment import ExecutionEnvironment
5
6 exec_cmd = common.exec_cmd
7 log = common.log
8 check_file_exists = common.check_file_exists
9 check_if_root = common.check_if_root
10
11 class VirtualFuel(ExecutionEnvironment):
12
13     def __init__(self, storage_dir, pxe_bridge, dha_file, root_dir):
14         super(VirtualFuel, self).__init__(storage_dir, dha_file, root_dir)
15         self.pxe_bridge = pxe_bridge
16
17     def set_vm_nic(self, temp_vm_file):
18         with open(temp_vm_file) as f:
19             vm_xml = etree.parse(f)
20         interfaces = vm_xml.xpath('/domain/devices/interface')
21         for interface in interfaces:
22             interface.getparent().remove(interface)
23         interface = etree.Element('interface')
24         interface.set('type', 'bridge')
25         source = etree.SubElement(interface, 'source')
26         source.set('bridge', self.pxe_bridge)
27         model = etree.SubElement(interface, 'model')
28         model.set('type', 'virtio')
29         devices = vm_xml.xpath('/domain/devices')
30         if devices:
31             device = devices[0]
32             device.append(interface)
33         with open(temp_vm_file, 'w') as f:
34             vm_xml.write(f, pretty_print=True, xml_declaration=True)
35
36     def create_vm(self):
37         temp_dir = exec_cmd('mktemp -d')
38         vm_name = self.dha.get_node_property(self.fuel_node_id, 'libvirtName')
39         vm_template = '%s/%s' % (self.root_dir,
40                                  self.dha.get_node_property(
41                                      self.fuel_node_id, 'libvirtTemplate'))
42         check_file_exists(vm_template)
43         disk_path = '%s/%s.raw' % (self.storage_dir, vm_name)
44         disk_sizes = self.dha.get_disks()
45         disk_size = disk_sizes['fuel']
46         exec_cmd('fallocate -l %s %s' % (disk_size, disk_path))
47         temp_vm_file = '%s/%s' % (temp_dir, vm_name)
48         exec_cmd('cp %s %s' % (vm_template, temp_vm_file))
49         self.set_vm_nic(temp_vm_file)
50         self.define_vm(vm_name, temp_vm_file, disk_path)
51         exec_cmd('rm -fr %s' % temp_dir)
52
53     def setup_environment(self):
54         check_if_root()
55         self.cleanup_environment()
56         self.create_vm()
57
58     def cleanup_environment(self):
59         self.delete_vm(self.fuel_node_id)