21654: Upgrades follow-redirects addressing CVE-2024-28849 & CVE-2023-26159
[arvados.git] / build / run-library.sh
1 #!/bin/bash -xe
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 # A library of functions shared by the various scripts in this directory.
7
8 # This is the timestamp about when we merged changed to include licenses
9 # with Arvados packages.  We use it as a heuristic to add revisions for
10 # older packages.
11 LICENSE_PACKAGE_TS=20151208015500
12
13 if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
14     RAILS_PACKAGE_ITERATION=1
15 else
16     RAILS_PACKAGE_ITERATION="$ARVADOS_BUILDING_ITERATION"
17 fi
18
19 debug_echo () {
20     echo "$@" >"$STDOUT_IF_DEBUG"
21 }
22
23 find_python_program() {
24     prog="$1"
25     shift
26     for prog in "$@"; do
27         if "$prog" --version >/dev/null 2>&1; then
28             echo "$prog"
29             return 0
30         fi
31     done
32     cat >&2 <<EOF
33 $helpmessage
34
35 Error: $prog (from Python setuptools module) not found
36
37 EOF
38     exit 1
39 }
40
41 format_last_commit_here() {
42     local format="$1"; shift
43     local dir="${1:-.}"; shift
44     TZ=UTC git log -n1 --first-parent "--format=format:$format" "$dir"
45 }
46
47 version_from_git() {
48     # Output the version being built, or if we're building a
49     # dev/prerelease, output a version number based on the git log for
50     # the given $subdir.
51     local subdir="$1"; shift
52     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
53         echo "$ARVADOS_BUILDING_VERSION"
54         return
55     fi
56
57     local git_ts git_hash
58     declare $(format_last_commit_here "git_ts=%ct git_hash=%h" "$subdir")
59     ARVADOS_BUILDING_VERSION="$($WORKSPACE/build/version-at-commit.sh $git_hash)"
60     echo "$ARVADOS_BUILDING_VERSION"
61 }
62
63 nohash_version_from_git() {
64     local subdir="$1"; shift
65     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
66         echo "$ARVADOS_BUILDING_VERSION"
67         return
68     fi
69     version_from_git $subdir | cut -d. -f1-4
70 }
71
72 timestamp_from_git() {
73     local subdir="$1"; shift
74     format_last_commit_here "%ct" "$subdir"
75 }
76
77 calculate_python_sdk_cwl_package_versions() {
78   python_sdk_version=$(cd sdk/python && python3 arvados_version.py)
79   cwl_runner_version=$(cd sdk/cwl && python3 arvados_version.py)
80 }
81
82 # Usage: get_native_arch
83 get_native_arch() {
84   # Only amd64 and aarch64 are supported at the moment
85   local native_arch=""
86   case "$HOSTTYPE" in
87     x86_64)
88       native_arch="amd64"
89       ;;
90     aarch64)
91       native_arch="arm64"
92       ;;
93     *)
94       echo "Error: architecture not supported"
95       exit 1
96       ;;
97   esac
98   echo $native_arch
99 }
100
101 handle_ruby_gem() {
102     local gem_name="$1"; shift
103     local gem_version="$(nohash_version_from_git)"
104     local gem_src_dir="$(pwd)"
105
106     if [[ -n "$ONLY_BUILD" ]] && [[ "$gem_name" != "$ONLY_BUILD" ]] ; then
107         return 0
108     fi
109
110     if ! [[ -e "${gem_name}-${gem_version}.gem" ]]; then
111         find -maxdepth 1 -name "${gem_name}-*.gem" -delete
112
113         # -q appears to be broken in gem version 2.2.2
114         $GEM build "$gem_name.gemspec" $DASHQ_UNLESS_DEBUG >"$STDOUT_IF_DEBUG" 2>"$STDERR_IF_DEBUG"
115     fi
116 }
117
118 # Usage: package_workbench2
119 package_workbench2() {
120     local pkgname=arvados-workbench2
121     local src=services/workbench2
122     local dst=/var/www/arvados-workbench2/workbench2
123     local description="Arvados Workbench 2"
124     cd "$WORKSPACE/$src"
125     local version="$(version_from_git)"
126     rm -rf ./build
127     NODE_ENV=production yarn install
128     VERSION="$version" BUILD_NUMBER="$(default_iteration "$pkgname" "$version" yarn)" GIT_COMMIT="$(git rev-parse HEAD | head -c9)" yarn build
129     cd "$WORKSPACE/packages/$TARGET"
130     fpm_build "${WORKSPACE}/$src" "${WORKSPACE}/$src/build/=$dst" "$pkgname" dir "$version" \
131               --license="GNU Affero General Public License, version 3.0" \
132               --description="${description}" \
133               --config-files="/etc/arvados/$pkgname/workbench2.example.json" \
134               "$WORKSPACE/services/workbench2/etc/arvados/workbench2/workbench2.example.json=/etc/arvados/$pkgname/workbench2.example.json"
135 }
136
137 calculate_go_package_version() {
138   # $__returnvar has the nameref attribute set, which means it is a reference
139   # to another variable that is passed in as the first argument to this function.
140   # see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html
141   local -n __returnvar="$1"; shift
142   local oldpwd="$PWD"
143
144   cd "$WORKSPACE"
145   go mod download
146
147   # Update the version number and build a new package if the vendor
148   # bundle has changed, or the command imports anything from the
149   # Arvados SDK and the SDK has changed.
150   declare -a checkdirs=(go.mod go.sum)
151   while [ -n "$1" ]; do
152       checkdirs+=("$1")
153       shift
154   done
155   # Even our rails packages (version calculation happens here!) depend on a go component (arvados-server)
156   # Everything depends on the build directory.
157   checkdirs+=(sdk/go lib build)
158   local timestamp=0
159   for dir in ${checkdirs[@]}; do
160       cd "$WORKSPACE"
161       ts="$(timestamp_from_git "$dir")"
162       if [[ "$ts" -gt "$timestamp" ]]; then
163           version=$(version_from_git "$dir")
164           timestamp="$ts"
165       fi
166   done
167   cd "$oldpwd"
168   __returnvar="$version"
169 }
170
171 # Usage: package_go_binary services/foo arvados-foo [deb|rpm] [amd64|arm64] "Compute foo to arbitrary precision" [apache-2.0.txt]
172 package_go_binary() {
173   local src_path="$1"; shift
174   local prog="$1"; shift
175   local package_format="$1"; shift
176   local target_arch="$1"; shift
177   local description="$1"; shift
178   local license_file="${1:-agpl-3.0.txt}"; shift
179
180   if [[ -n "$ONLY_BUILD" ]] && [[ "$prog" != "$ONLY_BUILD" ]]; then
181       debug_echo -e "Skipping build of $prog package."
182       return 0
183   fi
184
185   native_arch=$(get_native_arch)
186
187   if [[ "$native_arch" != "amd64" ]] && [[ -n "$target_arch" ]] && [[ "$native_arch" != "$target_arch" ]]; then
188     echo "Error: no cross compilation support for Go on $native_arch, can not build $prog for $target_arch"
189     return 1
190   fi
191
192   case "$package_format-$TARGET" in
193     # Ubuntu 20.04 does not support cross compilation because the
194     # libfuse package does not support multiarch. See
195     # <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=983477>.
196     # Red Hat-based distributions do not support native cross compilation at
197     # all (they use a qemu-based solution we haven't implemented yet).
198     deb-ubuntu2004|rpm-*)
199       cross_compilation=0
200       if [[ "$native_arch" == "amd64" ]] && [[ -n "$target_arch" ]] && [[ "$native_arch" != "$target_arch" ]]; then
201         echo "Error: no cross compilation support for Go on $native_arch for $TARGET, can not build $prog for $target_arch"
202         return 1
203       fi
204       ;;
205     *)
206       cross_compilation=1
207       ;;
208   esac
209
210   if [[ -n "$target_arch" ]]; then
211     archs=($target_arch)
212   else
213     # No target architecture specified, default to native target. When on amd64
214     # also crosscompile arm64 (when supported).
215     archs=($native_arch)
216     if [[ $cross_compilation -ne 0 ]]; then
217       archs+=("arm64")
218     fi
219   fi
220
221   for ta in ${archs[@]}; do
222     package_go_binary_worker "$src_path" "$prog" "$package_format" "$description" "$native_arch" "$ta" "$license_file"
223     retval=$?
224     if [[ $retval -ne 0 ]]; then
225       return $retval
226     fi
227   done
228 }
229
230 # Usage: package_go_binary services/foo arvados-foo deb "Compute foo to arbitrary precision" [amd64/arm64] [amd64/arm64] [apache-2.0.txt]
231 package_go_binary_worker() {
232     local src_path="$1"; shift
233     local prog="$1"; shift
234     local package_format="$1"; shift
235     local description="$1"; shift
236     local native_arch="${1:-amd64}"; shift
237     local target_arch="${1:-amd64}"; shift
238     local license_file="${1:-agpl-3.0.txt}"; shift
239
240     debug_echo "package_go_binary $src_path as $prog (native arch: $native_arch, target arch: $target_arch)"
241     local basename="${src_path##*/}"
242     calculate_go_package_version go_package_version $src_path
243
244     cd $WORKSPACE/packages/$TARGET
245     test_package_presence "$prog" "$go_package_version" "go" "" "$target_arch"
246     if [[ $? -ne 0 ]]; then
247       return 0
248     fi
249
250     echo "Building $package_format ($target_arch) package for $prog from $src_path"
251     if [[ "$native_arch" == "amd64" ]] && [[ "$target_arch" == "arm64" ]]; then
252       CGO_ENABLED=1 CC=aarch64-linux-gnu-gcc GOARCH=${target_arch} go install -ldflags "-X git.arvados.org/arvados.git/lib/cmd.version=${go_package_version} -X main.version=${go_package_version}" "git.arvados.org/arvados.git/$src_path"
253     else
254       GOARCH=${arch} go install -ldflags "-X git.arvados.org/arvados.git/lib/cmd.version=${go_package_version} -X main.version=${go_package_version}" "git.arvados.org/arvados.git/$src_path"
255     fi
256
257     local -a switches=()
258
259     binpath=$GOPATH/bin/${basename}
260     if [[ "${target_arch}" != "${native_arch}" ]]; then
261       switches+=("-a${target_arch}")
262       binpath="$GOPATH/bin/linux_${target_arch}/${basename}"
263     fi
264
265     systemd_unit="$WORKSPACE/${src_path}/${prog}.service"
266     if [[ -e "${systemd_unit}" ]]; then
267         switches+=(
268             --after-install "${WORKSPACE}/build/go-python-package-scripts/postinst"
269             --before-remove "${WORKSPACE}/build/go-python-package-scripts/prerm"
270             "${systemd_unit}=/lib/systemd/system/${prog}.service")
271     fi
272     switches+=("$WORKSPACE/${license_file}=/usr/share/doc/$prog/${license_file}")
273
274     fpm_build "${WORKSPACE}/${src_path}" "$binpath=/usr/bin/${prog}" "${prog}" dir "${go_package_version}" "--url=https://arvados.org" "--license=GNU Affero General Public License, version 3.0" "--description=${description}" "${switches[@]}"
275 }
276
277 # Usage: package_go_so lib/foo arvados_foo.so arvados-foo deb amd64 "Arvados foo library"
278 package_go_so() {
279     local src_path="$1"; shift
280     local sofile="$1"; shift
281     local pkg="$1"; shift
282     local package_format="$1"; shift
283     local target_arch="$1"; shift # supported: amd64, arm64
284     local description="$1"; shift
285
286     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkg" != "$ONLY_BUILD" ]]; then
287       debug_echo -e "Skipping build of $pkg package."
288       return 0
289     fi
290
291     debug_echo "package_go_so $src_path as $pkg"
292
293     calculate_go_package_version go_package_version $src_path
294     cd $WORKSPACE/packages/$TARGET
295     test_package_presence $pkg $go_package_version go || return 1
296     cd $WORKSPACE/$src_path
297     go build -buildmode=c-shared -o ${GOPATH}/bin/${sofile}
298     cd $WORKSPACE/packages/$TARGET
299     local -a fpmargs=(
300         "--url=https://arvados.org"
301         "--license=Apache License, Version 2.0"
302         "--description=${description}"
303         "$WORKSPACE/apache-2.0.txt=/usr/share/doc/$pkg/apache-2.0.txt"
304     )
305     if [[ -e "$WORKSPACE/$src_path/pam-configs-arvados" ]]; then
306         fpmargs+=("$WORKSPACE/$src_path/pam-configs-arvados=/usr/share/doc/$pkg/pam-configs-arvados-go")
307     fi
308     if [[ -e "$WORKSPACE/$src_path/README" ]]; then
309         fpmargs+=("$WORKSPACE/$src_path/README=/usr/share/doc/$pkg/README")
310     fi
311     fpm_build "${WORKSPACE}/${src_path}" "$GOPATH/bin/${sofile}=/usr/lib/${sofile}" "${pkg}" dir "${go_package_version}" "${fpmargs[@]}"
312 }
313
314 default_iteration() {
315     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
316         echo "$ARVADOS_BUILDING_ITERATION"
317         return
318     fi
319     local package_name="$1"; shift
320     local package_version="$1"; shift
321     local package_type="$1"; shift
322     local iteration=1
323     if [[ $package_version =~ ^0\.1\.([0-9]{14})(\.|$) ]] && \
324            [[ ${BASH_REMATCH[1]} -le $LICENSE_PACKAGE_TS ]]; then
325         iteration=2
326     fi
327     echo $iteration
328 }
329
330 _build_rails_package_scripts() {
331     local pkgname="$1"; shift
332     local destdir="$1"; shift
333     local srcdir="$RUN_BUILD_PACKAGES_PATH/rails-package-scripts"
334     for scriptname in postinst prerm postrm; do
335         cat "$srcdir/$pkgname.sh" "$srcdir/step2.sh" "$srcdir/$scriptname.sh" \
336             >"$destdir/$scriptname" || return $?
337     done
338 }
339
340 rails_package_version() {
341     local pkgname="$1"; shift
342     local srcdir="$1"; shift
343     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
344         echo "$ARVADOS_BUILDING_VERSION"
345         return
346     fi
347     local version="$(version_from_git)"
348     if [ $pkgname = "arvados-api-server" ] ; then
349         calculate_go_package_version version cmd/arvados-server "$srcdir"
350     fi
351     echo $version
352 }
353
354 test_rails_package_presence() {
355   local pkgname="$1"; shift
356   local srcdir="$1"; shift
357
358   if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
359     return 1
360   fi
361
362   tmppwd=`pwd`
363
364   cd $srcdir
365
366   local version="$(rails_package_version "$pkgname" "$srcdir")"
367
368   cd $tmppwd
369
370   test_package_presence $pkgname $version rails "$RAILS_PACKAGE_ITERATION"
371 }
372
373 get_complete_package_name() {
374   # if the errexit flag is set, unset it until this function returns
375   # otherwise, the shift calls below will abort the program if optional arguments are not supplied
376   if [ -o errexit ]; then
377     set +e
378     trap 'set -e' RETURN
379   fi
380   # $__returnvar has the nameref attribute set, which means it is a reference
381   # to another variable that is passed in as the first argument to this function.
382   # see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html
383   local -n __returnvar="$1"; shift
384   local pkgname="$1"; shift
385   local version="$1"; shift
386   local pkgtype="$1"; shift
387   local iteration="$1"; shift
388   local arch="$1"; shift
389   if [[ "$iteration" == "" ]]; then
390       iteration="$(default_iteration "$pkgname" "$version" "$pkgtype")"
391   fi
392
393   if [[ "$arch" == "" ]]; then
394     native_arch=$(get_native_arch)
395     rpm_native_arch="x86_64"
396     if [[ "$HOSTTYPE" == "aarch64" ]]; then
397       rpm_native_arch="arm64"
398     fi
399     rpm_architecture="$rpm_native_arch"
400     deb_architecture="$native_arch"
401
402     if [[ "$pkgtype" =~ ^(src)$ ]]; then
403       rpm_architecture="noarch"
404       deb_architecture="all"
405     fi
406   else
407     rpm_architecture=$arch
408     deb_architecture=$arch
409   fi
410
411   local complete_pkgname="${pkgname}_$version${iteration:+-$iteration}_$deb_architecture.deb"
412   if [[ "$FORMAT" == "rpm" ]]; then
413       # rpm packages get iteration 1 if we don't supply one
414       iteration=${iteration:-1}
415       complete_pkgname="$pkgname-$version-${iteration}.$rpm_architecture.rpm"
416   fi
417   __returnvar=${complete_pkgname}
418 }
419
420 # Test if the package already exists, if not return 0, if it does return 1
421 test_package_presence() {
422     local pkgname="$1"; shift
423     local version="$1"; shift
424     local pkgtype="$1"; shift
425     local iteration="$1"; shift
426     local arch="$1"; shift
427     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
428         return 1
429     fi
430
431     local full_pkgname
432     get_complete_package_name full_pkgname "$pkgname" "$version" "$pkgtype" "$iteration" "$arch"
433
434     # See if we can skip building the package, only if it already exists in the
435     # processed/ directory. If so, move it back to the packages directory to make
436     # sure it gets picked up by the test and/or upload steps.
437     # Get the list of packages from the repos
438
439     if [[ "$FORCE_BUILD" == "1" ]]; then
440       echo "Package $full_pkgname build forced with --force-build, building"
441     elif [[ "$FORMAT" == "deb" ]]; then
442       declare -A dd
443       dd[debian11]=bullseye
444       dd[debian12]=bookworm
445       dd[ubuntu2004]=focal
446       dd[ubuntu2204]=jammy
447       D=${dd[$TARGET]}
448       if [ ${pkgname:0:3} = "lib" ]; then
449         repo_subdir=${pkgname:0:4}
450       else
451         repo_subdir=${pkgname:0:1}
452       fi
453
454       repo_pkg_list=$(curl -s -o - http://apt.arvados.org/${D}/pool/main/${repo_subdir}/${pkgname}/)
455       echo "${repo_pkg_list}" |grep -q ${full_pkgname}
456       if [ $? -eq 0 ] ; then
457         echo "Package $full_pkgname exists upstream, not rebuilding, downloading instead!"
458         curl -s -o "$WORKSPACE/packages/$TARGET/${full_pkgname}" http://apt.arvados.org/${D}/pool/main/${repo_subdir}/${pkgname}/${full_pkgname}
459         return 1
460       elif test -f "$WORKSPACE/packages/$TARGET/processed/${full_pkgname}" ; then
461         echo "Package $full_pkgname exists, not rebuilding!"
462         return 1
463       else
464         echo "Package $full_pkgname not found, building"
465         return 0
466       fi
467     else
468       local rpm_root
469       case "$TARGET" in
470         rocky8) rpm_root="CentOS/8/dev" ;;
471         *)
472           echo "FIXME: Don't know RPM URL path for $TARGET, building"
473           return 0
474           ;;
475       esac
476       local rpm_url="http://rpm.arvados.org/$rpm_root/$arch/$full_pkgname"
477
478       if curl -fs -o "$WORKSPACE/packages/$TARGET/$full_pkgname" "$rpm_url"; then
479         echo "Package $full_pkgname exists upstream, not rebuilding, downloading instead!"
480         return 1
481       elif [[ -f "$WORKSPACE/packages/$TARGET/processed/$full_pkgname" ]]; then
482         echo "Package $full_pkgname exists, not rebuilding!"
483         return 1
484       else
485         echo "Package $full_pkgname not found, building"
486         return 0
487       fi
488     fi
489 }
490
491 handle_rails_package() {
492     local pkgname="$1"; shift
493
494     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
495         return 0
496     fi
497     local srcdir="$1"; shift
498     cd "$srcdir"
499     local license_path="$1"; shift
500     local version="$(rails_package_version "$pkgname" "$srcdir")"
501     echo "$version" >package-build.version
502     local scripts_dir="$(mktemp --tmpdir -d "$pkgname-XXXXXXXX.scripts")" && \
503     (
504         set -e
505         _build_rails_package_scripts "$pkgname" "$scripts_dir"
506         cd "$srcdir"
507         mkdir -p tmp
508         git rev-parse HEAD >git-commit.version
509         bundle config set cache_all true
510         bundle package
511     )
512     if [[ 0 != "$?" ]] || ! cd "$WORKSPACE/packages/$TARGET"; then
513         echo "ERROR: $pkgname package prep failed" >&2
514         rm -rf "$scripts_dir"
515         EXITCODE=1
516         return 1
517     fi
518     local railsdir="/var/www/${pkgname%-server}/current"
519     local -a pos_args=("$srcdir/=$railsdir" "$pkgname" dir "$version")
520     local license_arg="$license_path=$railsdir/$(basename "$license_path")"
521     local -a switches=(--after-install "$scripts_dir/postinst"
522                        --before-remove "$scripts_dir/prerm"
523                        --after-remove "$scripts_dir/postrm")
524     if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
525         switches+=(--iteration $RAILS_PACKAGE_ITERATION)
526     fi
527     # For some reason fpm excludes need to not start with /.
528     local exclude_root="${railsdir#/}"
529     for exclude in tmp log coverage Capfile\* \
530                        config/deploy\* \
531                        config/application.yml \
532                        config/database.yml; do
533         switches+=(-x "$exclude_root/$exclude")
534     done
535     fpm_build "${srcdir}" "${pos_args[@]}" "${switches[@]}" \
536               -x "$exclude_root/vendor/cache-*" \
537               -x "$exclude_root/vendor/bundle" "$@" "$license_arg"
538     rm -rf "$scripts_dir"
539 }
540
541 # Usage: handle_api_server [amd64|arm64]
542 handle_api_server () {
543   local target_arch="${1:-amd64}"; shift
544
545   if [[ -n "$ONLY_BUILD" ]] && [[ "$ONLY_BUILD" != "arvados-api-server" ]] ; then
546     debug_echo -e "Skipping build of arvados-api-server package."
547     return 0
548   fi
549
550   native_arch=$(get_native_arch)
551   if [[ "$target_arch" != "$native_arch" ]]; then
552     echo "Error: no cross compilation support for Rails yet, can not build arvados-api-server for $ARCH"
553     echo
554     exit 1
555   fi
556
557   # Build the API server package
558   test_rails_package_presence arvados-api-server "$WORKSPACE/services/api"
559   if [[ "$?" == "0" ]]; then
560     calculate_go_package_version arvados_server_version cmd/arvados-server
561     arvados_server_iteration=$(default_iteration "arvados-server" "$arvados_server_version" "go")
562     handle_rails_package arvados-api-server "$WORKSPACE/services/api" \
563         "$WORKSPACE/agpl-3.0.txt" --url="https://arvados.org" \
564         --description="Arvados API server - Arvados is a free and open source platform for big data science." \
565         --license="GNU Affero General Public License, version 3.0" --depends "arvados-server = ${arvados_server_version}-${arvados_server_iteration}"
566   fi
567 }
568
569 # Usage: handle_arvados_src
570 handle_arvados_src () {
571   if [[ -n "$ONLY_BUILD" ]] && [[ "$ONLY_BUILD" != "arvados-src" ]] ; then
572     debug_echo -e "Skipping build of arvados-src package."
573     return 0
574   fi
575   # arvados-src
576   (
577       cd "$WORKSPACE"
578       COMMIT_HASH=$(format_last_commit_here "%H")
579       arvados_src_version="$(version_from_git)"
580
581       cd $WORKSPACE/packages/$TARGET
582       test_package_presence arvados-src "$arvados_src_version" src ""
583
584       if [[ "$?" == "0" ]]; then
585         cd "$WORKSPACE"
586         SRC_BUILD_DIR=$(mktemp -d)
587         # mktemp creates the directory with 0700 permissions by default
588         chmod 755 $SRC_BUILD_DIR
589         git clone $DASHQ_UNLESS_DEBUG "$WORKSPACE/.git" "$SRC_BUILD_DIR"
590         cd "$SRC_BUILD_DIR"
591
592         # go into detached-head state
593         git checkout $DASHQ_UNLESS_DEBUG "$COMMIT_HASH"
594         echo "$COMMIT_HASH" >git-commit.version
595
596         cd $WORKSPACE/packages/$TARGET
597         fpm_build "$WORKSPACE" $SRC_BUILD_DIR/=/usr/local/arvados/src arvados-src 'dir' "$arvados_src_version" "--exclude=usr/local/arvados/src/.git" "--url=https://arvados.org" "--license=GNU Affero General Public License, version 3.0" "--description=The Arvados source code" "--architecture=all"
598
599         rm -rf "$SRC_BUILD_DIR"
600       fi
601   )
602 }
603
604 setup_build_virtualenv() {
605     PYTHON_BUILDROOT="$(mktemp --directory --tmpdir pybuild.XXXXXXXX)"
606     "$PYTHON3_EXECUTABLE" -m venv "$PYTHON_BUILDROOT/venv"
607     "$PYTHON_BUILDROOT/venv/bin/pip" install --upgrade build piprepo setuptools wheel
608     mkdir "$PYTHON_BUILDROOT/wheelhouse"
609 }
610
611 # Build python packages with a virtualenv built-in
612 # Usage: fpm_build_virtualenv arvados-python-client sdk/python [deb|rpm] [amd64|arm64]
613 fpm_build_virtualenv () {
614   local pkg=$1; shift
615   local pkg_dir=$1; shift
616   local package_format="$1"; shift
617   local target_arch="${1:-amd64}"; shift
618
619   native_arch=$(get_native_arch)
620   if [[ -n "$target_arch" ]] && [[ "$native_arch" == "$target_arch" ]]; then
621       fpm_build_virtualenv_worker "$pkg" "$pkg_dir" "$package_format" "$native_arch" "$target_arch"
622   elif [[ -z "$target_arch" ]]; then
623     fpm_build_virtualenv_worker "$pkg" "$pkg_dir" "$package_format" "$native_arch" "$native_arch"
624   else
625     echo "Error: no cross compilation support for Python yet, can not build $pkg for $target_arch"
626     return 1
627   fi
628 }
629
630 # Build python packages with a virtualenv built-in
631 # Usage: fpm_build_virtualenv_worker arvados-python-client sdk/python python3 [deb|rpm] [amd64|arm64] [amd64|arm64]
632 fpm_build_virtualenv_worker () {
633   PKG=$1; shift
634   PKG_DIR=$1; shift
635   local package_format="$1"; shift
636   local native_arch="${1:-amd64}"; shift
637   local target_arch=${1:-amd64}; shift
638
639   # Set up
640   STDOUT_IF_DEBUG=/dev/null
641   STDERR_IF_DEBUG=/dev/null
642   DASHQ_UNLESS_DEBUG=-q
643   if [[ "$DEBUG" != "0" ]]; then
644       STDOUT_IF_DEBUG=/dev/stdout
645       STDERR_IF_DEBUG=/dev/stderr
646       DASHQ_UNLESS_DEBUG=
647   fi
648   if [[ "$ARVADOS_BUILDING_ITERATION" == "" ]]; then
649     ARVADOS_BUILDING_ITERATION=1
650   fi
651
652   PACKAGE_PREFIX=$PYTHON3_PKG_PREFIX
653   if [[ "$PKG" != "arvados-docker-cleaner" ]]; then
654     PYTHON_PKG=$PACKAGE_PREFIX-$PKG
655   else
656     # Exception to our package naming convention
657     PYTHON_PKG=$PKG
658   fi
659
660   # We must always add a wheel to our repository, even if we're not building
661   # this distro package, because it might be a dependency for a later
662   # package we do build.
663   if [[ "$PKG_DIR" =~ ^.=[0-9]+\. ]]; then
664       # Not source to build, but a version to download.
665       # The rest of the function expects a filesystem path, so set one afterwards.
666       "$PYTHON_BUILDROOT/venv/bin/pip" download --dest="$PYTHON_BUILDROOT/wheelhouse" "$PKG$PKG_DIR" \
667           && PKG_DIR="$PYTHON_BUILDROOT/nonexistent"
668   else
669       # Make PKG_DIR absolute.
670       PKG_DIR="$(env -C "$WORKSPACE" readlink -e "$PKG_DIR")"
671       if [[ -e "$PKG_DIR/pyproject.toml" ]]; then
672           "$PYTHON_BUILDROOT/venv/bin/python" -m build --outdir="$PYTHON_BUILDROOT/wheelhouse" "$PKG_DIR"
673       else
674           env -C "$PKG_DIR" "$PYTHON_BUILDROOT/venv/bin/python" setup.py bdist_wheel --dist-dir="$PYTHON_BUILDROOT/wheelhouse"
675       fi
676   fi
677   if [[ $? -ne 0 ]]; then
678     printf "Error, unable to download/build wheel for %s @ %s" "$PKG" "$PKG_DIR"
679     exit 1
680   elif ! "$PYTHON_BUILDROOT/venv/bin/piprepo" build "$PYTHON_BUILDROOT/wheelhouse"; then
681     printf "Error, unable to update local wheel repository"
682     exit 1
683   fi
684
685   if [[ -n "$ONLY_BUILD" ]] && [[ "$PYTHON_PKG" != "$ONLY_BUILD" ]] && [[ "$PKG" != "$ONLY_BUILD" ]]; then
686     return 0
687   fi
688
689   local venv_dir="$PYTHON_BUILDROOT/$PYTHON_PKG"
690   echo "Creating virtualenv..."
691   if ! "$PYTHON3_EXECUTABLE" -m venv "$venv_dir"; then
692     printf "Error, unable to run\n  %s -m venv %s\n" "$PYTHON3_EXECUTABLE" "$venv_dir"
693     exit 1
694   # We must have the dependency resolver introduced in late 2020 for the rest
695   # of our install process to work.
696   # <https://blog.python.org/2020/11/pip-20-3-release-new-resolver.html>
697   elif ! "$venv_dir/bin/pip" install "pip>=20.3"; then
698     printf "Error, unable to run\n  %s/bin/pip install 'pip>=20.3'\n" "$venv_dir"
699     exit 1
700   fi
701
702   local pip_wheel="$(ls --sort=time --reverse "$PYTHON_BUILDROOT/wheelhouse/$(echo "$PKG" | sed s/-/_/g)-"*.whl | tail -n1)"
703   if [[ -z "$pip_wheel" ]]; then
704     printf "Error, unable to find built wheel for $PKG"
705     exit 1
706   elif ! "$venv_dir/bin/pip" install $DASHQ_UNLESS_DEBUG $CACHE_FLAG --extra-index-url="file://$PYTHON_BUILDROOT/wheelhouse/simple" "$pip_wheel"; then
707     printf "Error, unable to run
708   %s/bin/pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG --extra-index-url=file://%s %s
709 " "$venv_dir" "$PYTHON_BUILDROOT/wheelhouse/simple" "$pip_wheel"
710     exit 1
711   fi
712
713   # Determine the package version from the wheel
714   PYTHON_VERSION="$("$venv_dir/bin/python" "$WORKSPACE/build/pypkg_info.py" metadata "$PKG" Version)"
715   UNFILTERED_PYTHON_VERSION="$(echo "$PYTHON_VERSION" | sed 's/\.dev/~dev/; s/\([0-9]\)rc/\1~rc/')"
716
717   # See if we actually need to build this package; does it exist already?
718   # We can't do this earlier than here, because we need PYTHON_VERSION.
719   if ! test_package_presence "$PYTHON_PKG" "$UNFILTERED_PYTHON_VERSION" python3 "$ARVADOS_BUILDING_ITERATION" "$target_arch"; then
720     return 0
721   fi
722   echo "Building $package_format ($target_arch) package for $PKG from $PKG_DIR"
723
724   # Replace the shebang lines in all python scripts, and handle the activate
725   # scripts too. This is a functional replacement of the 237 line
726   # virtualenv_tools.py script that doesn't work in python3 without serious
727   # patching, minus the parts we don't need (modifying pyc files, etc).
728   local sys_venv_dir="/usr/lib/$PYTHON_PKG"
729   local sys_venv_py="$sys_venv_dir/bin/python$PYTHON3_VERSION"
730   find "$venv_dir/bin" -type f | while read binfile; do
731     if file --mime "$binfile" | grep -q binary; then
732       :  # Nothing to do for binary files
733     elif [[ "$binfile" =~ /activate(.csh|.fish|)$ ]]; then
734       sed -ri "s@VIRTUAL_ENV(=| )\".*\"@VIRTUAL_ENV\\1\"$sys_venv_dir\"@" "$binfile"
735     else
736       # Replace shebang line
737       sed -ri "1 s@^#\![^[:space:]]+/bin/python[0-9.]*@#\!$sys_venv_py@" "$binfile"
738     fi
739   done
740
741   # Using `env -C` sets the directory where the package is built.
742   # Using `fpm --chdir` sets the root directory for source arguments.
743   declare -a COMMAND_ARR=(
744       env -C "$PYTHON_BUILDROOT" fpm
745       --chdir="$venv_dir"
746       --name="$PYTHON_PKG"
747       --version="$UNFILTERED_PYTHON_VERSION"
748       --input-type=dir
749       --output-type="$package_format"
750       --depends="$PYTHON3_PACKAGE"
751       --iteration="$ARVADOS_BUILDING_ITERATION"
752       --replaces="python-$PKG"
753       --url="https://arvados.org"
754   )
755   # Append fpm flags corresponding to Python package metadata.
756   readarray -d "" -O "${#COMMAND_ARR[@]}" -t COMMAND_ARR < \
757             <("$venv_dir/bin/python3" "$WORKSPACE/build/pypkg_info.py" \
758                                       --delimiter=\\0 --format=fpm \
759                                       metadata "$PKG" License Summary)
760
761   if [[ -n "$target_arch" ]] && [[ "$target_arch" != "amd64" ]]; then
762     COMMAND_ARR+=("-a$target_arch")
763   fi
764
765   if [[ "$MAINTAINER" != "" ]]; then
766     COMMAND_ARR+=('--maintainer' "$MAINTAINER")
767   fi
768
769   if [[ "$VENDOR" != "" ]]; then
770     COMMAND_ARR+=('--vendor' "$VENDOR")
771   fi
772
773   if [[ "$DEBUG" != "0" ]]; then
774     COMMAND_ARR+=('--verbose' '--log' 'info')
775   fi
776
777   systemd_unit="$PKG_DIR/$PKG.service"
778   if [[ -e "${systemd_unit}" ]]; then
779     COMMAND_ARR+=('--after-install' "${WORKSPACE}/build/go-python-package-scripts/postinst")
780     COMMAND_ARR+=('--before-remove' "${WORKSPACE}/build/go-python-package-scripts/prerm")
781   fi
782
783   case "$package_format" in
784       deb)
785           COMMAND_ARR+=(
786               # Avoid warning
787               --deb-no-default-config-files
788           ) ;;
789       rpm)
790           COMMAND_ARR+=(
791               # Conflict with older packages we used to publish
792               --conflicts "rh-python36-python-$PKG"
793               # Do not generate /usr/lib/.build-id links on RH8+
794               # (otherwise our packages conflict with platform-python)
795               --rpm-rpmbuild-define "_build_id_links none"
796           ) ;;
797   esac
798
799   # Append --depends X and other arguments specified by fpm-info.sh in
800   # the package source dir. These are added last so they can override
801   # the arguments added by this script.
802   declare -a fpm_args=()
803   declare -a fpm_depends=()
804
805   fpminfo="$PKG_DIR/fpm-info.sh"
806   if [[ -e "$fpminfo" ]]; then
807     echo "Loading fpm overrides from $fpminfo"
808     if ! source "$fpminfo"; then
809       echo "Error, unable to source $WORKSPACE/$PKG_DIR/fpm-info.sh for $PKG"
810       exit 1
811     fi
812   fi
813
814   for i in "${fpm_depends[@]}"; do
815     COMMAND_ARR+=('--depends' "$i")
816   done
817
818   # make sure the systemd service file ends up in the right place
819   # used by arvados-docker-cleaner
820   if [[ -e "${systemd_unit}" ]]; then
821     COMMAND_ARR+=("share/doc/$PKG/$PKG.service=/lib/systemd/system/$PKG.service")
822   fi
823
824   COMMAND_ARR+=("${fpm_args[@]}")
825
826   while read -d "" binpath; do
827       COMMAND_ARR+=("$binpath=/usr/$binpath")
828   done < <("$venv_dir/bin/python3" "$WORKSPACE/build/pypkg_info.py" --delimiter=\\0 binfiles "$PKG")
829
830   # the python3-arvados-cwl-runner package comes with cwltool, expose that version
831   if [[ "$PKG" == arvados-cwl-runner ]]; then
832     COMMAND_ARR+=("bin/cwltool=/usr/bin/cwltool")
833   fi
834
835   COMMAND_ARR+=(".=$sys_venv_dir")
836
837   debug_echo -e "\n${COMMAND_ARR[@]}\n"
838
839   FPM_RESULTS=$("${COMMAND_ARR[@]}")
840   FPM_EXIT_CODE=$?
841
842   # if something went wrong and debug is off, print out the fpm command that errored
843   if ! fpm_verify $FPM_EXIT_CODE $FPM_RESULTS && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
844     echo "fpm returned an error executing the command:"
845     echo
846     echo -e "\n${COMMAND_ARR[@]}\n"
847   else
848     ls "$PYTHON_BUILDROOT"/*."$package_format"
849     mv "$PYTHON_BUILDROOT"/*."$package_format" "$WORKSPACE/packages/$TARGET/"
850   fi
851   echo
852 }
853
854 # Build packages for everything
855 fpm_build() {
856   # Source dir where fpm-info.sh (if any) will be found.
857   SRC_DIR=$1
858   shift
859   # The package source.  Depending on the source type, this can be a
860   # path, or the name of the package in an upstream repository (e.g.,
861   # pip).
862   PACKAGE=$1
863   shift
864   # The name of the package to build.
865   PACKAGE_NAME=$1
866   shift
867   # The type of source package.  Passed to fpm -s.  Default "dir".
868   PACKAGE_TYPE=${1:-dir}
869   shift
870   # Optional: the package version number.  Passed to fpm -v.
871   VERSION=$1
872   shift
873
874   if [[ -n "$ONLY_BUILD" ]] && [[ "$PACKAGE_NAME" != "$ONLY_BUILD" ]] && [[ "$PACKAGE" != "$ONLY_BUILD" ]] ; then
875       return 0
876   fi
877
878   local default_iteration_value="$(default_iteration "$PACKAGE" "$VERSION" "$PACKAGE_TYPE")"
879
880   declare -a COMMAND_ARR=("fpm" "-s" "$PACKAGE_TYPE" "-t" "$FORMAT")
881   if [ python = "$PACKAGE_TYPE" ] && [ deb = "$FORMAT" ]; then
882       # Dependencies are built from setup.py.  Since setup.py will never
883       # refer to Debian package iterations, it doesn't make sense to
884       # enforce those in the .deb dependencies.
885       COMMAND_ARR+=(--deb-ignore-iteration-in-dependencies)
886   fi
887
888   if [[ "$DEBUG" != "0" ]]; then
889     COMMAND_ARR+=('--verbose' '--log' 'info')
890   fi
891
892   if [[ -n "$PACKAGE_NAME" ]]; then
893     COMMAND_ARR+=('-n' "$PACKAGE_NAME")
894   fi
895
896   if [[ "$MAINTAINER" != "" ]]; then
897     COMMAND_ARR+=('--maintainer' "$MAINTAINER")
898   fi
899
900   if [[ "$VENDOR" != "" ]]; then
901     COMMAND_ARR+=('--vendor' "$VENDOR")
902   fi
903
904   if [[ "$VERSION" != "" ]]; then
905     COMMAND_ARR+=('-v' "$VERSION")
906   fi
907   if [[ -n "$default_iteration_value" ]]; then
908       # We can always add an --iteration here.  If another one is specified in $@,
909       # that will take precedence, as desired.
910       COMMAND_ARR+=(--iteration "$default_iteration_value")
911   fi
912
913   # Append --depends X and other arguments specified by fpm-info.sh in
914   # the package source dir. These are added last so they can override
915   # the arguments added by this script.
916   declare -a fpm_args=()
917   declare -a build_depends=()
918   declare -a fpm_depends=()
919   declare -a fpm_conflicts=()
920   declare -a fpm_exclude=()
921   if [[ ! -d "$SRC_DIR" ]]; then
922       echo >&2 "BUG: looking in wrong dir for fpm-info.sh: $pkgdir"
923       exit 1
924   fi
925   fpminfo="${SRC_DIR}/fpm-info.sh"
926   if [[ -e "$fpminfo" ]]; then
927       debug_echo "Loading fpm overrides from $fpminfo"
928       source "$fpminfo"
929   fi
930   for pkg in "${build_depends[@]}"; do
931       if [[ $TARGET =~ debian|ubuntu ]]; then
932           pkg_deb=$(ls "$WORKSPACE/packages/$TARGET/$pkg_"*.deb | sort -rg | awk 'NR==1')
933           if [[ -e $pkg_deb ]]; then
934               echo "Installing build_dep $pkg from $pkg_deb"
935               dpkg -i "$pkg_deb"
936           else
937               echo "Attemping to install build_dep $pkg using apt-get"
938               apt-get install -y "$pkg"
939           fi
940           apt-get -y -f install
941       else
942           pkg_rpm=$(ls "$WORKSPACE/packages/$TARGET/$pkg"-[0-9]*.rpm | sort -rg | awk 'NR==1')
943           if [[ -e $pkg_rpm ]]; then
944               echo "Installing build_dep $pkg from $pkg_rpm"
945               rpm -i "$pkg_rpm"
946           else
947               echo "Attemping to install build_dep $pkg"
948               rpm -i "$pkg"
949           fi
950       fi
951   done
952   for i in "${fpm_depends[@]}"; do
953     COMMAND_ARR+=('--depends' "$i")
954   done
955   for i in "${fpm_conflicts[@]}"; do
956     COMMAND_ARR+=('--conflicts' "$i")
957   done
958   for i in "${fpm_exclude[@]}"; do
959     COMMAND_ARR+=('--exclude' "$i")
960   done
961
962   COMMAND_ARR+=("${fpm_args[@]}")
963
964   # Append remaining function arguments directly to fpm's command line.
965   for i; do
966     COMMAND_ARR+=("$i")
967   done
968
969   COMMAND_ARR+=("$PACKAGE")
970
971   debug_echo -e "\n${COMMAND_ARR[@]}\n"
972
973   FPM_RESULTS=$("${COMMAND_ARR[@]}")
974   FPM_EXIT_CODE=$?
975   echo "fpm: exit code $FPM_EXIT_CODE" >>$STDOUT_IF_DEBUG
976   echo "$FPM_RESULTS" >>$STDOUT_IF_DEBUG
977
978   fpm_verify $FPM_EXIT_CODE $FPM_RESULTS
979
980   # if something went wrong and debug is off, print out the fpm command that errored
981   if [[ 0 -ne $? ]] && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
982     echo -e "\n${COMMAND_ARR[@]}\n"
983   fi
984 }
985
986 # verify build results
987 fpm_verify () {
988   FPM_EXIT_CODE=$1
989   shift
990   FPM_RESULTS=$@
991
992   FPM_PACKAGE_NAME=''
993   if [[ $FPM_RESULTS =~ ([A-Za-z0-9_\.~-]*\.)(deb|rpm) ]]; then
994     FPM_PACKAGE_NAME=${BASH_REMATCH[1]}${BASH_REMATCH[2]}
995   fi
996
997   if [[ "$FPM_PACKAGE_NAME" == "" ]]; then
998     EXITCODE=1
999     echo
1000     echo "Error: $PACKAGE: Unable to figure out package name from fpm results:"
1001     echo
1002     echo $FPM_RESULTS
1003     echo
1004     return 1
1005   elif [[ "$FPM_RESULTS" =~ "File already exists" ]]; then
1006     echo "Package $FPM_PACKAGE_NAME exists, not rebuilding"
1007     return 0
1008   elif [[ 0 -ne "$FPM_EXIT_CODE" ]]; then
1009     EXITCODE=1
1010     echo "Error building package for $1:\n $FPM_RESULTS"
1011     return 1
1012   fi
1013 }
1014
1015 install_package() {
1016   PACKAGES=$@
1017   if [[ "$FORMAT" == "deb" ]]; then
1018     $SUDO apt-get install $PACKAGES --yes
1019   elif [[ "$FORMAT" == "rpm" ]]; then
1020     $SUDO yum -q -y install $PACKAGES
1021   fi
1022 }
1023
1024 title() {
1025     printf '%s %s\n' "=======" "$1"
1026 }
1027
1028 checkexit() {
1029     if [[ "$1" != "0" ]]; then
1030         title "$2 -- FAILED"
1031         failures+=("$2 (`timer`)")
1032     else
1033         successes+=("$2 (`timer`)")
1034     fi
1035 }
1036
1037 timer_reset() {
1038     t0=$SECONDS
1039 }
1040
1041 timer() {
1042     if [[ -n "$t0" ]]; then
1043         echo -n "$(($SECONDS - $t0))s"
1044     fi
1045 }
1046
1047 report_outcomes() {
1048     for x in "${successes[@]}"
1049     do
1050         echo "Pass: $x"
1051     done
1052
1053     if [[ ${#failures[@]} == 0 ]]
1054     then
1055         if [[ ${#successes[@]} != 0 ]]; then
1056            echo "All test suites passed."
1057         fi
1058     else
1059         echo "Failures (${#failures[@]}):"
1060         for x in "${failures[@]}"
1061         do
1062             echo "Fail: $x"
1063         done
1064     fi
1065 }