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