blob: eba4985e405ed3a4ce72fc2ee65d0c67cfd016df [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 ...
Ian Wienandaee18c72014-02-21 15:35:08 +110041function 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
Ian Wienandaee18c72014-02-21 15:35:08 +110055function 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
Ian Wienandaee18c72014-02-21 15:35:08 +110067function 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
Ian Wienandaee18c72014-02-21 15:35:08 +110081function 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
Ian Wienandaee18c72014-02-21 15:35:08 +110095function 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100109function 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 ...
Ian Wienandaee18c72014-02-21 15:35:08 +1100138function 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100170function 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)
Ian Wienandaee18c72014-02-21 15:35:08 +1100184function 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"
Ian Wienandaee18c72014-02-21 15:35:08 +1100216function die {
Dean Troyerdff49a22014-01-30 15:37:40 -0600217 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"
Ian Wienandaee18c72014-02-21 15:35:08 +1100234function die_if_not_set {
Dean Troyerdff49a22014-01-30 15:37:40 -0600235 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"
Ian Wienandaee18c72014-02-21 15:35:08 +1100248function err {
Dean Troyerdff49a22014-01-30 15:37:40 -0600249 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"
Ian Wienandaee18c72014-02-21 15:35:08 +1100265function err_if_not_set {
Dean Troyerdff49a22014-01-30 15:37:40 -0600266 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100294function is_set {
Dean Troyerdff49a22014-01-30 15:37:40 -0600295 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"
Ian Wienandaee18c72014-02-21 15:35:08 +1100301function warn {
Dean Troyerdff49a22014-01-30 15:37:40 -0600302 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100327function GetOSVersion {
Dean Troyerdff49a22014-01-30 15:37:40 -0600328 # 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100417function GetDistro {
Dean Troyerdff49a22014-01-30 15:37:40 -0600418 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``
Ian Wienandaee18c72014-02-21 15:35:08 +1100494function get_release_name_from_branch {
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600495 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>
Ian Wienandaee18c72014-02-21 15:35:08 +1100580function git_timed {
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100581 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100606function git_update_branch {
Dean Troyerdff49a22014-01-30 15:37:40 -0600607
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
Ian Wienandaee18c72014-02-21 15:35:08 +1100618function git_update_remote_branch {
Dean Troyerdff49a22014-01-30 15:37:40 -0600619
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
Ian Wienandaee18c72014-02-21 15:35:08 +1100628function git_update_tag {
Dean Troyerdff49a22014-01-30 15:37:40 -0600629
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
Ian Wienandaee18c72014-02-21 15:35:08 +1100644function get_default_host_ip {
Dean Troyerdff49a22014-01-30 15:37:40 -0600645 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100676function get_field {
Dean Troyerdff49a22014-01-30 15:37:40 -0600677 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``
Ian Wienandaee18c72014-02-21 15:35:08 +1100690function policy_add {
Dean Troyerdff49a22014-01-30 15:37:40 -0600691 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100720function _get_package_dir {
Dean Troyerdff49a22014-01-30 15:37:40 -0600721 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 ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100737function 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.
Ian Wienandaee18c72014-02-21 15:35:08 +1100762function 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 ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100873function 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 ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100898function is_package_installed {
Dean Troyerdff49a22014-01-30 15:37:40 -0600899 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 ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100918function uninstall_package {
Dean Troyerdff49a22014-01-30 15:37:40 -0600919 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 ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100933function yum_install {
Dean Troyerdff49a22014-01-30 15:37:40 -0600934 [[ "$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 ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100944function zypper_install {
Dean Troyerdff49a22014-01-30 15:37:40 -0600945 [[ "$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"
Ian Wienandaee18c72014-02-21 15:35:08 +1100961function _run_process {
Dean Troyerdff49a22014-01-30 15:37:40 -0600962 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100986function init_service_check {
Dean Troyerdff49a22014-01-30 15:37:40 -0600987 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
Ian Wienandaee18c72014-02-21 15:35:08 +1100999function is_running {
Dean Troyerdff49a22014-01-30 15:37:40 -06001000 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"
Ian Wienandaee18c72014-02-21 15:35:08 +11001012function run_process {
Dean Troyerdff49a22014-01-30 15:37:40 -06001013 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
Ian Wienandaee18c72014-02-21 15:35:08 +11001095function screen_stop {
Dean Troyerdff49a22014-01-30 15:37:40 -06001096 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
Ian Wienandaee18c72014-02-21 15:35:08 +11001115function service_check {
Dean Troyerdff49a22014-01-30 15:37:40 -06001116 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
Sean Dague09bd7c82014-02-03 08:35:26 +09001128 # make this -o errexit safe
1129 failures=`ls "$SERVICE_DIR/$SCREEN_NAME"/*.failure 2>/dev/null || /bin/true`
Dean Troyerdff49a22014-01-30 15:37:40 -06001130
1131 for service in $failures; do
1132 service=`basename $service`
1133 service=${service%.failure}
1134 echo "Error: Service $service is not running"
1135 done
1136
1137 if [ -n "$failures" ]; then
1138 echo "More details about the above errors can be found with screen, with ./rejoin-stack.sh"
1139 fi
1140}
1141
1142
1143# Python Functions
1144# ================
1145
1146# Get the path to the pip command.
1147# get_pip_command
Ian Wienandaee18c72014-02-21 15:35:08 +11001148function get_pip_command {
Dean Troyerdff49a22014-01-30 15:37:40 -06001149 which pip || which pip-python
1150
1151 if [ $? -ne 0 ]; then
1152 die $LINENO "Unable to find pip; cannot continue"
1153 fi
1154}
1155
1156# Get the path to the direcotry where python executables are installed.
1157# get_python_exec_prefix
Ian Wienandaee18c72014-02-21 15:35:08 +11001158function get_python_exec_prefix {
Dean Troyerdff49a22014-01-30 15:37:40 -06001159 if is_fedora || is_suse; then
1160 echo "/usr/bin"
1161 else
1162 echo "/usr/local/bin"
1163 fi
1164}
1165
1166# Wrapper for ``pip install`` to set cache and proxy environment variables
1167# Uses globals ``OFFLINE``, ``PIP_DOWNLOAD_CACHE``, ``PIP_USE_MIRRORS``,
1168# ``TRACK_DEPENDS``, ``*_proxy``
1169# pip_install package [package ...]
1170function pip_install {
Sean Dague45917cc2014-02-24 16:09:14 -05001171 local xtrace=$(set +o | grep xtrace)
1172 set +o xtrace
1173 if [[ "$OFFLINE" = "True" || -z "$@" ]]; then
1174 $xtrace
1175 return
1176 fi
1177
Dean Troyerdff49a22014-01-30 15:37:40 -06001178 if [[ -z "$os_PACKAGE" ]]; then
1179 GetOSVersion
1180 fi
1181 if [[ $TRACK_DEPENDS = True ]]; then
1182 source $DEST/.venv/bin/activate
1183 CMD_PIP=$DEST/.venv/bin/pip
1184 SUDO_PIP="env"
1185 else
1186 SUDO_PIP="sudo"
1187 CMD_PIP=$(get_pip_command)
1188 fi
1189
1190 # Mirror option not needed anymore because pypi has CDN available,
1191 # but it's useful in certain circumstances
1192 PIP_USE_MIRRORS=${PIP_USE_MIRRORS:-False}
1193 if [[ "$PIP_USE_MIRRORS" != "False" ]]; then
1194 PIP_MIRROR_OPT="--use-mirrors"
1195 fi
1196
1197 # pip < 1.4 has a bug where it will use an already existing build
1198 # directory unconditionally. Say an earlier component installs
1199 # foo v1.1; pip will have built foo's source in
1200 # /tmp/$USER-pip-build. Even if a later component specifies foo <
1201 # 1.1, the existing extracted build will be used and cause
1202 # confusing errors. By creating unique build directories we avoid
1203 # this problem. See https://github.com/pypa/pip/issues/709
1204 local pip_build_tmp=$(mktemp --tmpdir -d pip-build.XXXXX)
1205
Sean Dague45917cc2014-02-24 16:09:14 -05001206 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001207 $SUDO_PIP PIP_DOWNLOAD_CACHE=${PIP_DOWNLOAD_CACHE:-/var/cache/pip} \
1208 HTTP_PROXY=$http_proxy \
1209 HTTPS_PROXY=$https_proxy \
1210 NO_PROXY=$no_proxy \
1211 $CMD_PIP install --build=${pip_build_tmp} \
1212 $PIP_MIRROR_OPT $@ \
1213 && $SUDO_PIP rm -rf ${pip_build_tmp}
1214}
1215
Dean Troyeraf616d92014-02-17 12:57:55 -06001216# ``pip install -e`` the package, which processes the dependencies
1217# using pip before running `setup.py develop`
1218#
1219# Updates the dependencies in project_dir from the
1220# openstack/requirements global list before installing anything.
1221#
1222# Uses globals ``TRACK_DEPENDS``, ``REQUIREMENTS_DIR``, ``UNDO_REQUIREMENTS``
1223# setup_develop directory
Ian Wienandaee18c72014-02-21 15:35:08 +11001224function setup_develop {
Dean Troyeraf616d92014-02-17 12:57:55 -06001225 local project_dir=$1
1226
1227 echo "cd $REQUIREMENTS_DIR; $SUDO_CMD python update.py $project_dir"
1228
1229 # Don't update repo if local changes exist
1230 # Don't use buggy "git diff --quiet"
1231 (cd $project_dir && git diff --exit-code >/dev/null)
1232 local update_requirements=$?
1233
1234 if [ $update_requirements -eq 0 ]; then
1235 (cd $REQUIREMENTS_DIR; \
1236 $SUDO_CMD python update.py $project_dir)
1237 fi
1238
1239 setup_develop_no_requirements_update $project_dir
1240
1241 # We've just gone and possibly modified the user's source tree in an
1242 # automated way, which is considered bad form if it's a development
1243 # tree because we've screwed up their next git checkin. So undo it.
1244 #
1245 # However... there are some circumstances, like running in the gate
1246 # where we really really want the overridden version to stick. So provide
1247 # a variable that tells us whether or not we should UNDO the requirements
1248 # changes (this will be set to False in the OpenStack ci gate)
1249 if [ $UNDO_REQUIREMENTS = "True" ]; then
1250 if [ $update_requirements -eq 0 ]; then
1251 (cd $project_dir && git reset --hard)
1252 fi
1253 fi
1254}
1255
1256# ``pip install -e`` the package, which processes the dependencies
1257# using pip before running `setup.py develop`
1258# Uses globals ``STACK_USER``
1259# setup_develop_no_requirements_update directory
Ian Wienandaee18c72014-02-21 15:35:08 +11001260function setup_develop_no_requirements_update {
Dean Troyeraf616d92014-02-17 12:57:55 -06001261 local project_dir=$1
1262
1263 pip_install -e $project_dir
1264 # ensure that further actions can do things like setup.py sdist
1265 safe_chown -R $STACK_USER $1/*.egg-info
1266}
1267
Dean Troyerdff49a22014-01-30 15:37:40 -06001268
1269# Service Functions
1270# =================
1271
1272# remove extra commas from the input string (i.e. ``ENABLED_SERVICES``)
1273# _cleanup_service_list service-list
Ian Wienandaee18c72014-02-21 15:35:08 +11001274function _cleanup_service_list {
Dean Troyerdff49a22014-01-30 15:37:40 -06001275 echo "$1" | sed -e '
1276 s/,,/,/g;
1277 s/^,//;
1278 s/,$//
1279 '
1280}
1281
1282# disable_all_services() removes all current services
1283# from ``ENABLED_SERVICES`` to reset the configuration
1284# before a minimal installation
1285# Uses global ``ENABLED_SERVICES``
1286# disable_all_services
Ian Wienandaee18c72014-02-21 15:35:08 +11001287function disable_all_services {
Dean Troyerdff49a22014-01-30 15:37:40 -06001288 ENABLED_SERVICES=""
1289}
1290
1291# Remove all services starting with '-'. For example, to install all default
1292# services except rabbit (rabbit) set in ``localrc``:
1293# ENABLED_SERVICES+=",-rabbit"
1294# Uses global ``ENABLED_SERVICES``
1295# disable_negated_services
Ian Wienandaee18c72014-02-21 15:35:08 +11001296function disable_negated_services {
Dean Troyerdff49a22014-01-30 15:37:40 -06001297 local tmpsvcs="${ENABLED_SERVICES}"
1298 local service
1299 for service in ${tmpsvcs//,/ }; do
1300 if [[ ${service} == -* ]]; then
1301 tmpsvcs=$(echo ${tmpsvcs}|sed -r "s/(,)?(-)?${service#-}(,)?/,/g")
1302 fi
1303 done
1304 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1305}
1306
1307# disable_service() removes the services passed as argument to the
1308# ``ENABLED_SERVICES`` list, if they are present.
1309#
1310# For example:
1311# disable_service rabbit
1312#
1313# This function does not know about the special cases
1314# for nova, glance, and neutron built into is_service_enabled().
1315# Uses global ``ENABLED_SERVICES``
1316# disable_service service [service ...]
Ian Wienandaee18c72014-02-21 15:35:08 +11001317function disable_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001318 local tmpsvcs=",${ENABLED_SERVICES},"
1319 local service
1320 for service in $@; do
1321 if is_service_enabled $service; then
1322 tmpsvcs=${tmpsvcs//,$service,/,}
1323 fi
1324 done
1325 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1326}
1327
1328# enable_service() adds the services passed as argument to the
1329# ``ENABLED_SERVICES`` list, if they are not already present.
1330#
1331# For example:
1332# enable_service qpid
1333#
1334# This function does not know about the special cases
1335# for nova, glance, and neutron built into is_service_enabled().
1336# Uses global ``ENABLED_SERVICES``
1337# enable_service service [service ...]
Ian Wienandaee18c72014-02-21 15:35:08 +11001338function enable_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001339 local tmpsvcs="${ENABLED_SERVICES}"
1340 for service in $@; do
1341 if ! is_service_enabled $service; then
1342 tmpsvcs+=",$service"
1343 fi
1344 done
1345 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1346 disable_negated_services
1347}
1348
1349# is_service_enabled() checks if the service(s) specified as arguments are
1350# enabled by the user in ``ENABLED_SERVICES``.
1351#
1352# Multiple services specified as arguments are ``OR``'ed together; the test
1353# is a short-circuit boolean, i.e it returns on the first match.
1354#
1355# There are special cases for some 'catch-all' services::
1356# **nova** returns true if any service enabled start with **n-**
1357# **cinder** returns true if any service enabled start with **c-**
1358# **ceilometer** returns true if any service enabled start with **ceilometer**
1359# **glance** returns true if any service enabled start with **g-**
1360# **neutron** returns true if any service enabled start with **q-**
1361# **swift** returns true if any service enabled start with **s-**
1362# **trove** returns true if any service enabled start with **tr-**
1363# For backward compatibility if we have **swift** in ENABLED_SERVICES all the
1364# **s-** services will be enabled. This will be deprecated in the future.
1365#
1366# Cells within nova is enabled if **n-cell** is in ``ENABLED_SERVICES``.
1367# We also need to make sure to treat **n-cell-region** and **n-cell-child**
1368# as enabled in this case.
1369#
1370# Uses global ``ENABLED_SERVICES``
1371# is_service_enabled service [service ...]
Ian Wienandaee18c72014-02-21 15:35:08 +11001372function is_service_enabled {
Sean Dague45917cc2014-02-24 16:09:14 -05001373 local xtrace=$(set +o | grep xtrace)
1374 set +o xtrace
1375 local enabled=1
Dean Troyerdff49a22014-01-30 15:37:40 -06001376 services=$@
1377 for service in ${services}; do
Sean Dague45917cc2014-02-24 16:09:14 -05001378 [[ ,${ENABLED_SERVICES}, =~ ,${service}, ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001379
1380 # Look for top-level 'enabled' function for this service
1381 if type is_${service}_enabled >/dev/null 2>&1; then
1382 # A function exists for this service, use it
1383 is_${service}_enabled
Sean Dague45917cc2014-02-24 16:09:14 -05001384 enabled=$?
Dean Troyerdff49a22014-01-30 15:37:40 -06001385 fi
1386
1387 # TODO(dtroyer): Remove these legacy special-cases after the is_XXX_enabled()
1388 # are implemented
1389
Sean Dague45917cc2014-02-24 16:09:14 -05001390 [[ ${service} == n-cell-* && ${ENABLED_SERVICES} =~ "n-cell" ]] && enabled=0
1391 [[ ${service} == "nova" && ${ENABLED_SERVICES} =~ "n-" ]] && enabled=0
1392 [[ ${service} == "cinder" && ${ENABLED_SERVICES} =~ "c-" ]] && enabled=0
1393 [[ ${service} == "ceilometer" && ${ENABLED_SERVICES} =~ "ceilometer-" ]] && enabled=0
1394 [[ ${service} == "glance" && ${ENABLED_SERVICES} =~ "g-" ]] && enabled=0
1395 [[ ${service} == "ironic" && ${ENABLED_SERVICES} =~ "ir-" ]] && enabled=0
1396 [[ ${service} == "neutron" && ${ENABLED_SERVICES} =~ "q-" ]] && enabled=0
1397 [[ ${service} == "trove" && ${ENABLED_SERVICES} =~ "tr-" ]] && enabled=0
1398 [[ ${service} == "swift" && ${ENABLED_SERVICES} =~ "s-" ]] && enabled=0
1399 [[ ${service} == s-* && ${ENABLED_SERVICES} =~ "swift" ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001400 done
Sean Dague45917cc2014-02-24 16:09:14 -05001401 $xtrace
1402 return $enabled
Dean Troyerdff49a22014-01-30 15:37:40 -06001403}
1404
1405# Toggle enable/disable_service for services that must run exclusive of each other
1406# $1 The name of a variable containing a space-separated list of services
1407# $2 The name of a variable in which to store the enabled service's name
1408# $3 The name of the service to enable
1409function use_exclusive_service {
1410 local options=${!1}
1411 local selection=$3
1412 out=$2
1413 [ -z $selection ] || [[ ! "$options" =~ "$selection" ]] && return 1
1414 for opt in $options;do
1415 [[ "$opt" = "$selection" ]] && enable_service $opt || disable_service $opt
1416 done
1417 eval "$out=$selection"
1418 return 0
1419}
1420
1421
1422# System Function
1423# ===============
1424
1425# Only run the command if the target file (the last arg) is not on an
1426# NFS filesystem.
Ian Wienandaee18c72014-02-21 15:35:08 +11001427function _safe_permission_operation {
Sean Dague45917cc2014-02-24 16:09:14 -05001428 local xtrace=$(set +o | grep xtrace)
1429 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001430 local args=( $@ )
1431 local last
1432 local sudo_cmd
1433 local dir_to_check
1434
1435 let last="${#args[*]} - 1"
1436
1437 dir_to_check=${args[$last]}
1438 if [ ! -d "$dir_to_check" ]; then
1439 dir_to_check=`dirname "$dir_to_check"`
1440 fi
1441
1442 if is_nfs_directory "$dir_to_check" ; then
Sean Dague45917cc2014-02-24 16:09:14 -05001443 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001444 return 0
1445 fi
1446
1447 if [[ $TRACK_DEPENDS = True ]]; then
1448 sudo_cmd="env"
1449 else
1450 sudo_cmd="sudo"
1451 fi
1452
Sean Dague45917cc2014-02-24 16:09:14 -05001453 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001454 $sudo_cmd $@
1455}
1456
1457# Exit 0 if address is in network or 1 if address is not in network
1458# ip-range is in CIDR notation: 1.2.3.4/20
1459# address_in_net ip-address ip-range
Ian Wienandaee18c72014-02-21 15:35:08 +11001460function address_in_net {
Dean Troyerdff49a22014-01-30 15:37:40 -06001461 local ip=$1
1462 local range=$2
1463 local masklen=${range#*/}
1464 local network=$(maskip ${range%/*} $(cidr2netmask $masklen))
1465 local subnet=$(maskip $ip $(cidr2netmask $masklen))
1466 [[ $network == $subnet ]]
1467}
1468
1469# Add a user to a group.
1470# add_user_to_group user group
Ian Wienandaee18c72014-02-21 15:35:08 +11001471function add_user_to_group {
Dean Troyerdff49a22014-01-30 15:37:40 -06001472 local user=$1
1473 local group=$2
1474
1475 if [[ -z "$os_VENDOR" ]]; then
1476 GetOSVersion
1477 fi
1478
1479 # SLE11 and openSUSE 12.2 don't have the usual usermod
1480 if ! is_suse || [[ "$os_VENDOR" = "openSUSE" && "$os_RELEASE" != "12.2" ]]; then
1481 sudo usermod -a -G "$group" "$user"
1482 else
1483 sudo usermod -A "$group" "$user"
1484 fi
1485}
1486
1487# Convert CIDR notation to a IPv4 netmask
1488# cidr2netmask cidr-bits
Ian Wienandaee18c72014-02-21 15:35:08 +11001489function cidr2netmask {
Dean Troyerdff49a22014-01-30 15:37:40 -06001490 local maskpat="255 255 255 255"
1491 local maskdgt="254 252 248 240 224 192 128"
1492 set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3}
1493 echo ${1-0}.${2-0}.${3-0}.${4-0}
1494}
1495
1496# Gracefully cp only if source file/dir exists
1497# cp_it source destination
1498function cp_it {
1499 if [ -e $1 ] || [ -d $1 ]; then
1500 cp -pRL $1 $2
1501 fi
1502}
1503
1504# HTTP and HTTPS proxy servers are supported via the usual environment variables [1]
1505# ``http_proxy``, ``https_proxy`` and ``no_proxy``. They can be set in
1506# ``localrc`` or on the command line if necessary::
1507#
1508# [1] http://www.w3.org/Daemon/User/Proxies/ProxyClients.html
1509#
1510# http_proxy=http://proxy.example.com:3128/ no_proxy=repo.example.net ./stack.sh
1511
Ian Wienandaee18c72014-02-21 15:35:08 +11001512function export_proxy_variables {
Dean Troyerdff49a22014-01-30 15:37:40 -06001513 if [[ -n "$http_proxy" ]]; then
1514 export http_proxy=$http_proxy
1515 fi
1516 if [[ -n "$https_proxy" ]]; then
1517 export https_proxy=$https_proxy
1518 fi
1519 if [[ -n "$no_proxy" ]]; then
1520 export no_proxy=$no_proxy
1521 fi
1522}
1523
1524# Returns true if the directory is on a filesystem mounted via NFS.
Ian Wienandaee18c72014-02-21 15:35:08 +11001525function is_nfs_directory {
Dean Troyerdff49a22014-01-30 15:37:40 -06001526 local mount_type=`stat -f -L -c %T $1`
1527 test "$mount_type" == "nfs"
1528}
1529
1530# Return the network portion of the given IP address using netmask
1531# netmask is in the traditional dotted-quad format
1532# maskip ip-address netmask
Ian Wienandaee18c72014-02-21 15:35:08 +11001533function maskip {
Dean Troyerdff49a22014-01-30 15:37:40 -06001534 local ip=$1
1535 local mask=$2
1536 local l="${ip%.*}"; local r="${ip#*.}"; local n="${mask%.*}"; local m="${mask#*.}"
1537 local subnet=$((${ip%%.*}&${mask%%.*})).$((${r%%.*}&${m%%.*})).$((${l##*.}&${n##*.})).$((${ip##*.}&${mask##*.}))
1538 echo $subnet
1539}
1540
1541# Service wrapper to restart services
1542# restart_service service-name
Ian Wienandaee18c72014-02-21 15:35:08 +11001543function restart_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001544 if is_ubuntu; then
1545 sudo /usr/sbin/service $1 restart
1546 else
1547 sudo /sbin/service $1 restart
1548 fi
1549}
1550
1551# Only change permissions of a file or directory if it is not on an
1552# NFS filesystem.
Ian Wienandaee18c72014-02-21 15:35:08 +11001553function safe_chmod {
Dean Troyerdff49a22014-01-30 15:37:40 -06001554 _safe_permission_operation chmod $@
1555}
1556
1557# Only change ownership of a file or directory if it is not on an NFS
1558# filesystem.
Ian Wienandaee18c72014-02-21 15:35:08 +11001559function safe_chown {
Dean Troyerdff49a22014-01-30 15:37:40 -06001560 _safe_permission_operation chown $@
1561}
1562
1563# Service wrapper to start services
1564# start_service service-name
Ian Wienandaee18c72014-02-21 15:35:08 +11001565function start_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001566 if is_ubuntu; then
1567 sudo /usr/sbin/service $1 start
1568 else
1569 sudo /sbin/service $1 start
1570 fi
1571}
1572
1573# Service wrapper to stop services
1574# stop_service service-name
Ian Wienandaee18c72014-02-21 15:35:08 +11001575function stop_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001576 if is_ubuntu; then
1577 sudo /usr/sbin/service $1 stop
1578 else
1579 sudo /sbin/service $1 stop
1580 fi
1581}
1582
1583
1584# Restore xtrace
1585$XTRACE
1586
1587# Local variables:
1588# mode: shell-script
1589# End: