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 virtual_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):
35 self.root_pw = root_pw
36 self.external_net = external_network
37 self.volume = os.path.join(constants.LIBVIRT_VOLUME_PATH,
39 self.image_path = image_path
40 self.template_path = template_path
42 if Undercloud._get_vm():
43 logging.error("Undercloud VM already exists. Please clean "
45 raise ApexUndercloudException("Undercloud VM already exists!")
50 conn = libvirt.open('qemu:///system')
52 vm = conn.lookupByName('undercloud')
54 except libvirt.libvirtError:
55 logging.debug("No undercloud VM exists")
60 networks.append('external')
61 self.vm = vm_lib.create_vm(name='undercloud',
63 baremetal_interfaces=networks,
64 direct_boot='overcloud-full',
65 kernel_args=['console=ttyS0',
68 template_dir=self.template_path)
73 ip_out = self.vm.interfaceAddresses(
74 libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, 0)
76 for (name, val) in ip_out.items():
77 for ipaddr in val['addrs']:
78 if ipaddr['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4:
79 self.ip = ipaddr['addr']
87 if self.vm.isActive():
88 logging.info("Undercloud already started")
90 logging.info("Starting undercloud")
92 # give 10 seconds to come up
97 logging.info("Undercloud started. IP Address: {}".format(
100 logging.debug("Did not find undercloud IP in {} "
101 "attempts...".format(x))
104 logging.error("Cannot find IP for Undercloud")
105 raise ApexUndercloudException(
106 "Unable to find IP for undercloud. Check if VM booted "
109 def configure(self, net_settings, playbook, apex_temp_dir):
111 Configures undercloud VM
112 :param net_setings: Network settings for deployment
113 :param playbook: playbook to use to configure undercloud
114 :param apex_temp_dir: temporary apex directory to hold configs/logs
118 logging.info("Configuring Undercloud...")
120 ansible_vars = Undercloud.generate_config(net_settings)
121 ansible_vars['apex_temp_dir'] = apex_temp_dir
123 utils.run_ansible(ansible_vars, playbook, host=self.ip,
125 except subprocess.CalledProcessError:
127 "Failed to install undercloud..."
128 "please check log: {}".format(os.path.join(
129 apex_temp_dir, 'apex-undercloud-install.log')))
130 raise ApexUndercloudException('Failed to install undercloud')
131 logging.info("Undercloud installed!")
133 def setup_volumes(self):
134 for img_file in ('overcloud-full.vmlinuz', 'overcloud-full.initrd',
136 src_img = os.path.join(self.image_path, img_file)
137 dest_img = os.path.join(constants.LIBVIRT_VOLUME_PATH, img_file)
138 if not os.path.isfile(src_img):
139 raise ApexUndercloudException(
140 "Required source file does not exist:{}".format(src_img))
141 if os.path.exists(dest_img):
143 shutil.copyfile(src_img, dest_img)
145 # TODO(trozet):check if resize needed right now size is 50gb
146 # there is a lib called vminspect which has some dependencies and is
147 # not yet available in pip. Consider switching to this lib later.
148 # execute ansible playbook
150 def inject_auth(self):
152 # virt-customize keys/pws
154 pw_op = "password:{}".format(self.root_pw)
155 virt_ops.append({constants.VIRT_PW: pw_op})
157 virt_ops.append({constants.VIRT_RUN_CMD:
158 'mkdir -p /root/.ssh'})
159 virt_ops.append({constants.VIRT_UPLOAD:
160 '/root/.ssh/id_rsa.pub:/root/.ssh/authorized_keys'})
162 'chmod 600 /root/.ssh/authorized_keys',
163 'restorecon /root/.ssh/authorized_keys',
164 'cp /root/.ssh/authorized_keys /home/stack/.ssh/',
165 'chown stack:stack /home/stack/.ssh/authorized_keys',
166 'chmod 600 /home/stack/.ssh/authorized_keys'
169 virt_ops.append({constants.VIRT_RUN_CMD: cmd})
170 virt_utils.virt_customize(virt_ops, self.volume)
173 def generate_config(ns):
175 Generates a dictionary of settings for configuring undercloud
176 :param ns: network settings to derive undercloud settings
177 :return: dictionary of settings
180 ns_admin = ns['networks']['admin']
181 intro_range = ns['apex']['networks']['admin']['introspection_range']
183 config['undercloud_config'] = [
185 "undercloud_update_packages false",
186 "undercloud_debug false",
187 "undercloud_hostname undercloud.{}".format(ns['dns-domain']),
188 "local_ip {}/{}".format(str(ns_admin['installer_vm']['ip']),
189 str(ns_admin['cidr']).split('/')[1]),
190 "network_gateway {}".format(str(ns_admin['installer_vm']['ip'])),
191 "network_cidr {}".format(str(ns_admin['cidr'])),
192 "dhcp_start {}".format(str(ns_admin['dhcp_range'][0])),
193 "dhcp_end {}".format(str(ns_admin['dhcp_range'][1])),
194 "inspection_iprange {}".format(','.join(intro_range))
197 config['ironic_config'] = [
198 "disk_utils iscsi_verify_attempts 30",
199 "disk_partitioner check_device_max_retries 40"
202 config['nova_config'] = [
203 "dns_domain {}".format(ns['dns-domain']),
204 "dhcp_domain {}".format(ns['dns-domain'])
207 config['neutron_config'] = [
208 "dns_domain {}".format(ns['dns-domain']),
210 # FIXME(trozet): possible bug here with not using external network
211 ns_external = ns['networks']['external'][0]
212 config['external_network'] = {
213 "vlan": ns_external['installer_vm']['vlan'],
214 "ip": ns_external['installer_vm']['ip'],
215 "prefix": str(ns_external['cidr']).split('/')[1],
216 "enabled": ns_external['enabled']
219 # Check if this is an ARM deployment
220 config['aarch64'] = platform.machine() == 'aarch64'