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