17417: add the scaffolding for multi-arch support for our Python
[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 handle_ruby_gem() {
83     local gem_name="$1"; shift
84     local gem_version="$(nohash_version_from_git)"
85     local gem_src_dir="$(pwd)"
86
87     if [[ -n "$ONLY_BUILD" ]] && [[ "$gem_name" != "$ONLY_BUILD" ]] ; then
88         return 0
89     fi
90
91     if ! [[ -e "${gem_name}-${gem_version}.gem" ]]; then
92         find -maxdepth 1 -name "${gem_name}-*.gem" -delete
93
94         # -q appears to be broken in gem version 2.2.2
95         $GEM build "$gem_name.gemspec" $DASHQ_UNLESS_DEBUG >"$STDOUT_IF_DEBUG" 2>"$STDERR_IF_DEBUG"
96     fi
97 }
98
99 calculate_go_package_version() {
100   # $__returnvar has the nameref attribute set, which means it is a reference
101   # to another variable that is passed in as the first argument to this function.
102   # see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html
103   local -n __returnvar="$1"; shift
104   local oldpwd="$PWD"
105
106   cd "$WORKSPACE"
107   go mod download
108
109   # Update the version number and build a new package if the vendor
110   # bundle has changed, or the command imports anything from the
111   # Arvados SDK and the SDK has changed.
112   declare -a checkdirs=(go.mod go.sum)
113   while [ -n "$1" ]; do
114       checkdirs+=("$1")
115       shift
116   done
117   # Even our rails packages (version calculation happens here!) depend on a go component (arvados-server)
118   # Everything depends on the build directory.
119   checkdirs+=(sdk/go lib build)
120   local timestamp=0
121   for dir in ${checkdirs[@]}; do
122       cd "$WORKSPACE"
123       ts="$(timestamp_from_git "$dir")"
124       if [[ "$ts" -gt "$timestamp" ]]; then
125           version=$(version_from_git "$dir")
126           timestamp="$ts"
127       fi
128   done
129   cd "$oldpwd"
130   __returnvar="$version"
131 }
132
133 # Usage: package_go_binary services/foo arvados-foo "Compute foo to arbitrary precision" [apache-2.0.txt]
134 package_go_binary() {
135     local src_path="$1"; shift
136     local prog="$1"; shift
137     local description="$1"; shift
138     local license_file="${1:-agpl-3.0.txt}"; shift
139
140     if [[ -n "$ONLY_ARCH" ]]; then
141         package_go_binary_worker "$src_path" "$prog" "$description" "$ONLY_ARCH" "$license_file"
142     else
143       for arch in 'amd64' 'arm64'; do
144         package_go_binary_worker "$src_path" "$prog" "$description" "$arch" "$license_file"
145       done
146     fi
147 }
148
149 # Usage: package_go_binary services/foo arvados-foo "Compute foo to arbitrary precision" [amd64/arm64] [apache-2.0.txt]
150 package_go_binary_worker() {
151     local src_path="$1"; shift
152     local prog="$1"; shift
153     local description="$1"; shift
154     local arch="${1:-amd64}"; shift
155     local license_file="${1:-agpl-3.0.txt}"; shift
156
157     if [[ -n "$ONLY_BUILD" ]] && [[ "$prog" != "$ONLY_BUILD" ]]; then
158       # arvados-workbench depends on arvados-server at build time, so even when
159       # only arvados-workbench is being built, we need to build arvados-server too
160       if [[ "$prog" != "arvados-server" ]] || [[ "$ONLY_BUILD" != "arvados-workbench" ]]; then
161         return 0
162       fi
163     fi
164
165     debug_echo "package_go_binary $src_path as $prog"
166     local basename="${src_path##*/}"
167     calculate_go_package_version go_package_version $src_path
168
169     cd $WORKSPACE/packages/$TARGET
170     test_package_presence "$prog" "$go_package_version" "go" "" "$arch"
171     if [[ "$?" != "0" ]]; then
172       return 1
173     fi
174
175     echo "BUILDING ${arch}"
176     if [[ "$arch" == "arm64" ]]; then
177       CGO_ENABLED=1 CC=aarch64-linux-gnu-gcc GOARCH=${arch} go get -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"
178     else
179       GOARCH=${arch} go get -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"
180     fi
181
182     local -a switches=()
183
184     binpath=$GOPATH/bin/${basename}
185     if [[ "${arch}" != "amd64" ]]; then
186       switches+=("-a${arch}")
187       binpath="$GOPATH/bin/linux_${arch}/${basename}"
188     fi
189
190     systemd_unit="$WORKSPACE/${src_path}/${prog}.service"
191     if [[ -e "${systemd_unit}" ]]; then
192         switches+=(
193             --after-install "${WORKSPACE}/build/go-python-package-scripts/postinst"
194             --before-remove "${WORKSPACE}/build/go-python-package-scripts/prerm"
195             "${systemd_unit}=/lib/systemd/system/${prog}.service")
196     fi
197     switches+=("$WORKSPACE/${license_file}=/usr/share/doc/$prog/${license_file}")
198
199     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[@]}"
200 }
201
202 # Usage: package_go_so lib/foo arvados_foo.so arvados-foo "Arvados foo library"
203 package_go_so() {
204     local src_path="$1"; shift
205     local sofile="$1"; shift
206     local pkg="$1"; shift
207     local description="$1"; shift
208
209     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkg" != "$ONLY_BUILD" ]]; then
210       return 0
211     fi
212
213     debug_echo "package_go_so $src_path as $pkg"
214
215     calculate_go_package_version go_package_version $src_path
216     cd $WORKSPACE/packages/$TARGET
217     test_package_presence $pkg $go_package_version go || return 1
218     cd $WORKSPACE/$src_path
219     go build -buildmode=c-shared -o ${GOPATH}/bin/${sofile}
220     cd $WORKSPACE/packages/$TARGET
221     local -a fpmargs=(
222         "--url=https://arvados.org"
223         "--license=Apache License, Version 2.0"
224         "--description=${description}"
225         "$WORKSPACE/apache-2.0.txt=/usr/share/doc/$pkg/apache-2.0.txt"
226     )
227     if [[ -e "$WORKSPACE/$src_path/pam-configs-arvados" ]]; then
228         fpmargs+=("$WORKSPACE/$src_path/pam-configs-arvados=/usr/share/doc/$pkg/pam-configs-arvados-go")
229     fi
230     if [[ -e "$WORKSPACE/$src_path/README" ]]; then
231         fpmargs+=("$WORKSPACE/$src_path/README=/usr/share/doc/$pkg/README")
232     fi
233     fpm_build "${WORKSPACE}/${src_path}" "$GOPATH/bin/${sofile}=/usr/lib/${sofile}" "${pkg}" dir "${go_package_version}" "${fpmargs[@]}"
234 }
235
236 default_iteration() {
237     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
238         echo "$ARVADOS_BUILDING_ITERATION"
239         return
240     fi
241     local package_name="$1"; shift
242     local package_version="$1"; shift
243     local package_type="$1"; shift
244     local iteration=1
245     if [[ $package_version =~ ^0\.1\.([0-9]{14})(\.|$) ]] && \
246            [[ ${BASH_REMATCH[1]} -le $LICENSE_PACKAGE_TS ]]; then
247         iteration=2
248     fi
249     echo $iteration
250 }
251
252 _build_rails_package_scripts() {
253     local pkgname="$1"; shift
254     local destdir="$1"; shift
255     local srcdir="$RUN_BUILD_PACKAGES_PATH/rails-package-scripts"
256     for scriptname in postinst prerm postrm; do
257         cat "$srcdir/$pkgname.sh" "$srcdir/step2.sh" "$srcdir/$scriptname.sh" \
258             >"$destdir/$scriptname" || return $?
259     done
260 }
261
262 rails_package_version() {
263     local pkgname="$1"; shift
264     local srcdir="$1"; shift
265     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
266         echo "$ARVADOS_BUILDING_VERSION"
267         return
268     fi
269     local version="$(version_from_git)"
270     if [ $pkgname = "arvados-api-server" -o $pkgname = "arvados-workbench" ] ; then
271         calculate_go_package_version version cmd/arvados-server "$srcdir"
272     fi
273     echo $version
274 }
275
276 test_rails_package_presence() {
277   local pkgname="$1"; shift
278   local srcdir="$1"; shift
279
280   if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
281     return 1
282   fi
283
284   tmppwd=`pwd`
285
286   cd $srcdir
287
288   local version="$(rails_package_version "$pkgname" "$srcdir")"
289
290   cd $tmppwd
291
292   test_package_presence $pkgname $version rails "$RAILS_PACKAGE_ITERATION"
293 }
294
295 get_complete_package_name() {
296   # if the errexit flag is set, unset it until this function returns
297   # otherwise, the shift calls below will abort the program if optional arguments are not supplied
298   if [ -o errexit ]; then
299     set +e
300     trap 'set -e' RETURN
301   fi
302   # $__returnvar has the nameref attribute set, which means it is a reference
303   # to another variable that is passed in as the first argument to this function.
304   # see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html
305   local -n __returnvar="$1"; shift
306   local pkgname="$1"; shift
307   local version="$1"; shift
308   local pkgtype="$1"; shift
309   local iteration="$1"; shift
310   local arch="$1"; shift
311   if [[ "$iteration" == "" ]]; then
312       iteration="$(default_iteration "$pkgname" "$version" "$pkgtype")"
313   fi
314
315   if [[ "$arch" == "" ]]; then
316     rpm_architecture="x86_64"
317     deb_architecture="amd64"
318
319     if [[ "$pkgtype" =~ ^(src)$ ]]; then
320       rpm_architecture="noarch"
321       deb_architecture="all"
322     fi
323
324     # These python packages have binary components
325     if [[ "$pkgname" =~ (ruamel|ciso|pycrypto|pyyaml) ]]; then
326       rpm_architecture="x86_64"
327       deb_architecture="amd64"
328     fi
329   else
330     rpm_architecture=$arch
331     deb_architecture=$arch
332   fi
333
334   local complete_pkgname="${pkgname}_$version${iteration:+-$iteration}_$deb_architecture.deb"
335   if [[ "$FORMAT" == "rpm" ]]; then
336       # rpm packages get iteration 1 if we don't supply one
337       iteration=${iteration:-1}
338       complete_pkgname="$pkgname-$version-${iteration}.$rpm_architecture.rpm"
339   fi
340   __returnvar=${complete_pkgname}
341 }
342
343 # Test if the package already exists, if not return 0, if it does return 1
344 test_package_presence() {
345     local pkgname="$1"; shift
346     local version="$1"; shift
347     local pkgtype="$1"; shift
348     local iteration="$1"; shift
349     local arch="$1"; shift
350     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
351       # arvados-workbench depends on arvados-server at build time, so even when
352       # only arvados-workbench is being built, we need to build arvados-server too
353       if [[ "$pkgname" != "arvados-server" ]] || [[ "$ONLY_BUILD" != "arvados-workbench" ]]; then
354         return 1
355       fi
356     fi
357
358     local full_pkgname
359     get_complete_package_name full_pkgname "$pkgname" "$version" "$pkgtype" "$iteration" "$arch"
360
361     # See if we can skip building the package, only if it already exists in the
362     # processed/ directory. If so, move it back to the packages directory to make
363     # sure it gets picked up by the test and/or upload steps.
364     # Get the list of packages from the repos
365
366     if [[ "$FORCE_BUILD" == "1" ]]; then
367       echo "Package $full_pkgname build forced with --force-build, building"
368     elif [[ "$FORMAT" == "deb" ]]; then
369       declare -A dd
370       dd[debian10]=buster
371       dd[debian11]=bullseye
372       dd[ubuntu1804]=bionic
373       dd[ubuntu2004]=focal
374       D=${dd[$TARGET]}
375       if [ ${pkgname:0:3} = "lib" ]; then
376         repo_subdir=${pkgname:0:4}
377       else
378         repo_subdir=${pkgname:0:1}
379       fi
380
381       repo_pkg_list=$(curl -s -o - http://apt.arvados.org/${D}/pool/main/${repo_subdir}/${pkgname}/)
382       echo "${repo_pkg_list}" |grep -q ${full_pkgname}
383       if [ $? -eq 0 ] ; then
384         echo "Package $full_pkgname exists upstream, not rebuilding, downloading instead!"
385         curl -s -o "$WORKSPACE/packages/$TARGET/${full_pkgname}" http://apt.arvados.org/${D}/pool/main/${repo_subdir}/${pkgname}/${full_pkgname}
386         return 1
387       elif test -f "$WORKSPACE/packages/$TARGET/processed/${full_pkgname}" ; then
388         echo "Package $full_pkgname exists, not rebuilding!"
389         return 1
390       else
391         echo "Package $full_pkgname not found, building"
392         return 0
393       fi
394     else
395       centos_repo="http://rpm.arvados.org/CentOS/7/dev/x86_64/"
396
397       repo_pkg_list=$(curl -s -o - ${centos_repo})
398       echo ${repo_pkg_list} |grep -q ${full_pkgname}
399       if [ $? -eq 0 ]; then
400         echo "Package $full_pkgname exists upstream, not rebuilding, downloading instead!"
401         curl -s -o "$WORKSPACE/packages/$TARGET/${full_pkgname}" ${centos_repo}${full_pkgname}
402         return 1
403       elif test -f "$WORKSPACE/packages/$TARGET/processed/${full_pkgname}" ; then
404         echo "Package $full_pkgname exists, not rebuilding!"
405         return 1
406       else
407         echo "Package $full_pkgname not found, building"
408         return 0
409       fi
410     fi
411 }
412
413 handle_rails_package() {
414     local pkgname="$1"; shift
415
416     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
417         return 0
418     fi
419     local srcdir="$1"; shift
420     cd "$srcdir"
421     local license_path="$1"; shift
422     local version="$(rails_package_version "$pkgname" "$srcdir")"
423     echo "$version" >package-build.version
424     local scripts_dir="$(mktemp --tmpdir -d "$pkgname-XXXXXXXX.scripts")" && \
425     (
426         set -e
427         _build_rails_package_scripts "$pkgname" "$scripts_dir"
428         cd "$srcdir"
429         mkdir -p tmp
430         git rev-parse HEAD >git-commit.version
431         bundle package --all
432     )
433     if [[ 0 != "$?" ]] || ! cd "$WORKSPACE/packages/$TARGET"; then
434         echo "ERROR: $pkgname package prep failed" >&2
435         rm -rf "$scripts_dir"
436         EXITCODE=1
437         return 1
438     fi
439     local railsdir="/var/www/${pkgname%-server}/current"
440     local -a pos_args=("$srcdir/=$railsdir" "$pkgname" dir "$version")
441     local license_arg="$license_path=$railsdir/$(basename "$license_path")"
442     local -a switches=(--after-install "$scripts_dir/postinst"
443                        --before-remove "$scripts_dir/prerm"
444                        --after-remove "$scripts_dir/postrm")
445     if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
446         switches+=(--iteration $RAILS_PACKAGE_ITERATION)
447     fi
448     # For some reason fpm excludes need to not start with /.
449     local exclude_root="${railsdir#/}"
450     local -a exclude_list=(tmp log coverage Capfile\* \
451                            config/deploy\* config/application.yml)
452     # for arvados-workbench, we need to have the (dummy) config/database.yml in the package
453     if  [[ "$pkgname" != "arvados-workbench" ]]; then
454       exclude_list+=('config/database.yml')
455     fi
456     for exclude in ${exclude_list[@]}; do
457         switches+=(-x "$exclude_root/$exclude")
458     done
459     fpm_build "${srcdir}" "${pos_args[@]}" "${switches[@]}" \
460               -x "$exclude_root/vendor/cache-*" \
461               -x "$exclude_root/vendor/bundle" "$@" "$license_arg"
462     rm -rf "$scripts_dir"
463 }
464
465 # Build python packages with a virtualenv built-in
466 fpm_build_virtualenv () {
467   PKG=$1
468   shift
469   PKG_DIR=$1
470   shift
471   PACKAGE_TYPE=${1:-python}
472   shift
473   native_arch="amd64"
474   if [[ "$HOSTTYPE" == "aarch64" ]]; then
475     native_arch="arm64"
476   fi
477
478   if [[ -n "$ONLY_ARCH" ]] && [[ "$ONLY_ARCH" == "$native_arch" ]]; then
479       fpm_build_virtualenv_worker "$PKG" "$PKG_DIR" "$PACKAGE_TYPE" "$ONLY_ARCH"
480   elif [[ -z "$ONLY_ARCH" ]]; then
481     for arch in $native_arch; do
482       fpm_build_virtualenv_worker "$PKG" "$PKG_DIR" "$PACKAGE_TYPE" "$arch"
483     done
484   else
485     echo "Error: no cross compilation support for Python yet, can not build $PKG for $ONLY_ARCH"
486   fi
487 }
488
489 # Build python packages with a virtualenv built-in
490 fpm_build_virtualenv_worker () {
491   PKG=$1
492   shift
493   PKG_DIR=$1
494   shift
495   PACKAGE_TYPE=${1:-python}
496   shift
497   arch=${1:-amd64}
498   shift
499
500   # Set up
501   STDOUT_IF_DEBUG=/dev/null
502   STDERR_IF_DEBUG=/dev/null
503   DASHQ_UNLESS_DEBUG=-q
504   if [[ "$DEBUG" != "0" ]]; then
505       STDOUT_IF_DEBUG=/dev/stdout
506       STDERR_IF_DEBUG=/dev/stderr
507       DASHQ_UNLESS_DEBUG=
508   fi
509   if [[ "$ARVADOS_BUILDING_ITERATION" == "" ]]; then
510     ARVADOS_BUILDING_ITERATION=1
511   fi
512
513   local python=""
514   case "$PACKAGE_TYPE" in
515     python3)
516         python=python3
517         pip=pip3
518         PACKAGE_PREFIX=$PYTHON3_PKG_PREFIX
519         ;;
520   esac
521
522   if [[ "$PKG" != "arvados-docker-cleaner" ]]; then
523     PYTHON_PKG=$PACKAGE_PREFIX-$PKG
524   else
525     # Exception to our package naming convention
526     PYTHON_PKG=$PKG
527   fi
528
529   # arvados-python-client sdist should always be built, to be available
530   # for other dependent packages.
531   if [[ -n "$ONLY_BUILD" ]] && [[ "arvados-python-client" != "$PKG" ]] && [[ "$PYTHON_PKG" != "$ONLY_BUILD" ]] && [[ "$PKG" != "$ONLY_BUILD" ]]; then
532     return 0
533   fi
534
535   cd $WORKSPACE/$PKG_DIR
536
537   rm -rf dist/*
538
539   # Get the latest setuptools
540   if ! $pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'; then
541     echo "Error, unable to upgrade setuptools with"
542     echo "  $pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'"
543     exit 1
544   fi
545   # filter a useless warning (when building the cwltest package) from the stderr output
546   if ! $python setup.py $DASHQ_UNLESS_DEBUG sdist 2> >(grep -v 'warning: no previously-included files matching'); then
547     echo "Error, unable to run $python setup.py sdist for $PKG"
548     exit 1
549   fi
550
551   PACKAGE_PATH=`(cd dist; ls *tar.gz)`
552
553   if [[ "arvados-python-client" == "$PKG" ]]; then
554     PYSDK_PATH=`pwd`/dist/
555   fi
556
557   if [[ -n "$ONLY_BUILD" ]] && [[ "$PYTHON_PKG" != "$ONLY_BUILD" ]] && [[ "$PKG" != "$ONLY_BUILD" ]]; then
558     return 0
559   fi
560
561   # Determine the package version from the generated sdist archive
562   if [[ -n "$ARVADOS_BUILDING_VERSION" ]] ; then
563       UNFILTERED_PYTHON_VERSION=$ARVADOS_BUILDING_VERSION
564       PYTHON_VERSION=$(echo -n $ARVADOS_BUILDING_VERSION | sed s/~dev/.dev/g | sed s/~rc/rc/g)
565   else
566       PYTHON_VERSION=$(awk '($1 == "Version:"){print $2}' *.egg-info/PKG-INFO)
567       UNFILTERED_PYTHON_VERSION=$(echo -n $PYTHON_VERSION | sed s/\.dev/~dev/g |sed 's/\([0-9]\)rc/\1~rc/g')
568   fi
569
570   # See if we actually need to build this package; does it exist already?
571   # We can't do this earlier than here, because we need PYTHON_VERSION...
572   # This isn't so bad; the sdist call above is pretty quick compared to
573   # the invocation of virtualenv and fpm, below.
574   if ! test_package_presence "$PYTHON_PKG" "$UNFILTERED_PYTHON_VERSION" "$PACKAGE_TYPE" "$ARVADOS_BUILDING_ITERATION" "$arch"; then
575     return 0
576   fi
577
578   echo "Building $FORMAT ($arch) package for $PKG from $PKG_DIR"
579
580   # Package the sdist in a virtualenv
581   echo "Creating virtualenv..."
582
583   cd dist
584
585   rm -rf build
586   rm -f $PYTHON_PKG*deb
587   echo "virtualenv version: `virtualenv --version`"
588   virtualenv_command="virtualenv --python `which $python` $DASHQ_UNLESS_DEBUG build/usr/share/$python/dist/$PYTHON_PKG"
589
590   if ! $virtualenv_command; then
591     echo "Error, unable to run"
592     echo "  $virtualenv_command"
593     exit 1
594   fi
595
596   if ! build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U pip; then
597     echo "Error, unable to upgrade pip with"
598     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U pip"
599     exit 1
600   fi
601   echo "pip version:        `build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip --version`"
602
603   if ! build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'; then
604     echo "Error, unable to upgrade setuptools with"
605     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'"
606     exit 1
607   fi
608   echo "setuptools version: `build/usr/share/$python/dist/$PYTHON_PKG/bin/$python -c 'import setuptools; print(setuptools.__version__)'`"
609
610   if ! build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U wheel; then
611     echo "Error, unable to upgrade wheel with"
612     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U wheel"
613     exit 1
614   fi
615   echo "wheel version:      `build/usr/share/$python/dist/$PYTHON_PKG/bin/wheel version`"
616
617   if [[ "$TARGET" != "centos7" ]] || [[ "$PYTHON_PKG" != "python-arvados-fuse" ]]; then
618     build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -f $PYSDK_PATH $PACKAGE_PATH
619   else
620     # centos7 needs these special tweaks to install python-arvados-fuse
621     build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG docutils
622     PYCURL_SSL_LIBRARY=nss build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -f $PYSDK_PATH $PACKAGE_PATH
623   fi
624
625   if [[ "$?" != "0" ]]; then
626     echo "Error, unable to run"
627     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -f $PYSDK_PATH $PACKAGE_PATH"
628     exit 1
629   fi
630
631   cd build/usr/share/$python/dist/$PYTHON_PKG/
632
633   # Replace the shebang lines in all python scripts, and handle the activate
634   # scripts too. This is a functional replacement of the 237 line
635   # virtualenv_tools.py script that doesn't work in python3 without serious
636   # patching, minus the parts we don't need (modifying pyc files, etc).
637   for binfile in `ls bin/`; do
638     if ! file --mime bin/$binfile |grep -q binary; then
639       # Not a binary file
640       if [[ "$binfile" =~ ^activate(.csh|.fish|)$ ]]; then
641         # these 'activate' scripts need special treatment
642         sed -i "s/VIRTUAL_ENV=\".*\"/VIRTUAL_ENV=\"\/usr\/share\/$python\/dist\/$PYTHON_PKG\"/" bin/$binfile
643         sed -i "s/VIRTUAL_ENV \".*\"/VIRTUAL_ENV \"\/usr\/share\/$python\/dist\/$PYTHON_PKG\"/" bin/$binfile
644       else
645         if grep -q -E '^#!.*/bin/python\d?' bin/$binfile; then
646           # Replace shebang line
647           sed -i "1 s/^.*$/#!\/usr\/share\/$python\/dist\/$PYTHON_PKG\/bin\/python/" bin/$binfile
648         fi
649       fi
650     fi
651   done
652
653   cd - >$STDOUT_IF_DEBUG
654
655   find build -iname '*.pyc' -exec rm {} \;
656   find build -iname '*.pyo' -exec rm {} \;
657
658   # Finally, generate the package
659   echo "Creating package..."
660
661   declare -a COMMAND_ARR=("fpm" "-s" "dir" "-t" "$FORMAT")
662
663   if [[ "${arch}" != "amd64" ]]; then
664     COMMAND_ARR+=("-a${arch}")
665   fi
666
667   if [[ "$MAINTAINER" != "" ]]; then
668     COMMAND_ARR+=('--maintainer' "$MAINTAINER")
669   fi
670
671   if [[ "$VENDOR" != "" ]]; then
672     COMMAND_ARR+=('--vendor' "$VENDOR")
673   fi
674
675   COMMAND_ARR+=('--url' 'https://arvados.org')
676
677   # Get description
678   DESCRIPTION=`grep '\sdescription' $WORKSPACE/$PKG_DIR/setup.py|cut -f2 -d=|sed -e "s/[',\\"]//g"`
679   COMMAND_ARR+=('--description' "$DESCRIPTION")
680
681   # Get license string
682   LICENSE_STRING=`grep license $WORKSPACE/$PKG_DIR/setup.py|cut -f2 -d=|sed -e "s/[',\\"]//g"`
683   COMMAND_ARR+=('--license' "$LICENSE_STRING")
684
685   if [[ "$FORMAT" == "rpm" ]]; then
686     # Make sure to conflict with the old rh-python36 packages we used to publish
687     COMMAND_ARR+=('--conflicts' "rh-python36-python-$PKG")
688   fi
689
690   if [[ "$DEBUG" != "0" ]]; then
691     COMMAND_ARR+=('--verbose' '--log' 'info')
692   fi
693
694   COMMAND_ARR+=('-v' $(echo -n "$PYTHON_VERSION" | sed s/.dev/~dev/g | sed s/rc/~rc/g))
695   COMMAND_ARR+=('--iteration' "$ARVADOS_BUILDING_ITERATION")
696   COMMAND_ARR+=('-n' "$PYTHON_PKG")
697   COMMAND_ARR+=('-C' "build")
698
699   systemd_unit="$WORKSPACE/$PKG_DIR/$PKG.service"
700   if [[ -e "${systemd_unit}" ]]; then
701     COMMAND_ARR+=('--after-install' "${WORKSPACE}/build/go-python-package-scripts/postinst")
702     COMMAND_ARR+=('--before-remove' "${WORKSPACE}/build/go-python-package-scripts/prerm")
703   fi
704
705   COMMAND_ARR+=('--depends' "$PYTHON3_PACKAGE")
706
707   # avoid warning
708   COMMAND_ARR+=('--deb-no-default-config-files')
709
710   # Append --depends X and other arguments specified by fpm-info.sh in
711   # the package source dir. These are added last so they can override
712   # the arguments added by this script.
713   declare -a fpm_args=()
714   declare -a fpm_depends=()
715
716   fpminfo="$WORKSPACE/$PKG_DIR/fpm-info.sh"
717   if [[ -e "$fpminfo" ]]; then
718     echo "Loading fpm overrides from $fpminfo"
719     if ! source "$fpminfo"; then
720       echo "Error, unable to source $WORKSPACE/$PKG_DIR/fpm-info.sh for $PKG"
721       exit 1
722     fi
723   fi
724
725   for i in "${fpm_depends[@]}"; do
726     COMMAND_ARR+=('--depends' "$i")
727   done
728
729   for i in "${fpm_depends[@]}"; do
730     COMMAND_ARR+=('--replaces' "python-$PKG")
731   done
732
733   # make sure the systemd service file ends up in the right place
734   # used by arvados-docker-cleaner
735   if [[ -e "${systemd_unit}" ]]; then
736     COMMAND_ARR+=("usr/share/$python/dist/$PKG/share/doc/$PKG/$PKG.service=/lib/systemd/system/$PKG.service")
737   fi
738
739   COMMAND_ARR+=("${fpm_args[@]}")
740
741   # Make sure to install all our package binaries in /usr/bin.
742   # We have to walk $WORKSPACE/$PKG_DIR/bin rather than
743   # $WORKSPACE/build/usr/share/$python/dist/$PYTHON_PKG/bin/ to get the list
744   # because the latter also includes all the python binaries for the virtualenv.
745   # We have to take the copies of our binaries from the latter directory, though,
746   # because those are the ones we rewrote the shebang line of, above.
747   if [[ -e "$WORKSPACE/$PKG_DIR/bin" ]]; then
748     for binary in `ls $WORKSPACE/$PKG_DIR/bin`; do
749       COMMAND_ARR+=("usr/share/$python/dist/$PYTHON_PKG/bin/$binary=/usr/bin/")
750     done
751   fi
752
753   # the python3-arvados-cwl-runner package comes with cwltool, expose that version
754   if [[ -e "$WORKSPACE/$PKG_DIR/dist/build/usr/share/$python/dist/$PYTHON_PKG/bin/cwltool" ]]; then
755     COMMAND_ARR+=("usr/share/$python/dist/$PYTHON_PKG/bin/cwltool=/usr/bin/")
756   fi
757
758   COMMAND_ARR+=(".")
759
760   debug_echo -e "\n${COMMAND_ARR[@]}\n"
761
762   FPM_RESULTS=$("${COMMAND_ARR[@]}")
763   FPM_EXIT_CODE=$?
764
765   # if something went wrong and debug is off, print out the fpm command that errored
766   if ! fpm_verify $FPM_EXIT_CODE $FPM_RESULTS && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
767     echo "fpm returned an error executing the command:"
768     echo
769     echo -e "\n${COMMAND_ARR[@]}\n"
770   else
771     echo `ls *$FORMAT`
772     mv $WORKSPACE/$PKG_DIR/dist/*$FORMAT $WORKSPACE/packages/$TARGET/
773   fi
774   echo
775 }
776
777 # build_metapackage builds meta packages that help with the python to python 3 package migration
778 build_metapackage() {
779   # base package name (e.g. arvados-python-client)
780   BASE_NAME=$1
781   shift
782   PKG_DIR=$1
783   shift
784
785   if [[ -n "$ONLY_BUILD" ]] && [[ "python-$BASE_NAME" != "$ONLY_BUILD" ]]; then
786     return 0
787   fi
788
789   if [[ "$ARVADOS_BUILDING_ITERATION" == "" ]]; then
790     ARVADOS_BUILDING_ITERATION=1
791   fi
792
793   if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
794     cd $WORKSPACE/$PKG_DIR
795     pwd
796     rm -rf dist/*
797
798     # Get the latest setuptools
799     if ! pip3 install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'; then
800       echo "Error, unable to upgrade setuptools with XY"
801       echo "  pip3 install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'"
802       exit 1
803     fi
804     # filter a useless warning (when building the cwltest package) from the stderr output
805     if ! python3 setup.py $DASHQ_UNLESS_DEBUG sdist 2> >(grep -v 'warning: no previously-included files matching'); then
806       echo "Error, unable to run python3 setup.py sdist for $PKG"
807       exit 1
808     fi
809
810     PYTHON_VERSION=$(awk '($1 == "Version:"){print $2}' *.egg-info/PKG-INFO)
811     UNFILTERED_PYTHON_VERSION=$(echo -n $PYTHON_VERSION | sed s/\.dev/~dev/g |sed 's/\([0-9]\)rc/\1~rc/g')
812
813   else
814     UNFILTERED_PYTHON_VERSION=$ARVADOS_BUILDING_VERSION
815     PYTHON_VERSION=$(echo -n $ARVADOS_BUILDING_VERSION | sed s/~dev/.dev/g | sed s/~rc/rc/g)
816   fi
817
818   cd - >$STDOUT_IF_DEBUG
819   if [[ -d "$BASE_NAME" ]]; then
820     rm -rf $BASE_NAME
821   fi
822   mkdir $BASE_NAME
823   cd $BASE_NAME
824
825   if [[ "$FORMAT" == "deb" ]]; then
826     cat >ns-control <<EOF
827 Section: misc
828 Priority: optional
829 Standards-Version: 3.9.2
830
831 Package: python-${BASE_NAME}
832 Version: ${PYTHON_VERSION}-${ARVADOS_BUILDING_ITERATION}
833 Maintainer: Arvados Package Maintainers <packaging@arvados.org>
834 Depends: python3-${BASE_NAME}
835 Description: metapackage to ease the upgrade to the Pyhon 3 version of ${BASE_NAME}
836  This package is a metapackage that will automatically install the new version of
837  ${BASE_NAME} which is Python 3 based and has a different name.
838 EOF
839
840     /usr/bin/equivs-build ns-control
841     if [[ $? -ne 0 ]]; then
842       echo "Error running 'equivs-build ns-control', is the 'equivs' package installed?"
843       return 1
844     fi
845   elif [[ "$FORMAT" == "rpm" ]]; then
846     cat >meta.spec <<EOF
847 Summary: metapackage to ease the upgrade to the Python 3 version of ${BASE_NAME}
848 Name: python-${BASE_NAME}
849 Version: ${PYTHON_VERSION}
850 Release: ${ARVADOS_BUILDING_ITERATION}
851 License: distributable
852
853 Requires: python3-${BASE_NAME}
854
855 %description
856 This package is a metapackage that will automatically install the new version of
857 python-${BASE_NAME} which is Python 3 based and has a different name.
858
859 %prep
860
861 %build
862
863 %clean
864
865 %install
866
867 %post
868
869 %files
870
871
872 %changelog
873 * Mon Apr 12 2021 Arvados Package Maintainers <packaging@arvados.org>
874 - initial release
875 EOF
876
877     /usr/bin/rpmbuild -ba meta.spec
878     if [[ $? -ne 0 ]]; then
879       echo "Error running 'rpmbuild -ba meta.spec', is the 'rpm-build' package installed?"
880       return 1
881     else
882       mv /root/rpmbuild/RPMS/x86_64/python-${BASE_NAME}*.${FORMAT} .
883       if [[ $? -ne 0 ]]; then
884         echo "Error finding rpm file output of 'rpmbuild -ba meta.spec'"
885         return 1
886       fi
887     fi
888   else
889     echo "Unknown format"
890     return 1
891   fi
892
893   if [[ $EXITCODE -ne 0 ]]; then
894     return 1
895   else
896     echo `ls *$FORMAT`
897     mv *$FORMAT $WORKSPACE/packages/$TARGET/
898   fi
899
900   # clean up
901   cd - >$STDOUT_IF_DEBUG
902   if [[ -d "$BASE_NAME" ]]; then
903     rm -rf $BASE_NAME
904   fi
905 }
906
907 # Build packages for everything
908 fpm_build () {
909   # Source dir where fpm-info.sh (if any) will be found.
910   SRC_DIR=$1
911   shift
912   # The package source.  Depending on the source type, this can be a
913   # path, or the name of the package in an upstream repository (e.g.,
914   # pip).
915   PACKAGE=$1
916   shift
917   # The name of the package to build.
918   PACKAGE_NAME=$1
919   shift
920   # The type of source package.  Passed to fpm -s.  Default "dir".
921   PACKAGE_TYPE=${1:-dir}
922   shift
923   # Optional: the package version number.  Passed to fpm -v.
924   VERSION=$1
925   shift
926
927   if [[ -n "$ONLY_BUILD" ]] && [[ "$PACKAGE_NAME" != "$ONLY_BUILD" ]] && [[ "$PACKAGE" != "$ONLY_BUILD" ]] ; then
928     # arvados-workbench depends on arvados-server at build time, so even when
929     # only arvados-workbench is being built, we need to build arvados-server too
930     if [[ "$PACKAGE_NAME" != "arvados-server" ]] || [[ "$ONLY_BUILD" != "arvados-workbench" ]]; then
931       return 0
932     fi
933   fi
934
935   local default_iteration_value="$(default_iteration "$PACKAGE" "$VERSION" "$PACKAGE_TYPE")"
936
937   declare -a COMMAND_ARR=("fpm" "-s" "$PACKAGE_TYPE" "-t" "$FORMAT")
938   if [ python = "$PACKAGE_TYPE" ] && [ deb = "$FORMAT" ]; then
939       # Dependencies are built from setup.py.  Since setup.py will never
940       # refer to Debian package iterations, it doesn't make sense to
941       # enforce those in the .deb dependencies.
942       COMMAND_ARR+=(--deb-ignore-iteration-in-dependencies)
943   fi
944
945   if [[ "$DEBUG" != "0" ]]; then
946     COMMAND_ARR+=('--verbose' '--log' 'info')
947   fi
948
949   if [[ -n "$PACKAGE_NAME" ]]; then
950     COMMAND_ARR+=('-n' "$PACKAGE_NAME")
951   fi
952
953   if [[ "$MAINTAINER" != "" ]]; then
954     COMMAND_ARR+=('--maintainer' "$MAINTAINER")
955   fi
956
957   if [[ "$VENDOR" != "" ]]; then
958     COMMAND_ARR+=('--vendor' "$VENDOR")
959   fi
960
961   if [[ "$VERSION" != "" ]]; then
962     COMMAND_ARR+=('-v' "$VERSION")
963   fi
964   if [[ -n "$default_iteration_value" ]]; then
965       # We can always add an --iteration here.  If another one is specified in $@,
966       # that will take precedence, as desired.
967       COMMAND_ARR+=(--iteration "$default_iteration_value")
968   fi
969
970   # Append --depends X and other arguments specified by fpm-info.sh in
971   # the package source dir. These are added last so they can override
972   # the arguments added by this script.
973   declare -a fpm_args=()
974   declare -a build_depends=()
975   declare -a fpm_depends=()
976   declare -a fpm_conflicts=()
977   declare -a fpm_exclude=()
978   if [[ ! -d "$SRC_DIR" ]]; then
979       echo >&2 "BUG: looking in wrong dir for fpm-info.sh: $pkgdir"
980       exit 1
981   fi
982   fpminfo="${SRC_DIR}/fpm-info.sh"
983   if [[ -e "$fpminfo" ]]; then
984       debug_echo "Loading fpm overrides from $fpminfo"
985       source "$fpminfo"
986   fi
987   for pkg in "${build_depends[@]}"; do
988       if [[ $TARGET =~ debian|ubuntu ]]; then
989           pkg_deb=$(ls "$WORKSPACE/packages/$TARGET/$pkg_"*.deb | sort -rg | awk 'NR==1')
990           if [[ -e $pkg_deb ]]; then
991               echo "Installing build_dep $pkg from $pkg_deb"
992               dpkg -i "$pkg_deb"
993           else
994               echo "Attemping to install build_dep $pkg using apt-get"
995               apt-get install -y "$pkg"
996           fi
997           apt-get -y -f install
998       else
999           pkg_rpm=$(ls "$WORKSPACE/packages/$TARGET/$pkg"-[0-9]*.rpm | sort -rg | awk 'NR==1')
1000           if [[ -e $pkg_rpm ]]; then
1001               echo "Installing build_dep $pkg from $pkg_rpm"
1002               rpm -i "$pkg_rpm"
1003           else
1004               echo "Attemping to install build_dep $pkg"
1005               rpm -i "$pkg"
1006           fi
1007       fi
1008   done
1009   for i in "${fpm_depends[@]}"; do
1010     COMMAND_ARR+=('--depends' "$i")
1011   done
1012   for i in "${fpm_conflicts[@]}"; do
1013     COMMAND_ARR+=('--conflicts' "$i")
1014   done
1015   for i in "${fpm_exclude[@]}"; do
1016     COMMAND_ARR+=('--exclude' "$i")
1017   done
1018
1019   COMMAND_ARR+=("${fpm_args[@]}")
1020
1021   # Append remaining function arguments directly to fpm's command line.
1022   for i; do
1023     COMMAND_ARR+=("$i")
1024   done
1025
1026   COMMAND_ARR+=("$PACKAGE")
1027
1028   debug_echo -e "\n${COMMAND_ARR[@]}\n"
1029
1030   FPM_RESULTS=$("${COMMAND_ARR[@]}")
1031   FPM_EXIT_CODE=$?
1032
1033   fpm_verify $FPM_EXIT_CODE $FPM_RESULTS
1034
1035   # if something went wrong and debug is off, print out the fpm command that errored
1036   if [[ 0 -ne $? ]] && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
1037     echo -e "\n${COMMAND_ARR[@]}\n"
1038   fi
1039 }
1040
1041 # verify build results
1042 fpm_verify () {
1043   FPM_EXIT_CODE=$1
1044   shift
1045   FPM_RESULTS=$@
1046
1047   FPM_PACKAGE_NAME=''
1048   if [[ $FPM_RESULTS =~ ([A-Za-z0-9_\.-]*\.)(deb|rpm) ]]; then
1049     FPM_PACKAGE_NAME=${BASH_REMATCH[1]}${BASH_REMATCH[2]}
1050   fi
1051
1052   if [[ "$FPM_PACKAGE_NAME" == "" ]]; then
1053     EXITCODE=1
1054     echo
1055     echo "Error: $PACKAGE: Unable to figure out package name from fpm results:"
1056     echo
1057     echo $FPM_RESULTS
1058     echo
1059     return 1
1060   elif [[ "$FPM_RESULTS" =~ "File already exists" ]]; then
1061     echo "Package $FPM_PACKAGE_NAME exists, not rebuilding"
1062     return 0
1063   elif [[ 0 -ne "$FPM_EXIT_CODE" ]]; then
1064     EXITCODE=1
1065     echo "Error building package for $1:\n $FPM_RESULTS"
1066     return 1
1067   fi
1068 }
1069
1070 install_package() {
1071   PACKAGES=$@
1072   if [[ "$FORMAT" == "deb" ]]; then
1073     $SUDO apt-get install $PACKAGES --yes
1074   elif [[ "$FORMAT" == "rpm" ]]; then
1075     $SUDO yum -q -y install $PACKAGES
1076   fi
1077 }
1078
1079 title() {
1080     printf '%s %s\n' "=======" "$1"
1081 }
1082
1083 checkexit() {
1084     if [[ "$1" != "0" ]]; then
1085         title "$2 -- FAILED"
1086         failures+=("$2 (`timer`)")
1087     else
1088         successes+=("$2 (`timer`)")
1089     fi
1090 }
1091
1092 timer_reset() {
1093     t0=$SECONDS
1094 }
1095
1096 timer() {
1097     if [[ -n "$t0" ]]; then
1098         echo -n "$(($SECONDS - $t0))s"
1099     fi
1100 }
1101
1102 report_outcomes() {
1103     for x in "${successes[@]}"
1104     do
1105         echo "Pass: $x"
1106     done
1107
1108     if [[ ${#failures[@]} == 0 ]]
1109     then
1110         if [[ ${#successes[@]} != 0 ]]; then
1111            echo "All test suites passed."
1112         fi
1113     else
1114         echo "Failures (${#failures[@]}):"
1115         for x in "${failures[@]}"
1116         do
1117             echo "Fail: $x"
1118         done
1119     fi
1120 }