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