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