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 mount_image {
41 OPNFV_MNT_DIR="${image_dir}/ubuntu"
43 sudo modprobe nbd loop
44 # Find free nbd, loop devices
45 for dev in '/sys/class/block/nbd'*; do
46 if [ "$(cat "${dev}/size")" = '0' ]; then
47 OPNFV_NBD_DEV=/dev/$(basename "${dev}")
51 OPNFV_LOOP_DEV=$(losetup -f)
52 export OPNFV_MNT_DIR OPNFV_LOOP_DEV
53 [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
54 qemu-img resize "${image_dir}/${image}" 3G
55 sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
56 "${image_dir}/${image}"
57 sleep 5 # /dev/nbdNp1 takes some time to come up
58 # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
59 if sudo growpart "${OPNFV_NBD_DEV}" 1; then
60 sudo e2fsck -yf "${OPNFV_NBD_DEV}p1" && sudo resize2fs "${OPNFV_NBD_DEV}p1"
62 # grub-update does not like /dev/nbd*, so use a loop device to work around it
63 sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_NBD_DEV}p1"
64 mkdir -p "${OPNFV_MNT_DIR}"
65 sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
66 sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
67 sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
68 sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
69 sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
70 sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
71 echo "GRUB_DISABLE_OS_PROBER=true" | \
72 sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
73 sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
74 "${OPNFV_MNT_DIR}/etc/default/grub"
77 function apt_repos_pkgs_image {
78 local apt_key_urls=(${1//,/ })
79 local all_repos=(${2//,/ })
80 local pkgs_i=(${3//,/ })
81 local pkgs_r=(${4//,/ })
82 [ -n "${OPNFV_MNT_DIR}" ] || exit 1
85 if [ "${#apt_key_urls[@]}" -gt 0 ]; then
86 for apt_key in "${apt_key_urls[@]}"; do
87 sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
88 "wget -qO - '${apt_key}' | apt-key add -"
91 # Additional repositories
92 for repo_line in "${all_repos[@]}"; do
93 # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
94 local repo=(${repo_line//|/ })
95 [ "${#repo[@]}" -gt 5 ] || continue
96 # NOTE: Names and formatting are compatible with Salt linux.system.repo
97 cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
100 Pin: release a=${repo[-2]}
101 Pin-Priority: ${repo[1]}
104 echo "${repo[@]:2}" | sudo tee \
105 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
108 if [ "${#pkgs_i[@]}" -gt 0 ]; then
109 sudo DEBIAN_FRONTEND="noninteractive" \
110 chroot "${OPNFV_MNT_DIR}" apt-get update
111 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
112 chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
115 if [ "${#pkgs_r[@]}" -gt 0 ]; then
116 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
117 chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
119 # Disable cloud-init metadata service datasource
120 sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
121 echo "datasource_list: [ NoCloud, None ]" | sudo tee \
122 "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
125 function cleanup_mounts {
126 # Remove any mounts, loop and/or nbd devs created while patching base image
127 if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
128 if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
129 # Grub thinks it's running from a live CD
130 sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
131 "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
133 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
135 if mountpoint -q "${OPNFV_MNT_DIR}"; then
136 sudo umount -l "${OPNFV_MNT_DIR}" || true
139 if [ -n "${OPNFV_LOOP_DEV}" ] && \
140 losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
141 sudo losetup -d "${OPNFV_LOOP_DEV}"
143 if [ -n "${OPNFV_NBD_DEV}" ]; then
144 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
148 function cleanup_uefi {
149 # Clean up Ubuntu boot entry if cfg01, kvm nodes online from previous deploy
150 # shellcheck disable=SC2086
151 ssh ${SSH_OPTS} "${SSH_SALT}" "sudo salt -C 'kvm* or cmp*' cmd.run \
152 \"which efibootmgr > /dev/null 2>&1 && \
153 efibootmgr | grep -oP '(?<=Boot)[0-9]+(?=.*ubuntu)' | \
154 xargs -I{} efibootmgr --delete-bootnum --bootnum {}; \
155 rm -rf /boot/efi/*\"" || true
158 function cleanup_vms {
159 # clean up existing nodes
160 for node in $(virsh list --name | grep -P '\w{3}\d{2}'); do
161 virsh destroy "${node}"
163 for node in $(virsh list --name --all | grep -P '\w{3}\d{2}'); do
164 virsh domblklist "${node}" | awk '/^.da/ {print $2}' | \
165 xargs --no-run-if-empty -I{} sudo rm -f {}
166 virsh undefine "${node}" --remove-all-storage --nvram
170 function prepare_vms {
171 local base_image=$1; shift
172 local image_dir=$1; shift
173 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
175 local image=base_image_opnfv_fuel.img
179 get_base_image "${base_image}" "${image_dir}"
181 rm -f "${image_dir}/${image%.*}"*
182 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
183 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
184 cp "${image_dir}/${base_image/*\/}" "${image_dir}/${image}"
185 mount_image "${image}" "${image_dir}"
186 apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
189 ln -sf "${image_dir}/${base_image/*\/}" "${image_dir}/${image}"
192 # CWD should be <mcp/scripts>
193 # shellcheck disable=SC2016
194 envsubst '${SALT_MASTER},${CLUSTER_DOMAIN}' < \
195 user-data.template > user-data.sh
197 # Create config ISO and resize OS disk image for each foundation node VM
198 for node in "${vnodes[@]}"; do
199 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" -u user-data.sh \
200 -h "${node}" "${image_dir}/mcp_${node}.iso"
201 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
202 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
205 # VCP VMs base image specific changes
206 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
207 mount_image "${image}" "${image_dir}"
208 apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
210 ln -sf "${image_dir}/${image}" "${image_dir}/${image%.*}_vcp.img"
214 function create_networks {
215 local vnode_networks=("$@")
216 # create required networks, including constant "mcpcontrol"
217 # FIXME(alav): since we renamed "pxe" to "mcpcontrol", we need to make sure
218 # we delete the old "pxe" virtual network, or it would cause IP conflicts.
219 # FIXME(alav): The same applies for "fuel1" virsh network.
220 for net in "fuel1" "pxe" "mcpcontrol" "${vnode_networks[@]}"; do
221 if virsh net-info "${net}" >/dev/null 2>&1; then
222 virsh net-destroy "${net}" || true
223 virsh net-undefine "${net}"
225 # in case of custom network, host should already have the bridge in place
226 if [ -f "net_${net}.xml" ] && [ ! -d "/sys/class/net/${net}/bridge" ]; then
227 virsh net-define "net_${net}.xml"
228 virsh net-autostart "${net}"
229 virsh net-start "${net}"
234 function create_vms {
235 local image_dir=$1; shift
236 # vnode data should be serialized with the following format:
237 # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
238 IFS='|' read -r -a vnodes <<< "$1"; shift
239 local vnode_networks=("$@")
241 # AArch64: prepare arch specific arguments
242 local virt_extra_args=""
243 if [ "$(uname -i)" = "aarch64" ]; then
244 # No Cirrus VGA on AArch64, use virtio instead
245 virt_extra_args="$virt_extra_args --video=virtio"
248 # create vms with specified options
249 for serialized_vnode_data in "${vnodes[@]}"; do
250 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
252 # prepare network args
253 net_args=" --network network=mcpcontrol,model=virtio"
254 if [ "${vnode_data[0]}" = "mas01" ]; then
255 # MaaS node's 3rd interface gets connected to PXE/Admin Bridge
256 vnode_networks[2]="${vnode_networks[0]}"
258 for net in "${vnode_networks[@]:1}"; do
259 net_args="${net_args} --network bridge=${net},model=virtio"
262 # shellcheck disable=SC2086
263 virt-install --name "${vnode_data[0]}" \
264 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
265 --cpu host-passthrough --accelerate ${net_args} \
266 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
267 --os-type linux --os-variant none \
268 --boot hd --vnc --console pty --autostart --noreboot \
269 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
275 function update_mcpcontrol_network {
276 # set static ip address for salt master node, MaaS node
277 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
278 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
279 virsh net-update "mcpcontrol" add ip-dhcp-host \
280 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live
281 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
282 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live
289 for node in "${vnodes[@]}"; do
290 virsh start "${node}"
291 sleep $((RANDOM%5+1))
295 function check_connection {
296 local total_attempts=60
300 echo '[INFO] Attempting to get into Salt master ...'
302 # wait until ssh on Salt master is available
303 # shellcheck disable=SC2034
304 for attempt in $(seq "${total_attempts}"); do
305 # shellcheck disable=SC2086
306 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
308 0) echo "${attempt}> Success"; break ;;
309 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
316 function parse_yaml {
323 fs="$(echo @|tr @ '\034')"
324 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
325 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
327 indent = length($1)/2;
329 for (i in vname) {if (i > indent) {delete vname[i]}}
330 if (length($3) > 0) {
331 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
332 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
338 # Execute in a subshell to prevent local variable override during recursion
340 local total_attempts=$1; shift
343 echo "[NOTE] Waiting for cmd to return success: ${cmdstr}"
344 # shellcheck disable=SC2034
345 for attempt in $(seq "${total_attempts}"); do
346 # shellcheck disable=SC2015
347 eval "${cmdstr}" && return 0 || true
348 echo -n '.'; sleep "${sleep_time}"