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