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