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