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