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