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