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 OPNFV_MAP_DEV=/dev/mapper/$(basename "${OPNFV_NBD_DEV}")p1
53 export OPNFV_MNT_DIR OPNFV_LOOP_DEV
54 [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
55 qemu-img resize "${image_dir}/${image}" 3G
56 sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
57 "${image_dir}/${image}"
58 sudo kpartx -av "${OPNFV_NBD_DEV}"
59 # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
60 if sudo growpart "${OPNFV_NBD_DEV}" 1; then
61 sudo kpartx -u "${OPNFV_NBD_DEV}"
62 sudo e2fsck -yf "${OPNFV_MAP_DEV}"
63 sudo resize2fs "${OPNFV_MAP_DEV}"
65 # grub-update does not like /dev/nbd*, so use a loop device to work around it
66 sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_MAP_DEV}"
67 mkdir -p "${OPNFV_MNT_DIR}"
68 sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
69 sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
70 sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
71 sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
72 sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
73 sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
74 echo "GRUB_DISABLE_OS_PROBER=true" | \
75 sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
76 sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
77 "${OPNFV_MNT_DIR}/etc/default/grub"
80 function apt_repos_pkgs_image {
81 local apt_key_urls=(${1//,/ })
82 local all_repos=(${2//,/ })
83 local pkgs_i=(${3//,/ })
84 local pkgs_r=(${4//,/ })
85 [ -n "${OPNFV_MNT_DIR}" ] || exit 1
88 if [ "${#apt_key_urls[@]}" -gt 0 ]; then
89 for apt_key in "${apt_key_urls[@]}"; do
90 sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
91 "wget -qO - '${apt_key}' | apt-key add -"
94 # Additional repositories
95 for repo_line in "${all_repos[@]}"; do
96 # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
97 local repo=(${repo_line//|/ })
98 [ "${#repo[@]}" -gt 5 ] || continue
99 # NOTE: Names and formatting are compatible with Salt linux.system.repo
100 cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
103 Pin: release a=${repo[-2]}
104 Pin-Priority: ${repo[1]}
107 echo "${repo[@]:2}" | sudo tee \
108 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
111 if [ "${#pkgs_i[@]}" -gt 0 ]; then
112 sudo DEBIAN_FRONTEND="noninteractive" \
113 chroot "${OPNFV_MNT_DIR}" apt-get update
114 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
115 chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
118 if [ "${#pkgs_r[@]}" -gt 0 ]; then
119 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
120 chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
122 # Disable cloud-init metadata service datasource
123 sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
124 echo "datasource_list: [ NoCloud, None ]" | sudo tee \
125 "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
128 function cleanup_mounts {
129 # Remove any mounts, loop and/or nbd devs created while patching base image
130 if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
131 if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
132 # Grub thinks it's running from a live CD
133 sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
134 "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
136 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
138 if mountpoint -q "${OPNFV_MNT_DIR}"; then
139 sudo umount -l "${OPNFV_MNT_DIR}" || true
142 if [ -n "${OPNFV_LOOP_DEV}" ] && \
143 losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
144 sudo losetup -d "${OPNFV_LOOP_DEV}"
146 if [ -n "${OPNFV_NBD_DEV}" ]; then
147 sudo kpartx -d "${OPNFV_NBD_DEV}" || true
148 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true
152 function cleanup_uefi {
153 # Clean up Ubuntu boot entry if cfg01, kvm nodes online from previous deploy
154 local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
155 [ ! "$(hostname)" = 'cfg01' ] || cmd_str='eval'
156 ${cmd_str} "sudo salt -C 'kvm* or cmp*' cmd.run \
157 \"which efibootmgr > /dev/null 2>&1 && \
158 efibootmgr | grep -oP '(?<=Boot)[0-9]+(?=.*ubuntu)' | \
159 xargs -I{} efibootmgr --delete-bootnum --bootnum {}; \
160 rm -rf /boot/efi/*\"" || true
163 function cleanup_vms {
164 # clean up existing nodes
165 for node in $(virsh list --name | grep -P '\w{3}\d{2}'); do
166 virsh destroy "${node}"
168 for node in $(virsh list --name --all | grep -P '\w{3}\d{2}'); do
169 virsh domblklist "${node}" | awk '/^.da/ {print $2}' | \
170 xargs --no-run-if-empty -I{} sudo rm -f {}
171 virsh undefine "${node}" --remove-all-storage --nvram
175 function prepare_vms {
176 local base_image=$1; shift
177 local image_dir=$1; shift
178 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
180 local image=base_image_opnfv_fuel.img
184 get_base_image "${base_image}" "${image_dir}"
186 rm -f "${image_dir}/${image%.*}"*
187 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
188 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
189 cp "${image_dir}/${base_image/*\/}" "${image_dir}/${image}"
190 mount_image "${image}" "${image_dir}"
191 apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
194 ln -sf "${image_dir}/${base_image/*\/}" "${image_dir}/${image}"
197 # CWD should be <mcp/scripts>
198 # shellcheck disable=SC2016
199 envsubst '${SALT_MASTER},${CLUSTER_DOMAIN}' < \
200 user-data.template > user-data.sh
202 # Create config ISO and resize OS disk image for each foundation node VM
203 for node in "${vnodes[@]}"; do
204 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" -u user-data.sh \
205 -h "${node}" "${image_dir}/mcp_${node}.iso"
206 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
207 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
210 # VCP VMs base image specific changes
211 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
212 mount_image "${image}" "${image_dir}"
213 apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
215 ln -sf "${image_dir}/${image}" "${image_dir}/${image%.*}_vcp.img"
219 function create_networks {
220 local vnode_networks=("$@")
221 # create required networks, including constant "mcpcontrol"
222 # FIXME(alav): since we renamed "pxe" to "mcpcontrol", we need to make sure
223 # we delete the old "pxe" virtual network, or it would cause IP conflicts.
224 for net in "pxe" "mcpcontrol" "${vnode_networks[@]}"; do
225 if virsh net-info "${net}" >/dev/null 2>&1; then
226 virsh net-destroy "${net}" || true
227 virsh net-undefine "${net}"
229 # in case of custom network, host should already have the bridge in place
230 if [ -f "net_${net}.xml" ] && [ ! -d "/sys/class/net/${net}/bridge" ]; then
231 virsh net-define "net_${net}.xml"
232 virsh net-autostart "${net}"
233 virsh net-start "${net}"
238 function create_vms {
239 local image_dir=$1; shift
240 # vnode data should be serialized with the following format:
241 # '<name0>,<ram0>,<vcpu0>|<name1>,<ram1>,<vcpu1>[...]'
242 IFS='|' read -r -a vnodes <<< "$1"; shift
243 local vnode_networks=("$@")
245 # AArch64: prepare arch specific arguments
246 local virt_extra_args=""
247 if [ "$(uname -i)" = "aarch64" ]; then
248 # No Cirrus VGA on AArch64, use virtio instead
249 virt_extra_args="$virt_extra_args --video=virtio"
252 # create vms with specified options
253 for serialized_vnode_data in "${vnodes[@]}"; do
254 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
256 # prepare network args
257 net_args=" --network network=mcpcontrol,model=virtio"
258 if [ "${DEPLOY_TYPE:-}" = 'baremetal' ]; then
259 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
260 vnode_networks[2]="${vnode_networks[0]}"
262 for net in "${vnode_networks[@]:1}"; do
263 net_args="${net_args} --network bridge=${net},model=virtio"
266 # shellcheck disable=SC2086
267 virt-install --name "${vnode_data[0]}" \
268 --ram "${vnode_data[1]}" --vcpus "${vnode_data[2]}" \
269 --cpu host-passthrough --accelerate ${net_args} \
270 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
271 --os-type linux --os-variant none \
272 --boot hd --vnc --console pty --autostart --noreboot \
273 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
279 function update_mcpcontrol_network {
280 # set static ip address for salt master node, MaaS node
281 local cmac=$(virsh domiflist cfg01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
282 local amac=$(virsh domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
283 virsh net-update "mcpcontrol" add ip-dhcp-host \
284 "<host mac='${cmac}' name='cfg01' ip='${SALT_MASTER}'/>" --live --config
285 [ -z "${amac}" ] || virsh net-update "mcpcontrol" add ip-dhcp-host \
286 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
293 for node in "${vnodes[@]}"; do
294 virsh start "${node}"
295 sleep $((RANDOM%5+1))
299 function check_connection {
300 local total_attempts=60
304 echo '[INFO] Attempting to get into Salt master ...'
306 # wait until ssh on Salt master is available
307 # shellcheck disable=SC2034
308 for attempt in $(seq "${total_attempts}"); do
309 # shellcheck disable=SC2086
310 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
312 0) echo "${attempt}> Success"; break ;;
313 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
320 function parse_yaml {
327 fs="$(echo @|tr @ '\034')"
328 sed -e 's|---||g' -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
329 -e "s|^\($s\)\($w\)$s[:-]$s\(.*\)$s\$|\1$fs\2$fs\3|p" "$1" |
331 indent = length($1)/2;
333 for (i in vname) {if (i > indent) {delete vname[i]}}
334 if (length($3) > 0) {
335 vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
336 printf("%s%s%s=(\"%s\")\n", "'"$prefix"'",vn, $2, $3);
342 # Execute in a subshell to prevent local variable override during recursion
344 local total_attempts=$1; shift
347 echo "[NOTE] Waiting for cmd to return success: ${cmdstr}"
348 # shellcheck disable=SC2034
349 for attempt in $(seq "${total_attempts}"); do
350 # shellcheck disable=SC2015
351 eval "${cmdstr}" && return 0 || true
352 echo -n '.'; sleep "${sleep_time}"