blob: 79003fcfaf1560803c18e7a7fd86e253feb955ed [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 "$*"
225 exit $exitcode
226}
227
228# Checks an environment variable is not set or has length 0 OR if the
229# exit code is non-zero and prints "message" and exits
230# NOTE: env-var is the variable name without a '$'
231# die_if_not_set $LINENO env-var "message"
232function die_if_not_set() {
233 local exitcode=$?
234 FXTRACE=$(set +o | grep xtrace)
235 set +o xtrace
236 local line=$1; shift
237 local evar=$1; shift
238 if ! is_set $evar || [ $exitcode != 0 ]; then
239 die $line "$*"
240 fi
241 $FXTRACE
242}
243
244# Prints line number and "message" in error format
245# err $LINENO "message"
246function err() {
247 local exitcode=$?
248 errXTRACE=$(set +o | grep xtrace)
249 set +o xtrace
250 local msg="[ERROR] ${BASH_SOURCE[2]}:$1 $2"
251 echo $msg 1>&2;
252 if [[ -n ${SCREEN_LOGDIR} ]]; then
253 echo $msg >> "${SCREEN_LOGDIR}/error.log"
254 fi
255 $errXTRACE
256 return $exitcode
257}
258
259# Checks an environment variable is not set or has length 0 OR if the
260# exit code is non-zero and prints "message"
261# NOTE: env-var is the variable name without a '$'
262# err_if_not_set $LINENO env-var "message"
263function err_if_not_set() {
264 local exitcode=$?
265 errinsXTRACE=$(set +o | grep xtrace)
266 set +o xtrace
267 local line=$1; shift
268 local evar=$1; shift
269 if ! is_set $evar || [ $exitcode != 0 ]; then
270 err $line "$*"
271 fi
272 $errinsXTRACE
273 return $exitcode
274}
275
276# Exit after outputting a message about the distribution not being supported.
277# exit_distro_not_supported [optional-string-telling-what-is-missing]
278function exit_distro_not_supported {
279 if [[ -z "$DISTRO" ]]; then
280 GetDistro
281 fi
282
283 if [ $# -gt 0 ]; then
284 die $LINENO "Support for $DISTRO is incomplete: no support for $@"
285 else
286 die $LINENO "Support for $DISTRO is incomplete."
287 fi
288}
289
290# Test if the named environment variable is set and not zero length
291# is_set env-var
292function is_set() {
293 local var=\$"$1"
294 eval "[ -n \"$var\" ]" # For ex.: sh -c "[ -n \"$var\" ]" would be better, but several exercises depends on this
295}
296
297# Prints line number and "message" in warning format
298# warn $LINENO "message"
299function warn() {
300 local exitcode=$?
301 errXTRACE=$(set +o | grep xtrace)
302 set +o xtrace
303 local msg="[WARNING] ${BASH_SOURCE[2]}:$1 $2"
304 echo $msg 1>&2;
305 if [[ -n ${SCREEN_LOGDIR} ]]; then
306 echo $msg >> "${SCREEN_LOGDIR}/error.log"
307 fi
308 $errXTRACE
309 return $exitcode
310}
311
312
313# Distro Functions
314# ================
315
316# Determine OS Vendor, Release and Update
317# Tested with OS/X, Ubuntu, RedHat, CentOS, Fedora
318# Returns results in global variables:
319# os_VENDOR - vendor name
320# os_RELEASE - release
321# os_UPDATE - update
322# os_PACKAGE - package type
323# os_CODENAME - vendor's codename for release
324# GetOSVersion
325GetOSVersion() {
326 # Figure out which vendor we are
327 if [[ -x "`which sw_vers 2>/dev/null`" ]]; then
328 # OS/X
329 os_VENDOR=`sw_vers -productName`
330 os_RELEASE=`sw_vers -productVersion`
331 os_UPDATE=${os_RELEASE##*.}
332 os_RELEASE=${os_RELEASE%.*}
333 os_PACKAGE=""
334 if [[ "$os_RELEASE" =~ "10.7" ]]; then
335 os_CODENAME="lion"
336 elif [[ "$os_RELEASE" =~ "10.6" ]]; then
337 os_CODENAME="snow leopard"
338 elif [[ "$os_RELEASE" =~ "10.5" ]]; then
339 os_CODENAME="leopard"
340 elif [[ "$os_RELEASE" =~ "10.4" ]]; then
341 os_CODENAME="tiger"
342 elif [[ "$os_RELEASE" =~ "10.3" ]]; then
343 os_CODENAME="panther"
344 else
345 os_CODENAME=""
346 fi
347 elif [[ -x $(which lsb_release 2>/dev/null) ]]; then
348 os_VENDOR=$(lsb_release -i -s)
349 os_RELEASE=$(lsb_release -r -s)
350 os_UPDATE=""
351 os_PACKAGE="rpm"
352 if [[ "Debian,Ubuntu,LinuxMint" =~ $os_VENDOR ]]; then
353 os_PACKAGE="deb"
354 elif [[ "SUSE LINUX" =~ $os_VENDOR ]]; then
355 lsb_release -d -s | grep -q openSUSE
356 if [[ $? -eq 0 ]]; then
357 os_VENDOR="openSUSE"
358 fi
359 elif [[ $os_VENDOR == "openSUSE project" ]]; then
360 os_VENDOR="openSUSE"
361 elif [[ $os_VENDOR =~ Red.*Hat ]]; then
362 os_VENDOR="Red Hat"
363 fi
364 os_CODENAME=$(lsb_release -c -s)
365 elif [[ -r /etc/redhat-release ]]; then
366 # Red Hat Enterprise Linux Server release 5.5 (Tikanga)
367 # Red Hat Enterprise Linux Server release 7.0 Beta (Maipo)
368 # CentOS release 5.5 (Final)
369 # CentOS Linux release 6.0 (Final)
370 # Fedora release 16 (Verne)
371 # XenServer release 6.2.0-70446c (xenenterprise)
372 os_CODENAME=""
373 for r in "Red Hat" CentOS Fedora XenServer; do
374 os_VENDOR=$r
375 if [[ -n "`grep \"$r\" /etc/redhat-release`" ]]; then
376 ver=`sed -e 's/^.* \([0-9].*\) (\(.*\)).*$/\1\|\2/' /etc/redhat-release`
377 os_CODENAME=${ver#*|}
378 os_RELEASE=${ver%|*}
379 os_UPDATE=${os_RELEASE##*.}
380 os_RELEASE=${os_RELEASE%.*}
381 break
382 fi
383 os_VENDOR=""
384 done
385 os_PACKAGE="rpm"
386 elif [[ -r /etc/SuSE-release ]]; then
387 for r in openSUSE "SUSE Linux"; do
388 if [[ "$r" = "SUSE Linux" ]]; then
389 os_VENDOR="SUSE LINUX"
390 else
391 os_VENDOR=$r
392 fi
393
394 if [[ -n "`grep \"$r\" /etc/SuSE-release`" ]]; then
395 os_CODENAME=`grep "CODENAME = " /etc/SuSE-release | sed 's:.* = ::g'`
396 os_RELEASE=`grep "VERSION = " /etc/SuSE-release | sed 's:.* = ::g'`
397 os_UPDATE=`grep "PATCHLEVEL = " /etc/SuSE-release | sed 's:.* = ::g'`
398 break
399 fi
400 os_VENDOR=""
401 done
402 os_PACKAGE="rpm"
403 # If lsb_release is not installed, we should be able to detect Debian OS
404 elif [[ -f /etc/debian_version ]] && [[ $(cat /proc/version) =~ "Debian" ]]; then
405 os_VENDOR="Debian"
406 os_PACKAGE="deb"
407 os_CODENAME=$(awk '/VERSION=/' /etc/os-release | sed 's/VERSION=//' | sed -r 's/\"|\(|\)//g' | awk '{print $2}')
408 os_RELEASE=$(awk '/VERSION_ID=/' /etc/os-release | sed 's/VERSION_ID=//' | sed 's/\"//g')
409 fi
410 export os_VENDOR os_RELEASE os_UPDATE os_PACKAGE os_CODENAME
411}
412
413# Translate the OS version values into common nomenclature
414# Sets global ``DISTRO`` from the ``os_*`` values
415function GetDistro() {
416 GetOSVersion
417 if [[ "$os_VENDOR" =~ (Ubuntu) || "$os_VENDOR" =~ (Debian) ]]; then
418 # 'Everyone' refers to Ubuntu / Debian releases by the code name adjective
419 DISTRO=$os_CODENAME
420 elif [[ "$os_VENDOR" =~ (Fedora) ]]; then
421 # For Fedora, just use 'f' and the release
422 DISTRO="f$os_RELEASE"
423 elif [[ "$os_VENDOR" =~ (openSUSE) ]]; then
424 DISTRO="opensuse-$os_RELEASE"
425 elif [[ "$os_VENDOR" =~ (SUSE LINUX) ]]; then
426 # For SLE, also use the service pack
427 if [[ -z "$os_UPDATE" ]]; then
428 DISTRO="sle${os_RELEASE}"
429 else
430 DISTRO="sle${os_RELEASE}sp${os_UPDATE}"
431 fi
432 elif [[ "$os_VENDOR" =~ (Red Hat) || "$os_VENDOR" =~ (CentOS) ]]; then
433 # Drop the . release as we assume it's compatible
434 DISTRO="rhel${os_RELEASE::1}"
435 elif [[ "$os_VENDOR" =~ (XenServer) ]]; then
436 DISTRO="xs$os_RELEASE"
437 else
438 # Catch-all for now is Vendor + Release + Update
439 DISTRO="$os_VENDOR-$os_RELEASE.$os_UPDATE"
440 fi
441 export DISTRO
442}
443
444# Utility function for checking machine architecture
445# is_arch arch-type
446function is_arch {
447 ARCH_TYPE=$1
448
449 [[ "$(uname -m)" == "$ARCH_TYPE" ]]
450}
451
452# Determine if current distribution is a Fedora-based distribution
453# (Fedora, RHEL, CentOS, etc).
454# is_fedora
455function is_fedora {
456 if [[ -z "$os_VENDOR" ]]; then
457 GetOSVersion
458 fi
459
460 [ "$os_VENDOR" = "Fedora" ] || [ "$os_VENDOR" = "Red Hat" ] || [ "$os_VENDOR" = "CentOS" ]
461}
462
463
464# Determine if current distribution is a SUSE-based distribution
465# (openSUSE, SLE).
466# is_suse
467function is_suse {
468 if [[ -z "$os_VENDOR" ]]; then
469 GetOSVersion
470 fi
471
472 [ "$os_VENDOR" = "openSUSE" ] || [ "$os_VENDOR" = "SUSE LINUX" ]
473}
474
475
476# Determine if current distribution is an Ubuntu-based distribution
477# It will also detect non-Ubuntu but Debian-based distros
478# is_ubuntu
479function is_ubuntu {
480 if [[ -z "$os_PACKAGE" ]]; then
481 GetOSVersion
482 fi
483 [ "$os_PACKAGE" = "deb" ]
484}
485
486
487# Git Functions
488# =============
489
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600490# Returns openstack release name for a given branch name
491# ``get_release_name_from_branch branch-name``
492function get_release_name_from_branch(){
493 local branch=$1
494 if [[ $branch =~ "stable/" ]]; then
495 echo ${branch#*/}
496 else
497 echo "master"
498 fi
499}
500
Dean Troyerdff49a22014-01-30 15:37:40 -0600501# git clone only if directory doesn't exist already. Since ``DEST`` might not
502# be owned by the installation user, we create the directory and change the
503# ownership to the proper user.
504# Set global RECLONE=yes to simulate a clone when dest-dir exists
505# Set global ERROR_ON_CLONE=True to abort execution with an error if the git repo
506# does not exist (default is False, meaning the repo will be cloned).
507# Uses global ``OFFLINE``
508# git_clone remote dest-dir branch
509function git_clone {
510 GIT_REMOTE=$1
511 GIT_DEST=$2
512 GIT_REF=$3
513 RECLONE=$(trueorfalse False $RECLONE)
514
515 if [[ "$OFFLINE" = "True" ]]; then
516 echo "Running in offline mode, clones already exist"
517 # print out the results so we know what change was used in the logs
518 cd $GIT_DEST
519 git show --oneline | head -1
520 return
521 fi
522
523 if echo $GIT_REF | egrep -q "^refs"; then
524 # If our branch name is a gerrit style refs/changes/...
525 if [[ ! -d $GIT_DEST ]]; then
526 [[ "$ERROR_ON_CLONE" = "True" ]] && \
527 die $LINENO "Cloning not allowed in this configuration"
528 git clone $GIT_REMOTE $GIT_DEST
529 fi
530 cd $GIT_DEST
531 git fetch $GIT_REMOTE $GIT_REF && git checkout FETCH_HEAD
532 else
533 # do a full clone only if the directory doesn't exist
534 if [[ ! -d $GIT_DEST ]]; then
535 [[ "$ERROR_ON_CLONE" = "True" ]] && \
536 die $LINENO "Cloning not allowed in this configuration"
537 git clone $GIT_REMOTE $GIT_DEST
538 cd $GIT_DEST
539 # This checkout syntax works for both branches and tags
540 git checkout $GIT_REF
541 elif [[ "$RECLONE" = "True" ]]; then
542 # if it does exist then simulate what clone does if asked to RECLONE
543 cd $GIT_DEST
544 # set the url to pull from and fetch
545 git remote set-url origin $GIT_REMOTE
546 git fetch origin
547 # remove the existing ignored files (like pyc) as they cause breakage
548 # (due to the py files having older timestamps than our pyc, so python
549 # thinks the pyc files are correct using them)
550 find $GIT_DEST -name '*.pyc' -delete
551
552 # handle GIT_REF accordingly to type (tag, branch)
553 if [[ -n "`git show-ref refs/tags/$GIT_REF`" ]]; then
554 git_update_tag $GIT_REF
555 elif [[ -n "`git show-ref refs/heads/$GIT_REF`" ]]; then
556 git_update_branch $GIT_REF
557 elif [[ -n "`git show-ref refs/remotes/origin/$GIT_REF`" ]]; then
558 git_update_remote_branch $GIT_REF
559 else
560 die $LINENO "$GIT_REF is neither branch nor tag"
561 fi
562
563 fi
564 fi
565
566 # print out the results so we know what change was used in the logs
567 cd $GIT_DEST
568 git show --oneline | head -1
569}
570
571# git update using reference as a branch.
572# git_update_branch ref
573function git_update_branch() {
574
575 GIT_BRANCH=$1
576
577 git checkout -f origin/$GIT_BRANCH
578 # a local branch might not exist
579 git branch -D $GIT_BRANCH || true
580 git checkout -b $GIT_BRANCH
581}
582
583# git update using reference as a branch.
584# git_update_remote_branch ref
585function git_update_remote_branch() {
586
587 GIT_BRANCH=$1
588
589 git checkout -b $GIT_BRANCH -t origin/$GIT_BRANCH
590}
591
592# git update using reference as a tag. Be careful editing source at that repo
593# as working copy will be in a detached mode
594# git_update_tag ref
595function git_update_tag() {
596
597 GIT_TAG=$1
598
599 git tag -d $GIT_TAG
600 # fetching given tag only
601 git fetch origin tag $GIT_TAG
602 git checkout -f $GIT_TAG
603}
604
605
606# OpenStack Functions
607# ===================
608
609# Get the default value for HOST_IP
610# get_default_host_ip fixed_range floating_range host_ip_iface host_ip
611function get_default_host_ip() {
612 local fixed_range=$1
613 local floating_range=$2
614 local host_ip_iface=$3
615 local host_ip=$4
616
617 # Find the interface used for the default route
618 host_ip_iface=${host_ip_iface:-$(ip route | sed -n '/^default/{ s/.*dev \(\w\+\)\s\+.*/\1/; p; }' | head -1)}
619 # Search for an IP unless an explicit is set by ``HOST_IP`` environment variable
620 if [ -z "$host_ip" -o "$host_ip" == "dhcp" ]; then
621 host_ip=""
622 host_ips=`LC_ALL=C ip -f inet addr show ${host_ip_iface} | awk '/inet/ {split($2,parts,"/"); print parts[1]}'`
623 for IP in $host_ips; do
624 # Attempt to filter out IP addresses that are part of the fixed and
625 # floating range. Note that this method only works if the ``netaddr``
626 # python library is installed. If it is not installed, an error
627 # will be printed and the first IP from the interface will be used.
628 # If that is not correct set ``HOST_IP`` in ``localrc`` to the correct
629 # address.
630 if ! (address_in_net $IP $fixed_range || address_in_net $IP $floating_range); then
631 host_ip=$IP
632 break;
633 fi
634 done
635 fi
636 echo $host_ip
637}
638
639# Grab a numbered field from python prettytable output
640# Fields are numbered starting with 1
641# Reverse syntax is supported: -1 is the last field, -2 is second to last, etc.
642# get_field field-number
643function get_field() {
644 while read data; do
645 if [ "$1" -lt 0 ]; then
646 field="(\$(NF$1))"
647 else
648 field="\$$(($1 + 1))"
649 fi
650 echo "$data" | awk -F'[ \t]*\\|[ \t]*' "{print $field}"
651 done
652}
653
654# Add a policy to a policy.json file
655# Do nothing if the policy already exists
656# ``policy_add policy_file policy_name policy_permissions``
657function policy_add() {
658 local policy_file=$1
659 local policy_name=$2
660 local policy_perm=$3
661
662 if grep -q ${policy_name} ${policy_file}; then
663 echo "Policy ${policy_name} already exists in ${policy_file}"
664 return
665 fi
666
667 # Add a terminating comma to policy lines without one
668 # Remove the closing '}' and all lines following to the end-of-file
669 local tmpfile=$(mktemp)
670 uniq ${policy_file} | sed -e '
671 s/]$/],/
672 /^[}]/,$d
673 ' > ${tmpfile}
674
675 # Append policy and closing brace
676 echo " \"${policy_name}\": ${policy_perm}" >>${tmpfile}
677 echo "}" >>${tmpfile}
678
679 mv ${tmpfile} ${policy_file}
680}
681
682
683# Package Functions
684# =================
685
686# _get_package_dir
687function _get_package_dir() {
688 local pkg_dir
689 if is_ubuntu; then
690 pkg_dir=$FILES/apts
691 elif is_fedora; then
692 pkg_dir=$FILES/rpms
693 elif is_suse; then
694 pkg_dir=$FILES/rpms-suse
695 else
696 exit_distro_not_supported "list of packages"
697 fi
698 echo "$pkg_dir"
699}
700
701# Wrapper for ``apt-get`` to set cache and proxy environment variables
702# Uses globals ``OFFLINE``, ``*_proxy``
703# apt_get operation package [package ...]
704function apt_get() {
Sean Dague45917cc2014-02-24 16:09:14 -0500705 local xtrace=$(set +o | grep xtrace)
706 set +o xtrace
707
Dean Troyerdff49a22014-01-30 15:37:40 -0600708 [[ "$OFFLINE" = "True" || -z "$@" ]] && return
709 local sudo="sudo"
710 [[ "$(id -u)" = "0" ]] && sudo="env"
Sean Dague45917cc2014-02-24 16:09:14 -0500711
712 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600713 $sudo DEBIAN_FRONTEND=noninteractive \
714 http_proxy=$http_proxy https_proxy=$https_proxy \
715 no_proxy=$no_proxy \
716 apt-get --option "Dpkg::Options::=--force-confold" --assume-yes "$@"
717}
718
719# get_packages() collects a list of package names of any type from the
720# prerequisite files in ``files/{apts|rpms}``. The list is intended
721# to be passed to a package installer such as apt or yum.
722#
723# Only packages required for the services in 1st argument will be
724# included. Two bits of metadata are recognized in the prerequisite files:
725#
726# - ``# NOPRIME`` defers installation to be performed later in `stack.sh`
727# - ``# dist:DISTRO`` or ``dist:DISTRO1,DISTRO2`` limits the selection
728# of the package to the distros listed. The distro names are case insensitive.
729function get_packages() {
Sean Dague45917cc2014-02-24 16:09:14 -0500730 local xtrace=$(set +o | grep xtrace)
731 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600732 local services=$@
733 local package_dir=$(_get_package_dir)
734 local file_to_parse
735 local service
736
737 if [[ -z "$package_dir" ]]; then
738 echo "No package directory supplied"
739 return 1
740 fi
741 if [[ -z "$DISTRO" ]]; then
742 GetDistro
Sean Dague45917cc2014-02-24 16:09:14 -0500743 echo "Found Distro $DISTRO"
Dean Troyerdff49a22014-01-30 15:37:40 -0600744 fi
745 for service in ${services//,/ }; do
746 # Allow individual services to specify dependencies
747 if [[ -e ${package_dir}/${service} ]]; then
748 file_to_parse="${file_to_parse} $service"
749 fi
750 # NOTE(sdague) n-api needs glance for now because that's where
751 # glance client is
752 if [[ $service == n-api ]]; then
753 if [[ ! $file_to_parse =~ nova ]]; then
754 file_to_parse="${file_to_parse} nova"
755 fi
756 if [[ ! $file_to_parse =~ glance ]]; then
757 file_to_parse="${file_to_parse} glance"
758 fi
759 elif [[ $service == c-* ]]; then
760 if [[ ! $file_to_parse =~ cinder ]]; then
761 file_to_parse="${file_to_parse} cinder"
762 fi
763 elif [[ $service == ceilometer-* ]]; then
764 if [[ ! $file_to_parse =~ ceilometer ]]; then
765 file_to_parse="${file_to_parse} ceilometer"
766 fi
767 elif [[ $service == s-* ]]; then
768 if [[ ! $file_to_parse =~ swift ]]; then
769 file_to_parse="${file_to_parse} swift"
770 fi
771 elif [[ $service == n-* ]]; then
772 if [[ ! $file_to_parse =~ nova ]]; then
773 file_to_parse="${file_to_parse} nova"
774 fi
775 elif [[ $service == g-* ]]; then
776 if [[ ! $file_to_parse =~ glance ]]; then
777 file_to_parse="${file_to_parse} glance"
778 fi
779 elif [[ $service == key* ]]; then
780 if [[ ! $file_to_parse =~ keystone ]]; then
781 file_to_parse="${file_to_parse} keystone"
782 fi
783 elif [[ $service == q-* ]]; then
784 if [[ ! $file_to_parse =~ neutron ]]; then
785 file_to_parse="${file_to_parse} neutron"
786 fi
787 fi
788 done
789
790 for file in ${file_to_parse}; do
791 local fname=${package_dir}/${file}
792 local OIFS line package distros distro
793 [[ -e $fname ]] || continue
794
795 OIFS=$IFS
796 IFS=$'\n'
797 for line in $(<${fname}); do
798 if [[ $line =~ "NOPRIME" ]]; then
799 continue
800 fi
801
802 # Assume we want this package
803 package=${line%#*}
804 inst_pkg=1
805
806 # Look for # dist:xxx in comment
807 if [[ $line =~ (.*)#.*dist:([^ ]*) ]]; then
808 # We are using BASH regexp matching feature.
809 package=${BASH_REMATCH[1]}
810 distros=${BASH_REMATCH[2]}
811 # In bash ${VAR,,} will lowecase VAR
812 # Look for a match in the distro list
813 if [[ ! ${distros,,} =~ ${DISTRO,,} ]]; then
814 # If no match then skip this package
815 inst_pkg=0
816 fi
817 fi
818
819 # Look for # testonly in comment
820 if [[ $line =~ (.*)#.*testonly.* ]]; then
821 package=${BASH_REMATCH[1]}
822 # Are we installing test packages? (test for the default value)
823 if [[ $INSTALL_TESTONLY_PACKAGES = "False" ]]; then
824 # If not installing test packages the skip this package
825 inst_pkg=0
826 fi
827 fi
828
829 if [[ $inst_pkg = 1 ]]; then
830 echo $package
831 fi
832 done
833 IFS=$OIFS
834 done
Sean Dague45917cc2014-02-24 16:09:14 -0500835 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600836}
837
838# Distro-agnostic package installer
839# install_package package [package ...]
840function install_package() {
Sean Dague45917cc2014-02-24 16:09:14 -0500841 local xtrace=$(set +o | grep xtrace)
842 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600843 if is_ubuntu; then
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600844 # if there are transient errors pulling the updates, that's fine. It may
845 # be secondary repositories that we don't really care about.
846 [[ "$NO_UPDATE_REPOS" = "True" ]] || apt_get update || /bin/true
Dean Troyerdff49a22014-01-30 15:37:40 -0600847 NO_UPDATE_REPOS=True
848
Sean Dague45917cc2014-02-24 16:09:14 -0500849 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600850 apt_get install "$@"
851 elif is_fedora; then
Sean Dague45917cc2014-02-24 16:09:14 -0500852 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600853 yum_install "$@"
854 elif is_suse; then
Sean Dague45917cc2014-02-24 16:09:14 -0500855 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600856 zypper_install "$@"
857 else
Sean Dague45917cc2014-02-24 16:09:14 -0500858 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600859 exit_distro_not_supported "installing packages"
860 fi
861}
862
863# Distro-agnostic function to tell if a package is installed
864# is_package_installed package [package ...]
865function is_package_installed() {
866 if [[ -z "$@" ]]; then
867 return 1
868 fi
869
870 if [[ -z "$os_PACKAGE" ]]; then
871 GetOSVersion
872 fi
873
874 if [[ "$os_PACKAGE" = "deb" ]]; then
875 dpkg -s "$@" > /dev/null 2> /dev/null
876 elif [[ "$os_PACKAGE" = "rpm" ]]; then
877 rpm --quiet -q "$@"
878 else
879 exit_distro_not_supported "finding if a package is installed"
880 fi
881}
882
883# Distro-agnostic package uninstaller
884# uninstall_package package [package ...]
885function uninstall_package() {
886 if is_ubuntu; then
887 apt_get purge "$@"
888 elif is_fedora; then
889 sudo yum remove -y "$@"
890 elif is_suse; then
891 sudo zypper rm "$@"
892 else
893 exit_distro_not_supported "uninstalling packages"
894 fi
895}
896
897# Wrapper for ``yum`` to set proxy environment variables
898# Uses globals ``OFFLINE``, ``*_proxy``
899# yum_install package [package ...]
900function yum_install() {
901 [[ "$OFFLINE" = "True" ]] && return
902 local sudo="sudo"
903 [[ "$(id -u)" = "0" ]] && sudo="env"
904 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
905 no_proxy=$no_proxy \
906 yum install -y "$@"
907}
908
909# zypper wrapper to set arguments correctly
910# zypper_install package [package ...]
911function zypper_install() {
912 [[ "$OFFLINE" = "True" ]] && return
913 local sudo="sudo"
914 [[ "$(id -u)" = "0" ]] && sudo="env"
915 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
916 zypper --non-interactive install --auto-agree-with-licenses "$@"
917}
918
919
920# Process Functions
921# =================
922
923# _run_process() is designed to be backgrounded by run_process() to simulate a
924# fork. It includes the dirty work of closing extra filehandles and preparing log
925# files to produce the same logs as screen_it(). The log filename is derived
926# from the service name and global-and-now-misnamed SCREEN_LOGDIR
927# _run_process service "command-line"
928function _run_process() {
929 local service=$1
930 local command="$2"
931
932 # Undo logging redirections and close the extra descriptors
933 exec 1>&3
934 exec 2>&3
935 exec 3>&-
936 exec 6>&-
937
938 if [[ -n ${SCREEN_LOGDIR} ]]; then
939 exec 1>&${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log 2>&1
940 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
941
942 # TODO(dtroyer): Hack to get stdout from the Python interpreter for the logs.
943 export PYTHONUNBUFFERED=1
944 fi
945
946 exec /bin/bash -c "$command"
947 die "$service exec failure: $command"
948}
949
950# Helper to remove the ``*.failure`` files under ``$SERVICE_DIR/$SCREEN_NAME``.
951# This is used for ``service_check`` when all the ``screen_it`` are called finished
952# init_service_check
953function init_service_check() {
954 SCREEN_NAME=${SCREEN_NAME:-stack}
955 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
956
957 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
958 mkdir -p "$SERVICE_DIR/$SCREEN_NAME"
959 fi
960
961 rm -f "$SERVICE_DIR/$SCREEN_NAME"/*.failure
962}
963
964# Find out if a process exists by partial name.
965# is_running name
966function is_running() {
967 local name=$1
968 ps auxw | grep -v grep | grep ${name} > /dev/null
969 RC=$?
970 # some times I really hate bash reverse binary logic
971 return $RC
972}
973
974# run_process() launches a child process that closes all file descriptors and
975# then exec's the passed in command. This is meant to duplicate the semantics
976# of screen_it() without screen. PIDs are written to
977# $SERVICE_DIR/$SCREEN_NAME/$service.pid
978# run_process service "command-line"
979function run_process() {
980 local service=$1
981 local command="$2"
982
983 # Spawn the child process
984 _run_process "$service" "$command" &
985 echo $!
986}
987
988# Helper to launch a service in a named screen
989# screen_it service "command-line"
990function screen_it {
991 SCREEN_NAME=${SCREEN_NAME:-stack}
992 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
993 USE_SCREEN=$(trueorfalse True $USE_SCREEN)
994
995 if is_service_enabled $1; then
996 # Append the service to the screen rc file
997 screen_rc "$1" "$2"
998
999 if [[ "$USE_SCREEN" = "True" ]]; then
1000 screen -S $SCREEN_NAME -X screen -t $1
1001
1002 if [[ -n ${SCREEN_LOGDIR} ]]; then
1003 screen -S $SCREEN_NAME -p $1 -X logfile ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log
1004 screen -S $SCREEN_NAME -p $1 -X log on
1005 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
1006 fi
1007
1008 # sleep to allow bash to be ready to be send the command - we are
1009 # creating a new window in screen and then sends characters, so if
1010 # bash isn't running by the time we send the command, nothing happens
1011 sleep 1.5
1012
1013 NL=`echo -ne '\015'`
1014 # This fun command does the following:
1015 # - the passed server command is backgrounded
1016 # - the pid of the background process is saved in the usual place
1017 # - the server process is brought back to the foreground
1018 # - if the server process exits prematurely the fg command errors
1019 # and a message is written to stdout and the service failure file
1020 # The pid saved can be used in screen_stop() as a process group
1021 # id to kill off all child processes
1022 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"
1023 else
1024 # Spawn directly without screen
1025 run_process "$1" "$2" >$SERVICE_DIR/$SCREEN_NAME/$1.pid
1026 fi
1027 fi
1028}
1029
1030# Screen rc file builder
1031# screen_rc service "command-line"
1032function screen_rc {
1033 SCREEN_NAME=${SCREEN_NAME:-stack}
1034 SCREENRC=$TOP_DIR/$SCREEN_NAME-screenrc
1035 if [[ ! -e $SCREENRC ]]; then
1036 # Name the screen session
1037 echo "sessionname $SCREEN_NAME" > $SCREENRC
1038 # Set a reasonable statusbar
1039 echo "hardstatus alwayslastline '$SCREEN_HARDSTATUS'" >> $SCREENRC
1040 # Some distributions override PROMPT_COMMAND for the screen terminal type - turn that off
1041 echo "setenv PROMPT_COMMAND /bin/true" >> $SCREENRC
1042 echo "screen -t shell bash" >> $SCREENRC
1043 fi
1044 # If this service doesn't already exist in the screenrc file
1045 if ! grep $1 $SCREENRC 2>&1 > /dev/null; then
1046 NL=`echo -ne '\015'`
1047 echo "screen -t $1 bash" >> $SCREENRC
1048 echo "stuff \"$2$NL\"" >> $SCREENRC
1049
1050 if [[ -n ${SCREEN_LOGDIR} ]]; then
1051 echo "logfile ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log" >>$SCREENRC
1052 echo "log on" >>$SCREENRC
1053 fi
1054 fi
1055}
1056
1057# Stop a service in screen
1058# If a PID is available use it, kill the whole process group via TERM
1059# If screen is being used kill the screen window; this will catch processes
1060# that did not leave a PID behind
1061# screen_stop service
1062function screen_stop() {
1063 SCREEN_NAME=${SCREEN_NAME:-stack}
1064 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1065 USE_SCREEN=$(trueorfalse True $USE_SCREEN)
1066
1067 if is_service_enabled $1; then
1068 # Kill via pid if we have one available
1069 if [[ -r $SERVICE_DIR/$SCREEN_NAME/$1.pid ]]; then
1070 pkill -TERM -P -$(cat $SERVICE_DIR/$SCREEN_NAME/$1.pid)
1071 rm $SERVICE_DIR/$SCREEN_NAME/$1.pid
1072 fi
1073 if [[ "$USE_SCREEN" = "True" ]]; then
1074 # Clean up the screen window
1075 screen -S $SCREEN_NAME -p $1 -X kill
1076 fi
1077 fi
1078}
1079
1080# Helper to get the status of each running service
1081# service_check
1082function service_check() {
1083 local service
1084 local failures
1085 SCREEN_NAME=${SCREEN_NAME:-stack}
1086 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1087
1088
1089 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
1090 echo "No service status directory found"
1091 return
1092 fi
1093
1094 # Check if there is any falure flag file under $SERVICE_DIR/$SCREEN_NAME
1095 failures=`ls "$SERVICE_DIR/$SCREEN_NAME"/*.failure 2>/dev/null`
1096
1097 for service in $failures; do
1098 service=`basename $service`
1099 service=${service%.failure}
1100 echo "Error: Service $service is not running"
1101 done
1102
1103 if [ -n "$failures" ]; then
1104 echo "More details about the above errors can be found with screen, with ./rejoin-stack.sh"
1105 fi
1106}
1107
1108
1109# Python Functions
1110# ================
1111
1112# Get the path to the pip command.
1113# get_pip_command
1114function get_pip_command() {
1115 which pip || which pip-python
1116
1117 if [ $? -ne 0 ]; then
1118 die $LINENO "Unable to find pip; cannot continue"
1119 fi
1120}
1121
1122# Get the path to the direcotry where python executables are installed.
1123# get_python_exec_prefix
1124function get_python_exec_prefix() {
1125 if is_fedora || is_suse; then
1126 echo "/usr/bin"
1127 else
1128 echo "/usr/local/bin"
1129 fi
1130}
1131
1132# Wrapper for ``pip install`` to set cache and proxy environment variables
1133# Uses globals ``OFFLINE``, ``PIP_DOWNLOAD_CACHE``, ``PIP_USE_MIRRORS``,
1134# ``TRACK_DEPENDS``, ``*_proxy``
1135# pip_install package [package ...]
1136function pip_install {
Sean Dague45917cc2014-02-24 16:09:14 -05001137 local xtrace=$(set +o | grep xtrace)
1138 set +o xtrace
1139 if [[ "$OFFLINE" = "True" || -z "$@" ]]; then
1140 $xtrace
1141 return
1142 fi
1143
Dean Troyerdff49a22014-01-30 15:37:40 -06001144 if [[ -z "$os_PACKAGE" ]]; then
1145 GetOSVersion
1146 fi
1147 if [[ $TRACK_DEPENDS = True ]]; then
1148 source $DEST/.venv/bin/activate
1149 CMD_PIP=$DEST/.venv/bin/pip
1150 SUDO_PIP="env"
1151 else
1152 SUDO_PIP="sudo"
1153 CMD_PIP=$(get_pip_command)
1154 fi
1155
1156 # Mirror option not needed anymore because pypi has CDN available,
1157 # but it's useful in certain circumstances
1158 PIP_USE_MIRRORS=${PIP_USE_MIRRORS:-False}
1159 if [[ "$PIP_USE_MIRRORS" != "False" ]]; then
1160 PIP_MIRROR_OPT="--use-mirrors"
1161 fi
1162
1163 # pip < 1.4 has a bug where it will use an already existing build
1164 # directory unconditionally. Say an earlier component installs
1165 # foo v1.1; pip will have built foo's source in
1166 # /tmp/$USER-pip-build. Even if a later component specifies foo <
1167 # 1.1, the existing extracted build will be used and cause
1168 # confusing errors. By creating unique build directories we avoid
1169 # this problem. See https://github.com/pypa/pip/issues/709
1170 local pip_build_tmp=$(mktemp --tmpdir -d pip-build.XXXXX)
1171
Sean Dague45917cc2014-02-24 16:09:14 -05001172 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001173 $SUDO_PIP PIP_DOWNLOAD_CACHE=${PIP_DOWNLOAD_CACHE:-/var/cache/pip} \
1174 HTTP_PROXY=$http_proxy \
1175 HTTPS_PROXY=$https_proxy \
1176 NO_PROXY=$no_proxy \
1177 $CMD_PIP install --build=${pip_build_tmp} \
1178 $PIP_MIRROR_OPT $@ \
1179 && $SUDO_PIP rm -rf ${pip_build_tmp}
1180}
1181
1182
1183# Service Functions
1184# =================
1185
1186# remove extra commas from the input string (i.e. ``ENABLED_SERVICES``)
1187# _cleanup_service_list service-list
1188function _cleanup_service_list () {
1189 echo "$1" | sed -e '
1190 s/,,/,/g;
1191 s/^,//;
1192 s/,$//
1193 '
1194}
1195
1196# disable_all_services() removes all current services
1197# from ``ENABLED_SERVICES`` to reset the configuration
1198# before a minimal installation
1199# Uses global ``ENABLED_SERVICES``
1200# disable_all_services
1201function disable_all_services() {
1202 ENABLED_SERVICES=""
1203}
1204
1205# Remove all services starting with '-'. For example, to install all default
1206# services except rabbit (rabbit) set in ``localrc``:
1207# ENABLED_SERVICES+=",-rabbit"
1208# Uses global ``ENABLED_SERVICES``
1209# disable_negated_services
1210function disable_negated_services() {
1211 local tmpsvcs="${ENABLED_SERVICES}"
1212 local service
1213 for service in ${tmpsvcs//,/ }; do
1214 if [[ ${service} == -* ]]; then
1215 tmpsvcs=$(echo ${tmpsvcs}|sed -r "s/(,)?(-)?${service#-}(,)?/,/g")
1216 fi
1217 done
1218 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1219}
1220
1221# disable_service() removes the services passed as argument to the
1222# ``ENABLED_SERVICES`` list, if they are present.
1223#
1224# For example:
1225# disable_service rabbit
1226#
1227# This function does not know about the special cases
1228# for nova, glance, and neutron built into is_service_enabled().
1229# Uses global ``ENABLED_SERVICES``
1230# disable_service service [service ...]
1231function disable_service() {
1232 local tmpsvcs=",${ENABLED_SERVICES},"
1233 local service
1234 for service in $@; do
1235 if is_service_enabled $service; then
1236 tmpsvcs=${tmpsvcs//,$service,/,}
1237 fi
1238 done
1239 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1240}
1241
1242# enable_service() adds the services passed as argument to the
1243# ``ENABLED_SERVICES`` list, if they are not already present.
1244#
1245# For example:
1246# enable_service qpid
1247#
1248# This function does not know about the special cases
1249# for nova, glance, and neutron built into is_service_enabled().
1250# Uses global ``ENABLED_SERVICES``
1251# enable_service service [service ...]
1252function enable_service() {
1253 local tmpsvcs="${ENABLED_SERVICES}"
1254 for service in $@; do
1255 if ! is_service_enabled $service; then
1256 tmpsvcs+=",$service"
1257 fi
1258 done
1259 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1260 disable_negated_services
1261}
1262
1263# is_service_enabled() checks if the service(s) specified as arguments are
1264# enabled by the user in ``ENABLED_SERVICES``.
1265#
1266# Multiple services specified as arguments are ``OR``'ed together; the test
1267# is a short-circuit boolean, i.e it returns on the first match.
1268#
1269# There are special cases for some 'catch-all' services::
1270# **nova** returns true if any service enabled start with **n-**
1271# **cinder** returns true if any service enabled start with **c-**
1272# **ceilometer** returns true if any service enabled start with **ceilometer**
1273# **glance** returns true if any service enabled start with **g-**
1274# **neutron** returns true if any service enabled start with **q-**
1275# **swift** returns true if any service enabled start with **s-**
1276# **trove** returns true if any service enabled start with **tr-**
1277# For backward compatibility if we have **swift** in ENABLED_SERVICES all the
1278# **s-** services will be enabled. This will be deprecated in the future.
1279#
1280# Cells within nova is enabled if **n-cell** is in ``ENABLED_SERVICES``.
1281# We also need to make sure to treat **n-cell-region** and **n-cell-child**
1282# as enabled in this case.
1283#
1284# Uses global ``ENABLED_SERVICES``
1285# is_service_enabled service [service ...]
1286function is_service_enabled() {
Sean Dague45917cc2014-02-24 16:09:14 -05001287 local xtrace=$(set +o | grep xtrace)
1288 set +o xtrace
1289 local enabled=1
Dean Troyerdff49a22014-01-30 15:37:40 -06001290 services=$@
1291 for service in ${services}; do
Sean Dague45917cc2014-02-24 16:09:14 -05001292 [[ ,${ENABLED_SERVICES}, =~ ,${service}, ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001293
1294 # Look for top-level 'enabled' function for this service
1295 if type is_${service}_enabled >/dev/null 2>&1; then
1296 # A function exists for this service, use it
1297 is_${service}_enabled
Sean Dague45917cc2014-02-24 16:09:14 -05001298 enabled=$?
Dean Troyerdff49a22014-01-30 15:37:40 -06001299 fi
1300
1301 # TODO(dtroyer): Remove these legacy special-cases after the is_XXX_enabled()
1302 # are implemented
1303
Sean Dague45917cc2014-02-24 16:09:14 -05001304 [[ ${service} == n-cell-* && ${ENABLED_SERVICES} =~ "n-cell" ]] && enabled=0
1305 [[ ${service} == "nova" && ${ENABLED_SERVICES} =~ "n-" ]] && enabled=0
1306 [[ ${service} == "cinder" && ${ENABLED_SERVICES} =~ "c-" ]] && enabled=0
1307 [[ ${service} == "ceilometer" && ${ENABLED_SERVICES} =~ "ceilometer-" ]] && enabled=0
1308 [[ ${service} == "glance" && ${ENABLED_SERVICES} =~ "g-" ]] && enabled=0
1309 [[ ${service} == "ironic" && ${ENABLED_SERVICES} =~ "ir-" ]] && enabled=0
1310 [[ ${service} == "neutron" && ${ENABLED_SERVICES} =~ "q-" ]] && enabled=0
1311 [[ ${service} == "trove" && ${ENABLED_SERVICES} =~ "tr-" ]] && enabled=0
1312 [[ ${service} == "swift" && ${ENABLED_SERVICES} =~ "s-" ]] && enabled=0
1313 [[ ${service} == s-* && ${ENABLED_SERVICES} =~ "swift" ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001314 done
Sean Dague45917cc2014-02-24 16:09:14 -05001315 $xtrace
1316 return $enabled
Dean Troyerdff49a22014-01-30 15:37:40 -06001317}
1318
1319# Toggle enable/disable_service for services that must run exclusive of each other
1320# $1 The name of a variable containing a space-separated list of services
1321# $2 The name of a variable in which to store the enabled service's name
1322# $3 The name of the service to enable
1323function use_exclusive_service {
1324 local options=${!1}
1325 local selection=$3
1326 out=$2
1327 [ -z $selection ] || [[ ! "$options" =~ "$selection" ]] && return 1
1328 for opt in $options;do
1329 [[ "$opt" = "$selection" ]] && enable_service $opt || disable_service $opt
1330 done
1331 eval "$out=$selection"
1332 return 0
1333}
1334
1335
1336# System Function
1337# ===============
1338
1339# Only run the command if the target file (the last arg) is not on an
1340# NFS filesystem.
1341function _safe_permission_operation() {
Sean Dague45917cc2014-02-24 16:09:14 -05001342 local xtrace=$(set +o | grep xtrace)
1343 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001344 local args=( $@ )
1345 local last
1346 local sudo_cmd
1347 local dir_to_check
1348
1349 let last="${#args[*]} - 1"
1350
1351 dir_to_check=${args[$last]}
1352 if [ ! -d "$dir_to_check" ]; then
1353 dir_to_check=`dirname "$dir_to_check"`
1354 fi
1355
1356 if is_nfs_directory "$dir_to_check" ; then
Sean Dague45917cc2014-02-24 16:09:14 -05001357 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001358 return 0
1359 fi
1360
1361 if [[ $TRACK_DEPENDS = True ]]; then
1362 sudo_cmd="env"
1363 else
1364 sudo_cmd="sudo"
1365 fi
1366
Sean Dague45917cc2014-02-24 16:09:14 -05001367 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001368 $sudo_cmd $@
1369}
1370
1371# Exit 0 if address is in network or 1 if address is not in network
1372# ip-range is in CIDR notation: 1.2.3.4/20
1373# address_in_net ip-address ip-range
1374function address_in_net() {
1375 local ip=$1
1376 local range=$2
1377 local masklen=${range#*/}
1378 local network=$(maskip ${range%/*} $(cidr2netmask $masklen))
1379 local subnet=$(maskip $ip $(cidr2netmask $masklen))
1380 [[ $network == $subnet ]]
1381}
1382
1383# Add a user to a group.
1384# add_user_to_group user group
1385function add_user_to_group() {
1386 local user=$1
1387 local group=$2
1388
1389 if [[ -z "$os_VENDOR" ]]; then
1390 GetOSVersion
1391 fi
1392
1393 # SLE11 and openSUSE 12.2 don't have the usual usermod
1394 if ! is_suse || [[ "$os_VENDOR" = "openSUSE" && "$os_RELEASE" != "12.2" ]]; then
1395 sudo usermod -a -G "$group" "$user"
1396 else
1397 sudo usermod -A "$group" "$user"
1398 fi
1399}
1400
1401# Convert CIDR notation to a IPv4 netmask
1402# cidr2netmask cidr-bits
1403function cidr2netmask() {
1404 local maskpat="255 255 255 255"
1405 local maskdgt="254 252 248 240 224 192 128"
1406 set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3}
1407 echo ${1-0}.${2-0}.${3-0}.${4-0}
1408}
1409
1410# Gracefully cp only if source file/dir exists
1411# cp_it source destination
1412function cp_it {
1413 if [ -e $1 ] || [ -d $1 ]; then
1414 cp -pRL $1 $2
1415 fi
1416}
1417
1418# HTTP and HTTPS proxy servers are supported via the usual environment variables [1]
1419# ``http_proxy``, ``https_proxy`` and ``no_proxy``. They can be set in
1420# ``localrc`` or on the command line if necessary::
1421#
1422# [1] http://www.w3.org/Daemon/User/Proxies/ProxyClients.html
1423#
1424# http_proxy=http://proxy.example.com:3128/ no_proxy=repo.example.net ./stack.sh
1425
1426function export_proxy_variables() {
1427 if [[ -n "$http_proxy" ]]; then
1428 export http_proxy=$http_proxy
1429 fi
1430 if [[ -n "$https_proxy" ]]; then
1431 export https_proxy=$https_proxy
1432 fi
1433 if [[ -n "$no_proxy" ]]; then
1434 export no_proxy=$no_proxy
1435 fi
1436}
1437
1438# Returns true if the directory is on a filesystem mounted via NFS.
1439function is_nfs_directory() {
1440 local mount_type=`stat -f -L -c %T $1`
1441 test "$mount_type" == "nfs"
1442}
1443
1444# Return the network portion of the given IP address using netmask
1445# netmask is in the traditional dotted-quad format
1446# maskip ip-address netmask
1447function maskip() {
1448 local ip=$1
1449 local mask=$2
1450 local l="${ip%.*}"; local r="${ip#*.}"; local n="${mask%.*}"; local m="${mask#*.}"
1451 local subnet=$((${ip%%.*}&${mask%%.*})).$((${r%%.*}&${m%%.*})).$((${l##*.}&${n##*.})).$((${ip##*.}&${mask##*.}))
1452 echo $subnet
1453}
1454
1455# Service wrapper to restart services
1456# restart_service service-name
1457function restart_service() {
1458 if is_ubuntu; then
1459 sudo /usr/sbin/service $1 restart
1460 else
1461 sudo /sbin/service $1 restart
1462 fi
1463}
1464
1465# Only change permissions of a file or directory if it is not on an
1466# NFS filesystem.
1467function safe_chmod() {
1468 _safe_permission_operation chmod $@
1469}
1470
1471# Only change ownership of a file or directory if it is not on an NFS
1472# filesystem.
1473function safe_chown() {
1474 _safe_permission_operation chown $@
1475}
1476
1477# Service wrapper to start services
1478# start_service service-name
1479function start_service() {
1480 if is_ubuntu; then
1481 sudo /usr/sbin/service $1 start
1482 else
1483 sudo /sbin/service $1 start
1484 fi
1485}
1486
1487# Service wrapper to stop services
1488# stop_service service-name
1489function stop_service() {
1490 if is_ubuntu; then
1491 sudo /usr/sbin/service $1 stop
1492 else
1493 sudo /sbin/service $1 stop
1494 fi
1495}
1496
1497
1498# Restore xtrace
1499$XTRACE
1500
1501# Local variables:
1502# mode: shell-script
1503# End: