Update stor4nfv install scripts according to opensds aruba release
[stor4nfv.git] / ci / ansible / script / util.sh
1 #!/bin/bash
2
3 # Copyright (c) 2017 Huawei Technologies Co., Ltd. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Echo text to the log file, summary log file and stdout
18 # echo_summary "something to say"
19 function echo_summary {
20     echo -e "$@"
21 }
22
23 wait_for_url() {
24   local url=$1
25   local prefix=${2:-}
26   local wait=${3:-1}
27   local times=${4:-30}
28
29   which curl >/dev/null || {
30     echo_summary "curl must be installed"
31     exit 1
32   }
33
34   local i
35   for i in $(seq 1 "$times"); do
36     local out
37     if out=$(curl --max-time 1 -gkfs "$url" 2>/dev/null); then
38       echo_summary "On try ${i}, ${prefix}: ${out}"
39       return 0
40     fi
41     sleep "${wait}"
42   done
43   echo_summary "Timed out waiting for ${prefix} to answer at ${url}; tried ${times} waiting ${wait} between each"
44   return 1
45 }
46
47 # Prints line number and "message" in error format
48 # err $LINENO "message"
49 err() {
50     local exitcode=$?
51     local xtrace
52     xtrace=$(set +o | grep xtrace)
53     set +o xtrace
54     local msg="[ERROR] ${BASH_SOURCE[2]}:$1 $2"
55     echo "$msg"
56     $xtrace
57     return $exitcode
58 }
59
60 # Prints line number and "message" then exits
61 # die $LINENO "message"
62 die() {
63     local exitcode=$?
64     set +o xtrace
65     local line=$1; shift
66     if [ $exitcode == 0 ]; then
67         exitcode=1
68     fi
69     err "$line" "$*"
70     # Give buffers a second to flush
71     sleep 1
72     exit $exitcode
73 }
74
75 get_default_host_ip() {
76     local host_ip=$1
77     local af=$2
78     # Search for an IP unless an explicit is set by ``HOST_IP`` environment variable
79     if [ -z "$host_ip" ]; then
80         host_ip=""
81         # Find the interface used for the default route
82         host_ip_iface=${host_ip_iface:-$(ip -f "$af" route | awk '/default/ {print $5}' | head -1)}
83         local host_ips
84         host_ips=$(LC_ALL=C ip -f "$af" addr show "${host_ip_iface}" | sed /temporary/d |awk /$af'/ {split($2,parts,"/");  print parts[1]}')
85         local ip
86         for ip in $host_ips; do
87             host_ip=$ip
88             break;
89         done
90     fi
91     echo "$host_ip"
92 }
93