blob: 0bf354f39418e4f064f49829c769aded876ecfaa [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``
Masayuki Igawad20f6322014-02-28 09:22:37 +090029# - ``REQUIREMENTS_DIR``
30# - ``STACK_USER``
Dean Troyerdff49a22014-01-30 15:37:40 -060031# - ``TRACK_DEPENDS``
Masayuki Igawad20f6322014-02-28 09:22:37 +090032# - ``UNDO_REQUIREMENTS``
Dean Troyerdff49a22014-01-30 15:37:40 -060033# - ``http_proxy``, ``https_proxy``, ``no_proxy``
34
35# Save trace setting
36XTRACE=$(set +o | grep xtrace)
37set +o xtrace
38
39
40# Config Functions
41# ================
42
43# Append a new option in an ini file without replacing the old value
44# iniadd config-file section option value1 value2 value3 ...
Ian Wienandaee18c72014-02-21 15:35:08 +110045function iniadd {
Sean Dague45917cc2014-02-24 16:09:14 -050046 local xtrace=$(set +o | grep xtrace)
47 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060048 local file=$1
49 local section=$2
50 local option=$3
51 shift 3
52 local values="$(iniget_multiline $file $section $option) $@"
53 iniset_multiline $file $section $option $values
Sean Dague45917cc2014-02-24 16:09:14 -050054 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060055}
56
57# Comment an option in an INI file
58# inicomment config-file section option
Ian Wienandaee18c72014-02-21 15:35:08 +110059function inicomment {
Sean Dague45917cc2014-02-24 16:09:14 -050060 local xtrace=$(set +o | grep xtrace)
61 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060062 local file=$1
63 local section=$2
64 local option=$3
65 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|^\($option[ \t]*=.*$\)|#\1|" "$file"
Sean Dague45917cc2014-02-24 16:09:14 -050066 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060067}
68
69# Get an option from an INI file
70# iniget config-file section option
Ian Wienandaee18c72014-02-21 15:35:08 +110071function iniget {
Sean Dague45917cc2014-02-24 16:09:14 -050072 local xtrace=$(set +o | grep xtrace)
73 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060074 local file=$1
75 local section=$2
76 local option=$3
77 local line
78 line=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ p; }" "$file")
79 echo ${line#*=}
Sean Dague45917cc2014-02-24 16:09:14 -050080 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060081}
82
83# Get a multiple line option from an INI file
84# iniget_multiline config-file section option
Ian Wienandaee18c72014-02-21 15:35:08 +110085function iniget_multiline {
Sean Dague45917cc2014-02-24 16:09:14 -050086 local xtrace=$(set +o | grep xtrace)
87 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060088 local file=$1
89 local section=$2
90 local option=$3
91 local values
92 values=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { s/^$option[ \t]*=[ \t]*//gp; }" "$file")
93 echo ${values}
Sean Dague45917cc2014-02-24 16:09:14 -050094 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -060095}
96
97# Determinate is the given option present in the INI file
98# ini_has_option config-file section option
Ian Wienandaee18c72014-02-21 15:35:08 +110099function ini_has_option {
Sean Dague45917cc2014-02-24 16:09:14 -0500100 local xtrace=$(set +o | grep xtrace)
101 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600102 local file=$1
103 local section=$2
104 local option=$3
105 local line
106 line=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ p; }" "$file")
Sean Dague45917cc2014-02-24 16:09:14 -0500107 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600108 [ -n "$line" ]
109}
110
111# Set an option in an INI file
112# iniset config-file section option value
Ian Wienandaee18c72014-02-21 15:35:08 +1100113function iniset {
Sean Dague45917cc2014-02-24 16:09:14 -0500114 local xtrace=$(set +o | grep xtrace)
115 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600116 local file=$1
117 local section=$2
118 local option=$3
119 local value=$4
120
121 [[ -z $section || -z $option ]] && return
122
123 if ! grep -q "^\[$section\]" "$file" 2>/dev/null; then
124 # Add section at the end
125 echo -e "\n[$section]" >>"$file"
126 fi
127 if ! ini_has_option "$file" "$section" "$option"; then
128 # Add it
129 sed -i -e "/^\[$section\]/ a\\
130$option = $value
131" "$file"
132 else
133 local sep=$(echo -ne "\x01")
134 # Replace it
135 sed -i -e '/^\['${section}'\]/,/^\[.*\]/ s'${sep}'^\('${option}'[ \t]*=[ \t]*\).*$'${sep}'\1'"${value}"${sep} "$file"
136 fi
Sean Dague45917cc2014-02-24 16:09:14 -0500137 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600138}
139
140# Set a multiple line option in an INI file
141# iniset_multiline config-file section option value1 value2 valu3 ...
Ian Wienandaee18c72014-02-21 15:35:08 +1100142function iniset_multiline {
Sean Dague45917cc2014-02-24 16:09:14 -0500143 local xtrace=$(set +o | grep xtrace)
144 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600145 local file=$1
146 local section=$2
147 local option=$3
148 shift 3
149 local values
150 for v in $@; do
151 # The later sed command inserts each new value in the line next to
152 # the section identifier, which causes the values to be inserted in
153 # the reverse order. Do a reverse here to keep the original order.
154 values="$v ${values}"
155 done
156 if ! grep -q "^\[$section\]" "$file"; then
157 # Add section at the end
158 echo -e "\n[$section]" >>"$file"
159 else
160 # Remove old values
161 sed -i -e "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ d; }" "$file"
162 fi
163 # Add new ones
164 for v in $values; do
165 sed -i -e "/^\[$section\]/ a\\
166$option = $v
167" "$file"
168 done
Sean Dague45917cc2014-02-24 16:09:14 -0500169 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600170}
171
172# Uncomment an option in an INI file
173# iniuncomment config-file section option
Ian Wienandaee18c72014-02-21 15:35:08 +1100174function iniuncomment {
Sean Dague45917cc2014-02-24 16:09:14 -0500175 local xtrace=$(set +o | grep xtrace)
176 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600177 local file=$1
178 local section=$2
179 local option=$3
180 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|[^ \t]*#[ \t]*\($option[ \t]*=.*$\)|\1|" "$file"
Sean Dague45917cc2014-02-24 16:09:14 -0500181 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600182}
183
184# Normalize config values to True or False
185# Accepts as False: 0 no No NO false False FALSE
186# Accepts as True: 1 yes Yes YES true True TRUE
187# VAR=$(trueorfalse default-value test-value)
Ian Wienandaee18c72014-02-21 15:35:08 +1100188function trueorfalse {
Sean Dague45917cc2014-02-24 16:09:14 -0500189 local xtrace=$(set +o | grep xtrace)
190 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600191 local default=$1
192 local testval=$2
193
194 [[ -z "$testval" ]] && { echo "$default"; return; }
195 [[ "0 no No NO false False FALSE" =~ "$testval" ]] && { echo "False"; return; }
196 [[ "1 yes Yes YES true True TRUE" =~ "$testval" ]] && { echo "True"; return; }
197 echo "$default"
Sean Dague45917cc2014-02-24 16:09:14 -0500198 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600199}
200
201
202# Control Functions
203# =================
204
205# Prints backtrace info
206# filename:lineno:function
207# backtrace level
208function backtrace {
209 local level=$1
210 local deep=$((${#BASH_SOURCE[@]} - 1))
211 echo "[Call Trace]"
212 while [ $level -le $deep ]; do
213 echo "${BASH_SOURCE[$deep]}:${BASH_LINENO[$deep-1]}:${FUNCNAME[$deep-1]}"
214 deep=$((deep - 1))
215 done
216}
217
218# Prints line number and "message" then exits
219# die $LINENO "message"
Ian Wienandaee18c72014-02-21 15:35:08 +1100220function die {
Dean Troyerdff49a22014-01-30 15:37:40 -0600221 local exitcode=$?
222 set +o xtrace
223 local line=$1; shift
224 if [ $exitcode == 0 ]; then
225 exitcode=1
226 fi
227 backtrace 2
228 err $line "$*"
Dean Troyera25a6f62014-02-24 16:03:41 -0600229 # Give buffers a second to flush
230 sleep 1
Dean Troyerdff49a22014-01-30 15:37:40 -0600231 exit $exitcode
232}
233
234# Checks an environment variable is not set or has length 0 OR if the
235# exit code is non-zero and prints "message" and exits
236# NOTE: env-var is the variable name without a '$'
237# die_if_not_set $LINENO env-var "message"
Ian Wienandaee18c72014-02-21 15:35:08 +1100238function die_if_not_set {
Dean Troyerdff49a22014-01-30 15:37:40 -0600239 local exitcode=$?
240 FXTRACE=$(set +o | grep xtrace)
241 set +o xtrace
242 local line=$1; shift
243 local evar=$1; shift
244 if ! is_set $evar || [ $exitcode != 0 ]; then
245 die $line "$*"
246 fi
247 $FXTRACE
248}
249
250# Prints line number and "message" in error format
251# err $LINENO "message"
Ian Wienandaee18c72014-02-21 15:35:08 +1100252function err {
Dean Troyerdff49a22014-01-30 15:37:40 -0600253 local exitcode=$?
254 errXTRACE=$(set +o | grep xtrace)
255 set +o xtrace
256 local msg="[ERROR] ${BASH_SOURCE[2]}:$1 $2"
257 echo $msg 1>&2;
258 if [[ -n ${SCREEN_LOGDIR} ]]; then
259 echo $msg >> "${SCREEN_LOGDIR}/error.log"
260 fi
261 $errXTRACE
262 return $exitcode
263}
264
265# Checks an environment variable is not set or has length 0 OR if the
266# exit code is non-zero and prints "message"
267# NOTE: env-var is the variable name without a '$'
268# err_if_not_set $LINENO env-var "message"
Ian Wienandaee18c72014-02-21 15:35:08 +1100269function err_if_not_set {
Dean Troyerdff49a22014-01-30 15:37:40 -0600270 local exitcode=$?
271 errinsXTRACE=$(set +o | grep xtrace)
272 set +o xtrace
273 local line=$1; shift
274 local evar=$1; shift
275 if ! is_set $evar || [ $exitcode != 0 ]; then
276 err $line "$*"
277 fi
278 $errinsXTRACE
279 return $exitcode
280}
281
282# Exit after outputting a message about the distribution not being supported.
283# exit_distro_not_supported [optional-string-telling-what-is-missing]
284function exit_distro_not_supported {
285 if [[ -z "$DISTRO" ]]; then
286 GetDistro
287 fi
288
289 if [ $# -gt 0 ]; then
290 die $LINENO "Support for $DISTRO is incomplete: no support for $@"
291 else
292 die $LINENO "Support for $DISTRO is incomplete."
293 fi
294}
295
296# Test if the named environment variable is set and not zero length
297# is_set env-var
Ian Wienandaee18c72014-02-21 15:35:08 +1100298function is_set {
Dean Troyerdff49a22014-01-30 15:37:40 -0600299 local var=\$"$1"
300 eval "[ -n \"$var\" ]" # For ex.: sh -c "[ -n \"$var\" ]" would be better, but several exercises depends on this
301}
302
303# Prints line number and "message" in warning format
304# warn $LINENO "message"
Ian Wienandaee18c72014-02-21 15:35:08 +1100305function warn {
Dean Troyerdff49a22014-01-30 15:37:40 -0600306 local exitcode=$?
307 errXTRACE=$(set +o | grep xtrace)
308 set +o xtrace
309 local msg="[WARNING] ${BASH_SOURCE[2]}:$1 $2"
310 echo $msg 1>&2;
311 if [[ -n ${SCREEN_LOGDIR} ]]; then
312 echo $msg >> "${SCREEN_LOGDIR}/error.log"
313 fi
314 $errXTRACE
315 return $exitcode
316}
317
318
319# Distro Functions
320# ================
321
322# Determine OS Vendor, Release and Update
323# Tested with OS/X, Ubuntu, RedHat, CentOS, Fedora
324# Returns results in global variables:
325# os_VENDOR - vendor name
326# os_RELEASE - release
327# os_UPDATE - update
328# os_PACKAGE - package type
329# os_CODENAME - vendor's codename for release
330# GetOSVersion
Ian Wienandaee18c72014-02-21 15:35:08 +1100331function GetOSVersion {
Dean Troyerdff49a22014-01-30 15:37:40 -0600332 # Figure out which vendor we are
333 if [[ -x "`which sw_vers 2>/dev/null`" ]]; then
334 # OS/X
335 os_VENDOR=`sw_vers -productName`
336 os_RELEASE=`sw_vers -productVersion`
337 os_UPDATE=${os_RELEASE##*.}
338 os_RELEASE=${os_RELEASE%.*}
339 os_PACKAGE=""
340 if [[ "$os_RELEASE" =~ "10.7" ]]; then
341 os_CODENAME="lion"
342 elif [[ "$os_RELEASE" =~ "10.6" ]]; then
343 os_CODENAME="snow leopard"
344 elif [[ "$os_RELEASE" =~ "10.5" ]]; then
345 os_CODENAME="leopard"
346 elif [[ "$os_RELEASE" =~ "10.4" ]]; then
347 os_CODENAME="tiger"
348 elif [[ "$os_RELEASE" =~ "10.3" ]]; then
349 os_CODENAME="panther"
350 else
351 os_CODENAME=""
352 fi
353 elif [[ -x $(which lsb_release 2>/dev/null) ]]; then
354 os_VENDOR=$(lsb_release -i -s)
355 os_RELEASE=$(lsb_release -r -s)
356 os_UPDATE=""
357 os_PACKAGE="rpm"
358 if [[ "Debian,Ubuntu,LinuxMint" =~ $os_VENDOR ]]; then
359 os_PACKAGE="deb"
360 elif [[ "SUSE LINUX" =~ $os_VENDOR ]]; then
361 lsb_release -d -s | grep -q openSUSE
362 if [[ $? -eq 0 ]]; then
363 os_VENDOR="openSUSE"
364 fi
365 elif [[ $os_VENDOR == "openSUSE project" ]]; then
366 os_VENDOR="openSUSE"
367 elif [[ $os_VENDOR =~ Red.*Hat ]]; then
368 os_VENDOR="Red Hat"
369 fi
370 os_CODENAME=$(lsb_release -c -s)
371 elif [[ -r /etc/redhat-release ]]; then
372 # Red Hat Enterprise Linux Server release 5.5 (Tikanga)
373 # Red Hat Enterprise Linux Server release 7.0 Beta (Maipo)
374 # CentOS release 5.5 (Final)
375 # CentOS Linux release 6.0 (Final)
376 # Fedora release 16 (Verne)
377 # XenServer release 6.2.0-70446c (xenenterprise)
378 os_CODENAME=""
379 for r in "Red Hat" CentOS Fedora XenServer; do
380 os_VENDOR=$r
381 if [[ -n "`grep \"$r\" /etc/redhat-release`" ]]; then
382 ver=`sed -e 's/^.* \([0-9].*\) (\(.*\)).*$/\1\|\2/' /etc/redhat-release`
383 os_CODENAME=${ver#*|}
384 os_RELEASE=${ver%|*}
385 os_UPDATE=${os_RELEASE##*.}
386 os_RELEASE=${os_RELEASE%.*}
387 break
388 fi
389 os_VENDOR=""
390 done
391 os_PACKAGE="rpm"
392 elif [[ -r /etc/SuSE-release ]]; then
393 for r in openSUSE "SUSE Linux"; do
394 if [[ "$r" = "SUSE Linux" ]]; then
395 os_VENDOR="SUSE LINUX"
396 else
397 os_VENDOR=$r
398 fi
399
400 if [[ -n "`grep \"$r\" /etc/SuSE-release`" ]]; then
401 os_CODENAME=`grep "CODENAME = " /etc/SuSE-release | sed 's:.* = ::g'`
402 os_RELEASE=`grep "VERSION = " /etc/SuSE-release | sed 's:.* = ::g'`
403 os_UPDATE=`grep "PATCHLEVEL = " /etc/SuSE-release | sed 's:.* = ::g'`
404 break
405 fi
406 os_VENDOR=""
407 done
408 os_PACKAGE="rpm"
409 # If lsb_release is not installed, we should be able to detect Debian OS
410 elif [[ -f /etc/debian_version ]] && [[ $(cat /proc/version) =~ "Debian" ]]; then
411 os_VENDOR="Debian"
412 os_PACKAGE="deb"
413 os_CODENAME=$(awk '/VERSION=/' /etc/os-release | sed 's/VERSION=//' | sed -r 's/\"|\(|\)//g' | awk '{print $2}')
414 os_RELEASE=$(awk '/VERSION_ID=/' /etc/os-release | sed 's/VERSION_ID=//' | sed 's/\"//g')
415 fi
416 export os_VENDOR os_RELEASE os_UPDATE os_PACKAGE os_CODENAME
417}
418
419# Translate the OS version values into common nomenclature
420# Sets global ``DISTRO`` from the ``os_*`` values
Ian Wienandaee18c72014-02-21 15:35:08 +1100421function GetDistro {
Dean Troyerdff49a22014-01-30 15:37:40 -0600422 GetOSVersion
423 if [[ "$os_VENDOR" =~ (Ubuntu) || "$os_VENDOR" =~ (Debian) ]]; then
424 # 'Everyone' refers to Ubuntu / Debian releases by the code name adjective
425 DISTRO=$os_CODENAME
426 elif [[ "$os_VENDOR" =~ (Fedora) ]]; then
427 # For Fedora, just use 'f' and the release
428 DISTRO="f$os_RELEASE"
429 elif [[ "$os_VENDOR" =~ (openSUSE) ]]; then
430 DISTRO="opensuse-$os_RELEASE"
431 elif [[ "$os_VENDOR" =~ (SUSE LINUX) ]]; then
432 # For SLE, also use the service pack
433 if [[ -z "$os_UPDATE" ]]; then
434 DISTRO="sle${os_RELEASE}"
435 else
436 DISTRO="sle${os_RELEASE}sp${os_UPDATE}"
437 fi
438 elif [[ "$os_VENDOR" =~ (Red Hat) || "$os_VENDOR" =~ (CentOS) ]]; then
439 # Drop the . release as we assume it's compatible
440 DISTRO="rhel${os_RELEASE::1}"
441 elif [[ "$os_VENDOR" =~ (XenServer) ]]; then
442 DISTRO="xs$os_RELEASE"
443 else
444 # Catch-all for now is Vendor + Release + Update
445 DISTRO="$os_VENDOR-$os_RELEASE.$os_UPDATE"
446 fi
447 export DISTRO
448}
449
450# Utility function for checking machine architecture
451# is_arch arch-type
452function is_arch {
453 ARCH_TYPE=$1
454
455 [[ "$(uname -m)" == "$ARCH_TYPE" ]]
456}
457
458# Determine if current distribution is a Fedora-based distribution
459# (Fedora, RHEL, CentOS, etc).
460# is_fedora
461function is_fedora {
462 if [[ -z "$os_VENDOR" ]]; then
463 GetOSVersion
464 fi
465
466 [ "$os_VENDOR" = "Fedora" ] || [ "$os_VENDOR" = "Red Hat" ] || [ "$os_VENDOR" = "CentOS" ]
467}
468
469
470# Determine if current distribution is a SUSE-based distribution
471# (openSUSE, SLE).
472# is_suse
473function is_suse {
474 if [[ -z "$os_VENDOR" ]]; then
475 GetOSVersion
476 fi
477
478 [ "$os_VENDOR" = "openSUSE" ] || [ "$os_VENDOR" = "SUSE LINUX" ]
479}
480
481
482# Determine if current distribution is an Ubuntu-based distribution
483# It will also detect non-Ubuntu but Debian-based distros
484# is_ubuntu
485function is_ubuntu {
486 if [[ -z "$os_PACKAGE" ]]; then
487 GetOSVersion
488 fi
489 [ "$os_PACKAGE" = "deb" ]
490}
491
492
493# Git Functions
494# =============
495
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600496# Returns openstack release name for a given branch name
497# ``get_release_name_from_branch branch-name``
Ian Wienandaee18c72014-02-21 15:35:08 +1100498function get_release_name_from_branch {
Dean Troyerabc7b1d2014-02-12 12:09:22 -0600499 local branch=$1
500 if [[ $branch =~ "stable/" ]]; then
501 echo ${branch#*/}
502 else
503 echo "master"
504 fi
505}
506
Dean Troyerdff49a22014-01-30 15:37:40 -0600507# git clone only if directory doesn't exist already. Since ``DEST`` might not
508# be owned by the installation user, we create the directory and change the
509# ownership to the proper user.
510# Set global RECLONE=yes to simulate a clone when dest-dir exists
511# Set global ERROR_ON_CLONE=True to abort execution with an error if the git repo
512# does not exist (default is False, meaning the repo will be cloned).
513# Uses global ``OFFLINE``
514# git_clone remote dest-dir branch
515function git_clone {
516 GIT_REMOTE=$1
517 GIT_DEST=$2
518 GIT_REF=$3
519 RECLONE=$(trueorfalse False $RECLONE)
Sean Dague64bd0162014-03-12 13:04:22 -0400520 local orig_dir=`pwd`
Dean Troyerdff49a22014-01-30 15:37:40 -0600521
522 if [[ "$OFFLINE" = "True" ]]; then
523 echo "Running in offline mode, clones already exist"
524 # print out the results so we know what change was used in the logs
525 cd $GIT_DEST
526 git show --oneline | head -1
Sean Dague64bd0162014-03-12 13:04:22 -0400527 cd $orig_dir
Dean Troyerdff49a22014-01-30 15:37:40 -0600528 return
529 fi
530
531 if echo $GIT_REF | egrep -q "^refs"; then
532 # If our branch name is a gerrit style refs/changes/...
533 if [[ ! -d $GIT_DEST ]]; then
534 [[ "$ERROR_ON_CLONE" = "True" ]] && \
535 die $LINENO "Cloning not allowed in this configuration"
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100536 git_timed clone $GIT_REMOTE $GIT_DEST
Dean Troyerdff49a22014-01-30 15:37:40 -0600537 fi
538 cd $GIT_DEST
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100539 git_timed fetch $GIT_REMOTE $GIT_REF && git checkout FETCH_HEAD
Dean Troyerdff49a22014-01-30 15:37:40 -0600540 else
541 # do a full clone only if the directory doesn't exist
542 if [[ ! -d $GIT_DEST ]]; then
543 [[ "$ERROR_ON_CLONE" = "True" ]] && \
544 die $LINENO "Cloning not allowed in this configuration"
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100545 git_timed clone $GIT_REMOTE $GIT_DEST
Dean Troyerdff49a22014-01-30 15:37:40 -0600546 cd $GIT_DEST
547 # This checkout syntax works for both branches and tags
548 git checkout $GIT_REF
549 elif [[ "$RECLONE" = "True" ]]; then
550 # if it does exist then simulate what clone does if asked to RECLONE
551 cd $GIT_DEST
552 # set the url to pull from and fetch
553 git remote set-url origin $GIT_REMOTE
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100554 git_timed fetch origin
Dean Troyerdff49a22014-01-30 15:37:40 -0600555 # remove the existing ignored files (like pyc) as they cause breakage
556 # (due to the py files having older timestamps than our pyc, so python
557 # thinks the pyc files are correct using them)
558 find $GIT_DEST -name '*.pyc' -delete
559
560 # handle GIT_REF accordingly to type (tag, branch)
561 if [[ -n "`git show-ref refs/tags/$GIT_REF`" ]]; then
562 git_update_tag $GIT_REF
563 elif [[ -n "`git show-ref refs/heads/$GIT_REF`" ]]; then
564 git_update_branch $GIT_REF
565 elif [[ -n "`git show-ref refs/remotes/origin/$GIT_REF`" ]]; then
566 git_update_remote_branch $GIT_REF
567 else
568 die $LINENO "$GIT_REF is neither branch nor tag"
569 fi
570
571 fi
572 fi
573
574 # print out the results so we know what change was used in the logs
575 cd $GIT_DEST
576 git show --oneline | head -1
Sean Dague64bd0162014-03-12 13:04:22 -0400577 cd $orig_dir
Dean Troyerdff49a22014-01-30 15:37:40 -0600578}
579
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100580# git can sometimes get itself infinitely stuck with transient network
581# errors or other issues with the remote end. This wraps git in a
582# timeout/retry loop and is intended to watch over non-local git
583# processes that might hang. GIT_TIMEOUT, if set, is passed directly
584# to timeout(1); otherwise the default value of 0 maintains the status
585# quo of waiting forever.
586# usage: git_timed <git-command>
Ian Wienandaee18c72014-02-21 15:35:08 +1100587function git_timed {
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100588 local count=0
589 local timeout=0
590
591 if [[ -n "${GIT_TIMEOUT}" ]]; then
592 timeout=${GIT_TIMEOUT}
593 fi
594
595 until timeout -s SIGINT ${timeout} git "$@"; do
596 # 124 is timeout(1)'s special return code when it reached the
597 # timeout; otherwise assume fatal failure
598 if [[ $? -ne 124 ]]; then
599 die $LINENO "git call failed: [git $@]"
600 fi
601
602 count=$(($count + 1))
603 warn "timeout ${count} for git call: [git $@]"
604 if [ $count -eq 3 ]; then
605 die $LINENO "Maximum of 3 git retries reached"
606 fi
607 sleep 5
608 done
609}
610
Dean Troyerdff49a22014-01-30 15:37:40 -0600611# git update using reference as a branch.
612# git_update_branch ref
Ian Wienandaee18c72014-02-21 15:35:08 +1100613function git_update_branch {
Dean Troyerdff49a22014-01-30 15:37:40 -0600614
615 GIT_BRANCH=$1
616
617 git checkout -f origin/$GIT_BRANCH
618 # a local branch might not exist
619 git branch -D $GIT_BRANCH || true
620 git checkout -b $GIT_BRANCH
621}
622
623# git update using reference as a branch.
624# git_update_remote_branch ref
Ian Wienandaee18c72014-02-21 15:35:08 +1100625function git_update_remote_branch {
Dean Troyerdff49a22014-01-30 15:37:40 -0600626
627 GIT_BRANCH=$1
628
629 git checkout -b $GIT_BRANCH -t origin/$GIT_BRANCH
630}
631
632# git update using reference as a tag. Be careful editing source at that repo
633# as working copy will be in a detached mode
634# git_update_tag ref
Ian Wienandaee18c72014-02-21 15:35:08 +1100635function git_update_tag {
Dean Troyerdff49a22014-01-30 15:37:40 -0600636
637 GIT_TAG=$1
638
639 git tag -d $GIT_TAG
640 # fetching given tag only
Ian Wienandd53ad0b2014-02-20 13:55:13 +1100641 git_timed fetch origin tag $GIT_TAG
Dean Troyerdff49a22014-01-30 15:37:40 -0600642 git checkout -f $GIT_TAG
643}
644
645
646# OpenStack Functions
647# ===================
648
649# Get the default value for HOST_IP
650# get_default_host_ip fixed_range floating_range host_ip_iface host_ip
Ian Wienandaee18c72014-02-21 15:35:08 +1100651function get_default_host_ip {
Dean Troyerdff49a22014-01-30 15:37:40 -0600652 local fixed_range=$1
653 local floating_range=$2
654 local host_ip_iface=$3
655 local host_ip=$4
656
657 # Find the interface used for the default route
658 host_ip_iface=${host_ip_iface:-$(ip route | sed -n '/^default/{ s/.*dev \(\w\+\)\s\+.*/\1/; p; }' | head -1)}
659 # Search for an IP unless an explicit is set by ``HOST_IP`` environment variable
660 if [ -z "$host_ip" -o "$host_ip" == "dhcp" ]; then
661 host_ip=""
662 host_ips=`LC_ALL=C ip -f inet addr show ${host_ip_iface} | awk '/inet/ {split($2,parts,"/"); print parts[1]}'`
663 for IP in $host_ips; do
664 # Attempt to filter out IP addresses that are part of the fixed and
665 # floating range. Note that this method only works if the ``netaddr``
666 # python library is installed. If it is not installed, an error
667 # will be printed and the first IP from the interface will be used.
668 # If that is not correct set ``HOST_IP`` in ``localrc`` to the correct
669 # address.
670 if ! (address_in_net $IP $fixed_range || address_in_net $IP $floating_range); then
671 host_ip=$IP
672 break;
673 fi
674 done
675 fi
676 echo $host_ip
677}
678
679# Grab a numbered field from python prettytable output
680# Fields are numbered starting with 1
681# Reverse syntax is supported: -1 is the last field, -2 is second to last, etc.
682# get_field field-number
Ian Wienandaee18c72014-02-21 15:35:08 +1100683function get_field {
Dean Troyerdff49a22014-01-30 15:37:40 -0600684 while read data; do
685 if [ "$1" -lt 0 ]; then
686 field="(\$(NF$1))"
687 else
688 field="\$$(($1 + 1))"
689 fi
690 echo "$data" | awk -F'[ \t]*\\|[ \t]*' "{print $field}"
691 done
692}
693
694# Add a policy to a policy.json file
695# Do nothing if the policy already exists
696# ``policy_add policy_file policy_name policy_permissions``
Ian Wienandaee18c72014-02-21 15:35:08 +1100697function policy_add {
Dean Troyerdff49a22014-01-30 15:37:40 -0600698 local policy_file=$1
699 local policy_name=$2
700 local policy_perm=$3
701
702 if grep -q ${policy_name} ${policy_file}; then
703 echo "Policy ${policy_name} already exists in ${policy_file}"
704 return
705 fi
706
707 # Add a terminating comma to policy lines without one
708 # Remove the closing '}' and all lines following to the end-of-file
709 local tmpfile=$(mktemp)
710 uniq ${policy_file} | sed -e '
711 s/]$/],/
712 /^[}]/,$d
713 ' > ${tmpfile}
714
715 # Append policy and closing brace
716 echo " \"${policy_name}\": ${policy_perm}" >>${tmpfile}
717 echo "}" >>${tmpfile}
718
719 mv ${tmpfile} ${policy_file}
720}
721
722
723# Package Functions
724# =================
725
726# _get_package_dir
Ian Wienandaee18c72014-02-21 15:35:08 +1100727function _get_package_dir {
Dean Troyerdff49a22014-01-30 15:37:40 -0600728 local pkg_dir
729 if is_ubuntu; then
730 pkg_dir=$FILES/apts
731 elif is_fedora; then
732 pkg_dir=$FILES/rpms
733 elif is_suse; then
734 pkg_dir=$FILES/rpms-suse
735 else
736 exit_distro_not_supported "list of packages"
737 fi
738 echo "$pkg_dir"
739}
740
741# Wrapper for ``apt-get`` to set cache and proxy environment variables
742# Uses globals ``OFFLINE``, ``*_proxy``
743# apt_get operation package [package ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100744function apt_get {
Sean Dague45917cc2014-02-24 16:09:14 -0500745 local xtrace=$(set +o | grep xtrace)
746 set +o xtrace
747
Dean Troyerdff49a22014-01-30 15:37:40 -0600748 [[ "$OFFLINE" = "True" || -z "$@" ]] && return
749 local sudo="sudo"
750 [[ "$(id -u)" = "0" ]] && sudo="env"
Sean Dague45917cc2014-02-24 16:09:14 -0500751
752 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600753 $sudo DEBIAN_FRONTEND=noninteractive \
754 http_proxy=$http_proxy https_proxy=$https_proxy \
755 no_proxy=$no_proxy \
756 apt-get --option "Dpkg::Options::=--force-confold" --assume-yes "$@"
757}
758
759# get_packages() collects a list of package names of any type from the
760# prerequisite files in ``files/{apts|rpms}``. The list is intended
761# to be passed to a package installer such as apt or yum.
762#
763# Only packages required for the services in 1st argument will be
764# included. Two bits of metadata are recognized in the prerequisite files:
765#
766# - ``# NOPRIME`` defers installation to be performed later in `stack.sh`
767# - ``# dist:DISTRO`` or ``dist:DISTRO1,DISTRO2`` limits the selection
768# of the package to the distros listed. The distro names are case insensitive.
Ian Wienandaee18c72014-02-21 15:35:08 +1100769function get_packages {
Sean Dague45917cc2014-02-24 16:09:14 -0500770 local xtrace=$(set +o | grep xtrace)
771 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600772 local services=$@
773 local package_dir=$(_get_package_dir)
774 local file_to_parse
775 local service
776
777 if [[ -z "$package_dir" ]]; then
778 echo "No package directory supplied"
779 return 1
780 fi
781 if [[ -z "$DISTRO" ]]; then
782 GetDistro
Sean Dague45917cc2014-02-24 16:09:14 -0500783 echo "Found Distro $DISTRO"
Dean Troyerdff49a22014-01-30 15:37:40 -0600784 fi
785 for service in ${services//,/ }; do
786 # Allow individual services to specify dependencies
787 if [[ -e ${package_dir}/${service} ]]; then
788 file_to_parse="${file_to_parse} $service"
789 fi
790 # NOTE(sdague) n-api needs glance for now because that's where
791 # glance client is
792 if [[ $service == n-api ]]; then
793 if [[ ! $file_to_parse =~ nova ]]; then
794 file_to_parse="${file_to_parse} nova"
795 fi
796 if [[ ! $file_to_parse =~ glance ]]; then
797 file_to_parse="${file_to_parse} glance"
798 fi
799 elif [[ $service == c-* ]]; then
800 if [[ ! $file_to_parse =~ cinder ]]; then
801 file_to_parse="${file_to_parse} cinder"
802 fi
803 elif [[ $service == ceilometer-* ]]; then
804 if [[ ! $file_to_parse =~ ceilometer ]]; then
805 file_to_parse="${file_to_parse} ceilometer"
806 fi
807 elif [[ $service == s-* ]]; then
808 if [[ ! $file_to_parse =~ swift ]]; then
809 file_to_parse="${file_to_parse} swift"
810 fi
811 elif [[ $service == n-* ]]; then
812 if [[ ! $file_to_parse =~ nova ]]; then
813 file_to_parse="${file_to_parse} nova"
814 fi
815 elif [[ $service == g-* ]]; then
816 if [[ ! $file_to_parse =~ glance ]]; then
817 file_to_parse="${file_to_parse} glance"
818 fi
819 elif [[ $service == key* ]]; then
820 if [[ ! $file_to_parse =~ keystone ]]; then
821 file_to_parse="${file_to_parse} keystone"
822 fi
823 elif [[ $service == q-* ]]; then
824 if [[ ! $file_to_parse =~ neutron ]]; then
825 file_to_parse="${file_to_parse} neutron"
826 fi
Adam Gandelman539ec432014-03-18 18:57:43 -0700827 elif [[ $service == ir-* ]]; then
828 if [[ ! $file_to_parse =~ ironic ]]; then
829 file_to_parse="${file_to_parse} ironic"
830 fi
Dean Troyerdff49a22014-01-30 15:37:40 -0600831 fi
832 done
833
834 for file in ${file_to_parse}; do
835 local fname=${package_dir}/${file}
836 local OIFS line package distros distro
837 [[ -e $fname ]] || continue
838
839 OIFS=$IFS
840 IFS=$'\n'
841 for line in $(<${fname}); do
842 if [[ $line =~ "NOPRIME" ]]; then
843 continue
844 fi
845
846 # Assume we want this package
847 package=${line%#*}
848 inst_pkg=1
849
850 # Look for # dist:xxx in comment
851 if [[ $line =~ (.*)#.*dist:([^ ]*) ]]; then
852 # We are using BASH regexp matching feature.
853 package=${BASH_REMATCH[1]}
854 distros=${BASH_REMATCH[2]}
855 # In bash ${VAR,,} will lowecase VAR
856 # Look for a match in the distro list
857 if [[ ! ${distros,,} =~ ${DISTRO,,} ]]; then
858 # If no match then skip this package
859 inst_pkg=0
860 fi
861 fi
862
863 # Look for # testonly in comment
864 if [[ $line =~ (.*)#.*testonly.* ]]; then
865 package=${BASH_REMATCH[1]}
866 # Are we installing test packages? (test for the default value)
867 if [[ $INSTALL_TESTONLY_PACKAGES = "False" ]]; then
868 # If not installing test packages the skip this package
869 inst_pkg=0
870 fi
871 fi
872
873 if [[ $inst_pkg = 1 ]]; then
874 echo $package
875 fi
876 done
877 IFS=$OIFS
878 done
Sean Dague45917cc2014-02-24 16:09:14 -0500879 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -0600880}
881
882# Distro-agnostic package installer
883# install_package package [package ...]
Monty Taylor5cc6d2c2014-06-06 08:45:16 -0400884function update_package_repo {
885 if [[ "NO_UPDATE_REPOS" = "True" ]]; then
886 return 0
887 fi
Dean Troyerdff49a22014-01-30 15:37:40 -0600888
Monty Taylor5cc6d2c2014-06-06 08:45:16 -0400889 if is_ubuntu; then
890 local xtrace=$(set +o | grep xtrace)
891 set +o xtrace
892 if [[ "$REPOS_UPDATED" != "True" || "$RETRY_UPDATE" = "True" ]]; then
893 # if there are transient errors pulling the updates, that's fine.
894 # It may be secondary repositories that we don't really care about.
895 apt_get update || /bin/true
896 REPOS_UPDATED=True
897 fi
Sean Dague45917cc2014-02-24 16:09:14 -0500898 $xtrace
Monty Taylor5cc6d2c2014-06-06 08:45:16 -0400899 fi
900}
901
902function real_install_package {
903 if is_ubuntu; then
Dean Troyerdff49a22014-01-30 15:37:40 -0600904 apt_get install "$@"
905 elif is_fedora; then
906 yum_install "$@"
907 elif is_suse; then
908 zypper_install "$@"
909 else
910 exit_distro_not_supported "installing packages"
911 fi
912}
913
Monty Taylor5cc6d2c2014-06-06 08:45:16 -0400914# Distro-agnostic package installer
915# install_package package [package ...]
916function install_package {
917 update_package_repo
918 real_install_package $@ || RETRY_UPDATE=True update_package_repo && real_install_package $@
919}
920
Dean Troyerdff49a22014-01-30 15:37:40 -0600921# Distro-agnostic function to tell if a package is installed
922# is_package_installed package [package ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100923function is_package_installed {
Dean Troyerdff49a22014-01-30 15:37:40 -0600924 if [[ -z "$@" ]]; then
925 return 1
926 fi
927
928 if [[ -z "$os_PACKAGE" ]]; then
929 GetOSVersion
930 fi
931
932 if [[ "$os_PACKAGE" = "deb" ]]; then
933 dpkg -s "$@" > /dev/null 2> /dev/null
934 elif [[ "$os_PACKAGE" = "rpm" ]]; then
935 rpm --quiet -q "$@"
936 else
937 exit_distro_not_supported "finding if a package is installed"
938 fi
939}
940
941# Distro-agnostic package uninstaller
942# uninstall_package package [package ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100943function uninstall_package {
Dean Troyerdff49a22014-01-30 15:37:40 -0600944 if is_ubuntu; then
945 apt_get purge "$@"
946 elif is_fedora; then
947 sudo yum remove -y "$@"
948 elif is_suse; then
949 sudo zypper rm "$@"
950 else
951 exit_distro_not_supported "uninstalling packages"
952 fi
953}
954
955# Wrapper for ``yum`` to set proxy environment variables
956# Uses globals ``OFFLINE``, ``*_proxy``
957# yum_install package [package ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100958function yum_install {
Dean Troyerdff49a22014-01-30 15:37:40 -0600959 [[ "$OFFLINE" = "True" ]] && return
960 local sudo="sudo"
961 [[ "$(id -u)" = "0" ]] && sudo="env"
Ian Wienandb27f16d2014-02-28 14:29:02 +1100962
963 # The manual check for missing packages is because yum -y assumes
964 # missing packages are OK. See
965 # https://bugzilla.redhat.com/show_bug.cgi?id=965567
Dean Troyerdff49a22014-01-30 15:37:40 -0600966 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
967 no_proxy=$no_proxy \
Ian Wienandb27f16d2014-02-28 14:29:02 +1100968 yum install -y "$@" 2>&1 | \
969 awk '
970 BEGIN { fail=0 }
971 /No package/ { fail=1 }
972 { print }
973 END { exit fail }' || \
974 die $LINENO "Missing packages detected"
975
976 # also ensure we catch a yum failure
977 if [[ ${PIPESTATUS[0]} != 0 ]]; then
978 die $LINENO "Yum install failure"
979 fi
Dean Troyerdff49a22014-01-30 15:37:40 -0600980}
981
982# zypper wrapper to set arguments correctly
983# zypper_install package [package ...]
Ian Wienandaee18c72014-02-21 15:35:08 +1100984function zypper_install {
Dean Troyerdff49a22014-01-30 15:37:40 -0600985 [[ "$OFFLINE" = "True" ]] && return
986 local sudo="sudo"
987 [[ "$(id -u)" = "0" ]] && sudo="env"
988 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
989 zypper --non-interactive install --auto-agree-with-licenses "$@"
990}
991
992
993# Process Functions
994# =================
995
996# _run_process() is designed to be backgrounded by run_process() to simulate a
997# fork. It includes the dirty work of closing extra filehandles and preparing log
998# files to produce the same logs as screen_it(). The log filename is derived
999# from the service name and global-and-now-misnamed SCREEN_LOGDIR
1000# _run_process service "command-line"
Ian Wienandaee18c72014-02-21 15:35:08 +11001001function _run_process {
Dean Troyerdff49a22014-01-30 15:37:40 -06001002 local service=$1
1003 local command="$2"
1004
1005 # Undo logging redirections and close the extra descriptors
1006 exec 1>&3
1007 exec 2>&3
1008 exec 3>&-
1009 exec 6>&-
1010
1011 if [[ -n ${SCREEN_LOGDIR} ]]; then
1012 exec 1>&${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log 2>&1
1013 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
1014
1015 # TODO(dtroyer): Hack to get stdout from the Python interpreter for the logs.
1016 export PYTHONUNBUFFERED=1
1017 fi
1018
1019 exec /bin/bash -c "$command"
1020 die "$service exec failure: $command"
1021}
1022
1023# Helper to remove the ``*.failure`` files under ``$SERVICE_DIR/$SCREEN_NAME``.
1024# This is used for ``service_check`` when all the ``screen_it`` are called finished
1025# init_service_check
Ian Wienandaee18c72014-02-21 15:35:08 +11001026function init_service_check {
Dean Troyerdff49a22014-01-30 15:37:40 -06001027 SCREEN_NAME=${SCREEN_NAME:-stack}
1028 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1029
1030 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
1031 mkdir -p "$SERVICE_DIR/$SCREEN_NAME"
1032 fi
1033
1034 rm -f "$SERVICE_DIR/$SCREEN_NAME"/*.failure
1035}
1036
1037# Find out if a process exists by partial name.
1038# is_running name
Ian Wienandaee18c72014-02-21 15:35:08 +11001039function is_running {
Dean Troyerdff49a22014-01-30 15:37:40 -06001040 local name=$1
1041 ps auxw | grep -v grep | grep ${name} > /dev/null
1042 RC=$?
1043 # some times I really hate bash reverse binary logic
1044 return $RC
1045}
1046
1047# run_process() launches a child process that closes all file descriptors and
1048# then exec's the passed in command. This is meant to duplicate the semantics
1049# of screen_it() without screen. PIDs are written to
1050# $SERVICE_DIR/$SCREEN_NAME/$service.pid
1051# run_process service "command-line"
Ian Wienandaee18c72014-02-21 15:35:08 +11001052function run_process {
Dean Troyerdff49a22014-01-30 15:37:40 -06001053 local service=$1
1054 local command="$2"
1055
1056 # Spawn the child process
1057 _run_process "$service" "$command" &
1058 echo $!
1059}
1060
Sean Dague0afa9122014-06-18 15:36:19 -04001061function _start_in_screen {
1062 local service=$1
1063 local cmd=$2
1064 local screen_name=${SCREEN_NAME:-stack}
1065 local status_dir=${SERVICE_DIR:-${DEST}/status}
1066 local service_dir="$status_dir/$screen_name"
1067 local pid="$service_dir/$service.pid"
1068 local failure="$service_dir/$service.failure"
1069
1070 if [[ -n ${SCREEN_LOGDIR} ]]; then
1071 local logfile=${SCREEN_LOGDIR}/screen-${service}.${CURRENT_LOG_TIME}.log
1072 local shortlog=${SCREEN_LOGDIR}/screen-${service}.log
1073 # this whole dance is done because of slow nodes
1074 screen -S $screen_name -p $service -X logfile ${logfile}
1075 screen -S $screen_name -p $service -X log on
1076 ln -sf ${logfile} ${shortlog}
1077 fi
1078
1079 NL=`echo -ne '\015'`
1080 # This fun command does the following:
1081 # - the passed server command is backgrounded
1082 # - the pid of the background process is saved in the usual place
1083 # - the server process is brought back to the foreground
1084 # - if the server process exits prematurely the fg command errors
1085 # and a message is written to stdout and the service failure file
1086 # The pid saved can be used in screen_stop() as a process group
1087 # id to kill off all child processes
1088 echo "Running: $cmd & echo \$! >$pid; fg || echo \"$service failed to start\" | tee \"$failure\"$NL"
1089 screen -S $screen_name -p $service -X stuff "$cmd & echo \$! >$pid; fg || echo \"$service failed to start\" | tee \"$failure\"$NL"
1090}
1091
1092
1093function _is_running_in_screen {
1094 local service=$1
1095 local screen_name=${SCREEN_NAME:-stack}
1096 local status_dir=${SERVICE_DIR:-${DEST}/status}
1097 local service_dir="$status_dir/$screen_name"
1098 local pid="$service_dir/$service.pid"
1099 local failure="$service_dir/$service.failure"
1100 if [[ ! -e "$pid" && ! -e "$failure" ]]; then
1101 # if we don't have a pid or a failure for why, the command may not
1102 # have stuffed in there
1103 echo "Warning: neither $pid nor $failure exist, $service didn't seem to start"
1104 return 1
1105 fi
1106 if [[ -n ${SCREEN_LOGDIR} ]]; then
1107 # if we should be logging, but we don't have a log file, something is wrong
1108 local logfile=${SCREEN_LOGDIR}/screen-${service}.${CURRENT_LOG_TIME}.log
1109 if [[ ! -e "$logfile" ]]; then
1110 echo "Warning: expected logfile $logfile not found, something wrong with starting $service"
1111 return 1
1112 fi
1113 fi
1114 return 0
1115}
1116
Dean Troyerdff49a22014-01-30 15:37:40 -06001117# Helper to launch a service in a named screen
1118# screen_it service "command-line"
1119function screen_it {
Sean Dague0afa9122014-06-18 15:36:19 -04001120 local service=$1
1121 local cmd=$2
1122 local screen_name=${SCREEN_NAME:-stack}
1123 local status_dir=${SERVICE_DIR:-${DEST}/status}
1124 local service_dir="$status_dir/$screen_name"
1125 local use_screen=$(trueorfalse True $USE_SCREEN)
1126 local pid="$service_dir/$service.pid"
Dean Troyerdff49a22014-01-30 15:37:40 -06001127
1128 if is_service_enabled $1; then
1129 # Append the service to the screen rc file
Sean Dague0afa9122014-06-18 15:36:19 -04001130 screen_rc "$service" "$cmd"
Dean Troyerdff49a22014-01-30 15:37:40 -06001131
Sean Dague0afa9122014-06-18 15:36:19 -04001132 if [[ "$use_screen" = "True" ]]; then
1133 screen -S $screen_name -X screen -t $service
Dean Troyerdff49a22014-01-30 15:37:40 -06001134
Sean Dague0afa9122014-06-18 15:36:19 -04001135 # this retry loop brought to you by slow compute nodes, screen raciness,
1136 # and frustration in upgrading.
1137 local screen_tries=0
1138 while [ "$screen_tries" -lt 10 ]; do
1139 _start_in_screen "$service" "$cmd"
1140 if _is_running_in_screen $service; then
1141 screen_tries=10
1142 else
1143 screen_tries=$[screen_tries + 1]
1144 echo "Failed to start service after $screen_tries attempt(s), retrying"
1145 if [[ "$screen_tries" -eq 10 ]]; then
1146 echo "Too many retries, giving up"
1147 exit 1
1148 fi
1149 sleep 1
1150 fi
1151 done
Dean Troyerdff49a22014-01-30 15:37:40 -06001152 else
1153 # Spawn directly without screen
Sean Dague0afa9122014-06-18 15:36:19 -04001154 run_process "$service" "$cmd" >$pid
Dean Troyerdff49a22014-01-30 15:37:40 -06001155 fi
1156 fi
1157}
1158
1159# Screen rc file builder
1160# screen_rc service "command-line"
1161function screen_rc {
1162 SCREEN_NAME=${SCREEN_NAME:-stack}
1163 SCREENRC=$TOP_DIR/$SCREEN_NAME-screenrc
1164 if [[ ! -e $SCREENRC ]]; then
1165 # Name the screen session
1166 echo "sessionname $SCREEN_NAME" > $SCREENRC
1167 # Set a reasonable statusbar
1168 echo "hardstatus alwayslastline '$SCREEN_HARDSTATUS'" >> $SCREENRC
1169 # Some distributions override PROMPT_COMMAND for the screen terminal type - turn that off
1170 echo "setenv PROMPT_COMMAND /bin/true" >> $SCREENRC
1171 echo "screen -t shell bash" >> $SCREENRC
1172 fi
1173 # If this service doesn't already exist in the screenrc file
1174 if ! grep $1 $SCREENRC 2>&1 > /dev/null; then
1175 NL=`echo -ne '\015'`
1176 echo "screen -t $1 bash" >> $SCREENRC
1177 echo "stuff \"$2$NL\"" >> $SCREENRC
1178
1179 if [[ -n ${SCREEN_LOGDIR} ]]; then
1180 echo "logfile ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log" >>$SCREENRC
1181 echo "log on" >>$SCREENRC
1182 fi
1183 fi
1184}
1185
1186# Stop a service in screen
1187# If a PID is available use it, kill the whole process group via TERM
1188# If screen is being used kill the screen window; this will catch processes
1189# that did not leave a PID behind
1190# screen_stop service
Ian Wienandaee18c72014-02-21 15:35:08 +11001191function screen_stop {
Dean Troyerdff49a22014-01-30 15:37:40 -06001192 SCREEN_NAME=${SCREEN_NAME:-stack}
1193 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1194 USE_SCREEN=$(trueorfalse True $USE_SCREEN)
1195
1196 if is_service_enabled $1; then
1197 # Kill via pid if we have one available
1198 if [[ -r $SERVICE_DIR/$SCREEN_NAME/$1.pid ]]; then
1199 pkill -TERM -P -$(cat $SERVICE_DIR/$SCREEN_NAME/$1.pid)
1200 rm $SERVICE_DIR/$SCREEN_NAME/$1.pid
1201 fi
1202 if [[ "$USE_SCREEN" = "True" ]]; then
1203 # Clean up the screen window
1204 screen -S $SCREEN_NAME -p $1 -X kill
1205 fi
1206 fi
1207}
1208
1209# Helper to get the status of each running service
1210# service_check
Ian Wienandaee18c72014-02-21 15:35:08 +11001211function service_check {
Dean Troyerdff49a22014-01-30 15:37:40 -06001212 local service
1213 local failures
1214 SCREEN_NAME=${SCREEN_NAME:-stack}
1215 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1216
1217
1218 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
1219 echo "No service status directory found"
1220 return
1221 fi
1222
1223 # Check if there is any falure flag file under $SERVICE_DIR/$SCREEN_NAME
Sean Dague09bd7c82014-02-03 08:35:26 +09001224 # make this -o errexit safe
1225 failures=`ls "$SERVICE_DIR/$SCREEN_NAME"/*.failure 2>/dev/null || /bin/true`
Dean Troyerdff49a22014-01-30 15:37:40 -06001226
1227 for service in $failures; do
1228 service=`basename $service`
1229 service=${service%.failure}
1230 echo "Error: Service $service is not running"
1231 done
1232
1233 if [ -n "$failures" ]; then
Sean Dague12379222014-02-27 17:16:46 -05001234 die $LINENO "More details about the above errors can be found with screen, with ./rejoin-stack.sh"
Dean Troyerdff49a22014-01-30 15:37:40 -06001235 fi
1236}
1237
1238
1239# Python Functions
1240# ================
1241
1242# Get the path to the pip command.
1243# get_pip_command
Ian Wienandaee18c72014-02-21 15:35:08 +11001244function get_pip_command {
Dean Troyerdff49a22014-01-30 15:37:40 -06001245 which pip || which pip-python
1246
1247 if [ $? -ne 0 ]; then
1248 die $LINENO "Unable to find pip; cannot continue"
1249 fi
1250}
1251
1252# Get the path to the direcotry where python executables are installed.
1253# get_python_exec_prefix
Ian Wienandaee18c72014-02-21 15:35:08 +11001254function get_python_exec_prefix {
Dean Troyerdff49a22014-01-30 15:37:40 -06001255 if is_fedora || is_suse; then
1256 echo "/usr/bin"
1257 else
1258 echo "/usr/local/bin"
1259 fi
1260}
1261
1262# Wrapper for ``pip install`` to set cache and proxy environment variables
1263# Uses globals ``OFFLINE``, ``PIP_DOWNLOAD_CACHE``, ``PIP_USE_MIRRORS``,
1264# ``TRACK_DEPENDS``, ``*_proxy``
1265# pip_install package [package ...]
1266function pip_install {
Sean Dague45917cc2014-02-24 16:09:14 -05001267 local xtrace=$(set +o | grep xtrace)
1268 set +o xtrace
1269 if [[ "$OFFLINE" = "True" || -z "$@" ]]; then
1270 $xtrace
1271 return
1272 fi
1273
Dean Troyerdff49a22014-01-30 15:37:40 -06001274 if [[ -z "$os_PACKAGE" ]]; then
1275 GetOSVersion
1276 fi
1277 if [[ $TRACK_DEPENDS = True ]]; then
1278 source $DEST/.venv/bin/activate
1279 CMD_PIP=$DEST/.venv/bin/pip
1280 SUDO_PIP="env"
1281 else
1282 SUDO_PIP="sudo"
1283 CMD_PIP=$(get_pip_command)
1284 fi
1285
1286 # Mirror option not needed anymore because pypi has CDN available,
1287 # but it's useful in certain circumstances
1288 PIP_USE_MIRRORS=${PIP_USE_MIRRORS:-False}
1289 if [[ "$PIP_USE_MIRRORS" != "False" ]]; then
1290 PIP_MIRROR_OPT="--use-mirrors"
1291 fi
1292
1293 # pip < 1.4 has a bug where it will use an already existing build
1294 # directory unconditionally. Say an earlier component installs
1295 # foo v1.1; pip will have built foo's source in
1296 # /tmp/$USER-pip-build. Even if a later component specifies foo <
1297 # 1.1, the existing extracted build will be used and cause
1298 # confusing errors. By creating unique build directories we avoid
1299 # this problem. See https://github.com/pypa/pip/issues/709
1300 local pip_build_tmp=$(mktemp --tmpdir -d pip-build.XXXXX)
1301
Sean Dague45917cc2014-02-24 16:09:14 -05001302 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001303 $SUDO_PIP PIP_DOWNLOAD_CACHE=${PIP_DOWNLOAD_CACHE:-/var/cache/pip} \
Yves-Gwenael Bourhisd79a8ac2014-04-14 14:49:07 +02001304 http_proxy=$http_proxy \
1305 https_proxy=$https_proxy \
1306 no_proxy=$no_proxy \
Dean Troyerdff49a22014-01-30 15:37:40 -06001307 $CMD_PIP install --build=${pip_build_tmp} \
1308 $PIP_MIRROR_OPT $@ \
1309 && $SUDO_PIP rm -rf ${pip_build_tmp}
1310}
1311
Sean Dague099e5e32014-03-31 10:35:43 -04001312# this should be used if you want to install globally, all libraries should
1313# use this, especially *oslo* ones
1314function setup_install {
1315 local project_dir=$1
1316 setup_package_with_req_sync $project_dir
1317}
1318
1319# this should be used for projects which run services, like all services
1320function setup_develop {
1321 local project_dir=$1
1322 setup_package_with_req_sync $project_dir -e
1323}
1324
Dean Troyeraf616d92014-02-17 12:57:55 -06001325# ``pip install -e`` the package, which processes the dependencies
1326# using pip before running `setup.py develop`
1327#
1328# Updates the dependencies in project_dir from the
1329# openstack/requirements global list before installing anything.
1330#
1331# Uses globals ``TRACK_DEPENDS``, ``REQUIREMENTS_DIR``, ``UNDO_REQUIREMENTS``
1332# setup_develop directory
Sean Dague099e5e32014-03-31 10:35:43 -04001333function setup_package_with_req_sync {
Dean Troyeraf616d92014-02-17 12:57:55 -06001334 local project_dir=$1
Sean Dague099e5e32014-03-31 10:35:43 -04001335 local flags=$2
Dean Troyeraf616d92014-02-17 12:57:55 -06001336
Dean Troyeraf616d92014-02-17 12:57:55 -06001337 # Don't update repo if local changes exist
1338 # Don't use buggy "git diff --quiet"
Dean Troyer83b6c992014-02-27 12:41:28 -06001339 # ``errexit`` requires us to trap the exit code when the repo is changed
1340 local update_requirements=$(cd $project_dir && git diff --exit-code >/dev/null || echo "changed")
Dean Troyeraf616d92014-02-17 12:57:55 -06001341
YAMAMOTO Takashi3b1f2e42014-02-24 20:30:07 +09001342 if [[ $update_requirements != "changed" ]]; then
Dean Troyeraf616d92014-02-17 12:57:55 -06001343 (cd $REQUIREMENTS_DIR; \
1344 $SUDO_CMD python update.py $project_dir)
1345 fi
1346
Sean Dague099e5e32014-03-31 10:35:43 -04001347 setup_package $project_dir $flags
Dean Troyeraf616d92014-02-17 12:57:55 -06001348
1349 # We've just gone and possibly modified the user's source tree in an
1350 # automated way, which is considered bad form if it's a development
1351 # tree because we've screwed up their next git checkin. So undo it.
1352 #
1353 # However... there are some circumstances, like running in the gate
1354 # where we really really want the overridden version to stick. So provide
1355 # a variable that tells us whether or not we should UNDO the requirements
1356 # changes (this will be set to False in the OpenStack ci gate)
1357 if [ $UNDO_REQUIREMENTS = "True" ]; then
YAMAMOTO Takashi3b1f2e42014-02-24 20:30:07 +09001358 if [[ $update_requirements != "changed" ]]; then
Dean Troyeraf616d92014-02-17 12:57:55 -06001359 (cd $project_dir && git reset --hard)
1360 fi
1361 fi
1362}
1363
1364# ``pip install -e`` the package, which processes the dependencies
1365# using pip before running `setup.py develop`
1366# Uses globals ``STACK_USER``
1367# setup_develop_no_requirements_update directory
Sean Dague099e5e32014-03-31 10:35:43 -04001368function setup_package {
Dean Troyeraf616d92014-02-17 12:57:55 -06001369 local project_dir=$1
Sean Dague099e5e32014-03-31 10:35:43 -04001370 local flags=$2
Dean Troyeraf616d92014-02-17 12:57:55 -06001371
Sean Dague099e5e32014-03-31 10:35:43 -04001372 pip_install $flags $project_dir
Dean Troyeraf616d92014-02-17 12:57:55 -06001373 # ensure that further actions can do things like setup.py sdist
Sean Dague099e5e32014-03-31 10:35:43 -04001374 if [[ "$flags" == "-e" ]]; then
1375 safe_chown -R $STACK_USER $1/*.egg-info
1376 fi
Dean Troyeraf616d92014-02-17 12:57:55 -06001377}
1378
Dean Troyerdff49a22014-01-30 15:37:40 -06001379
1380# Service Functions
1381# =================
1382
1383# remove extra commas from the input string (i.e. ``ENABLED_SERVICES``)
1384# _cleanup_service_list service-list
Ian Wienandaee18c72014-02-21 15:35:08 +11001385function _cleanup_service_list {
Dean Troyerdff49a22014-01-30 15:37:40 -06001386 echo "$1" | sed -e '
1387 s/,,/,/g;
1388 s/^,//;
1389 s/,$//
1390 '
1391}
1392
1393# disable_all_services() removes all current services
1394# from ``ENABLED_SERVICES`` to reset the configuration
1395# before a minimal installation
1396# Uses global ``ENABLED_SERVICES``
1397# disable_all_services
Ian Wienandaee18c72014-02-21 15:35:08 +11001398function disable_all_services {
Dean Troyerdff49a22014-01-30 15:37:40 -06001399 ENABLED_SERVICES=""
1400}
1401
1402# Remove all services starting with '-'. For example, to install all default
1403# services except rabbit (rabbit) set in ``localrc``:
1404# ENABLED_SERVICES+=",-rabbit"
1405# Uses global ``ENABLED_SERVICES``
1406# disable_negated_services
Ian Wienandaee18c72014-02-21 15:35:08 +11001407function disable_negated_services {
Dean Troyerdff49a22014-01-30 15:37:40 -06001408 local tmpsvcs="${ENABLED_SERVICES}"
1409 local service
1410 for service in ${tmpsvcs//,/ }; do
1411 if [[ ${service} == -* ]]; then
1412 tmpsvcs=$(echo ${tmpsvcs}|sed -r "s/(,)?(-)?${service#-}(,)?/,/g")
1413 fi
1414 done
1415 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1416}
1417
1418# disable_service() removes the services passed as argument to the
1419# ``ENABLED_SERVICES`` list, if they are present.
1420#
1421# For example:
1422# disable_service rabbit
1423#
1424# This function does not know about the special cases
1425# for nova, glance, and neutron built into is_service_enabled().
1426# Uses global ``ENABLED_SERVICES``
1427# disable_service service [service ...]
Ian Wienandaee18c72014-02-21 15:35:08 +11001428function disable_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001429 local tmpsvcs=",${ENABLED_SERVICES},"
1430 local service
1431 for service in $@; do
1432 if is_service_enabled $service; then
1433 tmpsvcs=${tmpsvcs//,$service,/,}
1434 fi
1435 done
1436 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1437}
1438
1439# enable_service() adds the services passed as argument to the
1440# ``ENABLED_SERVICES`` list, if they are not already present.
1441#
1442# For example:
1443# enable_service qpid
1444#
1445# This function does not know about the special cases
1446# for nova, glance, and neutron built into is_service_enabled().
1447# Uses global ``ENABLED_SERVICES``
1448# enable_service service [service ...]
Ian Wienandaee18c72014-02-21 15:35:08 +11001449function enable_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001450 local tmpsvcs="${ENABLED_SERVICES}"
1451 for service in $@; do
1452 if ! is_service_enabled $service; then
1453 tmpsvcs+=",$service"
1454 fi
1455 done
1456 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
1457 disable_negated_services
1458}
1459
1460# is_service_enabled() checks if the service(s) specified as arguments are
1461# enabled by the user in ``ENABLED_SERVICES``.
1462#
1463# Multiple services specified as arguments are ``OR``'ed together; the test
1464# is a short-circuit boolean, i.e it returns on the first match.
1465#
1466# There are special cases for some 'catch-all' services::
1467# **nova** returns true if any service enabled start with **n-**
1468# **cinder** returns true if any service enabled start with **c-**
1469# **ceilometer** returns true if any service enabled start with **ceilometer**
1470# **glance** returns true if any service enabled start with **g-**
1471# **neutron** returns true if any service enabled start with **q-**
1472# **swift** returns true if any service enabled start with **s-**
1473# **trove** returns true if any service enabled start with **tr-**
1474# For backward compatibility if we have **swift** in ENABLED_SERVICES all the
1475# **s-** services will be enabled. This will be deprecated in the future.
1476#
1477# Cells within nova is enabled if **n-cell** is in ``ENABLED_SERVICES``.
1478# We also need to make sure to treat **n-cell-region** and **n-cell-child**
1479# as enabled in this case.
1480#
1481# Uses global ``ENABLED_SERVICES``
1482# is_service_enabled service [service ...]
Ian Wienandaee18c72014-02-21 15:35:08 +11001483function is_service_enabled {
Sean Dague45917cc2014-02-24 16:09:14 -05001484 local xtrace=$(set +o | grep xtrace)
1485 set +o xtrace
1486 local enabled=1
Dean Troyerdff49a22014-01-30 15:37:40 -06001487 services=$@
1488 for service in ${services}; do
Sean Dague45917cc2014-02-24 16:09:14 -05001489 [[ ,${ENABLED_SERVICES}, =~ ,${service}, ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001490
1491 # Look for top-level 'enabled' function for this service
1492 if type is_${service}_enabled >/dev/null 2>&1; then
1493 # A function exists for this service, use it
1494 is_${service}_enabled
Sean Dague45917cc2014-02-24 16:09:14 -05001495 enabled=$?
Dean Troyerdff49a22014-01-30 15:37:40 -06001496 fi
1497
1498 # TODO(dtroyer): Remove these legacy special-cases after the is_XXX_enabled()
1499 # are implemented
1500
Sean Dague45917cc2014-02-24 16:09:14 -05001501 [[ ${service} == n-cell-* && ${ENABLED_SERVICES} =~ "n-cell" ]] && enabled=0
1502 [[ ${service} == "nova" && ${ENABLED_SERVICES} =~ "n-" ]] && enabled=0
1503 [[ ${service} == "cinder" && ${ENABLED_SERVICES} =~ "c-" ]] && enabled=0
1504 [[ ${service} == "ceilometer" && ${ENABLED_SERVICES} =~ "ceilometer-" ]] && enabled=0
1505 [[ ${service} == "glance" && ${ENABLED_SERVICES} =~ "g-" ]] && enabled=0
1506 [[ ${service} == "ironic" && ${ENABLED_SERVICES} =~ "ir-" ]] && enabled=0
1507 [[ ${service} == "neutron" && ${ENABLED_SERVICES} =~ "q-" ]] && enabled=0
1508 [[ ${service} == "trove" && ${ENABLED_SERVICES} =~ "tr-" ]] && enabled=0
1509 [[ ${service} == "swift" && ${ENABLED_SERVICES} =~ "s-" ]] && enabled=0
1510 [[ ${service} == s-* && ${ENABLED_SERVICES} =~ "swift" ]] && enabled=0
Dean Troyerdff49a22014-01-30 15:37:40 -06001511 done
Sean Dague45917cc2014-02-24 16:09:14 -05001512 $xtrace
1513 return $enabled
Dean Troyerdff49a22014-01-30 15:37:40 -06001514}
1515
1516# Toggle enable/disable_service for services that must run exclusive of each other
1517# $1 The name of a variable containing a space-separated list of services
1518# $2 The name of a variable in which to store the enabled service's name
1519# $3 The name of the service to enable
1520function use_exclusive_service {
1521 local options=${!1}
1522 local selection=$3
1523 out=$2
1524 [ -z $selection ] || [[ ! "$options" =~ "$selection" ]] && return 1
1525 for opt in $options;do
1526 [[ "$opt" = "$selection" ]] && enable_service $opt || disable_service $opt
1527 done
1528 eval "$out=$selection"
1529 return 0
1530}
1531
1532
Masayuki Igawaf6368d32014-02-20 13:31:26 +09001533# System Functions
1534# ================
Dean Troyerdff49a22014-01-30 15:37:40 -06001535
1536# Only run the command if the target file (the last arg) is not on an
1537# NFS filesystem.
Ian Wienandaee18c72014-02-21 15:35:08 +11001538function _safe_permission_operation {
Sean Dague45917cc2014-02-24 16:09:14 -05001539 local xtrace=$(set +o | grep xtrace)
1540 set +o xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001541 local args=( $@ )
1542 local last
1543 local sudo_cmd
1544 local dir_to_check
1545
1546 let last="${#args[*]} - 1"
1547
1548 dir_to_check=${args[$last]}
1549 if [ ! -d "$dir_to_check" ]; then
1550 dir_to_check=`dirname "$dir_to_check"`
1551 fi
1552
1553 if is_nfs_directory "$dir_to_check" ; then
Sean Dague45917cc2014-02-24 16:09:14 -05001554 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001555 return 0
1556 fi
1557
1558 if [[ $TRACK_DEPENDS = True ]]; then
1559 sudo_cmd="env"
1560 else
1561 sudo_cmd="sudo"
1562 fi
1563
Sean Dague45917cc2014-02-24 16:09:14 -05001564 $xtrace
Dean Troyerdff49a22014-01-30 15:37:40 -06001565 $sudo_cmd $@
1566}
1567
1568# Exit 0 if address is in network or 1 if address is not in network
1569# ip-range is in CIDR notation: 1.2.3.4/20
1570# address_in_net ip-address ip-range
Ian Wienandaee18c72014-02-21 15:35:08 +11001571function address_in_net {
Dean Troyerdff49a22014-01-30 15:37:40 -06001572 local ip=$1
1573 local range=$2
1574 local masklen=${range#*/}
1575 local network=$(maskip ${range%/*} $(cidr2netmask $masklen))
1576 local subnet=$(maskip $ip $(cidr2netmask $masklen))
1577 [[ $network == $subnet ]]
1578}
1579
1580# Add a user to a group.
1581# add_user_to_group user group
Ian Wienandaee18c72014-02-21 15:35:08 +11001582function add_user_to_group {
Dean Troyerdff49a22014-01-30 15:37:40 -06001583 local user=$1
1584 local group=$2
1585
1586 if [[ -z "$os_VENDOR" ]]; then
1587 GetOSVersion
1588 fi
1589
1590 # SLE11 and openSUSE 12.2 don't have the usual usermod
1591 if ! is_suse || [[ "$os_VENDOR" = "openSUSE" && "$os_RELEASE" != "12.2" ]]; then
1592 sudo usermod -a -G "$group" "$user"
1593 else
1594 sudo usermod -A "$group" "$user"
1595 fi
1596}
1597
1598# Convert CIDR notation to a IPv4 netmask
1599# cidr2netmask cidr-bits
Ian Wienandaee18c72014-02-21 15:35:08 +11001600function cidr2netmask {
Dean Troyerdff49a22014-01-30 15:37:40 -06001601 local maskpat="255 255 255 255"
1602 local maskdgt="254 252 248 240 224 192 128"
1603 set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3}
1604 echo ${1-0}.${2-0}.${3-0}.${4-0}
1605}
1606
1607# Gracefully cp only if source file/dir exists
1608# cp_it source destination
1609function cp_it {
1610 if [ -e $1 ] || [ -d $1 ]; then
1611 cp -pRL $1 $2
1612 fi
1613}
1614
1615# HTTP and HTTPS proxy servers are supported via the usual environment variables [1]
1616# ``http_proxy``, ``https_proxy`` and ``no_proxy``. They can be set in
1617# ``localrc`` or on the command line if necessary::
1618#
1619# [1] http://www.w3.org/Daemon/User/Proxies/ProxyClients.html
1620#
1621# http_proxy=http://proxy.example.com:3128/ no_proxy=repo.example.net ./stack.sh
1622
Ian Wienandaee18c72014-02-21 15:35:08 +11001623function export_proxy_variables {
Dean Troyerdff49a22014-01-30 15:37:40 -06001624 if [[ -n "$http_proxy" ]]; then
1625 export http_proxy=$http_proxy
1626 fi
1627 if [[ -n "$https_proxy" ]]; then
1628 export https_proxy=$https_proxy
1629 fi
1630 if [[ -n "$no_proxy" ]]; then
1631 export no_proxy=$no_proxy
1632 fi
1633}
1634
1635# Returns true if the directory is on a filesystem mounted via NFS.
Ian Wienandaee18c72014-02-21 15:35:08 +11001636function is_nfs_directory {
Dean Troyerdff49a22014-01-30 15:37:40 -06001637 local mount_type=`stat -f -L -c %T $1`
1638 test "$mount_type" == "nfs"
1639}
1640
1641# Return the network portion of the given IP address using netmask
1642# netmask is in the traditional dotted-quad format
1643# maskip ip-address netmask
Ian Wienandaee18c72014-02-21 15:35:08 +11001644function maskip {
Dean Troyerdff49a22014-01-30 15:37:40 -06001645 local ip=$1
1646 local mask=$2
1647 local l="${ip%.*}"; local r="${ip#*.}"; local n="${mask%.*}"; local m="${mask#*.}"
1648 local subnet=$((${ip%%.*}&${mask%%.*})).$((${r%%.*}&${m%%.*})).$((${l##*.}&${n##*.})).$((${ip##*.}&${mask##*.}))
1649 echo $subnet
1650}
1651
1652# Service wrapper to restart services
1653# restart_service service-name
Ian Wienandaee18c72014-02-21 15:35:08 +11001654function restart_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001655 if is_ubuntu; then
1656 sudo /usr/sbin/service $1 restart
1657 else
1658 sudo /sbin/service $1 restart
1659 fi
1660}
1661
1662# Only change permissions of a file or directory if it is not on an
1663# NFS filesystem.
Ian Wienandaee18c72014-02-21 15:35:08 +11001664function safe_chmod {
Dean Troyerdff49a22014-01-30 15:37:40 -06001665 _safe_permission_operation chmod $@
1666}
1667
1668# Only change ownership of a file or directory if it is not on an NFS
1669# filesystem.
Ian Wienandaee18c72014-02-21 15:35:08 +11001670function safe_chown {
Dean Troyerdff49a22014-01-30 15:37:40 -06001671 _safe_permission_operation chown $@
1672}
1673
1674# Service wrapper to start services
1675# start_service service-name
Ian Wienandaee18c72014-02-21 15:35:08 +11001676function start_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001677 if is_ubuntu; then
1678 sudo /usr/sbin/service $1 start
1679 else
1680 sudo /sbin/service $1 start
1681 fi
1682}
1683
1684# Service wrapper to stop services
1685# stop_service service-name
Ian Wienandaee18c72014-02-21 15:35:08 +11001686function stop_service {
Dean Troyerdff49a22014-01-30 15:37:40 -06001687 if is_ubuntu; then
1688 sudo /usr/sbin/service $1 stop
1689 else
1690 sudo /sbin/service $1 stop
1691 fi
1692}
1693
1694
1695# Restore xtrace
1696$XTRACE
1697
1698# Local variables:
1699# mode: shell-script
1700# End: