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 used by deploy script on jumpserver:
12 # - base cloud image (used by FN VMs and VCP VMs) processing:
14 # * tooling for offline image modification (without libguestfs);
15 # * package pre-installation (requires nbd, loop krn mods);
16 # - virtualized hosts processing:
17 # * virsh-managed VMs boilerplate;
18 # * salt master container tooling;
19 # * virsh & docker network plumbing;
22 ##############################################################################
23 # private helper functions
24 ##############################################################################
26 function __get_base_image {
30 mkdir -p "${image_dir}"
31 wget --progress=dot:giga -P "${image_dir}" -N "${base_image}"
34 function __kernel_modules {
35 # Load mandatory kernel modules: loop, nbd
37 test -e /dev/loop-control || sudo modprobe loop
38 if sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8; then
41 if [ -e /dev/nbd0 ]; then return 0; fi # nbd might be inbuilt
42 # CentOS (or RHEL family in general) do not provide 'nbd' out of the box
43 echo "[WARN] 'nbd' kernel module cannot be loaded!"
44 if [ ! -e /etc/redhat-release ]; then
45 echo "[ERROR] Non-RHEL system detected, aborting!"
46 echo "[ERROR] Try building 'nbd' manually or install it from a 3rd party."
50 # Best-effort attempt at building a non-maintaned kernel module
53 local __uname_r=$(uname -r)
54 local __uname_m=$(uname -m)
55 if [ "${__uname_m}" = 'x86_64' ]; then
56 __baseurl='http://vault.centos.org/centos'
57 __subdir='Source/SPackages'
58 __srpm="kernel-${__uname_r%.${__uname_m}}.src.rpm"
60 __baseurl='http://vault.centos.org/altarch'
61 __subdir="Source/${__uname_m}/Source/SPackages"
62 # NOTE: fmt varies across releases (e.g. kernel-alt-4.11.0-44.el7a.src.rpm)
63 __srpm="kernel-alt-${__uname_r%.${__uname_m}}.src.rpm"
67 local __versions=$(curl -s "${__baseurl}/" | grep -Po 'href="\K7\.[\d\.]+')
68 for ver in ${__versions}; do
69 for comp in os updates; do
70 local url="${__baseurl}/${ver}/${comp}/${__subdir}/${__srpm}"
71 if wget "${url}" -O "${image_dir}/${__srpm}" > /dev/null 2>&1; then
77 if [ "${__found}" = 'n' ]; then
78 echo "[ERROR] Can't find the linux kernel SRPM for: ${__uname_r}"
79 echo "[ERROR] 'nbd' module cannot be built, aborting!"
80 echo "[ERROR] Try 'yum upgrade' or building 'nbd' krn module manually ..."
84 rpm -ivh "${image_dir}/${__srpm}" 2> /dev/null
85 mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
86 # shellcheck disable=SC2016
87 echo '%_topdir %(echo $HOME)/rpmbuild' > ~/.rpmmacros
90 rpmbuild -bp --nodeps --target="${__uname_m}" kernel*.spec
91 cd ~/rpmbuild/BUILD/"${__srpm%.src.rpm}"/linux-*
92 sed -i 's/^.*\(CONFIG_BLK_DEV_NBD\).*$/\1=m/g' .config
93 # http://centosfaq.org/centos/nbd-does-not-compile-for-3100-514262el7x86_64
94 if grep -Rq 'REQ_TYPE_DRV_PRIV' drivers/block; then
95 sed -i 's/REQ_TYPE_SPECIAL/REQ_TYPE_DRV_PRIV/g' drivers/block/nbd.c
97 gunzip -c "/boot/symvers-${__uname_r}.gz" > Module.symvers
98 make prepare modules_prepare
99 make M=drivers/block -j
100 modinfo drivers/block/nbd.ko
101 sudo mkdir -p "/lib/modules/${__uname_r}/extra/"
102 sudo cp drivers/block/nbd.ko "/lib/modules/${__uname_r}/extra/"
105 sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8
108 function __mount_image {
111 OPNFV_MNT_DIR="${image_dir}/ubuntu"
113 # Find free nbd, loop devices
114 for dev in '/sys/class/block/nbd'*; do
115 if [ "$(cat "${dev}/size")" = '0' ]; then
116 OPNFV_NBD_DEV=/dev/$(basename "${dev}")
120 OPNFV_LOOP_DEV=$(sudo losetup -f)
121 OPNFV_MAP_DEV=/dev/mapper/$(basename "${OPNFV_NBD_DEV}")p1
122 export OPNFV_MNT_DIR OPNFV_LOOP_DEV
123 [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
124 qemu-img resize "${image_dir}/${image}" 3G
125 sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
126 "${image_dir}/${image}"
127 sudo kpartx -av "${OPNFV_NBD_DEV}"
128 sleep 5 # /dev/nbdNp1 takes some time to come up
129 # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
130 if sudo growpart "${OPNFV_NBD_DEV}" 1; then
131 sudo kpartx -u "${OPNFV_NBD_DEV}"
132 sudo e2fsck -pf "${OPNFV_MAP_DEV}"
133 sudo resize2fs "${OPNFV_MAP_DEV}"
135 # grub-update does not like /dev/nbd*, so use a loop device to work around it
136 sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_MAP_DEV}"
137 mkdir -p "${OPNFV_MNT_DIR}"
138 sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
139 sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
140 sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
141 sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
142 sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
143 sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
144 echo "GRUB_DISABLE_OS_PROBER=true" | \
145 sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
146 sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
147 "${OPNFV_MNT_DIR}/etc/default/grub"
150 function __apt_repos_pkgs_image {
151 local apt_key_urls=(${1//,/ })
152 local all_repos=(${2//,/ })
153 local pkgs_i=(${3//,/ })
154 local pkgs_r=(${4//,/ })
155 [ -n "${OPNFV_MNT_DIR}" ] || exit 1
158 if [ "${#apt_key_urls[@]}" -gt 0 ]; then
159 for apt_key in "${apt_key_urls[@]}"; do
160 sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
161 "wget -qO - '${apt_key}' | apt-key add -"
164 # Additional repositories
165 for repo_line in "${all_repos[@]}"; do
166 # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
167 local repo=(${repo_line//|/ })
168 [ "${#repo[@]}" -gt 5 ] || continue
169 # NOTE: Names and formatting are compatible with Salt linux.system.repo
170 cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
173 Pin: release a=${repo[-2]}
174 Pin-Priority: ${repo[1]}
177 echo "${repo[@]:2}" | sudo tee \
178 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
181 if [ "${#pkgs_i[@]}" -gt 0 ]; then
182 sudo DEBIAN_FRONTEND="noninteractive" \
183 chroot "${OPNFV_MNT_DIR}" apt-get update
184 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
185 chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
188 if [ "${#pkgs_r[@]}" -gt 0 ]; then
189 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
190 chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
192 # Disable cloud-init metadata service datasource
193 sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
194 echo "datasource_list: [ NoCloud, None ]" | sudo tee \
195 "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
198 function __cleanup_vms {
199 # clean up existing nodes
200 for node in $(${VIRSH} list --name | grep -P '\w{3}\d{2}'); do
201 ${VIRSH} destroy "${node}"
203 for node in $(${VIRSH} list --name --all | grep -P '\w{3}\d{2}'); do
204 ${VIRSH} domblklist "${node}" | awk '/^.da/ {print $2}' | \
205 xargs --no-run-if-empty -I{} sudo rm -f {}
206 ${VIRSH} undefine "${node}" --remove-all-storage --nvram || \
207 ${VIRSH} undefine "${node}" --remove-all-storage
211 ##############################################################################
213 ##############################################################################
215 function prepare_vms {
216 local base_image=$1; shift
217 local image_dir=$1; shift
218 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
220 local image=base_image_opnfv_fuel.img
221 local vcp_image=${image%.*}_vcp.img
222 local _o=${base_image/*\/}
223 local _h=$(echo "${repos_pkgs_str}.$(md5sum "${image_dir}/${_o}")" | \
226 [ -n "${image_dir}" ] || exit 1
230 __get_base_image "${base_image}" "${image_dir}"
231 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
233 echo "[INFO] Lookup cache / build patched base image for fingerprint: ${_h}"
234 _tmp="${image%.*}.${_h}.img"
235 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${image}" ]; then
236 echo "[INFO] Patched base image found"
238 # shellcheck disable=SC2115
239 rm -rf "${image_dir}/${image%.*}"*
240 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
241 echo "[INFO] Patching base image ..."
242 cp "${image_dir}/${_o}" "${image_dir}/${_tmp}"
243 __kernel_modules "${image_dir}"
244 __mount_image "${_tmp}" "${image_dir}"
245 __apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
248 echo "[INFO] No patching required, using vanilla base image"
249 ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
251 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
254 # Create config ISO and resize OS disk image for each foundation node VM
255 for node in "${vnodes[@]}"; do
256 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" \
257 -u 'user-data.sh' -h "${node}" "${image_dir}/mcp_${node}.iso"
258 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
259 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
260 # Prepare dedicated drive for cinder on cmp nodes
261 if [[ "${node}" =~ ^(cmp) ]]; then
262 qemu-img create "${image_dir}/mcp_${node}_storage.qcow2" 100G
266 # VCP VMs base image specific changes
267 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
268 echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
269 _tmp="${vcp_image%.*}.${_h}.img"
270 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
271 echo "[INFO] Patched VCP image found"
273 echo "[INFO] Patching VCP image ..."
274 cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
275 __kernel_modules "${image_dir}"
276 __mount_image "${_tmp}" "${image_dir}"
277 __apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
279 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
284 function create_networks {
285 local all_vnode_networks=("mcpcontrol" "$@")
286 # create required networks, including constant "mcpcontrol"
287 for net in "${all_vnode_networks[@]}"; do
288 if ${VIRSH} net-info "${net}" >/dev/null 2>&1; then
289 ${VIRSH} net-destroy "${net}" || true
290 ${VIRSH} net-undefine "${net}"
292 # in case of custom network, host should already have the bridge in place
293 if [ -f "virsh_net/net_${net}.xml" ] && \
294 [ ! -d "/sys/class/net/${net}/bridge" ]; then
295 ${VIRSH} net-define "virsh_net/net_${net}.xml"
296 ${VIRSH} net-autostart "${net}"
297 ${VIRSH} net-start "${net}"
300 # create veth pairs for relevant networks (mcpcontrol, pxebr, mgmt)
301 for i in $(seq 0 2 4); do
302 sudo ip link del "veth_mcp$i" || true
303 sudo ip link add "veth_mcp$i" type veth peer name "veth_mcp$((i+1))"
304 sudo ip link set "veth_mcp$i" up mtu 9000
305 sudo ip link set "veth_mcp$((i+1))" up mtu 9000
306 sudo brctl addif "${all_vnode_networks[$((i/2))]}" "veth_mcp$i"
310 function create_vms {
311 local image_dir=$1; shift
312 # vnode data should be serialized with the following format:
313 # <name0>,<ram0>,<vcpu0>[,<sockets0>,<cores0>,<threads0>[,<cell0name0>,<cell0memory0>,
314 # <cell0cpus0>,<cell1name0>,<cell1memory0>,<cell1cpus0>]]|<name1>,...'
315 IFS='|' read -r -a vnodes <<< "$1"; shift
317 # AArch64: prepare arch specific arguments
318 local virt_extra_args=""
319 if [ "$(uname -i)" = "aarch64" ]; then
320 # No Cirrus VGA on AArch64, use virtio instead
321 virt_extra_args="$virt_extra_args --video=virtio"
324 # create vms with specified options
325 for serialized_vnode_data in "${vnodes[@]}"; do
326 if [ -z "${serialized_vnode_data}" ]; then continue; fi
327 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
329 # prepare VM CPU model, count, topology (optional), NUMA cells (optional, requires topo)
330 local virt_cpu_args=' --cpu host-passthrough'
331 local idx=6 # cell0.name index in serialized data
332 while [ -n "${vnode_data[${idx}]}" ]; do
333 virt_cpu_args+=",${vnode_data[${idx}]}.memory=${vnode_data[$((idx + 1))]}"
334 virt_cpu_args+=",${vnode_data[${idx}]}.cpus=${vnode_data[$((idx + 2))]}"
337 virt_cpu_args+=" --vcpus vcpus=${vnode_data[2]}"
338 if [ -n "${vnode_data[5]}" ]; then
339 virt_cpu_args+=",sockets=${vnode_data[3]},cores=${vnode_data[4]},threads=${vnode_data[5]}"
342 # prepare network args
343 local vnode_networks=("$@")
344 if [[ "${vnode_data[0]}" =~ ^(cfg01|mas01) ]]; then
345 net_args=" --network network=mcpcontrol,model=virtio"
346 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
347 vnode_networks[2]="${vnode_networks[0]}"
349 net_args=" --network bridge=${vnode_networks[0]},model=virtio"
351 for net in "${vnode_networks[@]:1}"; do
352 net_args="${net_args} --network bridge=${net},model=virtio"
355 # dedicated storage drive for cinder on cmp nodes
357 if [[ "${vnode_data[0]}" =~ ^(cmp) ]]; then
358 virt_extra_storage="--disk path=${image_dir}/mcp_${vnode_data[0]}_storage.qcow2,format=qcow2,bus=virtio,cache=none,io=native"
361 [ ! -e "${image_dir}/virt-manager" ] || VIRT_PREFIX="${image_dir}/virt-manager/"
362 # shellcheck disable=SC2086
363 ${VIRT_PREFIX}${VIRSH/virsh/virt-install} --name "${vnode_data[0]}" \
364 ${virt_cpu_args} --accelerate \
366 --ram "${vnode_data[1]}" \
367 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
368 ${virt_extra_storage} \
369 --os-type linux --os-variant none \
370 --boot hd --vnc --console pty --autostart --noreboot \
371 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
377 function update_mcpcontrol_network {
378 # set static ip address for salt master node, MaaS node
379 local amac=$(${VIRSH} domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
380 [ -z "${amac}" ] || ${VIRSH} net-update "mcpcontrol" add ip-dhcp-host \
381 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
386 local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
388 # reset non-infrastructure vms, wait for them to come back online
389 for node in "${vnodes[@]}"; do
390 if [[ ! "${node}" =~ (cfg01|mas01) ]]; then
391 ${VIRSH} reset "${node}"
394 for node in "${vnodes[@]}"; do
395 if [[ ! "${node}" =~ (cfg01|mas01) ]]; then
396 wait_for 20.0 "${cmd_str} sudo salt -C '${node}*' saltutil.sync_all"
405 for node in "${vnodes[@]}"; do
406 ${VIRSH} start "${node}"
407 sleep $((RANDOM%5+1))
411 function prepare_containers {
413 [ -n "${image_dir}" ] || exit 1
414 [ -n "${MCP_REPO_ROOT_PATH}" ] || exit 1
415 [ ! -e "${image_dir}/docker-compose" ] || COMPOSE_PREFIX="${image_dir}/"
417 "${COMPOSE_PREFIX}docker-compose" -f docker-compose/docker-compose.yaml down
418 if [[ ! "${MCP_DOCKER_TAG}" =~ 'verify' ]]; then
419 "${COMPOSE_PREFIX}docker-compose" -f docker-compose/docker-compose.yaml pull
421 sudo rm -rf "${image_dir}/"{salt,hosts,pki} "${image_dir}/nodes/"*
422 mkdir -p "${image_dir}/salt/"{master.d,minion.d}
423 touch "${image_dir}/hosts"
426 function start_containers {
428 [ -n "${image_dir}" ] || exit 1
429 [ ! -e "${image_dir}/docker-compose" ] || COMPOSE_PREFIX="${image_dir}/"
430 "${COMPOSE_PREFIX}docker-compose" -f docker-compose/docker-compose.yaml up -d
433 function check_connection {
434 local total_attempts=60
438 echo '[INFO] Attempting to get into Salt master ...'
440 # wait until ssh on Salt master is available
441 # shellcheck disable=SC2034
442 for attempt in $(seq "${total_attempts}"); do
443 # shellcheck disable=SC2086
444 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
446 0) echo "${attempt}> Success"; break ;;
447 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
454 function cleanup_mounts {
455 # Remove any mounts, loop and/or nbd devs created while patching base image
456 if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
457 if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
458 # Grub thinks it's running from a live CD
459 sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
460 "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
462 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
464 if mountpoint -q "${OPNFV_MNT_DIR}"; then
465 sudo umount -l "${OPNFV_MNT_DIR}" || true
468 if [ -n "${OPNFV_LOOP_DEV}" ] && \
469 sudo losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
470 sudo losetup -d "${OPNFV_LOOP_DEV}"
472 if [ -n "${OPNFV_NBD_DEV}" ]; then
473 sudo kpartx -d "${OPNFV_NBD_DEV}" || true
474 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true