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