Feat!: Re-factor lf-activate-venv() to re-use venv
[releng/global-jjb.git] / jenkins-init-scripts / lf-env.sh
1 #!/usr/bin/no-execute
2 # shellcheck shell=bash
3
4 # SPDX-License-Identifier: EPL-1.0
5 ##############################################################################
6 # Copyright (c) 2019 The Linux Foundation and others.
7 #
8 # All rights reserved. This program and the accompanying materials
9 # are made available under the terms of the Eclipse Public License v1.0
10 # which accompanies this distribution, and is available at
11 # http://www.eclipse.org/legal/epl-v10.html
12 ##############################################################################
13 #
14 # A library of functions for LF/Jenkins bash scripts. In the general case, these
15 # functions should only use 'local' variables, and should NOT set
16 # shell/environment variables. If you want to make a variable available, provide
17 # a function that sets the variable: 'function lf_set_foo() {foo=asdf;}'. Any
18 # scripts that need access to the variable can call the 'set' function. This
19 # keeps the name-space pollution to a minimum.
20 #
21 # This script will be installed in ~jenkins by the Jenkins Init Script when the
22 # build agent boots. When the build starts it should already be installed.
23 #
24 ################################################################################
25 #
26 # NAME
27 #       lf-echo-stderr
28 #
29 # SYNOPSIS
30 #   source ~/lf-env.sh
31 #
32 #   lf-echo-stderr "this entire" "string will be sent to stderr"
33 #
34 # DESCRIPTION
35 #   This function will echo all command line aruments to 'stderr'
36 #
37 # RETURN VALUE
38 #   None
39 #
40 ################################################################################
41
42 lf-echo-stderr () {
43     echo "$@" 1>&2
44 }
45
46 ################################################################################
47 #
48 # NAME
49 #       lf-boolean
50 #
51 # SYNOPSIS
52 #   # shellcheck disable=SC1090
53 #   source ~/lf-env.sh
54 #
55 #   if lf-boolean $VAR; then
56 #       echo "VAR is true"
57 #   fi
58 #
59 # DESCRIPTION
60 #   This function will return a BOOLEAN (true or false) based upon the value
61 #   of VAR. The value of VAR will be mapped to lower case. If VAR maps to
62 #   "true", return true(0). If VAR maps to "false", return false(1).  Any
63 #   other values will return false(2) and an error message.
64 #
65 # RETURN VALUES
66 #   OK: 0
67 #   Fail: 1 or 2
68 #
69 ################################################################################
70
71 lf-boolean () {
72     if (( $# != 1 )); then
73         echo "ERROR: ${FUNCNAME[0]}() line: ${BASH_LINENO[0]} :"\
74         " Missing Required Argument"
75         return 1
76     fi
77     local bool
78     bool=$(echo "$1" | tr '[:upper:]' '[:lower:]')
79     case $bool in
80         true)  return 0 ;;
81         false) return 1 ;;
82         '')
83             lf-echo-stderr "ERROR: ${FUNCNAME[0]}() line:{BASH_LINENO[0]} :"\
84             " A boolean cannot be a empty string" >&2
85             return 2
86             ;;
87         *)
88             lf-echo-stderr "ERROR: ${FUNCNAME[0]}() line: ${BASH_LINENO[0]} :"\
89             " Invalid value for a boolean: '$bool'"
90             return 2
91             ;;
92     esac
93 }
94
95 ################################################################################
96 #
97 # NAME
98 #   lf-activate-venv [-p|--python python] [-v|--venv-file] [--no-path]
99 #                    [--system-site-packages] [package]...
100 #
101 # SYNOPSIS
102 #   # shellcheck disable=SC1090
103 #   source ~/lf-env.sh
104 #
105 #   lf-activate-venv tox tox-pyenv
106 #   or
107 #   lf-activate-venv jenkins-job-builder
108 #   or
109 #   lf-activate-venv lftools
110 #   or
111 #   lf-activate-venv --python python3.8 git-review
112 #
113 #   lf-activate-venv --python python3.8 --venv-file /tmp/.myvenv git-review
114 #
115 # DESCRIPTION
116 #   This function will create a new Python Virtual Environment (venv) and
117 #   install the specified packages in the new venv.  The venv will be installed
118 #   in $lf_venv and by default, the $lf_venv/bin directory will be prepended
119 #   to the PATH.
120 #
121 #   The 'lf_venv' variable will be set so you can directly execute commands
122 #   in the venv with: $lf_venv/bin/command. lf-activate-venv() will check for
123 #   existing file '/tmp/.os_lf_venv' and set 'lf_venv' if the file exists.
124 #
125 #   The function provides a --venv-file path for saving the value of the 'lf_env'
126 #   that can re-used later. By default '/tmp/.os_lf_venv' venv file is created
127 #   when the --venv-file option is not specified.
128 #
129 #   Subsequent calls to lf-activate-venv() will re-use the existing venv
130 #   throught and will NOT overwrite 'lf_venv', if the '/tmp/.os_lf_venv'
131 #   already exists.
132 #
133 #   If a new venv is required delete the file '/tmp/.os_lf_venv' before
134 #   calling lf-activate-venv() will create a fresh venv.
135 #
136 #   By default all packages are installed with '--upgrade-strategy eager'.
137 #   The venv will always contain pip & virtualenv.
138 #
139 #   Some packages have a default version. If one of those packages is specified,
140 #   the 'version' specifier will be added for the install. If the version is
141 #   specified on the command line that version will be used.
142 #   The following packages have default versions:
143 #       Package                  Version
144 #       jenkins-job-builder      $JJB_VERSION
145 #
146 #   If the --python flag is specified, the specified python executable will be
147 #   used to create the venv. The --python option must be in the PATH. The venv
148 #   will be located in $lf_venv (/tmp/venv-####).
149 #
150 #   If the --no-path flag is specified, $lf_venv/bin will not be prepended to
151 #   the PATH.
152 #
153 #   If the --system-site-packages flag is specified, the --system-site-packages
154 #   flag will be passed to the inital 'pip install' (python3* only).
155 #
156 # RETURN VALUES
157 #   OK: 0
158 #   Fail: 1
159 #
160 ################################################################################
161
162 lf-activate-venv () {
163     lf_venv=$(mktemp -d /tmp/venv-XXXX)
164     local venv_file="/tmp/.os_lf_venv"
165     local python=python3
166     local options
167     local set_path=true
168     local install_args=""
169     # set -x
170     options=$(getopt -o 'np:v:' -l 'no-path,system-site-packages,python:,venv-file:' \
171                 -n "${FUNCNAME[0]}" -- "$@" )
172     eval set -- "$options"
173     while true; do
174         case $1 in
175             -n|--no-path) set_path=false ; shift   ;;
176             -p|--python)  python="$2"      ; shift 2 ;;
177             -v|--venv-file) venv_file="$2" ; shift 2 ;;
178             --system-site-packages) install_args="--system-site-packages" ;
179                                     shift ;;
180             --) shift; break ;;
181             *)  lf-echo-stderr \
182                 "${FUNCNAME[0]}(): ERROR: Unknown switch '$1'." ;
183                 return 1 ;;
184         esac
185     done
186
187     case $python in
188     python2*)
189         local pkg_list="$*"
190         # For Python2, just create venv and install pip
191         virtualenv -p "$python" "$lf_venv" || return 1
192         "$lf_venv/bin/pip" install --upgrade --quiet pip || return 1
193         if [[ -z $pkg_list ]]; then
194             echo "${FUNCNAME[0]}(): WARNING: No packages to install"
195             return 0
196         fi
197         echo "${FUNCNAME[0]}(): INFO: Installing: $pkg_list"
198         # $pkg_list is expected to be unquoted
199         # shellcheck disable=SC2086
200         "$lf_venv/bin/pip" install --upgrade --quiet $pkg_list || return 1
201         ;;
202     python3*)
203         local pkg_list=""
204         # Use pyenv for selecting the python version
205         if [[ -d "/opt/pyenv" ]]; then
206             echo "Setup pyenv:"
207             export PYENV_ROOT="/opt/pyenv"
208             export PATH="$PYENV_ROOT/bin:$PATH"
209             pyenv versions
210             if command -v pyenv 1>/dev/null 2>&1; then
211                 eval "$(pyenv init - --no-rehash)"
212                 pyenv local $(lf-pyver "${python}")
213             fi
214         fi
215
216         # Add version specifier for some packages
217         for arg in "$@"; do
218             case $arg in
219                 jenkins-job-builder)
220                     pkg_list+="jenkins-job-builder==${JJB_VERSION:-2.8.0} " ;;
221                 *)                   pkg_list+="$arg " ;;
222             esac
223         done
224
225         # Precedence:
226         # - Re-use venv:
227         #     1. --venv-file <path/to/file> as lf_venv
228         #     2. default: "/tmp/.os_lf_venv"
229         # - Create new venv when 1. and 2. is absent
230         if [ -f "$venv_file" ]; then
231             lf_venv=$(cat "$venv_file")
232             echo "${FUNCNAME[0]}(): INFO: Reuse venv:$lf_venv from" \
233                 "file:$venv_file"
234         elif [ ! -f "$venv_file" ]; then
235             $python -m venv "$install_args" "$lf_venv" || return 1
236             echo "${FUNCNAME[0]}(): INFO: Creating $python venv at $lf_venv"
237             echo "$lf_venv" > "$venv_file"
238             echo "${FUNCNAME[0]}(): INFO: Save venv in file: $venv_file"
239         fi
240
241         "$lf_venv/bin/pip" install --upgrade --quiet pip virtualenv || return 1
242         if [[ -z $pkg_list ]]; then
243             echo "${FUNCNAME[0]}(): WARNING: No packages to install"
244             return 0
245         fi
246         echo "${FUNCNAME[0]}(): INFO: Installing: $pkg_list"
247         # $pkg_list is expected to be unquoted
248         # shellcheck disable=SC2086
249         "$lf_venv/bin/pip" install --upgrade --quiet --upgrade-strategy eager \
250                                 $pkg_list || return 1
251         ;;
252     *)
253         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: No support for: $python"
254         return 1
255         ;;
256     esac
257
258     if ! type "$python" > /dev/null; then
259         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: Unknown Python: $python"
260         return 1
261     fi
262
263     if $set_path; then
264         echo "${FUNCNAME[0]}(): INFO: Adding $lf_venv/bin to PATH"
265         PATH=$lf_venv/bin:$PATH
266         return 0
267     else
268         echo "${FUNCNAME[0]}(): INFO: Path not set, lf_venv set to: $lf_venv"
269     fi
270
271 }   # End lf-activate-venv
272
273 ################################################################################
274 #
275 # NAME
276 #   lf-git-validate-jira-urls
277 #
278 # SYNOPSIS
279 #   # shellcheck disable=SC1090
280 #   source ~/lf-env.sh
281 #
282 #   lf-git-validate-jira-urls
283 #
284 # DESCRIPTION
285 #   Check for JIRA URLS in the commit message
286 #
287 # RETURN VALUES
288 #   OK: 0
289 #   Fail: 1
290 #
291 ################################################################################
292
293 lf-git-validate-jira-urls () {
294     echo "Checking for JIRA URLs in commit message..."
295     # if JIRA_URL is not defined, nothing to do
296     if [[ -v JIRA_URL ]]; then
297         base_url=$(echo "$JIRA_URL" | awk -F'/' '{print $3}')
298         jira_link=$(git rev-list --format=%B --max-count=1 HEAD | \
299                     grep -io "http[s]*://$base_url/" || true)
300         if [[ -n $jira_link ]]; then
301             lf-echo-stderr \
302             "${FUNCNAME[0]}(): ERROR: JIRA URL found in commit message"
303             lf-echo-stderr \
304             'Add jira references as: Issue: <JIRAKEY>-<ISSUE#>,'\
305             ' instead of URLs'
306             return 1
307         fi
308     else
309         echo "${FUNCNAME[0]}(): WARNING: JIRA_URL not set, continuing anyway"
310     fi
311     return 0
312 }
313
314 ################################################################################
315 #
316 # NAME
317 #   lf-jjb-check-ascii
318 #
319 # SYNOPSIS
320 #   # shellcheck disable=SC1090
321 #   source ~/lf-env.sh
322 #
323 #   lf-jjb-check-ascii
324 #
325 # DESCRIPTION
326 #   Check for JJB YAML files containing non-printable ascii characters. This
327 #   function must be run from the top of the global-jjb repo.
328 #
329 # RETURN VALUES
330 #   OK: 0
331 #   Fail: 1
332 #
333 ################################################################################
334
335 lf-jjb-check-ascii () {
336     if [[ ! -d "jjb" ]]; then
337         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: missing jjb directory"
338         lf-echo-stderr \
339         "This function can only be run from top of global-jjb directory"
340         return 1
341     fi
342     if LC_ALL=C grep -I -r '[^[:print:][:space:]]' jjb/; then
343         lf-echo-stderr \
344         "${FUNCNAME[0]}(): ERROR: Found YAML files containing"\
345         " non-printable characters."
346         return 1
347     fi
348     echo "${FUNCNAME[0]}(): INFO: All JJB YAML files contain only printable"\
349     " ASCII characters"
350     return 0
351 }
352
353 ################################################################################
354 # Functions that assign Variables
355 ################################################################################
356
357 # These variables are shell (local) variables and need to be lower-case so
358 # Shellcheck knows they are shell variables and will check for
359 # 'used-before-set'.
360
361 lf-set-maven-options () {
362     # Disable 'unused-variable' check
363     # shellcheck disable=SC2034
364     maven_options="--show-version --batch-mode -Djenkins \
365         -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.\
366         transfer.Slf4jMavenTransferListener=warn \
367         -Dmaven.repo.local=/tmp/r \
368         -Dorg.ops4j.pax.url.mvn.localRepository=/tmp/r"
369 }
370
371 ################################################################################
372 #
373 # NAME
374 #   lf-pyver [python-version X.Y]
375 #
376 # SYNOPSIS
377 #   pyver 3.8 (outputs 3.8.13)
378 #   or
379 #   pyver 3.10 (outputs 3.10.6)
380 #   or
381 #   pyver 3 (outputs the most recent version 3.10.6)
382 #
383 # DESCRIPTION
384 #   The function takes short python version  in the format and X.Y and prints
385 #   the semver format (X.Y.Z) of the version that has been installed on the system
386 #   with pyenv.
387 #
388 #   When the expected version is not installed, nothing is returned.
389 #
390 # RETURN VALUES
391 #   OK: 0
392 #   Fail: 1
393 #
394 ################################################################################
395
396 lf-pyver() {
397     local py_version_xy="${1:-python3}"
398     local py_version_xyz=""
399
400     pyenv versions | sed 's/^[ *]* //' | awk '{ print $1 }' | grep -E '^[0-9.]*[0-9]$' \
401         > "/tmp/.pyenv_versions"
402     if [[ ! -s "/tmp/.pyenv_versions" ]]; then
403         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: pyenv not available"
404         return 1
405     fi
406
407     # strip out any prefix for (ex: 'python3.8' or 'v3.8') and match regex
408     # to the output return by pyenv
409     py_version_xyz=$(grep "^${py_version_xy//[a-zA-Z]/}" "/tmp/.pyenv_versions" |
410         sort -V | tail -n 1;)
411     if [[ -z ${py_version_xyz} ]]; then
412         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: Not installed on host: ${py_version_xy}"
413         return 1
414     fi
415     echo "${py_version_xyz}"
416     return 0
417 }