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