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