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