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
51 local __baseurl='http://vault.centos.org/centos'
52 local __subdir='Source/SPackages'
53 local __uname_r=$(uname -r)
54 local __uname_m=$(uname -m)
55 if [ "${__uname_m}" = 'x86_64' ]; then
56 __srpm="kernel-${__uname_r%.${__uname_m}}.src.rpm"
58 # NOTE: fmt varies across releases (e.g. kernel-alt-4.11.0-44.el7a.src.rpm)
59 __srpm="kernel-alt-${__uname_r%.${__uname_m}}.src.rpm"
63 local __versions=$(curl -s "${__baseurl}/" | grep -Po 'href="\K7\.[\d\.]+')
64 for ver in ${__versions}; do
65 for comp in os updates; do
66 local url="${__baseurl}/${ver}/${comp}/${__subdir}/${__srpm}"
67 if wget "${url}" -O "${image_dir}/${__srpm}" > /dev/null 2>&1; then
73 if [ "${__found}" = 'n' ]; then
74 echo "[ERROR] Can't find the linux kernel SRPM for: ${__uname_r}"
75 echo "[ERROR] 'nbd' module cannot be built, aborting!"
76 echo "[ERROR] Try 'yum upgrade' or building 'nbd' krn module manually ..."
80 rpm -ivh "${image_dir}/${__srpm}" 2> /dev/null
81 mkdir -p ~/rpmbuild/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
82 # shellcheck disable=SC2016
83 echo '%_topdir %(echo $HOME)/rpmbuild' > ~/.rpmmacros
86 rpmbuild -bp --nodeps --target="${__uname_m}" kernel*.spec
87 cd ~/rpmbuild/BUILD/"${__srpm%.src.rpm}"/linux-*
88 sed -i 's/^.*\(CONFIG_BLK_DEV_NBD\).*$/\1=m/g' .config
89 # http://centosfaq.org/centos/nbd-does-not-compile-for-3100-514262el7x86_64
90 if grep -Rq 'REQ_TYPE_DRV_PRIV' drivers/block; then
91 sed -i 's/REQ_TYPE_SPECIAL/REQ_TYPE_DRV_PRIV/g' drivers/block/nbd.c
93 gunzip -c "/boot/symvers-${__uname_r}.gz" > Module.symvers
94 make prepare modules_prepare
95 make M=drivers/block -j
96 modinfo drivers/block/nbd.ko
97 sudo mkdir -p "/lib/modules/${__uname_r}/extra/"
98 sudo cp drivers/block/nbd.ko "/lib/modules/${__uname_r}/extra/"
101 sudo modprobe nbd max_part=8 || sudo modprobe -f nbd max_part=8
104 function __mount_image {
107 OPNFV_MNT_DIR="${image_dir}/ubuntu"
109 # Find free nbd, loop devices
110 for dev in '/sys/class/block/nbd'*; do
111 if [ "$(cat "${dev}/size")" = '0' ]; then
112 OPNFV_NBD_DEV=/dev/$(basename "${dev}")
116 OPNFV_LOOP_DEV=$(sudo losetup -f)
117 OPNFV_MAP_DEV=/dev/mapper/$(basename "${OPNFV_NBD_DEV}")p1
118 export OPNFV_MNT_DIR OPNFV_LOOP_DEV
119 [ -n "${OPNFV_NBD_DEV}" ] && [ -n "${OPNFV_LOOP_DEV}" ] || exit 1
120 qemu-img resize "${image_dir}/${image}" 3G
121 sudo qemu-nbd --connect="${OPNFV_NBD_DEV}" --aio=native --cache=none \
122 "${image_dir}/${image}"
123 sudo kpartx -av "${OPNFV_NBD_DEV}"
124 sleep 5 # /dev/nbdNp1 takes some time to come up
125 # Hardcode partition index to 1, unlikely to change for Ubuntu UCA image
126 if sudo growpart "${OPNFV_NBD_DEV}" 1; then
127 sudo kpartx -u "${OPNFV_NBD_DEV}"
128 sudo e2fsck -pf "${OPNFV_MAP_DEV}"
129 sudo resize2fs "${OPNFV_MAP_DEV}"
131 # grub-update does not like /dev/nbd*, so use a loop device to work around it
132 sudo losetup "${OPNFV_LOOP_DEV}" "${OPNFV_MAP_DEV}"
133 mkdir -p "${OPNFV_MNT_DIR}"
134 sudo mount "${OPNFV_LOOP_DEV}" "${OPNFV_MNT_DIR}"
135 sudo mount -t proc proc "${OPNFV_MNT_DIR}/proc"
136 sudo mount -t sysfs sys "${OPNFV_MNT_DIR}/sys"
137 sudo mount -o bind /dev "${OPNFV_MNT_DIR}/dev"
138 sudo mkdir -p "${OPNFV_MNT_DIR}/run/resolvconf"
139 sudo cp /etc/resolv.conf "${OPNFV_MNT_DIR}/run/resolvconf"
140 echo "GRUB_DISABLE_OS_PROBER=true" | \
141 sudo tee -a "${OPNFV_MNT_DIR}/etc/default/grub"
142 sudo sed -i -e 's/^\(GRUB_TIMEOUT\)=.*$/\1=1/g' -e 's/^GRUB_HIDDEN.*$//g' \
143 "${OPNFV_MNT_DIR}/etc/default/grub"
146 function __apt_repos_pkgs_image {
147 local apt_key_urls=(${1//,/ })
148 local all_repos=(${2//,/ })
149 local pkgs_i=(${3//,/ })
150 local pkgs_r=(${4//,/ })
151 [ -n "${OPNFV_MNT_DIR}" ] || exit 1
154 if [ "${#apt_key_urls[@]}" -gt 0 ]; then
155 for apt_key in "${apt_key_urls[@]}"; do
156 sudo chroot "${OPNFV_MNT_DIR}" /bin/bash -c \
157 "wget -qO - '${apt_key}' | apt-key add -"
160 # Additional repositories
161 for repo_line in "${all_repos[@]}"; do
162 # <repo_name>|<repo prio>|deb|[arch=<arch>]|<repo url>|<dist>|<repo comp>
163 local repo=(${repo_line//|/ })
164 [ "${#repo[@]}" -gt 5 ] || continue
165 # NOTE: Names and formatting are compatible with Salt linux.system.repo
166 cat <<-EOF | sudo tee "${OPNFV_MNT_DIR}/etc/apt/preferences.d/${repo[0]}"
169 Pin: release a=${repo[-2]}
170 Pin-Priority: ${repo[1]}
173 echo "${repo[@]:2}" | sudo tee \
174 "${OPNFV_MNT_DIR}/etc/apt/sources.list.d/${repo[0]}.list"
177 if [ "${#pkgs_i[@]}" -gt 0 ]; then
178 sudo DEBIAN_FRONTEND="noninteractive" \
179 chroot "${OPNFV_MNT_DIR}" apt-get update
180 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
181 chroot "${OPNFV_MNT_DIR}" apt-get install -y "${pkgs_i[@]}"
184 if [ "${#pkgs_r[@]}" -gt 0 ]; then
185 sudo DEBIAN_FRONTEND="noninteractive" FLASH_KERNEL_SKIP="true" \
186 chroot "${OPNFV_MNT_DIR}" apt-get purge -y "${pkgs_r[@]}"
188 # Disable cloud-init metadata service datasource
189 sudo mkdir -p "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d"
190 echo "datasource_list: [ NoCloud, None ]" | sudo tee \
191 "${OPNFV_MNT_DIR}/etc/cloud/cloud.cfg.d/95_real_datasources.cfg"
194 function __cleanup_vms {
195 # clean up existing nodes
196 for node in $(${VIRSH} list --name | grep -P '\w{3}\d{2}'); do
197 ${VIRSH} destroy "${node}"
199 for node in $(${VIRSH} list --name --all | grep -P '\w{3}\d{2}'); do
200 ${VIRSH} domblklist "${node}" | awk '/^.da/ {print $2}' | \
201 xargs --no-run-if-empty -I{} sudo rm -f {}
202 ${VIRSH} undefine "${node}" --remove-all-storage --nvram || \
203 ${VIRSH} undefine "${node}" --remove-all-storage
207 ##############################################################################
209 ##############################################################################
211 function prepare_vms {
212 local base_image=$1; shift
213 local image_dir=$1; shift
214 local repos_pkgs_str=$1; shift # ^-sep list of repos, pkgs to install/rm
216 local image=base_image_opnfv_fuel.img
217 local vcp_image=${image%.*}_vcp.img
218 local _o=${base_image/*\/}
219 local _h=$(echo "${repos_pkgs_str}.$(md5sum "${image_dir}/${_o}")" | \
222 [ -n "${image_dir}" ] || exit 1
226 __get_base_image "${base_image}" "${image_dir}"
227 IFS='^' read -r -a repos_pkgs <<< "${repos_pkgs_str}"
229 echo "[INFO] Lookup cache / build patched base image for fingerprint: ${_h}"
230 _tmp="${image%.*}.${_h}.img"
231 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${image}" ]; then
232 echo "[INFO] Patched base image found"
234 # shellcheck disable=SC2115
235 rm -rf "${image_dir}/${image%.*}"*
236 if [[ ! "${repos_pkgs_str}" =~ ^\^+$ ]]; then
237 echo "[INFO] Patching base image ..."
238 cp "${image_dir}/${_o}" "${image_dir}/${_tmp}"
239 __kernel_modules "${image_dir}"
240 __mount_image "${_tmp}" "${image_dir}"
241 __apt_repos_pkgs_image "${repos_pkgs[@]:0:4}"
244 echo "[INFO] No patching required, using vanilla base image"
245 ln -sf "${image_dir}/${_o}" "${image_dir}/${_tmp}"
247 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${image}"
250 # Create config ISO and resize OS disk image for each foundation node VM
251 for node in "${vnodes[@]}"; do
252 ./create-config-drive.sh -k "$(basename "${SSH_KEY}").pub" \
253 -u 'user-data.sh' -h "${node}" "${image_dir}/mcp_${node}.iso"
254 cp "${image_dir}/${image}" "${image_dir}/mcp_${node}.qcow2"
255 qemu-img resize "${image_dir}/mcp_${node}.qcow2" 100G
256 # Prepare dedicated drive for cinder on cmp nodes
257 if [[ "${node}" =~ ^(cmp) ]]; then
258 qemu-img create "${image_dir}/mcp_${node}_storage.qcow2" 100G
262 # VCP VMs base image specific changes
263 if [[ ! "${repos_pkgs_str}" =~ \^{3}$ ]] && [ -n "${repos_pkgs[*]:4}" ]; then
264 echo "[INFO] Lookup cache / build patched VCP image for md5sum: ${_h}"
265 _tmp="${vcp_image%.*}.${_h}.img"
266 if [ "${image_dir}/${_tmp}" -ef "${image_dir}/${vcp_image}" ]; then
267 echo "[INFO] Patched VCP image found"
269 echo "[INFO] Patching VCP image ..."
270 cp "${image_dir}/${image}" "${image_dir}/${_tmp}"
271 __kernel_modules "${image_dir}"
272 __mount_image "${_tmp}" "${image_dir}"
273 __apt_repos_pkgs_image "${repos_pkgs[@]:4:4}"
275 ln -sf "${image_dir}/${_tmp}" "${image_dir}/${vcp_image}"
280 function create_networks {
281 local all_vnode_networks=("mcpcontrol" "$@")
282 # create required networks, including constant "mcpcontrol"
283 for net in "${all_vnode_networks[@]}"; do
284 if ${VIRSH} net-info "${net}" >/dev/null 2>&1; then
285 ${VIRSH} net-destroy "${net}" || true
286 ${VIRSH} net-undefine "${net}"
288 # in case of custom network, host should already have the bridge in place
289 if [ -f "virsh_net/net_${net}.xml" ] && \
290 [ ! -d "/sys/class/net/${net}/bridge" ]; then
291 ${VIRSH} net-define "virsh_net/net_${net}.xml"
292 ${VIRSH} net-autostart "${net}"
293 ${VIRSH} net-start "${net}"
296 # create veth pairs for relevant networks (mcpcontrol, pxebr, mgmt)
297 for i in $(seq 0 2 4); do
298 sudo ip link del "veth_mcp$i" || true
299 sudo ip link add "veth_mcp$i" type veth peer name "veth_mcp$((i+1))"
300 sudo ip link set "veth_mcp$i" up mtu 9000
301 sudo ip link set "veth_mcp$((i+1))" up mtu 9000
302 sudo brctl addif "${all_vnode_networks[$((i/2))]}" "veth_mcp$i"
306 function create_vms {
307 local image_dir=$1; shift
308 # vnode data should be serialized with the following format:
309 # <name0>,<ram0>,<vcpu0>[,<sockets0>,<cores0>,<threads0>[,<cell0name0>,<cell0memory0>,
310 # <cell0cpus0>,<cell1name0>,<cell1memory0>,<cell1cpus0>]]|<name1>,...'
311 IFS='|' read -r -a vnodes <<< "$1"; shift
313 # AArch64: prepare arch specific arguments
314 local virt_extra_args=""
315 if [ "$(uname -i)" = "aarch64" ]; then
316 # No Cirrus VGA on AArch64, use virtio instead
317 virt_extra_args="$virt_extra_args --video=virtio"
320 # create vms with specified options
321 for serialized_vnode_data in "${vnodes[@]}"; do
322 if [ -z "${serialized_vnode_data}" ]; then continue; fi
323 IFS=',' read -r -a vnode_data <<< "${serialized_vnode_data}"
325 # prepare VM CPU model, count, topology (optional), NUMA cells (optional, requires topo)
326 local virt_cpu_args=' --cpu host-passthrough'
327 local idx=6 # cell0.name index in serialized data
328 while [ -n "${vnode_data[${idx}]}" ]; do
329 virt_cpu_args+=",${vnode_data[${idx}]}.memory=${vnode_data[$((idx + 1))]}"
330 virt_cpu_args+=",${vnode_data[${idx}]}.cpus=${vnode_data[$((idx + 2))]}"
333 virt_cpu_args+=" --vcpus vcpus=${vnode_data[2]}"
334 if [ -n "${vnode_data[5]}" ]; then
335 virt_cpu_args+=",sockets=${vnode_data[3]},cores=${vnode_data[4]},threads=${vnode_data[5]}"
338 # prepare network args
339 local vnode_networks=("$@")
340 if [[ "${vnode_data[0]}" =~ ^(cfg01|mas01) ]]; then
341 net_args=" --network network=mcpcontrol,model=virtio"
342 # 3rd interface gets connected to PXE/Admin Bridge (cfg01, mas01)
343 vnode_networks[2]="${vnode_networks[0]}"
345 net_args=" --network bridge=${vnode_networks[0]},model=virtio"
347 for net in "${vnode_networks[@]:1}"; do
348 net_args="${net_args} --network bridge=${net},model=virtio"
351 # dedicated storage drive for cinder on cmp nodes
353 if [[ "${vnode_data[0]}" =~ ^(cmp) ]]; then
354 virt_extra_storage="--disk path=${image_dir}/mcp_${vnode_data[0]}_storage.qcow2,format=qcow2,bus=virtio,cache=none,io=native"
357 [ ! -e "${image_dir}/virt-manager" ] || VIRT_PREFIX="${image_dir}/virt-manager/"
358 # shellcheck disable=SC2086
359 ${VIRT_PREFIX}${VIRSH/virsh/virt-install} --name "${vnode_data[0]}" \
360 ${virt_cpu_args} --accelerate \
362 --ram "${vnode_data[1]}" \
363 --disk path="${image_dir}/mcp_${vnode_data[0]}.qcow2",format=qcow2,bus=virtio,cache=none,io=native \
364 ${virt_extra_storage} \
365 --os-type linux --os-variant none \
366 --boot hd --vnc --console pty --autostart --noreboot \
367 --disk path="${image_dir}/mcp_${vnode_data[0]}.iso",device=cdrom \
373 function update_mcpcontrol_network {
374 # set static ip address for salt master node, MaaS node
375 local amac=$(${VIRSH} domiflist mas01 2>&1| awk '/mcpcontrol/ {print $5; exit}')
376 [ -z "${amac}" ] || ${VIRSH} net-update "mcpcontrol" add ip-dhcp-host \
377 "<host mac='${amac}' name='mas01' ip='${MAAS_IP}'/>" --live --config
382 local cmd_str="ssh ${SSH_OPTS} ${SSH_SALT}"
384 # reset non-infrastructure vms, wait for them to come back online
385 for node in "${vnodes[@]}"; do
386 if [[ ! "${node}" =~ (cfg01|mas01) ]]; then
387 ${VIRSH} reset "${node}"
390 for node in "${vnodes[@]}"; do
391 if [[ ! "${node}" =~ (cfg01|mas01) ]]; then
392 wait_for 20.0 "${cmd_str} sudo salt -C '${node}*' saltutil.sync_all"
401 for node in "${vnodes[@]}"; do
402 ${VIRSH} start "${node}"
403 sleep $((RANDOM%5+1))
407 function prepare_containers {
409 [ -n "${image_dir}" ] || exit 1
410 [ -n "${MCP_REPO_ROOT_PATH}" ] || exit 1
411 [ ! -e "${image_dir}/docker-compose" ] || COMPOSE_PREFIX="${image_dir}/"
413 "${COMPOSE_PREFIX}docker-compose" -f docker-compose/docker-compose.yaml down
414 if [[ ! "${MCP_DOCKER_TAG}" =~ 'verify' ]]; then
415 "${COMPOSE_PREFIX}docker-compose" -f docker-compose/docker-compose.yaml pull
417 sudo rm -rf "${image_dir}/"{salt,hosts,pki} "${image_dir}/nodes/"*
418 mkdir -p "${image_dir}/salt/"{master.d,minion.d}
419 touch "${image_dir}/hosts"
422 function start_containers {
424 [ -n "${image_dir}" ] || exit 1
425 [ ! -e "${image_dir}/docker-compose" ] || COMPOSE_PREFIX="${image_dir}/"
426 "${COMPOSE_PREFIX}docker-compose" -f docker-compose/docker-compose.yaml up -d
429 function check_connection {
430 local total_attempts=60
434 echo '[INFO] Attempting to get into Salt master ...'
436 # wait until ssh on Salt master is available
437 # shellcheck disable=SC2034
438 for attempt in $(seq "${total_attempts}"); do
439 # shellcheck disable=SC2086
440 ssh ${SSH_OPTS} "ubuntu@${SALT_MASTER}" uptime
442 0) echo "${attempt}> Success"; break ;;
443 *) echo "${attempt}/${total_attempts}> ssh server ain't ready yet, waiting for ${sleep_time} seconds ..." ;;
450 function cleanup_mounts {
451 # Remove any mounts, loop and/or nbd devs created while patching base image
452 if [ -n "${OPNFV_MNT_DIR}" ] && [ -d "${OPNFV_MNT_DIR}" ]; then
453 if [ -f "${OPNFV_MNT_DIR}/boot/grub/grub.cfg" ]; then
454 # Grub thinks it's running from a live CD
455 sudo sed -i -e 's/^\s*set root=.*$//g' -e 's/^\s*loopback.*$//g' \
456 "${OPNFV_MNT_DIR}/boot/grub/grub.cfg"
458 sudo rm -f "${OPNFV_MNT_DIR}/run/resolvconf/resolv.conf"
460 if mountpoint -q "${OPNFV_MNT_DIR}"; then
461 sudo umount -l "${OPNFV_MNT_DIR}" || true
464 if [ -n "${OPNFV_LOOP_DEV}" ] && \
465 sudo losetup "${OPNFV_LOOP_DEV}" 1>&2 > /dev/null; then
466 sudo losetup -d "${OPNFV_LOOP_DEV}"
468 if [ -n "${OPNFV_NBD_DEV}" ]; then
469 sudo kpartx -d "${OPNFV_NBD_DEV}" || true
470 sudo qemu-nbd -d "${OPNFV_NBD_DEV}" || true