a972c35d998799f60160f7a39df9704cb8218bd9
[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" != "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 prepare_test_env() {
90     #TODO delete it when fuel support the configuration
91     if [[ "$INSTALLER_TYPE" == "fuel" ]] ; then
92         echo "modify the ceilometer event_pipeline configuration..."
93         cat > set_alarm_event_conf.sh << 'END_TXT'
94 #!/bin/bash
95 if [ -e /etc/ceilometer/event_pipeline.yaml ]; then
96     if ! grep -q '^ *- notifier://?topic=alarm.all$' /etc/ceilometer/event_pipeline.yaml; then
97         sed -i 's|- notifier://|- notifier://?topic=alarm.all|' /etc/ceilometer/event_pipeline.yaml
98         echo "modify the ceilometer config"
99         service ceilometer-agent-notification restart
100     fi
101 else
102     echo "ceilometer event_pipeline.yaml file does not exist"
103     exit 1
104 fi
105 exit 0
106 END_TXT
107         chmod +x set_alarm_event_conf.sh
108         CONTROLLER_IP=$(sshpass -p r00tme ssh 2>/dev/null $ssh_opts root@${INSTALLER_IP} \
109              "fuel node | grep controller | cut -d '|' -f 5|xargs")
110         for node in $CONTROLLER_IP;do
111             scp $ssh_opts_cpu set_alarm_event_conf.sh "root@$node:"
112             ssh $ssh_opts_cpu "root@$node" './set_alarm_event_conf.sh > set_alarm_event_conf.log 2>&1 &'
113             sleep 1
114             scp $ssh_opts_cpu "root@$node:set_alarm_event_conf.log" set_alarm_event_conf_$node.log
115         done
116
117         if grep -q "modify the ceilometer config" set_alarm_event_conf_*.log ; then
118             NEED_TO_RESTORE=true
119         fi
120
121         echo "waiting ceilometer-agent-notification restart..."
122         sleep 60
123     fi
124 }
125
126 restore_test_env() {
127     #TODO delete it when fuel support the configuration
128     if [[ "$INSTALLER_TYPE" == "fuel" ]] ; then
129         if ! $NEED_TO_RESTORE ; then
130             echo "Don't need to restore config"
131             exit 0
132         fi
133
134         echo "restore the ceilometer event_pipeline configuration..."
135         cat > restore_alarm_event_conf.sh << 'END_TXT'
136 #!/bin/bash
137 if [ -e /etc/ceilometer/event_pipeline.yaml ]; then
138     if grep -q '^ *- notifier://?topic=alarm.all$' /etc/ceilometer/event_pipeline.yaml; then
139         sed -i 's|- notifier://?topic=alarm.all|- notifier://|' /etc/ceilometer/event_pipeline.yaml
140         service ceilometer-agent-notification restart
141     fi
142 else
143     echo "ceilometer event_pipeline.yaml file does not exist"
144     exit 1
145 fi
146 exit 0
147 END_TXT
148         chmod +x restore_alarm_event_conf.sh
149         for node in $CONTROLLER_IP;do
150             scp $ssh_opts_cpu restore_alarm_event_conf.sh "root@$node:"
151             ssh $ssh_opts_cpu "root@$node" './restore_alarm_event_conf.sh > set_alarm_event_conf.log 2>&1 &'
152         done
153
154         echo "waiting ceilometer-agent-notification restart..."
155         sleep 60
156     fi
157 }
158
159 get_compute_host_info() {
160     # get computer host info which VM boot in
161     COMPUTE_HOST=$(openstack $as_doctor_user server show $VM_NAME |
162                    grep "OS-EXT-SRV-ATTR:host" | awk '{ print $4 }')
163     compute_host_in_undercloud=${COMPUTE_HOST%%.*}
164     if [[ -z "$COMPUTE_HOST" ]] ; then
165         echo "ERROR: failed to get compute hostname"
166         exit 1
167     fi
168
169     if [[ "$INSTALLER_TYPE" == "apex" ]] ; then
170         COMPUTE_USER=${COMPUTE_USER:-heat-admin}
171         COMPUTE_IP=$(sudo ssh $ssh_opts $INSTALLER_IP \
172              "source stackrc; \
173              nova show $compute_host_in_undercloud \
174              | awk '/ ctlplane network /{print \$5}'")
175     elif [[ "$INSTALLER_TYPE" == "fuel" ]] ; then
176         COMPUTE_USER=${COMPUTE_USER:-root}
177         node_id=$(echo $compute_host_in_undercloud | cut -d "-" -f 2)
178         COMPUTE_IP=$(sshpass -p r00tme ssh 2>/dev/null $ssh_opts root@${INSTALLER_IP} \
179              "fuel node|awk -F '|' -v id=$node_id '{if (\$1 == id) print \$5}' |xargs")
180     elif [[ "$INSTALLER_TYPE" == "local" ]] ; then
181         COMPUTE_USER=${COMPUTE_USER:-$(whoami)}
182         COMPUTE_IP=$(getent hosts "$COMPUTE_HOST" | awk '{ print $1 }')
183     fi
184
185     if [[ -z "$COMPUTE_IP" ]]; then
186         echo "ERROR: Could not resolve $COMPUTE_HOST. Either manually set COMPUTE_IP or enable DNS resolution."
187         exit 1
188     fi
189     echo "COMPUTE_HOST=$COMPUTE_HOST"
190     echo "COMPUTE_IP=$COMPUTE_IP"
191
192     # verify connectivity to target compute host
193     ping -c 1 "$COMPUTE_IP"
194     if [[ $? -ne 0 ]] ; then
195         echo "ERROR: can not ping to computer host"
196         exit 1
197     fi
198
199     # verify ssh to target compute host
200     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'exit'
201     if [[ $? -ne 0 ]] ; then
202         echo "ERROR: can not ssh to computer host"
203         exit 1
204     fi
205 }
206
207 get_consumer_ip() {
208     CONSUMER_IP=$(sudo ssh $ssh_opts root@$INSTALLER_IP \
209                   "ip route get $COMPUTE_IP | awk '/ src /{print \$NF}'")
210     echo "CONSUMER_IP=$CONSUMER_IP"
211
212     if [[ -z "$CONSUMER_IP" ]]; then
213         echo "ERROR: Could not get CONSUMER_IP."
214         exit 1
215     fi
216 }
217
218 download_image() {
219     [ -e "$IMAGE_FILE" ] && return 0
220     wget "$IMAGE_URL" -o "$IMAGE_FILE"
221 }
222
223 register_image() {
224     openstack image list | grep -q " $IMAGE_NAME " && return 0
225     openstack image create "$IMAGE_NAME" \
226                            --public \
227                            --disk-format "$IMAGE_FORMAT" \
228                            --container-format bare \
229                            --file "$IMAGE_FILE"
230 }
231
232 create_test_user() {
233     openstack project list | grep -q " $DOCTOR_PROJECT " || {
234         openstack project create "$DOCTOR_PROJECT"
235     }
236     openstack user list | grep -q " $DOCTOR_USER " || {
237         openstack user create "$DOCTOR_USER" --password "$DOCTOR_PW" \
238                               --project "$DOCTOR_PROJECT"
239     }
240     openstack user role list "$DOCTOR_USER" --project "$DOCTOR_PROJECT" \
241     | grep -q " $DOCTOR_ROLE " || {
242         openstack role add "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
243                            --project "$DOCTOR_PROJECT"
244     }
245 }
246
247 boot_vm() {
248     # test VM done with test user, so can test non-admin
249     openstack $as_doctor_user server list | grep -q " $VM_NAME " && return 0
250     openstack $as_doctor_user server create --flavor "$VM_FLAVOR" \
251                             --image "$IMAGE_NAME" \
252                             "$VM_NAME"
253     sleep 1
254 }
255
256 create_alarm() {
257     # get vm_id as test user
258     ceilometer $as_doctor_user alarm-list | grep -q " $ALARM_NAME " && return 0
259     vm_id=$(openstack $as_doctor_user server list | grep " $VM_NAME " | awk '{print $2}')
260     # TODO(r-mibu): change notification endpoint from localhost to the consumer
261     # IP address (functest container).
262     ceilometer $as_doctor_user alarm-event-create --name "$ALARM_NAME" \
263         --alarm-action "http://localhost:$CONSUMER_PORT/failure" \
264         --description "VM failure" \
265         --enabled True \
266         --repeat-actions False \
267         --severity "moderate" \
268         --event-type compute.instance.update \
269         -q "traits.state=string::error; traits.instance_id=string::$vm_id"
270 }
271
272 print_log() {
273     log_file=$1
274     echo "$log_file:"
275     sed -e 's/^/    /' "$log_file"
276 }
277
278 start_monitor() {
279     pgrep -f "python monitor.py" && return 0
280     sudo -E python monitor.py "$COMPUTE_HOST" "$COMPUTE_IP" "$INSPECTOR_TYPE" \
281         "http://127.0.0.1:$INSPECTOR_PORT/events" > monitor.log 2>&1 &
282 }
283
284 stop_monitor() {
285     pgrep -f "python monitor.py" || return 0
286     sudo kill $(pgrep -f "python monitor.py")
287     print_log monitor.log
288 }
289
290 congress_add_rule() {
291     name=$1
292     policy=$2
293     rule=$3
294
295     if ! openstack congress policy rule list $policy | grep -q -e "// Name: $name$" ; then
296         openstack congress policy rule create --name $name $policy "$rule"
297     fi
298 }
299
300 congress_del_rule() {
301     name=$1
302     policy=$2
303
304     if openstack congress policy rule list $policy | grep -q -e "^// Name: $name$" ; then
305         openstack congress policy rule delete $policy $name
306     fi
307 }
308
309 congress_setup_rules() {
310     congress_add_rule host_down classification \
311         'host_down(host) :-
312             doctor:events(hostname=host, type="compute.host.down", status="down")'
313
314     congress_add_rule active_instance_in_host classification \
315         'active_instance_in_host(vmid, host) :-
316             nova:servers(id=vmid, host_name=host, status="ACTIVE")'
317
318     congress_add_rule host_force_down classification \
319         'execute[nova:services.force_down(host, "nova-compute", "True")] :-
320             host_down(host)'
321
322     congress_add_rule error_vm_states classification \
323         'execute[nova:servers.reset_state(vmid, "error")] :-
324             host_down(host),
325             active_instance_in_host(vmid, host)'
326 }
327
328 start_inspector() {
329     if [[ "$INSPECTOR_TYPE" == "sample" ]] ; then
330         pgrep -f "python inspector.py" && return 0
331         python inspector.py "$INSPECTOR_PORT" > inspector.log 2>&1 &
332     elif [[ "$INSPECTOR_TYPE" == "congress" ]] ; then
333         nova_api_min_version="2.11"
334         nova_api_version=$(openstack congress datasource list | \
335                            grep nova | grep -Po "(?<='api_version': ')[^']*")
336         [[ -z $nova_api_version ]] && nova_api_version="2.0"
337         if [[ "$nova_api_version" < "$nova_api_min_version" ]]; then
338             echo "ERROR: Congress Nova datasource API version < $nova_api_min_version ($nova_api_version)"
339             exit 1
340         fi
341         openstack congress driver list | grep -q " doctor "
342         openstack congress datasource list | grep -q " doctor " || {
343             openstack congress datasource create doctor doctor
344         }
345         congress_setup_rules
346     fi
347 }
348
349 stop_inspector() {
350     if [[ "$INSPECTOR_TYPE" == "sample" ]] ; then
351         pgrep -f "python inspector.py" || return 0
352         kill $(pgrep -f "python inspector.py")
353         print_log inspector.log
354     elif [[ "$INSPECTOR_TYPE" == "congress" ]] ; then
355         congress_del_rule host_force_down classification
356         congress_del_rule error_vm_states classification
357         congress_del_rule active_instance_in_host classification
358         congress_del_rule host_down classification
359     fi
360 }
361
362 start_consumer() {
363     pgrep -f "python consumer.py" && return 0
364     python consumer.py "$CONSUMER_PORT" > consumer.log 2>&1 &
365
366     # NOTE(r-mibu): create tunnel to the controller nodes, so that we can
367     # avoid some network problems dpends on infra and installers.
368     # This tunnel will be terminated by stop_consumer() or after 10 mins passed.
369     if [[ "$INSTALLER_TYPE" == "apex" ]] ; then
370         CONTROLLER_IPS=$(sudo ssh $ssh_opts $INSTALLER_IP \
371                          "source stackrc; \
372                          nova list | grep ' overcloud-controller-[0-9] ' \
373                          | sed -e 's/^.*ctlplane=//' -e 's/ *|\$//'")
374     fi
375     if [[ -z "$CONTROLLER_IPS" ]]; then
376         echo "ERROR: Could not get CONTROLLER_IPS."
377         exit 1
378     fi
379     for ip in $CONTROLLER_IPS
380     do
381         forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
382         tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
383         $tunnel_command > "ssh_tunnel.${ip}.log" 2>&1 < /dev/null &
384     done
385 }
386
387 stop_consumer() {
388     pgrep -f "python consumer.py" || return 0
389     kill $(pgrep -f "python consumer.py")
390     print_log consumer.log
391
392     # NOTE(r-mibu): terminate tunnels to the controller nodes
393     for ip in $CONTROLLER_IPS
394     do
395         forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
396         tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
397         kill $(pgrep -f "$tunnel_command")
398         print_log "ssh_tunnel.${ip}.log"
399     done
400 }
401
402 wait_for_vm_launch() {
403     echo "waiting for vm launch..."
404
405     count=0
406     while [[ ${count} -lt 60 ]]
407     do
408         state=$(openstack $as_doctor_user server list | grep " $VM_NAME " | awk '{print $6}')
409         [[ "$state" == "ACTIVE" ]] && return 0
410         [[ "$state" == "ERROR" ]] && echo "vm state is ERROR" && exit 1
411         count=$(($count+1))
412         sleep 1
413     done
414     echo "ERROR: time out while waiting for vm launch"
415     exit 1
416 }
417
418 inject_failure() {
419     echo "disabling network of compute host [$COMPUTE_HOST] for 3 mins..."
420     cat > disable_network.sh << 'END_TXT'
421 #!/bin/bash -x
422 dev=$(sudo ip a | awk '/ @COMPUTE_IP@\//{print $7}')
423 sleep 1
424 sudo ip link set $dev down
425 sleep 180
426 sudo ip link set $dev up
427 sleep 1
428 END_TXT
429     sed -i -e "s/@COMPUTE_IP@/$COMPUTE_IP/" disable_network.sh
430     chmod +x disable_network.sh
431     scp $ssh_opts_cpu disable_network.sh "$COMPUTE_USER@$COMPUTE_IP:"
432     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'nohup ./disable_network.sh > disable_network.log 2>&1 &'
433 }
434
435 calculate_notification_time() {
436     detected=$(grep "doctor monitor detected at" monitor.log | awk '{print $5}')
437     notified=$(grep "doctor consumer notified at" consumer.log | awk '{print $5}')
438     if ! grep -q "doctor consumer notified at" consumer.log ; then
439         echo "ERROR: consumer hasn't received fault notification."
440         exit 1
441     fi
442     echo "$notified $detected" | \
443         awk '{d = $1 - $2; if (d < 1 && d > 0) print d " OK"; else print d " NG"}'
444 }
445
446 check_host_status() {
447     expected_state=$1
448
449     host_status_line=$(openstack $as_doctor_user --os-compute-api-version 2.16 \
450                        server show $VM_NAME | grep "host_status")
451     host_status=$(echo $host_status_line | awk '{print $4}')
452     if [ -z "$host_status" ] ; then
453         echo "ERROR: host_status not reported by: nova show $VM_NAME"
454         exit 1
455     elif [[ "$expected_state" =~ "$host_status" ]] ; then
456         echo "$VM_NAME showing host_status: $host_status"
457     else
458         echo "ERROR: host_status:$host_status not equal to expected_state: $expected_state"
459         exit 1
460     fi
461 }
462
463 cleanup() {
464     set +e
465     echo "cleanup..."
466     stop_monitor
467     stop_inspector
468     stop_consumer
469
470     echo "waiting disabled compute host back to be enabled..."
471     python ./nova_force_down.py "$COMPUTE_HOST" --unset
472     sleep 240
473     check_host_status "UP"
474     scp $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP:disable_network.log" .
475     print_log disable_network.log
476
477     openstack $as_doctor_user server list | grep -q " $VM_NAME " && openstack $as_doctor_user server delete "$VM_NAME"
478     sleep 1
479     alarm_id=$(ceilometer $as_doctor_user alarm-list | grep " $ALARM_NAME " | awk '{print $2}')
480     sleep 1
481     [ -n "$alarm_id" ] && ceilometer $as_doctor_user alarm-delete "$alarm_id"
482     sleep 1
483
484     image_id=$(openstack image list | grep " $IMAGE_NAME " | awk '{print $2}')
485     sleep 1
486     [ -n "$image_id" ] && openstack image delete "$image_id"
487     openstack role remove "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
488                               --project "$DOCTOR_PROJECT"
489     openstack project delete "$DOCTOR_PROJECT"
490     openstack user delete "$DOCTOR_USER"
491
492     restore_test_env
493 }
494
495
496 echo "Note: doctor/tests/run.sh has been executed."
497
498 trap cleanup EXIT
499
500 echo "preparing test env..."
501 get_installer_ip
502 prepare_ssh_to_cloud
503 prepare_test_env
504
505 echo "preparing VM image..."
506 download_image
507 register_image
508
509 echo "creating test user..."
510 create_test_user
511
512 echo "creating VM..."
513 boot_vm
514 wait_for_vm_launch
515 openstack $as_doctor_user server show $VM_NAME
516
517 echo "get computer host info..."
518 get_compute_host_info
519
520 echo "creating alarm..."
521 get_consumer_ip
522 create_alarm
523
524 echo "starting doctor sample components..."
525 start_inspector
526 start_monitor
527 start_consumer
528
529 sleep 60
530 echo "injecting host failure..."
531 inject_failure
532 sleep 60
533
534 check_host_status "(DOWN|UNKNOWN)"
535 calculate_notification_time
536
537 echo "done"