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