c566cc993b78b25f2ed4806c071343db99e2a4b0
[fuel.git] / mcp / scripts / lib.sh
1 #!/bin/bash -e
2 # shellcheck disable=SC2155,SC1001,SC2015,SC2128
3 ##############################################################################
4 # Copyright (c) 2018 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   test -e /dev/loop-control || 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   if [ -e /dev/nbd0 ]; then return 0; fi  # nbd might be inbuilt
46   # CentOS (or RHEL family in general) do not provide 'nbd' out of the box
47   echo "[WARN] 'nbd' kernel module cannot be loaded!"
48   if [ ! -e /etc/redhat-release ]; then
49     echo "[ERROR] Non-RHEL system detected, aborting!"
50     echo "[ERROR] Try building 'nbd' manually or install it from a 3rd party."
51     exit 1
52   fi
53
54   # Best-effort attempt at building a non-maintaned kernel module
55   local __baseurl
56   local __subdir
57   local __uname_r=$(uname -r)
58   local __uname_m=$(uname -m)
59   if [ "${__uname_m}" = 'x86_64' ]; then
60     __baseurl='http://vault.centos.org/centos'
61     __subdir='Source/SPackages'
62     __srpm="kernel-${__uname_r%.${__uname_m}}.src.rpm"
63   else
64     __baseurl='http://vault.centos.org/altarch'
65     __subdir="Source/${__uname_m}/Source/SPackages"
66     # NOTE: fmt varies across releases (e.g. kernel-alt-4.11.0-44.el7a.src.rpm)
67     __srpm="kernel-alt-${__uname_r%.${__uname_m}}.src.rpm"
68   fi
69
70   local __found='n'
71   local __versions=$(curl -s "${__baseurl}/" | grep -Po 'href="\K7\.[\d\.]+')
72   for ver in ${__versions}; do
73     for comp in os updates; do
74       local url="${__baseurl}/${ver}/${comp}/${__subdir}/${__srpm}"
75       if wget "${url}" -O "${image_dir}/${__srpm}" > /dev/null 2>&1; then
76         __found='y'; break 2
77       fi
78     done
79   done
80
81   if [ "${__found}" = 'n' ]; then
82     echo "[ERROR] Can't find the linux kernel SRPM for: ${__uname_r}"
83     echo "[ERROR] 'nbd' module cannot be built, aborting!"
84     echo "[ERROR] Try 'yum upgrade' or building 'nbd' krn module manually ..."
85     exit 1
86   fi
87
88   rpm -ivh "${image_dir}/${__srpm}" 2> /dev/null
89   mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
90   # shellcheck disable=SC2016
91   echo '%_topdir %(echo $HOME)/rpmbuild' > ~/.rpmmacros
92   (
93     cd ~/rpmbuild/SPECS
94     rpmbuild -bp --nodeps --target="${__uname_m}" kernel*.spec
95     cd ~/rpmbuild/BUILD/"${__srpm%.src.rpm}"/linux-*
96     sed -i 's/^.*\(CONFIG_BLK_DEV_NBD\).*$/\1=m/g' .config
97     # http://centosfaq.org/centos/nbd-does-not-compile-for-3100-514262el7x86_64
98     if grep -Rq 'REQ_TYPE_DRV_PRIV' drivers/block; then
99       sed -i 's/REQ_TYPE_SPECIAL/REQ_TYPE_DRV_PRIV/g' drivers/block/nbd.c
100     fi
101     gunzip -c "/boot/symvers-${__uname_r}.gz" > Module.symvers
102     make prepare modules_prepare
103     make M=drivers/block -j
104     modinfo drivers/block/nbd.ko
105     sudo mkdir -p "/lib/modules/${__uname_r}/extra/"
106     sudo cp drivers/block/nbd.ko "/lib/modules/${__uname_r}/extra/"
107   )
108   sudo depmod -a
109   sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8
110 }
111
112 function mount_image {
113   local image=$1
114   local image_dir=$2
115   OPNFV_MNT_DIR="${image_dir}/ubuntu"
116
117   # Find free nbd, loop devices
118   for dev in '/sys/class/block/nbd'*; do
119     if [ "$(cat "${dev}/size")" = '0' ]; then
120       OPNFV_NBD_DEV=/dev/$(basename "${dev}")
121       break
122     fi
123   done
124   OPNFV_LOOP_DEV=$(sudo losetup -f)
125   OPNFV_MAP_DEV=/dev/mapper/$(basename "${OPNFV_NBD_DEV}")p1
126   export OPNFV_MNT_DIR OPNFV_LOOP_DEV
127   [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
128   qemu-img resize "${image_dir}/${image}" 3G
129   sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
130     "${image_dir}/${image}"
131   sudo kpartx -av "${OPNFV_NBD_DEV}"
132   sleep 5 # /dev/nbdNp1 takes some time to come up
133   # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
134   if sudo growpart "${OPNFV_NBD_DEV}" 1; then
135     sudo kpartx -u "${OPNFV_NBD_DEV}"
136     sudo e2fsck -pf "${OPNFV_MAP_DEV}"
137     sudo resize2fs "${OPNFV_MAP_DEV}"
138   fi
139   # grub-update does not like /dev/nbd*, so use a loop device to work around it
140   sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_MAP_DEV}"
141   mkdir -p "${OPNFV_MNT_DIR}"
142   sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
143   sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
144   sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
145   sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
146   sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
147   sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
148   echo "GRUB_DISABLE_OS_PROBER=true" | \
149     sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
150   sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
151     "${OPNFV_MNT_DIR}/etc/default/grub"
152 }
153
154 function apt_repos_pkgs_image {
155   local apt_key_urls=(${1//,/ })
156   local all_repos=(${2//,/ })
157   local pkgs_i=(${3//,/ })
158   local pkgs_r=(${4//,/ })
159   [ -n "${OPNFV_MNT_DIR}" ] || exit 1
160
161   # APT keys
162   if [ "${#apt_key_urls[@]}" -gt 0 ]; then
163     for apt_key in "${apt_key_urls[@]}"; do
164       sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
165         "wget -qO - '${apt_key}' | apt-key add -"
166     done
167   fi
168   # Additional repositories
169   for repo_line in "${all_repos[@]}"; do
170     # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
171     local repo=(${repo_line//|/ })
172     [ "${#repo[@]}" -gt 5 ] || continue
173     # NOTE: Names and formatting are compatible with Salt linux.system.repo
174     cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
175
176                 Package: *
177                 Pin: release a=${repo[-2]}
178                 Pin-Priority: ${repo[1]}
179
180                 EOF
181     echo "${repo[@]:2}" | sudo tee \
182       "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
183   done
184   # Install packages
185   if [ "${#pkgs_i[@]}" -gt 0 ]; then
186     sudo DEBIAN_FRONTEND="noninteractive" \
187       chroot "${OPNFV_MNT_DIR}" apt-get update
188     sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
189       chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
190   fi
191   # Remove packages
192   if [ "${#pkgs_r[@]}" -gt 0 ]; then
193     sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
194       chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
195   fi
196   # Disable cloud-init metadata service datasource
197   sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
198   echo "datasource_list: [ NoCloud, None ]" | sudo tee \
199     "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
200 }
201
202 function cleanup_mounts {
203   # Remove any mounts, loop and/or nbd devs created while patching base image
204   if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
205     if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
206       # Grub thinks it's running from a live CD
207       sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
208         "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
209     fi
210     sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
211     sync
212     if mountpoint -q "${OPNFV_MNT_DIR}"; then
213       sudo umount -l "${OPNFV_MNT_DIR}" || true
214     fi
215   fi
216   if [ -n "${OPNFV_LOOP_DEV}" ] && \
217     sudo losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
218       sudo losetup -d "${OPNFV_LOOP_DEV}"
219   fi
220   if [ -n "${OPNFV_NBD_DEV}" ]; then
221     sudo kpartx -d "${OPNFV_NBD_DEV}" || true
222     sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
223   fi
224 }
225
226 function cleanup_uefi {
227   # Clean up Ubuntu boot entry if cfg01, kvm nodes online from previous deploy
228   local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
229   ping -c 1 -w 1 "${SALT_MASTER}" || return 0
230   [ ! "$(hostname)" = 'cfg01' ] || cmd_str='eval'
231   ${cmd_str} "sudo salt -C 'kvm* or cmp*' cmd.run \
232     \"which efibootmgr > /dev/null 2>&1 && \
233     efibootmgr | grep -oP '(?<=Boot)[0-9]+(?=.*ubuntu)' | \
234     xargs -I{} efibootmgr --delete-bootnum --bootnum {}; \
235     rm -rf /boot/efi/*\"" || true
236 }
237
238 function cleanup_vms {
239   # clean up existing nodes
240   for node in $(virsh list --name | grep -P '\w{3}\d{2}'); do
241     virsh destroy "${node}"
242   done
243   for node in $(virsh list --name --all | grep -P '\w{3}\d{2}'); do
244     virsh domblklist "${node}" | awk '/^.da/ {print $2}' | \
245       xargs --no-run-if-empty -I{} sudo rm -f {}
246     virsh undefine "${node}" --remove-all-storage --nvram || \
247       virsh undefine "${node}" --remove-all-storage
248   done
249 }
250
251 function prepare_vms {
252   local base_image=$1; shift
253   local image_dir=$1; shift
254   local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
255   local vnodes=("$@")
256   local image=base_image_opnfv_fuel.img
257   local vcp_image=${image%.*}_vcp.img
258   local _o=${base_image/*\/}
259   local _h=$(echo "${repos_pkgs_str}.$(md5sum "${image_dir}/${_o}")" | \
260              md5sum | cut -c -8)
261   local _tmp
262
263   cleanup_uefi
264   cleanup_vms
265   get_base_image "${base_image}" "${image_dir}"
266   IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
267
268   echo "[INFO] Lookup cache / build patched base image for fingerprint: ${_h}"
269   _tmp="${image%.*}.${_h}.img"
270   if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${image}" ]; then
271     echo "[INFO] Patched base image found"
272   else
273     rm -f "${image_dir}/${image%.*}"*
274     if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
275       echo "[INFO] Patching base image ..."
276       cp "${image_dir}/${_o}" "${image_dir}/${_tmp}"
277       __kernel_modules "${image_dir}"
278       mount_image "${_tmp}" "${image_dir}"
279       apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
280       cleanup_mounts
281     else
282       echo "[INFO] No patching required, using vanilla base image"
283       ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
284     fi
285     ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
286   fi
287
288   # Create config ISO and resize OS disk image for each foundation node VM
289   for node in "${vnodes[@]}"; do
290     if [[ "${node}" =~ ^(cfg01|mas01) ]]; then
291       user_data='user-data.mcp.sh'
292     else
293       user_data='user-data.admin.sh'
294     fi
295     ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" \
296        -u "${user_data}" -h "${node}" "${image_dir}/mcp_${node}.iso"
297     cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
298     qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
299     # Prepare dedicated drive for cinder on cmp nodes
300     if [[ "${node}" =~ ^(cmp) ]]; then
301       qemu-img create "${image_dir}/mcp_${node}_storage.qcow2" 100G
302     fi
303   done
304
305   # VCP VMs base image specific changes
306   if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
307     echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
308     _tmp="${vcp_image%.*}.${_h}.img"
309     if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
310       echo "[INFO] Patched VCP image found"
311     else
312       echo "[INFO] Patching VCP image ..."
313       cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
314       __kernel_modules "${image_dir}"
315       mount_image "${_tmp}" "${image_dir}"
316       apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
317       cleanup_mounts
318       ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
319     fi
320   fi
321 }
322
323 function jumpserver_pkg_install {
324   if [ -n "$(command -v apt-get)" ]; then
325     pkg_type='deb'; pkg_cmd='sudo apt-get install -y'
326   else
327     pkg_type='rpm'; pkg_cmd='sudo yum install -y --skip-broken'
328   fi
329   eval "$(parse_yaml "./requirements_${pkg_type}.yaml")"
330   for section in 'common' "$(uname -i)"; do
331     section_var="requirements_pkg_${section}[*]"
332     pkg_list+=" ${!section_var}"
333   done
334   # shellcheck disable=SC2086
335   ${pkg_cmd} ${pkg_list}
336 }
337
338 function jumpserver_check_requirements {
339   # shellcheck disable=SC2178
340   local vnodes=$1; shift
341   local br=("$@")
342   local err_br_not_found='Linux bridge not found!'
343   local err_br_virsh_net='is a virtual network, Linux bridge expected!'
344   local warn_br_endpoint="Endpoints might be inaccessible from external hosts!"
345   # MaaS requires a Linux bridge for PXE/admin
346   if [[ "${vnodes}" =~ mas01 ]]; then
347     if ! brctl showmacs "${br[0]}" >/dev/null 2>&1; then
348       notify_e "[ERROR] PXE/admin (${br[0]}) ${err_br_not_found}"
349     fi
350     # Assume virsh network name matches bridge name (true if created by us)
351     if virsh net-info "${br[0]}" >/dev/null 2>&1; then
352       notify_e "[ERROR] ${br[0]} ${err_br_virsh_net}"
353     fi
354   fi
355   # If virtual nodes are present, public should be a Linux bridge
356   if [ "$(echo "${vnodes}" | wc -w)" -gt 2 ]; then
357     if ! brctl showmacs "${br[3]}" >/dev/null 2>&1; then
358       if [[ "${vnodes}" =~ mas01 ]]; then
359         # Baremetal nodes *require* a proper public network
360         notify_e "[ERROR] Public (${br[3]}) ${err_br_not_found}"
361       else
362         notify_n "[WARN] Public (${br[3]}) ${err_br_not_found}" 3
363         notify_n "[WARN] ${warn_br_endpoint}" 3
364       fi
365     fi
366     if virsh net-info "${br[3]}" >/dev/null 2>&1; then
367       if [[ "${vnodes}" =~ mas01 ]]; then
368         notify_e "[ERROR] ${br[3]} ${err_br_virsh_net}"
369       else
370         notify_n "[WARN] ${br[3]} ${err_br_virsh_net}" 3
371         notify_n "[WARN] ${warn_br_endpoint}" 3
372       fi
373     fi
374   fi
375 }
376
377 function create_networks {
378   local vnode_networks=("$@")
379   # create required networks, including constant "mcpcontrol"
380   for net in "mcpcontrol" "${vnode_networks[@]}"; do
381     if virsh net-info "${net}" >/dev/null 2>&1; then
382       virsh net-destroy "${net}" || true
383       virsh net-undefine "${net}"
384     fi
385     # in case of custom network, host should already have the bridge in place
386     if [ -f "virsh_net/net_${net}.xml" ] && \
387      [ ! -d "/sys/class/net/${net}/bridge" ]; then
388       virsh net-define "virsh_net/net_${net}.xml"
389       virsh net-autostart "${net}"
390       virsh net-start "${net}"
391     fi
392   done
393 }
394
395 function create_vms {
396   local image_dir=$1; shift
397   # vnode data should be serialized with the following format:
398   # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
399   IFS='|' read -r -a vnodes <<< "$1"; shift
400
401   # AArch64: prepare arch specific arguments
402   local virt_extra_args=""
403   if [ "$(uname -i)" = "aarch64" ]; then
404     # No Cirrus VGA on AArch64, use virtio instead
405     virt_extra_args="$virt_extra_args --video=virtio"
406   fi
407
408   # create vms with specified options
409   for serialized_vnode_data in "${vnodes[@]}"; do
410     if [ -z "${serialized_vnode_data}" ]; then continue; fi
411     IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
412
413     # prepare network args
414     local vnode_networks=("$@")
415     if [[ "${vnode_data[0]}" =~ ^(cfg01|mas01) ]]; then
416       net_args=" --network network=mcpcontrol,model=virtio"
417       # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
418       vnode_networks[2]="${vnode_networks[0]}"
419     else
420       net_args=" --network bridge=${vnode_networks[0]},model=virtio"
421     fi
422     for net in "${vnode_networks[@]:1}"; do
423       net_args="${net_args} --network bridge=${net},model=virtio"
424     done
425
426     # dedicated storage drive for cinder on cmp nodes
427     virt_extra_storage=
428     if [[ "${vnode_data[0]}" =~ ^(cmp) ]]; then
429       virt_extra_storage="--disk path=${image_dir}/mcp_${vnode_data[0]}_storage.qcow2,format=qcow2,bus=virtio,cache=none,io=native"
430     fi
431
432     # shellcheck disable=SC2086
433     virt-install --name "${vnode_data[0]}" \
434     --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
435     --cpu host-passthrough --accelerate ${net_args} \
436     --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
437     ${virt_extra_storage} \
438     --os-type linux --os-variant none \
439     --boot hd --vnc --console pty --autostart --noreboot \
440     --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
441     --noautoconsole \
442     ${virt_extra_args}
443   done
444 }
445
446 function update_mcpcontrol_network {
447   # set static ip address for salt master node, MaaS node
448   local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
449   local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
450   virsh net-update "mcpcontrol" add ip-dhcp-host \
451     "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
452   [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
453     "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
454 }
455
456 function reset_vms {
457   local vnodes=("$@")
458   local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
459
460   # reset non-infrastructure vms, wait for them to come back online
461   for node in "${vnodes[@]}"; do
462     if [[ ! "${node}" =~ (cfg01|mas01) ]]; then
463       virsh reset "${node}"
464     fi
465   done
466   for node in "${vnodes[@]}"; do
467     if [[ ! "${node}" =~ (cfg01|mas01) ]]; then
468       wait_for 20.0 "${cmd_str} sudo salt -C '${node}*' saltutil.sync_all"
469     fi
470   done
471 }
472
473 function start_vms {
474   local vnodes=("$@")
475
476   # start vms
477   for node in "${vnodes[@]}"; do
478     virsh start "${node}"
479     sleep $((RANDOM%5+1))
480   done
481 }
482
483 function check_connection {
484   local total_attempts=60
485   local sleep_time=5
486
487   set +e
488   echo '[INFO] Attempting to get into Salt master ...'
489
490   # wait until ssh on Salt master is available
491   # shellcheck disable=SC2034
492   for attempt in $(seq "${total_attempts}"); do
493     # shellcheck disable=SC2086
494     ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
495     case $? in
496       0) echo "${attempt}> Success"; break ;;
497       *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
498     esac
499     sleep $sleep_time
500   done
501   set -e
502 }
503
504 function parse_yaml {
505   local prefix=$2
506   local s
507   local w
508   local fs
509   s='[[:space:]]*'
510   w='[a-zA-Z0-9_]*'
511   fs="$(echo @|tr @ '\034')"
512   sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
513       -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
514   awk -F"$fs" '{
515   indent = length($1)/2;
516   vname[indent] = $2;
517   for (i in vname) {if (i > indent) {delete vname[i]}}
518       if (length($3) > 0) {
519           vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
520           printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
521       }
522   }' | sed 's/_=/+=/g'
523 }
524
525 function wait_for {
526   # Execute in a subshell to prevent local variable override during recursion
527   (
528     local total_attempts=$1; shift
529     local cmdstr=$*
530     local sleep_time=10
531     echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
532     # shellcheck disable=SC2034
533     for attempt in $(seq "${total_attempts}"); do
534       echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
535       if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
536         eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
537       else
538         ! (eval "${cmdstr}" || echo 'No response') |& tee /dev/stderr | \
539            grep -Eq '(Not connected|No response)' && \
540            echo "[wait_for] OK: ${cmdstr}" && return 0 || true
541       fi
542       sleep "${sleep_time}"
543     done
544     echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"
545     return 1
546   )
547 }
548
549 function do_udev_cfg {
550   local _conf='/etc/udev/rules.d/99-opnfv-fuel-vnet-mtu.rules'
551   # http://linuxaleph.blogspot.com/2013/01/how-to-network-jumbo-frames-to-kvm-guest.html
552   echo 'SUBSYSTEM=="net", ACTION=="add", KERNEL=="vnet*", RUN+="/sbin/ip link set mtu 9000 dev '"'"%k"'"'"' |& sudo tee "${_conf}"
553   sudo udevadm control --reload || true
554 }
555
556 function do_sysctl_cfg {
557   local _conf='/etc/sysctl.d/99-opnfv-fuel-bridge.conf'
558   # https://wiki.libvirt.org/page/Net.bridge.bridge-nf-call_and_sysctl.conf
559   if modprobe br_netfilter bridge; then
560     echo 'net.bridge.bridge-nf-call-arptables = 0' |& sudo tee "${_conf}"
561     echo 'net.bridge.bridge-nf-call-iptables = 0'  |& sudo tee -a "${_conf}"
562     echo 'net.bridge.bridge-nf-call-ip6tables = 0' |& sudo tee -a "${_conf}"
563     # Some distros / sysadmins explicitly blacklist br_netfilter
564     sudo sysctl -q -p "${_conf}" || true
565   fi
566 }
567
568 function get_nova_compute_pillar_data {
569   local value=$(salt -C 'I@nova:compute and *01*' pillar.get _param:"${1}" --out yaml | cut -d ' ' -f2)
570   if [ "${value}" != "''" ]; then
571     echo "${value}"
572   fi
573 }