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