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