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