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