Fix: Address submodule update issues
[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             if [[ -n "$install_args" ]]; then
236                 $python -m venv "$install_args" "$lf_venv" || return 1
237             else
238                 $python -m venv "$lf_venv" || return 1
239             fi
240             echo "${FUNCNAME[0]}(): INFO: Creating $python venv at $lf_venv"
241             echo "$lf_venv" > "$venv_file"
242             echo "${FUNCNAME[0]}(): INFO: Save venv in file: $venv_file"
243         fi
244
245         "$lf_venv/bin/pip" install --upgrade --quiet pip virtualenv || return 1
246         if [[ -z $pkg_list ]]; then
247             echo "${FUNCNAME[0]}(): WARNING: No packages to install"
248             return 0
249         fi
250         echo "${FUNCNAME[0]}(): INFO: Installing: $pkg_list"
251         # $pkg_list is expected to be unquoted
252         # shellcheck disable=SC2086
253         "$lf_venv/bin/pip" install --upgrade --quiet --upgrade-strategy eager \
254                                 $pkg_list || return 1
255         ;;
256     *)
257         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: No support for: $python"
258         return 1
259         ;;
260     esac
261
262     if ! type "$python" > /dev/null; then
263         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: Unknown Python: $python"
264         return 1
265     fi
266
267     if $set_path; then
268         echo "${FUNCNAME[0]}(): INFO: Adding $lf_venv/bin to PATH"
269         PATH=$lf_venv/bin:$PATH
270         return 0
271     else
272         echo "${FUNCNAME[0]}(): INFO: Path not set, lf_venv set to: $lf_venv"
273     fi
274
275 }   # End lf-activate-venv
276
277 ################################################################################
278 #
279 # NAME
280 #   lf-git-validate-jira-urls
281 #
282 # SYNOPSIS
283 #   # shellcheck disable=SC1090
284 #   source ~/lf-env.sh
285 #
286 #   lf-git-validate-jira-urls
287 #
288 # DESCRIPTION
289 #   Check for JIRA URLS in the commit message
290 #
291 # RETURN VALUES
292 #   OK: 0
293 #   Fail: 1
294 #
295 ################################################################################
296
297 lf-git-validate-jira-urls () {
298     echo "Checking for JIRA URLs in commit message..."
299     # if JIRA_URL is not defined, nothing to do
300     if [[ -v JIRA_URL ]]; then
301         base_url=$(echo "$JIRA_URL" | awk -F'/' '{print $3}')
302         jira_link=$(git rev-list --format=%B --max-count=1 HEAD | \
303                     grep -io "http[s]*://$base_url/" || true)
304         if [[ -n $jira_link ]]; then
305             lf-echo-stderr \
306             "${FUNCNAME[0]}(): ERROR: JIRA URL found in commit message"
307             lf-echo-stderr \
308             'Add jira references as: Issue: <JIRAKEY>-<ISSUE#>,'\
309             ' instead of URLs'
310             return 1
311         fi
312     else
313         echo "${FUNCNAME[0]}(): WARNING: JIRA_URL not set, continuing anyway"
314     fi
315     return 0
316 }
317
318 ################################################################################
319 #
320 # NAME
321 #   lf-jjb-check-ascii
322 #
323 # SYNOPSIS
324 #   # shellcheck disable=SC1090
325 #   source ~/lf-env.sh
326 #
327 #   lf-jjb-check-ascii
328 #
329 # DESCRIPTION
330 #   Check for JJB YAML files containing non-printable ascii characters. This
331 #   function must be run from the top of the global-jjb repo.
332 #
333 # RETURN VALUES
334 #   OK: 0
335 #   Fail: 1
336 #
337 ################################################################################
338
339 lf-jjb-check-ascii () {
340     if [[ ! -d "jjb" ]]; then
341         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: missing jjb directory"
342         lf-echo-stderr \
343         "This function can only be run from top of global-jjb directory"
344         return 1
345     fi
346     if LC_ALL=C grep -I -r '[^[:print:][:space:]]' jjb/; then
347         lf-echo-stderr \
348         "${FUNCNAME[0]}(): ERROR: Found YAML files containing"\
349         " non-printable characters."
350         return 1
351     fi
352     echo "${FUNCNAME[0]}(): INFO: All JJB YAML files contain only printable"\
353     " ASCII characters"
354     return 0
355 }
356
357 ################################################################################
358 # Functions that assign Variables
359 ################################################################################
360
361 # These variables are shell (local) variables and need to be lower-case so
362 # Shellcheck knows they are shell variables and will check for
363 # 'used-before-set'.
364
365 lf-set-maven-options () {
366     # Disable 'unused-variable' check
367     # shellcheck disable=SC2034
368     maven_options="--show-version --batch-mode -Djenkins \
369         -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.\
370         transfer.Slf4jMavenTransferListener=warn \
371         -Dmaven.repo.local=/tmp/r \
372         -Dorg.ops4j.pax.url.mvn.localRepository=/tmp/r"
373 }
374
375 ################################################################################
376 #
377 # NAME
378 #   lf-pyver [python-version X.Y]
379 #
380 # SYNOPSIS
381 #   pyver 3.8 (outputs 3.8.13)
382 #   or
383 #   pyver 3.10 (outputs 3.10.6)
384 #   or
385 #   pyver 3 (outputs the most recent version 3.10.6)
386 #
387 # DESCRIPTION
388 #   The function takes short python version  in the format and X.Y and prints
389 #   the semver format (X.Y.Z) of the version that has been installed on the system
390 #   with pyenv.
391 #
392 #   When the expected version is not installed, nothing is returned.
393 #
394 # RETURN VALUES
395 #   OK: 0
396 #   Fail: 1
397 #
398 ################################################################################
399
400 lf-pyver() {
401     local py_version_xy="${1:-python3}"
402     local py_version_xyz=""
403
404     pyenv versions | sed 's/^[ *]* //' | awk '{ print $1 }' | grep -E '^[0-9.]*[0-9]$' \
405         > "/tmp/.pyenv_versions"
406     if [[ ! -s "/tmp/.pyenv_versions" ]]; then
407         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: pyenv not available"
408         return 1
409     fi
410
411     # strip out any prefix for (ex: 'python3.8' or 'v3.8') and match regex
412     # to the output return by pyenv
413     py_version_xyz=$(grep "^${py_version_xy//[a-zA-Z]/}" "/tmp/.pyenv_versions" |
414         sort -V | tail -n 1;)
415     if [[ -z ${py_version_xyz} ]]; then
416         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: Not installed on host: ${py_version_xy}"
417         return 1
418     fi
419     echo "${py_version_xyz}"
420     return 0
421 }