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