Fix run.sh bug for dynamic interfaces
[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 # Configuration
12
13 [[ "${CI_DEBUG:-true}" == [Tt]rue ]] && set -x
14
15 IMAGE_URL=https://launchpad.net/cirros/trunk/0.3.0/+download/cirros-0.3.0-x86_64-disk.img
16 #if an existing image name is provided in the enviroment, use that one
17 IMAGE_NAME=${IMAGE_NAME:-cirros}
18 IMAGE_FILE="${IMAGE_NAME}.img"
19 IMAGE_FORMAT=qcow2
20 VM_BASENAME=doctor_vm
21 VM_FLAVOR=m1.tiny
22 #if VM_COUNT set, use that instead
23 VM_COUNT=${VM_COUNT:-1}
24 NET_NAME=doctor_net
25 NET_CIDR=192.168.168.0/24
26 ALARM_BASENAME=doctor_alarm
27 CONSUMER_PORT=12346
28 DOCTOR_USER=doctor
29 DOCTOR_PW=doctor
30 DOCTOR_PROJECT=doctor
31 DOCTOR_ROLE=_member_
32 PROFILER_TYPE=${PROFILER_TYPE:-none}
33
34 TOP_DIR=$(cd $(dirname "$0") && pwd)
35
36 as_doctor_user="--os-username $DOCTOR_USER --os-password $DOCTOR_PW
37                 --os-project-name $DOCTOR_PROJECT --os-tenant-name $DOCTOR_PROJECT"
38 # NOTE: ceilometer command still requires '--os-tenant-name'.
39 #ceilometer="ceilometer ${as_doctor_user/--os-project-name/--os-tenant-name}"
40 ceilometer="ceilometer $as_doctor_user"
41 as_admin_user="--os-username admin --os-project-name $DOCTOR_PROJECT
42                --os-tenant-name $DOCTOR_PROJECT"
43
44
45 # Functions
46
47 get_compute_host_info() {
48     # get computer host info which first VM boot in as admin user
49     COMPUTE_HOST=$(openstack $as_admin_user server show ${VM_BASENAME}1 |
50                    grep "OS-EXT-SRV-ATTR:host" | awk '{ print $4 }')
51     compute_host_in_undercloud=${COMPUTE_HOST%%.*}
52     die_if_not_set $LINENO COMPUTE_HOST "Failed to get compute hostname"
53
54     get_compute_ip_from_hostname $COMPUTE_HOST
55
56     echo "COMPUTE_HOST=$COMPUTE_HOST"
57     echo "COMPUTE_IP=$COMPUTE_IP"
58
59     # verify connectivity to target compute host
60     ping -c 1 "$COMPUTE_IP"
61     if [[ $? -ne 0 ]] ; then
62         die $LINENO "Can not ping to computer host"
63     fi
64
65     # verify ssh to target compute host
66     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'exit'
67     if [[ $? -ne 0 ]] ; then
68         die $LINENO "Can not ssh to computer host"
69     fi
70 }
71
72 # TODO(r-mibu): update this function to support consumer instance
73 #               and migrate this function into installer lib
74 get_consumer_ip___to_be_removed() {
75     local get_consumer_command="ip route get $COMPUTE_IP | awk '/ src /{print \$NF}'"
76     if is_installer apex; then
77         CONSUMER_IP=$(sudo ssh $ssh_opts root@$INSTALLER_IP \
78                       "$get_consumer_command")
79     elif is_installer fuel; then
80         CONSUMER_IP=$(sudo sshpass -p r00tme ssh $ssh_opts root@${INSTALLER_IP} \
81                       "$get_consumer_command")
82     elif is_installer local; then
83         CONSUMER_IP=`$get_consumer_command`
84     fi
85     echo "CONSUMER_IP=$CONSUMER_IP"
86
87     die_if_not_set $LINENO CONSUMER_IP "Could not get CONSUMER_IP."
88 }
89
90 download_image() {
91     #if a different name was provided for the image in the enviroment there's no need to download the image
92     use_existing_image=false
93     openstack image list | grep -q " $IMAGE_NAME " && use_existing_image=true
94
95     if [[ "$use_existing_image" == false ]] ; then
96         [ -e "$IMAGE_FILE" ] && return 0
97         wget "$IMAGE_URL" -o "$IMAGE_FILE"
98     fi
99 }
100
101 register_image() {
102     openstack image list | grep -q " $IMAGE_NAME " && return 0
103     openstack image create "$IMAGE_NAME" \
104                            --public \
105                            --disk-format "$IMAGE_FORMAT" \
106                            --container-format bare \
107                            --file "$IMAGE_FILE"
108 }
109
110 create_test_user() {
111     openstack project list | grep -q " $DOCTOR_PROJECT " || {
112         openstack project create --description "Doctor Project" \
113                                  "$DOCTOR_PROJECT"
114     }
115     openstack user list | grep -q " $DOCTOR_USER " || {
116         openstack user create "$DOCTOR_USER" --password "$DOCTOR_PW" \
117                               --project "$DOCTOR_PROJECT"
118     }
119     openstack role show "$DOCTOR_ROLE" | grep -q " $DOCTOR_ROLE " || {
120         openstack role create "$DOCTOR_ROLE"
121     }
122     openstack role assignment list --user "$DOCTOR_USER" \
123     --project "$DOCTOR_PROJECT" --names | grep -q " $DOCTOR_ROLE " || {
124         openstack role add "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
125                            --project "$DOCTOR_PROJECT"
126     }
127     openstack role assignment list --user admin --project "$DOCTOR_PROJECT" \
128     --names | grep -q " admin " || {
129         openstack role add admin --user admin --project "$DOCTOR_PROJECT"
130     }
131     # tojuvone: openstack quota show is broken and have to use nova
132     # https://bugs.launchpad.net/manila/+bug/1652118
133     # Note! while it is encouraged to use openstack client it has proven
134     # quite buggy.
135     # QUOTA=$(openstack quota show $DOCTOR_PROJECT)
136     DOCTOR_QUOTA=$(nova quota-show --tenant $DOCTOR_PROJECT)
137     # We make sure that quota allows number of instances and cores
138     OLD_INSTANCE_QUOTA=$(echo "${DOCTOR_QUOTA}" | grep " instances " | \
139                          awk '{print $4}')
140     if [ $OLD_INSTANCE_QUOTA -lt $VM_COUNT ]; then
141         openstack quota set --instances $VM_COUNT \
142                   $DOCTOR_USER
143     fi
144     OLD_CORES_QUOTA=$(echo "${DOCTOR_QUOTA}" | grep " cores " | \
145                       awk '{print $4}')
146     if [ $OLD_CORES_QUOTA -lt $VM_COUNT ]; then
147         openstack quota set --cores $VM_COUNT \
148                   $DOCTOR_USER
149     fi
150 }
151
152 remove_test_user() {
153     openstack project list | grep -q " $DOCTOR_PROJECT " && {
154         openstack role assignment list --user admin \
155         --project "$DOCTOR_PROJECT" --names | grep -q " admin " && {
156             openstack role remove admin --user admin --project "$DOCTOR_PROJECT"
157         }
158         openstack user list | grep -q " $DOCTOR_USER " && {
159             openstack role assignment list --user "$DOCTOR_USER" \
160             --project "$DOCTOR_PROJECT" --names | grep -q " $DOCTOR_ROLE " && {
161                 openstack role remove "$DOCTOR_ROLE" --user "$DOCTOR_USER" \
162                 --project "$DOCTOR_PROJECT"
163             }
164             openstack user delete "$DOCTOR_USER"
165         }
166         openstack project delete "$DOCTOR_PROJECT"
167     }
168 }
169
170 boot_vm() {
171     # test VM done with test user, so can test non-admin
172
173     if ! openstack $as_doctor_user network show $NET_NAME; then
174         openstack $as_doctor_user network create $NET_NAME
175     fi
176     if ! openstack $as_doctor_user subnet show $NET_NAME; then
177         openstack $as_doctor_user subnet create $NET_NAME \
178             --network $NET_NAME --subnet-range $NET_CIDR --no-dhcp
179     fi
180     net_id=$(openstack $as_doctor_user network show $NET_NAME -f value -c id)
181
182     servers=$(openstack $as_doctor_user server list)
183     for i in `seq $VM_COUNT`; do
184         echo "${servers}" | grep -q " $VM_BASENAME$i " && continue
185         openstack $as_doctor_user server create --flavor "$VM_FLAVOR" \
186             --image "$IMAGE_NAME" --nic net-id=$net_id "$VM_BASENAME$i"
187     done
188     sleep 1
189 }
190
191 create_alarm() {
192     # get vm_id as test user
193     alarm_list=$($ceilometer alarm-list)
194     vms=$(openstack $as_doctor_user server list)
195     for i in `seq $VM_COUNT`; do
196         echo "${alarm_list}" | grep -q " $ALARM_BASENAME$i " || {
197             vm_id=$(echo "${vms}" | grep " $VM_BASENAME$i " | awk '{print $2}')
198             # TODO(r-mibu): change notification endpoint from localhost to the
199             # consumer. IP address (functest container).
200             $ceilometer alarm-event-create \
201                        --name "$ALARM_BASENAME$i" \
202                        --alarm-action "http://localhost:$CONSUMER_PORT/failure" \
203                        --description "VM failure" \
204                        --enabled True \
205                        --repeat-actions False \
206                        --severity "moderate" \
207                        --event-type compute.instance.update \
208                        -q "traits.state=string::error; \
209                        traits.instance_id=string::$vm_id"
210             }
211      done
212 }
213
214 start_monitor() {
215     pgrep -f "python monitor.py" && return 0
216     sudo -E python monitor.py "$COMPUTE_HOST" "$COMPUTE_IP" "$INSPECTOR_TYPE" \
217         > monitor.log 2>&1 &
218 }
219
220 stop_monitor() {
221     pgrep -f "python monitor.py" || return 0
222     sudo kill $(pgrep -f "python monitor.py")
223 }
224
225 start_consumer() {
226     pgrep -f "python consumer.py" && return 0
227     python consumer.py "$CONSUMER_PORT" > consumer.log 2>&1 &
228
229     # NOTE(r-mibu): create tunnel to the controller nodes, so that we can
230     # avoid some network problems dpends on infra and installers.
231     # This tunnel will be terminated by stop_consumer() or after 10 mins passed.
232     if ! is_installer local; then
233         for ip in $CONTROLLER_IPS
234         do
235             forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
236             tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
237             $tunnel_command > "ssh_tunnel.${ip}.log" 2>&1 < /dev/null &
238         done
239     fi
240 }
241
242 stop_consumer() {
243     pgrep -f "python consumer.py" || return 0
244     kill $(pgrep -f "python consumer.py")
245
246     # NOTE(r-mibu): terminate tunnels to the controller nodes
247     if ! is_installer local; then
248         for ip in $CONTROLLER_IPS
249         do
250             forward_rule="-R $CONSUMER_PORT:localhost:$CONSUMER_PORT"
251             tunnel_command="sudo ssh $ssh_opts_cpu $COMPUTE_USER@$ip $forward_rule sleep 600"
252             kill $(pgrep -f "$tunnel_command")
253         done
254     fi
255 }
256
257 wait_for_vm_launch() {
258     echo "waiting for vm launch..."
259
260     count=0
261     while [[ ${count} -lt 60 ]]
262     do
263         active_count=0
264         vms=$(openstack $as_doctor_user server list)
265         for i in `seq $VM_COUNT`; do
266             state=$(echo "${vms}" | grep " $VM_BASENAME$i " | awk '{print $6}')
267             if [[ "$state" == "ACTIVE" ]]; then
268                 active_count=$(($active_count+1))
269             elif [[ "$state" == "ERROR" ]]; then
270                 die $LINENO "vm state $VM_BASENAME$i is ERROR"
271             else
272                 #This VM not yet active
273                 count=$(($count+1))
274                 sleep 5
275                 continue
276             fi
277         done
278         [[ $active_count -eq $VM_COUNT ]] && {
279             echo "get computer host info..."
280             get_compute_host_info
281             VMS_ON_FAILED_HOST=$(openstack $as_doctor_user server list --host \
282                          $COMPUTE_HOST | grep " ${VM_BASENAME}" |  wc -l)
283             return 0
284         }
285         #Not all VMs active
286         count=$(($count+1))
287         sleep 5
288     done
289     die $LINENO "Time out while waiting for VM launch"
290 }
291
292 inject_failure() {
293     echo "disabling network of compute host [$COMPUTE_HOST] for 3 mins..."
294     cat > disable_network.sh << 'END_TXT'
295 #!/bin/bash -x
296 dev=$(sudo ip a | awk '/ @COMPUTE_IP@\//{print $NF}')
297 sleep 1
298 sudo ip link set $dev down
299 echo "doctor set link down at" $(date "+%s.%N")
300 sleep 180
301 sudo ip link set $dev up
302 sleep 1
303 END_TXT
304     sed -i -e "s/@COMPUTE_IP@/$COMPUTE_IP/" disable_network.sh
305     chmod +x disable_network.sh
306     scp $ssh_opts_cpu disable_network.sh "$COMPUTE_USER@$COMPUTE_IP:"
307     ssh $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP" 'nohup ./disable_network.sh > disable_network.log 2>&1 &'
308     # use host time to get rid of potential time sync deviation between nodes
309     triggered=$(date "+%s.%N")
310 }
311
312 wait_consumer() {
313     local interval=1
314     local rounds=$(($1 / $interval))
315     for i in `seq $rounds`; do
316         notified_count=$(grep "doctor consumer notified at" consumer.log | wc -l)
317         if [[ $notified_count -eq  $VMS_ON_FAILED_HOST ]]; then
318             return 0
319         fi
320         sleep $interval
321     done
322     die $LINENO "Consumer hasn't received fault notification."
323 }
324
325 calculate_notification_time() {
326     wait_consumer 60
327     #keep 'at' as the last keyword just before the value, and
328     #use regex to get value instead of the fixed column
329     detected=$(grep "doctor monitor detected at" monitor.log |\
330                sed -e "s/^.* at //")
331     notified=$(grep "doctor consumer notified at" consumer.log |\
332                sed -e "s/^.* at //" | tail -1)
333
334     echo "$notified $detected" | \
335         awk '{
336             d = $1 - $2;
337             if (d < 1 && d > 0) { print d " OK"; exit 0 }
338             else { print d " NG"; exit 1 }
339         }'
340 }
341
342 check_host_status() {
343     # Check host related to first Doctor VM is in wanted state
344     # $1    Expected state
345     # $2    Seconds to wait to have wanted state
346     expected_state=$1
347     local interval=5
348     local rounds=$(($2 / $interval))
349     for i in `seq $rounds`; do
350         host_status_line=$(openstack $as_doctor_user --os-compute-api-version \
351                            2.16 server show ${VM_BASENAME}1 | 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_BASENAME}1"
354         if [[ "$expected_state" =~ "$host_status" ]] ; then
355             echo "${VM_BASENAME}1 showing host_status: $host_status"
356             return 0
357         else
358             sleep $interval
359         fi
360     done
361     if [[ "$expected_state" =~ "$host_status" ]] ; then
362         echo "${VM_BASENAME}1 showing host_status: $host_status"
363     else
364         die $LINENO  "host_status:$host_status not equal to expected_state: $expected_state"
365     fi
366 }
367
368 unset_forced_down_hosts() {
369     # for debug
370     openstack compute service list --service nova-compute
371
372     downed_computes=$(openstack compute service list --service nova-compute \
373                       -f value -c Host -c State | grep ' down$' \
374                       | sed -e 's/ *down$//')
375     echo "downed_computes: $downed_computes"
376     for host in $downed_computes
377     do
378         # TODO(r-mibu): use openstack client
379         #openstack compute service set --up $host nova-compute
380         nova service-force-down --unset $host nova-compute
381     done
382
383     echo "waiting disabled compute host back to be enabled..."
384     wait_until 'openstack compute service list --service nova-compute
385                 -f value -c State | grep -q down' 240 5
386
387     for host in $downed_computes
388     do
389         # TODO(r-mibu): improve 'get_compute_ip_from_hostname'
390         get_compute_ip_from_hostname $host
391         wait_until "! ping -c 1 $COMPUTE_IP" 120 5
392     done
393 }
394
395 collect_logs() {
396     if [[ -n "$COMPUTE_IP" ]];then
397         scp $ssh_opts_cpu "$COMPUTE_USER@$COMPUTE_IP:disable_network.log" .
398     fi
399
400     # TODO(yujunz) collect other logs, e.g. nova, aodh
401 }
402
403 run_profiler() {
404     if [[ "$PROFILER_TYPE" == "poc" ]]; then
405         linkdown=$(grep "doctor set link down at " disable_network.log |\
406                   sed -e "s/^.* at //")
407         vmdown=$(grep "doctor mark vm.* error at" inspector.log |tail -n 1 |\
408                  sed -e "s/^.* at //")
409         hostdown=$(grep "doctor mark host.* down at" inspector.log |\
410                  sed -e "s/^.* at //")
411
412         # TODO(yujunz) check the actual delay to verify time sync status
413         # expected ~1s delay from $trigger to $linkdown
414         relative_start=${linkdown}
415         export DOCTOR_PROFILER_T00=$(python -c \
416           "print(int(($linkdown-$relative_start)*1000))")
417         export DOCTOR_PROFILER_T01=$(python -c \
418           "print(int(($detected-$relative_start)*1000))")
419         export DOCTOR_PROFILER_T03=$(python -c \
420           "print(int(($vmdown-$relative_start)*1000))")
421         export DOCTOR_PROFILER_T04=$(python -c \
422           "print(int(($hostdown-$relative_start)*1000))")
423         export DOCTOR_PROFILER_T09=$(python -c \
424           "print(int(($notified-$relative_start)*1000))")
425
426         python profiler-poc.py >doctor_profiler.log 2>&1
427     fi
428 }
429
430 cleanup() {
431     set +e
432     echo "cleanup..."
433     stop_monitor
434     stop_inspector
435     stop_consumer
436
437     unset_forced_down_hosts
438     collect_logs
439
440     vms=$(openstack $as_doctor_user server list)
441     vmstodel=""
442     for i in `seq $VM_COUNT`; do
443         $(echo "${vms}" | grep -q " $VM_BASENAME$i ") &&
444         vmstodel+=" $VM_BASENAME$i"
445     done
446     [[ $vmstodel ]] && openstack $as_doctor_user server delete $vmstodel
447     alarm_list=$($ceilometer alarm-list)
448     for i in `seq $VM_COUNT`; do
449         alarm_id=$(echo "${alarm_list}" | grep " $ALARM_BASENAME$i " |
450                    awk '{print $2}')
451         [ -n "$alarm_id" ] && $ceilometer alarm-delete "$alarm_id"
452     done
453     openstack $as_doctor_user subnet delete $NET_NAME
454     sleep 1
455     openstack $as_doctor_user network delete $NET_NAME
456     sleep 1
457
458     image_id=$(openstack image list | grep " $IMAGE_NAME " | awk '{print $2}')
459     sleep 1
460     #if an existing image was used, there's no need to remove it here
461     if [[ "$use_existing_image" == false ]] ; then
462         [ -n "$image_id" ] && openstack image delete "$image_id"
463     fi
464
465     remove_test_user
466
467     cleanup_installer
468     cleanup_inspector
469
470     # NOTE: Temporal log printer.
471     for f in $(find . -name '*.log')
472     do
473         echo
474         echo "[$f]"
475         sed -e 's/^/ | /' $f
476         echo
477     done
478 }
479
480 # Main process
481
482 echo "Note: doctor/tests/run.sh has been executed."
483 git log --oneline -1 || true   # ignore even you don't have git installed
484
485 trap cleanup EXIT
486
487 source $TOP_DIR/functions-common
488 source $TOP_DIR/lib/installer
489 source $TOP_DIR/lib/inspector
490
491 setup_installer
492
493 echo "preparing VM image..."
494 download_image
495 register_image
496
497 echo "creating test user..."
498 create_test_user
499
500 echo "creating VM..."
501 boot_vm
502 wait_for_vm_launch
503
504 echo "creating alarm..."
505 #TODO: change back to use, network problems depends on infra and installers
506 #get_consumer_ip
507 create_alarm
508
509 echo "starting doctor sample components..."
510 start_inspector
511 start_monitor
512 start_consumer
513
514 sleep 60
515 echo "injecting host failure..."
516 inject_failure
517
518 check_host_status "(DOWN|UNKNOWN)" 60
519 calculate_notification_time
520 unset_forced_down_hosts
521 collect_logs
522 run_profiler
523
524 echo "done"