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 ##############################################################################
11 # Library of shell functions
14 function generate_ssh_key {
15 local mcp_ssh_key=$(basename "${SSH_KEY}")
17 if [ -n "${SUDO_USER}" ] && [ "${SUDO_USER}" != 'root' ]; then
21 if [ -f "${SSH_KEY}" ]; then
23 ssh-keygen -f "${mcp_ssh_key}" -y > "${mcp_ssh_key}.pub"
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}"
30 function get_base_image {
34 mkdir -p "${image_dir}"
35 wget --progress=dot:giga -P "${image_dir}" -N "${base_image}"
38 function __kernel_modules {
39 # Load mandatory kernel modules: loop, nbd
42 if sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8; then
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."
53 # Best-effort attempt at building a non-maintaned kernel module
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"
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"
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
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 ..."
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
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
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/"
108 sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8
111 function mount_image {
114 OPNFV_MNT_DIR="${image_dir}/ubuntu"
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}")
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}"
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"
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
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 -"
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]}"
176 Pin: release a=${repo[-2]}
177 Pin-Priority: ${repo[1]}
180 echo "${repo[@]:2}" | sudo tee \
181 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
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[@]}"
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[@]}"
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"
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"
209 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
211 if mountpoint -q "${OPNFV_MNT_DIR}"; then
212 sudo umount -l "${OPNFV_MNT_DIR}" || true
215 if [ -n "${OPNFV_LOOP_DEV}" ] && \
216 losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
217 sudo losetup -d "${OPNFV_LOOP_DEV}"
219 if [ -n "${OPNFV_NBD_DEV}" ]; then
220 sudo kpartx -d "${OPNFV_NBD_DEV}" || true
221 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
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
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}"
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
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
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}")" | \
262 get_base_image "${base_image}" "${image_dir}"
263 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
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"
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}"
279 echo "[INFO] No patching required, using vanilla base image"
280 ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
282 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
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'
290 user_data='user-data.admin.sh'
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
298 # VCP VMs base image specific changes
299 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
300 echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
301 _tmp="${vcp_image%.*}.${_h}.img"
302 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
303 echo "[INFO] Patched VCP image found"
305 echo "[INFO] Patching VCP image ..."
306 cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
307 __kernel_modules "${image_dir}"
308 mount_image "${_tmp}" "${image_dir}"
309 apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
311 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
316 function create_networks {
317 local vnode_networks=("$@")
318 # create required networks, including constant "mcpcontrol"
319 # FIXME(alav): since we renamed "pxe" to "mcpcontrol", we need to make sure
320 # we delete the old "pxe" virtual network, or it would cause IP conflicts.
321 for net in "pxe" "mcpcontrol" "${vnode_networks[@]}"; do
322 if virsh net-info "${net}" >/dev/null 2>&1; then
323 virsh net-destroy "${net}" || true
324 virsh net-undefine "${net}"
326 # in case of custom network, host should already have the bridge in place
327 if [ -f "virsh_net/net_${net}.xml" ] && \
328 [ ! -d "/sys/class/net/${net}/bridge" ]; then
329 virsh net-define "virsh_net/net_${net}.xml"
330 virsh net-autostart "${net}"
331 virsh net-start "${net}"
336 function create_vms {
337 local image_dir=$1; shift
338 # vnode data should be serialized with the following format:
339 # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
340 IFS='|' read -r -a vnodes <<< "$1"; shift
342 # AArch64: prepare arch specific arguments
343 local virt_extra_args=""
344 if [ "$(uname -i)" = "aarch64" ]; then
345 # No Cirrus VGA on AArch64, use virtio instead
346 virt_extra_args="$virt_extra_args --video=virtio"
349 # create vms with specified options
350 for serialized_vnode_data in "${vnodes[@]}"; do
351 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
353 # prepare network args
354 local vnode_networks=("$@")
355 if [[ "${vnode_data[0]}" =~ ^(cfg01|mas01) ]]; then
356 net_args=" --network network=mcpcontrol,model=virtio"
357 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
358 vnode_networks[2]="${vnode_networks[0]}"
360 net_args=" --network bridge=${vnode_networks[0]},model=virtio"
362 for net in "${vnode_networks[@]:1}"; do
363 net_args="${net_args} --network bridge=${net},model=virtio"
366 # shellcheck disable=SC2086
367 virt-install --name "${vnode_data[0]}" \
368 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
369 --cpu host-passthrough --accelerate ${net_args} \
370 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
371 --os-type linux --os-variant none \
372 --boot hd --vnc --console pty --autostart --noreboot \
373 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
379 function update_mcpcontrol_network {
380 # set static ip address for salt master node, MaaS node
381 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
382 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
383 virsh net-update "mcpcontrol" add ip-dhcp-host \
384 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
385 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
386 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
393 for node in "${vnodes[@]}"; do
394 virsh start "${node}"
395 sleep $((RANDOM%5+1))
399 function check_connection {
400 local total_attempts=60
404 echo '[INFO] Attempting to get into Salt master ...'
406 # wait until ssh on Salt master is available
407 # shellcheck disable=SC2034
408 for attempt in $(seq "${total_attempts}"); do
409 # shellcheck disable=SC2086
410 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
412 0) echo "${attempt}> Success"; break ;;
413 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
420 function parse_yaml {
427 fs="$(echo @|tr @ '\034')"
428 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
429 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
431 indent = length($1)/2;
433 for (i in vname) {if (i > indent) {delete vname[i]}}
434 if (length($3) > 0) {
435 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
436 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
442 # Execute in a subshell to prevent local variable override during recursion
444 local total_attempts=$1; shift
447 echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
448 # shellcheck disable=SC2034
449 for attempt in $(seq "${total_attempts}"); do
450 echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
451 if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
452 # shellcheck disable=SC2015
453 eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
455 !(eval "${cmdstr}" || echo __fuel_wf_failure__) |& tee /dev/stderr | \
456 grep -Eq '(Not connected|No response|__fuel_wf_failure__)' && \
457 echo "[wait_for] OK: ${cmdstr}" && return 0 || true
459 sleep "${sleep_time}"
461 echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"
466 function do_sysctl_cfg {
467 local _conf='/etc/sysctl.d/99-opnfv-fuel-bridge.conf'
468 # https://wiki.libvirt.org/page/Net.bridge.bridge-nf-call_and_sysctl.conf
469 echo 'net.bridge.bridge-nf-call-arptables = 0' |& sudo tee "${_conf}"
470 echo 'net.bridge.bridge-nf-call-iptables = 0' |& sudo tee -a "${_conf}"
471 echo 'net.bridge.bridge-nf-call-ip6tables = 0' |& sudo tee -a "${_conf}"
472 sudo sysctl -q -p "${_conf}"
475 function get_nova_compute_pillar_data {
476 local value=$(salt -C 'I@nova:compute and *01*' pillar.get _param:"${1}" --out yaml | cut -d ' ' -f2)
477 if [ "${value}" != "''" ]; then
482 function do_templates() {
483 local git_repo_root=$1; shift
484 local image_dir=$1; shift
485 local target_lab=$1; shift
486 local target_pod=$1; shift
487 local lab_config_uri=$1; shift
488 local scenario_dir=${1:-}
490 RECLASS_CLUSTER_DIR=$(cd "${git_repo_root}/mcp/reclass/classes/cluster"; pwd)
491 PHAROS_GEN_CFG="./pharos/config/utils/generate_config.py"
492 PHAROS_INSTALLER_ADAPTER="./pharos/config/installers/fuel/pod_config.yml.j2"
493 BASE_CONFIG_PDF="${lab_config_uri}/labs/${target_lab}/${target_pod}.yaml"
494 BASE_CONFIG_IDF="${lab_config_uri}/labs/${target_lab}/idf-${target_pod}.yaml"
495 LOCAL_PDF="${image_dir}/$(basename "${BASE_CONFIG_PDF}")"
496 LOCAL_IDF="${image_dir}/$(basename "${BASE_CONFIG_IDF}")"
497 LOCAL_PDF_RECLASS="${image_dir}/pod_config.yml"
499 # Two-stage expansion, first stage handles pod_config and scenarios only
500 if [ -n "${scenario_dir}" ]; then
501 # Make sample PDF/IDF available via default lab-config (pharos submodule)
502 ln -sf "$(readlink -f "../config/labs/local")" "./pharos/labs/"
504 # Expand scenario file and main reclass input (pod_config.yaml) based on PDF
505 if ! curl --create-dirs -o "${LOCAL_PDF}" "${BASE_CONFIG_PDF}"; then
506 notify_e "[ERROR] Could not retrieve PDF (Pod Descriptor File)!"
507 elif ! curl -o "${LOCAL_IDF}" "${BASE_CONFIG_IDF}"; then
508 notify_e "[ERROR] Could not retrieve IDF (Installer Descriptor File)!"
509 elif ! "${PHAROS_GEN_CFG}" -y "${LOCAL_PDF}" \
510 -j "${PHAROS_INSTALLER_ADAPTER}" > "${LOCAL_PDF_RECLASS}"; then
511 notify_e "[ERROR] Could not convert PDF+IDF to reclass model input!"
513 template_dirs="${scenario_dir}"
514 template_err_str='Could not convert j2 scenario definitions!'
516 # Expand reclass and virsh network templates based on PDF + IDF
518 awk '/^(SALT|MCP|MAAS|CLUSTER).*=/ { gsub(/=/,": "); print }' >> "${LOCAL_PDF}"
519 template_dirs="${RECLASS_CLUSTER_DIR} virsh_net ./*j2"
520 template_err_str='Could not convert PDF to network definitions!'
522 # shellcheck disable=SC2086
523 find ${template_dirs} -name '*.j2' | while read -r tp; do
524 # Jinja2 import does not allow '..' directory traversal
525 if ! "${PHAROS_GEN_CFG}" -y "${LOCAL_PDF}" -j "${tp}" > "${tp%.j2}"; then
526 notify_e "[ERROR] ${template_err_str}"