1 ##############################################################################
2 # Copyright (c) 2017 Tim Rozet (trozet@redhat.com) and others.
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 ##############################################################################
18 from apex.virtual import utils as virt_utils
19 from apex.virtual import configure_vm as vm_lib
20 from apex.common import constants
21 from apex.common import utils
24 class ApexUndercloudException(Exception):
30 This class represents an Apex Undercloud VM
32 def __init__(self, image_path, template_path,
33 root_pw=None, external_network=False,
34 image_name='undercloud.qcow2'):
36 self.root_pw = root_pw
37 self.external_net = external_network
38 self.volume = os.path.join(constants.LIBVIRT_VOLUME_PATH,
40 self.image_path = image_path
41 self.image_name = image_name
42 self.template_path = template_path
44 if Undercloud._get_vm():
45 logging.error("Undercloud VM already exists. Please clean "
47 raise ApexUndercloudException("Undercloud VM already exists!")
52 conn = libvirt.open('qemu:///system')
54 vm = conn.lookupByName('undercloud')
56 except libvirt.libvirtError:
57 logging.debug("No undercloud VM exists")
62 networks.append('external')
63 console = 'ttyAMA0' if platform.machine() == 'aarch64' else 'ttyS0'
65 self.vm = vm_lib.create_vm(name='undercloud',
67 baremetal_interfaces=networks,
68 direct_boot='overcloud-full',
69 kernel_args=['console={}'.format(console),
72 template_dir=self.template_path)
77 ip_out = self.vm.interfaceAddresses(
78 libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, 0)
80 for (name, val) in ip_out.items():
81 for ipaddr in val['addrs']:
82 if ipaddr['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4:
83 self.ip = ipaddr['addr']
91 if self.vm.isActive():
92 logging.info("Undercloud already started")
94 logging.info("Starting undercloud")
96 # give 10 seconds to come up
101 logging.info("Undercloud started. IP Address: {}".format(
104 logging.debug("Did not find undercloud IP in {} "
105 "attempts...".format(x))
108 logging.error("Cannot find IP for Undercloud")
109 raise ApexUndercloudException(
110 "Unable to find IP for undercloud. Check if VM booted "
113 def configure(self, net_settings, playbook, apex_temp_dir):
115 Configures undercloud VM
116 :param net_setings: Network settings for deployment
117 :param playbook: playbook to use to configure undercloud
118 :param apex_temp_dir: temporary apex directory to hold configs/logs
122 logging.info("Configuring Undercloud...")
124 ansible_vars = Undercloud.generate_config(net_settings)
125 ansible_vars['apex_temp_dir'] = apex_temp_dir
127 utils.run_ansible(ansible_vars, playbook, host=self.ip,
129 except subprocess.CalledProcessError:
131 "Failed to install undercloud..."
132 "please check log: {}".format(os.path.join(
133 apex_temp_dir, 'apex-undercloud-install.log')))
134 raise ApexUndercloudException('Failed to install undercloud')
135 logging.info("Undercloud installed!")
137 def setup_volumes(self):
138 for img_file in ('overcloud-full.vmlinuz', 'overcloud-full.initrd',
140 src_img = os.path.join(self.image_path, img_file)
141 if img_file == self.image_name:
142 dest_img = os.path.join(constants.LIBVIRT_VOLUME_PATH,
145 dest_img = os.path.join(constants.LIBVIRT_VOLUME_PATH,
147 if not os.path.isfile(src_img):
148 raise ApexUndercloudException(
149 "Required source file does not exist:{}".format(src_img))
150 if os.path.exists(dest_img):
152 shutil.copyfile(src_img, dest_img)
153 shutil.chown(dest_img, user='qemu', group='qemu')
154 os.chmod(dest_img, 0o0744)
155 # TODO(trozet):check if resize needed right now size is 50gb
156 # there is a lib called vminspect which has some dependencies and is
157 # not yet available in pip. Consider switching to this lib later.
159 def inject_auth(self):
161 # virt-customize keys/pws
163 pw_op = "password:{}".format(self.root_pw)
164 virt_ops.append({constants.VIRT_PW: pw_op})
166 virt_ops.append({constants.VIRT_RUN_CMD:
167 'mkdir -p /root/.ssh'})
168 virt_ops.append({constants.VIRT_UPLOAD:
169 '/root/.ssh/id_rsa.pub:/root/.ssh/authorized_keys'})
171 'chmod 600 /root/.ssh/authorized_keys',
172 'restorecon /root/.ssh/authorized_keys',
173 'cp /root/.ssh/authorized_keys /home/stack/.ssh/',
174 'chown stack:stack /home/stack/.ssh/authorized_keys',
175 'chmod 600 /home/stack/.ssh/authorized_keys'
178 virt_ops.append({constants.VIRT_RUN_CMD: cmd})
179 virt_utils.virt_customize(virt_ops, self.volume)
182 def generate_config(ns):
184 Generates a dictionary of settings for configuring undercloud
185 :param ns: network settings to derive undercloud settings
186 :return: dictionary of settings
189 ns_admin = ns['networks']['admin']
190 intro_range = ns['apex']['networks']['admin']['introspection_range']
192 config['undercloud_config'] = [
194 "undercloud_update_packages false",
195 "undercloud_debug false",
196 "inspection_extras false",
197 "undercloud_hostname undercloud.{}".format(ns['dns-domain']),
198 "local_ip {}/{}".format(str(ns_admin['installer_vm']['ip']),
199 str(ns_admin['cidr']).split('/')[1]),
200 "network_gateway {}".format(str(ns_admin['installer_vm']['ip'])),
201 "network_cidr {}".format(str(ns_admin['cidr'])),
202 "dhcp_start {}".format(str(ns_admin['dhcp_range'][0])),
203 "dhcp_end {}".format(str(ns_admin['dhcp_range'][1])),
204 "inspection_iprange {}".format(','.join(intro_range))
207 config['ironic_config'] = [
208 "disk_utils iscsi_verify_attempts 30",
209 "disk_partitioner check_device_max_retries 40"
212 config['nova_config'] = [
213 "dns_domain {}".format(ns['dns-domain']),
214 "dhcp_domain {}".format(ns['dns-domain'])
217 config['neutron_config'] = [
218 "dns_domain {}".format(ns['dns-domain']),
220 # FIXME(trozet): possible bug here with not using external network
221 ns_external = ns['networks']['external'][0]
222 config['external_network'] = {
223 "vlan": ns_external['installer_vm']['vlan'],
224 "ip": ns_external['installer_vm']['ip'],
225 "prefix": str(ns_external['cidr']).split('/')[1],
226 "enabled": ns_external['enabled']
229 # Check if this is an ARM deployment
230 config['aarch64'] = platform.machine() == 'aarch64'