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