18874: Add workbench2 to package-building scripts.
[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 subdir="$1"; shift
52     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
53         echo "$ARVADOS_BUILDING_VERSION"
54         return
55     fi
56
57     local git_ts git_hash
58     declare $(format_last_commit_here "git_ts=%ct git_hash=%h" "$subdir")
59     ARVADOS_BUILDING_VERSION="$($WORKSPACE/build/version-at-commit.sh $git_hash)"
60     echo "$ARVADOS_BUILDING_VERSION"
61 }
62
63 nohash_version_from_git() {
64     local subdir="$1"; shift
65     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
66         echo "$ARVADOS_BUILDING_VERSION"
67         return
68     fi
69     version_from_git $subdir | 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 calculate_python_sdk_cwl_package_versions() {
78   python_sdk_version=$(cd sdk/python && python3 arvados_version.py)
79   cwl_runner_version=$(cd sdk/cwl && python3 arvados_version.py)
80 }
81
82 # Usage: get_native_arch
83 get_native_arch() {
84   # Only amd64 and aarch64 are supported at the moment
85   local native_arch=""
86   case "$HOSTTYPE" in
87     x86_64)
88       native_arch="amd64"
89       ;;
90     aarch64)
91       native_arch="arm64"
92       ;;
93     *)
94       echo "Error: architecture not supported"
95       exit 1
96       ;;
97   esac
98   echo $native_arch
99 }
100
101 handle_ruby_gem() {
102     local gem_name="$1"; shift
103     local gem_version="$(nohash_version_from_git)"
104     local gem_src_dir="$(pwd)"
105
106     if [[ -n "$ONLY_BUILD" ]] && [[ "$gem_name" != "$ONLY_BUILD" ]] ; then
107         return 0
108     fi
109
110     if ! [[ -e "${gem_name}-${gem_version}.gem" ]]; then
111         find -maxdepth 1 -name "${gem_name}-*.gem" -delete
112
113         # -q appears to be broken in gem version 2.2.2
114         $GEM build "$gem_name.gemspec" $DASHQ_UNLESS_DEBUG >"$STDOUT_IF_DEBUG" 2>"$STDERR_IF_DEBUG"
115     fi
116 }
117
118 # Usage: package_workbench2
119 package_workbench2() {
120     local pkgname=arvados-workbench2
121     local src=services/workbench2
122     local dst=/var/www/arvados-workbench2/workbench2
123     local description="Arvados Workbench 2"
124     local version="$(version_from_git)"
125     cd "$WORKSPACE/$src"
126     rm -rf ./build
127     VERSION="$VERSION" BUILD_NUMBER="$(default_iteration "$pkgname" "$version" yarn)" GIT_COMMIT="$(git rev-parse HEAD | head -c9)" yarn build
128     cd "$WORKSPACE/packages/$TARGET"
129     fpm_build "${WORKSPACE}/$src" "${WORKSPACE}/$src/build/=$dst" "$pkgname" dir "$version" \
130               --license="GNU Affero General Public License, version 3.0" \
131               --description="${description}" \
132               --config-files="/etc/arvados/$pkgname/workbench2.example.json" \
133               "$WORKSPACE/services/workbench2/etc/arvados/workbench2/workbench2.example.json=/etc/arvados/$pkgname/workbench2.example.json"
134 }
135
136 calculate_go_package_version() {
137   # $__returnvar has the nameref attribute set, which means it is a reference
138   # to another variable that is passed in as the first argument to this function.
139   # see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html
140   local -n __returnvar="$1"; shift
141   local oldpwd="$PWD"
142
143   cd "$WORKSPACE"
144   go mod download
145
146   # Update the version number and build a new package if the vendor
147   # bundle has changed, or the command imports anything from the
148   # Arvados SDK and the SDK has changed.
149   declare -a checkdirs=(go.mod go.sum)
150   while [ -n "$1" ]; do
151       checkdirs+=("$1")
152       shift
153   done
154   # Even our rails packages (version calculation happens here!) depend on a go component (arvados-server)
155   # Everything depends on the build directory.
156   checkdirs+=(sdk/go lib build)
157   local timestamp=0
158   for dir in ${checkdirs[@]}; do
159       cd "$WORKSPACE"
160       ts="$(timestamp_from_git "$dir")"
161       if [[ "$ts" -gt "$timestamp" ]]; then
162           version=$(version_from_git "$dir")
163           timestamp="$ts"
164       fi
165   done
166   cd "$oldpwd"
167   __returnvar="$version"
168 }
169
170 # Usage: package_go_binary services/foo arvados-foo [deb|rpm] [amd64|arm64] "Compute foo to arbitrary precision" [apache-2.0.txt]
171 package_go_binary() {
172   local src_path="$1"; shift
173   local prog="$1"; shift
174   local package_format="$1"; shift
175   local target_arch="$1"; shift
176   local description="$1"; shift
177   local license_file="${1:-agpl-3.0.txt}"; shift
178
179   if [[ -n "$ONLY_BUILD" ]] && [[ "$prog" != "$ONLY_BUILD" ]]; then
180       debug_echo -e "Skipping build of $prog package."
181       return 0
182   fi
183
184   native_arch=$(get_native_arch)
185
186   if [[ "$native_arch" != "amd64" ]] && [[ -n "$target_arch" ]] && [[ "$native_arch" != "$target_arch" ]]; then
187     echo "Error: no cross compilation support for Go on $native_arch, can not build $prog for $target_arch"
188     return 1
189   fi
190
191   case "$package_format-$TARGET" in
192     # Older Debian/Ubuntu do not support cross compilation because the
193     # libfuse package does not support multiarch. See
194     # <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=983477>.
195     # Red Hat-based distributions do not support native cross compilation at
196     # all (they use a qemu-based solution we haven't implemented yet).
197     deb-debian10|deb-ubuntu1804|deb-ubuntu2004|rpm-*)
198       cross_compilation=0
199       if [[ "$native_arch" == "amd64" ]] && [[ -n "$target_arch" ]] && [[ "$native_arch" != "$target_arch" ]]; then
200         echo "Error: no cross compilation support for Go on $native_arch for $TARGET, can not build $prog for $target_arch"
201         return 1
202       fi
203       ;;
204     *)
205       cross_compilation=1
206       ;;
207   esac
208
209   if [[ -n "$target_arch" ]]; then
210     archs=($target_arch)
211   else
212     # No target architecture specified, default to native target. When on amd64
213     # also crosscompile arm64 (when supported).
214     archs=($native_arch)
215     if [[ $cross_compilation -ne 0 ]]; then
216       archs+=("arm64")
217     fi
218   fi
219
220   for ta in ${archs[@]}; do
221     package_go_binary_worker "$src_path" "$prog" "$package_format" "$description" "$native_arch" "$ta" "$license_file"
222     retval=$?
223     if [[ $retval -ne 0 ]]; then
224       return $retval
225     fi
226   done
227 }
228
229 # Usage: package_go_binary services/foo arvados-foo deb "Compute foo to arbitrary precision" [amd64/arm64] [amd64/arm64] [apache-2.0.txt]
230 package_go_binary_worker() {
231     local src_path="$1"; shift
232     local prog="$1"; shift
233     local package_format="$1"; shift
234     local description="$1"; shift
235     local native_arch="${1:-amd64}"; shift
236     local target_arch="${1:-amd64}"; shift
237     local license_file="${1:-agpl-3.0.txt}"; shift
238
239     debug_echo "package_go_binary $src_path as $prog (native arch: $native_arch, target arch: $target_arch)"
240     local basename="${src_path##*/}"
241     calculate_go_package_version go_package_version $src_path
242
243     cd $WORKSPACE/packages/$TARGET
244     test_package_presence "$prog" "$go_package_version" "go" "" "$target_arch"
245     if [[ $? -ne 0 ]]; then
246       return 0
247     fi
248
249     echo "Building $package_format ($target_arch) package for $prog from $src_path"
250     if [[ "$native_arch" == "amd64" ]] && [[ "$target_arch" == "arm64" ]]; then
251       CGO_ENABLED=1 CC=aarch64-linux-gnu-gcc GOARCH=${target_arch} go install -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"
252     else
253       GOARCH=${arch} go install -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"
254     fi
255
256     local -a switches=()
257
258     binpath=$GOPATH/bin/${basename}
259     if [[ "${target_arch}" != "${native_arch}" ]]; then
260       switches+=("-a${target_arch}")
261       binpath="$GOPATH/bin/linux_${target_arch}/${basename}"
262     fi
263
264     systemd_unit="$WORKSPACE/${src_path}/${prog}.service"
265     if [[ -e "${systemd_unit}" ]]; then
266         switches+=(
267             --after-install "${WORKSPACE}/build/go-python-package-scripts/postinst"
268             --before-remove "${WORKSPACE}/build/go-python-package-scripts/prerm"
269             "${systemd_unit}=/lib/systemd/system/${prog}.service")
270     fi
271     switches+=("$WORKSPACE/${license_file}=/usr/share/doc/$prog/${license_file}")
272
273     fpm_build "${WORKSPACE}/${src_path}" "$binpath=/usr/bin/${prog}" "${prog}" dir "${go_package_version}" "--url=https://arvados.org" "--license=GNU Affero General Public License, version 3.0" "--description=${description}" "${switches[@]}"
274 }
275
276 # Usage: package_go_so lib/foo arvados_foo.so arvados-foo deb amd64 "Arvados foo library"
277 package_go_so() {
278     local src_path="$1"; shift
279     local sofile="$1"; shift
280     local pkg="$1"; shift
281     local package_format="$1"; shift
282     local target_arch="$1"; shift # supported: amd64, arm64
283     local description="$1"; shift
284
285     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkg" != "$ONLY_BUILD" ]]; then
286       debug_echo -e "Skipping build of $pkg package."
287       return 0
288     fi
289
290     debug_echo "package_go_so $src_path as $pkg"
291
292     calculate_go_package_version go_package_version $src_path
293     cd $WORKSPACE/packages/$TARGET
294     test_package_presence $pkg $go_package_version go || return 1
295     cd $WORKSPACE/$src_path
296     go build -buildmode=c-shared -o ${GOPATH}/bin/${sofile}
297     cd $WORKSPACE/packages/$TARGET
298     local -a fpmargs=(
299         "--url=https://arvados.org"
300         "--license=Apache License, Version 2.0"
301         "--description=${description}"
302         "$WORKSPACE/apache-2.0.txt=/usr/share/doc/$pkg/apache-2.0.txt"
303     )
304     if [[ -e "$WORKSPACE/$src_path/pam-configs-arvados" ]]; then
305         fpmargs+=("$WORKSPACE/$src_path/pam-configs-arvados=/usr/share/doc/$pkg/pam-configs-arvados-go")
306     fi
307     if [[ -e "$WORKSPACE/$src_path/README" ]]; then
308         fpmargs+=("$WORKSPACE/$src_path/README=/usr/share/doc/$pkg/README")
309     fi
310     fpm_build "${WORKSPACE}/${src_path}" "$GOPATH/bin/${sofile}=/usr/lib/${sofile}" "${pkg}" dir "${go_package_version}" "${fpmargs[@]}"
311 }
312
313 default_iteration() {
314     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
315         echo "$ARVADOS_BUILDING_ITERATION"
316         return
317     fi
318     local package_name="$1"; shift
319     local package_version="$1"; shift
320     local package_type="$1"; shift
321     local iteration=1
322     if [[ $package_version =~ ^0\.1\.([0-9]{14})(\.|$) ]] && \
323            [[ ${BASH_REMATCH[1]} -le $LICENSE_PACKAGE_TS ]]; then
324         iteration=2
325     fi
326     echo $iteration
327 }
328
329 _build_rails_package_scripts() {
330     local pkgname="$1"; shift
331     local destdir="$1"; shift
332     local srcdir="$RUN_BUILD_PACKAGES_PATH/rails-package-scripts"
333     for scriptname in postinst prerm postrm; do
334         cat "$srcdir/$pkgname.sh" "$srcdir/step2.sh" "$srcdir/$scriptname.sh" \
335             >"$destdir/$scriptname" || return $?
336     done
337 }
338
339 rails_package_version() {
340     local pkgname="$1"; shift
341     local srcdir="$1"; shift
342     if [[ -n "$ARVADOS_BUILDING_VERSION" ]]; then
343         echo "$ARVADOS_BUILDING_VERSION"
344         return
345     fi
346     local version="$(version_from_git)"
347     if [ $pkgname = "arvados-api-server" ] ; then
348         calculate_go_package_version version cmd/arvados-server "$srcdir"
349     fi
350     echo $version
351 }
352
353 test_rails_package_presence() {
354   local pkgname="$1"; shift
355   local srcdir="$1"; shift
356
357   if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
358     return 1
359   fi
360
361   tmppwd=`pwd`
362
363   cd $srcdir
364
365   local version="$(rails_package_version "$pkgname" "$srcdir")"
366
367   cd $tmppwd
368
369   test_package_presence $pkgname $version rails "$RAILS_PACKAGE_ITERATION"
370 }
371
372 get_complete_package_name() {
373   # if the errexit flag is set, unset it until this function returns
374   # otherwise, the shift calls below will abort the program if optional arguments are not supplied
375   if [ -o errexit ]; then
376     set +e
377     trap 'set -e' RETURN
378   fi
379   # $__returnvar has the nameref attribute set, which means it is a reference
380   # to another variable that is passed in as the first argument to this function.
381   # see https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html
382   local -n __returnvar="$1"; shift
383   local pkgname="$1"; shift
384   local version="$1"; shift
385   local pkgtype="$1"; shift
386   local iteration="$1"; shift
387   local arch="$1"; shift
388   if [[ "$iteration" == "" ]]; then
389       iteration="$(default_iteration "$pkgname" "$version" "$pkgtype")"
390   fi
391
392   if [[ "$arch" == "" ]]; then
393     native_arch=$(get_native_arch)
394     rpm_native_arch="x86_64"
395     if [[ "$HOSTTYPE" == "aarch64" ]]; then
396       rpm_native_arch="arm64"
397     fi
398     rpm_architecture="$rpm_native_arch"
399     deb_architecture="$native_arch"
400
401     if [[ "$pkgtype" =~ ^(src)$ ]]; then
402       rpm_architecture="noarch"
403       deb_architecture="all"
404     fi
405   else
406     rpm_architecture=$arch
407     deb_architecture=$arch
408   fi
409
410   local complete_pkgname="${pkgname}_$version${iteration:+-$iteration}_$deb_architecture.deb"
411   if [[ "$FORMAT" == "rpm" ]]; then
412       # rpm packages get iteration 1 if we don't supply one
413       iteration=${iteration:-1}
414       complete_pkgname="$pkgname-$version-${iteration}.$rpm_architecture.rpm"
415   fi
416   __returnvar=${complete_pkgname}
417 }
418
419 # Test if the package already exists, if not return 0, if it does return 1
420 test_package_presence() {
421     local pkgname="$1"; shift
422     local version="$1"; shift
423     local pkgtype="$1"; shift
424     local iteration="$1"; shift
425     local arch="$1"; shift
426     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
427         return 1
428     fi
429
430     local full_pkgname
431     get_complete_package_name full_pkgname "$pkgname" "$version" "$pkgtype" "$iteration" "$arch"
432
433     # See if we can skip building the package, only if it already exists in the
434     # processed/ directory. If so, move it back to the packages directory to make
435     # sure it gets picked up by the test and/or upload steps.
436     # Get the list of packages from the repos
437
438     if [[ "$FORCE_BUILD" == "1" ]]; then
439       echo "Package $full_pkgname build forced with --force-build, building"
440     elif [[ "$FORMAT" == "deb" ]]; then
441       declare -A dd
442       dd[debian10]=buster
443       dd[debian11]=bullseye
444       dd[ubuntu1804]=bionic
445       dd[ubuntu2004]=focal
446       D=${dd[$TARGET]}
447       if [ ${pkgname:0:3} = "lib" ]; then
448         repo_subdir=${pkgname:0:4}
449       else
450         repo_subdir=${pkgname:0:1}
451       fi
452
453       repo_pkg_list=$(curl -s -o - http://apt.arvados.org/${D}/pool/main/${repo_subdir}/${pkgname}/)
454       echo "${repo_pkg_list}" |grep -q ${full_pkgname}
455       if [ $? -eq 0 ] ; then
456         echo "Package $full_pkgname exists upstream, not rebuilding, downloading instead!"
457         curl -s -o "$WORKSPACE/packages/$TARGET/${full_pkgname}" http://apt.arvados.org/${D}/pool/main/${repo_subdir}/${pkgname}/${full_pkgname}
458         return 1
459       elif test -f "$WORKSPACE/packages/$TARGET/processed/${full_pkgname}" ; then
460         echo "Package $full_pkgname exists, not rebuilding!"
461         return 1
462       else
463         echo "Package $full_pkgname not found, building"
464         return 0
465       fi
466     else
467       local rpm_root
468       case "$TARGET" in
469         centos7) rpm_root="CentOS/7/dev" ;;
470         rocky8) rpm_root="CentOS/8/dev" ;;
471         *)
472           echo "FIXME: Don't know RPM URL path for $TARGET, building"
473           return 0
474           ;;
475       esac
476       local rpm_url="http://rpm.arvados.org/$rpm_root/$arch/$full_pkgname"
477
478       if curl -fs -o "$WORKSPACE/packages/$TARGET/$full_pkgname" "$rpm_url"; then
479         echo "Package $full_pkgname exists upstream, not rebuilding, downloading instead!"
480         return 1
481       elif [[ -f "$WORKSPACE/packages/$TARGET/processed/$full_pkgname" ]]; then
482         echo "Package $full_pkgname exists, not rebuilding!"
483         return 1
484       else
485         echo "Package $full_pkgname not found, building"
486         return 0
487       fi
488     fi
489 }
490
491 handle_rails_package() {
492     local pkgname="$1"; shift
493
494     if [[ -n "$ONLY_BUILD" ]] && [[ "$pkgname" != "$ONLY_BUILD" ]] ; then
495         return 0
496     fi
497     local srcdir="$1"; shift
498     cd "$srcdir"
499     local license_path="$1"; shift
500     local version="$(rails_package_version "$pkgname" "$srcdir")"
501     echo "$version" >package-build.version
502     local scripts_dir="$(mktemp --tmpdir -d "$pkgname-XXXXXXXX.scripts")" && \
503     (
504         set -e
505         _build_rails_package_scripts "$pkgname" "$scripts_dir"
506         cd "$srcdir"
507         mkdir -p tmp
508         git rev-parse HEAD >git-commit.version
509         bundle config set cache_all true
510         bundle package
511     )
512     if [[ 0 != "$?" ]] || ! cd "$WORKSPACE/packages/$TARGET"; then
513         echo "ERROR: $pkgname package prep failed" >&2
514         rm -rf "$scripts_dir"
515         EXITCODE=1
516         return 1
517     fi
518     local railsdir="/var/www/${pkgname%-server}/current"
519     local -a pos_args=("$srcdir/=$railsdir" "$pkgname" dir "$version")
520     local license_arg="$license_path=$railsdir/$(basename "$license_path")"
521     local -a switches=(--after-install "$scripts_dir/postinst"
522                        --before-remove "$scripts_dir/prerm"
523                        --after-remove "$scripts_dir/postrm")
524     if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
525         switches+=(--iteration $RAILS_PACKAGE_ITERATION)
526     fi
527     # For some reason fpm excludes need to not start with /.
528     local exclude_root="${railsdir#/}"
529     for exclude in tmp log coverage Capfile\* \
530                        config/deploy\* \
531                        config/application.yml \
532                        config/database.yml; do
533         switches+=(-x "$exclude_root/$exclude")
534     done
535     fpm_build "${srcdir}" "${pos_args[@]}" "${switches[@]}" \
536               -x "$exclude_root/vendor/cache-*" \
537               -x "$exclude_root/vendor/bundle" "$@" "$license_arg"
538     rm -rf "$scripts_dir"
539 }
540
541 # Usage: handle_api_server [amd64|arm64]
542 handle_api_server () {
543   local target_arch="${1:-amd64}"; shift
544
545   if [[ -n "$ONLY_BUILD" ]] && [[ "$ONLY_BUILD" != "arvados-api-server" ]] ; then
546     debug_echo -e "Skipping build of arvados-api-server package."
547     return 0
548   fi
549
550   native_arch=$(get_native_arch)
551   if [[ "$target_arch" != "$native_arch" ]]; then
552     echo "Error: no cross compilation support for Rails yet, can not build arvados-api-server for $ARCH"
553     echo
554     exit 1
555   fi
556
557   # Build the API server package
558   test_rails_package_presence arvados-api-server "$WORKSPACE/services/api"
559   if [[ "$?" == "0" ]]; then
560     calculate_go_package_version arvados_server_version cmd/arvados-server
561     arvados_server_iteration=$(default_iteration "arvados-server" "$arvados_server_version" "go")
562     handle_rails_package arvados-api-server "$WORKSPACE/services/api" \
563         "$WORKSPACE/agpl-3.0.txt" --url="https://arvados.org" \
564         --description="Arvados API server - Arvados is a free and open source platform for big data science." \
565         --license="GNU Affero General Public License, version 3.0" --depends "arvados-server = ${arvados_server_version}-${arvados_server_iteration}"
566   fi
567 }
568
569 # Usage: handle_cwltest [deb|rpm] [amd64|arm64]
570 handle_cwltest () {
571   local package_format="$1"; shift
572   local target_arch="${1:-amd64}"; shift
573
574   if [[ -n "$ONLY_BUILD" ]] && [[ "$ONLY_BUILD" != "python3-cwltest" ]] ; then
575     debug_echo -e "Skipping build of cwltest package."
576     return 0
577   fi
578   cd "$WORKSPACE"
579   if [[ -e "$WORKSPACE/cwltest" ]]; then
580     rm -rf "$WORKSPACE/cwltest"
581   fi
582   git clone https://github.com/common-workflow-language/cwltest.git
583
584   # The subsequent release of cwltest confirms that files exist on disk, since
585   # our files are in Keep, all the tests fail.
586   # We should add [optional] Arvados support to cwltest so it can access
587   # Keep but for the time being just package the last working version.
588   (cd cwltest && git checkout 2.3.20230108193615)
589
590   # signal to our build script that we want a cwltest executable installed in /usr/bin/
591   mkdir cwltest/bin && touch cwltest/bin/cwltest
592   fpm_build_virtualenv "cwltest" "cwltest" "$package_format" "$target_arch"
593   # The python->python3 metapackage
594   build_metapackage "cwltest" "cwltest"
595   cd "$WORKSPACE"
596   rm -rf "$WORKSPACE/cwltest"
597 }
598
599 # Usage: handle_arvados_src
600 handle_arvados_src () {
601   if [[ -n "$ONLY_BUILD" ]] && [[ "$ONLY_BUILD" != "arvados-src" ]] ; then
602     debug_echo -e "Skipping build of arvados-src package."
603     return 0
604   fi
605   # arvados-src
606   (
607       cd "$WORKSPACE"
608       COMMIT_HASH=$(format_last_commit_here "%H")
609       arvados_src_version="$(version_from_git)"
610
611       cd $WORKSPACE/packages/$TARGET
612       test_package_presence arvados-src "$arvados_src_version" src ""
613
614       if [[ "$?" == "0" ]]; then
615         cd "$WORKSPACE"
616         SRC_BUILD_DIR=$(mktemp -d)
617         # mktemp creates the directory with 0700 permissions by default
618         chmod 755 $SRC_BUILD_DIR
619         git clone $DASHQ_UNLESS_DEBUG "$WORKSPACE/.git" "$SRC_BUILD_DIR"
620         cd "$SRC_BUILD_DIR"
621
622         # go into detached-head state
623         git checkout $DASHQ_UNLESS_DEBUG "$COMMIT_HASH"
624         echo "$COMMIT_HASH" >git-commit.version
625
626         cd $WORKSPACE/packages/$TARGET
627         fpm_build "$WORKSPACE" $SRC_BUILD_DIR/=/usr/local/arvados/src arvados-src 'dir' "$arvados_src_version" "--exclude=usr/local/arvados/src/.git" "--url=https://arvados.org" "--license=GNU Affero General Public License, version 3.0" "--description=The Arvados source code" "--architecture=all"
628
629         rm -rf "$SRC_BUILD_DIR"
630       fi
631   )
632 }
633
634 # Build python packages with a virtualenv built-in
635 # Usage: fpm_build_virtualenv arvados-python-client sdk/python [deb|rpm] [amd64|arm64]
636 fpm_build_virtualenv () {
637   local pkg=$1; shift
638   local pkg_dir=$1; shift
639   local package_format="$1"; shift
640   local target_arch="${1:-amd64}"; shift
641
642   native_arch=$(get_native_arch)
643
644   if [[ "$pkg" != "arvados-docker-cleaner" ]]; then
645     PYTHON_PKG=$PYTHON3_PKG_PREFIX-$pkg
646   else
647     # Exception to our package naming convention
648     PYTHON_PKG=$pkg
649   fi
650
651   if [[ -n "$ONLY_BUILD" ]] && [[ "$PYTHON_PKG" != "$ONLY_BUILD" ]]; then
652     # arvados-python-client sdist should always be built if we are building a
653     # python package.
654     if [[ "$ONLY_BUILD" != "python3-arvados-cwl-runner" ]] &&
655        [[ "$ONLY_BUILD" != "python3-arvados-fuse" ]] &&
656        [[ "$ONLY_BUILD" != "python3-crunchstat-summary" ]] &&
657        [[ "$ONLY_BUILD" != "arvados-docker-cleaner" ]] &&
658        [[ "$ONLY_BUILD" != "python3-arvados-user-activity" ]]; then
659       debug_echo -e "Skipping build of $pkg package."
660       return 0
661     fi
662   fi
663
664   if [[ -n "$target_arch" ]] && [[ "$native_arch" == "$target_arch" ]]; then
665       fpm_build_virtualenv_worker "$pkg" "$pkg_dir" "$package_format" "$native_arch" "$target_arch"
666   elif [[ -z "$target_arch" ]]; then
667     fpm_build_virtualenv_worker "$pkg" "$pkg_dir" "$package_format" "$native_arch" "$native_arch"
668   else
669     echo "Error: no cross compilation support for Python yet, can not build $pkg for $target_arch"
670     return 1
671   fi
672 }
673
674 # Build python packages with a virtualenv built-in
675 # Usage: fpm_build_virtualenv_worker arvados-python-client sdk/python python3 [deb|rpm] [amd64|arm64] [amd64|arm64]
676 fpm_build_virtualenv_worker () {
677   PKG=$1; shift
678   PKG_DIR=$1; shift
679   local package_format="$1"; shift
680   local native_arch="${1:-amd64}"; shift
681   local target_arch=${1:-amd64}; shift
682
683   # Set up
684   STDOUT_IF_DEBUG=/dev/null
685   STDERR_IF_DEBUG=/dev/null
686   DASHQ_UNLESS_DEBUG=-q
687   if [[ "$DEBUG" != "0" ]]; then
688       STDOUT_IF_DEBUG=/dev/stdout
689       STDERR_IF_DEBUG=/dev/stderr
690       DASHQ_UNLESS_DEBUG=
691   fi
692   if [[ "$ARVADOS_BUILDING_ITERATION" == "" ]]; then
693     ARVADOS_BUILDING_ITERATION=1
694   fi
695
696   local python=$PYTHON3_EXECUTABLE
697   pip=pip3
698   PACKAGE_PREFIX=$PYTHON3_PKG_PREFIX
699
700   if [[ "$PKG" != "arvados-docker-cleaner" ]]; then
701     PYTHON_PKG=$PACKAGE_PREFIX-$PKG
702   else
703     # Exception to our package naming convention
704     PYTHON_PKG=$PKG
705   fi
706
707   cd $WORKSPACE/$PKG_DIR
708
709   rm -rf dist/*
710
711   # Get the latest setuptools
712   if ! $pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'; then
713     echo "Error, unable to upgrade setuptools with"
714     echo "  $pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'"
715     exit 1
716   fi
717   # filter a useless warning (when building the cwltest package) from the stderr output
718   if ! $python setup.py $DASHQ_UNLESS_DEBUG sdist 2> >(grep -v 'warning: no previously-included files matching'); then
719     echo "Error, unable to run $python setup.py sdist for $PKG"
720     exit 1
721   fi
722
723   PACKAGE_PATH=`(cd dist; ls *tar.gz)`
724
725   if [[ "arvados-python-client" == "$PKG" ]]; then
726     PYSDK_PATH="-f $(pwd)/dist/"
727   fi
728
729   if [[ -n "$ONLY_BUILD" ]] && [[ "$PYTHON_PKG" != "$ONLY_BUILD" ]] && [[ "$PKG" != "$ONLY_BUILD" ]]; then
730     return 0
731   fi
732
733   # Determine the package version from the generated sdist archive
734   if [[ -n "$ARVADOS_BUILDING_VERSION" ]] ; then
735       UNFILTERED_PYTHON_VERSION=$ARVADOS_BUILDING_VERSION
736       PYTHON_VERSION=$(echo -n $ARVADOS_BUILDING_VERSION | sed s/~dev/.dev/g | sed s/~rc/rc/g)
737   else
738       PYTHON_VERSION=$(awk '($1 == "Version:"){print $2}' *.egg-info/PKG-INFO)
739       UNFILTERED_PYTHON_VERSION=$(echo -n $PYTHON_VERSION | sed s/\.dev/~dev/g |sed 's/\([0-9]\)rc/\1~rc/g')
740   fi
741
742   # See if we actually need to build this package; does it exist already?
743   # We can't do this earlier than here, because we need PYTHON_VERSION...
744   # This isn't so bad; the sdist call above is pretty quick compared to
745   # the invocation of virtualenv and fpm, below.
746   if ! test_package_presence "$PYTHON_PKG" "$UNFILTERED_PYTHON_VERSION" "$python" "$ARVADOS_BUILDING_ITERATION" "$target_arch"; then
747     return 0
748   fi
749
750   echo "Building $package_format ($target_arch) package for $PKG from $PKG_DIR"
751
752   # Package the sdist in a virtualenv
753   echo "Creating virtualenv..."
754
755   cd dist
756
757   rm -rf build
758   rm -f $PYTHON_PKG*deb
759   echo "virtualenv version: `virtualenv --version`"
760   virtualenv_command="virtualenv --python `which $python` $DASHQ_UNLESS_DEBUG build/usr/share/$python/dist/$PYTHON_PKG"
761
762   if ! $virtualenv_command; then
763     echo "Error, unable to run"
764     echo "  $virtualenv_command"
765     exit 1
766   fi
767
768   if ! build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U pip; then
769     echo "Error, unable to upgrade pip with"
770     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U pip"
771     exit 1
772   fi
773   echo "pip version:        `build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip --version`"
774
775   if ! build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'; then
776     echo "Error, unable to upgrade setuptools with"
777     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'"
778     exit 1
779   fi
780   echo "setuptools version: `build/usr/share/$python/dist/$PYTHON_PKG/bin/$python -c 'import setuptools; print(setuptools.__version__)'`"
781
782   if ! build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U wheel; then
783     echo "Error, unable to upgrade wheel with"
784     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U wheel"
785     exit 1
786   fi
787   echo "wheel version:      `build/usr/share/$python/dist/$PYTHON_PKG/bin/wheel version`"
788
789   if [[ "$TARGET" != "centos7" ]] || [[ "$PYTHON_PKG" != "python-arvados-fuse" ]]; then
790     build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG $PYSDK_PATH $PACKAGE_PATH
791   else
792     # centos7 needs these special tweaks to install python-arvados-fuse
793     build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG docutils
794     PYCURL_SSL_LIBRARY=nss build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG $PYSDK_PATH $PACKAGE_PATH
795   fi
796
797   if [[ "$?" != "0" ]]; then
798     echo "Error, unable to run"
799     echo "  build/usr/share/$python/dist/$PYTHON_PKG/bin/$pip install $DASHQ_UNLESS_DEBUG $CACHE_FLAG $PYSDK_PATH $PACKAGE_PATH"
800     exit 1
801   fi
802
803   cd build/usr/share/$python/dist/$PYTHON_PKG/
804
805   # Replace the shebang lines in all python scripts, and handle the activate
806   # scripts too. This is a functional replacement of the 237 line
807   # virtualenv_tools.py script that doesn't work in python3 without serious
808   # patching, minus the parts we don't need (modifying pyc files, etc).
809   for binfile in `ls bin/`; do
810     if ! file --mime bin/$binfile |grep -q binary; then
811       # Not a binary file
812       if [[ "$binfile" =~ ^activate(.csh|.fish|)$ ]]; then
813         # these 'activate' scripts need special treatment
814         sed -i "s/VIRTUAL_ENV=\".*\"/VIRTUAL_ENV=\"\/usr\/share\/$python\/dist\/$PYTHON_PKG\"/" bin/$binfile
815         sed -i "s/VIRTUAL_ENV \".*\"/VIRTUAL_ENV \"\/usr\/share\/$python\/dist\/$PYTHON_PKG\"/" bin/$binfile
816       else
817         if grep -q -E '^#!.*/bin/python\d?' bin/$binfile; then
818           # Replace shebang line
819           sed -i "1 s/^.*$/#!\/usr\/share\/$python\/dist\/$PYTHON_PKG\/bin\/python/" bin/$binfile
820         fi
821       fi
822     fi
823   done
824
825   cd - >$STDOUT_IF_DEBUG
826
827   find build -iname '*.pyc' -exec rm {} \;
828   find build -iname '*.pyo' -exec rm {} \;
829
830   # Finally, generate the package
831   echo "Creating package..."
832
833   declare -a COMMAND_ARR=("fpm" "-s" "dir" "-t" "$package_format")
834
835   if [[ -n "$target_arch" ]] && [[ "$target_arch" != "amd64" ]]; then
836     COMMAND_ARR+=("-a$target_arch")
837   fi
838
839   if [[ "$MAINTAINER" != "" ]]; then
840     COMMAND_ARR+=('--maintainer' "$MAINTAINER")
841   fi
842
843   if [[ "$VENDOR" != "" ]]; then
844     COMMAND_ARR+=('--vendor' "$VENDOR")
845   fi
846
847   COMMAND_ARR+=('--url' 'https://arvados.org')
848
849   # Get description
850   DESCRIPTION=`grep '\sdescription' $WORKSPACE/$PKG_DIR/setup.py|cut -f2 -d=|sed -e "s/[',\\"]//g"`
851   COMMAND_ARR+=('--description' "$DESCRIPTION")
852
853   # Get license string
854   LICENSE_STRING=`grep license $WORKSPACE/$PKG_DIR/setup.py|cut -f2 -d=|sed -e "s/[',\\"]//g"`
855   COMMAND_ARR+=('--license' "$LICENSE_STRING")
856
857   if [[ "$DEBUG" != "0" ]]; then
858     COMMAND_ARR+=('--verbose' '--log' 'info')
859   fi
860
861   COMMAND_ARR+=('-v' $(echo -n "$PYTHON_VERSION" | sed s/.dev/~dev/g | sed s/rc/~rc/g))
862   COMMAND_ARR+=('--iteration' "$ARVADOS_BUILDING_ITERATION")
863   COMMAND_ARR+=('-n' "$PYTHON_PKG")
864   COMMAND_ARR+=('-C' "build")
865
866   systemd_unit="$WORKSPACE/$PKG_DIR/$PKG.service"
867   if [[ -e "${systemd_unit}" ]]; then
868     COMMAND_ARR+=('--after-install' "${WORKSPACE}/build/go-python-package-scripts/postinst")
869     COMMAND_ARR+=('--before-remove' "${WORKSPACE}/build/go-python-package-scripts/prerm")
870   fi
871
872   COMMAND_ARR+=('--depends' "$PYTHON3_PACKAGE")
873   case "$package_format" in
874       deb)
875           COMMAND_ARR+=(
876               # Avoid warning
877               --deb-no-default-config-files
878           ) ;;
879       rpm)
880           COMMAND_ARR+=(
881               # Conflict with older packages we used to publish
882               --conflicts "rh-python36-python-$PKG"
883               # Do not generate /usr/lib/.build-id links on RH8+
884               # (otherwise our packages conflict with platform-python)
885               --rpm-rpmbuild-define "_build_id_links none"
886           ) ;;
887   esac
888
889   # Append --depends X and other arguments specified by fpm-info.sh in
890   # the package source dir. These are added last so they can override
891   # the arguments added by this script.
892   declare -a fpm_args=()
893   declare -a fpm_depends=()
894
895   fpminfo="$WORKSPACE/$PKG_DIR/fpm-info.sh"
896   if [[ -e "$fpminfo" ]]; then
897     echo "Loading fpm overrides from $fpminfo"
898     if ! source "$fpminfo"; then
899       echo "Error, unable to source $WORKSPACE/$PKG_DIR/fpm-info.sh for $PKG"
900       exit 1
901     fi
902   fi
903
904   for i in "${fpm_depends[@]}"; do
905     COMMAND_ARR+=('--depends' "$i")
906   done
907
908   for i in "${fpm_depends[@]}"; do
909     COMMAND_ARR+=('--replaces' "python-$PKG")
910   done
911
912   # make sure the systemd service file ends up in the right place
913   # used by arvados-docker-cleaner
914   if [[ -e "${systemd_unit}" ]]; then
915     COMMAND_ARR+=("usr/share/$python/dist/$PKG/share/doc/$PKG/$PKG.service=/lib/systemd/system/$PKG.service")
916   fi
917
918   COMMAND_ARR+=("${fpm_args[@]}")
919
920   # Make sure to install all our package binaries in /usr/bin.
921   # We have to walk $WORKSPACE/$PKG_DIR/bin rather than
922   # $WORKSPACE/build/usr/share/$python/dist/$PYTHON_PKG/bin/ to get the list
923   # because the latter also includes all the python binaries for the virtualenv.
924   # We have to take the copies of our binaries from the latter directory, though,
925   # because those are the ones we rewrote the shebang line of, above.
926   if [[ -e "$WORKSPACE/$PKG_DIR/bin" ]]; then
927     for binary in `ls $WORKSPACE/$PKG_DIR/bin`; do
928       COMMAND_ARR+=("usr/share/$python/dist/$PYTHON_PKG/bin/$binary=/usr/bin/")
929     done
930   fi
931
932   # the python3-arvados-cwl-runner package comes with cwltool, expose that version
933   if [[ -e "$WORKSPACE/$PKG_DIR/dist/build/usr/share/$python/dist/$PYTHON_PKG/bin/cwltool" ]]; then
934     COMMAND_ARR+=("usr/share/$python/dist/$PYTHON_PKG/bin/cwltool=/usr/bin/")
935   fi
936
937   COMMAND_ARR+=(".")
938
939   debug_echo -e "\n${COMMAND_ARR[@]}\n"
940
941   FPM_RESULTS=$("${COMMAND_ARR[@]}")
942   FPM_EXIT_CODE=$?
943
944   # if something went wrong and debug is off, print out the fpm command that errored
945   if ! fpm_verify $FPM_EXIT_CODE $FPM_RESULTS && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
946     echo "fpm returned an error executing the command:"
947     echo
948     echo -e "\n${COMMAND_ARR[@]}\n"
949   else
950     echo `ls *$package_format`
951     mv $WORKSPACE/$PKG_DIR/dist/*$package_format $WORKSPACE/packages/$TARGET/
952   fi
953   echo
954 }
955
956 # build_metapackage builds meta packages that help with the python to python 3 package migration
957 build_metapackage() {
958   # base package name (e.g. arvados-python-client)
959   BASE_NAME=$1
960   shift
961   PKG_DIR=$1
962   shift
963
964   if [[ -n "$ONLY_BUILD" ]] && [[ "python-$BASE_NAME" != "$ONLY_BUILD" ]]; then
965     return 0
966   fi
967
968   if [[ "$ARVADOS_BUILDING_ITERATION" == "" ]]; then
969     ARVADOS_BUILDING_ITERATION=1
970   fi
971
972   if [[ -z "$ARVADOS_BUILDING_VERSION" ]]; then
973     cd $WORKSPACE/$PKG_DIR
974     pwd
975     rm -rf dist/*
976
977     # Get the latest setuptools
978     if ! pip3 install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'; then
979       echo "Error, unable to upgrade setuptools with XY"
980       echo "  pip3 install $DASHQ_UNLESS_DEBUG $CACHE_FLAG -U 'setuptools<45'"
981       exit 1
982     fi
983     # filter a useless warning (when building the cwltest package) from the stderr output
984     if ! python3 setup.py $DASHQ_UNLESS_DEBUG sdist 2> >(grep -v 'warning: no previously-included files matching'); then
985       echo "Error, unable to run python3 setup.py sdist for $PKG"
986       exit 1
987     fi
988
989     PYTHON_VERSION=$(awk '($1 == "Version:"){print $2}' *.egg-info/PKG-INFO)
990     UNFILTERED_PYTHON_VERSION=$(echo -n $PYTHON_VERSION | sed s/\.dev/~dev/g |sed 's/\([0-9]\)rc/\1~rc/g')
991
992   else
993     UNFILTERED_PYTHON_VERSION=$ARVADOS_BUILDING_VERSION
994     PYTHON_VERSION=$(echo -n $ARVADOS_BUILDING_VERSION | sed s/~dev/.dev/g | sed s/~rc/rc/g)
995   fi
996
997   cd - >$STDOUT_IF_DEBUG
998   if [[ -d "$BASE_NAME" ]]; then
999     rm -rf $BASE_NAME
1000   fi
1001   mkdir $BASE_NAME
1002   cd $BASE_NAME
1003
1004   if [[ "$FORMAT" == "deb" ]]; then
1005     cat >ns-control <<EOF
1006 Section: misc
1007 Priority: optional
1008 Standards-Version: 3.9.2
1009
1010 Package: python-${BASE_NAME}
1011 Version: ${PYTHON_VERSION}-${ARVADOS_BUILDING_ITERATION}
1012 Maintainer: Arvados Package Maintainers <packaging@arvados.org>
1013 Depends: python3-${BASE_NAME}
1014 Description: metapackage to ease the upgrade to the Pyhon 3 version of ${BASE_NAME}
1015  This package is a metapackage that will automatically install the new version of
1016  ${BASE_NAME} which is Python 3 based and has a different name.
1017 EOF
1018
1019     /usr/bin/equivs-build ns-control
1020     if [[ $? -ne 0 ]]; then
1021       echo "Error running 'equivs-build ns-control', is the 'equivs' package installed?"
1022       return 1
1023     fi
1024   elif [[ "$FORMAT" == "rpm" ]]; then
1025     cat >meta.spec <<EOF
1026 Summary: metapackage to ease the upgrade to the Python 3 version of ${BASE_NAME}
1027 Name: python-${BASE_NAME}
1028 Version: ${PYTHON_VERSION}
1029 Release: ${ARVADOS_BUILDING_ITERATION}
1030 License: distributable
1031
1032 Requires: python3-${BASE_NAME}
1033
1034 %description
1035 This package is a metapackage that will automatically install the new version of
1036 python-${BASE_NAME} which is Python 3 based and has a different name.
1037
1038 %prep
1039
1040 %build
1041
1042 %clean
1043
1044 %install
1045
1046 %post
1047
1048 %files
1049
1050
1051 %changelog
1052 * Mon Apr 12 2021 Arvados Package Maintainers <packaging@arvados.org>
1053 - initial release
1054 EOF
1055
1056     /usr/bin/rpmbuild -ba meta.spec
1057     if [[ $? -ne 0 ]]; then
1058       echo "Error running 'rpmbuild -ba meta.spec', is the 'rpm-build' package installed?"
1059       return 1
1060     else
1061       mv /root/rpmbuild/RPMS/x86_64/python-${BASE_NAME}*.${FORMAT} .
1062       if [[ $? -ne 0 ]]; then
1063         echo "Error finding rpm file output of 'rpmbuild -ba meta.spec'"
1064         return 1
1065       fi
1066     fi
1067   else
1068     echo "Unknown format"
1069     return 1
1070   fi
1071
1072   if [[ $EXITCODE -ne 0 ]]; then
1073     return 1
1074   else
1075     echo `ls *$FORMAT`
1076     mv *$FORMAT $WORKSPACE/packages/$TARGET/
1077   fi
1078
1079   # clean up
1080   cd - >$STDOUT_IF_DEBUG
1081   if [[ -d "$BASE_NAME" ]]; then
1082     rm -rf $BASE_NAME
1083   fi
1084 }
1085
1086 # Build packages for everything
1087 fpm_build() {
1088   # Source dir where fpm-info.sh (if any) will be found.
1089   SRC_DIR=$1
1090   shift
1091   # The package source.  Depending on the source type, this can be a
1092   # path, or the name of the package in an upstream repository (e.g.,
1093   # pip).
1094   PACKAGE=$1
1095   shift
1096   # The name of the package to build.
1097   PACKAGE_NAME=$1
1098   shift
1099   # The type of source package.  Passed to fpm -s.  Default "dir".
1100   PACKAGE_TYPE=${1:-dir}
1101   shift
1102   # Optional: the package version number.  Passed to fpm -v.
1103   VERSION=$1
1104   shift
1105
1106   if [[ -n "$ONLY_BUILD" ]] && [[ "$PACKAGE_NAME" != "$ONLY_BUILD" ]] && [[ "$PACKAGE" != "$ONLY_BUILD" ]] ; then
1107       return 0
1108   fi
1109
1110   local default_iteration_value="$(default_iteration "$PACKAGE" "$VERSION" "$PACKAGE_TYPE")"
1111
1112   declare -a COMMAND_ARR=("fpm" "-s" "$PACKAGE_TYPE" "-t" "$FORMAT")
1113   if [ python = "$PACKAGE_TYPE" ] && [ deb = "$FORMAT" ]; then
1114       # Dependencies are built from setup.py.  Since setup.py will never
1115       # refer to Debian package iterations, it doesn't make sense to
1116       # enforce those in the .deb dependencies.
1117       COMMAND_ARR+=(--deb-ignore-iteration-in-dependencies)
1118   fi
1119
1120   if [[ "$DEBUG" != "0" ]]; then
1121     COMMAND_ARR+=('--verbose' '--log' 'info')
1122   fi
1123
1124   if [[ -n "$PACKAGE_NAME" ]]; then
1125     COMMAND_ARR+=('-n' "$PACKAGE_NAME")
1126   fi
1127
1128   if [[ "$MAINTAINER" != "" ]]; then
1129     COMMAND_ARR+=('--maintainer' "$MAINTAINER")
1130   fi
1131
1132   if [[ "$VENDOR" != "" ]]; then
1133     COMMAND_ARR+=('--vendor' "$VENDOR")
1134   fi
1135
1136   if [[ "$VERSION" != "" ]]; then
1137     COMMAND_ARR+=('-v' "$VERSION")
1138   fi
1139   if [[ -n "$default_iteration_value" ]]; then
1140       # We can always add an --iteration here.  If another one is specified in $@,
1141       # that will take precedence, as desired.
1142       COMMAND_ARR+=(--iteration "$default_iteration_value")
1143   fi
1144
1145   # Append --depends X and other arguments specified by fpm-info.sh in
1146   # the package source dir. These are added last so they can override
1147   # the arguments added by this script.
1148   declare -a fpm_args=()
1149   declare -a build_depends=()
1150   declare -a fpm_depends=()
1151   declare -a fpm_conflicts=()
1152   declare -a fpm_exclude=()
1153   if [[ ! -d "$SRC_DIR" ]]; then
1154       echo >&2 "BUG: looking in wrong dir for fpm-info.sh: $pkgdir"
1155       exit 1
1156   fi
1157   fpminfo="${SRC_DIR}/fpm-info.sh"
1158   if [[ -e "$fpminfo" ]]; then
1159       debug_echo "Loading fpm overrides from $fpminfo"
1160       source "$fpminfo"
1161   fi
1162   for pkg in "${build_depends[@]}"; do
1163       if [[ $TARGET =~ debian|ubuntu ]]; then
1164           pkg_deb=$(ls "$WORKSPACE/packages/$TARGET/$pkg_"*.deb | sort -rg | awk 'NR==1')
1165           if [[ -e $pkg_deb ]]; then
1166               echo "Installing build_dep $pkg from $pkg_deb"
1167               dpkg -i "$pkg_deb"
1168           else
1169               echo "Attemping to install build_dep $pkg using apt-get"
1170               apt-get install -y "$pkg"
1171           fi
1172           apt-get -y -f install
1173       else
1174           pkg_rpm=$(ls "$WORKSPACE/packages/$TARGET/$pkg"-[0-9]*.rpm | sort -rg | awk 'NR==1')
1175           if [[ -e $pkg_rpm ]]; then
1176               echo "Installing build_dep $pkg from $pkg_rpm"
1177               rpm -i "$pkg_rpm"
1178           else
1179               echo "Attemping to install build_dep $pkg"
1180               rpm -i "$pkg"
1181           fi
1182       fi
1183   done
1184   for i in "${fpm_depends[@]}"; do
1185     COMMAND_ARR+=('--depends' "$i")
1186   done
1187   for i in "${fpm_conflicts[@]}"; do
1188     COMMAND_ARR+=('--conflicts' "$i")
1189   done
1190   for i in "${fpm_exclude[@]}"; do
1191     COMMAND_ARR+=('--exclude' "$i")
1192   done
1193
1194   COMMAND_ARR+=("${fpm_args[@]}")
1195
1196   # Append remaining function arguments directly to fpm's command line.
1197   for i; do
1198     COMMAND_ARR+=("$i")
1199   done
1200
1201   COMMAND_ARR+=("$PACKAGE")
1202
1203   debug_echo -e "\n${COMMAND_ARR[@]}\n"
1204
1205   FPM_RESULTS=$("${COMMAND_ARR[@]}")
1206   FPM_EXIT_CODE=$?
1207
1208   fpm_verify $FPM_EXIT_CODE $FPM_RESULTS
1209
1210   # if something went wrong and debug is off, print out the fpm command that errored
1211   if [[ 0 -ne $? ]] && [[ "$STDOUT_IF_DEBUG" == "/dev/null" ]]; then
1212     echo -e "\n${COMMAND_ARR[@]}\n"
1213   fi
1214 }
1215
1216 # verify build results
1217 fpm_verify () {
1218   FPM_EXIT_CODE=$1
1219   shift
1220   FPM_RESULTS=$@
1221
1222   FPM_PACKAGE_NAME=''
1223   if [[ $FPM_RESULTS =~ ([A-Za-z0-9_\.-]*\.)(deb|rpm) ]]; then
1224     FPM_PACKAGE_NAME=${BASH_REMATCH[1]}${BASH_REMATCH[2]}
1225   fi
1226
1227   if [[ "$FPM_PACKAGE_NAME" == "" ]]; then
1228     EXITCODE=1
1229     echo
1230     echo "Error: $PACKAGE: Unable to figure out package name from fpm results:"
1231     echo
1232     echo $FPM_RESULTS
1233     echo
1234     return 1
1235   elif [[ "$FPM_RESULTS" =~ "File already exists" ]]; then
1236     echo "Package $FPM_PACKAGE_NAME exists, not rebuilding"
1237     return 0
1238   elif [[ 0 -ne "$FPM_EXIT_CODE" ]]; then
1239     EXITCODE=1
1240     echo "Error building package for $1:\n $FPM_RESULTS"
1241     return 1
1242   fi
1243 }
1244
1245 install_package() {
1246   PACKAGES=$@
1247   if [[ "$FORMAT" == "deb" ]]; then
1248     $SUDO apt-get install $PACKAGES --yes
1249   elif [[ "$FORMAT" == "rpm" ]]; then
1250     $SUDO yum -q -y install $PACKAGES
1251   fi
1252 }
1253
1254 title() {
1255     printf '%s %s\n' "=======" "$1"
1256 }
1257
1258 checkexit() {
1259     if [[ "$1" != "0" ]]; then
1260         title "$2 -- FAILED"
1261         failures+=("$2 (`timer`)")
1262     else
1263         successes+=("$2 (`timer`)")
1264     fi
1265 }
1266
1267 timer_reset() {
1268     t0=$SECONDS
1269 }
1270
1271 timer() {
1272     if [[ -n "$t0" ]]; then
1273         echo -n "$(($SECONDS - $t0))s"
1274     fi
1275 }
1276
1277 report_outcomes() {
1278     for x in "${successes[@]}"
1279     do
1280         echo "Pass: $x"
1281     done
1282
1283     if [[ ${#failures[@]} == 0 ]]
1284     then
1285         if [[ ${#successes[@]} != 0 ]]; then
1286            echo "All test suites passed."
1287         fi
1288     else
1289         echo "Failures (${#failures[@]}):"
1290         for x in "${failures[@]}"
1291         do
1292             echo "Fail: $x"
1293         done
1294     fi
1295 }