blob: 0d85068a2f0630ff91dda52fd23da3e0a911fab0 [file] [log] [blame]
Dean Troyerdff49a22014-01-30 15:37:40 -06001# functions-common - Common functions used by DevStack components
2#
3# The canonical copy of this file is maintained in the DevStack repo.
4# All modifications should be made there and then sync'ed to other repos
5# as required.
6#
7# This file is sorted alphabetically within the function groups.
8#
9# - Config Functions
10# - Control Functions
11# - Distro Functions
12# - Git Functions
13# - OpenStack Functions
14# - Package Functions
15# - Process Functions
16# - Python Functions
17# - Service Functions
18#
19# The following variables are assumed to be defined by certain functions:
20#
21# - ``ENABLED_SERVICES``
22# - ``ERROR_ON_CLONE``
23# - ``FILES``
24# - ``OFFLINE``
25# - ``PIP_DOWNLOAD_CACHE``
26# - ``PIP_USE_MIRRORS``
27# - ``RECLONE``
28# - ``TRACK_DEPENDS``
29# - ``http_proxy``, ``https_proxy``, ``no_proxy``
30
31# Save trace setting
32XTRACE=$(set +o | grep xtrace)
33set +o xtrace
34
35
36# Config Functions
37# ================
38
39# Append a new option in an ini file without replacing the old value
40# iniadd config-file section option value1 value2 value3 ...
41function iniadd() {
Sean Dague45917cc2014-02-24 16:09:14 -050042 local xtrace=$(set +o | grep xtrace)
43 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060044 local file=$1
45 local section=$2
46 local option=$3
47 shift 3
48 local values="$(iniget_multiline $file $section $option) $@"
49 iniset_multiline $file $section $option $values
Sean Dague45917cc2014-02-24 16:09:14 -050050 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060051}
52
53# Comment an option in an INI file
54# inicomment config-file section option
55function inicomment() {
Sean Dague45917cc2014-02-24 16:09:14 -050056 local xtrace=$(set +o | grep xtrace)
57 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060058 local file=$1
59 local section=$2
60 local option=$3
61 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|^\($option[ \t]*=.*$\)|#\1|" "$file"
Sean Dague45917cc2014-02-24 16:09:14 -050062 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060063}
64
65# Get an option from an INI file
66# iniget config-file section option
67function iniget() {
Sean Dague45917cc2014-02-24 16:09:14 -050068 local xtrace=$(set +o | grep xtrace)
69 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060070 local file=$1
71 local section=$2
72 local option=$3
73 local line
74 line=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ p; }" "$file")
75 echo ${line#*=}
Sean Dague45917cc2014-02-24 16:09:14 -050076 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060077}
78
79# Get a multiple line option from an INI file
80# iniget_multiline config-file section option
81function iniget_multiline() {
Sean Dague45917cc2014-02-24 16:09:14 -050082 local xtrace=$(set +o | grep xtrace)
83 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060084 local file=$1
85 local section=$2
86 local option=$3
87 local values
88 values=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { s/^$option[ \t]*=[ \t]*//gp; }" "$file")
89 echo ${values}
Sean Dague45917cc2014-02-24 16:09:14 -050090 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060091}
92
93# Determinate is the given option present in the INI file
94# ini_has_option config-file section option
95function ini_has_option() {
Sean Dague45917cc2014-02-24 16:09:14 -050096 local xtrace=$(set +o | grep xtrace)
97 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060098 local file=$1
99 local section=$2
100 local option=$3
101 local line
102 line=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ p; }" "$file")
Sean Dague45917cc2014-02-24 16:09:14 -0500103 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600104 [ -n "$line" ]
105}
106
107# Set an option in an INI file
108# iniset config-file section option value
109function iniset() {
Sean Dague45917cc2014-02-24 16:09:14 -0500110 local xtrace=$(set +o | grep xtrace)
111 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600112 local file=$1
113 local section=$2
114 local option=$3
115 local value=$4
116
117 [[ -z $section || -z $option ]] && return
118
119 if ! grep -q "^\[$section\]" "$file" 2>/dev/null; then
120 # Add section at the end
121 echo -e "\n[$section]" >>"$file"
122 fi
123 if ! ini_has_option "$file" "$section" "$option"; then
124 # Add it
125 sed -i -e "/^\[$section\]/ a\\
126$option = $value
127" "$file"
128 else
129 local sep=$(echo -ne "\x01")
130 # Replace it
131 sed -i -e '/^\['${section}'\]/,/^\[.*\]/ s'${sep}'^\('${option}'[ \t]*=[ \t]*\).*$'${sep}'\1'"${value}"${sep} "$file"
132 fi
Sean Dague45917cc2014-02-24 16:09:14 -0500133 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600134}
135
136# Set a multiple line option in an INI file
137# iniset_multiline config-file section option value1 value2 valu3 ...
138function iniset_multiline() {
Sean Dague45917cc2014-02-24 16:09:14 -0500139 local xtrace=$(set +o | grep xtrace)
140 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600141 local file=$1
142 local section=$2
143 local option=$3
144 shift 3
145 local values
146 for v in $@; do
147 # The later sed command inserts each new value in the line next to
148 # the section identifier, which causes the values to be inserted in
149 # the reverse order. Do a reverse here to keep the original order.
150 values="$v ${values}"
151 done
152 if ! grep -q "^\[$section\]" "$file"; then
153 # Add section at the end
154 echo -e "\n[$section]" >>"$file"
155 else
156 # Remove old values
157 sed -i -e "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ d; }" "$file"
158 fi
159 # Add new ones
160 for v in $values; do
161 sed -i -e "/^\[$section\]/ a\\
162$option = $v
163" "$file"
164 done
Sean Dague45917cc2014-02-24 16:09:14 -0500165 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600166}
167
168# Uncomment an option in an INI file
169# iniuncomment config-file section option
170function iniuncomment() {
Sean Dague45917cc2014-02-24 16:09:14 -0500171 local xtrace=$(set +o | grep xtrace)
172 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600173 local file=$1
174 local section=$2
175 local option=$3
176 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|[^ \t]*#[ \t]*\($option[ \t]*=.*$\)|\1|" "$file"
Sean Dague45917cc2014-02-24 16:09:14 -0500177 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600178}
179
180# Normalize config values to True or False
181# Accepts as False: 0 no No NO false False FALSE
182# Accepts as True: 1 yes Yes YES true True TRUE
183# VAR=$(trueorfalse default-value test-value)
184function trueorfalse() {
Sean Dague45917cc2014-02-24 16:09:14 -0500185 local xtrace=$(set +o | grep xtrace)
186 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600187 local default=$1
188 local testval=$2
189
190 [[ -z "$testval" ]] && { echo "$default"; return; }
191 [[ "0 no No NO false False FALSE" =~ "$testval" ]] && { echo "False"; return; }
192 [[ "1 yes Yes YES true True TRUE" =~ "$testval" ]] && { echo "True"; return; }
193 echo "$default"
Sean Dague45917cc2014-02-24 16:09:14 -0500194 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600195}
196
197
198# Control Functions
199# =================
200
201# Prints backtrace info
202# filename:lineno:function
203# backtrace level
204function backtrace {
205 local level=$1
206 local deep=$((${#BASH_SOURCE[@]} - 1))
207 echo "[Call Trace]"
208 while [ $level -le $deep ]; do
209 echo "${BASH_SOURCE[$deep]}:${BASH_LINENO[$deep-1]}:${FUNCNAME[$deep-1]}"
210 deep=$((deep - 1))
211 done
212}
213
214# Prints line number and "message" then exits
215# die $LINENO "message"
216function die() {
217 local exitcode=$?
218 set +o xtrace
219 local line=$1; shift
220 if [ $exitcode == 0 ]; then
221 exitcode=1
222 fi
223 backtrace 2
224 err $line "$*"
Dean Troyera25a6f62014-02-24 16:03:41 -0600225 # Give buffers a second to flush
226 sleep 1
Dean Troyerdff49a22014-01-30 15:37:40 -0600227 exit $exitcode
228}
229
230# Checks an environment variable is not set or has length 0 OR if the
231# exit code is non-zero and prints "message" and exits
232# NOTE: env-var is the variable name without a '$'
233# die_if_not_set $LINENO env-var "message"
234function die_if_not_set() {
235 local exitcode=$?
236 FXTRACE=$(set +o | grep xtrace)
237 set +o xtrace
238 local line=$1; shift
239 local evar=$1; shift
240 if ! is_set $evar || [ $exitcode != 0 ]; then
241 die $line "$*"
242 fi
243 $FXTRACE
244}
245
246# Prints line number and "message" in error format
247# err $LINENO "message"
248function err() {
249 local exitcode=$?
250 errXTRACE=$(set +o | grep xtrace)
251 set +o xtrace
252 local msg="[ERROR] ${BASH_SOURCE[2]}:$1 $2"
253 echo $msg 1>&2;
254 if [[ -n ${SCREEN_LOGDIR} ]]; then
255 echo $msg >> "${SCREEN_LOGDIR}/error.log"
256 fi
257 $errXTRACE
258 return $exitcode
259}
260
261# Checks an environment variable is not set or has length 0 OR if the
262# exit code is non-zero and prints "message"
263# NOTE: env-var is the variable name without a '$'
264# err_if_not_set $LINENO env-var "message"
265function err_if_not_set() {
266 local exitcode=$?
267 errinsXTRACE=$(set +o | grep xtrace)
268 set +o xtrace
269 local line=$1; shift
270 local evar=$1; shift
271 if ! is_set $evar || [ $exitcode != 0 ]; then
272 err $line "$*"
273 fi
274 $errinsXTRACE
275 return $exitcode
276}
277
278# Exit after outputting a message about the distribution not being supported.
279# exit_distro_not_supported [optional-string-telling-what-is-missing]
280function exit_distro_not_supported {
281 if [[ -z "$DISTRO" ]]; then
282 GetDistro
283 fi
284
285 if [ $# -gt 0 ]; then
286 die $LINENO "Support for $DISTRO is incomplete: no support for $@"
287 else
288 die $LINENO "Support for $DISTRO is incomplete."
289 fi
290}
291
292# Test if the named environment variable is set and not zero length
293# is_set env-var
294function is_set() {
295 local var=\$"$1"
296 eval "[ -n \"$var\" ]" # For ex.: sh -c "[ -n \"$var\" ]" would be better, but several exercises depends on this
297}
298
299# Prints line number and "message" in warning format
300# warn $LINENO "message"
301function warn() {
302 local exitcode=$?
303 errXTRACE=$(set +o | grep xtrace)
304 set +o xtrace
305 local msg="[WARNING] ${BASH_SOURCE[2]}:$1 $2"
306 echo $msg 1>&2;
307 if [[ -n ${SCREEN_LOGDIR} ]]; then
308 echo $msg >> "${SCREEN_LOGDIR}/error.log"
309 fi
310 $errXTRACE
311 return $exitcode
312}
313
314
315# Distro Functions
316# ================
317
318# Determine OS Vendor, Release and Update
319# Tested with OS/X, Ubuntu, RedHat, CentOS, Fedora
320# Returns results in global variables:
321# os_VENDOR - vendor name
322# os_RELEASE - release
323# os_UPDATE - update
324# os_PACKAGE - package type
325# os_CODENAME - vendor's codename for release
326# GetOSVersion
327GetOSVersion() {
328 # Figure out which vendor we are
329 if [[ -x "`which sw_vers 2>/dev/null`" ]]; then
330 # OS/X
331 os_VENDOR=`sw_vers -productName`
332 os_RELEASE=`sw_vers -productVersion`
333 os_UPDATE=${os_RELEASE##*.}
334 os_RELEASE=${os_RELEASE%.*}
335 os_PACKAGE=""
336 if [[ "$os_RELEASE" =~ "10.7" ]]; then
337 os_CODENAME="lion"
338 elif [[ "$os_RELEASE" =~ "10.6" ]]; then
339 os_CODENAME="snow leopard"
340 elif [[ "$os_RELEASE" =~ "10.5" ]]; then
341 os_CODENAME="leopard"
342 elif [[ "$os_RELEASE" =~ "10.4" ]]; then
343 os_CODENAME="tiger"
344 elif [[ "$os_RELEASE" =~ "10.3" ]]; then
345 os_CODENAME="panther"
346 else
347 os_CODENAME=""
348 fi
349 elif [[ -x $(which lsb_release 2>/dev/null) ]]; then
350 os_VENDOR=$(lsb_release -i -s)
351 os_RELEASE=$(lsb_release -r -s)
352 os_UPDATE=""
353 os_PACKAGE="rpm"
354 if [[ "Debian,Ubuntu,LinuxMint" =~ $os_VENDOR ]]; then
355 os_PACKAGE="deb"
356 elif [[ "SUSE LINUX" =~ $os_VENDOR ]]; then
357 lsb_release -d -s | grep -q openSUSE
358 if [[ $? -eq 0 ]]; then
359 os_VENDOR="openSUSE"
360 fi
361 elif [[ $os_VENDOR == "openSUSE project" ]]; then
362 os_VENDOR="openSUSE"
363 elif [[ $os_VENDOR =~ Red.*Hat ]]; then
364 os_VENDOR="Red Hat"
365 fi
366 os_CODENAME=$(lsb_release -c -s)
367 elif [[ -r /etc/redhat-release ]]; then
368 # Red Hat Enterprise Linux Server release 5.5 (Tikanga)
369 # Red Hat Enterprise Linux Server release 7.0 Beta (Maipo)
370 # CentOS release 5.5 (Final)
371 # CentOS Linux release 6.0 (Final)
372 # Fedora release 16 (Verne)
373 # XenServer release 6.2.0-70446c (xenenterprise)
374 os_CODENAME=""
375 for r in "Red Hat" CentOS Fedora XenServer; do
376 os_VENDOR=$r
377 if [[ -n "`grep \"$r\" /etc/redhat-release`" ]]; then
378 ver=`sed -e 's/^.* \([0-9].*\) (\(.*\)).*$/\1\|\2/' /etc/redhat-release`
379 os_CODENAME=${ver#*|}
380 os_RELEASE=${ver%|*}
381 os_UPDATE=${os_RELEASE##*.}
382 os_RELEASE=${os_RELEASE%.*}
383 break
384 fi
385 os_VENDOR=""
386 done
387 os_PACKAGE="rpm"
388 elif [[ -r /etc/SuSE-release ]]; then
389 for r in openSUSE "SUSE Linux"; do
390 if [[ "$r" = "SUSE Linux" ]]; then
391 os_VENDOR="SUSE LINUX"
392 else
393 os_VENDOR=$r
394 fi
395
396 if [[ -n "`grep \"$r\" /etc/SuSE-release`" ]]; then
397 os_CODENAME=`grep "CODENAME = " /etc/SuSE-release | sed 's:.* = ::g'`
398 os_RELEASE=`grep "VERSION = " /etc/SuSE-release | sed 's:.* = ::g'`
399 os_UPDATE=`grep "PATCHLEVEL = " /etc/SuSE-release | sed 's:.* = ::g'`
400 break
401 fi
402 os_VENDOR=""
403 done
404 os_PACKAGE="rpm"
405 # If lsb_release is not installed, we should be able to detect Debian OS
406 elif [[ -f /etc/debian_version ]] && [[ $(cat /proc/version) =~ "Debian" ]]; then
407 os_VENDOR="Debian"
408 os_PACKAGE="deb"
409 os_CODENAME=$(awk '/VERSION=/' /etc/os-release | sed 's/VERSION=//' | sed -r 's/\"|\(|\)//g' | awk '{print $2}')
410 os_RELEASE=$(awk '/VERSION_ID=/' /etc/os-release | sed 's/VERSION_ID=//' | sed 's/\"//g')
411 fi
412 export os_VENDOR os_RELEASE os_UPDATE os_PACKAGE os_CODENAME
413}
414
415# Translate the OS version values into common nomenclature
416# Sets global ``DISTRO`` from the ``os_*`` values
417function GetDistro() {
418 GetOSVersion
419 if [[ "$os_VENDOR" =~ (Ubuntu) || "$os_VENDOR" =~ (Debian) ]]; then
420 # 'Everyone' refers to Ubuntu / Debian releases by the code name adjective
421 DISTRO=$os_CODENAME
422 elif [[ "$os_VENDOR" =~ (Fedora) ]]; then
423 # For Fedora, just use 'f' and the release
424 DISTRO="f$os_RELEASE"
425 elif [[ "$os_VENDOR" =~ (openSUSE) ]]; then
426 DISTRO="opensuse-$os_RELEASE"
427 elif [[ "$os_VENDOR" =~ (SUSE LINUX) ]]; then
428 # For SLE, also use the service pack
429 if [[ -z "$os_UPDATE" ]]; then
430 DISTRO="sle${os_RELEASE}"
431 else
432 DISTRO="sle${os_RELEASE}sp${os_UPDATE}"
433 fi
434 elif [[ "$os_VENDOR" =~ (Red Hat) || "$os_VENDOR" =~ (CentOS) ]]; then
435 # Drop the . release as we assume it's compatible
436 DISTRO="rhel${os_RELEASE::1}"
437 elif [[ "$os_VENDOR" =~ (XenServer) ]]; then
438 DISTRO="xs$os_RELEASE"
439 else
440 # Catch-all for now is Vendor + Release + Update
441 DISTRO="$os_VENDOR-$os_RELEASE.$os_UPDATE"
442 fi
443 export DISTRO
444}
445
446# Utility function for checking machine architecture
447# is_arch arch-type
448function is_arch {
449 ARCH_TYPE=$1
450
451 [[ "$(uname -m)" == "$ARCH_TYPE" ]]
452}
453
454# Determine if current distribution is a Fedora-based distribution
455# (Fedora, RHEL, CentOS, etc).
456# is_fedora
457function is_fedora {
458 if [[ -z "$os_VENDOR" ]]; then
459 GetOSVersion
460 fi
461
462 [ "$os_VENDOR" = "Fedora" ] || [ "$os_VENDOR" = "Red Hat" ] || [ "$os_VENDOR" = "CentOS" ]
463}
464
465
466# Determine if current distribution is a SUSE-based distribution
467# (openSUSE, SLE).
468# is_suse
469function is_suse {
470 if [[ -z "$os_VENDOR" ]]; then
471 GetOSVersion
472 fi
473
474 [ "$os_VENDOR" = "openSUSE" ] || [ "$os_VENDOR" = "SUSE LINUX" ]
475}
476
477
478# Determine if current distribution is an Ubuntu-based distribution
479# It will also detect non-Ubuntu but Debian-based distros
480# is_ubuntu
481function is_ubuntu {
482 if [[ -z "$os_PACKAGE" ]]; then
483 GetOSVersion
484 fi
485 [ "$os_PACKAGE" = "deb" ]
486}
487
488
489# Git Functions
490# =============
491
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600492# Returns openstack release name for a given branch name
493# ``get_release_name_from_branch branch-name``
494function get_release_name_from_branch(){
495 local branch=$1
496 if [[ $branch =~ "stable/" ]]; then
497 echo ${branch#*/}
498 else
499 echo "master"
500 fi
501}
502
Dean Troyerdff49a22014-01-30 15:37:40 -0600503# git clone only if directory doesn't exist already. Since ``DEST`` might not
504# be owned by the installation user, we create the directory and change the
505# ownership to the proper user.
506# Set global RECLONE=yes to simulate a clone when dest-dir exists
507# Set global ERROR_ON_CLONE=True to abort execution with an error if the git repo
508# does not exist (default is False, meaning the repo will be cloned).
509# Uses global ``OFFLINE``
510# git_clone remote dest-dir branch
511function git_clone {
512 GIT_REMOTE=$1
513 GIT_DEST=$2
514 GIT_REF=$3
515 RECLONE=$(trueorfalse False $RECLONE)
516
517 if [[ "$OFFLINE" = "True" ]]; then
518 echo "Running in offline mode, clones already exist"
519 # print out the results so we know what change was used in the logs
520 cd $GIT_DEST
521 git show --oneline | head -1
522 return
523 fi
524
525 if echo $GIT_REF | egrep -q "^refs"; then
526 # If our branch name is a gerrit style refs/changes/...
527 if [[ ! -d $GIT_DEST ]]; then
528 [[ "$ERROR_ON_CLONE" = "True" ]] && \
529 die $LINENO "Cloning not allowed in this configuration"
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100530 git_timed clone $GIT_REMOTE $GIT_DEST
Dean Troyerdff49a22014-01-30 15:37:40 -0600531 fi
532 cd $GIT_DEST
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100533 git_timed fetch $GIT_REMOTE $GIT_REF && git checkout FETCH_HEAD
Dean Troyerdff49a22014-01-30 15:37:40 -0600534 else
535 # do a full clone only if the directory doesn't exist
536 if [[ ! -d $GIT_DEST ]]; then
537 [[ "$ERROR_ON_CLONE" = "True" ]] && \
538 die $LINENO "Cloning not allowed in this configuration"
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100539 git_timed clone $GIT_REMOTE $GIT_DEST
Dean Troyerdff49a22014-01-30 15:37:40 -0600540 cd $GIT_DEST
541 # This checkout syntax works for both branches and tags
542 git checkout $GIT_REF
543 elif [[ "$RECLONE" = "True" ]]; then
544 # if it does exist then simulate what clone does if asked to RECLONE
545 cd $GIT_DEST
546 # set the url to pull from and fetch
547 git remote set-url origin $GIT_REMOTE
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100548 git_timed fetch origin
Dean Troyerdff49a22014-01-30 15:37:40 -0600549 # remove the existing ignored files (like pyc) as they cause breakage
550 # (due to the py files having older timestamps than our pyc, so python
551 # thinks the pyc files are correct using them)
552 find $GIT_DEST -name '*.pyc' -delete
553
554 # handle GIT_REF accordingly to type (tag, branch)
555 if [[ -n "`git show-ref refs/tags/$GIT_REF`" ]]; then
556 git_update_tag $GIT_REF
557 elif [[ -n "`git show-ref refs/heads/$GIT_REF`" ]]; then
558 git_update_branch $GIT_REF
559 elif [[ -n "`git show-ref refs/remotes/origin/$GIT_REF`" ]]; then
560 git_update_remote_branch $GIT_REF
561 else
562 die $LINENO "$GIT_REF is neither branch nor tag"
563 fi
564
565 fi
566 fi
567
568 # print out the results so we know what change was used in the logs
569 cd $GIT_DEST
570 git show --oneline | head -1
571}
572
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100573# git can sometimes get itself infinitely stuck with transient network
574# errors or other issues with the remote end. This wraps git in a
575# timeout/retry loop and is intended to watch over non-local git
576# processes that might hang. GIT_TIMEOUT, if set, is passed directly
577# to timeout(1); otherwise the default value of 0 maintains the status
578# quo of waiting forever.
579# usage: git_timed <git-command>
580function git_timed() {
581 local count=0
582 local timeout=0
583
584 if [[ -n "${GIT_TIMEOUT}" ]]; then
585 timeout=${GIT_TIMEOUT}
586 fi
587
588 until timeout -s SIGINT ${timeout} git "$@"; do
589 # 124 is timeout(1)'s special return code when it reached the
590 # timeout; otherwise assume fatal failure
591 if [[ $? -ne 124 ]]; then
592 die $LINENO "git call failed: [git $@]"
593 fi
594
595 count=$(($count + 1))
596 warn "timeout ${count} for git call: [git $@]"
597 if [ $count -eq 3 ]; then
598 die $LINENO "Maximum of 3 git retries reached"
599 fi
600 sleep 5
601 done
602}
603
Dean Troyerdff49a22014-01-30 15:37:40 -0600604# git update using reference as a branch.
605# git_update_branch ref
606function git_update_branch() {
607
608 GIT_BRANCH=$1
609
610 git checkout -f origin/$GIT_BRANCH
611 # a local branch might not exist
612 git branch -D $GIT_BRANCH || true
613 git checkout -b $GIT_BRANCH
614}
615
616# git update using reference as a branch.
617# git_update_remote_branch ref
618function git_update_remote_branch() {
619
620 GIT_BRANCH=$1
621
622 git checkout -b $GIT_BRANCH -t origin/$GIT_BRANCH
623}
624
625# git update using reference as a tag. Be careful editing source at that repo
626# as working copy will be in a detached mode
627# git_update_tag ref
628function git_update_tag() {
629
630 GIT_TAG=$1
631
632 git tag -d $GIT_TAG
633 # fetching given tag only
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100634 git_timed fetch origin tag $GIT_TAG
Dean Troyerdff49a22014-01-30 15:37:40 -0600635 git checkout -f $GIT_TAG
636}
637
638
639# OpenStack Functions
640# ===================
641
642# Get the default value for HOST_IP
643# get_default_host_ip fixed_range floating_range host_ip_iface host_ip
644function get_default_host_ip() {
645 local fixed_range=$1
646 local floating_range=$2
647 local host_ip_iface=$3
648 local host_ip=$4
649
650 # Find the interface used for the default route
651 host_ip_iface=${host_ip_iface:-$(ip route | sed -n '/^default/{ s/.*dev \(\w\+\)\s\+.*/\1/; p; }' | head -1)}
652 # Search for an IP unless an explicit is set by ``HOST_IP`` environment variable
653 if [ -z "$host_ip" -o "$host_ip" == "dhcp" ]; then
654 host_ip=""
655 host_ips=`LC_ALL=C ip -f inet addr show ${host_ip_iface} | awk '/inet/ {split($2,parts,"/"); print parts[1]}'`
656 for IP in $host_ips; do
657 # Attempt to filter out IP addresses that are part of the fixed and
658 # floating range. Note that this method only works if the ``netaddr``
659 # python library is installed. If it is not installed, an error
660 # will be printed and the first IP from the interface will be used.
661 # If that is not correct set ``HOST_IP`` in ``localrc`` to the correct
662 # address.
663 if ! (address_in_net $IP $fixed_range || address_in_net $IP $floating_range); then
664 host_ip=$IP
665 break;
666 fi
667 done
668 fi
669 echo $host_ip
670}
671
672# Grab a numbered field from python prettytable output
673# Fields are numbered starting with 1
674# Reverse syntax is supported: -1 is the last field, -2 is second to last, etc.
675# get_field field-number
676function get_field() {
677 while read data; do
678 if [ "$1" -lt 0 ]; then
679 field="(\$(NF$1))"
680 else
681 field="\$$(($1 + 1))"
682 fi
683 echo "$data" | awk -F'[ \t]*\\|[ \t]*' "{print $field}"
684 done
685}
686
687# Add a policy to a policy.json file
688# Do nothing if the policy already exists
689# ``policy_add policy_file policy_name policy_permissions``
690function policy_add() {
691 local policy_file=$1
692 local policy_name=$2
693 local policy_perm=$3
694
695 if grep -q ${policy_name} ${policy_file}; then
696 echo "Policy ${policy_name} already exists in ${policy_file}"
697 return
698 fi
699
700 # Add a terminating comma to policy lines without one
701 # Remove the closing '}' and all lines following to the end-of-file
702 local tmpfile=$(mktemp)
703 uniq ${policy_file} | sed -e '
704 s/]$/],/
705 /^[}]/,$d
706 ' > ${tmpfile}
707
708 # Append policy and closing brace
709 echo " \"${policy_name}\": ${policy_perm}" >>${tmpfile}
710 echo "}" >>${tmpfile}
711
712 mv ${tmpfile} ${policy_file}
713}
714
715
716# Package Functions
717# =================
718
719# _get_package_dir
720function _get_package_dir() {
721 local pkg_dir
722 if is_ubuntu; then
723 pkg_dir=$FILES/apts
724 elif is_fedora; then
725 pkg_dir=$FILES/rpms
726 elif is_suse; then
727 pkg_dir=$FILES/rpms-suse
728 else
729 exit_distro_not_supported "list of packages"
730 fi
731 echo "$pkg_dir"
732}
733
734# Wrapper for ``apt-get`` to set cache and proxy environment variables
735# Uses globals ``OFFLINE``, ``*_proxy``
736# apt_get operation package [package ...]
737function apt_get() {
Sean Dague45917cc2014-02-24 16:09:14 -0500738 local xtrace=$(set +o | grep xtrace)
739 set +o xtrace
740
Dean Troyerdff49a22014-01-30 15:37:40 -0600741 [[ "$OFFLINE" = "True" || -z "$@" ]] && return
742 local sudo="sudo"
743 [[ "$(id -u)" = "0" ]] && sudo="env"
Sean Dague45917cc2014-02-24 16:09:14 -0500744
745 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600746 $sudo DEBIAN_FRONTEND=noninteractive \
747 http_proxy=$http_proxy https_proxy=$https_proxy \
748 no_proxy=$no_proxy \
749 apt-get --option "Dpkg::Options::=--force-confold" --assume-yes "$@"
750}
751
752# get_packages() collects a list of package names of any type from the
753# prerequisite files in ``files/{apts|rpms}``. The list is intended
754# to be passed to a package installer such as apt or yum.
755#
756# Only packages required for the services in 1st argument will be
757# included. Two bits of metadata are recognized in the prerequisite files:
758#
759# - ``# NOPRIME`` defers installation to be performed later in `stack.sh`
760# - ``# dist:DISTRO`` or ``dist:DISTRO1,DISTRO2`` limits the selection
761# of the package to the distros listed. The distro names are case insensitive.
762function get_packages() {
Sean Dague45917cc2014-02-24 16:09:14 -0500763 local xtrace=$(set +o | grep xtrace)
764 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600765 local services=$@
766 local package_dir=$(_get_package_dir)
767 local file_to_parse
768 local service
769
770 if [[ -z "$package_dir" ]]; then
771 echo "No package directory supplied"
772 return 1
773 fi
774 if [[ -z "$DISTRO" ]]; then
775 GetDistro
Sean Dague45917cc2014-02-24 16:09:14 -0500776 echo "Found Distro $DISTRO"
Dean Troyerdff49a22014-01-30 15:37:40 -0600777 fi
778 for service in ${services//,/ }; do
779 # Allow individual services to specify dependencies
780 if [[ -e ${package_dir}/${service} ]]; then
781 file_to_parse="${file_to_parse} $service"
782 fi
783 # NOTE(sdague) n-api needs glance for now because that's where
784 # glance client is
785 if [[ $service == n-api ]]; then
786 if [[ ! $file_to_parse =~ nova ]]; then
787 file_to_parse="${file_to_parse} nova"
788 fi
789 if [[ ! $file_to_parse =~ glance ]]; then
790 file_to_parse="${file_to_parse} glance"
791 fi
792 elif [[ $service == c-* ]]; then
793 if [[ ! $file_to_parse =~ cinder ]]; then
794 file_to_parse="${file_to_parse} cinder"
795 fi
796 elif [[ $service == ceilometer-* ]]; then
797 if [[ ! $file_to_parse =~ ceilometer ]]; then
798 file_to_parse="${file_to_parse} ceilometer"
799 fi
800 elif [[ $service == s-* ]]; then
801 if [[ ! $file_to_parse =~ swift ]]; then
802 file_to_parse="${file_to_parse} swift"
803 fi
804 elif [[ $service == n-* ]]; then
805 if [[ ! $file_to_parse =~ nova ]]; then
806 file_to_parse="${file_to_parse} nova"
807 fi
808 elif [[ $service == g-* ]]; then
809 if [[ ! $file_to_parse =~ glance ]]; then
810 file_to_parse="${file_to_parse} glance"
811 fi
812 elif [[ $service == key* ]]; then
813 if [[ ! $file_to_parse =~ keystone ]]; then
814 file_to_parse="${file_to_parse} keystone"
815 fi
816 elif [[ $service == q-* ]]; then
817 if [[ ! $file_to_parse =~ neutron ]]; then
818 file_to_parse="${file_to_parse} neutron"
819 fi
820 fi
821 done
822
823 for file in ${file_to_parse}; do
824 local fname=${package_dir}/${file}
825 local OIFS line package distros distro
826 [[ -e $fname ]] || continue
827
828 OIFS=$IFS
829 IFS=$'\n'
830 for line in $(<${fname}); do
831 if [[ $line =~ "NOPRIME" ]]; then
832 continue
833 fi
834
835 # Assume we want this package
836 package=${line%#*}
837 inst_pkg=1
838
839 # Look for # dist:xxx in comment
840 if [[ $line =~ (.*)#.*dist:([^ ]*) ]]; then
841 # We are using BASH regexp matching feature.
842 package=${BASH_REMATCH[1]}
843 distros=${BASH_REMATCH[2]}
844 # In bash ${VAR,,} will lowecase VAR
845 # Look for a match in the distro list
846 if [[ ! ${distros,,} =~ ${DISTRO,,} ]]; then
847 # If no match then skip this package
848 inst_pkg=0
849 fi
850 fi
851
852 # Look for # testonly in comment
853 if [[ $line =~ (.*)#.*testonly.* ]]; then
854 package=${BASH_REMATCH[1]}
855 # Are we installing test packages? (test for the default value)
856 if [[ $INSTALL_TESTONLY_PACKAGES = "False" ]]; then
857 # If not installing test packages the skip this package
858 inst_pkg=0
859 fi
860 fi
861
862 if [[ $inst_pkg = 1 ]]; then
863 echo $package
864 fi
865 done
866 IFS=$OIFS
867 done
Sean Dague45917cc2014-02-24 16:09:14 -0500868 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600869}
870
871# Distro-agnostic package installer
872# install_package package [package ...]
873function install_package() {
Sean Dague45917cc2014-02-24 16:09:14 -0500874 local xtrace=$(set +o | grep xtrace)
875 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600876 if is_ubuntu; then
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600877 # if there are transient errors pulling the updates, that's fine. It may
878 # be secondary repositories that we don't really care about.
879 [[ "$NO_UPDATE_REPOS" = "True" ]] || apt_get update || /bin/true
Dean Troyerdff49a22014-01-30 15:37:40 -0600880 NO_UPDATE_REPOS=True
881
Sean Dague45917cc2014-02-24 16:09:14 -0500882 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600883 apt_get install "$@"
884 elif is_fedora; then
Sean Dague45917cc2014-02-24 16:09:14 -0500885 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600886 yum_install "$@"
887 elif is_suse; then
Sean Dague45917cc2014-02-24 16:09:14 -0500888 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600889 zypper_install "$@"
890 else
Sean Dague45917cc2014-02-24 16:09:14 -0500891 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600892 exit_distro_not_supported "installing packages"
893 fi
894}
895
896# Distro-agnostic function to tell if a package is installed
897# is_package_installed package [package ...]
898function is_package_installed() {
899 if [[ -z "$@" ]]; then
900 return 1
901 fi
902
903 if [[ -z "$os_PACKAGE" ]]; then
904 GetOSVersion
905 fi
906
907 if [[ "$os_PACKAGE" = "deb" ]]; then
908 dpkg -s "$@" > /dev/null 2> /dev/null
909 elif [[ "$os_PACKAGE" = "rpm" ]]; then
910 rpm --quiet -q "$@"
911 else
912 exit_distro_not_supported "finding if a package is installed"
913 fi
914}
915
916# Distro-agnostic package uninstaller
917# uninstall_package package [package ...]
918function uninstall_package() {
919 if is_ubuntu; then
920 apt_get purge "$@"
921 elif is_fedora; then
922 sudo yum remove -y "$@"
923 elif is_suse; then
924 sudo zypper rm "$@"
925 else
926 exit_distro_not_supported "uninstalling packages"
927 fi
928}
929
930# Wrapper for ``yum`` to set proxy environment variables
931# Uses globals ``OFFLINE``, ``*_proxy``
932# yum_install package [package ...]
933function yum_install() {
934 [[ "$OFFLINE" = "True" ]] && return
935 local sudo="sudo"
936 [[ "$(id -u)" = "0" ]] && sudo="env"
937 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
938 no_proxy=$no_proxy \
939 yum install -y "$@"
940}
941
942# zypper wrapper to set arguments correctly
943# zypper_install package [package ...]
944function zypper_install() {
945 [[ "$OFFLINE" = "True" ]] && return
946 local sudo="sudo"
947 [[ "$(id -u)" = "0" ]] && sudo="env"
948 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
949 zypper --non-interactive install --auto-agree-with-licenses "$@"
950}
951
952
953# Process Functions
954# =================
955
956# _run_process() is designed to be backgrounded by run_process() to simulate a
957# fork. It includes the dirty work of closing extra filehandles and preparing log
958# files to produce the same logs as screen_it(). The log filename is derived
959# from the service name and global-and-now-misnamed SCREEN_LOGDIR
960# _run_process service "command-line"
961function _run_process() {
962 local service=$1
963 local command="$2"
964
965 # Undo logging redirections and close the extra descriptors
966 exec 1>&3
967 exec 2>&3
968 exec 3>&-
969 exec 6>&-
970
971 if [[ -n ${SCREEN_LOGDIR} ]]; then
972 exec 1>&${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log 2>&1
973 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
974
975 # TODO(dtroyer): Hack to get stdout from the Python interpreter for the logs.
976 export PYTHONUNBUFFERED=1
977 fi
978
979 exec /bin/bash -c "$command"
980 die "$service exec failure: $command"
981}
982
983# Helper to remove the ``*.failure`` files under ``$SERVICE_DIR/$SCREEN_NAME``.
984# This is used for ``service_check`` when all the ``screen_it`` are called finished
985# init_service_check
986function init_service_check() {
987 SCREEN_NAME=${SCREEN_NAME:-stack}
988 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
989
990 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
991 mkdir -p "$SERVICE_DIR/$SCREEN_NAME"
992 fi
993
994 rm -f "$SERVICE_DIR/$SCREEN_NAME"/*.failure
995}
996
997# Find out if a process exists by partial name.
998# is_running name
999function is_running() {
1000 local name=$1
1001 ps auxw | grep -v grep | grep ${name} > /dev/null
1002 RC=$?
1003 # some times I really hate bash reverse binary logic
1004 return $RC
1005}
1006
1007# run_process() launches a child process that closes all file descriptors and
1008# then exec's the passed in command. This is meant to duplicate the semantics
1009# of screen_it() without screen. PIDs are written to
1010# $SERVICE_DIR/$SCREEN_NAME/$service.pid
1011# run_process service "command-line"
1012function run_process() {
1013 local service=$1
1014 local command="$2"
1015
1016 # Spawn the child process
1017 _run_process "$service" "$command" &
1018 echo $!
1019}
1020
1021# Helper to launch a service in a named screen
1022# screen_it service "command-line"
1023function screen_it {
1024 SCREEN_NAME=${SCREEN_NAME:-stack}
1025 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1026 USE_SCREEN=$(trueorfalse True $USE_SCREEN)
1027
1028 if is_service_enabled $1; then
1029 # Append the service to the screen rc file
1030 screen_rc "$1" "$2"
1031
1032 if [[ "$USE_SCREEN" = "True" ]]; then
1033 screen -S $SCREEN_NAME -X screen -t $1
1034
1035 if [[ -n ${SCREEN_LOGDIR} ]]; then
1036 screen -S $SCREEN_NAME -p $1 -X logfile ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log
1037 screen -S $SCREEN_NAME -p $1 -X log on
1038 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
1039 fi
1040
1041 # sleep to allow bash to be ready to be send the command - we are
1042 # creating a new window in screen and then sends characters, so if
1043 # bash isn't running by the time we send the command, nothing happens
1044 sleep 1.5
1045
1046 NL=`echo -ne '\015'`
1047 # This fun command does the following:
1048 # - the passed server command is backgrounded
1049 # - the pid of the background process is saved in the usual place
1050 # - the server process is brought back to the foreground
1051 # - if the server process exits prematurely the fg command errors
1052 # and a message is written to stdout and the service failure file
1053 # The pid saved can be used in screen_stop() as a process group
1054 # id to kill off all child processes
1055 screen -S $SCREEN_NAME -p $1 -X stuff "$2 & echo \$! >$SERVICE_DIR/$SCREEN_NAME/$1.pid; fg || echo \"$1 failed to start\" | tee \"$SERVICE_DIR/$SCREEN_NAME/$1.failure\"$NL"
1056 else
1057 # Spawn directly without screen
1058 run_process "$1" "$2" >$SERVICE_DIR/$SCREEN_NAME/$1.pid
1059 fi
1060 fi
1061}
1062
1063# Screen rc file builder
1064# screen_rc service "command-line"
1065function screen_rc {
1066 SCREEN_NAME=${SCREEN_NAME:-stack}
1067 SCREENRC=$TOP_DIR/$SCREEN_NAME-screenrc
1068 if [[ ! -e $SCREENRC ]]; then
1069 # Name the screen session
1070 echo "sessionname $SCREEN_NAME" > $SCREENRC
1071 # Set a reasonable statusbar
1072 echo "hardstatus alwayslastline '$SCREEN_HARDSTATUS'" >> $SCREENRC
1073 # Some distributions override PROMPT_COMMAND for the screen terminal type - turn that off
1074 echo "setenv PROMPT_COMMAND /bin/true" >> $SCREENRC
1075 echo "screen -t shell bash" >> $SCREENRC
1076 fi
1077 # If this service doesn't already exist in the screenrc file
1078 if ! grep $1 $SCREENRC 2>&1 > /dev/null; then
1079 NL=`echo -ne '\015'`
1080 echo "screen -t $1 bash" >> $SCREENRC
1081 echo "stuff \"$2$NL\"" >> $SCREENRC
1082
1083 if [[ -n ${SCREEN_LOGDIR} ]]; then
1084 echo "logfile ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log" >>$SCREENRC
1085 echo "log on" >>$SCREENRC
1086 fi
1087 fi
1088}
1089
1090# Stop a service in screen
1091# If a PID is available use it, kill the whole process group via TERM
1092# If screen is being used kill the screen window; this will catch processes
1093# that did not leave a PID behind
1094# screen_stop service
1095function screen_stop() {
1096 SCREEN_NAME=${SCREEN_NAME:-stack}
1097 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1098 USE_SCREEN=$(trueorfalse True $USE_SCREEN)
1099
1100 if is_service_enabled $1; then
1101 # Kill via pid if we have one available
1102 if [[ -r $SERVICE_DIR/$SCREEN_NAME/$1.pid ]]; then
1103 pkill -TERM -P -$(cat $SERVICE_DIR/$SCREEN_NAME/$1.pid)
1104 rm $SERVICE_DIR/$SCREEN_NAME/$1.pid
1105 fi
1106 if [[ "$USE_SCREEN" = "True" ]]; then
1107 # Clean up the screen window
1108 screen -S $SCREEN_NAME -p $1 -X kill
1109 fi
1110 fi
1111}
1112
1113# Helper to get the status of each running service
1114# service_check
1115function service_check() {
1116 local service
1117 local failures
1118 SCREEN_NAME=${SCREEN_NAME:-stack}
1119 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1120
1121
1122 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
1123 echo "No service status directory found"
1124 return
1125 fi
1126
1127 # Check if there is any falure flag file under $SERVICE_DIR/$SCREEN_NAME
1128 failures=`ls "$SERVICE_DIR/$SCREEN_NAME"/*.failure 2>/dev/null`
1129
1130 for service in $failures; do
1131 service=`basename $service`
1132 service=${service%.failure}
1133 echo "Error: Service $service is not running"
1134 done
1135
1136 if [ -n "$failures" ]; then
1137 echo "More details about the above errors can be found with screen, with ./rejoin-stack.sh"
1138 fi
1139}
1140
1141
1142# Python Functions
1143# ================
1144
1145# Get the path to the pip command.
1146# get_pip_command
1147function get_pip_command() {
1148 which pip || which pip-python
1149
1150 if [ $? -ne 0 ]; then
1151 die $LINENO "Unable to find pip; cannot continue"
1152 fi
1153}
1154
1155# Get the path to the direcotry where python executables are installed.
1156# get_python_exec_prefix
1157function get_python_exec_prefix() {
1158 if is_fedora || is_suse; then
1159 echo "/usr/bin"
1160 else
1161 echo "/usr/local/bin"
1162 fi
1163}
1164
1165# Wrapper for ``pip install`` to set cache and proxy environment variables
1166# Uses globals ``OFFLINE``, ``PIP_DOWNLOAD_CACHE``, ``PIP_USE_MIRRORS``,
1167# ``TRACK_DEPENDS``, ``*_proxy``
1168# pip_install package [package ...]
1169function pip_install {
Sean Dague45917cc2014-02-24 16:09:14 -05001170 local xtrace=$(set +o | grep xtrace)
1171 set +o xtrace
1172 if [[ "$OFFLINE" = "True" || -z "$@" ]]; then
1173 $xtrace
1174 return
1175 fi
1176
Dean Troyerdff49a22014-01-30 15:37:40 -06001177 if [[ -z "$os_PACKAGE" ]]; then
1178 GetOSVersion
1179 fi
1180 if [[ $TRACK_DEPENDS = True ]]; then
1181 source $DEST/.venv/bin/activate
1182 CMD_PIP=$DEST/.venv/bin/pip
1183 SUDO_PIP="env"
1184 else
1185 SUDO_PIP="sudo"
1186 CMD_PIP=$(get_pip_command)
1187 fi
1188
1189 # Mirror option not needed anymore because pypi has CDN available,
1190 # but it's useful in certain circumstances
1191 PIP_USE_MIRRORS=${PIP_USE_MIRRORS:-False}
1192 if [[ "$PIP_USE_MIRRORS" != "False" ]]; then
1193 PIP_MIRROR_OPT="--use-mirrors"
1194 fi
1195
1196 # pip < 1.4 has a bug where it will use an already existing build
1197 # directory unconditionally. Say an earlier component installs
1198 # foo v1.1; pip will have built foo's source in
1199 # /tmp/$USER-pip-build. Even if a later component specifies foo <
1200 # 1.1, the existing extracted build will be used and cause
1201 # confusing errors. By creating unique build directories we avoid
1202 # this problem. See https://github.com/pypa/pip/issues/709
1203 local pip_build_tmp=$(mktemp --tmpdir -d pip-build.XXXXX)
1204
Sean Dague45917cc2014-02-24 16:09:14 -05001205 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001206 $SUDO_PIP PIP_DOWNLOAD_CACHE=${PIP_DOWNLOAD_CACHE:-/var/cache/pip} \
1207 HTTP_PROXY=$http_proxy \
1208 HTTPS_PROXY=$https_proxy \
1209 NO_PROXY=$no_proxy \
1210 $CMD_PIP install --build=${pip_build_tmp} \
1211 $PIP_MIRROR_OPT $@ \
1212 && $SUDO_PIP rm -rf ${pip_build_tmp}
1213}
1214
Dean Troyeraf616d92014-02-17 12:57:55 -06001215# ``pip install -e`` the package, which processes the dependencies
1216# using pip before running `setup.py develop`
1217#
1218# Updates the dependencies in project_dir from the
1219# openstack/requirements global list before installing anything.
1220#
1221# Uses globals ``TRACK_DEPENDS``, ``REQUIREMENTS_DIR``, ``UNDO_REQUIREMENTS``
1222# setup_develop directory
1223function setup_develop() {
1224 local project_dir=$1
1225
Dean Troyeraf616d92014-02-17 12:57:55 -06001226 # Don't update repo if local changes exist
1227 # Don't use buggy "git diff --quiet"
Dean Troyer83b6c992014-02-27 12:41:28 -06001228 # ``errexit`` requires us to trap the exit code when the repo is changed
1229 local update_requirements=$(cd $project_dir && git diff --exit-code >/dev/null || echo "changed")
Dean Troyeraf616d92014-02-17 12:57:55 -06001230
Dean Troyer83b6c992014-02-27 12:41:28 -06001231 if [[ $update_requirements = "changed" ]]; then
Dean Troyeraf616d92014-02-17 12:57:55 -06001232 (cd $REQUIREMENTS_DIR; \
1233 $SUDO_CMD python update.py $project_dir)
1234 fi
1235
1236 setup_develop_no_requirements_update $project_dir
1237
1238 # We've just gone and possibly modified the user's source tree in an
1239 # automated way, which is considered bad form if it's a development
1240 # tree because we've screwed up their next git checkin. So undo it.
1241 #
1242 # However... there are some circumstances, like running in the gate
1243 # where we really really want the overridden version to stick. So provide
1244 # a variable that tells us whether or not we should UNDO the requirements
1245 # changes (this will be set to False in the OpenStack ci gate)
1246 if [ $UNDO_REQUIREMENTS = "True" ]; then
Dean Troyer83b6c992014-02-27 12:41:28 -06001247 if [[ $update_requirements = "changed" ]]; then
Dean Troyeraf616d92014-02-17 12:57:55 -06001248 (cd $project_dir && git reset --hard)
1249 fi
1250 fi
1251}
1252
1253# ``pip install -e`` the package, which processes the dependencies
1254# using pip before running `setup.py develop`
1255# Uses globals ``STACK_USER``
1256# setup_develop_no_requirements_update directory
1257function setup_develop_no_requirements_update() {
1258 local project_dir=$1
1259
1260 pip_install -e $project_dir
1261 # ensure that further actions can do things like setup.py sdist
1262 safe_chown -R $STACK_USER $1/*.egg-info
1263}
1264
Dean Troyerdff49a22014-01-30 15:37:40 -06001265
1266# Service Functions
1267# =================
1268
1269# remove extra commas from the input string (i.e. ``ENABLED_SERVICES``)
1270# _cleanup_service_list service-list
1271function _cleanup_service_list () {
1272 echo "$1" | sed -e '
1273 s/,,/,/g;
1274 s/^,//;
1275 s/,$//
1276 '
1277}
1278
1279# disable_all_services() removes all current services
1280# from ``ENABLED_SERVICES`` to reset the configuration
1281# before a minimal installation
1282# Uses global ``ENABLED_SERVICES``
1283# disable_all_services
1284function disable_all_services() {
1285 ENABLED_SERVICES=""
1286}
1287
1288# Remove all services starting with '-'. For example, to install all default
1289# services except rabbit (rabbit) set in ``localrc``:
1290# ENABLED_SERVICES+=",-rabbit"
1291# Uses global ``ENABLED_SERVICES``
1292# disable_negated_services
1293function disable_negated_services() {
1294 local tmpsvcs="${ENABLED_SERVICES}"
1295 local service
1296 for service in ${tmpsvcs//,/ }; do
1297 if [[ ${service} == -* ]]; then
1298 tmpsvcs=$(echo ${tmpsvcs}|sed -r "s/(,)?(-)?${service#-}(,)?/,/g")
1299 fi
1300 done
1301 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1302}
1303
1304# disable_service() removes the services passed as argument to the
1305# ``ENABLED_SERVICES`` list, if they are present.
1306#
1307# For example:
1308# disable_service rabbit
1309#
1310# This function does not know about the special cases
1311# for nova, glance, and neutron built into is_service_enabled().
1312# Uses global ``ENABLED_SERVICES``
1313# disable_service service [service ...]
1314function disable_service() {
1315 local tmpsvcs=",${ENABLED_SERVICES},"
1316 local service
1317 for service in $@; do
1318 if is_service_enabled $service; then
1319 tmpsvcs=${tmpsvcs//,$service,/,}
1320 fi
1321 done
1322 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1323}
1324
1325# enable_service() adds the services passed as argument to the
1326# ``ENABLED_SERVICES`` list, if they are not already present.
1327#
1328# For example:
1329# enable_service qpid
1330#
1331# This function does not know about the special cases
1332# for nova, glance, and neutron built into is_service_enabled().
1333# Uses global ``ENABLED_SERVICES``
1334# enable_service service [service ...]
1335function enable_service() {
1336 local tmpsvcs="${ENABLED_SERVICES}"
1337 for service in $@; do
1338 if ! is_service_enabled $service; then
1339 tmpsvcs+=",$service"
1340 fi
1341 done
1342 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1343 disable_negated_services
1344}
1345
1346# is_service_enabled() checks if the service(s) specified as arguments are
1347# enabled by the user in ``ENABLED_SERVICES``.
1348#
1349# Multiple services specified as arguments are ``OR``'ed together; the test
1350# is a short-circuit boolean, i.e it returns on the first match.
1351#
1352# There are special cases for some 'catch-all' services::
1353# **nova** returns true if any service enabled start with **n-**
1354# **cinder** returns true if any service enabled start with **c-**
1355# **ceilometer** returns true if any service enabled start with **ceilometer**
1356# **glance** returns true if any service enabled start with **g-**
1357# **neutron** returns true if any service enabled start with **q-**
1358# **swift** returns true if any service enabled start with **s-**
1359# **trove** returns true if any service enabled start with **tr-**
1360# For backward compatibility if we have **swift** in ENABLED_SERVICES all the
1361# **s-** services will be enabled. This will be deprecated in the future.
1362#
1363# Cells within nova is enabled if **n-cell** is in ``ENABLED_SERVICES``.
1364# We also need to make sure to treat **n-cell-region** and **n-cell-child**
1365# as enabled in this case.
1366#
1367# Uses global ``ENABLED_SERVICES``
1368# is_service_enabled service [service ...]
1369function is_service_enabled() {
Sean Dague45917cc2014-02-24 16:09:14 -05001370 local xtrace=$(set +o | grep xtrace)
1371 set +o xtrace
1372 local enabled=1
Dean Troyerdff49a22014-01-30 15:37:40 -06001373 services=$@
1374 for service in ${services}; do
Sean Dague45917cc2014-02-24 16:09:14 -05001375 [[ ,${ENABLED_SERVICES}, =~ ,${service}, ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001376
1377 # Look for top-level 'enabled' function for this service
1378 if type is_${service}_enabled >/dev/null 2>&1; then
1379 # A function exists for this service, use it
1380 is_${service}_enabled
Sean Dague45917cc2014-02-24 16:09:14 -05001381 enabled=$?
Dean Troyerdff49a22014-01-30 15:37:40 -06001382 fi
1383
1384 # TODO(dtroyer): Remove these legacy special-cases after the is_XXX_enabled()
1385 # are implemented
1386
Sean Dague45917cc2014-02-24 16:09:14 -05001387 [[ ${service} == n-cell-* && ${ENABLED_SERVICES} =~ "n-cell" ]] && enabled=0
1388 [[ ${service} == "nova" && ${ENABLED_SERVICES} =~ "n-" ]] && enabled=0
1389 [[ ${service} == "cinder" && ${ENABLED_SERVICES} =~ "c-" ]] && enabled=0
1390 [[ ${service} == "ceilometer" && ${ENABLED_SERVICES} =~ "ceilometer-" ]] && enabled=0
1391 [[ ${service} == "glance" && ${ENABLED_SERVICES} =~ "g-" ]] && enabled=0
1392 [[ ${service} == "ironic" && ${ENABLED_SERVICES} =~ "ir-" ]] && enabled=0
1393 [[ ${service} == "neutron" && ${ENABLED_SERVICES} =~ "q-" ]] && enabled=0
1394 [[ ${service} == "trove" && ${ENABLED_SERVICES} =~ "tr-" ]] && enabled=0
1395 [[ ${service} == "swift" && ${ENABLED_SERVICES} =~ "s-" ]] && enabled=0
1396 [[ ${service} == s-* && ${ENABLED_SERVICES} =~ "swift" ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001397 done
Sean Dague45917cc2014-02-24 16:09:14 -05001398 $xtrace
1399 return $enabled
Dean Troyerdff49a22014-01-30 15:37:40 -06001400}
1401
1402# Toggle enable/disable_service for services that must run exclusive of each other
1403# $1 The name of a variable containing a space-separated list of services
1404# $2 The name of a variable in which to store the enabled service's name
1405# $3 The name of the service to enable
1406function use_exclusive_service {
1407 local options=${!1}
1408 local selection=$3
1409 out=$2
1410 [ -z $selection ] || [[ ! "$options" =~ "$selection" ]] && return 1
1411 for opt in $options;do
1412 [[ "$opt" = "$selection" ]] && enable_service $opt || disable_service $opt
1413 done
1414 eval "$out=$selection"
1415 return 0
1416}
1417
1418
1419# System Function
1420# ===============
1421
1422# Only run the command if the target file (the last arg) is not on an
1423# NFS filesystem.
1424function _safe_permission_operation() {
Sean Dague45917cc2014-02-24 16:09:14 -05001425 local xtrace=$(set +o | grep xtrace)
1426 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001427 local args=( $@ )
1428 local last
1429 local sudo_cmd
1430 local dir_to_check
1431
1432 let last="${#args[*]} - 1"
1433
1434 dir_to_check=${args[$last]}
1435 if [ ! -d "$dir_to_check" ]; then
1436 dir_to_check=`dirname "$dir_to_check"`
1437 fi
1438
1439 if is_nfs_directory "$dir_to_check" ; then
Sean Dague45917cc2014-02-24 16:09:14 -05001440 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001441 return 0
1442 fi
1443
1444 if [[ $TRACK_DEPENDS = True ]]; then
1445 sudo_cmd="env"
1446 else
1447 sudo_cmd="sudo"
1448 fi
1449
Sean Dague45917cc2014-02-24 16:09:14 -05001450 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001451 $sudo_cmd $@
1452}
1453
1454# Exit 0 if address is in network or 1 if address is not in network
1455# ip-range is in CIDR notation: 1.2.3.4/20
1456# address_in_net ip-address ip-range
1457function address_in_net() {
1458 local ip=$1
1459 local range=$2
1460 local masklen=${range#*/}
1461 local network=$(maskip ${range%/*} $(cidr2netmask $masklen))
1462 local subnet=$(maskip $ip $(cidr2netmask $masklen))
1463 [[ $network == $subnet ]]
1464}
1465
1466# Add a user to a group.
1467# add_user_to_group user group
1468function add_user_to_group() {
1469 local user=$1
1470 local group=$2
1471
1472 if [[ -z "$os_VENDOR" ]]; then
1473 GetOSVersion
1474 fi
1475
1476 # SLE11 and openSUSE 12.2 don't have the usual usermod
1477 if ! is_suse || [[ "$os_VENDOR" = "openSUSE" && "$os_RELEASE" != "12.2" ]]; then
1478 sudo usermod -a -G "$group" "$user"
1479 else
1480 sudo usermod -A "$group" "$user"
1481 fi
1482}
1483
1484# Convert CIDR notation to a IPv4 netmask
1485# cidr2netmask cidr-bits
1486function cidr2netmask() {
1487 local maskpat="255 255 255 255"
1488 local maskdgt="254 252 248 240 224 192 128"
1489 set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3}
1490 echo ${1-0}.${2-0}.${3-0}.${4-0}
1491}
1492
1493# Gracefully cp only if source file/dir exists
1494# cp_it source destination
1495function cp_it {
1496 if [ -e $1 ] || [ -d $1 ]; then
1497 cp -pRL $1 $2
1498 fi
1499}
1500
1501# HTTP and HTTPS proxy servers are supported via the usual environment variables [1]
1502# ``http_proxy``, ``https_proxy`` and ``no_proxy``. They can be set in
1503# ``localrc`` or on the command line if necessary::
1504#
1505# [1] http://www.w3.org/Daemon/User/Proxies/ProxyClients.html
1506#
1507# http_proxy=http://proxy.example.com:3128/ no_proxy=repo.example.net ./stack.sh
1508
1509function export_proxy_variables() {
1510 if [[ -n "$http_proxy" ]]; then
1511 export http_proxy=$http_proxy
1512 fi
1513 if [[ -n "$https_proxy" ]]; then
1514 export https_proxy=$https_proxy
1515 fi
1516 if [[ -n "$no_proxy" ]]; then
1517 export no_proxy=$no_proxy
1518 fi
1519}
1520
1521# Returns true if the directory is on a filesystem mounted via NFS.
1522function is_nfs_directory() {
1523 local mount_type=`stat -f -L -c %T $1`
1524 test "$mount_type" == "nfs"
1525}
1526
1527# Return the network portion of the given IP address using netmask
1528# netmask is in the traditional dotted-quad format
1529# maskip ip-address netmask
1530function maskip() {
1531 local ip=$1
1532 local mask=$2
1533 local l="${ip%.*}"; local r="${ip#*.}"; local n="${mask%.*}"; local m="${mask#*.}"
1534 local subnet=$((${ip%%.*}&${mask%%.*})).$((${r%%.*}&${m%%.*})).$((${l##*.}&${n##*.})).$((${ip##*.}&${mask##*.}))
1535 echo $subnet
1536}
1537
1538# Service wrapper to restart services
1539# restart_service service-name
1540function restart_service() {
1541 if is_ubuntu; then
1542 sudo /usr/sbin/service $1 restart
1543 else
1544 sudo /sbin/service $1 restart
1545 fi
1546}
1547
1548# Only change permissions of a file or directory if it is not on an
1549# NFS filesystem.
1550function safe_chmod() {
1551 _safe_permission_operation chmod $@
1552}
1553
1554# Only change ownership of a file or directory if it is not on an NFS
1555# filesystem.
1556function safe_chown() {
1557 _safe_permission_operation chown $@
1558}
1559
1560# Service wrapper to start services
1561# start_service service-name
1562function start_service() {
1563 if is_ubuntu; then
1564 sudo /usr/sbin/service $1 start
1565 else
1566 sudo /sbin/service $1 start
1567 fi
1568}
1569
1570# Service wrapper to stop services
1571# stop_service service-name
1572function stop_service() {
1573 if is_ubuntu; then
1574 sudo /usr/sbin/service $1 stop
1575 else
1576 sudo /sbin/service $1 stop
1577 fi
1578}
1579
1580
1581# Restore xtrace
1582$XTRACE
1583
1584# Local variables:
1585# mode: shell-script
1586# End: