Debian Codegraph @

tools/run-container

raw symbols SCIP
1 #!/bin/bash
2 # This file is part of cloud-init. See LICENSE file for license information.
3 #
4 # shellcheck disable=2015,2016,2039,2162,2166
5
6 set -u
7
8 VERBOSITY=0
9 KEEP=false
10 CONTAINER=""
11 WAIT_MAX=30
12 LXC=${LXC:-lxc}
13
14 error() { echo "$@" 1>&2; }
15 fail() {
16 [ $# -eq 0 ] || error "$@"
17 exit 1
18 }
19 errorrc() {
20 local r=$?
21 error "$@" "ret=$r"
22 return $r
23 }
24
25 Usage() {
26 cat << EOF
27 Usage: ${0##*/} [ options ] [images:]image-ref
28
29 This utility can makes it easier to run tests, build rpm and source rpm
30 generation inside a LXC of the specified version of CentOS.
31
32 To see images available, run 'lxc image list images:'
33 Example input:
34 rockylinux/9
35 opensuse/15.4
36 debian/10
37
38 options:
39 -a | --artifacts DIR copy build artifacts out to DIR.
40 by default artifacts are not copied out.
41 --dirty apply local changes before running tests.
42 If not provided, a clean checkout of branch is
43 tested. Inside container, changes are in
44 local-changes.diff.
45 -k | --keep keep container after tests
46 -p | --package build a binary package (.deb or .rpm)
47 -s | --source-package build source package (debuild -S or srpm)
48 -u | --unittest run unit tests
49 --vm use a VM instead of a container
50 --wait-max max time to wait or a container or VM to be ready
51 --commitish commit to package and run, default: HEAD
52
53 Example:
54 * ${0##*/} --package --source-package --unittest centos/6
55 EOF
56 }
57
58 bad_Usage() {
59 Usage 1>&2
60 [ $# -eq 0 ] || error "$@"
61 return 1
62 }
63 cleanup() {
64 if [ -n "$CONTAINER" ]; then
65 if [ "$KEEP" = "true" ]; then
66 error "not deleting container '$CONTAINER' due to --keep"
67 else
68 delete_instance "$CONTAINER"
69 fi
70 fi
71 }
72
73 debug() {
74 local level=${1}
75 shift
76 [ "${level}" -gt "${VERBOSITY}" ] && return
77 error "${@}"
78 }
79
80 inside_as() {
81 # inside_as(container_name, user, cmd[, args])
82 # executes cmd with args inside container as user in users home dir.
83 local name="$1" user="$2"
84 shift 2
85 if [ "$user" = "root" ]; then
86 inside "$name" "$@"
87 return
88 fi
89 local stuffed="" b64=""
90 stuffed=$(getopt --shell sh --options "" -- -- "$@")
91 stuffed=${stuffed# -- }
92 b64=$(printf "%s\n" "$stuffed" | base64 --wrap=0)
93 inside "$name" su "$user" -c \
94 'cd; eval set -- "$(echo '"$b64"' | base64 --decode)" && exec "$@"'
95 }
96
97 inside_as_cd() {
98 local name="$1" user="$2" dir="$3"
99 shift 3
100 inside_as "$name" "$user" sh -c 'cd "$0" && exec "$@"' "$dir" "$@"
101 }
102
103 inside() {
104 local name="$1"
105 shift
106 $LXC exec "$name" -- "$@"
107 }
108
109 inject_cloud_init() {
110 # take current cloud-init git dir and put it inside $name at
111 # ~$user/cloud-init.
112 local name="$1" user="$2" dirty="$3"
113 local dname="cloud-init" gitdir="" commitish=""
114 gitdir=$(git rev-parse --git-dir) || {
115 errorrc "Failed to get git dir in $PWD"
116 return
117 }
118 local t=${gitdir%/*}
119 case "$t" in
120 */worktrees)
121 if [ -f "${t%worktrees}/config" ]; then
122 gitdir="${t%worktrees}"
123 fi
124 ;;
125 esac
126
127 # attempt to get branch name.
128 commitish=$(git rev-parse --abbrev-ref "$COMMITISH") || {
129 errorrc "Failed git rev-parse --abbrev-ref $COMMITISH"
130 return
131 }
132 if [ "$commitish" = "HEAD" ]; then
133 # detached head
134 commitish=$(git rev-parse HEAD) || {
135 errorrc "failed git rev-parse HEAD"
136 return
137 }
138 fi
139
140 local local_changes=false
141 if ! git diff --quiet "$commitish"; then
142 # there are local changes not committed.
143 local_changes=true
144 if [ "$dirty" = "false" ]; then
145 error "WARNING: You had uncommitted changes. Those changes will "
146 error "be put into 'local-changes.diff' inside the container. "
147 error "To test these changes you must pass --dirty."
148 fi
149 fi
150
151 debug 1 "collecting ${gitdir} ($dname) into user $user in $name."
152 tar -C "${gitdir}" -cpf - . |
153 inside_as "$name" "$user" sh -ec '
154 dname=$1
155 commitish=$2
156 rm -Rf "$dname"
157 mkdir -p $dname/.git
158 cd $dname/.git
159 tar -xpf -
160 cd ..
161 git config core.bare false
162 out=$(git checkout $commitish 2>&1) ||
163 { echo "failed git checkout $commitish: $out" 1>&2; exit 1; }
164 out=$(git checkout . 2>&1) ||
165 { echo "failed git checkout .: $out" 1>&2; exit 1; }
166 ' extract "$dname" "$commitish"
167 [ "${PIPESTATUS[*]}" = "0 0" ] || {
168 error "Failed to push tarball of '$gitdir' into $name" \
169 " for user $user (dname=$dname)"
170 return 1
171 }
172
173 echo "local_changes=$local_changes dirty=$dirty"
174 if [ "$local_changes" = "true" ]; then
175 git diff "$commitish" |
176 inside_as "$name" "$user" sh -exc '
177 cd "$1"
178 if [ "$2" = "true" ]; then
179 git apply
180 else
181 cat > local-changes.diff
182 fi
183 ' insert_changes "$dname" "$dirty"
184 [ "${PIPESTATUS[*]}" = "0 0" ] || {
185 error "Failed to apply local changes."
186 return 1
187 }
188 fi
189
190 return 0
191 }
192
193 get_os_info_in() {
194 # prep the container (install very basic dependencies)
195 [ -n "${OS_VERSION:-}" -a -n "${OS_NAME:-}" ] && return 0
196 data=$(run_self_inside "$name" os_info) ||
197 {
198 errorrc "Failed to get os-info in container $name"
199 return
200 }
201 eval "$data" && [ -n "${OS_VERSION:-}" -a -n "${OS_NAME:-}" ] || return
202 debug 1 "determined $name is $OS_NAME/$OS_VERSION"
203 }
204
205 os_info() {
206 get_os_info || return
207 echo "OS_NAME=$OS_NAME"
208 echo "OS_VERSION=$OS_VERSION"
209 }
210
211 get_os_info() {
212 # run inside container, set OS_NAME, OS_VERSION
213 # example OS_NAME are centos, debian, opensuse, rockylinux
214 [ -n "${OS_NAME:-}" -a -n "${OS_VERSION:-}" ] && return 0
215 if [ -f /etc/os-release ]; then
216 OS_NAME=$(sh -c '. /etc/os-release; echo $ID')
217 OS_VERSION=$(sh -c '. /etc/os-release; echo $VERSION_ID')
218 if [ -z "$OS_VERSION" ]; then
219 local pname=""
220 pname=$(sh -c '. /etc/os-release; echo $PRETTY_NAME')
221 case "$pname" in
222 *buster*) OS_VERSION=10 ;;
223 *sid*) OS_VERSION="sid" ;;
224 esac
225 fi
226 elif [ -f /etc/centos-release ]; then
227 local line=""
228 read line < /etc/centos-release
229 case "$line" in
230 CentOS\ *\ 6.*)
231 OS_VERSION="6"
232 OS_NAME="centos"
233 ;;
234 esac
235 fi
236 [ -n "${OS_NAME:-}" -a -n "${OS_VERSION:-}" ] ||
237 {
238 error "Unable to determine OS_NAME/OS_VERSION"
239 return 1
240 }
241 }
242
243 yum_install() {
244 local n=0 max=10 ret
245 bcmd="yum install --downloadonly --assumeyes --setopt=keepcache=1"
246 while n=$((n + 1)); do
247 error ":: running $bcmd $* [$n/$max]"
248 $bcmd "$@"
249 ret=$?
250 [ $ret -eq 0 ] && break
251 [ $n -ge $max ] && {
252 error "gave up on $bcmd"
253 exit $ret
254 }
255 nap=$((n * 5))
256 error ":: failed [$ret] ($n/$max). sleeping $nap."
257 sleep $nap
258 done
259 error ":: running yum install --cacheonly --assumeyes $*"
260 yum install --cacheonly --assumeyes "$@"
261 }
262
263 zypper_install() {
264 local pkgs="$*"
265 set -- zypper --non-interactive --gpg-auto-import-keys install \
266 --auto-agree-with-licenses "$@"
267 debug 1 ":: installing $pkgs with zypper: $*"
268 "$@"
269 }
270
271 apt_install() {
272 apt-get update -q && apt-get install --no-install-recommends "$@"
273 }
274
275 install_packages() {
276 get_os_info || return
277 case "$OS_NAME" in
278 centos | rocky* | fedora) yum_install "$@" ;;
279 opensuse*) zypper_install "$@" ;;
280 debian | ubuntu) apt_install "$@" -y ;;
281 *)
282 error "Do not know how to install packages on ${OS_NAME}"
283 return 1
284 ;;
285 esac
286 }
287
288 prep() {
289 # we need some very basic things not present in the container.
290 # - git
291 # - tar (CentOS 6 lxc container does not have it)
292 # - python3
293 local needed="" pair="" pkg="" cmd="" needed=""
294 local pairs="tar:tar git:git"
295 get_os_info
296 local py3pkg="python3"
297 case "$OS_NAME" in
298 opensuse)
299 py3pkg="python3-base"
300 ;;
301 esac
302
303 pairs="$pairs python3:$py3pkg"
304
305 for pair in $pairs; do
306 pkg=${pair#*:}
307 cmd=${pair%%:*}
308 command -v "$cmd" > /dev/null 2>&1 || needed="${needed} $pkg"
309 done
310 needed=${needed# }
311 if [ -z "$needed" ]; then
312 error "No prep packages needed"
313 return 0
314 fi
315 error "Installing prep packages: ${needed}"
316 # shellcheck disable=SC2086
317 set -- $needed
318 install_packages "$@"
319 }
320
321 pytest() {
322 python3 -m pytest "$@"
323 }
324
325 is_done_cloudinit() {
326 [ -e "/run/cloud-init/result.json" ]
327 _RET=""
328 }
329
330 is_done_systemd() {
331 local s="" num="$1"
332 s=$(systemctl is-system-running 2>&1)
333 _RET="$? $s"
334 case "$s" in
335 initializing | starting) return 1 ;;
336 *[Ff]ailed*connect*bus*)
337 # warn if not the first run.
338 [ "$num" -lt 5 ] ||
339 error "Failed to connect to systemd bus [${_RET%% *}]"
340 return 1
341 ;;
342 esac
343 return 0
344 }
345
346 is_done_other() {
347 local out=""
348 out=$(getent hosts ubuntu.com 2>&1)
349 return
350 }
351
352 wait_inside() {
353 local name="$1" max="${2:-${WAIT_MAX}}" debug=${3:-0}
354 local i=0 check="is_done_other"
355 if [ -e /run/systemd ]; then
356 check=is_done_systemd
357 elif [ -x /usr/bin/cloud-init ]; then
358 check=is_done_cloudinit
359 fi
360 [ "$debug" != "0" ] && debug 1 "check=$check"
361 while ! $check $i && i=$((i + 1)); do
362 [ "$i" -ge "$max" ] && exit 1
363 [ "$debug" = "0" ] || echo -n .
364 sleep 1
365 done
366 if [ "$debug" != "0" ]; then
367 read up _ < /proc/uptime
368 debug 1 "[$name ${i:+done after $i }up=$up${_RET:+ ${_RET}}]"
369 fi
370 }
371
372 wait_for_boot() {
373 local name="$1"
374 local out="" ret="" wtime=$WAIT_MAX
375 local system_up=false
376 for i in {0..30}; do
377 [ "$i" -gt 1 ] && sleep 5
378 inside "$name" true 2> /dev/null && system_up=true && break
379 done
380 [ $system_up == true ] || {
381 errorrc "exec command inside $name failed."
382 return
383 }
384 get_os_info_in "$name"
385 [ "$OS_NAME" = "debian" ] && wtime=300 &&
386 debug 1 "on debian we wait for ${wtime}s"
387 debug 1 "waiting for boot of $name"
388 run_self_inside "$name" wait_inside "$name" "$wtime" "$VERBOSITY" ||
389 {
390 errorrc "wait inside $name failed."
391 return
392 }
393
394 if [ -n "${http_proxy-}" ]; then
395 if [ "$OS_NAME" = "centos" -o "$OS_NAME" = "fedora" ]; then
396 debug 1 "configuring proxy ${http_proxy}"
397 inside "$name" sh -c "echo proxy=$http_proxy >> /etc/yum.conf"
398 inside "$name" sh -c "sed -i --regexp-extended '/^#baseurl=/s/#// ; /^(mirrorlist|metalink)=/s/^/#/' /etc/yum.repos.d/*.repo"
399 inside "$name" sh -c "sed -i 's/download\.fedoraproject\.org/dl.fedoraproject.org/g' /etc/yum.repos.d/*.repo"
400 inside "$name" sh -c "sed -i 's/download\.example/dl.fedoraproject.org/g' /etc/yum.repos.d/*.repo"
401 if [ "$OS_NAME" = "centos" ]; then
402 CENTOS_REPO="/etc/yum.repos.d/centos.repo"
403 inside "$name" sh -c "grep -q baseurl $CENTOS_REPO"
404 if [ $? -eq 1 ]; then
405 # CentOS 9 does not provide baseurl definitions
406 inside "$name" sh -c "sed -i '/\[baseos\]/a baseurl=https://mirror.stream.centos.org/9-stream/BaseOS/x86_64/os' ${CENTOS_REPO}"
407 inside "$name" sh -c "sed -i '/\[appstream\]/a baseurl=https://mirror.stream.centos.org/9-stream/AppStream/x86_64/os' ${CENTOS_REPO}"
408 inside "$name" sh -c "sed -i '/\[crb\]/a baseurl=https://mirror.stream.centos.org/9-stream/CRB/x86_64/os' ${CENTOS_REPO}"
409 CENTOS_EXTRAS_REPO="/etc/yum.repos.d/centos-addons.repo"
410 inside "$name" sh -c "sed -i '/\[extras-common\]/a baseurl=https://mirror.stream.centos.org/SIGs/9-stream/extras/x86_64/extras-common' ${CENTOS_EXTRAS_REPO}"
411 inside "$name" sh -c "dnf install -y 'dnf-command(config-manager)'"
412 inside "$name" sh -c "dnf config-manager --set-enabled crb"
413 inside "$name" sh -c "dnf config-manager --set-disabled epel-cisco-openh264" || true
414 fi
415 fi
416 else
417 debug 1 "do not know how to configure proxy on $OS_NAME"
418 fi
419 fi
420 }
421
422 start_instance() {
423 local src="$1" name="$2" use_vm="$3"
424 debug 1 "starting container $name from '$src'"
425 launch_flags=()
426 [ "$use_vm" == true ] && launch_flags+=(--vm)
427 $LXC launch "$src" "$name" "${launch_flags[@]}" || {
428 errorrc "Failed to start container '$name' from '$src'"
429 return
430 }
431 CONTAINER=$name
432 wait_for_boot "$name"
433 }
434
435 delete_instance() {
436 debug 1 "removing container $1 [--keep to keep]"
437 $LXC delete --force "$1"
438 }
439
440 run_self_inside() {
441 # run_self_inside(container, args)
442 local name="$1"
443 shift
444 inside "$name" bash -s "$@" < "$0"
445 }
446
447 run_self_inside_as_cd() {
448 local name="$1" user="$2" dir="$3"
449 shift 3
450 inside_as_cd "$name" "$user" "$dir" bash -s "$@" < "$0"
451 }
452
453 main() {
454 local short_opts="a:hknpsuv"
455 local long_opts="artifacts:,dirty,help,keep,name:,package,source-package,unittest,verbose,vm,wait-max:,commitish:"
456 local getopt_out=""
457 getopt_out=$(getopt --name "${0##*/}" \
458 --options "${short_opts}" --long "${long_opts}" -- "$@") &&
459 eval set -- "${getopt_out}" ||
460 {
461 bad_Usage
462 return
463 }
464
465 local cur="" next=""
466 local package=false srcpackage=false unittest="" name=""
467 local dirty=false artifact_d="."
468 local use_vm=false
469
470 while [ $# -ne 0 ]; do
471 cur="${1:-}"
472 next="${2:-}"
473 case "$cur" in
474 -a | --artifacts) artifact_d="$next" ;;
475 --dirty) dirty=true ;;
476 -h | --help)
477 Usage
478 exit 0
479 ;;
480 -k | --keep) KEEP=true ;;
481 -n | --name)
482 name="$next"
483 shift
484 ;;
485 -p | --package) package=true ;;
486 -s | --source-package) srcpackage=true ;;
487 -u | --unittest) unittest=1 ;;
488 -v | --verbose) VERBOSITY=$((VERBOSITY + 1)) ;;
489 --vm) use_vm=true ;;
490 --wait-max)
491 WAIT_MAX="$next"
492 shift
493 ;;
494 --commitish)
495 COMMITISH="$next"
496 shift
497 ;;
498 --)
499 shift
500 break
501 ;;
502 esac
503 shift
504 done
505 COMMITISH=${COMMITISH:-HEAD}
506
507 [ $# -eq 1 ] || {
508 bad_Usage "Expected 1 arg, got $# ($*)"
509 return
510 }
511 local img_ref_in="$1"
512 case "${img_ref_in}" in
513 *:*) img_ref="${img_ref_in}" ;;
514 *) img_ref="images:${img_ref_in}" ;;
515 esac
516
517 # program starts here
518 local out="" user="ci-test" cdir="" home=""
519 home="/home/$user"
520 cdir="$home/cloud-init"
521 if [ -z "$name" ]; then
522 if out=$(petname 2>&1); then
523 name="ci-${out}"
524 elif out=$(uuidgen -t 2>&1); then
525 name="ci-${out%%-*}"
526 else
527 error "Must provide name or have petname or uuidgen"
528 return 1
529 fi
530 fi
531
532 trap cleanup EXIT
533
534 start_instance "$img_ref" "$name" "$use_vm" ||
535 {
536 errorrc "Failed to start container for $img_ref"
537 return
538 }
539
540 get_os_info_in "$name" ||
541 {
542 errorrc "failed to get os_info in $name"
543 return
544 }
545
546 # prep the container (install very basic dependencies)
547 run_self_inside "$name" prep ||
548 {
549 errorrc "Failed to prep container $name"
550 return
551 }
552
553 # add the user
554 inside "$name" useradd "$user" --create-home "--home-dir=$home" ||
555 {
556 errorrc "Failed to add user '$user' in '$name'"
557 return 1
558 }
559
560 debug 1 "inserting cloud-init"
561 inject_cloud_init "$name" "$user" "$dirty" || {
562 errorrc "FAIL: injecting cloud-init into $name failed."
563 return
564 }
565
566 local rdcmd=(python3 tools/read-dependencies "--distro=${OS_NAME}" --install --test-distro)
567 inside_as_cd "$name" root "$cdir" "${rdcmd[@]}" || {
568 errorrc "FAIL: failed to install dependencies with read-dependencies"
569 return
570 }
571
572 local errors=()
573 inside_as_cd "$name" "$user" "$cdir" git status || {
574 errorrc "git checkout failed."
575 errors[${#errors[@]}]="git checkout"
576 }
577
578 if [ -n "$unittest" ]; then
579 debug 1 "running unit tests."
580 run_self_inside_as_cd "$name" "$user" "$cdir" pytest \
581 tests/unittests cloudinit/ || {
582 errorrc "pytest failed."
583 errors[${#errors[@]}]="pytest"
584 }
585 fi
586
587 local build_pkg="" build_srcpkg="" pkg_ext="" distflag=""
588 case "$OS_NAME" in
589 centos | rocky* | fedora) distflag="--distro=redhat" ;;
590 opensuse*) distflag="--distro=suse" ;;
591 esac
592
593 case "$OS_NAME" in
594 debian | ubuntu)
595 build_pkg="./packages/bddeb -d"
596 build_srcpkg="./packages/bddeb -S -d"
597 pkg_ext=".deb"
598 ;;
599 centos | opensuse* | rocky* | fedora)
600 build_pkg="./packages/brpm $distflag"
601 build_srcpkg="./packages/brpm $distflag --srpm"
602 pkg_ext=".rpm"
603 ;;
604 esac
605 if [ "$srcpackage" = "true" ]; then
606 [ -n "$build_srcpkg" ] || {
607 error "Unknown package command for $OS_NAME"
608 return 1
609 }
610 debug 1 "building source package with $build_srcpkg."
611 # shellcheck disable=SC2086
612 inside_as_cd "$name" "$user" "$cdir" python3 $build_srcpkg || {
613 errorrc "failed: $build_srcpkg"
614 errors[${#errors[@]}]="source package"
615 }
616 fi
617
618 if [ "$package" = "true" ]; then
619 [ -n "$build_pkg" ] || {
620 error "Unknown build source command for $OS_NAME"
621 return 1
622 }
623 debug 1 "building binary package with $build_pkg."
624 # shellcheck disable=SC2086
625 inside_as_cd "$name" "$user" "$cdir" python3 $build_pkg || {
626 errorrc "failed: $build_pkg"
627 errors[${#errors[@]}]="binary package"
628 }
629 fi
630
631 if [ -n "$artifact_d" ] &&
632 [ "$package" = "true" -o "$srcpackage" = "true" ]; then
633 local art=""
634 artifact_d="${artifact_d%/}/"
635 [ -d "${artifact_d}" ] || mkdir -p "$artifact_d" || {
636 errorrc "failed to create artifact dir '$artifact_d'"
637 return
638 }
639
640 for art in $(inside "$name" sh -c "echo $cdir/*${pkg_ext}"); do
641 $LXC file pull "$name/$art" "$artifact_d" || {
642 errorrc "Failed to pull '$name/$art' to ${artifact_d}"
643 errors[${#errors[@]}]="artifact copy: $art"
644 }
645 debug 1 "wrote ${artifact_d}${art##*/}"
646 done
647 fi
648
649 if [ "${#errors[@]}" != "0" ]; then
650 local e=""
651 error "there were ${#errors[@]} errors."
652 for e in "${errors[@]}"; do
653 error " $e"
654 done
655 return 1
656 fi
657 return 0
658 }
659
660 case "${1:-}" in
661 prep | os_info | wait_inside | pytest)
662 _n=$1
663 shift
664 "$_n" "$@"
665 ;;
666 *) main "$@" ;;
667 esac