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