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