f425879a14e82aa65f28e5bf930aeb9bedfda09b
[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     local get_consumer_command="ip route get $COMPUTE_IP | awk '/ src /{print \$NF}'"
209     if [[ "$INSTALLER_TYPE" == "apex" ]] ; then
210         CONSUMER_IP=$(sudo ssh $ssh_opts root@$INSTALLER_IP \
211                       "$get_consumer_command")
212     elif [[ "$INSTALLER_TYPE" == "fuel" ]] ; then
213         CONSUMER_IP=$(sudo sshpass -p r00tme ssh $ssh_opts root@${INSTALLER_IP} \
214                       "$get_consumer_command")
215     elif [[ "$INSTALLER_TYPE" == "local" ]] ; then
216         CONSUMER_IP=`$get_consumer_command`
217     fi
218     echo "CONSUMER_IP=$CONSUMER_IP"
219
220     if [[ -z "$CONSUMER_IP" ]]; then
221         echo "ERROR: Could not get CONSUMER_IP."
222         exit 1
223     fi
224 }
225
226 download_image() {
227     [ -e "$IMAGE_FILE" ] && return 0
228     wget "$IMAGE_URL" -o "$IMAGE_FILE"
229 }
230
231 register_image() {
232     openstack image list | grep -q " $IMAGE_NAME " && return 0
233     openstack image create "$IMAGE_NAME" \
234                            --public \
235                            --disk-format "$IMAGE_FORMAT" \
236                            --container-format bare \
237                            --file "$IMAGE_FILE"
238 }
239
240 create_test_user() {
241     openstack project list | grep -q " $DOCTOR_PROJECT " || {
242         openstack project create "$DOCTOR_PROJECT"
243     }
244     openstack user list | grep -q " $DOCTOR_USER " || {
245         openstack user create "$DOCTOR_USER" --password "$DOCTOR_PW" \
246                               --project "$DOCTOR_PROJECT"
247     }
248     openstack user role list "$DOCTOR_USER" --project "$DOCTOR_PROJECT" \
249     | grep -q " $DOCTOR_ROLE " || {
250         openstack role add "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
251                            --project "$DOCTOR_PROJECT"
252     }
253 }
254
255 boot_vm() {
256     # test VM done with test user, so can test non-admin
257     openstack $as_doctor_user server list | grep -q " $VM_NAME " && return 0
258     openstack $as_doctor_user server create --flavor "$VM_FLAVOR" \
259                             --image "$IMAGE_NAME" \
260                             "$VM_NAME"
261     sleep 1
262 }
263
264 create_alarm() {
265     # get vm_id as test user
266     ceilometer $as_doctor_user alarm-list | grep -q " $ALARM_NAME " && return 0
267     vm_id=$(openstack $as_doctor_user server list | grep " $VM_NAME " | awk '{print $2}')
268     # TODO(r-mibu): change notification endpoint from localhost to the consumer
269     # IP address (functest container).
270     ceilometer $as_doctor_user alarm-event-create --name "$ALARM_NAME" \
271         --alarm-action "http://localhost:$CONSUMER_PORT/failure" \
272         --description "VM failure" \
273         --enabled True \
274         --repeat-actions False \
275         --severity "moderate" \
276         --event-type compute.instance.update \
277         -q "traits.state=string::error; traits.instance_id=string::$vm_id"
278 }
279
280 print_log() {
281     log_file=$1
282     echo "$log_file:"
283     sed -e 's/^/    /' "$log_file"
284 }
285
286 start_monitor() {
287     pgrep -f "python monitor.py" && return 0
288     sudo -E python monitor.py "$COMPUTE_HOST" "$COMPUTE_IP" "$INSPECTOR_TYPE" \
289         "http://127.0.0.1:$INSPECTOR_PORT/events" > monitor.log 2>&1 &
290 }
291
292 stop_monitor() {
293     pgrep -f "python monitor.py" || return 0
294     sudo kill $(pgrep -f "python monitor.py")
295     print_log monitor.log
296 }
297
298 congress_add_rule() {
299     name=$1
300     policy=$2
301     rule=$3
302
303     if ! openstack congress policy rule list $policy | grep -q -e "// Name: $name$" ; then
304         openstack congress policy rule create --name $name $policy "$rule"
305     fi
306 }
307
308 congress_del_rule() {
309     name=$1
310     policy=$2
311
312     if openstack congress policy rule list $policy | grep -q -e "^// Name: $name$" ; then
313         openstack congress policy rule delete $policy $name
314     fi
315 }
316
317 congress_setup_rules() {
318     congress_add_rule host_down classification \
319         'host_down(host) :-
320             doctor:events(hostname=host, type="compute.host.down", status="down")'
321
322     congress_add_rule active_instance_in_host classification \
323         'active_instance_in_host(vmid, host) :-
324             nova:servers(id=vmid, host_name=host, status="ACTIVE")'
325
326     congress_add_rule host_force_down classification \
327         'execute[nova:services.force_down(host, "nova-compute", "True")] :-
328             host_down(host)'
329
330     congress_add_rule error_vm_states classification \
331         'execute[nova:servers.reset_state(vmid, "error")] :-
332             host_down(host),
333             active_instance_in_host(vmid, host)'
334 }
335
336 start_inspector() {
337     if [[ "$INSPECTOR_TYPE" == "sample" ]] ; then
338         pgrep -f "python inspector.py" && return 0
339         python inspector.py "$INSPECTOR_PORT" > inspector.log 2>&1 &
340     elif [[ "$INSPECTOR_TYPE" == "congress" ]] ; then
341         nova_api_min_version="2.11"
342         nova_api_version=$(openstack congress datasource list | \
343                            grep nova | grep -Po "(?<='api_version': ')[^']*")
344         [[ -z $nova_api_version ]] && nova_api_version="2.0"
345         if [[ "$nova_api_version" < "$nova_api_min_version" ]]; then
346             echo "ERROR: Congress Nova datasource API version < $nova_api_min_version ($nova_api_version)"
347             exit 1
348         fi
349         openstack congress driver list | grep -q " doctor "
350         openstack congress datasource list | grep -q " doctor " || {
351             openstack congress datasource create doctor doctor
352         }
353         congress_setup_rules
354     fi
355 }
356
357 stop_inspector() {
358     if [[ "$INSPECTOR_TYPE" == "sample" ]] ; then
359         pgrep -f "python inspector.py" || return 0
360         kill $(pgrep -f "python inspector.py")
361         print_log inspector.log
362     elif [[ "$INSPECTOR_TYPE" == "congress" ]] ; then
363         congress_del_rule host_force_down classification
364         congress_del_rule error_vm_states classification
365         congress_del_rule active_instance_in_host classification
366         congress_del_rule host_down classification
367     fi
368 }
369
370 start_consumer() {
371     pgrep -f "python consumer.py" && return 0
372     python consumer.py "$CONSUMER_PORT" > consumer.log 2>&1 &
373
374     # NOTE(r-mibu): create tunnel to the controller nodes, so that we can
375     # avoid some network problems dpends on infra and installers.
376     # This tunnel will be terminated by stop_consumer() or after 10 mins passed.
377     if [[ "$INSTALLER_TYPE" != "local" ]] ; then
378         if [[ "$INSTALLER_TYPE" == "apex" ]] ; then
379             CONTROLLER_IPS=$(sudo ssh $ssh_opts $INSTALLER_IP \
380                              "source stackrc; \
381                              nova list | grep ' overcloud-controller-[0-9] ' \
382                              | sed -e 's/^.*ctlplane=//' -e 's/ *|\$//'")
383         elif [[ "$INSTALLER_TYPE" == "fuel" ]] ; then
384             CONTROLLER_IPS=$(sshpass -p r00tme ssh 2>/dev/null $ssh_opts root@${INSTALLER_IP} \
385                             "fuel node | grep controller | cut -d '|' -f 5|xargs")
386         fi
387
388         if [[ -z "$CONTROLLER_IPS" ]]; then
389             echo "ERROR: Could not get CONTROLLER_IPS."
390             exit 1
391         fi
392         for ip in $CONTROLLER_IPS
393         do
394             forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
395             tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
396             $tunnel_command > "ssh_tunnel.${ip}.log" 2>&1 < /dev/null &
397         done
398     fi
399 }
400
401 stop_consumer() {
402     pgrep -f "python consumer.py" || return 0
403     kill $(pgrep -f "python consumer.py")
404     print_log consumer.log
405
406     # NOTE(r-mibu): terminate tunnels to the controller nodes
407     if [[ "$INSTALLER_TYPE" != "local" ]] ; then
408         for ip in $CONTROLLER_IPS
409         do
410             forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
411             tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
412             kill $(pgrep -f "$tunnel_command")
413             print_log "ssh_tunnel.${ip}.log"
414         done
415     fi
416 }
417
418 wait_for_vm_launch() {
419     echo "waiting for vm launch..."
420
421     count=0
422     while [[ ${count} -lt 60 ]]
423     do
424         state=$(openstack $as_doctor_user server list | grep " $VM_NAME " | awk '{print $6}')
425         [[ "$state" == "ACTIVE" ]] && return 0
426         [[ "$state" == "ERROR" ]] && echo "vm state is ERROR" && exit 1
427         count=$(($count+1))
428         sleep 1
429     done
430     echo "ERROR: time out while waiting for vm launch"
431     exit 1
432 }
433
434 inject_failure() {
435     echo "disabling network of compute host [$COMPUTE_HOST] for 3 mins..."
436     cat > disable_network.sh << 'END_TXT'
437 #!/bin/bash -x
438 dev=$(sudo ip a | awk '/ @COMPUTE_IP@\//{print $7}')
439 sleep 1
440 sudo ip link set $dev down
441 sleep 180
442 sudo ip link set $dev up
443 sleep 1
444 END_TXT
445     sed -i -e "s/@COMPUTE_IP@/$COMPUTE_IP/" disable_network.sh
446     chmod +x disable_network.sh
447     scp $ssh_opts_cpu disable_network.sh "$COMPUTE_USER@$COMPUTE_IP:"
448     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'nohup ./disable_network.sh > disable_network.log 2>&1 &'
449 }
450
451 calculate_notification_time() {
452     detected=$(grep "doctor monitor detected at" monitor.log | awk '{print $5}')
453     notified=$(grep "doctor consumer notified at" consumer.log | awk '{print $5}')
454     if ! grep -q "doctor consumer notified at" consumer.log ; then
455         echo "ERROR: consumer hasn't received fault notification."
456         exit 1
457     fi
458     echo "$notified $detected" | \
459         awk '{d = $1 - $2; if (d < 1 && d > 0) print d " OK"; else print d " NG"}'
460 }
461
462 check_host_status() {
463     expected_state=$1
464
465     host_status_line=$(openstack $as_doctor_user --os-compute-api-version 2.16 \
466                        server show $VM_NAME | grep "host_status")
467     host_status=$(echo $host_status_line | awk '{print $4}')
468     if [ -z "$host_status" ] ; then
469         echo "ERROR: host_status not reported by: nova show $VM_NAME"
470         exit 1
471     elif [[ "$expected_state" =~ "$host_status" ]] ; then
472         echo "$VM_NAME showing host_status: $host_status"
473     else
474         echo "ERROR: host_status:$host_status not equal to expected_state: $expected_state"
475         exit 1
476     fi
477 }
478
479 cleanup() {
480     set +e
481     echo "cleanup..."
482     stop_monitor
483     stop_inspector
484     stop_consumer
485
486     echo "waiting disabled compute host back to be enabled..."
487     python ./nova_force_down.py "$COMPUTE_HOST" --unset
488     sleep 240
489     check_host_status "UP"
490     scp $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP:disable_network.log" .
491     print_log disable_network.log
492
493     openstack $as_doctor_user server list | grep -q " $VM_NAME " && openstack $as_doctor_user server delete "$VM_NAME"
494     sleep 1
495     alarm_id=$(ceilometer $as_doctor_user alarm-list | grep " $ALARM_NAME " | awk '{print $2}')
496     sleep 1
497     [ -n "$alarm_id" ] && ceilometer $as_doctor_user alarm-delete "$alarm_id"
498     sleep 1
499
500     image_id=$(openstack image list | grep " $IMAGE_NAME " | awk '{print $2}')
501     sleep 1
502     [ -n "$image_id" ] && openstack image delete "$image_id"
503     openstack role remove "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
504                               --project "$DOCTOR_PROJECT"
505     openstack project delete "$DOCTOR_PROJECT"
506     openstack user delete "$DOCTOR_USER"
507
508     restore_test_env
509 }
510
511
512 echo "Note: doctor/tests/run.sh has been executed."
513
514 trap cleanup EXIT
515
516 echo "preparing test env..."
517 get_installer_ip
518 prepare_ssh_to_cloud
519 prepare_test_env
520
521 echo "preparing VM image..."
522 download_image
523 register_image
524
525 echo "creating test user..."
526 create_test_user
527
528 echo "creating VM..."
529 boot_vm
530 wait_for_vm_launch
531 openstack $as_doctor_user server show $VM_NAME
532
533 echo "get computer host info..."
534 get_compute_host_info
535
536 echo "creating alarm..."
537 #TODO: change back to use, network problems depends on infra and installers 
538 #get_consumer_ip
539 create_alarm
540
541 echo "starting doctor sample components..."
542 start_inspector
543 start_monitor
544 start_consumer
545
546 sleep 60
547 echo "injecting host failure..."
548 inject_failure
549 sleep 60
550
551 check_host_status "(DOWN|UNKNOWN)"
552 calculate_notification_time
553
554 echo "done"