blob: 087a0ea8440cdb19520cbc07d65ab9ea7cb7d7ed [file] [log] [blame]
Dean Troyer7f9aa712012-01-31 12:11:56 -06001# functions - Common functions used by DevStack components
Dean Troyer13dc5cc2012-03-27 14:50:45 -05002#
Dean Troyer4a43b7b2012-08-28 17:43:40 -05003# The following variables are assumed to be defined by certain functions:
Dean Troyer4a43b7b2012-08-28 17:43:40 -05004# ``ENABLED_SERVICES``
5# ``EROR_ON_CLONE``
6# ``FILES``
7# ``GLANCE_HOSTPORT``
8# ``OFFLINE``
9# ``PIP_DOWNLOAD_CACHE``
Maru Newby3a87edd2012-10-25 23:01:06 +000010# ``PIP_USE_MIRRORS``
Dean Troyer4a43b7b2012-08-28 17:43:40 -050011# ``RECLONE``
12# ``TRACK_DEPENDS``
13# ``http_proxy``, ``https_proxy``, ``no_proxy``
Dean Troyer13dc5cc2012-03-27 14:50:45 -050014
Dean Troyer7f9aa712012-01-31 12:11:56 -060015
Dean Troyer27e32692012-03-16 16:16:56 -050016# Save trace setting
17XTRACE=$(set +o | grep xtrace)
18set +o xtrace
19
Dean Troyer7f9aa712012-01-31 12:11:56 -060020
Dean Troyerd4f69b22013-07-24 12:24:43 -050021# Convert CIDR notation to a IPv4 netmask
22# cidr2netmask cidr-bits
23function cidr2netmask() {
24 local maskpat="255 255 255 255"
25 local maskdgt="254 252 248 240 224 192 128"
26 set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3}
27 echo ${1-0}.${2-0}.${3-0}.${4-0}
28}
29
30
31# Return the network portion of the given IP address using netmask
32# netmask is in the traditional dotted-quad format
33# maskip ip-address netmask
34function maskip() {
35 local ip=$1
36 local mask=$2
37 local l="${ip%.*}"; local r="${ip#*.}"; local n="${mask%.*}"; local m="${mask#*.}"
38 local subnet=$((${ip%%.*}&${mask%%.*})).$((${r%%.*}&${m%%.*})).$((${l##*.}&${n##*.})).$((${ip##*.}&${mask##*.}))
39 echo $subnet
40}
41
42
43# Exit 0 if address is in network or 1 if address is not in network
44# ip-range is in CIDR notation: 1.2.3.4/20
Dean Troyer4a43b7b2012-08-28 17:43:40 -050045# address_in_net ip-address ip-range
Vishvananda Ishayac9ad14b2012-07-03 20:29:01 +000046function address_in_net() {
Dean Troyerd4f69b22013-07-24 12:24:43 -050047 local ip=$1
48 local range=$2
49 local masklen=${range#*/}
50 local network=$(maskip ${range%/*} $(cidr2netmask $masklen))
51 local subnet=$(maskip $ip $(cidr2netmask $masklen))
52 [[ $network == $subnet ]]
Vishvananda Ishayac9ad14b2012-07-03 20:29:01 +000053}
54
55
Dean Troyer4a43b7b2012-08-28 17:43:40 -050056# Wrapper for ``apt-get`` to set cache and proxy environment variables
57# Uses globals ``OFFLINE``, ``*_proxy`
Dean Troyer13dc5cc2012-03-27 14:50:45 -050058# apt_get operation package [package ...]
Dean Troyer7f9aa712012-01-31 12:11:56 -060059function apt_get() {
Dean Troyerd0b21e22012-03-07 14:52:25 -060060 [[ "$OFFLINE" = "True" || -z "$@" ]] && return
Dean Troyer7f9aa712012-01-31 12:11:56 -060061 local sudo="sudo"
62 [[ "$(id -u)" = "0" ]] && sudo="env"
63 $sudo DEBIAN_FRONTEND=noninteractive \
64 http_proxy=$http_proxy https_proxy=$https_proxy \
Osamu Habuka7abe4f22012-07-25 12:39:32 +090065 no_proxy=$no_proxy \
Dean Troyer7f9aa712012-01-31 12:11:56 -060066 apt-get --option "Dpkg::Options::=--force-confold" --assume-yes "$@"
67}
68
69
70# Gracefully cp only if source file/dir exists
71# cp_it source destination
72function cp_it {
73 if [ -e $1 ] || [ -d $1 ]; then
74 cp -pRL $1 $2
75 fi
76}
77
78
Kui Shi5e28a3e2013-08-02 17:26:28 +080079# Prints backtrace info
80# filename:lineno:function
81function backtrace {
82 local level=$1
83 local deep=$((${#BASH_SOURCE[@]} - 1))
84 echo "[Call Trace]"
85 while [ $level -le $deep ]; do
86 echo "${BASH_SOURCE[$deep]}:${BASH_LINENO[$deep-1]}:${FUNCNAME[$deep-1]}"
87 deep=$((deep - 1))
88 done
89}
90
91
Dean Troyerac93efb2013-03-13 14:30:54 -050092# Prints line number and "message" then exits
93# die $LINENO "message"
Dean Troyer27e32692012-03-16 16:16:56 -050094function die() {
Dean Troyer489bd2a2012-03-02 10:44:29 -060095 local exitcode=$?
Dean Troyer896eb662013-04-05 15:02:01 -050096 set +o xtrace
97 local line=$1; shift
Nachi Ueno07115eb2013-02-26 12:38:18 -080098 if [ $exitcode == 0 ]; then
99 exitcode=1
100 fi
Kui Shi5e28a3e2013-08-02 17:26:28 +0800101 backtrace 2
Dean Troyer896eb662013-04-05 15:02:01 -0500102 err $line "$*"
Dean Troyer27e32692012-03-16 16:16:56 -0500103 exit $exitcode
Dean Troyer489bd2a2012-03-02 10:44:29 -0600104}
105
106
107# Checks an environment variable is not set or has length 0 OR if the
108# exit code is non-zero and prints "message" and exits
109# NOTE: env-var is the variable name without a '$'
Dean Troyerac93efb2013-03-13 14:30:54 -0500110# die_if_not_set $LINENO env-var "message"
Dean Troyer489bd2a2012-03-02 10:44:29 -0600111function die_if_not_set() {
Dean Troyer896eb662013-04-05 15:02:01 -0500112 local exitcode=$?
113 FXTRACE=$(set +o | grep xtrace)
114 set +o xtrace
115 local line=$1; shift
116 local evar=$1; shift
117 if ! is_set $evar || [ $exitcode != 0 ]; then
118 die $line "$*"
119 fi
120 $FXTRACE
121}
122
123
124# Prints line number and "message" in error format
125# err $LINENO "message"
126function err() {
127 local exitcode=$?
128 errXTRACE=$(set +o | grep xtrace)
129 set +o xtrace
Kui Shi17df0772013-08-02 17:55:41 +0800130 local msg="[ERROR] ${BASH_SOURCE[2]}:$1 $2"
Dean Troyer896eb662013-04-05 15:02:01 -0500131 echo $msg 1>&2;
132 if [[ -n ${SCREEN_LOGDIR} ]]; then
133 echo $msg >> "${SCREEN_LOGDIR}/error.log"
134 fi
135 $errXTRACE
136 return $exitcode
137}
138
139
140# Checks an environment variable is not set or has length 0 OR if the
141# exit code is non-zero and prints "message"
142# NOTE: env-var is the variable name without a '$'
143# err_if_not_set $LINENO env-var "message"
144function err_if_not_set() {
145 local exitcode=$?
146 errinsXTRACE=$(set +o | grep xtrace)
147 set +o xtrace
148 local line=$1; shift
149 local evar=$1; shift
150 if ! is_set $evar || [ $exitcode != 0 ]; then
151 err $line "$*"
152 fi
153 $errinsXTRACE
154 return $exitcode
Dean Troyer489bd2a2012-03-02 10:44:29 -0600155}
156
157
Dean Troyer48352ee2012-12-12 12:50:38 -0600158# HTTP and HTTPS proxy servers are supported via the usual environment variables [1]
159# ``http_proxy``, ``https_proxy`` and ``no_proxy``. They can be set in
160# ``localrc`` or on the command line if necessary::
161#
162# [1] http://www.w3.org/Daemon/User/Proxies/ProxyClients.html
163#
164# http_proxy=http://proxy.example.com:3128/ no_proxy=repo.example.net ./stack.sh
165
166function export_proxy_variables() {
167 if [[ -n "$http_proxy" ]]; then
168 export http_proxy=$http_proxy
169 fi
170 if [[ -n "$https_proxy" ]]; then
171 export https_proxy=$https_proxy
172 fi
173 if [[ -n "$no_proxy" ]]; then
174 export no_proxy=$no_proxy
175 fi
176}
177
178
Dean Troyer489bd2a2012-03-02 10:44:29 -0600179# Grab a numbered field from python prettytable output
180# Fields are numbered starting with 1
181# Reverse syntax is supported: -1 is the last field, -2 is second to last, etc.
182# get_field field-number
183function get_field() {
184 while read data; do
185 if [ "$1" -lt 0 ]; then
186 field="(\$(NF$1))"
187 else
188 field="\$$(($1 + 1))"
189 fi
190 echo "$data" | awk -F'[ \t]*\\|[ \t]*' "{print $field}"
191 done
192}
193
194
Dean Troyerc892bde2013-03-13 14:06:13 -0500195# Get the default value for HOST_IP
196# get_default_host_ip fixed_range floating_range host_ip_iface host_ip
197function get_default_host_ip() {
198 local fixed_range=$1
199 local floating_range=$2
200 local host_ip_iface=$3
201 local host_ip=$4
202
203 # Find the interface used for the default route
204 host_ip_iface=${host_ip_iface:-$(ip route | sed -n '/^default/{ s/.*dev \(\w\+\)\s\+.*/\1/; p; }' | head -1)}
205 # Search for an IP unless an explicit is set by ``HOST_IP`` environment variable
206 if [ -z "$host_ip" -o "$host_ip" == "dhcp" ]; then
207 host_ip=""
208 host_ips=`LC_ALL=C ip -f inet addr show ${host_ip_iface} | awk '/inet/ {split($2,parts,"/"); print parts[1]}'`
209 for IP in $host_ips; do
210 # Attempt to filter out IP addresses that are part of the fixed and
211 # floating range. Note that this method only works if the ``netaddr``
212 # python library is installed. If it is not installed, an error
213 # will be printed and the first IP from the interface will be used.
214 # If that is not correct set ``HOST_IP`` in ``localrc`` to the correct
215 # address.
216 if ! (address_in_net $IP $fixed_range || address_in_net $IP $floating_range); then
217 host_ip=$IP
218 break;
219 fi
220 done
221 fi
222 echo $host_ip
223}
224
225
Isaku Yamahata8c438092013-02-12 22:30:56 +0900226function _get_package_dir() {
227 local pkg_dir
228 if is_ubuntu; then
229 pkg_dir=$FILES/apts
230 elif is_fedora; then
231 pkg_dir=$FILES/rpms
232 elif is_suse; then
233 pkg_dir=$FILES/rpms-suse
234 else
235 exit_distro_not_supported "list of packages"
236 fi
237 echo "$pkg_dir"
238}
239
Dean Troyer1a6d4492013-06-03 16:47:36 -0500240
Dean Troyer7e270512012-06-14 15:23:24 -0500241# get_packages() collects a list of package names of any type from the
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500242# prerequisite files in ``files/{apts|rpms}``. The list is intended
243# to be passed to a package installer such as apt or yum.
Dean Troyer7e270512012-06-14 15:23:24 -0500244#
Isaku Yamahata8c438092013-02-12 22:30:56 +0900245# Only packages required for the services in 1st argument will be
Dean Troyer7e270512012-06-14 15:23:24 -0500246# included. Two bits of metadata are recognized in the prerequisite files:
247# - ``# NOPRIME`` defers installation to be performed later in stack.sh
248# - ``# dist:DISTRO`` or ``dist:DISTRO1,DISTRO2`` limits the selection
249# of the package to the distros listed. The distro names are case insensitive.
Dean Troyer7e270512012-06-14 15:23:24 -0500250function get_packages() {
Isaku Yamahata8c438092013-02-12 22:30:56 +0900251 local services=$1
252 local package_dir=$(_get_package_dir)
Dean Troyer7e270512012-06-14 15:23:24 -0500253 local file_to_parse
254 local service
255
256 if [[ -z "$package_dir" ]]; then
257 echo "No package directory supplied"
258 return 1
259 fi
260 if [[ -z "$DISTRO" ]]; then
Vincent Untz855c5872012-10-04 13:36:46 +0200261 GetDistro
Dean Troyer7e270512012-06-14 15:23:24 -0500262 fi
Isaku Yamahata8c438092013-02-12 22:30:56 +0900263 for service in general ${services//,/ }; do
Dean Troyer7e270512012-06-14 15:23:24 -0500264 # Allow individual services to specify dependencies
265 if [[ -e ${package_dir}/${service} ]]; then
266 file_to_parse="${file_to_parse} $service"
267 fi
268 # NOTE(sdague) n-api needs glance for now because that's where
269 # glance client is
270 if [[ $service == n-api ]]; then
271 if [[ ! $file_to_parse =~ nova ]]; then
272 file_to_parse="${file_to_parse} nova"
273 fi
274 if [[ ! $file_to_parse =~ glance ]]; then
275 file_to_parse="${file_to_parse} glance"
276 fi
277 elif [[ $service == c-* ]]; then
278 if [[ ! $file_to_parse =~ cinder ]]; then
279 file_to_parse="${file_to_parse} cinder"
280 fi
John H. Tran93361642012-07-26 11:22:05 -0700281 elif [[ $service == ceilometer-* ]]; then
282 if [[ ! $file_to_parse =~ ceilometer ]]; then
283 file_to_parse="${file_to_parse} ceilometer"
284 fi
Chmouel Boudjnah0c3a5582013-03-06 10:58:33 +0100285 elif [[ $service == s-* ]]; then
286 if [[ ! $file_to_parse =~ swift ]]; then
287 file_to_parse="${file_to_parse} swift"
288 fi
Dean Troyer7e270512012-06-14 15:23:24 -0500289 elif [[ $service == n-* ]]; then
290 if [[ ! $file_to_parse =~ nova ]]; then
291 file_to_parse="${file_to_parse} nova"
292 fi
293 elif [[ $service == g-* ]]; then
294 if [[ ! $file_to_parse =~ glance ]]; then
295 file_to_parse="${file_to_parse} glance"
296 fi
297 elif [[ $service == key* ]]; then
298 if [[ ! $file_to_parse =~ keystone ]]; then
299 file_to_parse="${file_to_parse} keystone"
300 fi
Robert Collins0a9954f2012-11-20 11:34:25 +1300301 elif [[ $service == q-* ]]; then
Mark McClainb05c8762013-07-06 23:29:39 -0400302 if [[ ! $file_to_parse =~ neutron ]]; then
303 file_to_parse="${file_to_parse} neutron"
Robert Collins0a9954f2012-11-20 11:34:25 +1300304 fi
Dean Troyer7e270512012-06-14 15:23:24 -0500305 fi
306 done
307
308 for file in ${file_to_parse}; do
309 local fname=${package_dir}/${file}
310 local OIFS line package distros distro
311 [[ -e $fname ]] || continue
312
313 OIFS=$IFS
314 IFS=$'\n'
315 for line in $(<${fname}); do
316 if [[ $line =~ "NOPRIME" ]]; then
317 continue
318 fi
319
320 if [[ $line =~ (.*)#.*dist:([^ ]*) ]]; then
321 # We are using BASH regexp matching feature.
322 package=${BASH_REMATCH[1]}
323 distros=${BASH_REMATCH[2]}
324 # In bash ${VAR,,} will lowecase VAR
325 [[ ${distros,,} =~ ${DISTRO,,} ]] && echo $package
326 continue
327 fi
328
329 echo ${line%#*}
330 done
331 IFS=$OIFS
332 done
333}
334
335
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500336# Determine OS Vendor, Release and Update
337# Tested with OS/X, Ubuntu, RedHat, CentOS, Fedora
338# Returns results in global variables:
339# os_VENDOR - vendor name
340# os_RELEASE - release
341# os_UPDATE - update
342# os_PACKAGE - package type
343# os_CODENAME - vendor's codename for release
344# GetOSVersion
345GetOSVersion() {
346 # Figure out which vendor we are
347 if [[ -n "`which sw_vers 2>/dev/null`" ]]; then
348 # OS/X
349 os_VENDOR=`sw_vers -productName`
350 os_RELEASE=`sw_vers -productVersion`
351 os_UPDATE=${os_RELEASE##*.}
352 os_RELEASE=${os_RELEASE%.*}
353 os_PACKAGE=""
354 if [[ "$os_RELEASE" =~ "10.7" ]]; then
355 os_CODENAME="lion"
356 elif [[ "$os_RELEASE" =~ "10.6" ]]; then
357 os_CODENAME="snow leopard"
358 elif [[ "$os_RELEASE" =~ "10.5" ]]; then
359 os_CODENAME="leopard"
360 elif [[ "$os_RELEASE" =~ "10.4" ]]; then
361 os_CODENAME="tiger"
362 elif [[ "$os_RELEASE" =~ "10.3" ]]; then
363 os_CODENAME="panther"
364 else
365 os_CODENAME=""
366 fi
367 elif [[ -x $(which lsb_release 2>/dev/null) ]]; then
368 os_VENDOR=$(lsb_release -i -s)
369 os_RELEASE=$(lsb_release -r -s)
370 os_UPDATE=""
Attila Fazekasaf988fd2013-01-13 14:20:47 +0100371 os_PACKAGE="rpm"
Derek Morton4a8496e2013-04-08 23:46:08 -0500372 if [[ "Debian,Ubuntu,LinuxMint" =~ $os_VENDOR ]]; then
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500373 os_PACKAGE="deb"
Vincent Untz856a11e2012-11-21 16:04:12 +0100374 elif [[ "SUSE LINUX" =~ $os_VENDOR ]]; then
375 lsb_release -d -s | grep -q openSUSE
376 if [[ $? -eq 0 ]]; then
377 os_VENDOR="openSUSE"
378 fi
Vincent Untzcd1fe982013-03-12 18:04:29 +0100379 elif [[ $os_VENDOR == "openSUSE project" ]]; then
380 os_VENDOR="openSUSE"
Attila Fazekasaf988fd2013-01-13 14:20:47 +0100381 elif [[ $os_VENDOR =~ Red.*Hat ]]; then
382 os_VENDOR="Red Hat"
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500383 fi
384 os_CODENAME=$(lsb_release -c -s)
385 elif [[ -r /etc/redhat-release ]]; then
386 # Red Hat Enterprise Linux Server release 5.5 (Tikanga)
387 # CentOS release 5.5 (Final)
388 # CentOS Linux release 6.0 (Final)
389 # Fedora release 16 (Verne)
390 os_CODENAME=""
391 for r in "Red Hat" CentOS Fedora; do
392 os_VENDOR=$r
393 if [[ -n "`grep \"$r\" /etc/redhat-release`" ]]; then
394 ver=`sed -e 's/^.* \(.*\) (\(.*\)).*$/\1\|\2/' /etc/redhat-release`
395 os_CODENAME=${ver#*|}
396 os_RELEASE=${ver%|*}
397 os_UPDATE=${os_RELEASE##*.}
398 os_RELEASE=${os_RELEASE%.*}
399 break
400 fi
401 os_VENDOR=""
402 done
403 os_PACKAGE="rpm"
Vincent Untz856a11e2012-11-21 16:04:12 +0100404 elif [[ -r /etc/SuSE-release ]]; then
405 for r in openSUSE "SUSE Linux"; do
406 if [[ "$r" = "SUSE Linux" ]]; then
407 os_VENDOR="SUSE LINUX"
408 else
409 os_VENDOR=$r
410 fi
411
412 if [[ -n "`grep \"$r\" /etc/SuSE-release`" ]]; then
413 os_CODENAME=`grep "CODENAME = " /etc/SuSE-release | sed 's:.* = ::g'`
414 os_RELEASE=`grep "VERSION = " /etc/SuSE-release | sed 's:.* = ::g'`
415 os_UPDATE=`grep "PATCHLEVEL = " /etc/SuSE-release | sed 's:.* = ::g'`
416 break
417 fi
418 os_VENDOR=""
419 done
420 os_PACKAGE="rpm"
Émilien Macchib2ef8902013-05-04 00:48:20 +0200421 # If lsb_release is not installed, we should be able to detect Debian OS
422 elif [[ -f /etc/debian_version ]] && [[ $(cat /proc/version) =~ "Debian" ]]; then
423 os_VENDOR="Debian"
424 os_PACKAGE="deb"
425 os_CODENAME=$(awk '/VERSION=/' /etc/os-release | sed 's/VERSION=//' | sed -r 's/\"|\(|\)//g' | awk '{print $2}')
426 os_RELEASE=$(awk '/VERSION_ID=/' /etc/os-release | sed 's/VERSION_ID=//' | sed 's/\"//g')
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500427 fi
428 export os_VENDOR os_RELEASE os_UPDATE os_PACKAGE os_CODENAME
429}
430
Andrew Laskif900bd72012-09-05 17:23:14 -0400431
Dean Troyera9e0a482012-07-09 14:07:23 -0500432# Translate the OS version values into common nomenclature
433# Sets ``DISTRO`` from the ``os_*`` values
434function GetDistro() {
435 GetOSVersion
Émilien Macchib2ef8902013-05-04 00:48:20 +0200436 if [[ "$os_VENDOR" =~ (Ubuntu) || "$os_VENDOR" =~ (Debian) ]]; then
437 # 'Everyone' refers to Ubuntu / Debian releases by the code name adjective
Dean Troyera9e0a482012-07-09 14:07:23 -0500438 DISTRO=$os_CODENAME
439 elif [[ "$os_VENDOR" =~ (Fedora) ]]; then
440 # For Fedora, just use 'f' and the release
441 DISTRO="f$os_RELEASE"
Vincent Untz856a11e2012-11-21 16:04:12 +0100442 elif [[ "$os_VENDOR" =~ (openSUSE) ]]; then
443 DISTRO="opensuse-$os_RELEASE"
444 elif [[ "$os_VENDOR" =~ (SUSE LINUX) ]]; then
445 # For SLE, also use the service pack
446 if [[ -z "$os_UPDATE" ]]; then
447 DISTRO="sle${os_RELEASE}"
448 else
449 DISTRO="sle${os_RELEASE}sp${os_UPDATE}"
450 fi
Ian Wienandd857f4b2013-03-20 14:51:06 +1100451 elif [[ "$os_VENDOR" =~ (Red Hat) || "$os_VENDOR" =~ (CentOS) ]]; then
452 # Drop the . release as we assume it's compatible
453 DISTRO="rhel${os_RELEASE::1}"
Dean Troyera9e0a482012-07-09 14:07:23 -0500454 else
455 # Catch-all for now is Vendor + Release + Update
456 DISTRO="$os_VENDOR-$os_RELEASE.$os_UPDATE"
457 fi
458 export DISTRO
459}
460
461
Vincent Untz00011c02012-12-06 09:56:32 +0100462# Determine if current distribution is a Fedora-based distribution
Dean Troyer1a6d4492013-06-03 16:47:36 -0500463# (Fedora, RHEL, CentOS, etc).
Vincent Untz00011c02012-12-06 09:56:32 +0100464# is_fedora
465function is_fedora {
466 if [[ -z "$os_VENDOR" ]]; then
467 GetOSVersion
468 fi
469
470 [ "$os_VENDOR" = "Fedora" ] || [ "$os_VENDOR" = "Red Hat" ] || [ "$os_VENDOR" = "CentOS" ]
471}
472
Dean Troyer1a6d4492013-06-03 16:47:36 -0500473
Vincent Untz856a11e2012-11-21 16:04:12 +0100474# Determine if current distribution is a SUSE-based distribution
475# (openSUSE, SLE).
476# is_suse
477function is_suse {
478 if [[ -z "$os_VENDOR" ]]; then
479 GetOSVersion
480 fi
481
Steve Baker1a7bbd22012-12-03 17:04:02 +1300482 [ "$os_VENDOR" = "openSUSE" ] || [ "$os_VENDOR" = "SUSE LINUX" ]
Vincent Untz856a11e2012-11-21 16:04:12 +0100483}
484
485
Dean Troyer1a6d4492013-06-03 16:47:36 -0500486# Determine if current distribution is an Ubuntu-based distribution
487# It will also detect non-Ubuntu but Debian-based distros
488# is_ubuntu
489function is_ubuntu {
490 if [[ -z "$os_PACKAGE" ]]; then
491 GetOSVersion
492 fi
493 [ "$os_PACKAGE" = "deb" ]
494}
495
496
Vincent Untz00011c02012-12-06 09:56:32 +0100497# Exit after outputting a message about the distribution not being supported.
498# exit_distro_not_supported [optional-string-telling-what-is-missing]
499function exit_distro_not_supported {
500 if [[ -z "$DISTRO" ]]; then
501 GetDistro
502 fi
503
504 if [ $# -gt 0 ]; then
Nachi Ueno07115eb2013-02-26 12:38:18 -0800505 die $LINENO "Support for $DISTRO is incomplete: no support for $@"
Vincent Untz00011c02012-12-06 09:56:32 +0100506 else
Nachi Ueno07115eb2013-02-26 12:38:18 -0800507 die $LINENO "Support for $DISTRO is incomplete."
Vincent Untz00011c02012-12-06 09:56:32 +0100508 fi
Vincent Untz00011c02012-12-06 09:56:32 +0100509}
510
Daniel Jonesfa868cb2013-06-18 15:28:01 -0500511# Utility function for checking machine architecture
512# is_arch arch-type
513function is_arch {
514 ARCH_TYPE=$1
515
516 [ "($uname -m)" = "$ARCH_TYPE" ]
517}
Vincent Untz00011c02012-12-06 09:56:32 +0100518
Dean Troyer7f9aa712012-01-31 12:11:56 -0600519# git clone only if directory doesn't exist already. Since ``DEST`` might not
520# be owned by the installation user, we create the directory and change the
521# ownership to the proper user.
522# Set global RECLONE=yes to simulate a clone when dest-dir exists
James E. Blair94cb9602012-06-22 15:28:29 -0700523# Set global ERROR_ON_CLONE=True to abort execution with an error if the git repo
524# does not exist (default is False, meaning the repo will be cloned).
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500525# Uses global ``OFFLINE``
Dean Troyer7f9aa712012-01-31 12:11:56 -0600526# git_clone remote dest-dir branch
527function git_clone {
528 [[ "$OFFLINE" = "True" ]] && return
529
530 GIT_REMOTE=$1
531 GIT_DEST=$2
Evgeniy Afonichev6a3912d2012-07-10 14:02:43 +0300532 GIT_REF=$3
Dean Troyer7f9aa712012-01-31 12:11:56 -0600533
Evgeniy Afonichev6a3912d2012-07-10 14:02:43 +0300534 if echo $GIT_REF | egrep -q "^refs"; then
Dean Troyer7f9aa712012-01-31 12:11:56 -0600535 # If our branch name is a gerrit style refs/changes/...
536 if [[ ! -d $GIT_DEST ]]; then
James E. Blair94cb9602012-06-22 15:28:29 -0700537 [[ "$ERROR_ON_CLONE" = "True" ]] && exit 1
Dean Troyer7f9aa712012-01-31 12:11:56 -0600538 git clone $GIT_REMOTE $GIT_DEST
539 fi
540 cd $GIT_DEST
Evgeniy Afonichev6a3912d2012-07-10 14:02:43 +0300541 git fetch $GIT_REMOTE $GIT_REF && git checkout FETCH_HEAD
Dean Troyer7f9aa712012-01-31 12:11:56 -0600542 else
543 # do a full clone only if the directory doesn't exist
544 if [[ ! -d $GIT_DEST ]]; then
James E. Blair94cb9602012-06-22 15:28:29 -0700545 [[ "$ERROR_ON_CLONE" = "True" ]] && exit 1
Dean Troyer7f9aa712012-01-31 12:11:56 -0600546 git clone $GIT_REMOTE $GIT_DEST
547 cd $GIT_DEST
548 # This checkout syntax works for both branches and tags
Evgeniy Afonichev6a3912d2012-07-10 14:02:43 +0300549 git checkout $GIT_REF
Dean Troyer7f9aa712012-01-31 12:11:56 -0600550 elif [[ "$RECLONE" == "yes" ]]; then
551 # if it does exist then simulate what clone does if asked to RECLONE
552 cd $GIT_DEST
553 # set the url to pull from and fetch
554 git remote set-url origin $GIT_REMOTE
555 git fetch origin
556 # remove the existing ignored files (like pyc) as they cause breakage
557 # (due to the py files having older timestamps than our pyc, so python
558 # thinks the pyc files are correct using them)
559 find $GIT_DEST -name '*.pyc' -delete
Evgeniy Afonichev6a3912d2012-07-10 14:02:43 +0300560
561 # handle GIT_REF accordingly to type (tag, branch)
562 if [[ -n "`git show-ref refs/tags/$GIT_REF`" ]]; then
563 git_update_tag $GIT_REF
564 elif [[ -n "`git show-ref refs/heads/$GIT_REF`" ]]; then
565 git_update_branch $GIT_REF
Andrew Laskif900bd72012-09-05 17:23:14 -0400566 elif [[ -n "`git show-ref refs/remotes/origin/$GIT_REF`" ]]; then
567 git_update_remote_branch $GIT_REF
Evgeniy Afonichev6a3912d2012-07-10 14:02:43 +0300568 else
569 echo $GIT_REF is neither branch nor tag
570 exit 1
571 fi
572
Dean Troyer7f9aa712012-01-31 12:11:56 -0600573 fi
574 fi
575}
576
577
Dean Troyer1a6d4492013-06-03 16:47:36 -0500578# git update using reference as a branch.
579# git_update_branch ref
580function git_update_branch() {
581
582 GIT_BRANCH=$1
583
584 git checkout -f origin/$GIT_BRANCH
585 # a local branch might not exist
586 git branch -D $GIT_BRANCH || true
587 git checkout -b $GIT_BRANCH
588}
589
590
591# git update using reference as a branch.
592# git_update_remote_branch ref
593function git_update_remote_branch() {
594
595 GIT_BRANCH=$1
596
597 git checkout -b $GIT_BRANCH -t origin/$GIT_BRANCH
598}
599
600
601# git update using reference as a tag. Be careful editing source at that repo
602# as working copy will be in a detached mode
603# git_update_tag ref
604function git_update_tag() {
605
606 GIT_TAG=$1
607
608 git tag -d $GIT_TAG
609 # fetching given tag only
610 git fetch origin tag $GIT_TAG
611 git checkout -f $GIT_TAG
612}
613
614
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500615# Comment an option in an INI file
Chmouel Boudjnahc7214e82012-06-06 13:56:39 +0200616# inicomment config-file section option
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500617function inicomment() {
618 local file=$1
619 local section=$2
620 local option=$3
Attila Fazekas588eb412012-12-20 10:57:16 +0100621 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|^\($option[ \t]*=.*$\)|#\1|" "$file"
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500622}
623
Dean Troyer896eb662013-04-05 15:02:01 -0500624
Chmouel Boudjnahc7214e82012-06-06 13:56:39 +0200625# Uncomment an option in an INI file
626# iniuncomment config-file section option
627function iniuncomment() {
628 local file=$1
629 local section=$2
630 local option=$3
Attila Fazekas588eb412012-12-20 10:57:16 +0100631 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|[^ \t]*#[ \t]*\($option[ \t]*=.*$\)|\1|" "$file"
Chmouel Boudjnahc7214e82012-06-06 13:56:39 +0200632}
633
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500634
635# Get an option from an INI file
Dean Troyer09e636e2012-03-19 16:31:12 -0500636# iniget config-file section option
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500637function iniget() {
638 local file=$1
639 local section=$2
640 local option=$3
641 local line
Attila Fazekas588eb412012-12-20 10:57:16 +0100642 line=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ p; }" "$file")
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500643 echo ${line#*=}
644}
645
Dean Troyer896eb662013-04-05 15:02:01 -0500646
Attila Fazekas588eb412012-12-20 10:57:16 +0100647# Determinate is the given option present in the INI file
648# ini_has_option config-file section option
649function ini_has_option() {
650 local file=$1
651 local section=$2
652 local option=$3
653 local line
654 line=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ p; }" "$file")
655 [ -n "$line" ]
656}
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500657
Dean Troyer896eb662013-04-05 15:02:01 -0500658
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500659# Set an option in an INI file
Dean Troyer09e636e2012-03-19 16:31:12 -0500660# iniset config-file section option value
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500661function iniset() {
662 local file=$1
663 local section=$2
664 local option=$3
665 local value=$4
Attila Fazekas588eb412012-12-20 10:57:16 +0100666 if ! grep -q "^\[$section\]" "$file"; then
Dean Troyer09e636e2012-03-19 16:31:12 -0500667 # Add section at the end
Attila Fazekas588eb412012-12-20 10:57:16 +0100668 echo -e "\n[$section]" >>"$file"
Dean Troyer09e636e2012-03-19 16:31:12 -0500669 fi
Attila Fazekas588eb412012-12-20 10:57:16 +0100670 if ! ini_has_option "$file" "$section" "$option"; then
Dean Troyer09e636e2012-03-19 16:31:12 -0500671 # Add it
Attila Fazekas588eb412012-12-20 10:57:16 +0100672 sed -i -e "/^\[$section\]/ a\\
Dean Troyer09e636e2012-03-19 16:31:12 -0500673$option = $value
Attila Fazekas588eb412012-12-20 10:57:16 +0100674" "$file"
Dean Troyer09e636e2012-03-19 16:31:12 -0500675 else
676 # Replace it
Attila Fazekas588eb412012-12-20 10:57:16 +0100677 sed -i -e "/^\[$section\]/,/^\[.*\]/ s|^\($option[ \t]*=[ \t]*\).*$|\1$value|" "$file"
Dean Troyer09e636e2012-03-19 16:31:12 -0500678 fi
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500679}
680
Dean Troyer896eb662013-04-05 15:02:01 -0500681
Lianhao Lu239f3242013-03-01 15:54:02 +0800682# Get a multiple line option from an INI file
683# iniget_multiline config-file section option
684function iniget_multiline() {
685 local file=$1
686 local section=$2
687 local option=$3
688 local values
689 values=$(sed -ne "/^\[$section\]/,/^\[.*\]/ { s/^$option[ \t]*=[ \t]*//gp; }" "$file")
690 echo ${values}
691}
692
Dean Troyer896eb662013-04-05 15:02:01 -0500693
Lianhao Lu239f3242013-03-01 15:54:02 +0800694# Set a multiple line option in an INI file
695# iniset_multiline config-file section option value1 value2 valu3 ...
696function iniset_multiline() {
697 local file=$1
698 local section=$2
699 local option=$3
700 shift 3
701 local values
702 for v in $@; do
703 # The later sed command inserts each new value in the line next to
704 # the section identifier, which causes the values to be inserted in
705 # the reverse order. Do a reverse here to keep the original order.
706 values="$v ${values}"
707 done
708 if ! grep -q "^\[$section\]" "$file"; then
709 # Add section at the end
710 echo -e "\n[$section]" >>"$file"
711 else
712 # Remove old values
713 sed -i -e "/^\[$section\]/,/^\[.*\]/ { /^$option[ \t]*=/ d; }" "$file"
714 fi
715 # Add new ones
716 for v in $values; do
717 sed -i -e "/^\[$section\]/ a\\
718$option = $v
719" "$file"
720 done
721}
722
Dean Troyer896eb662013-04-05 15:02:01 -0500723
Lianhao Lu239f3242013-03-01 15:54:02 +0800724# Append a new option in an ini file without replacing the old value
725# iniadd config-file section option value1 value2 value3 ...
726function iniadd() {
727 local file=$1
728 local section=$2
729 local option=$3
730 shift 3
731 local values="$(iniget_multiline $file $section $option) $@"
732 iniset_multiline $file $section $option $values
733}
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500734
Dean Troyer896eb662013-04-05 15:02:01 -0500735# Find out if a process exists by partial name.
736# is_running name
737function is_running() {
738 local name=$1
739 ps auxw | grep -v grep | grep ${name} > /dev/null
740 RC=$?
741 # some times I really hate bash reverse binary logic
742 return $RC
743}
744
745
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000746# is_service_enabled() checks if the service(s) specified as arguments are
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500747# enabled by the user in ``ENABLED_SERVICES``.
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000748#
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500749# Multiple services specified as arguments are ``OR``'ed together; the test
750# is a short-circuit boolean, i.e it returns on the first match.
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000751#
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500752# There are special cases for some 'catch-all' services::
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000753# **nova** returns true if any service enabled start with **n-**
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500754# **cinder** returns true if any service enabled start with **c-**
755# **ceilometer** returns true if any service enabled start with **ceilometer**
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000756# **glance** returns true if any service enabled start with **g-**
Mark McClainb05c8762013-07-06 23:29:39 -0400757# **neutron** returns true if any service enabled start with **q-**
Chmouel Boudjnah0c3a5582013-03-06 10:58:33 +0100758# **swift** returns true if any service enabled start with **s-**
759# For backward compatibility if we have **swift** in ENABLED_SERVICES all the
760# **s-** services will be enabled. This will be deprecated in the future.
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500761#
Chris Behrensc62c2b92013-07-24 03:56:13 -0700762# Cells within nova is enabled if **n-cell** is in ``ENABLED_SERVICES``.
763# We also need to make sure to treat **n-cell-region** and **n-cell-child**
764# as enabled in this case.
765#
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500766# Uses global ``ENABLED_SERVICES``
767# is_service_enabled service [service ...]
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000768function is_service_enabled() {
769 services=$@
770 for service in ${services}; do
771 [[ ,${ENABLED_SERVICES}, =~ ,${service}, ]] && return 0
Chris Behrensc62c2b92013-07-24 03:56:13 -0700772 [[ ${service} == n-cell-* && ${ENABLED_SERVICES} =~ "n-cell" ]] && return 0
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000773 [[ ${service} == "nova" && ${ENABLED_SERVICES} =~ "n-" ]] && return 0
Dean Troyer67787e62012-05-02 11:48:15 -0500774 [[ ${service} == "cinder" && ${ENABLED_SERVICES} =~ "c-" ]] && return 0
John H. Tran93361642012-07-26 11:22:05 -0700775 [[ ${service} == "ceilometer" && ${ENABLED_SERVICES} =~ "ceilometer-" ]] && return 0
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000776 [[ ${service} == "glance" && ${ENABLED_SERVICES} =~ "g-" ]] && return 0
Mark McClainb05c8762013-07-06 23:29:39 -0400777 [[ ${service} == "neutron" && ${ENABLED_SERVICES} =~ "q-" ]] && return 0
Chmouel Boudjnah0c3a5582013-03-06 10:58:33 +0100778 [[ ${service} == "swift" && ${ENABLED_SERVICES} =~ "s-" ]] && return 0
779 [[ ${service} == s-* && ${ENABLED_SERVICES} =~ "swift" ]] && return 0
Chmouel Boudjnah408b0092012-03-15 23:21:55 +0000780 done
781 return 1
782}
783
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500784
785# remove extra commas from the input string (i.e. ``ENABLED_SERVICES``)
786# _cleanup_service_list service-list
Doug Hellmannf04178f2012-07-05 17:10:03 -0400787function _cleanup_service_list () {
Dean Troyerca0e3d02012-04-13 15:58:37 -0500788 echo "$1" | sed -e '
Doug Hellmannf04178f2012-07-05 17:10:03 -0400789 s/,,/,/g;
790 s/^,//;
791 s/,$//
792 '
793}
794
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500795
Doug Hellmannf04178f2012-07-05 17:10:03 -0400796# enable_service() adds the services passed as argument to the
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500797# ``ENABLED_SERVICES`` list, if they are not already present.
Doug Hellmannf04178f2012-07-05 17:10:03 -0400798#
799# For example:
Joe Gordon6fd28112012-11-13 16:55:41 -0800800# enable_service qpid
Doug Hellmannf04178f2012-07-05 17:10:03 -0400801#
802# This function does not know about the special cases
Mark McClainb05c8762013-07-06 23:29:39 -0400803# for nova, glance, and neutron built into is_service_enabled().
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500804# Uses global ``ENABLED_SERVICES``
805# enable_service service [service ...]
Doug Hellmannf04178f2012-07-05 17:10:03 -0400806function enable_service() {
807 local tmpsvcs="${ENABLED_SERVICES}"
808 for service in $@; do
809 if ! is_service_enabled $service; then
810 tmpsvcs+=",$service"
811 fi
812 done
813 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
814 disable_negated_services
815}
816
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500817
Doug Hellmannf04178f2012-07-05 17:10:03 -0400818# disable_service() removes the services passed as argument to the
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500819# ``ENABLED_SERVICES`` list, if they are present.
Doug Hellmannf04178f2012-07-05 17:10:03 -0400820#
821# For example:
Joe Gordon6fd28112012-11-13 16:55:41 -0800822# disable_service rabbit
Doug Hellmannf04178f2012-07-05 17:10:03 -0400823#
824# This function does not know about the special cases
Mark McClainb05c8762013-07-06 23:29:39 -0400825# for nova, glance, and neutron built into is_service_enabled().
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500826# Uses global ``ENABLED_SERVICES``
827# disable_service service [service ...]
Doug Hellmannf04178f2012-07-05 17:10:03 -0400828function disable_service() {
829 local tmpsvcs=",${ENABLED_SERVICES},"
830 local service
831 for service in $@; do
832 if is_service_enabled $service; then
833 tmpsvcs=${tmpsvcs//,$service,/,}
834 fi
835 done
836 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
837}
838
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500839
Doug Hellmannf04178f2012-07-05 17:10:03 -0400840# disable_all_services() removes all current services
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500841# from ``ENABLED_SERVICES`` to reset the configuration
Doug Hellmannf04178f2012-07-05 17:10:03 -0400842# before a minimal installation
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500843# Uses global ``ENABLED_SERVICES``
844# disable_all_services
Doug Hellmannf04178f2012-07-05 17:10:03 -0400845function disable_all_services() {
846 ENABLED_SERVICES=""
847}
848
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500849
850# Remove all services starting with '-'. For example, to install all default
Joe Gordon6fd28112012-11-13 16:55:41 -0800851# services except rabbit (rabbit) set in ``localrc``:
852# ENABLED_SERVICES+=",-rabbit"
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500853# Uses global ``ENABLED_SERVICES``
854# disable_negated_services
Doug Hellmannf04178f2012-07-05 17:10:03 -0400855function disable_negated_services() {
856 local tmpsvcs="${ENABLED_SERVICES}"
857 local service
858 for service in ${tmpsvcs//,/ }; do
859 if [[ ${service} == -* ]]; then
860 tmpsvcs=$(echo ${tmpsvcs}|sed -r "s/(,)?(-)?${service#-}(,)?/,/g")
861 fi
862 done
863 ENABLED_SERVICES=$(_cleanup_service_list "$tmpsvcs")
864}
Dean Troyer489bd2a2012-03-02 10:44:29 -0600865
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500866
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500867# Distro-agnostic package installer
868# install_package package [package ...]
869function install_package() {
Vincent Untzc18b9652012-12-04 12:36:34 +0100870 if is_ubuntu; then
Vincent Untzc0482e62012-06-12 11:30:43 +0200871 [[ "$NO_UPDATE_REPOS" = "True" ]] || apt_get update
872 NO_UPDATE_REPOS=True
873
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500874 apt_get install "$@"
Vincent Untz00011c02012-12-06 09:56:32 +0100875 elif is_fedora; then
876 yum_install "$@"
877 elif is_suse; then
878 zypper_install "$@"
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500879 else
Vincent Untz00011c02012-12-06 09:56:32 +0100880 exit_distro_not_supported "installing packages"
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500881 fi
882}
883
884
Dean Troyer995eb922013-03-07 16:11:40 -0600885# Distro-agnostic package uninstaller
886# uninstall_package package [package ...]
887function uninstall_package() {
888 if is_ubuntu; then
889 apt_get purge "$@"
890 elif is_fedora; then
Ian Wienand2c678cc2013-03-20 13:00:44 +1100891 sudo yum remove -y "$@"
Dean Troyer995eb922013-03-07 16:11:40 -0600892 elif is_suse; then
Ian Wienand2c678cc2013-03-20 13:00:44 +1100893 sudo rpm -e "$@"
Dean Troyer995eb922013-03-07 16:11:40 -0600894 else
895 exit_distro_not_supported "uninstalling packages"
896 fi
897}
898
899
Vincent Untz71ebc6f2012-06-12 13:45:15 +0200900# Distro-agnostic function to tell if a package is installed
901# is_package_installed package [package ...]
902function is_package_installed() {
903 if [[ -z "$@" ]]; then
904 return 1
905 fi
906
907 if [[ -z "$os_PACKAGE" ]]; then
908 GetOSVersion
909 fi
Vincent Untzc18b9652012-12-04 12:36:34 +0100910
Vincent Untz71ebc6f2012-06-12 13:45:15 +0200911 if [[ "$os_PACKAGE" = "deb" ]]; then
912 dpkg -l "$@" > /dev/null
Vincent Untz00011c02012-12-06 09:56:32 +0100913 elif [[ "$os_PACKAGE" = "rpm" ]]; then
Vincent Untz71ebc6f2012-06-12 13:45:15 +0200914 rpm --quiet -q "$@"
Vincent Untz00011c02012-12-06 09:56:32 +0100915 else
916 exit_distro_not_supported "finding if a package is installed"
Vincent Untz71ebc6f2012-06-12 13:45:15 +0200917 fi
918}
919
920
Dean Troyer489bd2a2012-03-02 10:44:29 -0600921# Test if the named environment variable is set and not zero length
922# is_set env-var
923function is_set() {
924 local var=\$"$1"
Attila Fazekas251d3b52012-12-16 15:05:44 +0100925 eval "[ -n \"$var\" ]" # For ex.: sh -c "[ -n \"$var\" ]" would be better, but several exercises depends on this
Dean Troyer489bd2a2012-03-02 10:44:29 -0600926}
927
928
Dean Troyer4a43b7b2012-08-28 17:43:40 -0500929# Wrapper for ``pip install`` to set cache and proxy environment variables
Maru Newby3a87edd2012-10-25 23:01:06 +0000930# Uses globals ``OFFLINE``, ``PIP_DOWNLOAD_CACHE``, ``PIP_USE_MIRRORS``,
931# ``TRACK_DEPENDS``, ``*_proxy`
Dean Troyer7f9aa712012-01-31 12:11:56 -0600932# pip_install package [package ...]
933function pip_install {
Dean Troyerd0b21e22012-03-07 14:52:25 -0600934 [[ "$OFFLINE" = "True" || -z "$@" ]] && return
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500935 if [[ -z "$os_PACKAGE" ]]; then
936 GetOSVersion
937 fi
Dean Troyercc6b4432013-04-08 15:38:03 -0500938 if [[ $TRACK_DEPENDS = True ]]; then
Monty Taylor47f02062012-07-26 11:09:24 -0500939 source $DEST/.venv/bin/activate
940 CMD_PIP=$DEST/.venv/bin/pip
941 SUDO_PIP="env"
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500942 else
Monty Taylor47f02062012-07-26 11:09:24 -0500943 SUDO_PIP="sudo"
Vincent Untz8ec27222012-11-29 09:25:31 +0100944 CMD_PIP=$(get_pip_command)
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500945 fi
Ian Wienandd67dd872013-04-11 11:14:36 +1000946
Roman Gorodeckij99405a42013-08-07 09:20:36 -0400947 # Mirror option not needed anymore because pypi has CDN available,
948 # but it's useful in certain circumstances
949 PIP_USE_MIRRORS=${PIP_USE_MIRRORS:-False}
Maru Newby3a87edd2012-10-25 23:01:06 +0000950 if [[ "$PIP_USE_MIRRORS" != "False" ]]; then
951 PIP_MIRROR_OPT="--use-mirrors"
952 fi
Ian Wienandd67dd872013-04-11 11:14:36 +1000953
Ian Wienand31dcd3e2013-07-16 13:36:34 +1000954 # pip < 1.4 has a bug where it will use an already existing build
955 # directory unconditionally. Say an earlier component installs
956 # foo v1.1; pip will have built foo's source in
957 # /tmp/$USER-pip-build. Even if a later component specifies foo <
958 # 1.1, the existing extracted build will be used and cause
959 # confusing errors. By creating unique build directories we avoid
960 # this problem. See
961 # https://github.com/pypa/pip/issues/709
962 local pip_build_tmp=$(mktemp --tmpdir -d pip-build.XXXXX)
963
Monty Taylor47f02062012-07-26 11:09:24 -0500964 $SUDO_PIP PIP_DOWNLOAD_CACHE=${PIP_DOWNLOAD_CACHE:-/var/cache/pip} \
Dean Troyer7f9aa712012-01-31 12:11:56 -0600965 HTTP_PROXY=$http_proxy \
966 HTTPS_PROXY=$https_proxy \
Osamu Habuka7abe4f22012-07-25 12:39:32 +0900967 NO_PROXY=$no_proxy \
Ian Wienand31dcd3e2013-07-16 13:36:34 +1000968 $CMD_PIP install --build=${pip_build_tmp} \
969 $PIP_MIRROR_OPT $@ \
970 && $SUDO_PIP rm -rf ${pip_build_tmp}
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500971}
972
973
Ian Wienand31dcd3e2013-07-16 13:36:34 +1000974# Cleanup anything from /tmp on unstack
975# clean_tmp
976function cleanup_tmp {
977 local tmp_dir=${TMPDIR:-/tmp}
978
979 # see comments in pip_install
980 sudo rm -rf ${tmp_dir}/pip-build.*
981}
982
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500983# Service wrapper to restart services
984# restart_service service-name
985function restart_service() {
Vincent Untzc18b9652012-12-04 12:36:34 +0100986 if is_ubuntu; then
Dean Troyer5218d452012-02-04 02:13:23 -0600987 sudo /usr/sbin/service $1 restart
988 else
989 sudo /sbin/service $1 restart
990 fi
Dean Troyer13dc5cc2012-03-27 14:50:45 -0500991}
992
993
Dean Troyer681f3fd2013-02-27 19:00:39 -0600994# _run_process() is designed to be backgrounded by run_process() to simulate a
995# fork. It includes the dirty work of closing extra filehandles and preparing log
996# files to produce the same logs as screen_it(). The log filename is derived
997# from the service name and global-and-now-misnamed SCREEN_LOGDIR
998# _run_process service "command-line"
999function _run_process() {
1000 local service=$1
1001 local command="$2"
1002
1003 # Undo logging redirections and close the extra descriptors
1004 exec 1>&3
1005 exec 2>&3
1006 exec 3>&-
1007 exec 6>&-
1008
1009 if [[ -n ${SCREEN_LOGDIR} ]]; then
1010 exec 1>&${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log 2>&1
1011 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
1012
1013 # TODO(dtroyer): Hack to get stdout from the Python interpreter for the logs.
1014 export PYTHONUNBUFFERED=1
1015 fi
1016
1017 exec /bin/bash -c "$command"
1018 die "$service exec failure: $command"
1019}
1020
1021
1022# run_process() launches a child process that closes all file descriptors and
1023# then exec's the passed in command. This is meant to duplicate the semantics
1024# of screen_it() without screen. PIDs are written to
1025# $SERVICE_DIR/$SCREEN_NAME/$service.pid
1026# run_process service "command-line"
1027function run_process() {
1028 local service=$1
1029 local command="$2"
1030
1031 # Spawn the child process
1032 _run_process "$service" "$command" &
1033 echo $!
1034}
1035
1036
Dean Troyer15733352012-09-06 11:51:30 -05001037# Helper to launch a service in a named screen
1038# screen_it service "command-line"
1039function screen_it {
Dean Troyer15733352012-09-06 11:51:30 -05001040 SCREEN_NAME=${SCREEN_NAME:-stack}
jiajun xua9414242012-12-06 16:30:57 +08001041 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
Dean Troyer681f3fd2013-02-27 19:00:39 -06001042 USE_SCREEN=$(trueorfalse True $USE_SCREEN)
jiajun xua9414242012-12-06 16:30:57 +08001043
Dean Troyer15733352012-09-06 11:51:30 -05001044 if is_service_enabled $1; then
1045 # Append the service to the screen rc file
1046 screen_rc "$1" "$2"
1047
Dean Troyer681f3fd2013-02-27 19:00:39 -06001048 if [[ "$USE_SCREEN" = "True" ]]; then
1049 screen -S $SCREEN_NAME -X screen -t $1
Jeremy Stanley25ebbcd2013-02-17 15:45:55 +00001050
Dean Troyer681f3fd2013-02-27 19:00:39 -06001051 if [[ -n ${SCREEN_LOGDIR} ]]; then
1052 screen -S $SCREEN_NAME -p $1 -X logfile ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log
1053 screen -S $SCREEN_NAME -p $1 -X log on
1054 ln -sf ${SCREEN_LOGDIR}/screen-${1}.${CURRENT_LOG_TIME}.log ${SCREEN_LOGDIR}/screen-${1}.log
1055 fi
Jeremy Stanley25ebbcd2013-02-17 15:45:55 +00001056
Vishvananda Ishaya58e21342013-02-11 16:48:12 -08001057 # sleep to allow bash to be ready to be send the command - we are
1058 # creating a new window in screen and then sends characters, so if
1059 # bash isn't running by the time we send the command, nothing happens
1060 sleep 1.5
Dean Troyer15733352012-09-06 11:51:30 -05001061
Vishvananda Ishaya58e21342013-02-11 16:48:12 -08001062 NL=`echo -ne '\015'`
1063 screen -S $SCREEN_NAME -p $1 -X stuff "$2 || touch \"$SERVICE_DIR/$SCREEN_NAME/$1.failure\"$NL"
1064 else
Dean Troyer681f3fd2013-02-27 19:00:39 -06001065 # Spawn directly without screen
1066 run_process "$1" "$2" >$SERVICE_DIR/$SCREEN_NAME/$service.pid
Dean Troyer15733352012-09-06 11:51:30 -05001067 fi
Dean Troyer15733352012-09-06 11:51:30 -05001068 fi
1069}
1070
1071
1072# Screen rc file builder
1073# screen_rc service "command-line"
1074function screen_rc {
1075 SCREEN_NAME=${SCREEN_NAME:-stack}
1076 SCREENRC=$TOP_DIR/$SCREEN_NAME-screenrc
1077 if [[ ! -e $SCREENRC ]]; then
1078 # Name the screen session
1079 echo "sessionname $SCREEN_NAME" > $SCREENRC
1080 # Set a reasonable statusbar
1081 echo "hardstatus alwayslastline '$SCREEN_HARDSTATUS'" >> $SCREENRC
Steven Dake30396572013-06-30 16:11:54 -07001082 # Some distributions override PROMPT_COMMAND for the screen terminal type - turn that off
1083 echo "setenv PROMPT_COMMAND /bin/true" >> $SCREENRC
Dean Troyer15733352012-09-06 11:51:30 -05001084 echo "screen -t shell bash" >> $SCREENRC
1085 fi
1086 # If this service doesn't already exist in the screenrc file
1087 if ! grep $1 $SCREENRC 2>&1 > /dev/null; then
1088 NL=`echo -ne '\015'`
1089 echo "screen -t $1 bash" >> $SCREENRC
1090 echo "stuff \"$2$NL\"" >> $SCREENRC
1091 fi
1092}
1093
Dean Troyer1a6d4492013-06-03 16:47:36 -05001094
jiajun xua9414242012-12-06 16:30:57 +08001095# Helper to remove the *.failure files under $SERVICE_DIR/$SCREEN_NAME
1096# This is used for service_check when all the screen_it are called finished
1097# init_service_check
1098function init_service_check() {
1099 SCREEN_NAME=${SCREEN_NAME:-stack}
1100 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1101
1102 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
1103 mkdir -p "$SERVICE_DIR/$SCREEN_NAME"
1104 fi
1105
1106 rm -f "$SERVICE_DIR/$SCREEN_NAME"/*.failure
1107}
1108
Dean Troyer1a6d4492013-06-03 16:47:36 -05001109
jiajun xua9414242012-12-06 16:30:57 +08001110# Helper to get the status of each running service
1111# service_check
1112function service_check() {
1113 local service
1114 local failures
1115 SCREEN_NAME=${SCREEN_NAME:-stack}
1116 SERVICE_DIR=${SERVICE_DIR:-${DEST}/status}
1117
1118
1119 if [[ ! -d "$SERVICE_DIR/$SCREEN_NAME" ]]; then
1120 echo "No service status directory found"
1121 return
1122 fi
1123
1124 # Check if there is any falure flag file under $SERVICE_DIR/$SCREEN_NAME
1125 failures=`ls "$SERVICE_DIR/$SCREEN_NAME"/*.failure 2>/dev/null`
1126
1127 for service in $failures; do
1128 service=`basename $service`
Bob Ball46287d82013-07-30 09:43:17 +01001129 service=${service%.failure}
jiajun xua9414242012-12-06 16:30:57 +08001130 echo "Error: Service $service is not running"
1131 done
1132
1133 if [ -n "$failures" ]; then
1134 echo "More details about the above errors can be found with screen, with ./rejoin-stack.sh"
1135 fi
1136}
Dean Troyer15733352012-09-06 11:51:30 -05001137
Dean Troyer1a6d4492013-06-03 16:47:36 -05001138
Monty Taylor408a4a72013-08-02 15:43:47 -04001139# ``pip install -e`` the package, which processes the dependencies
1140# using pip before running `setup.py develop`
Monty Taylorb5bbaac2013-08-06 10:35:02 -03001141# Uses globals ``STACK_USER``, ``TRACK_DEPENDS``, ``REQUIREMENTS_DIR``
Dean Troyerbbafb1b2012-06-11 16:51:39 -05001142# setup_develop directory
1143function setup_develop() {
Sean Dague6c844632013-07-31 06:50:14 -04001144 local project_dir=$1
Dean Troyercc6b4432013-04-08 15:38:03 -05001145 if [[ $TRACK_DEPENDS = True ]]; then
Monty Taylor47f02062012-07-26 11:09:24 -05001146 SUDO_CMD="env"
1147 else
1148 SUDO_CMD="sudo"
1149 fi
Sean Dague6c844632013-07-31 06:50:14 -04001150
1151 echo "cd $REQUIREMENTS_DIR; $SUDO_CMD python update.py $project_dir"
1152
Dean Troyer62d1d692013-08-01 17:40:40 -05001153 # Don't update repo if local changes exist
1154 if (cd $project_dir && git diff --quiet); then
1155 (cd $REQUIREMENTS_DIR; \
1156 $SUDO_CMD python update.py $project_dir)
1157 fi
Sean Dague6c844632013-07-31 06:50:14 -04001158
Monty Taylorb5bbaac2013-08-06 10:35:02 -03001159 pip_install -e $project_dir
1160 # ensure that further actions can do things like setup.py sdist
1161 $SUDO_CMD chown -R $STACK_USER $1/*.egg-info
Dean Troyerbbafb1b2012-06-11 16:51:39 -05001162}
1163
1164
Dean Troyer13dc5cc2012-03-27 14:50:45 -05001165# Service wrapper to start services
1166# start_service service-name
1167function start_service() {
Vincent Untzc18b9652012-12-04 12:36:34 +01001168 if is_ubuntu; then
Dean Troyer5218d452012-02-04 02:13:23 -06001169 sudo /usr/sbin/service $1 start
1170 else
1171 sudo /sbin/service $1 start
1172 fi
Dean Troyer13dc5cc2012-03-27 14:50:45 -05001173}
1174
1175
1176# Service wrapper to stop services
1177# stop_service service-name
1178function stop_service() {
Vincent Untzc18b9652012-12-04 12:36:34 +01001179 if is_ubuntu; then
Dean Troyer5218d452012-02-04 02:13:23 -06001180 sudo /usr/sbin/service $1 stop
1181 else
1182 sudo /sbin/service $1 stop
1183 fi
Dean Troyer7f9aa712012-01-31 12:11:56 -06001184}
1185
1186
1187# Normalize config values to True or False
Dean Troyer4a43b7b2012-08-28 17:43:40 -05001188# Accepts as False: 0 no false False FALSE
1189# Accepts as True: 1 yes true True TRUE
1190# VAR=$(trueorfalse default-value test-value)
Dean Troyer7f9aa712012-01-31 12:11:56 -06001191function trueorfalse() {
1192 local default=$1
1193 local testval=$2
1194
1195 [[ -z "$testval" ]] && { echo "$default"; return; }
1196 [[ "0 no false False FALSE" =~ "$testval" ]] && { echo "False"; return; }
1197 [[ "1 yes true True TRUE" =~ "$testval" ]] && { echo "True"; return; }
1198 echo "$default"
1199}
Dean Troyer27e32692012-03-16 16:16:56 -05001200
Dean Troyer13dc5cc2012-03-27 14:50:45 -05001201
Dean Troyerca0e3d02012-04-13 15:58:37 -05001202# Retrieve an image from a URL and upload into Glance
1203# Uses the following variables:
Dean Troyer4a43b7b2012-08-28 17:43:40 -05001204# ``FILES`` must be set to the cache dir
1205# ``GLANCE_HOSTPORT``
Dean Troyerca0e3d02012-04-13 15:58:37 -05001206# upload_image image-url glance-token
1207function upload_image() {
1208 local image_url=$1
1209 local token=$2
1210
1211 # Create a directory for the downloaded image tarballs.
1212 mkdir -p $FILES/images
1213
1214 # Downloads the image (uec ami+aki style), then extracts it.
1215 IMAGE_FNAME=`basename "$image_url"`
1216 if [[ ! -f $FILES/$IMAGE_FNAME || "$(stat -c "%s" $FILES/$IMAGE_FNAME)" = "0" ]]; then
1217 wget -c $image_url -O $FILES/$IMAGE_FNAME
1218 if [[ $? -ne 0 ]]; then
1219 echo "Not found: $image_url"
1220 return
1221 fi
1222 fi
1223
1224 # OpenVZ-format images are provided as .tar.gz, but not decompressed prior to loading
1225 if [[ "$image_url" =~ 'openvz' ]]; then
1226 IMAGE="$FILES/${IMAGE_FNAME}"
1227 IMAGE_NAME="${IMAGE_FNAME%.tar.gz}"
1228 glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public=True --container-format ami --disk-format ami < "${IMAGE}"
1229 return
1230 fi
1231
Sreeram Yerrapragadacbaff862013-07-24 19:49:23 -07001232 # vmdk format images
1233 if [[ "$image_url" =~ '.vmdk' ]]; then
1234 IMAGE="$FILES/${IMAGE_FNAME}"
1235 IMAGE_NAME="${IMAGE_FNAME%.vmdk}"
1236 glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public=True --container-format bare --disk-format vmdk --property vmware-disktype="preallocated" < "${IMAGE}"
1237 return
1238 fi
1239
Davanum Srinivas316ed6c2013-02-06 15:29:49 -05001240 # XenServer-ovf-format images are provided as .vhd.tgz as well
1241 # and should not be decompressed prior to loading
1242 if [[ "$image_url" =~ '.vhd.tgz' ]]; then
1243 IMAGE="$FILES/${IMAGE_FNAME}"
1244 IMAGE_NAME="${IMAGE_FNAME%.vhd.tgz}"
1245 glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public=True --container-format=ovf --disk-format=vhd < "${IMAGE}"
1246 return
1247 fi
1248
Dean Troyerca0e3d02012-04-13 15:58:37 -05001249 KERNEL=""
1250 RAMDISK=""
1251 DISK_FORMAT=""
1252 CONTAINER_FORMAT=""
1253 UNPACK=""
1254 case "$IMAGE_FNAME" in
1255 *.tar.gz|*.tgz)
1256 # Extract ami and aki files
1257 [ "${IMAGE_FNAME%.tar.gz}" != "$IMAGE_FNAME" ] &&
1258 IMAGE_NAME="${IMAGE_FNAME%.tar.gz}" ||
1259 IMAGE_NAME="${IMAGE_FNAME%.tgz}"
1260 xdir="$FILES/images/$IMAGE_NAME"
1261 rm -Rf "$xdir";
1262 mkdir "$xdir"
1263 tar -zxf $FILES/$IMAGE_FNAME -C "$xdir"
1264 KERNEL=$(for f in "$xdir/"*-vmlinuz* "$xdir/"aki-*/image; do
1265 [ -f "$f" ] && echo "$f" && break; done; true)
1266 RAMDISK=$(for f in "$xdir/"*-initrd* "$xdir/"ari-*/image; do
1267 [ -f "$f" ] && echo "$f" && break; done; true)
1268 IMAGE=$(for f in "$xdir/"*.img "$xdir/"ami-*/image; do
1269 [ -f "$f" ] && echo "$f" && break; done; true)
1270 if [[ -z "$IMAGE_NAME" ]]; then
1271 IMAGE_NAME=$(basename "$IMAGE" ".img")
1272 fi
1273 ;;
1274 *.img)
1275 IMAGE="$FILES/$IMAGE_FNAME";
1276 IMAGE_NAME=$(basename "$IMAGE" ".img")
Dean Troyer636a3ff2012-09-14 11:36:07 -05001277 format=$(qemu-img info ${IMAGE} | awk '/^file format/ { print $3; exit }')
1278 if [[ ",qcow2,raw,vdi,vmdk,vpc," =~ ",$format," ]]; then
1279 DISK_FORMAT=$format
1280 else
1281 DISK_FORMAT=raw
1282 fi
Dean Troyerca0e3d02012-04-13 15:58:37 -05001283 CONTAINER_FORMAT=bare
1284 ;;
1285 *.img.gz)
1286 IMAGE="$FILES/${IMAGE_FNAME}"
1287 IMAGE_NAME=$(basename "$IMAGE" ".img.gz")
1288 DISK_FORMAT=raw
1289 CONTAINER_FORMAT=bare
1290 UNPACK=zcat
1291 ;;
1292 *.qcow2)
1293 IMAGE="$FILES/${IMAGE_FNAME}"
1294 IMAGE_NAME=$(basename "$IMAGE" ".qcow2")
1295 DISK_FORMAT=qcow2
1296 CONTAINER_FORMAT=bare
1297 ;;
Jonathan Michalon06802042013-03-21 14:29:58 +01001298 *.iso)
1299 IMAGE="$FILES/${IMAGE_FNAME}"
1300 IMAGE_NAME=$(basename "$IMAGE" ".iso")
1301 DISK_FORMAT=iso
1302 CONTAINER_FORMAT=bare
1303 ;;
Dean Troyerca0e3d02012-04-13 15:58:37 -05001304 *) echo "Do not know what to do with $IMAGE_FNAME"; false;;
1305 esac
1306
1307 if [ "$CONTAINER_FORMAT" = "bare" ]; then
1308 if [ "$UNPACK" = "zcat" ]; then
Christian Berendta7a219a2013-07-30 18:22:32 +02001309 glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public True --container-format=$CONTAINER_FORMAT --disk-format $DISK_FORMAT < <(zcat --force "${IMAGE}")
Dean Troyerca0e3d02012-04-13 15:58:37 -05001310 else
Christian Berendta7a219a2013-07-30 18:22:32 +02001311 glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME" --is-public True --container-format=$CONTAINER_FORMAT --disk-format $DISK_FORMAT < "${IMAGE}"
Dean Troyerca0e3d02012-04-13 15:58:37 -05001312 fi
1313 else
1314 # Use glance client to add the kernel the root filesystem.
1315 # We parse the results of the first upload to get the glance ID of the
1316 # kernel for use when uploading the root filesystem.
1317 KERNEL_ID=""; RAMDISK_ID="";
1318 if [ -n "$KERNEL" ]; then
Christian Berendta7a219a2013-07-30 18:22:32 +02001319 KERNEL_ID=$(glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME-kernel" --is-public True --container-format aki --disk-format aki < "$KERNEL" | grep ' id ' | get_field 2)
Dean Troyerca0e3d02012-04-13 15:58:37 -05001320 fi
1321 if [ -n "$RAMDISK" ]; then
Christian Berendta7a219a2013-07-30 18:22:32 +02001322 RAMDISK_ID=$(glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "$IMAGE_NAME-ramdisk" --is-public True --container-format ari --disk-format ari < "$RAMDISK" | grep ' id ' | get_field 2)
Dean Troyerca0e3d02012-04-13 15:58:37 -05001323 fi
Christian Berendta7a219a2013-07-30 18:22:32 +02001324 glance --os-auth-token $token --os-image-url http://$GLANCE_HOSTPORT image-create --name "${IMAGE_NAME%.img}" --is-public True --container-format ami --disk-format ami ${KERNEL_ID:+--property kernel_id=$KERNEL_ID} ${RAMDISK_ID:+--property ramdisk_id=$RAMDISK_ID} < "${IMAGE}"
Dean Troyerca0e3d02012-04-13 15:58:37 -05001325 fi
1326}
1327
Dean Troyer1a6d4492013-06-03 16:47:36 -05001328
Dean Troyerc1b486a2012-11-05 14:26:09 -06001329# Set the database backend to use
1330# When called from stackrc/localrc DATABASE_BACKENDS has not been
1331# initialized yet, just save the configuration selection and call back later
1332# to validate it.
1333# $1 The name of the database backend to use (mysql, postgresql, ...)
1334function use_database {
1335 if [[ -z "$DATABASE_BACKENDS" ]]; then
Dean Troyerafc29fe2013-02-07 15:56:24 -06001336 # No backends registered means this is likely called from ``localrc``
1337 # This is now deprecated usage
Dean Troyerc1b486a2012-11-05 14:26:09 -06001338 DATABASE_TYPE=$1
Bob Ball3aa88872013-02-28 17:39:41 +00001339 DEPRECATED_TEXT="$DEPRECATED_TEXT\nThe database backend needs to be properly set in ENABLED_SERVICES; use_database is deprecated localrc\n"
Attila Fazekas251d3b52012-12-16 15:05:44 +01001340 else
Dean Troyerafc29fe2013-02-07 15:56:24 -06001341 # This should no longer get called...here for posterity
Attila Fazekas251d3b52012-12-16 15:05:44 +01001342 use_exclusive_service DATABASE_BACKENDS DATABASE_TYPE $1
Dean Troyerc1b486a2012-11-05 14:26:09 -06001343 fi
Dean Troyerc1b486a2012-11-05 14:26:09 -06001344}
1345
Dean Troyer1a6d4492013-06-03 16:47:36 -05001346
Terry Wilson428af5a2012-11-01 16:12:39 -04001347# Toggle enable/disable_service for services that must run exclusive of each other
1348# $1 The name of a variable containing a space-separated list of services
1349# $2 The name of a variable in which to store the enabled service's name
1350# $3 The name of the service to enable
1351function use_exclusive_service {
1352 local options=${!1}
1353 local selection=$3
1354 out=$2
1355 [ -z $selection ] || [[ ! "$options" =~ "$selection" ]] && return 1
1356 for opt in $options;do
1357 [[ "$opt" = "$selection" ]] && enable_service $opt || disable_service $opt
1358 done
1359 eval "$out=$selection"
1360 return 0
1361}
Dean Troyerca0e3d02012-04-13 15:58:37 -05001362
Dean Troyer1a6d4492013-06-03 16:47:36 -05001363
Dean Troyer3a3a2ba2012-12-11 15:26:24 -06001364# Wait for an HTTP server to start answering requests
1365# wait_for_service timeout url
1366function wait_for_service() {
1367 local timeout=$1
1368 local url=$2
1369 timeout $timeout sh -c "while ! http_proxy= https_proxy= curl -s $url >/dev/null; do sleep 1; done"
1370}
1371
Dean Troyer1a6d4492013-06-03 16:47:36 -05001372
Dean Troyer4a43b7b2012-08-28 17:43:40 -05001373# Wrapper for ``yum`` to set proxy environment variables
1374# Uses globals ``OFFLINE``, ``*_proxy`
Dean Troyer13dc5cc2012-03-27 14:50:45 -05001375# yum_install package [package ...]
1376function yum_install() {
1377 [[ "$OFFLINE" = "True" ]] && return
1378 local sudo="sudo"
1379 [[ "$(id -u)" = "0" ]] && sudo="env"
1380 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
Osamu Habuka7abe4f22012-07-25 12:39:32 +09001381 no_proxy=$no_proxy \
Dean Troyer13dc5cc2012-03-27 14:50:45 -05001382 yum install -y "$@"
1383}
1384
Dean Troyer1a6d4492013-06-03 16:47:36 -05001385
1386# zypper wrapper to set arguments correctly
1387# zypper_install package [package ...]
1388function zypper_install() {
1389 [[ "$OFFLINE" = "True" ]] && return
1390 local sudo="sudo"
1391 [[ "$(id -u)" = "0" ]] && sudo="env"
1392 $sudo http_proxy=$http_proxy https_proxy=$https_proxy \
1393 zypper --non-interactive install --auto-agree-with-licenses "$@"
1394}
1395
1396
Nachi Uenofda946e2012-10-24 17:26:02 -07001397# ping check
1398# Uses globals ``ENABLED_SERVICES``
Dean Troyer1a6d4492013-06-03 16:47:36 -05001399# ping_check from-net ip boot-timeout expected
Nachi Uenofda946e2012-10-24 17:26:02 -07001400function ping_check() {
Mark McClainb05c8762013-07-06 23:29:39 -04001401 if is_service_enabled neutron; then
1402 _ping_check_neutron "$1" $2 $3 $4
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001403 return
1404 fi
1405 _ping_check_novanet "$1" $2 $3 $4
Nachi Uenofda946e2012-10-24 17:26:02 -07001406}
1407
1408# ping check for nova
1409# Uses globals ``MULTI_HOST``, ``PRIVATE_NETWORK``
1410function _ping_check_novanet() {
1411 local from_net=$1
1412 local ip=$2
1413 local boot_timeout=$3
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001414 local expected=${4:-"True"}
1415 local check_command=""
Nachi Uenofda946e2012-10-24 17:26:02 -07001416 MULTI_HOST=`trueorfalse False $MULTI_HOST`
1417 if [[ "$MULTI_HOST" = "True" && "$from_net" = "$PRIVATE_NETWORK_NAME" ]]; then
1418 sleep $boot_timeout
1419 return
1420 fi
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001421 if [[ "$expected" = "True" ]]; then
1422 check_command="while ! ping -c1 -w1 $ip; do sleep 1; done"
1423 else
1424 check_command="while ping -c1 -w1 $ip; do sleep 1; done"
1425 fi
1426 if ! timeout $boot_timeout sh -c "$check_command"; then
1427 if [[ "$expected" = "True" ]]; then
Nachi Ueno07115eb2013-02-26 12:38:18 -08001428 die $LINENO "[Fail] Couldn't ping server"
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001429 else
Nachi Ueno07115eb2013-02-26 12:38:18 -08001430 die $LINENO "[Fail] Could ping server"
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001431 fi
Nachi Uenofda946e2012-10-24 17:26:02 -07001432 exit 1
1433 fi
1434}
1435
Dean Troyer1a6d4492013-06-03 16:47:36 -05001436
Nachi Uenofda946e2012-10-24 17:26:02 -07001437# ssh check
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001438
Dean Troyer1a6d4492013-06-03 16:47:36 -05001439# ssh_check net-name key-file floating-ip default-user active-timeout
Nachi Uenofda946e2012-10-24 17:26:02 -07001440function ssh_check() {
Mark McClainb05c8762013-07-06 23:29:39 -04001441 if is_service_enabled neutron; then
1442 _ssh_check_neutron "$1" $2 $3 $4 $5
Nachi Ueno5db5bfa2012-10-29 11:25:29 -07001443 return
1444 fi
1445 _ssh_check_novanet "$1" $2 $3 $4 $5
1446}
1447
1448function _ssh_check_novanet() {
Nachi Uenofda946e2012-10-24 17:26:02 -07001449 local NET_NAME=$1
1450 local KEY_FILE=$2
1451 local FLOATING_IP=$3
1452 local DEFAULT_INSTANCE_USER=$4
1453 local ACTIVE_TIMEOUT=$5
Dean Troyer6931c132012-11-07 16:51:21 -06001454 local probe_cmd=""
Dean Troyercc6b4432013-04-08 15:38:03 -05001455 if ! timeout $ACTIVE_TIMEOUT sh -c "while ! ssh -o StrictHostKeyChecking=no -i $KEY_FILE ${DEFAULT_INSTANCE_USER}@$FLOATING_IP echo success; do sleep 1; done"; then
Nachi Ueno07115eb2013-02-26 12:38:18 -08001456 die $LINENO "server didn't become ssh-able!"
Nachi Uenofda946e2012-10-24 17:26:02 -07001457 fi
1458}
Dean Troyer13dc5cc2012-03-27 14:50:45 -05001459
Vincent Untz856a11e2012-11-21 16:04:12 +01001460
Vincent Untz856a11e2012-11-21 16:04:12 +01001461# Add a user to a group.
1462# add_user_to_group user group
1463function add_user_to_group() {
1464 local user=$1
1465 local group=$2
1466
1467 if [[ -z "$os_VENDOR" ]]; then
1468 GetOSVersion
1469 fi
1470
1471 # SLE11 and openSUSE 12.2 don't have the usual usermod
1472 if ! is_suse || [[ "$os_VENDOR" = "openSUSE" && "$os_RELEASE" != "12.2" ]]; then
1473 sudo usermod -a -G "$group" "$user"
1474 else
1475 sudo usermod -A "$group" "$user"
1476 fi
1477}
1478
1479
Jakub Ruzicka4196d552013-01-30 15:35:54 +01001480# Get the path to the direcotry where python executables are installed.
1481# get_python_exec_prefix
1482function get_python_exec_prefix() {
Martin Vidner4f9b33d2013-06-27 13:11:22 +00001483 if is_fedora || is_suse; then
Jakub Ruzicka4196d552013-01-30 15:35:54 +01001484 echo "/usr/bin"
1485 else
1486 echo "/usr/local/bin"
1487 fi
1488}
1489
Dean Troyer1a6d4492013-06-03 16:47:36 -05001490
Vincent Untz856a11e2012-11-21 16:04:12 +01001491# Get the location of the $module-rootwrap executables, where module is cinder
1492# or nova.
1493# get_rootwrap_location module
1494function get_rootwrap_location() {
1495 local module=$1
1496
Jakub Ruzicka4196d552013-01-30 15:35:54 +01001497 echo "$(get_python_exec_prefix)/$module-rootwrap"
Vincent Untz856a11e2012-11-21 16:04:12 +01001498}
1499
Dean Troyer1a6d4492013-06-03 16:47:36 -05001500
Vincent Untz8ec27222012-11-29 09:25:31 +01001501# Get the path to the pip command.
1502# get_pip_command
1503function get_pip_command() {
Dean Troyerd2cfcaa2013-08-01 14:17:27 -05001504 which pip || which pip-python
Ian Wienand535a8142013-05-15 09:25:27 +10001505
1506 if [ $? -ne 0 ]; then
1507 die $LINENO "Unable to find pip; cannot continue"
1508 fi
Vincent Untz8ec27222012-11-29 09:25:31 +01001509}
Vincent Untz856a11e2012-11-21 16:04:12 +01001510
Dean Troyer1a6d4492013-06-03 16:47:36 -05001511
Ian Wienand0488edd2013-04-11 12:04:36 +10001512# Path permissions sanity check
1513# check_path_perm_sanity path
1514function check_path_perm_sanity() {
1515 # Ensure no element of the path has 0700 permissions, which is very
1516 # likely to cause issues for daemons. Inspired by default 0700
1517 # homedir permissions on RHEL and common practice of making DEST in
1518 # the stack user's homedir.
1519
1520 local real_path=$(readlink -f $1)
1521 local rebuilt_path=""
1522 for i in $(echo ${real_path} | tr "/" " "); do
1523 rebuilt_path=$rebuilt_path"/"$i
1524
1525 if [[ $(stat -c '%a' ${rebuilt_path}) = 700 ]]; then
1526 echo "*** DEST path element"
1527 echo "*** ${rebuilt_path}"
1528 echo "*** appears to have 0700 permissions."
1529 echo "*** This is very likely to cause fatal issues for devstack daemons."
1530
1531 if [[ -n "$SKIP_PATH_SANITY" ]]; then
1532 return
1533 else
1534 echo "*** Set SKIP_PATH_SANITY to skip this check"
1535 die $LINENO "Invalid path permissions"
1536 fi
1537 fi
1538 done
1539}
1540
Dean Troyer1a6d4492013-06-03 16:47:36 -05001541
Kyle Mestery51a3f1f2013-06-13 11:47:56 +00001542# This function recursively compares versions, and is not meant to be
1543# called by anything other than vercmp_numbers below. This function does
1544# not work with alphabetic versions.
1545#
1546# _vercmp_r sep ver1 ver2
1547function _vercmp_r {
1548 typeset sep
1549 typeset -a ver1=() ver2=()
1550 sep=$1; shift
1551 ver1=("${@:1:sep}")
1552 ver2=("${@:sep+1}")
1553
1554 if ((ver1 > ver2)); then
1555 echo 1; return 0
1556 elif ((ver2 > ver1)); then
1557 echo -1; return 0
1558 fi
1559
1560 if ((sep <= 1)); then
1561 echo 0; return 0
1562 fi
1563
1564 _vercmp_r $((sep-1)) "${ver1[@]:1}" "${ver2[@]:1}"
1565}
1566
1567
1568# This function compares two versions and is meant to be called by
1569# external callers. Please note the function assumes non-alphabetic
1570# versions. For example, this will work:
1571#
1572# vercmp_numbers 1.10 1.4
1573#
1574# The above will return "1", as 1.10 is greater than 1.4.
1575#
1576# vercmp_numbers 5.2 6.4
1577#
1578# The above will return "-1", as 5.2 is less than 6.4.
1579#
1580# vercmp_numbers 4.0 4.0
1581#
1582# The above will return "0", as the versions are equal.
1583#
1584# vercmp_numbers ver1 ver2
1585vercmp_numbers() {
1586 typeset v1=$1 v2=$2 sep
1587 typeset -a ver1 ver2
1588
1589 IFS=. read -ra ver1 <<< "$v1"
1590 IFS=. read -ra ver2 <<< "$v2"
1591
1592 _vercmp_r "${#ver1[@]}" "${ver1[@]}" "${ver2[@]}"
1593}
1594
1595
Dean Troyer27e32692012-03-16 16:16:56 -05001596# Restore xtrace
Chmouel Boudjnah408b0092012-03-15 23:21:55 +00001597$XTRACE
Dean Troyer4a43b7b2012-08-28 17:43:40 -05001598
1599
1600# Local variables:
Sean Dague584d90e2013-03-29 14:34:53 -04001601# mode: shell-script
Andrew Laskif900bd72012-09-05 17:23:14 -04001602# End: