[jump req] Move pkg installation to lib.sh
[fuel.git] / mcp / scripts / lib.sh
1 #!/bin/bash -e
2 # shellcheck disable=SC2155,SC1001,SC2015,SC2128
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   # Create config ISO and resize OS disk image for each foundation node VM
286   for node in "${vnodes[@]}"; do
287     if [[ "${node}" =~ ^(cfg01|mas01) ]]; then
288       user_data='user-data.mcp.sh'
289     else
290       user_data='user-data.admin.sh'
291     fi
292     ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" \
293        -u "${user_data}" -h "${node}" "${image_dir}/mcp_${node}.iso"
294     cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
295     qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
296     # Prepare dedicated drive for cinder on cmp nodes
297     if [[ "${node}" =~ ^(cmp) ]]; then
298       qemu-img create "${image_dir}/mcp_${node}_storage.qcow2" 100G
299     fi
300   done
301
302   # VCP VMs base image specific changes
303   if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
304     echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
305     _tmp="${vcp_image%.*}.${_h}.img"
306     if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
307       echo "[INFO] Patched VCP image found"
308     else
309       echo "[INFO] Patching VCP image ..."
310       cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
311       __kernel_modules "${image_dir}"
312       mount_image "${_tmp}" "${image_dir}"
313       apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
314       cleanup_mounts
315       ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
316     fi
317   fi
318 }
319
320 function jumpserver_pkg_install {
321   if [ -n "$(command -v apt-get)" ]; then
322     pkg_type='deb'; pkg_cmd='sudo apt-get install -y'
323   else
324     pkg_type='rpm'; pkg_cmd='sudo yum install -y --skip-broken'
325   fi
326   eval "$(parse_yaml "./requirements_${pkg_type}.yaml")"
327   for section in 'common' "$(uname -i)"; do
328     section_var="requirements_pkg_${section}[*]"
329     pkg_list+=" ${!section_var}"
330   done
331   # shellcheck disable=SC2086
332   ${pkg_cmd} ${pkg_list}
333 }
334
335 function jumpserver_check_requirements {
336   # shellcheck disable=SC2178
337   local vnodes=$1; shift
338   local br=("$@")
339   local err_br_not_found='Linux bridge not found!'
340   local err_br_virsh_net='is a virtual network, Linux bridge expected!'
341   local warn_br_endpoint="Endpoints might be inaccessible from external hosts!"
342   # MaaS requires a Linux bridge for PXE/admin
343   if [[ "${vnodes}" =~ mas01 ]]; then
344     if ! brctl showmacs "${br[0]}" >/dev/null 2>&1; then
345       notify_e "[ERROR] PXE/admin (${br[0]}) ${err_br_not_found}"
346     fi
347     # Assume virsh network name matches bridge name (true if created by us)
348     if virsh net-info "${br[0]}" >/dev/null 2>&1; then
349       notify_e "[ERROR] ${br[0]} ${err_br_virsh_net}"
350     fi
351   fi
352   # If virtual nodes are present, public should be a Linux bridge
353   if [ "$(echo "${vnodes}" | wc -w)" -gt 2 ]; then
354     if ! brctl showmacs "${br[3]}" >/dev/null 2>&1; then
355       if [[ "${vnodes}" =~ mas01 ]]; then
356         # Baremetal nodes *require* a proper public network
357         notify_e "[ERROR] Public (${br[3]}) ${err_br_not_found}"
358       else
359         notify_n "[WARN] Public (${br[3]}) ${err_br_not_found}" 3
360         notify_n "[WARN] ${warn_br_endpoint}" 3
361       fi
362     fi
363     if virsh net-info "${br[3]}" >/dev/null 2>&1; then
364       if [[ "${vnodes}" =~ mas01 ]]; then
365         notify_e "[ERROR] ${br[3]} ${err_br_virsh_net}"
366       else
367         notify_n "[WARN] ${br[3]} ${err_br_virsh_net}" 3
368         notify_n "[WARN] ${warn_br_endpoint}" 3
369       fi
370     fi
371   fi
372 }
373
374 function create_networks {
375   local vnode_networks=("$@")
376   # create required networks, including constant "mcpcontrol"
377   for net in "mcpcontrol" "${vnode_networks[@]}"; do
378     if virsh net-info "${net}" >/dev/null 2>&1; then
379       virsh net-destroy "${net}" || true
380       virsh net-undefine "${net}"
381     fi
382     # in case of custom network, host should already have the bridge in place
383     if [ -f "virsh_net/net_${net}.xml" ] && \
384      [ ! -d "/sys/class/net/${net}/bridge" ]; then
385       virsh net-define "virsh_net/net_${net}.xml"
386       virsh net-autostart "${net}"
387       virsh net-start "${net}"
388     fi
389   done
390 }
391
392 function create_vms {
393   local image_dir=$1; shift
394   # vnode data should be serialized with the following format:
395   # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
396   IFS='|' read -r -a vnodes <<< "$1"; shift
397
398   # AArch64: prepare arch specific arguments
399   local virt_extra_args=""
400   if [ "$(uname -i)" = "aarch64" ]; then
401     # No Cirrus VGA on AArch64, use virtio instead
402     virt_extra_args="$virt_extra_args --video=virtio"
403   fi
404
405   # create vms with specified options
406   for serialized_vnode_data in "${vnodes[@]}"; do
407     IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
408
409     # prepare network args
410     local vnode_networks=("$@")
411     if [[ "${vnode_data[0]}" =~ ^(cfg01|mas01) ]]; then
412       net_args=" --network network=mcpcontrol,model=virtio"
413       # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
414       vnode_networks[2]="${vnode_networks[0]}"
415     else
416       net_args=" --network bridge=${vnode_networks[0]},model=virtio"
417     fi
418     for net in "${vnode_networks[@]:1}"; do
419       net_args="${net_args} --network bridge=${net},model=virtio"
420     done
421
422     # dedicated storage drive for cinder on cmp nodes
423     virt_extra_storage=
424     if [[ "${vnode_data[0]}" =~ ^(cmp) ]]; then
425       virt_extra_storage="--disk path=${image_dir}/mcp_${vnode_data[0]}_storage.qcow2,format=qcow2,bus=virtio,cache=none,io=native"
426     fi
427
428     # shellcheck disable=SC2086
429     virt-install --name "${vnode_data[0]}" \
430     --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
431     --cpu host-passthrough --accelerate ${net_args} \
432     --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
433     ${virt_extra_storage} \
434     --os-type linux --os-variant none \
435     --boot hd --vnc --console pty --autostart --noreboot \
436     --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
437     --noautoconsole \
438     ${virt_extra_args}
439   done
440 }
441
442 function update_mcpcontrol_network {
443   # set static ip address for salt master node, MaaS node
444   local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
445   local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
446   virsh net-update "mcpcontrol" add ip-dhcp-host \
447     "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
448   [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
449     "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
450 }
451
452 function start_vms {
453   local vnodes=("$@")
454
455   # start vms
456   for node in "${vnodes[@]}"; do
457     virsh start "${node}"
458     sleep $((RANDOM%5+1))
459   done
460 }
461
462 function check_connection {
463   local total_attempts=60
464   local sleep_time=5
465
466   set +e
467   echo '[INFO] Attempting to get into Salt master ...'
468
469   # wait until ssh on Salt master is available
470   # shellcheck disable=SC2034
471   for attempt in $(seq "${total_attempts}"); do
472     # shellcheck disable=SC2086
473     ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
474     case $? in
475       0) echo "${attempt}> Success"; break ;;
476       *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
477     esac
478     sleep $sleep_time
479   done
480   set -e
481 }
482
483 function parse_yaml {
484   local prefix=$2
485   local s
486   local w
487   local fs
488   s='[[:space:]]*'
489   w='[a-zA-Z0-9_]*'
490   fs="$(echo @|tr @ '\034')"
491   sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
492       -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
493   awk -F"$fs" '{
494   indent = length($1)/2;
495   vname[indent] = $2;
496   for (i in vname) {if (i > indent) {delete vname[i]}}
497       if (length($3) > 0) {
498           vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
499           printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
500       }
501   }' | sed 's/_=/+=/g'
502 }
503
504 function wait_for {
505   # Execute in a subshell to prevent local variable override during recursion
506   (
507     local total_attempts=$1; shift
508     local cmdstr=$*
509     local sleep_time=10
510     echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
511     # shellcheck disable=SC2034
512     for attempt in $(seq "${total_attempts}"); do
513       echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
514       if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
515         eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
516       else
517         ! (eval "${cmdstr}" || echo 'No response') |& tee /dev/stderr | \
518            grep -Eq '(Not connected|No response)' && \
519            echo "[wait_for] OK: ${cmdstr}" && return 0 || true
520       fi
521       sleep "${sleep_time}"
522     done
523     echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"
524     return 1
525   )
526 }
527
528 function do_sysctl_cfg {
529   local _conf='/etc/sysctl.d/99-opnfv-fuel-bridge.conf'
530   # https://wiki.libvirt.org/page/Net.bridge.bridge-nf-call_and_sysctl.conf
531   if modprobe br_netfilter bridge; then
532     echo 'net.bridge.bridge-nf-call-arptables = 0' |& sudo tee "${_conf}"
533     echo 'net.bridge.bridge-nf-call-iptables = 0'  |& sudo tee -a "${_conf}"
534     echo 'net.bridge.bridge-nf-call-ip6tables = 0' |& sudo tee -a "${_conf}"
535     # Some distros / sysadmins explicitly blacklist br_netfilter
536     sudo sysctl -q -p "${_conf}" || true
537   fi
538 }
539
540 function get_nova_compute_pillar_data {
541   local value=$(salt -C 'I@nova:compute and *01*' pillar.get _param:"${1}" --out yaml | cut -d ' ' -f2)
542   if [ "${value}" != "''" ]; then
543     echo "${value}"
544   fi
545 }
546
547 function do_templates() {
548   local git_repo_root=$1; shift
549   local image_dir=$1; shift
550   local target_lab=$1; shift
551   local target_pod=$1; shift
552   local lab_config_uri=$1; shift
553   local scenario_dir=${1:-}
554
555   RECLASS_CLUSTER_DIR=$(cd "${git_repo_root}/mcp/reclass/classes/cluster"; pwd)
556   PHAROS_GEN_CFG="./pharos/config/utils/generate_config.py"
557   PHAROS_IA=$(readlink -f "./pharos/config/installers/fuel/pod_config.yml.j2")
558   PHAROS_VALIDATE_SCHEMA_SCRIPT="./pharos/config/utils/validate_schema.py"
559   PHAROS_SCHEMA_PDF="./pharos/config/pdf/pod1.schema.yaml"
560   PHAROS_SCHEMA_IDF="./pharos/config/pdf/idf-pod1.schema.yaml"
561   BASE_CONFIG_PDF="${lab_config_uri}/labs/${target_lab}/${target_pod}.yaml"
562   BASE_CONFIG_IDF="${lab_config_uri}/labs/${target_lab}/idf-${target_pod}.yaml"
563   LOCAL_PDF="${image_dir}/$(basename "${BASE_CONFIG_PDF}")"
564   LOCAL_IDF="${image_dir}/$(basename "${BASE_CONFIG_IDF}")"
565
566   # Two-stage expansion, first stage handles pod_config and scenarios only
567   if [ -n "${scenario_dir}" ]; then
568     # Make sample PDF/IDF available via default lab-config (pharos submodule)
569     ln -sf "$(readlink -f "../config/labs/local")" "./pharos/labs/"
570
571     # Expand scenario file and main reclass input (pod_config.yaml) based on PDF
572     if ! curl --create-dirs -o "${LOCAL_PDF}" "${BASE_CONFIG_PDF}"; then
573       notify_e "[ERROR] Could not retrieve PDF (Pod Descriptor File)!"
574     elif ! curl -o "${LOCAL_IDF}" "${BASE_CONFIG_IDF}"; then
575       notify_e "[ERROR] Could not retrieve IDF (Installer Descriptor File)!"
576     fi
577     # Check first if configuration files are valid
578     if [[ ! "$target_pod" =~ "virtual" ]]; then
579       if ! "${PHAROS_VALIDATE_SCHEMA_SCRIPT}" -y "${LOCAL_PDF}" \
580         -s "${PHAROS_SCHEMA_PDF}"; then
581         notify_e "[ERROR] PDF does not match yaml schema!"
582       elif ! "${PHAROS_VALIDATE_SCHEMA_SCRIPT}" -y "${LOCAL_IDF}" \
583         -s "${PHAROS_SCHEMA_IDF}"; then
584         notify_e "[ERROR] IDF does not match yaml schema!"
585       fi
586     fi
587     if ! "${PHAROS_GEN_CFG}" -y "${LOCAL_PDF}" \
588       -j "${PHAROS_IA}" -v > "${image_dir}/pod_config.yml"; then
589       notify_e "[ERROR] Could not convert PDF+IDF to reclass model input!"
590     fi
591     template_dirs="${scenario_dir}"
592     template_err_str='Could not convert j2 scenario definitions!'
593   else
594     # Expand reclass and virsh network templates based on PDF + IDF
595     printenv | \
596       awk '/^(SALT|MCP|MAAS|CLUSTER).*=/ { gsub(/=/,": "); print }' >> "${LOCAL_PDF}"
597     template_dirs="${RECLASS_CLUSTER_DIR} $(readlink -f virsh_net) $(readlink -f ./*j2)"
598     template_err_str='Could not convert PDF to network definitions!'
599   fi
600   # shellcheck disable=SC2086
601   j2args=$(find $template_dirs -name '*.j2' -exec echo -j {} \;)
602   # shellcheck disable=SC2086
603   if ! "${PHAROS_GEN_CFG}" -y "${LOCAL_PDF}" ${j2args} -b -v \
604     -i "$(dirname "${PHAROS_IA}")"; then
605     notify_e "[ERROR] ${template_err_str}"
606   fi
607 }