Fix: Use lf-activate-venv to install openstack dep
[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] [--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 # DESCRIPTION
114 #   This function will create a new Python Virtual Environment (venv) and
115 #   install the specified packages in the new venv.  The venv will be installed
116 #   in $lf_venv and by default, the $lf_venv/bin directory will be prepended
117 #   to the PATH.
118 #
119 #   The 'lf_venv' variable will be set so you can directly execute commands
120 #   in the venv with: $lf_venv/bin/command. Beware that subsequent calls to
121 #   lf-activate-venv() will overwrite 'lf_venv'.
122 #
123 #   By default all packages are installed with '--upgrade-strategy eager'.
124 #   The venv will always contain pip & virtualenv.
125 #
126 #   Some packages have a default version. If one of those packages is specified,
127 #   the 'version' specifier will be added for the install. If the version is
128 #   specified on the command line that version will be used.
129 #   The following packages have default versions:
130 #       Package                  Version
131 #       jenkins-job-builder      $JJB_VERSION
132 #
133 #   If the --python flag is specified, the specified python executable will be
134 #   used to create the venv. The --python option must be in the PATH. The venv
135 #   will be located in $lf_venv (/tmp/venv-####).
136 #
137 #   If the --no-path flag is specified, $lf_venv/bin will not be prepended to
138 #   the PATH.
139 #
140 #   If the --system-site-packages flag is specified, the --system-site-packages
141 #   flag will be passed to the inital 'pip install' (python3* only).
142 #
143 # RETURN VALUES
144 #   OK: 0
145 #   Fail: 1
146 #
147 ################################################################################
148
149 lf-activate-venv () {
150     lf_venv=$(mktemp -d /tmp/venv-XXXX)
151     local python=python3
152     local options
153     local set_path=true
154     local install_args=""
155     options=$(getopt -o 'n:p:' -l 'no-path,python:,system-site-packages' \
156                 -n "${FUNCNAME[0]}" -- "$@" )
157     eval set -- "$options"
158     while true; do
159         case $1 in
160             -n|--no-path) set_path=false ; shift   ;;
161             -p|--python)  python=$2      ; shift 2 ;;
162             --system-site-packages) install_args="--system-site-packages" ;
163                                     shift ;;
164             --) shift; break ;;
165             *)  lf-echo-stderr \
166                 "${FUNCNAME[0]}(): ERROR: Unknown switch '$1'." ;
167                 return 1 ;;
168         esac
169     done
170
171     echo "${FUNCNAME[0]}(): INFO: Creating $python venv at $lf_venv"
172
173     case $python in
174     python2*)
175         local pkg_list="$*"
176         # For Python2, just create venv and install pip
177         virtualenv -p "$python" "$lf_venv" || return 1
178         "$lf_venv/bin/pip" install --upgrade --quiet pip || return 1
179         if [[ -z $pkg_list ]]; then
180             echo "${FUNCNAME[0]}(): WARNING: No packages to install"
181             return 0
182         fi
183         echo "${FUNCNAME[0]}(): INFO: Installing: $pkg_list"
184         # $pkg_list is expected to be unquoted
185         # shellcheck disable=SC2086
186         "$lf_venv/bin/pip" install --upgrade --quiet $pkg_list || return 1
187         ;;
188     python3*)
189         local pkg_list=""
190         # Use pyenv for selecting the python version
191         if [[ -d "/opt/pyenv" ]]; then
192             # set_python_version = pyver "${python//[a-zA-Z]/}"
193             echo "Setup pyenv:"
194             export PYENV_ROOT="/opt/pyenv"
195             export PATH="$PYENV_ROOT/bin:$PATH"
196             pyenv versions
197             if command -v pyenv 1>/dev/null 2>&1; then
198                 eval "$(pyenv init - --no-rehash)"
199                 pyenv local $(lf-pyver "${python}")
200             fi
201         fi
202         # Add version specifier for some packages
203         for arg in "$@"; do
204             case $arg in
205                 jenkins-job-builder)
206                     pkg_list+="jenkins-job-builder==${JJB_VERSION:-2.8.0} " ;;
207                 *)                   pkg_list+="$arg " ;;
208             esac
209         done
210         $python -m venv "$install_args" "$lf_venv" || return 1
211         "$lf_venv/bin/pip" install --upgrade --quiet pip virtualenv || return 1
212         if [[ -z $pkg_list ]]; then
213             echo "${FUNCNAME[0]}(): WARNING: No packages to install"
214             return 0
215         fi
216         echo "${FUNCNAME[0]}(): INFO: Installing: $pkg_list"
217         # $pkg_list is expected to be unquoted
218         # shellcheck disable=SC2086
219         "$lf_venv/bin/pip" install --upgrade --quiet --upgrade-strategy eager \
220                                 $pkg_list || return 1
221         ;;
222     *)
223         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: No support for: $python"
224         return 1
225         ;;
226     esac
227
228     if ! type "$python" > /dev/null; then
229         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: Unknown Python: $python"
230         return 1
231     fi
232
233     if $set_path; then
234         echo "${FUNCNAME[0]}(): INFO: Adding $lf_venv/bin to PATH"
235         PATH=$lf_venv/bin:$PATH
236         return 0
237     else
238         echo "${FUNCNAME[0]}(): INFO: Path not set, lf_venv set to: $lf_venv"
239     fi
240
241 }   # End lf-activate-venv
242
243 ################################################################################
244 #
245 # NAME
246 #   lf-git-validate-jira-urls
247 #
248 # SYNOPSIS
249 #   # shellcheck disable=SC1090
250 #   source ~/lf-env.sh
251 #
252 #   lf-git-validate-jira-urls
253 #
254 # DESCRIPTION
255 #   Check for JIRA URLS in the commit message
256 #
257 # RETURN VALUES
258 #   OK: 0
259 #   Fail: 1
260 #
261 ################################################################################
262
263 lf-git-validate-jira-urls () {
264     echo "Checking for JIRA URLs in commit message..."
265     # if JIRA_URL is not defined, nothing to do
266     if [[ -v JIRA_URL ]]; then
267         base_url=$(echo "$JIRA_URL" | awk -F'/' '{print $3}')
268         jira_link=$(git rev-list --format=%B --max-count=1 HEAD | \
269                     grep -io "http[s]*://$base_url/" || true)
270         if [[ -n $jira_link ]]; then
271             lf-echo-stderr \
272             "${FUNCNAME[0]}(): ERROR: JIRA URL found in commit message"
273             lf-echo-stderr \
274             'Add jira references as: Issue: <JIRAKEY>-<ISSUE#>,'\
275             ' instead of URLs'
276             return 1
277         fi
278     else
279         echo "${FUNCNAME[0]}(): WARNING: JIRA_URL not set, continuing anyway"
280     fi
281     return 0
282 }
283
284 ################################################################################
285 #
286 # NAME
287 #   lf-jjb-check-ascii
288 #
289 # SYNOPSIS
290 #   # shellcheck disable=SC1090
291 #   source ~/lf-env.sh
292 #
293 #   lf-jjb-check-ascii
294 #
295 # DESCRIPTION
296 #   Check for JJB YAML files containing non-printable ascii characters. This
297 #   function must be run from the top of the global-jjb repo.
298 #
299 # RETURN VALUES
300 #   OK: 0
301 #   Fail: 1
302 #
303 ################################################################################
304
305 lf-jjb-check-ascii () {
306     if [[ ! -d "jjb" ]]; then
307         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: missing jjb directory"
308         lf-echo-stderr \
309         "This function can only be run from top of global-jjb directory"
310         return 1
311     fi
312     if LC_ALL=C grep -I -r '[^[:print:][:space:]]' jjb/; then
313         lf-echo-stderr \
314         "${FUNCNAME[0]}(): ERROR: Found YAML files containing"\
315         " non-printable characters."
316         return 1
317     fi
318     echo "${FUNCNAME[0]}(): INFO: All JJB YAML files contain only printable"\
319     " ASCII characters"
320     return 0
321 }
322
323 ################################################################################
324 # Functions that assign Variables
325 ################################################################################
326
327 # These variables are shell (local) variables and need to be lower-case so
328 # Shellcheck knows they are shell variables and will check for
329 # 'used-before-set'.
330
331 lf-set-maven-options () {
332     # Disable 'unused-variable' check
333     # shellcheck disable=SC2034
334     maven_options="--show-version --batch-mode -Djenkins \
335         -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.\
336         transfer.Slf4jMavenTransferListener=warn \
337         -Dmaven.repo.local=/tmp/r \
338         -Dorg.ops4j.pax.url.mvn.localRepository=/tmp/r"
339 }
340
341 ################################################################################
342 #
343 # NAME
344 #   lf-pyver [python-version X.Y]
345 #
346 # SYNOPSIS
347 #   pyver 3.8 (outputs 3.8.13)
348 #   or
349 #   pyver 3.10 (outputs 3.10.6)
350 #   or
351 #   pyver 3 (outputs the most recent version 3.10.6)
352 #
353 # DESCRIPTION
354 #   The function takes short python version  in the format and X.Y and prints
355 #   the semver format (X.Y.Z) of the version that has been installed on the system
356 #   with pyenv.
357 #
358 #   When the expected version is not installed, nothing is returned.
359 #
360 # RETURN VALUES
361 #   OK: 0
362 #   Fail: 1
363 #
364 ################################################################################
365
366 lf-pyver() {
367     local py_version_xy="${1:-python3}"
368     local py_version_xyz=""
369
370     pyenv versions | sed 's/^[ *]* //' | awk '{ print $1 }' | grep -E '^[0-9.]*[0-9]$' \
371         > "/tmp/.pyenv_versions"
372     if [[ ! -s "/tmp/.pyenv_versions" ]]; then
373         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: pyenv not available"
374         return 1
375     fi
376
377     # strip out any prefix for (ex: 'python3.8' or 'v3.8') and match regex
378     # to the output return by pyenv
379     py_version_xyz=$(grep "^${py_version_xy//[a-zA-Z]/}" "/tmp/.pyenv_versions" |
380         sort -V | tail -n 1;)
381     if [[ -z ${py_version_xyz} ]]; then
382         lf-echo-stderr "${FUNCNAME[0]}(): ERROR: Not installed on host: ${py_version_xy}"
383         return 1
384     fi
385     echo "${py_version_xyz}"
386     return 0
387 }