Typo fix for disabling ipxe
[apex.git] / apex / undercloud / undercloud.py
1 ##############################################################################
2 # Copyright (c) 2017 Tim Rozet (trozet@redhat.com) and others.
3 #
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 import libvirt
11 import logging
12 import os
13 import platform
14 import shutil
15 import subprocess
16 import time
17
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
22
23
24 class ApexUndercloudException(Exception):
25     pass
26
27
28 class Undercloud:
29     """
30     This class represents an Apex Undercloud VM
31     """
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):
36         self.ip = None
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,
41                                    'undercloud.qcow2')
42         self.image_path = image_path
43         self.image_name = image_name
44         self.template_path = template_path
45         self.vm = None
46         if Undercloud._get_vm():
47             logging.error("Undercloud VM already exists.  Please clean "
48                           "before creating")
49             raise ApexUndercloudException("Undercloud VM already exists!")
50         self.create()
51
52     @staticmethod
53     def _get_vm():
54         conn = libvirt.open('qemu:///system')
55         try:
56             vm = conn.lookupByName('undercloud')
57             return vm
58         except libvirt.libvirtError:
59             logging.debug("No undercloud VM exists")
60
61     def create(self):
62         networks = ['admin']
63         if self.external_net:
64             networks.append('external')
65         console = 'ttyAMA0' if platform.machine() == 'aarch64' else 'ttyS0'
66         root = 'vda' if platform.machine() == 'aarch64' else 'sda'
67
68         self.vm = vm_lib.create_vm(name='undercloud',
69                                    image=self.volume,
70                                    baremetal_interfaces=networks,
71                                    direct_boot='overcloud-full',
72                                    kernel_args=['console={}'.format(console),
73                                                 'root=/dev/{}'.format(root)],
74                                    default_network=True,
75                                    template_dir=self.template_path)
76         self.setup_volumes()
77         self.inject_auth()
78         self._update_delorean_repo()
79
80     def _set_ip(self):
81         ip_out = self.vm.interfaceAddresses(
82             libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, 0)
83         if ip_out:
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']
88                         return True
89
90     def start(self):
91         """
92         Start Undercloud VM
93         :return: None
94         """
95         if self.vm.isActive():
96             logging.info("Undercloud already started")
97         else:
98             logging.info("Starting undercloud")
99             self.vm.create()
100             # give 10 seconds to come up
101             time.sleep(10)
102         # set IP
103         for x in range(5):
104             if self._set_ip():
105                 logging.info("Undercloud started.  IP Address: {}".format(
106                     self.ip))
107                 break
108             logging.debug("Did not find undercloud IP in {} "
109                           "attempts...".format(x))
110             time.sleep(10)
111         else:
112             logging.error("Cannot find IP for Undercloud")
113             raise ApexUndercloudException(
114                 "Unable to find IP for undercloud.  Check if VM booted "
115                 "correctly")
116
117     def configure(self, net_settings, deploy_settings,
118                   playbook, apex_temp_dir):
119         """
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
125         :return: None
126         """
127
128         logging.info("Configuring Undercloud...")
129         # run ansible
130         ansible_vars = Undercloud.generate_config(net_settings,
131                                                   deploy_settings)
132         ansible_vars['apex_temp_dir'] = apex_temp_dir
133         try:
134             utils.run_ansible(ansible_vars, playbook, host=self.ip,
135                               user='stack')
136         except subprocess.CalledProcessError:
137             logging.error(
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!")
143
144     def setup_volumes(self):
145         for img_file in ('overcloud-full.vmlinuz', 'overcloud-full.initrd',
146                          self.image_name):
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,
150                                         'undercloud.qcow2')
151             else:
152                 dest_img = os.path.join(constants.LIBVIRT_VOLUME_PATH,
153                                         img_file)
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):
158                 os.remove(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.
165
166     def inject_auth(self):
167         virt_ops = list()
168         # virt-customize keys/pws
169         if self.root_pw:
170             pw_op = "password:{}".format(self.root_pw)
171             virt_ops.append({constants.VIRT_PW: pw_op})
172         # ssh key setup
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'})
177         run_cmds = [
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'
183         ]
184         for cmd in run_cmds:
185             virt_ops.append({constants.VIRT_RUN_CMD: cmd})
186         virt_utils.virt_customize(virt_ops, self.volume)
187
188     @staticmethod
189     def generate_config(ns, ds):
190         """
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
195         """
196
197         ns_admin = ns['networks']['admin']
198         intro_range = ns['apex']['networks']['admin']['introspection_range']
199         config = dict()
200         # Check if this is an ARM deployment
201         config['aarch64'] = platform.machine() == 'aarch64'
202         # Configuration for undercloud.conf
203         config['undercloud_config'] = [
204             "enable_ui false",
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))
219         ]
220
221         config['ironic_config'] = [
222             "disk_utils iscsi_verify_attempts 30",
223             "disk_partitioner check_device_max_retries 40"
224         ]
225
226         config['nova_config'] = [
227             "dns_domain {}".format(ns['dns-domain']),
228             "dhcp_domain {}".format(ns['dns-domain'])
229         ]
230
231         config['neutron_config'] = [
232             "dns_domain {}".format(ns['dns-domain']),
233         ]
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']
241         }
242
243         config['http_proxy'] = ns.get('http_proxy', '')
244         config['https_proxy'] = ns.get('https_proxy', '')
245
246         return config
247
248     def _update_delorean_repo(self):
249         if utils.internet_connectivity():
250             logging.info('Updating delorean repo on Undercloud')
251             delorean_repo = (
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))
256             try:
257                 virt_utils.virt_customize({constants.VIRT_RUN_CMD: cmd},
258                                           self.volume)
259             except Exception:
260                 logging.warning("Failed to download and update delorean repo "
261                                 "for Undercloud")