Refactor installers support code
[doctor.git] / tests / run.sh
1 #!/bin/bash -e
2 ##############################################################################
3 # Copyright (c) 2016 NEC Corporation and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11 [[ "${CI_DEBUG:-true}" == [Tt]rue ]] && set -x
12
13 IMAGE_URL=https://launchpad.net/cirros/trunk/0.3.0/+download/cirros-0.3.0-x86_64-disk.img
14 #if an existing image name is provided in the enviroment, use that one
15 IMAGE_NAME=${IMAGE_NAME:-cirros}
16 IMAGE_FILE="${IMAGE_NAME}.img"
17 IMAGE_FORMAT=qcow2
18 VM_NAME=doctor_vm1
19 VM_FLAVOR=m1.tiny
20 ALARM_NAME=doctor_alarm1
21 INSPECTOR_PORT=12345
22 CONSUMER_PORT=12346
23 DOCTOR_USER=doctor
24 DOCTOR_PW=doctor
25 DOCTOR_PROJECT=doctor
26 #TODO: change back to `_member_` when JIRA DOCTOR-55 is done
27 DOCTOR_ROLE=admin
28
29 SUPPORTED_INSPECTOR_TYPES="sample congress"
30 INSPECTOR_TYPE=${INSPECTOR_TYPE:-sample}
31 TOP_DIR=$(cd $(dirname "$0") && pwd)
32
33 ssh_opts="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"
34 as_doctor_user="--os-username $DOCTOR_USER --os-password $DOCTOR_PW
35                 --os-tenant-name $DOCTOR_PROJECT"
36
37 if [[ ! "$SUPPORTED_INSPECTOR_TYPES" =~ "$INSPECTOR_TYPE" ]] ; then
38     echo "ERROR: INSPECTOR_TYPE=$INSPECTOR_TYPE is not supported."
39     exit 1
40 fi
41
42 get_compute_host_info() {
43     # get computer host info which VM boot in
44     COMPUTE_HOST=$(openstack $as_doctor_user server show $VM_NAME |
45                    grep "OS-EXT-SRV-ATTR:host" | awk '{ print $4 }')
46     compute_host_in_undercloud=${COMPUTE_HOST%%.*}
47     die_if_not_set $LINENO COMPUTE_HOST "Failed to get compute hostname"
48
49     if is_installer apex; then
50         COMPUTE_USER=${COMPUTE_USER:-heat-admin}
51         COMPUTE_IP=$(sudo ssh $ssh_opts $INSTALLER_IP \
52              "source stackrc; \
53              nova show $compute_host_in_undercloud \
54              | awk '/ ctlplane network /{print \$5}'")
55     elif is_installer fuel; then
56         COMPUTE_USER=${COMPUTE_USER:-root}
57         node_id=$(echo $compute_host_in_undercloud | cut -d "-" -f 2)
58         COMPUTE_IP=$(sshpass -p r00tme ssh 2>/dev/null $ssh_opts root@${INSTALLER_IP} \
59              "fuel node|awk -F '|' -v id=$node_id '{if (\$1 == id) print \$5}' |xargs")
60     elif is_installer local; then
61         COMPUTE_USER=${COMPUTE_USER:-$(whoami)}
62         COMPUTE_IP=$(getent hosts "$COMPUTE_HOST" | awk '{ print $1 }')
63     fi
64
65     die_if_not_set $LINENO COMPUTE_IP "Could not resolve $COMPUTE_HOST. Either manually set COMPUTE_IP or enable DNS resolution."
66     echo "COMPUTE_HOST=$COMPUTE_HOST"
67     echo "COMPUTE_IP=$COMPUTE_IP"
68
69     # verify connectivity to target compute host
70     ping -c 1 "$COMPUTE_IP"
71     if [[ $? -ne 0 ]] ; then
72         die $LINENO "Can not ping to computer host"
73     fi
74
75     # verify ssh to target compute host
76     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'exit'
77     if [[ $? -ne 0 ]] ; then
78         die $LINENO "Can not ssh to computer host"
79     fi
80 }
81
82 get_consumer_ip() {
83     local get_consumer_command="ip route get $COMPUTE_IP | awk '/ src /{print \$NF}'"
84     if is_installer apex; then
85         CONSUMER_IP=$(sudo ssh $ssh_opts root@$INSTALLER_IP \
86                       "$get_consumer_command")
87     elif is_installer fuel; then
88         CONSUMER_IP=$(sudo sshpass -p r00tme ssh $ssh_opts root@${INSTALLER_IP} \
89                       "$get_consumer_command")
90     elif is_installer local; then
91         CONSUMER_IP=`$get_consumer_command`
92     fi
93     echo "CONSUMER_IP=$CONSUMER_IP"
94
95     die_if_not_set $LINENO CONSUMER_IP "Could not get CONSUMER_IP."
96 }
97
98 download_image() {
99     #if a different name was provided for the image in the enviroment there's no need to download the image
100     use_existing_image=false
101     openstack image list | grep -q " $IMAGE_NAME " && use_existing_image=true
102
103     if [[ "$use_existing_image" == false ]] ; then
104         [ -e "$IMAGE_FILE" ] && return 0
105         wget "$IMAGE_URL" -o "$IMAGE_FILE"
106     fi
107 }
108
109 register_image() {
110     openstack image list | grep -q " $IMAGE_NAME " && return 0
111     openstack image create "$IMAGE_NAME" \
112                            --public \
113                            --disk-format "$IMAGE_FORMAT" \
114                            --container-format bare \
115                            --file "$IMAGE_FILE"
116 }
117
118 create_test_user() {
119     openstack project list | grep -q " $DOCTOR_PROJECT " || {
120         openstack project create "$DOCTOR_PROJECT"
121     }
122     openstack user list | grep -q " $DOCTOR_USER " || {
123         openstack user create "$DOCTOR_USER" --password "$DOCTOR_PW" \
124                               --project "$DOCTOR_PROJECT"
125     }
126     openstack user role list "$DOCTOR_USER" --project "$DOCTOR_PROJECT" \
127     | grep -q " $DOCTOR_ROLE " || {
128         openstack role add "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
129                            --project "$DOCTOR_PROJECT"
130     }
131 }
132
133 boot_vm() {
134     # test VM done with test user, so can test non-admin
135     openstack $as_doctor_user server list | grep -q " $VM_NAME " && return 0
136     openstack $as_doctor_user server create --flavor "$VM_FLAVOR" \
137                             --image "$IMAGE_NAME" \
138                             "$VM_NAME"
139     sleep 1
140 }
141
142 create_alarm() {
143     # get vm_id as test user
144     ceilometer $as_doctor_user alarm-list | grep -q " $ALARM_NAME " && return 0
145     vm_id=$(openstack $as_doctor_user server list | grep " $VM_NAME " | awk '{print $2}')
146     # TODO(r-mibu): change notification endpoint from localhost to the consumer
147     # IP address (functest container).
148     ceilometer $as_doctor_user alarm-event-create --name "$ALARM_NAME" \
149         --alarm-action "http://localhost:$CONSUMER_PORT/failure" \
150         --description "VM failure" \
151         --enabled True \
152         --repeat-actions False \
153         --severity "moderate" \
154         --event-type compute.instance.update \
155         -q "traits.state=string::error; traits.instance_id=string::$vm_id"
156 }
157
158 print_log() {
159     log_file=$1
160     echo "$log_file:"
161     sed -e 's/^/    /' "$log_file"
162 }
163
164 start_monitor() {
165     pgrep -f "python monitor.py" && return 0
166     sudo -E python monitor.py "$COMPUTE_HOST" "$COMPUTE_IP" "$INSPECTOR_TYPE" \
167         "http://127.0.0.1:$INSPECTOR_PORT/events" > monitor.log 2>&1 &
168 }
169
170 stop_monitor() {
171     pgrep -f "python monitor.py" || return 0
172     sudo kill $(pgrep -f "python monitor.py")
173     print_log monitor.log
174 }
175
176 congress_add_rule() {
177     name=$1
178     policy=$2
179     rule=$3
180
181     if ! openstack congress policy rule list $policy | grep -q -e "// Name: $name$" ; then
182         openstack congress policy rule create --name $name $policy "$rule"
183     fi
184 }
185
186 congress_del_rule() {
187     name=$1
188     policy=$2
189
190     if openstack congress policy rule list $policy | grep -q -e "^// Name: $name$" ; then
191         openstack congress policy rule delete $policy $name
192     fi
193 }
194
195 congress_setup_rules() {
196     congress_add_rule host_down classification \
197         'host_down(host) :-
198             doctor:events(hostname=host, type="compute.host.down", status="down")'
199
200     congress_add_rule active_instance_in_host classification \
201         'active_instance_in_host(vmid, host) :-
202             nova:servers(id=vmid, host_name=host, status="ACTIVE")'
203
204     congress_add_rule host_force_down classification \
205         'execute[nova:services.force_down(host, "nova-compute", "True")] :-
206             host_down(host)'
207
208     congress_add_rule error_vm_states classification \
209         'execute[nova:servers.reset_state(vmid, "error")] :-
210             host_down(host),
211             active_instance_in_host(vmid, host)'
212 }
213
214 start_inspector() {
215     if [[ "$INSPECTOR_TYPE" == "sample" ]] ; then
216         pgrep -f "python inspector.py" && return 0
217         python inspector.py "$INSPECTOR_PORT" > inspector.log 2>&1 &
218     elif [[ "$INSPECTOR_TYPE" == "congress" ]] ; then
219         nova_api_min_version="2.11"
220         nova_api_version=$(openstack congress datasource list | \
221                            grep nova | grep -Po "(?<='api_version': ')[^']*")
222         if ! is_set nova_api_version; then
223             nova_api_version="2.0"
224         fi
225         if [[ "$nova_api_version" < "$nova_api_min_version" ]]; then
226             die $LINENO "Congress Nova datasource API version < $nova_api_min_version ($nova_api_version)"
227         fi
228         openstack congress driver list | grep -q " doctor "
229         openstack congress datasource list | grep -q " doctor " || {
230             openstack congress datasource create doctor doctor
231         }
232         congress_setup_rules
233     fi
234 }
235
236 stop_inspector() {
237     if [[ "$INSPECTOR_TYPE" == "sample" ]] ; then
238         pgrep -f "python inspector.py" || return 0
239         kill $(pgrep -f "python inspector.py")
240         print_log inspector.log
241     elif [[ "$INSPECTOR_TYPE" == "congress" ]] ; then
242         congress_del_rule host_force_down classification
243         congress_del_rule error_vm_states classification
244         congress_del_rule active_instance_in_host classification
245         congress_del_rule host_down classification
246     fi
247 }
248
249 start_consumer() {
250     pgrep -f "python consumer.py" && return 0
251     python consumer.py "$CONSUMER_PORT" > consumer.log 2>&1 &
252
253     # NOTE(r-mibu): create tunnel to the controller nodes, so that we can
254     # avoid some network problems dpends on infra and installers.
255     # This tunnel will be terminated by stop_consumer() or after 10 mins passed.
256     if ! is_installer local; then
257         if is_installer apex; then
258             CONTROLLER_IPS=$(sudo ssh $ssh_opts $INSTALLER_IP \
259                              "source stackrc; \
260                              nova list | grep ' overcloud-controller-[0-9] ' \
261                              | sed -e 's/^.*ctlplane=//' -e 's/ *|\$//'")
262         elif is_installer fuel; then
263             CONTROLLER_IPS=$(sshpass -p r00tme ssh 2>/dev/null $ssh_opts root@${INSTALLER_IP} \
264                             "fuel node | grep controller | cut -d '|' -f 5|xargs")
265         fi
266
267         die_if_not_set $LINENO CONTROLLER_IPS "Could not get CONTROLLER_IPS."
268         for ip in $CONTROLLER_IPS
269         do
270             forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
271             tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
272             $tunnel_command > "ssh_tunnel.${ip}.log" 2>&1 < /dev/null &
273         done
274     fi
275 }
276
277 stop_consumer() {
278     pgrep -f "python consumer.py" || return 0
279     kill $(pgrep -f "python consumer.py")
280     print_log consumer.log
281
282     # NOTE(r-mibu): terminate tunnels to the controller nodes
283     if ! is_installer local; then
284         for ip in $CONTROLLER_IPS
285         do
286             forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
287             tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
288             kill $(pgrep -f "$tunnel_command")
289             print_log "ssh_tunnel.${ip}.log"
290         done
291     fi
292 }
293
294 wait_for_vm_launch() {
295     echo "waiting for vm launch..."
296
297     count=0
298     while [[ ${count} -lt 60 ]]
299     do
300         state=$(openstack $as_doctor_user server list | grep " $VM_NAME " | awk '{print $6}')
301         if [[ "$state" == "ACTIVE" ]]; then
302             # NOTE(cgoncalves): sleeping for a bit to stabilize
303             # See python-openstackclient/functional/tests/compute/v2/test_server.py:wait_for_status
304             sleep 5
305             return 0
306         fi
307         if [[ "$state" == "ERROR" ]]; then
308             die $LINENO "vm state is ERROR"
309         fi
310         count=$(($count+1))
311         sleep 1
312     done
313     die $LINENO "Time out while waiting for VM launch"
314 }
315
316 inject_failure() {
317     echo "disabling network of compute host [$COMPUTE_HOST] for 3 mins..."
318     cat > disable_network.sh << 'END_TXT'
319 #!/bin/bash -x
320 dev=$(sudo ip a | awk '/ @COMPUTE_IP@\//{print $7}')
321 sleep 1
322 sudo ip link set $dev down
323 sleep 180
324 sudo ip link set $dev up
325 sleep 1
326 END_TXT
327     sed -i -e "s/@COMPUTE_IP@/$COMPUTE_IP/" disable_network.sh
328     chmod +x disable_network.sh
329     scp $ssh_opts_cpu disable_network.sh "$COMPUTE_USER@$COMPUTE_IP:"
330     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'nohup ./disable_network.sh > disable_network.log 2>&1 &'
331 }
332
333 calculate_notification_time() {
334     detected=$(grep "doctor monitor detected at" monitor.log | awk '{print $10}')
335     notified=$(grep "doctor consumer notified at" consumer.log | awk '{print $10}')
336     if ! grep -q "doctor consumer notified at" consumer.log ; then
337         die $LINENO "Consumer hasn't received fault notification."
338     fi
339     echo "$notified $detected" | \
340         awk '{
341             d = $1 - $2;
342             if (d < 1 && d > 0) { print d " OK"; exit 0 }
343             else { print d " NG"; exit 1 }
344         }'
345 }
346
347 check_host_status() {
348     expected_state=$1
349
350     host_status_line=$(openstack $as_doctor_user --os-compute-api-version 2.16 \
351                        server show $VM_NAME | grep "host_status")
352     host_status=$(echo $host_status_line | awk '{print $4}')
353     die_if_not_set $LINENO host_status "host_status not reported by: nova show $VM_NAME"
354     if [[ "$expected_state" =~ "$host_status" ]] ; then
355         echo "$VM_NAME showing host_status: $host_status"
356     else
357         die $LINENO "host_status:$host_status not equal to expected_state: $expected_state"
358     fi
359 }
360
361 cleanup() {
362     set +e
363     echo "cleanup..."
364     stop_monitor
365     stop_inspector
366     stop_consumer
367
368     echo "waiting disabled compute host back to be enabled..."
369     python ./nova_force_down.py "$COMPUTE_HOST" --unset
370     sleep 240
371     check_host_status "UP"
372     scp $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP:disable_network.log" .
373     print_log disable_network.log
374
375     openstack $as_doctor_user server list | grep -q " $VM_NAME " && openstack $as_doctor_user server delete "$VM_NAME"
376     sleep 1
377     alarm_id=$(ceilometer $as_doctor_user alarm-list | grep " $ALARM_NAME " | awk '{print $2}')
378     sleep 1
379     [ -n "$alarm_id" ] && ceilometer $as_doctor_user alarm-delete "$alarm_id"
380     sleep 1
381
382     image_id=$(openstack image list | grep " $IMAGE_NAME " | awk '{print $2}')
383     sleep 1
384     #if an existing image was used, there's no need to remove it here
385     if [[ "$use_existing_image" == false ]] ; then
386         [ -n "$image_id" ] && openstack image delete "$image_id"
387     fi
388     openstack role remove "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
389                               --project "$DOCTOR_PROJECT"
390     openstack project delete "$DOCTOR_PROJECT"
391     openstack user delete "$DOCTOR_USER"
392
393     cleanup_installer
394 }
395
396
397 echo "Note: doctor/tests/run.sh has been executed."
398
399 trap cleanup EXIT
400
401 source $TOP_DIR/functions-common
402 source $TOP_DIR/lib/installer
403
404 setup_installer
405
406 echo "preparing VM image..."
407 download_image
408 register_image
409
410 echo "creating test user..."
411 create_test_user
412
413 echo "creating VM..."
414 boot_vm
415 wait_for_vm_launch
416
417 echo "get computer host info..."
418 get_compute_host_info
419
420 echo "creating alarm..."
421 #TODO: change back to use, network problems depends on infra and installers
422 #get_consumer_ip
423 create_alarm
424
425 echo "starting doctor sample components..."
426 start_inspector
427 start_monitor
428 start_consumer
429
430 sleep 60
431 echo "injecting host failure..."
432 inject_failure
433 sleep 60
434
435 check_host_status "(DOWN|UNKNOWN)"
436 calculate_notification_time
437
438 echo "done"