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