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 -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/"
107 sudo depmod -a && sudo modprobe -f nbd max_part=8
110 function mount_image {
113 OPNFV_MNT_DIR="${image_dir}/ubuntu"
115 # Find free nbd, loop devices
116 for dev in '/sys/class/block/nbd'*; do
117 if [ "$(cat "${dev}/size")" = '0' ]; then
118 OPNFV_NBD_DEV=/dev/$(basename "${dev}")
122 OPNFV_LOOP_DEV=$(losetup -f)
123 OPNFV_MAP_DEV=/dev/mapper/$(basename "${OPNFV_NBD_DEV}")p1
124 export OPNFV_MNT_DIR OPNFV_LOOP_DEV
125 [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
126 qemu-img resize "${image_dir}/${image}" 3G
127 sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
128 "${image_dir}/${image}"
129 sudo kpartx -av "${OPNFV_NBD_DEV}"
130 sleep 5 # /dev/nbdNp1 takes some time to come up
131 # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
132 if sudo growpart "${OPNFV_NBD_DEV}" 1; then
133 sudo kpartx -u "${OPNFV_NBD_DEV}"
134 sudo e2fsck -pf "${OPNFV_MAP_DEV}"
135 sudo resize2fs "${OPNFV_MAP_DEV}"
137 # grub-update does not like /dev/nbd*, so use a loop device to work around it
138 sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_MAP_DEV}"
139 mkdir -p "${OPNFV_MNT_DIR}"
140 sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
141 sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
142 sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
143 sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
144 sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
145 sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
146 echo "GRUB_DISABLE_OS_PROBER=true" | \
147 sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
148 sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
149 "${OPNFV_MNT_DIR}/etc/default/grub"
152 function apt_repos_pkgs_image {
153 local apt_key_urls=(${1//,/ })
154 local all_repos=(${2//,/ })
155 local pkgs_i=(${3//,/ })
156 local pkgs_r=(${4//,/ })
157 [ -n "${OPNFV_MNT_DIR}" ] || exit 1
160 if [ "${#apt_key_urls[@]}" -gt 0 ]; then
161 for apt_key in "${apt_key_urls[@]}"; do
162 sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
163 "wget -qO - '${apt_key}' | apt-key add -"
166 # Additional repositories
167 for repo_line in "${all_repos[@]}"; do
168 # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
169 local repo=(${repo_line//|/ })
170 [ "${#repo[@]}" -gt 5 ] || continue
171 # NOTE: Names and formatting are compatible with Salt linux.system.repo
172 cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
175 Pin: release a=${repo[-2]}
176 Pin-Priority: ${repo[1]}
179 echo "${repo[@]:2}" | sudo tee \
180 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
183 if [ "${#pkgs_i[@]}" -gt 0 ]; then
184 sudo DEBIAN_FRONTEND="noninteractive" \
185 chroot "${OPNFV_MNT_DIR}" apt-get update
186 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
187 chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
190 if [ "${#pkgs_r[@]}" -gt 0 ]; then
191 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
192 chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
194 # Disable cloud-init metadata service datasource
195 sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
196 echo "datasource_list: [ NoCloud, None ]" | sudo tee \
197 "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
200 function cleanup_mounts {
201 # Remove any mounts, loop and/or nbd devs created while patching base image
202 if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
203 if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
204 # Grub thinks it's running from a live CD
205 sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
206 "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
208 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
210 if mountpoint -q "${OPNFV_MNT_DIR}"; then
211 sudo umount -l "${OPNFV_MNT_DIR}" || true
214 if [ -n "${OPNFV_LOOP_DEV}" ] && \
215 losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
216 sudo losetup -d "${OPNFV_LOOP_DEV}"
218 if [ -n "${OPNFV_NBD_DEV}" ]; then
219 sudo kpartx -d "${OPNFV_NBD_DEV}" || true
220 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
224 function cleanup_uefi {
225 # Clean up Ubuntu boot entry if cfg01, kvm nodes online from previous deploy
226 local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
227 [ ! "$(hostname)" = 'cfg01' ] || cmd_str='eval'
228 ${cmd_str} "sudo salt -C 'kvm* or cmp*' cmd.run \
229 \"which efibootmgr > /dev/null 2>&1 && \
230 efibootmgr | grep -oP '(?<=Boot)[0-9]+(?=.*ubuntu)' | \
231 xargs -I{} efibootmgr --delete-bootnum --bootnum {}; \
232 rm -rf /boot/efi/*\"" || true
235 function cleanup_vms {
236 # clean up existing nodes
237 for node in $(virsh list --name | grep -P '\w{3}\d{2}'); do
238 virsh destroy "${node}"
240 for node in $(virsh list --name --all | grep -P '\w{3}\d{2}'); do
241 virsh domblklist "${node}" | awk '/^.da/ {print $2}' | \
242 xargs --no-run-if-empty -I{} sudo rm -f {}
243 virsh undefine "${node}" --remove-all-storage --nvram
247 function prepare_vms {
248 local base_image=$1; shift
249 local image_dir=$1; shift
250 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
252 local image=base_image_opnfv_fuel.img
253 local vcp_image=${image%.*}_vcp.img
254 local _o=${base_image/*\/}
255 local _h=$(echo "${repos_pkgs_str}.$(md5sum "${image_dir}/${_o}")" | \
261 get_base_image "${base_image}" "${image_dir}"
262 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
264 echo "[INFO] Lookup cache / build patched base image for fingerprint: ${_h}"
265 _tmp="${image%.*}.${_h}.img"
266 if [ -f "$(readlink -f "${image_dir}/${_tmp}")" ]; then
267 echo "[INFO] Patched base image found"
269 rm -f "${image_dir}/${image%.*}"*
270 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
271 echo "[INFO] Patching base image ..."
272 cp "${image_dir}/${_o}" "${image_dir}/${_tmp}"
273 __kernel_modules "${image_dir}"
274 mount_image "${_tmp}" "${image_dir}"
275 apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
278 echo "[INFO] No patching required, using vanilla base image"
279 ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
282 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
284 envsubst < user-data.template > user-data.sh # CWD should be <mcp/scripts>
286 # Create config ISO and resize OS disk image for each foundation node VM
287 for node in "${vnodes[@]}"; do
288 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" -u user-data.sh \
289 -h "${node}" "${image_dir}/mcp_${node}.iso"
290 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
291 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
294 # VCP VMs base image specific changes
295 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
296 echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
297 _tmp="${vcp_image%.*}.${_h}.img"
298 if [ -f "$(readlink -f "${image_dir}/${_tmp}")" ]; then
299 echo "[INFO] Patched VCP image found"
301 echo "[INFO] Patching VCP image ..."
302 cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
303 __kernel_modules "${image_dir}"
304 mount_image "${_tmp}" "${image_dir}"
305 apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
308 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
312 function create_networks {
313 local vnode_networks=("$@")
314 # create required networks, including constant "mcpcontrol"
315 # FIXME(alav): since we renamed "pxe" to "mcpcontrol", we need to make sure
316 # we delete the old "pxe" virtual network, or it would cause IP conflicts.
317 for net in "pxe" "mcpcontrol" "${vnode_networks[@]}"; do
318 if virsh net-info "${net}" >/dev/null 2>&1; then
319 virsh net-destroy "${net}" || true
320 virsh net-undefine "${net}"
322 # in case of custom network, host should already have the bridge in place
323 if [ -f "net_${net}.xml" ] && [ ! -d "/sys/class/net/${net}/bridge" ]; then
324 virsh net-define "net_${net}.xml"
325 virsh net-autostart "${net}"
326 virsh net-start "${net}"
331 function create_vms {
332 local image_dir=$1; shift
333 # vnode data should be serialized with the following format:
334 # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
335 IFS='|' read -r -a vnodes <<< "$1"; shift
336 local vnode_networks=("$@")
338 # AArch64: prepare arch specific arguments
339 local virt_extra_args=""
340 if [ "$(uname -i)" = "aarch64" ]; then
341 # No Cirrus VGA on AArch64, use virtio instead
342 virt_extra_args="$virt_extra_args --video=virtio"
345 # create vms with specified options
346 for serialized_vnode_data in "${vnodes[@]}"; do
347 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
349 # prepare network args
350 net_args=" --network network=mcpcontrol,model=virtio"
351 if [ "${DEPLOY_TYPE:-}" = 'baremetal' ]; then
352 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
353 vnode_networks[2]="${vnode_networks[0]}"
355 for net in "${vnode_networks[@]:1}"; do
356 net_args="${net_args} --network bridge=${net},model=virtio"
359 # shellcheck disable=SC2086
360 virt-install --name "${vnode_data[0]}" \
361 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
362 --cpu host-passthrough --accelerate ${net_args} \
363 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
364 --os-type linux --os-variant none \
365 --boot hd --vnc --console pty --autostart --noreboot \
366 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
372 function update_mcpcontrol_network {
373 # set static ip address for salt master node, MaaS node
374 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
375 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
376 virsh net-update "mcpcontrol" add ip-dhcp-host \
377 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
378 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
379 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
386 for node in "${vnodes[@]}"; do
387 virsh start "${node}"
388 sleep $((RANDOM%5+1))
392 function check_connection {
393 local total_attempts=60
397 echo '[INFO] Attempting to get into Salt master ...'
399 # wait until ssh on Salt master is available
400 # shellcheck disable=SC2034
401 for attempt in $(seq "${total_attempts}"); do
402 # shellcheck disable=SC2086
403 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
405 0) echo "${attempt}> Success"; break ;;
406 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
413 function parse_yaml {
420 fs="$(echo @|tr @ '\034')"
421 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
422 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
424 indent = length($1)/2;
426 for (i in vname) {if (i > indent) {delete vname[i]}}
427 if (length($3) > 0) {
428 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
429 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
435 # Execute in a subshell to prevent local variable override during recursion
437 local total_attempts=$1; shift
440 echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
441 # shellcheck disable=SC2034
442 for attempt in $(seq "${total_attempts}"); do
443 echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
444 if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
445 # shellcheck disable=SC2015
446 eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
448 !(eval "${cmdstr}" || echo __fuel_wf_failure__) |& tee /dev/stderr | \
449 grep -Eq '(Not connected|No response|__fuel_wf_failure__)' && \
450 echo "[wait_for] OK: ${cmdstr}" && return 0 || true
452 sleep "${sleep_time}"
454 echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"