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',
35 os_version=constants.DEFAULT_OS_VERSION):
37 self.os_version = os_version
38 self.root_pw = root_pw
39 self.external_net = external_network
40 self.volume = os.path.join(constants.LIBVIRT_VOLUME_PATH,
42 self.image_path = image_path
43 self.image_name = image_name
44 self.template_path = template_path
46 if Undercloud._get_vm():
47 logging.error("Undercloud VM already exists. Please clean "
49 raise ApexUndercloudException("Undercloud VM already exists!")
54 conn = libvirt.open('qemu:///system')
56 vm = conn.lookupByName('undercloud')
58 except libvirt.libvirtError:
59 logging.debug("No undercloud VM exists")
64 networks.append('external')
65 console = 'ttyAMA0' if platform.machine() == 'aarch64' else 'ttyS0'
66 root = 'vda' if platform.machine() == 'aarch64' else 'sda'
68 self.vm = vm_lib.create_vm(name='undercloud',
70 baremetal_interfaces=networks,
71 direct_boot='overcloud-full',
72 kernel_args=['console={}'.format(console),
73 'root=/dev/{}'.format(root)],
75 template_dir=self.template_path)
78 self._update_delorean_repo()
81 ip_out = self.vm.interfaceAddresses(
82 libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, 0)
84 for (name, val) in ip_out.items():
85 for ipaddr in val['addrs']:
86 if ipaddr['type'] == libvirt.VIR_IP_ADDR_TYPE_IPV4:
87 self.ip = ipaddr['addr']
95 if self.vm.isActive():
96 logging.info("Undercloud already started")
98 logging.info("Starting undercloud")
100 # give 10 seconds to come up
105 logging.info("Undercloud started. IP Address: {}".format(
108 logging.debug("Did not find undercloud IP in {} "
109 "attempts...".format(x))
112 logging.error("Cannot find IP for Undercloud")
113 raise ApexUndercloudException(
114 "Unable to find IP for undercloud. Check if VM booted "
117 def configure(self, net_settings, deploy_settings,
118 playbook, apex_temp_dir):
120 Configures undercloud VM
121 :param net_settings: Network settings for deployment
122 :param deploy_settings: Deployment settings for deployment
123 :param playbook: playbook to use to configure undercloud
124 :param apex_temp_dir: temporary apex directory to hold configs/logs
128 logging.info("Configuring Undercloud...")
130 ansible_vars = Undercloud.generate_config(net_settings,
132 ansible_vars['apex_temp_dir'] = apex_temp_dir
134 utils.run_ansible(ansible_vars, playbook, host=self.ip,
136 except subprocess.CalledProcessError:
138 "Failed to install undercloud..."
139 "please check log: {}".format(os.path.join(
140 apex_temp_dir, 'apex-undercloud-install.log')))
141 raise ApexUndercloudException('Failed to install undercloud')
142 logging.info("Undercloud installed!")
144 def setup_volumes(self):
145 for img_file in ('overcloud-full.vmlinuz', 'overcloud-full.initrd',
147 src_img = os.path.join(self.image_path, img_file)
148 if img_file == self.image_name:
149 dest_img = os.path.join(constants.LIBVIRT_VOLUME_PATH,
152 dest_img = os.path.join(constants.LIBVIRT_VOLUME_PATH,
154 if not os.path.isfile(src_img):
155 raise ApexUndercloudException(
156 "Required source file does not exist:{}".format(src_img))
157 if os.path.exists(dest_img):
159 shutil.copyfile(src_img, dest_img)
160 shutil.chown(dest_img, user='qemu', group='qemu')
161 os.chmod(dest_img, 0o0744)
162 # TODO(trozet):check if resize needed right now size is 50gb
163 # there is a lib called vminspect which has some dependencies and is
164 # not yet available in pip. Consider switching to this lib later.
166 def inject_auth(self):
168 # virt-customize keys/pws
170 pw_op = "password:{}".format(self.root_pw)
171 virt_ops.append({constants.VIRT_PW: pw_op})
173 virt_ops.append({constants.VIRT_RUN_CMD:
174 'mkdir -p /root/.ssh'})
175 virt_ops.append({constants.VIRT_UPLOAD:
176 '/root/.ssh/id_rsa.pub:/root/.ssh/authorized_keys'})
178 'chmod 600 /root/.ssh/authorized_keys',
179 'restorecon /root/.ssh/authorized_keys',
180 'cp /root/.ssh/authorized_keys /home/stack/.ssh/',
181 'chown stack:stack /home/stack/.ssh/authorized_keys',
182 'chmod 600 /home/stack/.ssh/authorized_keys'
185 virt_ops.append({constants.VIRT_RUN_CMD: cmd})
186 virt_utils.virt_customize(virt_ops, self.volume)
189 def generate_config(ns, ds):
191 Generates a dictionary of settings for configuring undercloud
192 :param ns: network settings to derive undercloud settings
193 :param ds: deploy settings to derive undercloud settings
194 :return: dictionary of settings
197 ns_admin = ns['networks']['admin']
198 intro_range = ns['apex']['networks']['admin']['introspection_range']
200 # Check if this is an ARM deployment
201 config['aarch64'] = platform.machine() == 'aarch64'
202 # Configuration for undercloud.conf
203 config['undercloud_config'] = [
205 "undercloud_update_packages false",
206 "undercloud_debug false",
207 "inspection_extras false",
208 "ipxe_enabled {}".format(
209 str(ds['global_params'].get('ipxe', True) and
210 not config['aarch64'])),
211 "undercloud_hostname undercloud.{}".format(ns['dns-domain']),
212 "local_ip {}/{}".format(str(ns_admin['installer_vm']['ip']),
213 str(ns_admin['cidr']).split('/')[1]),
214 "network_gateway {}".format(str(ns_admin['installer_vm']['ip'])),
215 "network_cidr {}".format(str(ns_admin['cidr'])),
216 "dhcp_start {}".format(str(ns_admin['dhcp_range'][0])),
217 "dhcp_end {}".format(str(ns_admin['dhcp_range'][1])),
218 "inspection_iprange {}".format(','.join(intro_range))
221 config['ironic_config'] = [
222 "disk_utils iscsi_verify_attempts 30",
223 "disk_partitioner check_device_max_retries 40"
226 config['nova_config'] = [
227 "dns_domain {}".format(ns['dns-domain']),
228 "dhcp_domain {}".format(ns['dns-domain'])
231 config['neutron_config'] = [
232 "dns_domain {}".format(ns['dns-domain']),
234 # FIXME(trozet): possible bug here with not using external network
235 ns_external = ns['networks']['external'][0]
236 config['external_network'] = {
237 "vlan": ns_external['installer_vm']['vlan'],
238 "ip": ns_external['installer_vm']['ip'],
239 "prefix": str(ns_external['cidr']).split('/')[1],
240 "enabled": ns_external['enabled']
243 config['http_proxy'] = ns.get('http_proxy', '')
244 config['https_proxy'] = ns.get('https_proxy', '')
248 def _update_delorean_repo(self):
249 if utils.internet_connectivity():
250 logging.info('Updating delorean repo on Undercloud')
252 "https://trunk.rdoproject.org/centos7-{}"
253 "/current-tripleo/delorean.repo".format(self.os_version))
254 cmd = ("curl -L -f -o "
255 "/etc/yum.repos.d/deloran.repo {}".format(delorean_repo))
257 virt_utils.virt_customize({constants.VIRT_RUN_CMD: cmd},
260 logging.warning("Failed to download and update delorean repo "