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 ##############################################################################
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
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
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."
54 # Best-effort attempt at building a non-maintaned kernel module
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"
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"
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
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 ..."
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
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
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/"
109 sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8
112 function mount_image {
115 OPNFV_MNT_DIR="${image_dir}/ubuntu"
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}")
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}"
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"
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
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 -"
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]}"
177 Pin: release a=${repo[-2]}
178 Pin-Priority: ${repo[1]}
181 echo "${repo[@]:2}" | sudo tee \
182 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
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[@]}"
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[@]}"
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"
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"
210 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
212 if mountpoint -q "${OPNFV_MNT_DIR}"; then
213 sudo umount -l "${OPNFV_MNT_DIR}" || true
216 if [ -n "${OPNFV_LOOP_DEV}" ] && \
217 sudo losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
218 sudo losetup -d "${OPNFV_LOOP_DEV}"
220 if [ -n "${OPNFV_NBD_DEV}" ]; then
221 sudo kpartx -d "${OPNFV_NBD_DEV}" || true
222 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
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
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}"
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
250 function prepare_vms {
251 local base_image=$1; shift
252 local image_dir=$1; shift
253 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
255 local image=base_image_opnfv_fuel.img
256 local vcp_image=${image%.*}_vcp.img
257 local _o=${base_image/*\/}
258 local _h=$(echo "${repos_pkgs_str}.$(md5sum "${image_dir}/${_o}")" | \
264 get_base_image "${base_image}" "${image_dir}"
265 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
267 echo "[INFO] Lookup cache / build patched base image for fingerprint: ${_h}"
268 _tmp="${image%.*}.${_h}.img"
269 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${image}" ]; then
270 echo "[INFO] Patched base image found"
272 rm -f "${image_dir}/${image%.*}"*
273 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
274 echo "[INFO] Patching base image ..."
275 cp "${image_dir}/${_o}" "${image_dir}/${_tmp}"
276 __kernel_modules "${image_dir}"
277 mount_image "${_tmp}" "${image_dir}"
278 apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
281 echo "[INFO] No patching required, using vanilla base image"
282 ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
284 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
287 # Create config ISO and resize OS disk image for each foundation node VM
288 for node in "${vnodes[@]}"; do
289 if [[ "${node}" =~ ^(cfg01|mas01) ]]; then
290 user_data='user-data.mcp.sh'
292 user_data='user-data.admin.sh'
294 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" \
295 -u "${user_data}" -h "${node}" "${image_dir}/mcp_${node}.iso"
296 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
297 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
298 # Prepare dedicated drive for cinder on cmp nodes
299 if [[ "${node}" =~ ^(cmp) ]]; then
300 qemu-img create "${image_dir}/mcp_${node}_storage.qcow2" 100G
304 # VCP VMs base image specific changes
305 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
306 echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
307 _tmp="${vcp_image%.*}.${_h}.img"
308 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
309 echo "[INFO] Patched VCP image found"
311 echo "[INFO] Patching VCP image ..."
312 cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
313 __kernel_modules "${image_dir}"
314 mount_image "${_tmp}" "${image_dir}"
315 apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
317 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
322 function jumpserver_pkg_install {
323 if [ -n "$(command -v apt-get)" ]; then
324 pkg_type='deb'; pkg_cmd='sudo apt-get install -y'
326 pkg_type='rpm'; pkg_cmd='sudo yum install -y --skip-broken'
328 eval "$(parse_yaml "./requirements_${pkg_type}.yaml")"
329 for section in 'common' "$(uname -i)"; do
330 section_var="requirements_pkg_${section}[*]"
331 pkg_list+=" ${!section_var}"
333 # shellcheck disable=SC2086
334 ${pkg_cmd} ${pkg_list}
337 function jumpserver_check_requirements {
338 # shellcheck disable=SC2178
339 local vnodes=$1; shift
341 local err_br_not_found='Linux bridge not found!'
342 local err_br_virsh_net='is a virtual network, Linux bridge expected!'
343 local warn_br_endpoint="Endpoints might be inaccessible from external hosts!"
344 # MaaS requires a Linux bridge for PXE/admin
345 if [[ "${vnodes}" =~ mas01 ]]; then
346 if ! brctl showmacs "${br[0]}" >/dev/null 2>&1; then
347 notify_e "[ERROR] PXE/admin (${br[0]}) ${err_br_not_found}"
349 # Assume virsh network name matches bridge name (true if created by us)
350 if virsh net-info "${br[0]}" >/dev/null 2>&1; then
351 notify_e "[ERROR] ${br[0]} ${err_br_virsh_net}"
354 # If virtual nodes are present, public should be a Linux bridge
355 if [ "$(echo "${vnodes}" | wc -w)" -gt 2 ]; then
356 if ! brctl showmacs "${br[3]}" >/dev/null 2>&1; then
357 if [[ "${vnodes}" =~ mas01 ]]; then
358 # Baremetal nodes *require* a proper public network
359 notify_e "[ERROR] Public (${br[3]}) ${err_br_not_found}"
361 notify_n "[WARN] Public (${br[3]}) ${err_br_not_found}" 3
362 notify_n "[WARN] ${warn_br_endpoint}" 3
365 if virsh net-info "${br[3]}" >/dev/null 2>&1; then
366 if [[ "${vnodes}" =~ mas01 ]]; then
367 notify_e "[ERROR] ${br[3]} ${err_br_virsh_net}"
369 notify_n "[WARN] ${br[3]} ${err_br_virsh_net}" 3
370 notify_n "[WARN] ${warn_br_endpoint}" 3
376 function create_networks {
377 local vnode_networks=("$@")
378 # create required networks, including constant "mcpcontrol"
379 for net in "mcpcontrol" "${vnode_networks[@]}"; do
380 if virsh net-info "${net}" >/dev/null 2>&1; then
381 virsh net-destroy "${net}" || true
382 virsh net-undefine "${net}"
384 # in case of custom network, host should already have the bridge in place
385 if [ -f "virsh_net/net_${net}.xml" ] && \
386 [ ! -d "/sys/class/net/${net}/bridge" ]; then
387 virsh net-define "virsh_net/net_${net}.xml"
388 virsh net-autostart "${net}"
389 virsh net-start "${net}"
394 function create_vms {
395 local image_dir=$1; shift
396 # vnode data should be serialized with the following format:
397 # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
398 IFS='|' read -r -a vnodes <<< "$1"; shift
400 # AArch64: prepare arch specific arguments
401 local virt_extra_args=""
402 if [ "$(uname -i)" = "aarch64" ]; then
403 # No Cirrus VGA on AArch64, use virtio instead
404 virt_extra_args="$virt_extra_args --video=virtio"
407 # create vms with specified options
408 for serialized_vnode_data in "${vnodes[@]}"; do
409 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
411 # prepare network args
412 local vnode_networks=("$@")
413 if [[ "${vnode_data[0]}" =~ ^(cfg01|mas01) ]]; then
414 net_args=" --network network=mcpcontrol,model=virtio"
415 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
416 vnode_networks[2]="${vnode_networks[0]}"
418 net_args=" --network bridge=${vnode_networks[0]},model=virtio"
420 for net in "${vnode_networks[@]:1}"; do
421 net_args="${net_args} --network bridge=${net},model=virtio"
424 # dedicated storage drive for cinder on cmp nodes
426 if [[ "${vnode_data[0]}" =~ ^(cmp) ]]; then
427 virt_extra_storage="--disk path=${image_dir}/mcp_${vnode_data[0]}_storage.qcow2,format=qcow2,bus=virtio,cache=none,io=native"
430 # shellcheck disable=SC2086
431 virt-install --name "${vnode_data[0]}" \
432 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
433 --cpu host-passthrough --accelerate ${net_args} \
434 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
435 ${virt_extra_storage} \
436 --os-type linux --os-variant none \
437 --boot hd --vnc --console pty --autostart --noreboot \
438 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
444 function update_mcpcontrol_network {
445 # set static ip address for salt master node, MaaS node
446 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
447 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
448 virsh net-update "mcpcontrol" add ip-dhcp-host \
449 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
450 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
451 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
458 for node in "${vnodes[@]}"; do
459 virsh start "${node}"
460 sleep $((RANDOM%5+1))
464 function check_connection {
465 local total_attempts=60
469 echo '[INFO] Attempting to get into Salt master ...'
471 # wait until ssh on Salt master is available
472 # shellcheck disable=SC2034
473 for attempt in $(seq "${total_attempts}"); do
474 # shellcheck disable=SC2086
475 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
477 0) echo "${attempt}> Success"; break ;;
478 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
485 function parse_yaml {
492 fs="$(echo @|tr @ '\034')"
493 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
494 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
496 indent = length($1)/2;
498 for (i in vname) {if (i > indent) {delete vname[i]}}
499 if (length($3) > 0) {
500 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
501 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
507 # Execute in a subshell to prevent local variable override during recursion
509 local total_attempts=$1; shift
512 echo -e "\n[wait_for] Waiting for cmd to return success: ${cmdstr}"
513 # shellcheck disable=SC2034
514 for attempt in $(seq "${total_attempts}"); do
515 echo "[wait_for] Attempt ${attempt}/${total_attempts%.*} for: ${cmdstr}"
516 if [ "${total_attempts%.*}" = "${total_attempts}" ]; then
517 eval "${cmdstr}" && echo "[wait_for] OK: ${cmdstr}" && return 0 || true
519 ! (eval "${cmdstr}" || echo 'No response') |& tee /dev/stderr | \
520 grep -Eq '(Not connected|No response)' && \
521 echo "[wait_for] OK: ${cmdstr}" && return 0 || true
523 sleep "${sleep_time}"
525 echo "[wait_for] ERROR: Failed after max attempts: ${cmdstr}"
530 function do_sysctl_cfg {
531 local _conf='/etc/sysctl.d/99-opnfv-fuel-bridge.conf'
532 # https://wiki.libvirt.org/page/Net.bridge.bridge-nf-call_and_sysctl.conf
533 if modprobe br_netfilter bridge; then
534 echo 'net.bridge.bridge-nf-call-arptables = 0' |& sudo tee "${_conf}"
535 echo 'net.bridge.bridge-nf-call-iptables = 0' |& sudo tee -a "${_conf}"
536 echo 'net.bridge.bridge-nf-call-ip6tables = 0' |& sudo tee -a "${_conf}"
537 # Some distros / sysadmins explicitly blacklist br_netfilter
538 sudo sysctl -q -p "${_conf}" || true
542 function get_nova_compute_pillar_data {
543 local value=$(salt -C 'I@nova:compute and *01*' pillar.get _param:"${1}" --out yaml | cut -d ' ' -f2)
544 if [ "${value}" != "''" ]; then