Merge "deploy.sh: Retire `-B` argument"
[fuel.git] / mcp / scripts / lib.sh
1 #!/bin/bash -e
2 # shellcheck disable=SC2155,SC1001
3 ##############################################################################
4 # Copyright (c) 2017 Mirantis Inc., Enea AB and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 #
11 # Library of shell functions
12 #
13
14 function generate_ssh_key {
15   local mcp_ssh_key=$(basename "${SSH_KEY}")
16   local user=${USER}
17   if [ -n "${SUDO_USER}" ] && [ "${SUDO_USER}" != 'root' ]; then
18     user=${SUDO_USER}
19   fi
20
21   if [ -f "${SSH_KEY}" ]; then
22     cp "${SSH_KEY}" .
23     ssh-keygen -f "${mcp_ssh_key}" -y > "${mcp_ssh_key}.pub"
24   fi
25
26   [ -f "${mcp_ssh_key}" ] || ssh-keygen -f "${mcp_ssh_key}" -N ''
27   sudo install -D -o "${user}" -m 0600 "${mcp_ssh_key}" "${SSH_KEY}"
28 }
29
30 function get_base_image {
31   local base_image=$1
32   local image_dir=$2
33
34   mkdir -p "${image_dir}"
35   wget --progress=dot:giga -P "${image_dir}" -N "${base_image}"
36 }
37
38 function __kernel_modules {
39   # Load mandatory kernel modules: loop, nbd
40   local image_dir=$1
41   sudo modprobe loop
42   if sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8; then
43     return 0
44   fi
45   # CentOS (or RHEL family in general) do not provide 'nbd' out of the box
46   echo "[WARN] 'nbd' kernel module cannot be loaded!"
47   if [ ! -e /etc/redhat-release ]; then
48     echo "[ERROR] Non-RHEL system detected, aborting!"
49     echo "[ERROR] Try building 'nbd' manually or install it from a 3rd party."
50     exit 1
51   fi
52
53   # Best-effort attempt at building a non-maintaned kernel module
54   local __baseurl
55   local __subdir
56   local __uname_r=$(uname -r)
57   local __uname_m=$(uname -m)
58   if [ "${__uname_m}" = 'x86_64' ]; then
59     __baseurl='http://vault.centos.org/centos'
60     __subdir='Source/SPackages'
61     __srpm="kernel-${__uname_r%.${__uname_m}}.src.rpm"
62   else
63     __baseurl='http://vault.centos.org/altarch'
64     __subdir="Source/${__uname_m}/Source/SPackages"
65     # NOTE: fmt varies across releases (e.g. kernel-alt-4.11.0-44.el7a.src.rpm)
66     __srpm="kernel-alt-${__uname_r%.${__uname_m}}.src.rpm"
67   fi
68
69   local __found='n'
70   local __versions=$(curl -s "${__baseurl}/" | grep -Po 'href="\K7\.[\d\.]+')
71   for ver in ${__versions}; do
72     for comp in os updates; do
73       local url="${__baseurl}/${ver}/${comp}/${__subdir}/${__srpm}"
74       if wget "${url}" -O "${image_dir}/${__srpm}" > /dev/null 2>&1; then
75         __found='y'; break 2
76       fi
77     done
78   done
79
80   if [ "${__found}" = 'n' ]; then
81     echo "[ERROR] Can't find the linux kernel SRPM for: ${__uname_r}"
82     echo "[ERROR] 'nbd' module cannot be built, aborting!"
83     echo "[ERROR] Try 'yum upgrade' or building 'nbd' krn module manually ..."
84     exit 1
85   fi
86
87   rpm -ivh "${image_dir}/${__srpm}" 2> /dev/null
88   mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
89   # shellcheck disable=SC2016
90   echo '%_topdir %(echo $HOME)/rpmbuild' > ~/.rpmmacros
91   (
92     cd ~/rpmbuild/SPECS
93     rpmbuild -bp --nodeps --target="${__uname_m}" kernel*.spec
94     cd ~/rpmbuild/BUILD/"${__srpm%.src.rpm}"/linux-*
95     sed -i 's/^.*\(CONFIG_BLK_DEV_NBD\).*$/\1=m/g' .config
96     # http://centosfaq.org/centos/nbd-does-not-compile-for-3100-514262el7x86_64
97     if grep -Rq 'REQ_TYPE_DRV_PRIV' drivers/block; then
98       sed -i 's/REQ_TYPE_SPECIAL/REQ_TYPE_DRV_PRIV/g' drivers/block/nbd.c
99     fi
100     gunzip -c "/boot/symvers-${__uname_r}.gz" > Module.symvers
101     make prepare modules_prepare
102     make M=drivers/block -j
103     modinfo drivers/block/nbd.ko
104     sudo mkdir -p "/lib/modules/${__uname_r}/extra/"
105     sudo cp drivers/block/nbd.ko "/lib/modules/${__uname_r}/extra/"
106   )
107   sudo depmod -a
108   sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8
109 }
110
111 function mount_image {
112   local image=$1
113   local image_dir=$2
114   OPNFV_MNT_DIR="${image_dir}/ubuntu"
115
116   # Find free nbd, loop devices
117   for dev in '/sys/class/block/nbd'*; do
118     if [ "$(cat "${dev}/size")" = '0' ]; then
119       OPNFV_NBD_DEV=/dev/$(basename "${dev}")
120       break
121     fi
122   done
123   OPNFV_LOOP_DEV=$(losetup -f)
124   OPNFV_MAP_DEV=/dev/mapper/$(basename "${OPNFV_NBD_DEV}")p1
125   export OPNFV_MNT_DIR OPNFV_LOOP_DEV
126   [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
127   qemu-img resize "${image_dir}/${image}" 3G
128   sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
129     "${image_dir}/${image}"
130   sudo kpartx -av "${OPNFV_NBD_DEV}"
131   sleep 5 # /dev/nbdNp1 takes some time to come up
132   # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
133   if sudo growpart "${OPNFV_NBD_DEV}" 1; then
134     sudo kpartx -u "${OPNFV_NBD_DEV}"
135     sudo e2fsck -pf "${OPNFV_MAP_DEV}"
136     sudo resize2fs "${OPNFV_MAP_DEV}"
137   fi
138   # grub-update does not like /dev/nbd*, so use a loop device to work around it
139   sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_MAP_DEV}"
140   mkdir -p "${OPNFV_MNT_DIR}"
141   sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
142   sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
143   sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
144   sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
145   sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
146   sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
147   echo "GRUB_DISABLE_OS_PROBER=true" | \
148     sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
149   sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
150     "${OPNFV_MNT_DIR}/etc/default/grub"
151 }
152
153 function apt_repos_pkgs_image {
154   local apt_key_urls=(${1//,/ })
155   local all_repos=(${2//,/ })
156   local pkgs_i=(${3//,/ })
157   local pkgs_r=(${4//,/ })
158   [ -n "${OPNFV_MNT_DIR}" ] || exit 1
159
160   # APT keys
161   if [ "${#apt_key_urls[@]}" -gt 0 ]; then
162     for apt_key in "${apt_key_urls[@]}"; do
163       sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
164         "wget -qO - '${apt_key}' | apt-key add -"
165     done
166   fi
167   # Additional repositories
168   for repo_line in "${all_repos[@]}"; do
169     # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
170     local repo=(${repo_line//|/ })
171     [ "${#repo[@]}" -gt 5 ] || continue
172     # NOTE: Names and formatting are compatible with Salt linux.system.repo
173     cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
174
175                 Package: *
176                 Pin: release a=${repo[-2]}
177                 Pin-Priority: ${repo[1]}
178
179                 EOF
180     echo "${repo[@]:2}" | sudo tee \
181       "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
182   done
183   # Install packages
184   if [ "${#pkgs_i[@]}" -gt 0 ]; then
185     sudo DEBIAN_FRONTEND="noninteractive" \
186       chroot "${OPNFV_MNT_DIR}" apt-get update
187     sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
188       chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
189   fi
190   # Remove packages
191   if [ "${#pkgs_r[@]}" -gt 0 ]; then
192     sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
193       chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
194   fi
195   # Disable cloud-init metadata service datasource
196   sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
197   echo "datasource_list: [ NoCloud, None ]" | sudo tee \
198     "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
199 }
200
201 function cleanup_mounts {
202   # Remove any mounts, loop and/or nbd devs created while patching base image
203   if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
204     if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
205       # Grub thinks it's running from a live CD
206       sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
207         "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
208     fi
209     sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
210     sync
211     if mountpoint -q "${OPNFV_MNT_DIR}"; then
212       sudo umount -l "${OPNFV_MNT_DIR}" || true
213     fi
214   fi
215   if [ -n "${OPNFV_LOOP_DEV}" ] && \
216     losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
217       sudo losetup -d "${OPNFV_LOOP_DEV}"
218   fi
219   if [ -n "${OPNFV_NBD_DEV}" ]; then
220     sudo kpartx -d "${OPNFV_NBD_DEV}" || true
221     sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
222   fi
223 }
224
225 function cleanup_uefi {
226   # Clean up Ubuntu boot entry if cfg01, kvm nodes online from previous deploy
227   local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
228   [ ! "$(hostname)" = 'cfg01' ] || cmd_str='eval'
229   ${cmd_str} "sudo salt -C 'kvm* or cmp*' cmd.run \
230     \"which efibootmgr > /dev/null 2>&1 && \
231     efibootmgr | grep -oP '(?<=Boot)[0-9]+(?=.*ubuntu)' | \
232     xargs -I{} efibootmgr --delete-bootnum --bootnum {}; \
233     rm -rf /boot/efi/*\"" || true
234 }
235
236 function cleanup_vms {
237   # clean up existing nodes
238   for node in $(virsh list --name | grep -P '\w{3}\d{2}'); do
239     virsh destroy "${node}"
240   done
241   for node in $(virsh list --name --all | grep -P '\w{3}\d{2}'); do
242     virsh domblklist "${node}" | awk '/^.da/ {print $2}' | \
243       xargs --no-run-if-empty -I{} sudo rm -f {}
244     virsh undefine "${node}" --remove-all-storage --nvram
245   done
246 }
247
248 function prepare_vms {
249   local base_image=$1; shift
250   local image_dir=$1; shift
251   local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
252   local vnodes=("$@")
253   local image=base_image_opnfv_fuel.img
254   local vcp_image=${image%.*}_vcp.img
255   local _o=${base_image/*\/}
256   local _h=$(echo "${repos_pkgs_str}.$(md5sum "${image_dir}/${_o}")" | \
257              md5sum | cut -c -8)
258   local _tmp
259
260   cleanup_uefi
261   cleanup_vms
262   get_base_image "${base_image}" "${image_dir}"
263   IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
264
265   echo "[INFO] Lookup cache / build patched base image for fingerprint: ${_h}"
266   _tmp="${image%.*}.${_h}.img"
267   if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${image}" ]; then
268     echo "[INFO] Patched base image found"
269   else
270     rm -f "${image_dir}/${image%.*}"*
271     if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
272       echo "[INFO] Patching base image ..."
273       cp "${image_dir}/${_o}" "${image_dir}/${_tmp}"
274       __kernel_modules "${image_dir}"
275       mount_image "${_tmp}" "${image_dir}"
276       apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
277       cleanup_mounts
278     else
279       echo "[INFO] No patching required, using vanilla base image"
280       ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
281     fi
282     ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
283   fi
284
285   envsubst < user-data.template > user-data.sh # CWD should be <mcp/scripts>
286
287   # Create config ISO and resize OS disk image for each foundation node VM
288   for node in "${vnodes[@]}"; do
289     ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" -u user-data.sh \
290        -h "${node}" "${image_dir}/mcp_${node}.iso"
291     cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
292     qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
293   done
294
295   # VCP VMs base image specific changes
296   if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
297     echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
298     _tmp="${vcp_image%.*}.${_h}.img"
299     if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
300       echo "[INFO] Patched VCP image found"
301     else
302       echo "[INFO] Patching VCP image ..."
303       cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
304       __kernel_modules "${image_dir}"
305       mount_image "${_tmp}" "${image_dir}"
306       apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
307       cleanup_mounts
308       ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
309     fi
310   fi
311 }
312
313 function create_networks {
314   local vnode_networks=("$@")
315   # create required networks, including constant "mcpcontrol"
316   # FIXME(alav): since we renamed "pxe" to "mcpcontrol", we need to make sure
317   # we delete the old "pxe" virtual network, or it would cause IP conflicts.
318   for net in "pxe" "mcpcontrol" "${vnode_networks[@]}"; do
319     if virsh net-info "${net}" >/dev/null 2>&1; then
320       virsh net-destroy "${net}" || true
321       virsh net-undefine "${net}"
322     fi
323     # in case of custom network, host should already have the bridge in place
324     if [ -f "net_${net}.xml" ] && [ ! -d "/sys/class/net/${net}/bridge" ]; then
325       virsh net-define "net_${net}.xml"
326       virsh net-autostart "${net}"
327       virsh net-start "${net}"
328     fi
329   done
330 }
331
332 function create_vms {
333   local image_dir=$1; shift
334   # vnode data should be serialized with the following format:
335   # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
336   IFS='|' read -r -a vnodes <<< "$1"; shift
337   local vnode_networks=("$@")
338
339   # create vms with specified options
340   for serialized_vnode_data in "${vnodes[@]}"; do
341     IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
342
343     # prepare network args
344     net_args=" --network network=mcpcontrol,model=virtio"
345     if [ "${DEPLOY_TYPE:-}" = 'baremetal' ]; then
346       # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
347       vnode_networks[2]="${vnode_networks[0]}"
348     fi
349     for net in "${vnode_networks[@]:1}"; do
350       net_args="${net_args} --network bridge=${net},model=virtio"
351     done
352
353     # shellcheck disable=SC2086
354     virt-install --name "${vnode_data[0]}" \
355     --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
356     --cpu host-passthrough --accelerate ${net_args} \
357     --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
358     --os-type linux --os-variant none \
359     --boot hd --nographics --console pty --autostart --noreboot \
360     --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
361     --noautoconsole
362   done
363 }
364
365 function update_mcpcontrol_network {
366   # set static ip address for salt master node, MaaS node
367   local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
368   local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
369   virsh net-update "mcpcontrol" add ip-dhcp-host \
370     "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
371   [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
372     "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
373 }
374
375 function start_vms {
376   local vnodes=("$@")
377
378   # start vms
379   for node in "${vnodes[@]}"; do
380     virsh start "${node}"
381     sleep $((RANDOM%5+1))
382   done
383 }
384
385 function check_connection {
386   local total_attempts=60
387   local sleep_time=5
388
389   set +e
390   echo '[INFO] Attempting to get into Salt master ...'
391
392   # wait until ssh on Salt master is available
393   # shellcheck disable=SC2034
394   for attempt in $(seq "${total_attempts}"); do
395     # shellcheck disable=SC2086
396     ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
397     case $? in
398       0) echo "${attempt}> Success"; break ;;
399       *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
400     esac
401     sleep $sleep_time
402   done
403   set -e
404 }
405
406 function parse_yaml {
407   local prefix=$2
408   local s
409   local w
410   local fs
411   s='[[:space:]]*'
412   w='[a-zA-Z0-9_]*'
413   fs="$(echo @|tr @ '\034')"
414   sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
415       -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
416   awk -F"$fs" '{
417   indent = length($1)/2;
418   vname[indent] = $2;
419   for (i in vname) {if (i > indent) {delete vname[i]}}
420       if (length($3) > 0) {
421           vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
422           printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
423       }
424   }' | sed 's/_=/+=/g'
425 }
426
427 function wait_for {
428   # Execute in a subshell to prevent local variable override during recursion
429   (
430     local total_attempts=$1; shift
431     local cmdstr=$*
432     local sleep_time=10
433     echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
434     # shellcheck disable=SC2034
435     for attempt in $(seq "${total_attempts}"); do
436       echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
437       if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
438         # shellcheck disable=SC2015
439         eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
440       else
441         !(eval "${cmdstr}" || echo __fuel_wf_failure__) |& tee /dev/stderr | \
442           grep -Eq '(Not connected|No response|__fuel_wf_failure__)' && \
443           echo "[wait_for] OK: ${cmdstr}" && return 0 || true
444       fi
445       sleep "${sleep_time}"
446     done
447     echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"
448     return 1
449   )
450 }
451
452 function get_nova_compute_pillar_data {
453   local value=$(salt -C 'I@nova:compute and *01*' pillar.get _param:"${1}" --out yaml | cut -d ' ' -f2)
454   if [ "${value}" != "''" ]; then
455     echo  ${value}
456   fi
457 }