Refactor temporary directory creation
[fuel.git] / deploy / environments / virtual_fuel.py
1 ###############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # szilard.cserey@ericsson.com
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ###############################################################################
9
10
11 from lxml import etree
12 from execution_environment import ExecutionEnvironment
13 import tempfile
14
15 from common import (
16     exec_cmd,
17     check_file_exists,
18     check_if_root,
19     delete,
20 )
21
22
23 class VirtualFuel(ExecutionEnvironment):
24
25     def __init__(self, storage_dir, pxe_bridge, dha_file, root_dir):
26         super(VirtualFuel, self).__init__(storage_dir, dha_file, root_dir)
27         self.pxe_bridge = pxe_bridge
28
29     def set_vm_nic(self, temp_vm_file):
30         with open(temp_vm_file) as f:
31             vm_xml = etree.parse(f)
32         interfaces = vm_xml.xpath('/domain/devices/interface')
33         for interface in interfaces:
34             interface.getparent().remove(interface)
35         interface = etree.Element('interface')
36         interface.set('type', 'bridge')
37         source = etree.SubElement(interface, 'source')
38         source.set('bridge', self.pxe_bridge)
39         model = etree.SubElement(interface, 'model')
40         model.set('type', 'virtio')
41         devices = vm_xml.xpath('/domain/devices')
42         if devices:
43             device = devices[0]
44             device.append(interface)
45         with open(temp_vm_file, 'w') as f:
46             vm_xml.write(f, pretty_print=True, xml_declaration=True)
47
48     def create_vm(self):
49         temp_dir = tempfile.mkdtemp()
50         vm_name = self.dha.get_node_property(self.fuel_node_id, 'libvirtName')
51         vm_template = '%s/%s' % (self.root_dir,
52                                  self.dha.get_node_property(
53                                      self.fuel_node_id, 'libvirtTemplate'))
54         check_file_exists(vm_template)
55         disk_path = '%s/%s.raw' % (self.storage_dir, vm_name)
56         disk_sizes = self.dha.get_disks()
57         disk_size = disk_sizes['fuel']
58         exec_cmd('fallocate -l %s %s' % (disk_size, disk_path))
59         temp_vm_file = '%s/%s' % (temp_dir, vm_name)
60         exec_cmd('cp %s %s' % (vm_template, temp_vm_file))
61         self.set_vm_nic(temp_vm_file)
62         self.define_vm(vm_name, temp_vm_file, disk_path)
63         delete(temp_dir)
64
65     def setup_environment(self):
66         check_if_root()
67         self.cleanup_environment()
68         self.create_vm()
69
70     def cleanup_environment(self):
71         self.delete_vm(self.fuel_node_id)