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