13200:fix python gittagers version with latest git tag and timestamp
[arvados.git] / build / run-library.sh
1   #!/bin/bash
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_easy_install() {
24     for version_suffix in "$@"; do
25         if "easy_install$version_suffix" --version >/dev/null 2>&1; then
26             echo "easy_install$version_suffix"
27             return 0
28         fi
29     done
30     cat >&2 <<EOF
31 $helpmessage
32
33 Error: easy_install$1 (from Python setuptools module) not found
34
35 EOF
36     exit 1
37 }
38
39 format_last_commit_here() {
40     local format="$1"; shift
41     TZ=UTC git log -n1 --first-parent "--format=format:$format" .
42 }
43
44 version_from_git() {
45     # Output the version being built, or if we're building a
46     # dev/prerelease, output a version number based on the git log for
47     # the current working directory.
48     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
49         echo "$ARVADOS_BUILDING_VERSION"
50         return
51     fi
52
53     ARVADOS_BUILDING_VERSION=`git describe --abbrev=0`
54     local git_ts 
55     if [[ -n "$1" ]] ; then
56         prefix="$1"
57     else
58         prefix="0.1"
59     fi
60
61     declare $(format_last_commit_here "git_ts=%ct")
62     ARVADOS_BUILDING_VERSION="$ARVADOS_BUILDING_VERSION.$(date -ud "@$git_ts" +%Y%m%d%H%M%S)"
63     echo "$ARVADOS_BUILDING_VERSION"
64 }
65
66 nohash_version_from_git() {
67     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
68         echo "$ARVADOS_BUILDING_VERSION"
69         return
70     fi
71     version_from_git $1 | cut -d. -f1-3
72 }
73
74 timestamp_from_git() {
75     format_last_commit_here "%ct"
76 }
77
78 handle_python_package () {
79   # This function assumes the current working directory is the python package directory
80   if [ -n "$(find dist -name "*-$ARVADOS_BUILDING_VERSION.$(date -ud "@$git_ts" +%Y%m%d%H%M%S).tar.gz" -print -quit)" ]; then
81     # This package doesn't need rebuilding.
82     return
83   fi
84   # Make sure only to use sdist - that's the only format pip can deal with (sigh)
85   python setup.py $DASHQ_UNLESS_DEBUG sdist
86 }
87
88 handle_ruby_gem() {
89     local gem_name="$1"; shift
90     local gem_version="$(nohash_version_from_git)"
91     local gem_src_dir="$(pwd)"
92
93     if [[ -n "$ONLY_BUILD" ]] && [[ "$gem_name" != "$ONLY_BUILD" ]] ; then
94         return 0
95     fi
96
97     if ! [[ -e "${gem_name}-${gem_version}.gem" ]]; then
98         find -maxdepth 1 -name "${gem_name}-*.gem" -delete
99
100         # -q appears to be broken in gem version 2.2.2
101         $GEM build "$gem_name.gemspec" $DASHQ_UNLESS_DEBUG >"$STDOUT_IF_DEBUG" 2>"$STDERR_IF_DEBUG"
102     fi
103 }
104
105 # Usage: package_go_binary services/foo arvados-foo "Compute foo to arbitrary precision"
106 package_go_binary() {
107     local src_path="$1"; shift
108     local prog="$1"; shift
109     local description="$1"; shift
110     local license_file="${1:-agpl-3.0.txt}"; shift
111
112     if [[ -n "$ONLY_BUILD" ]] && [[ "$prog" != "$ONLY_BUILD" ]] ; then
113         return 0
114     fi
115
116     debug_echo "package_go_binary $src_path as $prog"
117
118     local basename="${src_path##*/}"
119
120     mkdir -p "$GOPATH/src/git.curoverse.com"
121     ln -sfn "$WORKSPACE" "$GOPATH/src/git.curoverse.com/arvados.git"
122     (cd "$GOPATH/src/git.curoverse.com/arvados.git" && "$GOPATH/bin/govendor" sync -v)
123
124     cd "$GOPATH/src/git.curoverse.com/arvados.git/$src_path"
125     local version="$(version_from_git)"
126     local timestamp="$(timestamp_from_git)"
127
128     # Update the version number and build a new package if the vendor
129     # bundle has changed, or the command imports anything from the
130     # Arvados SDK and the SDK has changed.
131     declare -a checkdirs=(vendor)
132     if grep -qr git.curoverse.com/arvados .; then
133         checkdirs+=(sdk/go)
134         if [[ "$prog" -eq "crunch-dispatch-slurm" ]]; then
135           checkdirs+=(lib/dispatchcloud)
136         fi
137     fi
138     for dir in ${checkdirs[@]}; do
139         cd "$GOPATH/src/git.curoverse.com/arvados.git/$dir"
140         ts="$(timestamp_from_git)"
141         if [[ "$ts" -gt "$timestamp" ]]; then
142             version=$(version_from_git)
143             timestamp="$ts"
144         fi
145     done
146
147     cd $WORKSPACE/packages/$TARGET
148     test_package_presence $prog $version go
149
150     if [[ "$?" != "0" ]]; then
151       return 1
152     fi
153
154     go get -ldflags "-X main.version=${version}" "git.curoverse.com/arvados.git/$src_path"
155
156     local -a switches=()
157     systemd_unit="$WORKSPACE/${src_path}/${prog}.service"
158     if [[ -e "${systemd_unit}" ]]; then
159         switches+=(
160             --after-install "${WORKSPACE}/build/go-python-package-scripts/postinst"
161             --before-remove "${WORKSPACE}/build/go-python-package-scripts/prerm"
162             "${systemd_unit}=/lib/systemd/system/${prog}.service")
163     fi
164     switches+=("$WORKSPACE/${license_file}=/usr/share/doc/$prog/${license_file}")
165
166     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[@]}"
167 }
168
169 default_iteration() {
170     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
171         echo "$ARVADOS_BUILDING_ITERATION"
172         return
173     fi
174     local package_name="$1"; shift
175     local package_version="$1"; shift
176     local package_type="$1"; shift
177     local iteration=1
178     if [[ $package_version =~ ^0\.1\.([0-9]{14})(\.|$) ]] && \
179            [[ ${BASH_REMATCH[1]} -le $LICENSE_PACKAGE_TS ]]; then
180         iteration=2
181     fi
182     if [[ $package_type =~ ^python ]]; then
183       # Fix --iteration for #9242.
184       iteration=2
185     fi
186     echo $iteration
187 }
188
189 _build_rails_package_scripts() {
190     local pkgname="$1"; shift
191     local destdir="$1"; shift
192     local srcdir="$RUN_BUILD_PACKAGES_PATH/rails-package-scripts"
193     for scriptname in postinst prerm postrm; do
194         cat "$srcdir/$pkgname.sh" "$srcdir/step2.sh" "$srcdir/$scriptname.sh" \
195             >"$destdir/$scriptname" || return $?
196     done
197 }
198
199 test_rails_package_presence() {
200   local pkgname="$1"; shift
201   local srcdir="$1"; shift
202
203   if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
204     return 1
205   fi
206
207   tmppwd=`pwd`
208
209   cd $srcdir
210
211   local version="$(version_from_git)"
212
213   cd $tmppwd
214
215   test_package_presence $pkgname $version rails "$RAILS_PACKAGE_ITERATION"
216 }
217
218 test_package_presence() {
219     local pkgname="$1"; shift
220     local version="$1"; shift
221     local pkgtype="$1"; shift
222     local iteration="$1"; shift
223     local arch="$1"; shift
224
225     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
226         return 1
227     fi
228
229     if [[ "$iteration" == "" ]]; then
230         iteration="$(default_iteration "$pkgname" "$version" "$pkgtype")"
231     fi
232
233     if [[ "$arch" == "" ]]; then
234       rpm_architecture="x86_64"
235       deb_architecture="amd64"
236
237       if [[ "$pkgtype" =~ ^(python|python3)$ ]]; then
238         rpm_architecture="noarch"
239         deb_architecture="all"
240       fi
241
242       if [[ "$pkgtype" =~ ^(src)$ ]]; then
243         rpm_architecture="noarch"
244         deb_architecture="all"
245       fi
246
247       # These python packages have binary components
248       if [[ "$pkgname" =~ (ruamel|ciso|pycrypto|pyyaml) ]]; then
249         rpm_architecture="x86_64"
250         deb_architecture="amd64"
251       fi
252     else
253       rpm_architecture=$arch
254       deb_architecture=$arch
255     fi
256
257     if [[ "$FORMAT" == "deb" ]]; then
258         local complete_pkgname="${pkgname}_$version${iteration:+-$iteration}_$deb_architecture.deb"
259     else
260         # rpm packages get iteration 1 if we don't supply one
261         iteration=${iteration:-1}
262         local complete_pkgname="$pkgname-$version-${iteration}.$rpm_architecture.rpm"
263     fi
264
265     # See if we can skip building the package, only if it already exists in the
266     # processed/ directory. If so, move it back to the packages directory to make
267     # sure it gets picked up by the test and/or upload steps.
268     if [[ -e "processed/$complete_pkgname" ]]; then
269       echo "Package $complete_pkgname exists, not rebuilding!"
270       mv processed/$complete_pkgname .
271       return 1
272     else
273       echo "Package $complete_pkgname not found, building"
274       return 0
275     fi
276 }
277
278 handle_rails_package() {
279     local pkgname="$1"; shift
280
281     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
282         return 0
283     fi
284     local srcdir="$1"; shift
285     cd "$srcdir"
286     local license_path="$1"; shift
287     local version="$(version_from_git)"
288     local scripts_dir="$(mktemp --tmpdir -d "$pkgname-XXXXXXXX.scripts")" && \
289     (
290         set -e
291         _build_rails_package_scripts "$pkgname" "$scripts_dir"
292         cd "$srcdir"
293         mkdir -p tmp
294         git rev-parse HEAD >git-commit.version
295         bundle package --all
296     )
297     if [[ 0 != "$?" ]] || ! cd "$WORKSPACE/packages/$TARGET"; then
298         echo "ERROR: $pkgname package prep failed" >&2
299         rm -rf "$scripts_dir"
300         EXITCODE=1
301         return 1
302     fi
303     local railsdir="/var/www/${pkgname%-server}/current"
304     local -a pos_args=("$srcdir/=$railsdir" "$pkgname" "Curoverse, Inc." dir "$version")
305     local license_arg="$license_path=$railsdir/$(basename "$license_path")"
306     local -a switches=(--after-install "$scripts_dir/postinst"
307                        --before-remove "$scripts_dir/prerm"
308                        --after-remove "$scripts_dir/postrm")
309     if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
310         switches+=(--iteration $RAILS_PACKAGE_ITERATION)
311     fi
312     # For some reason fpm excludes need to not start with /.
313     local exclude_root="${railsdir#/}"
314     # .git and packages are for the SSO server, which is built from its
315     # repository root.
316     local -a exclude_list=(.git packages tmp log coverage Capfile\* \
317                            config/deploy\* config/application.yml)
318     # for arvados-workbench, we need to have the (dummy) config/database.yml in the package
319     if  [[ "$pkgname" != "arvados-workbench" ]]; then
320       exclude_list+=('config/database.yml')
321     fi
322     for exclude in ${exclude_list[@]}; do
323         switches+=(-x "$exclude_root/$exclude")
324     done
325     fpm_build "${pos_args[@]}" "${switches[@]}" \
326               -x "$exclude_root/vendor/cache-*" \
327               -x "$exclude_root/vendor/bundle" "$@" "$license_arg"
328     rm -rf "$scripts_dir"
329 }
330
331 # Build packages for everything
332 fpm_build () {
333   # The package source.  Depending on the source type, this can be a
334   # path, or the name of the package in an upstream repository (e.g.,
335   # pip).
336   PACKAGE=$1
337   shift
338   # The name of the package to build.
339   PACKAGE_NAME=$1
340   shift
341   # Optional: the vendor of the package.  Should be "Curoverse, Inc." for
342   # packages of our own software.  Passed to fpm --vendor.
343   VENDOR=$1
344   shift
345   # The type of source package.  Passed to fpm -s.  Default "python".
346   PACKAGE_TYPE=${1:-python}
347   shift
348   # Optional: the package version number.  Passed to fpm -v.
349   VERSION=$1
350   shift
351
352   if [[ -n "$ONLY_BUILD" ]] && [[ "$PACKAGE_NAME" != "$ONLY_BUILD" ]] && [[ "$PACKAGE" != "$ONLY_BUILD" ]] ; then
353       return 0
354   fi
355
356   local default_iteration_value="$(default_iteration "$PACKAGE" "$VERSION" "$PACKAGE_TYPE")"
357   local python=""
358
359   case "$PACKAGE_TYPE" in
360       python)
361           # All Arvados Python2 packages depend on Python 2.7.
362           # Make sure we build with that for consistency.
363           python=python2.7
364           set -- "$@" --python-bin python2.7 \
365               --python-easyinstall "$EASY_INSTALL2" \
366               --python-package-name-prefix "$PYTHON2_PKG_PREFIX" \
367               --prefix "$PYTHON2_PREFIX" \
368               --python-install-lib "$PYTHON2_INSTALL_LIB" \
369               --python-install-data . \
370               --exclude "${PYTHON2_INSTALL_LIB#/}/tests" \
371               --depends "$PYTHON2_PACKAGE"
372           ;;
373       python3)
374           # fpm does not actually support a python3 package type.  Instead
375           # we recognize it as a convenience shortcut to add several
376           # necessary arguments to fpm's command line later, after we're
377           # done handling positional arguments.
378           PACKAGE_TYPE=python
379           python=python3
380           set -- "$@" --python-bin python3 \
381               --python-easyinstall "$EASY_INSTALL3" \
382               --python-package-name-prefix "$PYTHON3_PKG_PREFIX" \
383               --prefix "$PYTHON3_PREFIX" \
384               --python-install-lib "$PYTHON3_INSTALL_LIB" \
385               --python-install-data . \
386               --exclude "${PYTHON3_INSTALL_LIB#/}/tests" \
387               --depends "$PYTHON3_PACKAGE"
388           ;;
389   esac
390
391   declare -a COMMAND_ARR=("fpm" "--maintainer=Ward Vandewege <ward@curoverse.com>" "-s" "$PACKAGE_TYPE" "-t" "$FORMAT")
392   if [ python = "$PACKAGE_TYPE" ] && [ deb = "$FORMAT" ]; then
393       # Dependencies are built from setup.py.  Since setup.py will never
394       # refer to Debian package iterations, it doesn't make sense to
395       # enforce those in the .deb dependencies.
396       COMMAND_ARR+=(--deb-ignore-iteration-in-dependencies)
397   fi
398
399   # 12271 - As FPM-generated packages don't include scripts by default, the
400   # packages cleanup on upgrade depends on files being listed on the %files
401   # section in the generated SPEC files. To remove DIRECTORIES, they need to
402   # be listed in that sectiontoo, so we need to add this parameter to properly
403   # remove lingering dirs. But this only works for python2: if used on
404   # python33, it includes dirs like /opt/rh/python33 that belong to
405   # other packages.
406   if [[ "$FORMAT" = rpm ]] && [[ "$python" = python2.7 ]]; then
407     COMMAND_ARR+=('--rpm-auto-add-directories')
408   fi
409
410   if [[ "${DEBUG:-0}" != "0" ]]; then
411     COMMAND_ARR+=('--verbose' '--log' 'info')
412   fi
413
414   if [[ -n "$PACKAGE_NAME" ]]; then
415     COMMAND_ARR+=('-n' "$PACKAGE_NAME")
416   fi
417
418   if [[ "$VENDOR" != "" ]]; then
419     COMMAND_ARR+=('--vendor' "$VENDOR")
420   fi
421
422   if [[ "$VERSION" != "" ]]; then
423     COMMAND_ARR+=('-v' "$VERSION")
424   fi
425   if [[ -n "$default_iteration_value" ]]; then
426       # We can always add an --iteration here.  If another one is specified in $@,
427       # that will take precedence, as desired.
428       COMMAND_ARR+=(--iteration "$default_iteration_value")
429   fi
430
431   if [[ python = "$PACKAGE_TYPE" ]] && [[ -e "${PACKAGE}/${PACKAGE_NAME}.service" ]]
432   then
433       COMMAND_ARR+=(
434           --after-install "${WORKSPACE}/build/go-python-package-scripts/postinst"
435           --before-remove "${WORKSPACE}/build/go-python-package-scripts/prerm"
436       )
437   fi
438
439   # Append --depends X and other arguments specified by fpm-info.sh in
440   # the package source dir. These are added last so they can override
441   # the arguments added by this script.
442   declare -a fpm_args=()
443   declare -a build_depends=()
444   declare -a fpm_depends=()
445   declare -a fpm_exclude=()
446   declare -a fpm_dirs=(
447       # source dir part of 'dir' package ("/source=/dest" => "/source"):
448       "${PACKAGE%%=/*}"
449       # backports ("llfuse>=1.0" => "backports/python-llfuse")
450       "${WORKSPACE}/backports/${PACKAGE_TYPE}-${PACKAGE%%[<=>]*}")
451   if [[ -n "$PACKAGE_NAME" ]]; then
452       fpm_dirs+=("${WORKSPACE}/backports/${PACKAGE_NAME}")
453   fi
454   for pkgdir in "${fpm_dirs[@]}"; do
455       fpminfo="$pkgdir/fpm-info.sh"
456       if [[ -e "$fpminfo" ]]; then
457           debug_echo "Loading fpm overrides from $fpminfo"
458           source "$fpminfo"
459           break
460       fi
461   done
462   for pkg in "${build_depends[@]}"; do
463       if [[ $TARGET =~ debian|ubuntu ]]; then
464           pkg_deb=$(ls "$WORKSPACE/packages/$TARGET/$pkg_"*.deb | sort -rg | awk 'NR==1')
465           if [[ -e $pkg_deb ]]; then
466               echo "Installing build_dep $pkg from $pkg_deb"
467               dpkg -i "$pkg_deb"
468           else
469               echo "Attemping to install build_dep $pkg using apt-get"
470               apt-get install -y "$pkg"
471           fi
472           apt-get -y -f install
473       else
474           pkg_rpm=$(ls "$WORKSPACE/packages/$TARGET/$pkg"-[0-9]*.rpm | sort -rg | awk 'NR==1')
475           if [[ -e $pkg_rpm ]]; then
476               echo "Installing build_dep $pkg from $pkg_rpm"
477               rpm -i "$pkg_rpm"
478           else
479               echo "Attemping to install build_dep $pkg"
480               rpm -i "$pkg"
481           fi
482       fi
483   done
484   for i in "${fpm_depends[@]}"; do
485     COMMAND_ARR+=('--depends' "$i")
486   done
487   for i in "${fpm_exclude[@]}"; do
488     COMMAND_ARR+=('--exclude' "$i")
489   done
490
491   # Append remaining function arguments directly to fpm's command line.
492   for i; do
493     COMMAND_ARR+=("$i")
494   done
495
496   COMMAND_ARR+=("${fpm_args[@]}")
497
498   COMMAND_ARR+=("$PACKAGE")
499
500   debug_echo -e "\n${COMMAND_ARR[@]}\n"
501
502   FPM_RESULTS=$("${COMMAND_ARR[@]}")
503   FPM_EXIT_CODE=$?
504
505   fpm_verify $FPM_EXIT_CODE $FPM_RESULTS
506
507   # if something went wrong and debug is off, print out the fpm command that errored
508   if [[ 0 -ne $? ]] && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
509     echo -e "\n${COMMAND_ARR[@]}\n"
510   fi
511 }
512
513 # verify build results
514 fpm_verify () {
515   FPM_EXIT_CODE=$1
516   shift
517   FPM_RESULTS=$@
518
519   FPM_PACKAGE_NAME=''
520   if [[ $FPM_RESULTS =~ ([A-Za-z0-9_\.-]*\.)(deb|rpm) ]]; then
521     FPM_PACKAGE_NAME=${BASH_REMATCH[1]}${BASH_REMATCH[2]}
522   fi
523
524   if [[ "$FPM_PACKAGE_NAME" == "" ]]; then
525     EXITCODE=1
526     echo
527     echo "Error: $PACKAGE: Unable to figure out package name from fpm results:"
528     echo
529     echo $FPM_RESULTS
530     echo
531     return 1
532   elif [[ "$FPM_RESULTS" =~ "File already exists" ]]; then
533     echo "Package $FPM_PACKAGE_NAME exists, not rebuilding"
534     return 0
535   elif [[ 0 -ne "$FPM_EXIT_CODE" ]]; then
536     EXITCODE=1
537     echo "Error building package for $1:\n $FPM_RESULTS"
538     return 1
539   fi
540 }
541
542 install_package() {
543   PACKAGES=$@
544   if [[ "$FORMAT" == "deb" ]]; then
545     $SUDO apt-get install $PACKAGES --yes
546   elif [[ "$FORMAT" == "rpm" ]]; then
547     $SUDO yum -q -y install $PACKAGES
548   fi
549 }
550
551 title () {
552     txt="********** $1 **********"
553     printf "\n%*s%s\n\n" $((($COLUMNS-${#txt})/2)) "" "$txt"
554 }
555
556 checkexit() {
557     if [[ "$1" != "0" ]]; then
558         title "!!!!!! $2 FAILED !!!!!!"
559         failures+=("$2 (`timer`)")
560     else
561         successes+=("$2 (`timer`)")
562     fi
563 }
564
565 timer_reset() {
566     t0=$SECONDS
567 }
568
569 timer() {
570     echo -n "$(($SECONDS - $t0))s"
571 }
572
573 report_outcomes() {
574     for x in "${successes[@]}"
575     do
576         echo "Pass: $x"
577     done
578
579     if [[ ${#failures[@]} == 0 ]]
580     then
581         echo "All test suites passed."
582     else
583         echo "Failures (${#failures[@]}):"
584         for x in "${failures[@]}"
585         do
586             echo "Fail: $x"
587         done
588     fi
589 }