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