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 sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
55 "${image_dir}/${image}"
56 sleep 5 # /dev/nbdNp1 takes some time to come up
57 # grub-update does not like /dev/nbd*, so use a loop device to work around it
58 # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
59 sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_NBD_DEV}p1"
60 mkdir -p "${OPNFV_MNT_DIR}"
61 sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
62 sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
63 sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
64 sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
65 sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
66 sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
67 echo "GRUB_DISABLE_OS_PROBER=true" | \
68 sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
71 function apt_repos_pkgs_image {
72 local apt_key_urls=(${1//,/ })
73 local all_repos=(${2//,/ })
74 local pkgs_i=(${3//,/ })
75 local pkgs_r=(${4//,/ })
76 [ -n "${OPNFV_MNT_DIR}" ] || exit 1
79 if [ "${#apt_key_urls[@]}" -gt 0 ]; then
80 for apt_key in "${apt_key_urls[@]}"; do
81 sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
82 "wget -qO - '${apt_key}' | apt-key add -"
85 # Additional repositories
86 for repo_line in "${all_repos[@]}"; do
87 # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
88 local repo=(${repo_line//|/ })
89 [ "${#repo[@]}" -gt 5 ] || continue
90 # NOTE: Names and formatting are compatible with Salt linux.system.repo
91 cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
94 Pin: release a=${repo[-2]}
95 Pin-Priority: ${repo[1]}
98 echo "${repo[@]:2}" | sudo tee \
99 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
102 if [ "${#pkgs_i[@]}" -gt 0 ]; then
103 sudo DEBIAN_FRONTEND="noninteractive" \
104 chroot "${OPNFV_MNT_DIR}" apt-get update
105 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
106 chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
109 if [ "${#pkgs_r[@]}" -gt 0 ]; then
110 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
111 chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
113 # Disable cloud-init metadata service datasource
114 sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
115 echo "datasource_list: [ NoCloud, None ]" | sudo tee \
116 "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
119 function cleanup_mounts {
120 # Remove any mounts, loop and/or nbd devs created while patching base image
121 if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
122 if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
123 # Grub thinks it's running from a live CD
124 sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
125 "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
127 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
129 if mountpoint -q "${OPNFV_MNT_DIR}"; then
130 sudo umount -l "${OPNFV_MNT_DIR}" || true
133 if [ -n "${OPNFV_LOOP_DEV}" ] && \
134 losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
135 sudo losetup -d "${OPNFV_LOOP_DEV}"
137 if [ -n "${OPNFV_NBD_DEV}" ]; then
138 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
142 function cleanup_uefi {
143 # Clean up Ubuntu boot entry if cfg01, kvm nodes online from previous deploy
144 # shellcheck disable=SC2086
145 ssh ${SSH_OPTS} "${SSH_SALT}" "sudo salt -C 'kvm* or cmp*' cmd.run \
146 \"which efibootmgr > /dev/null 2>&1 && \
147 efibootmgr | grep -oP '(?<=Boot)[0-9]+(?=.*ubuntu)' | \
148 xargs -I{} efibootmgr --delete-bootnum --bootnum {}; \
149 rm -rf /boot/efi/*\"" || true
152 function cleanup_vms {
153 # clean up existing nodes
154 for node in $(virsh list --name | grep -P '\w{3}\d{2}'); do
155 virsh destroy "${node}"
157 for node in $(virsh list --name --all | grep -P '\w{3}\d{2}'); do
158 virsh domblklist "${node}" | awk '/^.da/ {print $2}' | \
159 xargs --no-run-if-empty -I{} sudo rm -f {}
160 virsh undefine "${node}" --remove-all-storage --nvram
164 function prepare_vms {
165 local base_image=$1; shift
166 local image_dir=$1; shift
167 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
169 local image=base_image_opnfv_fuel.img
173 get_base_image "${base_image}" "${image_dir}"
175 rm -f "${image_dir}/${image%.*}"*
176 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
177 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
178 cp "${image_dir}/${base_image/*\/}" "${image_dir}/${image}"
179 mount_image "${image}" "${image_dir}"
180 apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
183 ln -sf "${image_dir}/${base_image/*\/}" "${image_dir}/${image}"
186 # CWD should be <mcp/scripts>
187 # shellcheck disable=SC2016
188 envsubst '${SALT_MASTER},${CLUSTER_DOMAIN}' < \
189 user-data.template > user-data.sh
191 # Create config ISO and resize OS disk image for each foundation node VM
192 for node in "${vnodes[@]}"; do
193 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" -u user-data.sh \
194 -h "${node}" "${image_dir}/mcp_${node}.iso"
195 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
196 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
199 # VCP VMs base image specific changes
200 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
201 mount_image "${image}" "${image_dir}"
202 apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
204 ln -sf "${image_dir}/${image}" "${image_dir}/${image%.*}_vcp.img"
208 function create_networks {
209 local vnode_networks=("$@")
210 # create required networks, including constant "mcpcontrol"
211 # FIXME(alav): since we renamed "pxe" to "mcpcontrol", we need to make sure
212 # we delete the old "pxe" virtual network, or it would cause IP conflicts.
213 # FIXME(alav): The same applies for "fuel1" virsh network.
214 for net in "fuel1" "pxe" "mcpcontrol" "${vnode_networks[@]}"; do
215 if virsh net-info "${net}" >/dev/null 2>&1; then
216 virsh net-destroy "${net}" || true
217 virsh net-undefine "${net}"
219 # in case of custom network, host should already have the bridge in place
220 if [ -f "net_${net}.xml" ] && [ ! -d "/sys/class/net/${net}/bridge" ]; then
221 virsh net-define "net_${net}.xml"
222 virsh net-autostart "${net}"
223 virsh net-start "${net}"
228 function create_vms {
229 local image_dir=$1; shift
230 # vnode data should be serialized with the following format:
231 # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
232 IFS='|' read -r -a vnodes <<< "$1"; shift
233 local vnode_networks=("$@")
235 # AArch64: prepare arch specific arguments
236 local virt_extra_args=""
237 if [ "$(uname -i)" = "aarch64" ]; then
238 # No Cirrus VGA on AArch64, use virtio instead
239 virt_extra_args="$virt_extra_args --video=virtio"
242 # create vms with specified options
243 for serialized_vnode_data in "${vnodes[@]}"; do
244 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
246 # prepare network args
247 net_args=" --network network=mcpcontrol,model=virtio"
248 if [ "${vnode_data[0]}" = "mas01" ]; then
249 # MaaS node's 3rd interface gets connected to PXE/Admin Bridge
250 vnode_networks[2]="${vnode_networks[0]}"
252 for net in "${vnode_networks[@]:1}"; do
253 net_args="${net_args} --network bridge=${net},model=virtio"
256 # shellcheck disable=SC2086
257 virt-install --name "${vnode_data[0]}" \
258 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
259 --cpu host-passthrough --accelerate ${net_args} \
260 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
261 --os-type linux --os-variant none \
262 --boot hd --vnc --console pty --autostart --noreboot \
263 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
269 function update_mcpcontrol_network {
270 # set static ip address for salt master node, MaaS node
271 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
272 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
273 virsh net-update "mcpcontrol" add ip-dhcp-host \
274 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live
275 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
276 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live
283 for node in "${vnodes[@]}"; do
284 virsh start "${node}"
285 sleep $((RANDOM%5+1))
289 function check_connection {
290 local total_attempts=60
294 echo '[INFO] Attempting to get into Salt master ...'
296 # wait until ssh on Salt master is available
297 # shellcheck disable=SC2034
298 for attempt in $(seq "${total_attempts}"); do
299 # shellcheck disable=SC2086
300 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
302 0) echo "${attempt}> Success"; break ;;
303 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
310 function parse_yaml {
317 fs="$(echo @|tr @ '\034')"
318 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
319 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
321 indent = length($1)/2;
323 for (i in vname) {if (i > indent) {delete vname[i]}}
324 if (length($3) > 0) {
325 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
326 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
332 # Execute in a subshell to prevent local variable override during recursion
334 local total_attempts=$1; shift
337 echo "[NOTE] Waiting for cmd to return success: ${cmdstr}"
338 # shellcheck disable=SC2034
339 for attempt in $(seq "${total_attempts}"); do
340 # shellcheck disable=SC2015
341 eval "${cmdstr}" && return 0 || true
342 echo -n '.'; sleep "${sleep_time}"