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