ctdb-tests: Actually restart if cluster doesn't become healthy
[samba.git] / ctdb / tests / scripts / integration.bash
1 # Hey Emacs, this is a -*- shell-script -*- !!!  :-)
2
3 . "${TEST_SCRIPTS_DIR}/common.sh"
4
5 ######################################################################
6
7 export CTDB_TIMEOUT=60
8
9 if [ -n "$CTDB_TEST_REMOTE_DIR" ] ; then
10     CTDB_TEST_WRAPPER="${CTDB_TEST_REMOTE_DIR}/test_wrap"
11 else
12     _d=$(cd ${TEST_SCRIPTS_DIR}; echo $PWD)
13     CTDB_TEST_WRAPPER="$_d/test_wrap"
14 fi
15 export CTDB_TEST_WRAPPER
16
17 # If $VALGRIND is set then use it whenever ctdb is called, but only if
18 # $CTDB is not already set.
19 [ -n "$CTDB" ] || export CTDB="${VALGRIND}${VALGRIND:+ }ctdb"
20
21 # why???
22 PATH="${TEST_SCRIPTS_DIR}:${PATH}"
23
24 ######################################################################
25
26 ctdb_test_exit ()
27 {
28     local status=$?
29
30     trap - 0
31
32     # run_tests.sh pipes stdout into tee.  If the tee process is
33     # killed then any attempt to write to stdout (e.g. echo) will
34     # result in SIGPIPE, terminating the caller.  Ignore SIGPIPE to
35     # ensure that all clean-up is run.
36     trap '' PIPE
37
38     # Avoid making a test fail from this point onwards.  The test is
39     # now complete.
40     set +e
41
42     echo "*** TEST COMPLETED (RC=$status) AT $(date '+%F %T'), CLEANING UP..."
43
44     eval "$ctdb_test_exit_hook" || true
45     unset ctdb_test_exit_hook
46
47     echo "Stopping cluster..."
48     ctdb_stop_all
49
50     exit $status
51 }
52
53 ctdb_test_exit_hook_add ()
54 {
55     ctdb_test_exit_hook="${ctdb_test_exit_hook}${ctdb_test_exit_hook:+ ; }$*"
56 }
57
58 ctdb_test_init ()
59 {
60         trap "ctdb_test_exit" 0
61
62         ctdb_stop_all >/dev/null 2>&1 || true
63
64         echo "Configuring cluster..."
65         setup_ctdb "$@" || exit 1
66
67         echo "Starting cluster..."
68         ctdb_init || exit 1
69
70         echo  "*** SETUP COMPLETE AT $(date '+%F %T'), RUNNING TEST..."
71 }
72
73 ########################################
74
75 # Sets: $out, $outfile
76 # * The first 1KB of output is put into $out
77 # * Tests should use $outfile for handling large output
78 # * $outfile is removed after each test
79 out=""
80 outfile="${TEST_VAR_DIR}/try_command_on_node.out"
81
82 outfile_cleanup ()
83 {
84         rm -f "$outfile"
85 }
86
87 ctdb_test_exit_hook_add outfile_cleanup
88
89 try_command_on_node ()
90 {
91     local nodespec="$1" ; shift
92
93     local verbose=false
94     local onnode_opts=""
95
96     while [ "${nodespec#-}" != "$nodespec" ] ; do
97         if [ "$nodespec" = "-v" ] ; then
98             verbose=true
99         else
100             onnode_opts="${onnode_opts}${onnode_opts:+ }${nodespec}"
101         fi
102         nodespec="$1" ; shift
103     done
104
105     local cmd="$*"
106
107     if ! onnode -q $onnode_opts "$nodespec" "$cmd" >"$outfile" 2>&1 ; then
108         echo "Failed to execute \"$cmd\" on node(s) \"$nodespec\""
109         cat "$outfile"
110         return 1
111     fi
112
113     if $verbose ; then
114         echo "Output of \"$cmd\":"
115         cat "$outfile"
116     fi
117
118     out=$(dd if="$outfile" bs=1k count=1 2>/dev/null)
119 }
120
121 sanity_check_output ()
122 {
123     local min_lines="$1"
124     local regexp="$2" # Should be anchored as necessary.
125
126     local ret=0
127
128     local num_lines=$(wc -l <"$outfile")
129     echo "There are $num_lines lines of output"
130     if [ $num_lines -lt $min_lines ] ; then
131         echo "BAD: that's less than the required number (${min_lines})"
132         ret=1
133     fi
134
135     local status=0
136     local unexpected # local doesn't pass through status of command on RHS.
137     unexpected=$(grep -Ev "$regexp" "$outfile") || status=$?
138
139     # Note that this is reversed.
140     if [ $status -eq 0 ] ; then
141         echo "BAD: unexpected lines in output:"
142         echo "$unexpected" | cat -A
143         ret=1
144     else
145         echo "Output lines look OK"
146     fi
147
148     return $ret
149 }
150
151 # This returns a list of "ip node" lines in $outfile
152 all_ips_on_node()
153 {
154     local node="$1"
155     try_command_on_node $node \
156         "$CTDB ip -X | awk -F'|' 'NR > 1 { print \$2, \$3 }'"
157 }
158
159 _select_test_node_and_ips ()
160 {
161     try_command_on_node any \
162         "$CTDB ip -X all | awk -F'|' 'NR > 1 { print \$2, \$3 }'"
163
164     test_node=""  # this matches no PNN
165     test_node_ips=""
166     local ip pnn
167     while read ip pnn ; do
168         if [ -z "$test_node" -a "$pnn" != "-1" ] ; then
169             test_node="$pnn"
170         fi
171         if [ "$pnn" = "$test_node" ] ; then
172             test_node_ips="${test_node_ips}${test_node_ips:+ }${ip}"
173         fi
174     done <"$outfile"
175
176     echo "Selected node ${test_node} with IPs: ${test_node_ips}."
177     test_ip="${test_node_ips%% *}"
178
179     case "$test_ip" in
180         *:*) test_prefix="${test_ip}/128" ;;
181         *)   test_prefix="${test_ip}/32"  ;;
182     esac
183
184     [ -n "$test_node" ] || return 1
185 }
186
187 select_test_node_and_ips ()
188 {
189     local timeout=10
190     while ! _select_test_node_and_ips ; do
191         echo "Unable to find a test node with IPs assigned"
192         if [ $timeout -le 0 ] ; then
193             echo "BAD: Too many attempts"
194             return 1
195         fi
196         sleep_for 1
197         timeout=$(($timeout - 1))
198     done
199
200     return 0
201 }
202
203 # Sets: mask, iface
204 get_test_ip_mask_and_iface ()
205 {
206     # Find the interface
207     try_command_on_node $test_node "$CTDB ip -v -X | awk -F'|' -v ip=$test_ip '\$2 == ip { print \$4 }'"
208     iface="$out"
209
210     if [ -z "$TEST_LOCAL_DAEMONS" ] ; then
211         # Find the netmask
212         try_command_on_node $test_node ip addr show to $test_ip
213         mask="${out##*/}"
214         mask="${mask%% *}"
215     else
216         mask="24"
217     fi
218
219     echo "$test_ip/$mask is on $iface"
220 }
221
222 ctdb_get_all_pnns ()
223 {
224     try_command_on_node -q all "$CTDB pnn"
225     all_pnns="$out"
226 }
227
228 # The subtlety is that "ctdb delip" will fail if the IP address isn't
229 # configured on a node...
230 delete_ip_from_all_nodes ()
231 {
232     _ip="$1"
233
234     ctdb_get_all_pnns
235
236     _nodes=""
237
238     for _pnn in $all_pnns ; do
239         all_ips_on_node $_pnn
240         while read _i _n ; do
241             if [ "$_ip" = "$_i" ] ; then
242                 _nodes="${_nodes}${_nodes:+,}${_pnn}"
243             fi
244         done <"$outfile"
245     done
246
247     try_command_on_node -pq "$_nodes" "$CTDB delip $_ip"
248 }
249
250 #######################################
251
252 sleep_for ()
253 {
254     echo -n "=${1}|"
255     for i in $(seq 1 $1) ; do
256         echo -n '.'
257         sleep 1
258     done
259     echo '|'
260 }
261
262 _cluster_is_healthy ()
263 {
264     $CTDB nodestatus all >/dev/null
265 }
266
267 _cluster_is_recovered ()
268 {
269     node_has_status 0 recovered
270 }
271
272 _cluster_is_ready ()
273 {
274     _cluster_is_healthy && _cluster_is_recovered
275 }
276
277 cluster_is_healthy ()
278 {
279         if onnode 0 $CTDB_TEST_WRAPPER _cluster_is_healthy ; then
280                 echo "Cluster is HEALTHY"
281                 if ! onnode 0 $CTDB_TEST_WRAPPER _cluster_is_recovered ; then
282                         echo "WARNING: cluster in recovery mode!"
283                 fi
284                 return 0
285         fi
286
287         echo "Cluster is UNHEALTHY"
288
289         echo "DEBUG AT $(date '+%F %T'):"
290         local i
291         for i in "onnode -q 0 $CTDB status" \
292                          "onnode -q 0 onnode all $CTDB scriptstatus" ; do
293                 echo "$i"
294                 $i || true
295         done
296
297         return 1
298 }
299
300 wait_until_ready ()
301 {
302     local timeout="${1:-120}"
303
304     echo "Waiting for cluster to become ready..."
305
306     wait_until $timeout onnode -q any $CTDB_TEST_WRAPPER _cluster_is_ready
307 }
308
309 # This function is becoming nicely overloaded.  Soon it will collapse!  :-)
310 node_has_status ()
311 {
312     local pnn="$1"
313     local status="$2"
314
315     local bits fpat mpat rpat
316     case "$status" in
317         (unhealthy)    bits="?|?|?|1|*" ;;
318         (healthy)      bits="?|?|?|0|*" ;;
319         (disconnected) bits="1|*" ;;
320         (connected)    bits="0|*" ;;
321         (banned)       bits="?|1|*" ;;
322         (unbanned)     bits="?|0|*" ;;
323         (disabled)     bits="?|?|1|*" ;;
324         (enabled)      bits="?|?|0|*" ;;
325         (stopped)      bits="?|?|?|?|1|*" ;;
326         (notstopped)   bits="?|?|?|?|0|*" ;;
327         (frozen)       fpat='^[[:space:]]+frozen[[:space:]]+1$' ;;
328         (unfrozen)     fpat='^[[:space:]]+frozen[[:space:]]+0$' ;;
329         (recovered)    rpat='^Recovery mode:RECOVERY \(1\)$' ;;
330         (notlmaster)   rpat="^hash:.* lmaster:${pnn}\$" ;;
331         *)
332             echo "node_has_status: unknown status \"$status\""
333             return 1
334     esac
335
336     if [ -n "$bits" ] ; then
337         local out x line
338
339         out=$($CTDB -X status 2>&1) || return 1
340
341         {
342             read x
343             while read line ; do
344                 # This needs to be done in 2 steps to avoid false matches.
345                 local line_bits="${line#|${pnn}|*|}"
346                 [ "$line_bits" = "$line" ] && continue
347                 [ "${line_bits#${bits}}" != "$line_bits" ] && return 0
348             done
349             return 1
350         } <<<"$out" # Yay bash!
351     elif [ -n "$fpat" ] ; then
352         $CTDB statistics -n "$pnn" | egrep -q "$fpat"
353     elif [ -n "$rpat" ] ; then
354         ! $CTDB status -n "$pnn" | egrep -q "$rpat"
355     else
356         echo 'node_has_status: unknown mode, neither $bits nor $fpat is set'
357         return 1
358     fi
359 }
360
361 wait_until_node_has_status ()
362 {
363     local pnn="$1"
364     local status="$2"
365     local timeout="${3:-30}"
366     local proxy_pnn="${4:-any}"
367
368     echo "Waiting until node $pnn has status \"$status\"..."
369
370     if ! wait_until $timeout onnode $proxy_pnn $CTDB_TEST_WRAPPER node_has_status "$pnn" "$status" ; then
371         for i in "onnode -q any $CTDB status" "onnode -q any onnode all $CTDB scriptstatus" ; do
372             echo "$i"
373             $i || true
374         done
375
376         return 1
377     fi
378
379 }
380
381 # Useful for superficially testing IP failover.
382 # IPs must be on the given node.
383 # If the first argument is '!' then the IPs must not be on the given node.
384 ips_are_on_node ()
385 {
386     local negating=false
387     if [ "$1" = "!" ] ; then
388         negating=true ; shift
389     fi
390     local node="$1" ; shift
391     local ips="$*"
392
393     local out
394
395     all_ips_on_node $node
396
397     local check
398     for check in $ips ; do
399         local ip pnn
400         while read ip pnn ; do
401             if [ "$check" = "$ip" ] ; then
402                 if [ "$pnn" = "$node" ] ; then
403                     if $negating ; then return 1 ; fi
404                 else
405                     if ! $negating ; then return 1 ; fi
406                 fi
407                 ips="${ips/${ip}}" # Remove from list
408                 break
409             fi
410             # If we're negating and we didn't see the address then it
411             # isn't hosted by anyone!
412             if $negating ; then
413                 ips="${ips/${check}}"
414             fi
415         done <"$outfile"
416     done
417
418     ips="${ips// }" # Remove any spaces.
419     [ -z "$ips" ]
420 }
421
422 wait_until_ips_are_on_node ()
423 {
424     # Go to some trouble to print a use description of what is happening
425     local not=""
426     if [ "$1" == "!" ] ; then
427         not="no longer "
428     fi
429     local node=""
430     local ips=""
431     local i
432     for i ; do
433         [ "$i" != "!" ] || continue
434         if [ -z "$node" ] ; then
435             node="$i"
436             continue
437         fi
438         ips="${ips}${ips:+, }${i}"
439     done
440     echo "Waiting for ${ips} to ${not}be assigned to node ${node}"
441
442     wait_until 60 ips_are_on_node "$@"
443 }
444
445 node_has_some_ips ()
446 {
447     local node="$1"
448
449     local out
450
451     all_ips_on_node $node
452
453     while read ip pnn ; do
454         if [ "$node" = "$pnn" ] ; then
455             return 0
456         fi
457     done <"$outfile"
458
459     return 1
460 }
461
462 wait_until_node_has_some_ips ()
463 {
464     echo "Waiting for some IPs to be assigned to node ${test_node}"
465
466     wait_until 60 node_has_some_ips "$@"
467 }
468
469 wait_until_node_has_no_ips ()
470 {
471     echo "Waiting until no IPs are assigned to node ${test_node}"
472
473     wait_until 60 ! node_has_some_ips "$@"
474 }
475
476 #######################################
477
478 _service_ctdb ()
479 {
480     cmd="$1"
481
482     if [ -e /etc/redhat-release ] ; then
483         service ctdb "$cmd"
484     else
485         /etc/init.d/ctdb "$cmd"
486     fi
487 }
488
489 # Stop/start CTDB on all nodes.  Override for local daemons.
490 ctdb_stop_all ()
491 {
492         onnode -p all $CTDB_TEST_WRAPPER _service_ctdb stop
493 }
494 ctdb_start_all ()
495 {
496         onnode -p all $CTDB_TEST_WRAPPER _service_ctdb start
497 }
498
499 setup_ctdb ()
500 {
501         ctdb_enable_cluster_test_event_scripts
502 }
503
504 start_ctdb_1 ()
505 {
506     onnode "$1" $CTDB_TEST_WRAPPER _service_ctdb start
507 }
508
509 stop_ctdb_1 ()
510 {
511     onnode "$1" $CTDB_TEST_WRAPPER _service_ctdb stop
512 }
513
514 restart_ctdb_1 ()
515 {
516     onnode "$1" $CTDB_TEST_WRAPPER _service_ctdb restart
517 }
518
519 ctdb_init ()
520 {
521     local i
522     for i in $(seq 1 5) ; do
523         ctdb_stop_all >/dev/null 2>&1 || :
524         ctdb_start_all || {
525             echo "Start failed.  Trying again in a few seconds..."
526             sleep_for 5
527             continue
528         }
529
530         wait_until_ready || {
531             echo "Cluster didn't become ready.  Restarting..."
532             continue
533         }
534
535         echo "Setting RerecoveryTimeout to 1"
536         onnode -pq all "$CTDB setvar RerecoveryTimeout 1"
537
538         # In recent versions of CTDB, forcing a recovery like this
539         # blocks until the recovery is complete.  Hopefully this will
540         # help the cluster to stabilise before a subsequent test.
541         echo "Forcing a recovery..."
542         onnode -q 0 $CTDB recover
543         sleep_for 2
544
545         if ! onnode -q any $CTDB_TEST_WRAPPER _cluster_is_recovered ; then
546             echo "Cluster has gone into recovery again, waiting..."
547             wait_until 30/2 onnode -q any $CTDB_TEST_WRAPPER _cluster_is_recovered
548         fi
549
550
551         # Cluster is still healthy.  Good, we're done!
552         if ! onnode 0 $CTDB_TEST_WRAPPER _cluster_is_healthy ; then
553             echo "Cluster became UNHEALTHY again [$(date)]"
554             onnode -p all ctdb status -X 2>&1
555             onnode -p all ctdb scriptstatus 2>&1
556             echo "Restarting..."
557             continue
558         fi
559
560         echo "Doing a sync..."
561         onnode -q 0 $CTDB sync
562
563         echo "ctdb is ready"
564         return 0
565     done
566
567     echo "Cluster UNHEALTHY...  too many attempts..."
568     onnode -p all ctdb status -X 2>&1
569     onnode -p all ctdb scriptstatus 2>&1
570
571     # Try to make the calling test fail
572     status=1
573     return 1
574 }
575
576 ctdb_base_show ()
577 {
578         echo "${CTDB_BASE:-${CTDB_SCRIPTS_BASE}}"
579 }
580
581 #######################################
582
583 wait_for_monitor_event ()
584 {
585     local pnn="$1"
586     local timeout=120
587
588     echo "Waiting for a monitor event on node ${pnn}..."
589
590     try_command_on_node "$pnn" $CTDB scriptstatus || {
591         echo "Unable to get scriptstatus from node $pnn"
592         return 1
593     }
594
595     mv "$outfile" "${outfile}.orig"
596
597     wait_until 120 _ctdb_scriptstatus_changed
598 }
599
600 _ctdb_scriptstatus_changed ()
601 {
602     try_command_on_node "$pnn" $CTDB scriptstatus || {
603         echo "Unable to get scriptstatus from node $pnn"
604         return 1
605     }
606
607     ! diff "$outfile" "${outfile}.orig" >/dev/null
608 }
609
610 #######################################
611
612 nfs_test_setup ()
613 {
614     select_test_node_and_ips
615
616     nfs_first_export=$(showmount -e $test_ip | sed -n -e '2s/ .*//p')
617
618     echo "Creating test subdirectory..."
619     try_command_on_node $test_node "TMPDIR=$nfs_first_export mktemp -d"
620     nfs_test_dir="$out"
621     try_command_on_node $test_node "chmod 777 $nfs_test_dir"
622
623     nfs_mnt_d=$(mktemp -d)
624     nfs_local_file="${nfs_mnt_d}/${nfs_test_dir##*/}/TEST_FILE"
625     nfs_remote_file="${nfs_test_dir}/TEST_FILE"
626
627     ctdb_test_exit_hook_add nfs_test_cleanup
628
629     echo "Mounting ${test_ip}:${nfs_first_export} on ${nfs_mnt_d} ..."
630     mount -o timeo=1,hard,intr,vers=3 \
631         "[${test_ip}]:${nfs_first_export}" ${nfs_mnt_d}
632 }
633
634 nfs_test_cleanup ()
635 {
636     rm -f "$nfs_local_file"
637     umount -f "$nfs_mnt_d"
638     rmdir "$nfs_mnt_d"
639     onnode -q $test_node rmdir "$nfs_test_dir"
640 }
641
642 #######################################
643
644 # If the given IP is hosted then print 2 items: maskbits and iface
645 ip_maskbits_iface ()
646 {
647     _addr="$1"
648
649     case "$_addr" in
650         *:*) _family="inet6" ; _bits=128 ;;
651         *)   _family="inet"  ; _bits=32  ;;
652     esac
653
654     ip addr show to "${_addr}/${_bits}" 2>/dev/null | \
655         awk -v family="${_family}" \
656             'NR == 1 { iface = $2; sub(":$", "", iface) } \
657              $1 ~ /inet/ { mask = $2; sub(".*/", "", mask); \
658                            print mask, iface, family }'
659 }
660
661 drop_ip ()
662 {
663     _addr="${1%/*}"  # Remove optional maskbits
664
665     set -- $(ip_maskbits_iface $_addr)
666     if [ -n "$1" ] ; then
667         _maskbits="$1"
668         _iface="$2"
669         echo "Removing public address $_addr/$_maskbits from device $_iface"
670         ip addr del "$_ip/$_maskbits" dev "$_iface" >/dev/null 2>&1 || true
671     fi
672 }
673
674 drop_ips ()
675 {
676     for _ip ; do
677         drop_ip "$_ip"
678     done
679 }
680
681 #######################################
682
683 # $1: pnn, $2: DB name
684 db_get_path ()
685 {
686     try_command_on_node -v $1 $CTDB getdbstatus "$2" |
687     sed -n -e "s@^path: @@p"
688 }
689
690 # $1: pnn, $2: DB name
691 db_ctdb_cattdb_count_records ()
692 {
693         # Count the number of keys, excluding any that begin with '_'.
694         # This excludes at least the sequence number record in
695         # persistent/replicated databases.  The trailing "|| :" forces
696         # the command to succeed when no records are matched.
697         try_command_on_node $1 \
698                 "$CTDB cattdb $2 | grep -c '^key([0-9][0-9]*) = \"[^_]' || :"
699         echo "$out"
700 }
701
702 # $1: pnn, $2: DB name, $3: key string, $4: value string, $5: RSN (default 7)
703 db_ctdb_tstore ()
704 {
705     _tdb=$(db_get_path $1 "$2")
706     _rsn="${5:-7}"
707     try_command_on_node $1 $CTDB tstore "$_tdb" "$3" "$4" "$_rsn"
708 }
709
710 # $1: pnn, $2: DB name, $3: dbseqnum (must be < 255!!!!!)
711 db_ctdb_tstore_dbseqnum ()
712 {
713     # "__db_sequence_number__" + trailing 0x00
714     _key='0x5f5f64625f73657175656e63655f6e756d6265725f5f00'
715
716     # Construct 8 byte (unit64_t) database sequence number.  This
717     # probably breaks if $3 > 255
718     _value=$(printf "0x%02x%014x" $3 0)
719
720     db_ctdb_tstore $1 "$2" "$_key" "$_value"
721 }
722
723 #######################################
724
725 # Enables all of the event scripts used in cluster tests, except for
726 # the mandatory scripts
727 ctdb_enable_cluster_test_event_scripts ()
728 {
729         local scripts="
730                        06.nfs
731                        10.interface
732                        49.winbind
733                        50.samba
734                        60.nfs
735                       "
736
737         local s
738         for s in $scripts ; do
739                 try_command_on_node all ctdb event script enable legacy "$s"
740         done
741 }
742
743 ########################################
744
745 # Make sure that $CTDB is set.
746 : ${CTDB:=ctdb}
747
748 local="${TEST_SUBDIR}/scripts/local.bash"
749 if [ -r "$local" ] ; then
750     . "$local"
751 fi