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 -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 envsubst < user-data.template > user-data.sh # CWD should be <mcp/scripts>
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
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"
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}"
308 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
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}"
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}"
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=("$@")
339 # AArch64: prepare arch specific arguments
340 local virt_extra_args=""
341 if [ "$(uname -i)" = "aarch64" ]; then
342 # No Cirrus VGA on AArch64, use virtio instead
343 virt_extra_args="$virt_extra_args --video=virtio"
346 # create vms with specified options
347 for serialized_vnode_data in "${vnodes[@]}"; do
348 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
350 # prepare network args
351 net_args=" --network network=mcpcontrol,model=virtio"
352 if [ "${DEPLOY_TYPE:-}" = 'baremetal' ]; then
353 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
354 vnode_networks[2]="${vnode_networks[0]}"
356 for net in "${vnode_networks[@]:1}"; do
357 net_args="${net_args} --network bridge=${net},model=virtio"
360 # shellcheck disable=SC2086
361 virt-install --name "${vnode_data[0]}" \
362 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
363 --cpu host-passthrough --accelerate ${net_args} \
364 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
365 --os-type linux --os-variant none \
366 --boot hd --vnc --console pty --autostart --noreboot \
367 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
373 function update_mcpcontrol_network {
374 # set static ip address for salt master node, MaaS node
375 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
376 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
377 virsh net-update "mcpcontrol" add ip-dhcp-host \
378 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
379 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
380 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
387 for node in "${vnodes[@]}"; do
388 virsh start "${node}"
389 sleep $((RANDOM%5+1))
393 function check_connection {
394 local total_attempts=60
398 echo '[INFO] Attempting to get into Salt master ...'
400 # wait until ssh on Salt master is available
401 # shellcheck disable=SC2034
402 for attempt in $(seq "${total_attempts}"); do
403 # shellcheck disable=SC2086
404 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
406 0) echo "${attempt}> Success"; break ;;
407 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
414 function parse_yaml {
421 fs="$(echo @|tr @ '\034')"
422 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
423 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
425 indent = length($1)/2;
427 for (i in vname) {if (i > indent) {delete vname[i]}}
428 if (length($3) > 0) {
429 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
430 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
436 # Execute in a subshell to prevent local variable override during recursion
438 local total_attempts=$1; shift
441 echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
442 # shellcheck disable=SC2034
443 for attempt in $(seq "${total_attempts}"); do
444 echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
445 if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
446 # shellcheck disable=SC2015
447 eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
449 !(eval "${cmdstr}" || echo __fuel_wf_failure__) |& tee /dev/stderr | \
450 grep -Eq '(Not connected|No response|__fuel_wf_failure__)' && \
451 echo "[wait_for] OK: ${cmdstr}" && return 0 || true
453 sleep "${sleep_time}"
455 echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"
460 function get_nova_compute_pillar_data {
461 local value=$(salt -C 'I@nova:compute and *01*' pillar.get _param:"${1}" --out yaml | cut -d ' ' -f2)
462 if [ "${value}" != "''" ]; then