Whamcloud - gitweb
LU-17744 ldiskfs: mballoc stats fixes
[fs/lustre-release.git] / lustre / tests / ha.sh
1 #!/bin/bash
2 # -*- mode: Bash; tab-width: 4; indent-tabs-mode: t; -*-
3 # vim:shiftwidth=4:softtabstop=4:tabstop=4:
4 #
5 # NAME
6 #
7 #   ha.sh - test Lustre HA (aka failover) configurations
8 #
9 # SYNOPSIS
10 #
11 #   ha.sh [OPTIONS]
12 #
13 # DESCRIPTION
14 #
15 #   ha.sh tests Lustre HA (aka failover) configurations with a CRM.
16 #
17 # OPTIONS
18 #
19 #   -h
20 #       Help.
21 #
22 #   -c HOST[,...]
23 #       Specify client nodes.
24 #
25 #   -s HOST[,...]
26 #       Specify server nodes.
27 #
28 #   -v HOST[,...]
29 #       Specify victim nodes to be rebooted.
30 #
31 #   -d DIRECTORY
32 #       Choose a parent of the test directory.  "/mnt/lustre" if not specified.
33 #
34 #   -u SECONDS
35 #       Define a duration for the test. 86400 seconds if not specified.
36 #
37 #   -p SECONDS
38 #       Define a max failover period. 10 minutes if not set.
39 #
40 #   -w
41 #       Only run the workloads; no failure will be introduced.
42 #       -v, -s are ignored in this case.
43 #   -r
44 #       Workloads dry run for several seconds; no failures will be introduced.
45 #       This option is useful to verify the loads.
46 #       -u is ignored in this case
47 #   -m
48 #       Reboot victim nodes simultaneously.
49 #
50 #
51 # ASSUMPTIONS
52 #
53 #   A Lustre file system is up and mounted on all client nodes.  This script
54 #   does not mount or unmount any Lustre targets or clients, let alone format
55 #   anything.
56 #
57 #   Each target has a failnode, so that workloads can continue after a power
58 #   failure.
59 #
60 #   CRM could be configured by 2 ways:
61 #   1.
62 #   Targets are automatically failed back when their primary node is back.  This
63 #   assumption avoids calling CRM-specific commands to trigger failbacks, making
64 #   this script more CRM-neural.
65 #   2.
66 #   Targets are not automatically failed back when their primary node is back.
67 #   CRM-specific command is executed to trigger failbacks.
68 #
69 #   A crash dump mechanism is configured to catch LBUGs, panics, etc.
70 #
71 # WORKLOADS
72 #
73 #   Each client runs set of MPI and non-MPI workloads. These
74 #   applications are run in short loops so that their exit status can be waited
75 #   for and checked within reasonable time by ha_wait_loads.
76 #   The set of MPI and non-MPI workloads are configurable by parameters:
77 #       ha_nonmpi_loads
78 #               default set: dd, tar, iozone
79 #       ha_mpi_loads
80 #               default set: ior, simul, mdtest
81 #
82 #   The number of clients run MPI loads is configured by parameter
83 #   ha_mpi_instances. Only one client runs MPI workloads by default.
84 #
85 #   MPI workloads can be run from several users. The list of users to use is
86 #   configured by parameter ha_mpi_users, default is "mpiuser".
87 #
88 # PROCESS STRUCTURE AND IPC
89 #
90 #   On the node where this script is run, the processes look like this:
91 #
92 #       ~ ha.sh (ha_killer)
93 #
94 #           ~ ha.sh (ha_repeat_mpi_load ior)
95 #               ~ mpirun IOR
96 #           ~ ha.sh (ha_repeat_mpi_load simul)
97 #               ~ mpirun simul
98 #           ~ ha.sh (ha_repeat_mpi_load mdtest)
99 #               ~ mpirun mdtest
100 #           ~ ... (one for each MPI load)
101 #
102 #           ~ ha.sh (ha_repeat_nonmpi_load client2 dbench)
103 #               ~ pdsh client2 dbench
104 #           ~ ha.sh (ha_repeat_nonmpi_load client2 iozone)
105 #               ~ pdsh client2 iozone
106 #           ~ ha.sh (ha_repeat_nonmpi_load client5 iozone)
107 #               ~ pdsh client5 iozone
108 #           ~ ... (one for each non-MPI load on each client)
109 #
110 #   Each tilde represents a process.  Indentations imply parent-children
111 #   relation.
112 #
113 #   IPC is done by files in the temporary directory.
114 #
115
116 #set -x
117
118 SIMUL=${SIMUL:-$(which simul 2> /dev/null || true)}
119 IOR=${IOR:-$(which IOR 2> /dev/null || true)}
120 MDTEST=${MDTEST:-$(which mdtest 2> /dev/null || true)}
121
122 ior_blockSize=${ior_blockSize:-6g}
123 mpi_threads_per_client=${mpi_threads_per_client:-2}
124
125 iozone_SIZE=${iozone_SIZE:-262144} # 256m
126
127 mpirun=${MPIRUN:-$(which mpirun)}
128 LFS=${LFS:-$(which lfs)}
129
130 ha_check_env()
131 {
132         for ((load = 0; load < ${#ha_mpi_load_tags[@]}; load++)); do
133                 local tag=${ha_mpi_load_tags[$load]}
134                 local bin=$(echo $tag | tr '[:lower:]' '[:upper:]')
135                 if [ x${!bin} = x ]; then
136                         ha_error ha_mpi_loads: ${ha_mpi_loads}, $bin is not set
137                         exit 1
138                 fi
139         done
140 }
141
142 ha_info()
143 {
144         echo "$0: $(date +%H:%M:%S' '%s):" "$@"
145 }
146
147 ha_log()
148 {
149         local nodes=${1// /,}
150         shift
151         ha_on $nodes "lctl mark $*"
152 }
153
154 ha_error()
155 {
156     ha_info "$@" >&2
157 }
158
159 ha_trap_err()
160 {
161     local i
162
163     ha_error "Trap ERR triggered by:"
164     ha_error "    $BASH_COMMAND"
165     ha_error "Call trace:"
166     for ((i = 0; i < ${#FUNCNAME[@]}; i++)); do
167         ha_error "    ${FUNCNAME[$i]} [${BASH_SOURCE[$i]}:${BASH_LINENO[$i]}]"
168     done
169 }
170
171 trap ha_trap_err ERR
172 set -eE
173
174 declare     ha_tmp_dir=/tmp/$(basename $0)-$$
175 declare     ha_stop_file=$ha_tmp_dir/stop
176 declare     ha_fail_file=$ha_tmp_dir/fail
177 declare     ha_pm_states=$ha_tmp_dir/ha_pm_states
178 declare     ha_status_file_prefix=$ha_tmp_dir/status
179 declare -a  ha_status_files
180 declare     ha_machine_file=$ha_tmp_dir/machine_file
181 declare     ha_lfsck_log=$ha_tmp_dir/lfsck.log
182 declare     ha_lfsck_lock=$ha_tmp_dir/lfsck.lock
183 declare     ha_lfsck_stop=$ha_tmp_dir/lfsck.stop
184 declare     ha_lfsck_bg=${LFSCK_BG:-false}
185 declare     ha_lfsck_after=${LFSCK_AFTER:-false}
186 declare     ha_lfsck_node=${LFSCK_NODE:-""}
187 declare     ha_lfsck_device=${LFSCK_DEV:-""}
188 declare     ha_lfsck_types=${LFSCK_TYPES:-"namespace layout"}
189 declare     ha_lfsck_custom_params=${LFSCK_CUSTOM_PARAMS:-""}
190 declare     ha_lfsck_wait=${LFSCK_WAIT:-1200}
191 declare     ha_lfsck_fail_on_repaired=${LFSCK_FAIL_ON_REPAIRED:-false}
192 declare     ha_power_down_cmd=${POWER_DOWN:-"pm -0"}
193 declare     ha_power_up_cmd=${POWER_UP:-"pm -1"}
194 declare     ha_power_delay=${POWER_DELAY:-60}
195 declare     ha_node_up_delay=${NODE_UP_DELAY:-10}
196 declare     ha_pm_host=${PM_HOST:-$(hostname)}
197 declare     ha_failback_delay=${DELAY:-5}
198 declare     ha_failback_cmd=${FAILBACK:-""}
199 declare     ha_stripe_params=${STRIPEPARAMS:-"-c 0"}
200 declare     ha_test_dir_stripe_count=${TDSTRIPECOUNT:-"1"}
201 declare     ha_test_dir_mdt_index=${TDMDTINDEX:-"0"}
202 declare     ha_test_dir_mdt_index_random=${TDMDTINDEXRAND:-false}
203 declare     ha_dir_stripe_count=${DSTRIPECOUNT:-"1"}
204 declare     ha_mdt_index=${MDTINDEX:-"0"}
205 declare     ha_mdt_index_random=${MDTINDEXRAND:-false}
206 declare -a  ha_clients
207 declare -a  ha_servers
208 declare -a  ha_victims
209 declare -a  ha_victims_pair
210 declare     ha_test_dir=/mnt/lustre/$(basename $0)-$$
211 declare -a  ha_testdirs=(${ha_test_dirs="$ha_test_dir"})
212
213 for ((i=0; i<${#ha_testdirs[@]}; i++)); do
214         echo I=$i ${ha_testdirs[i]}
215         ha_testdirs[i]="${ha_testdirs[i]}/$(basename $0)-$$"
216         echo i=$i ${ha_testdirs[i]}
217 done
218
219 declare     ha_cleanup=${CLEANUP:-true}
220 declare     ha_start_time=$(date +%s)
221 declare     ha_expected_duration=$((60 * 60 * 24))
222 declare     ha_max_failover_period=10
223 declare     ha_nr_loops=0
224 declare     ha_stop_signals="SIGINT SIGTERM SIGHUP"
225 declare     ha_load_timeout=${LOAD_TIMEOUT:-$((60 * 10))}
226 declare     ha_workloads_only=false
227 declare     ha_workloads_dry_run=false
228 declare     ha_simultaneous=false
229
230 declare     ha_mpi_instances=${ha_mpi_instances:-1}
231
232 declare     ha_mpi_loads=${ha_mpi_loads="ior simul mdtest"}
233 declare -a  ha_mpi_load_tags=($ha_mpi_loads)
234 declare -a  ha_mpiusers=(${ha_mpi_users="mpiuser"})
235 declare -a  ha_users
236 declare -A  ha_mpiopts
237
238 for ((i=0; i<${#ha_mpiusers[@]}; i++)); do
239         u=${ha_mpiusers[i]%%:*}
240         o=""
241         # user gets empty option if ha_mpi_users does not specify it explicitly
242         [[ ${ha_mpiusers[i]} =~ : ]] && o=${ha_mpiusers[i]##*:}
243         ha_users[i]=$u
244         ha_mpiopts[$u]+=" $o"
245 done
246 ha_users=(${!ha_mpiopts[@]})
247
248 declare     ha_ior_params=${IORP:-'" -b $ior_blockSize -t 2m -w -W -T 1"'}
249 declare     ha_simul_params=${SIMULP:-'" -n 10"'}
250 declare     ha_mdtest_params=${MDTESTP:-'" -i 1 -n 1000"'}
251 declare     ha_mpirun_options=${MPIRUN_OPTIONS:-""}
252 declare     ha_clients_stripe=${CLIENTSSTRIPE:-'"$STRIPEPARAMS"'}
253 declare     ha_nclientsset=${NCLIENTSSET:-1}
254 declare     ha_ninstmustfail=${NINSTMUSTFAIL:-0}
255
256 declare     ha_racer_params=${RACERP:-"MDSCOUNT=1"}
257
258 eval ha_params_ior=($ha_ior_params)
259 eval ha_params_simul=($ha_simul_params)
260 eval ha_params_mdtest=($ha_mdtest_params)
261 eval ha_stripe_clients=($ha_clients_stripe)
262
263 declare ha_nparams_ior=${#ha_params_ior[@]}
264 declare ha_nparams_simul=${#ha_params_simul[@]}
265 declare ha_nparams_mdtest=${#ha_params_mdtest[@]}
266 declare ha_nstripe_clients=${#ha_stripe_clients[@]}
267
268 declare -A  ha_mpi_load_cmds=(
269         [ior]="$IOR -o {}/f.ior {params}"
270         [simul]="$SIMUL {params} -d {}"
271         [mdtest]="$MDTEST {params} -d {}"
272 )
273
274 declare racer=${RACER:-"$(dirname $0)/racer/racer.sh"}
275
276 declare     ha_nonmpi_loads=${ha_nonmpi_loads="dd tar iozone"}
277 declare -a  ha_nonmpi_load_tags=($ha_nonmpi_loads)
278 declare -A  ha_nonmpi_load_cmds=(
279         [dd]="dd if=/dev/zero of={}/f.dd bs=1M count=256"
280         [tar]="tar cf - /etc | tar xf - -C {}"
281         [iozone]="iozone -a -e -+d -s $iozone_SIZE {}/f.iozone"
282         [racer]="$ha_racer_params $racer {}"
283 )
284
285 ha_usage()
286 {
287         ha_info "Usage: $0 -c HOST[,...] -s HOST[,...]" \
288                 "-v HOST[,...] -f HOST[,...] [-d DIRECTORY] [-u SECONDS]"
289 }
290
291 ha_process_arguments()
292 {
293     local opt
294
295         while getopts hc:s:v:d:p:u:wrmf: opt; do
296         case $opt in
297         h)
298             ha_usage
299             exit 0
300             ;;
301         c)
302             ha_clients=(${OPTARG//,/ })
303             ;;
304         s)
305             ha_servers=(${OPTARG//,/ })
306             ;;
307         v)
308             ha_victims=(${OPTARG//,/ })
309             ;;
310         d)
311             ha_test_dir=$OPTARG/$(basename $0)-$$
312             ;;
313         u)
314             ha_expected_duration=$OPTARG
315             ;;
316         p)
317                 ha_max_failover_period=$OPTARG
318                 ;;
319         w)
320                 ha_workloads_only=true
321                 ;;
322         r)
323                 ha_workloads_dry_run=true
324                 ;;
325         m)
326                 ha_simultaneous=true
327                 ;;
328         f)
329                 ha_victims_pair=(${OPTARG//,/ })
330                 ;;
331         \?)
332             ha_usage
333             exit 1
334             ;;
335         esac
336     done
337
338         if [ -z "${ha_clients[*]}" ]; then
339                 ha_error "-c is mandatory"
340                 ha_usage
341                 exit 1
342         fi
343         if ! ($ha_workloads_dry_run ||
344                         $ha_workloads_only) &&
345                         ([ -z "${ha_servers[*]}" ] ||
346                         [ -z "${ha_victims[*]}" ]); then
347                 ha_error "-s, and -v are all mandatory"
348                 ha_usage
349                 exit 1
350         fi
351 }
352
353 ha_on()
354 {
355         local nodes=$1
356         local rc=0
357
358         shift
359
360         #
361         # -S is to be used here to track the
362         # remote command return values
363         #
364         pdsh -S -w $nodes "PATH=/usr/local/sbin:/usr/local/bin:/sbin:\
365 /bin:/usr/sbin:/usr/bin; $@" ||
366                 rc=$?
367         return $rc
368 }
369
370 ha_trap_exit()
371 {
372         touch "$ha_stop_file"
373         trap 0
374         if [ -e "$ha_fail_file" ]; then
375                 ha_info "Test directories ${ha_testdirs[@]} not removed"
376                 ha_info "Temporary directory $ha_tmp_dir not removed"
377         else
378                 $ha_cleanup &&
379                         ha_on ${ha_clients[0]} rm -rf ${ha_testdirs[@]} ||
380                         ha_info "Test directories ${ha_testdirs[@]} not removed"
381                 ha_info "Please find the results in the directory $ha_tmp_dir"
382         fi
383 }
384
385 ha_trap_stop_signals()
386 {
387     ha_info "${ha_stop_signals// /,} received"
388     touch "$ha_stop_file"
389 }
390
391 ha_sleep()
392 {
393     local n=$1
394
395     ha_info "Sleeping for ${n}s"
396     #
397     # sleep(1) could interrupted.
398     #
399     sleep $n || true
400 }
401
402 ha_wait_unlock()
403 {
404         local lock=$1
405
406         while [ -e $lock ]; do
407                 sleep 1
408         done
409 }
410
411 ha_lock()
412 {
413     local lock=$1
414
415     until mkdir "$lock" >/dev/null 2>&1; do
416         ha_sleep 1 >/dev/null
417     done
418 }
419
420 ha_unlock()
421 {
422     local lock=$1
423
424     rm -r "$lock"
425 }
426
427 ha_dump_logs()
428 {
429         local nodes=${1// /,}
430         local file=/tmp/$(basename $0)-$$-$(date +%s).dk
431         local lock=$ha_tmp_dir/lock-dump-logs
432         local rc=0
433
434         ha_lock "$lock"
435         ha_info "Dumping lctl log to $file"
436
437         #
438         # some nodes could crash, so
439         # do not exit with error if not all logs are dumped
440         #
441         ha_on $nodes "lctl dk >>$file" || rc=$?
442
443         [ $rc -eq 0 ] ||
444                 ha_error "not all logs are dumped! Some nodes are unreachable."
445         ha_unlock "$lock"
446 }
447
448 ha_repeat_mpi_load()
449 {
450         local client=$1
451         local load=$2
452         local status=$3
453         local parameter=$4
454         local machines=$5
455         local stripeparams=$6
456         local mpiuser=$7
457         local mustpass=$8
458         local mpirunoptions=$9
459         local test_dir=${10}
460         local tag=${ha_mpi_load_tags[$load]}
461         local cmd=${ha_mpi_load_cmds[$tag]}
462         local dir=$test_dir/$client-$tag
463         local log=$ha_tmp_dir/$client-$tag
464         local rc=0
465         local nr_loops=0
466         local avg_loop_time=0
467         local start_time=$(date +%s)
468
469         cmd=${cmd//"{}"/$dir}
470         cmd=${cmd//"{params}"/$parameter}
471
472         [[ -n "$ha_postcmd" ]] && ha_postcmd=${ha_postcmd//"{}"/$dir}
473         [[ -n "$ha_precmd" ]] && ha_precmd=${ha_precmd//"{}"/$dir}
474         ha_info "Starting $tag"
475
476         machines="-machinefile $machines"
477         while [ ! -e "$ha_stop_file" ] && ((rc == 0)); do
478                 ha_info "$client Starts: $mpiuser: $cmd" 2>&1 |  tee -a $log
479                 {
480                 local mdt_index
481                 if $ha_mdt_index_random && [ $ha_mdt_index -ne 0 ]; then
482                         mdt_index=$(ha_rand $ha_mdt_index)
483                 else
484                         mdt_index=$ha_mdt_index
485                 fi
486                 [[ -n "$ha_precmd" ]] && ha_info "$ha_precmd" &&
487                         ha_on $client "$ha_precmd" >>"$log" 2>&1
488                 ha_on $client $LFS mkdir -i$mdt_index -c$ha_dir_stripe_count "$dir" &&
489                 ha_on $client $LFS getdirstripe "$dir" &&
490                 ha_on $client $LFS setstripe $stripeparams $dir &&
491                 ha_on $client $LFS getstripe $dir &&
492                 ha_on $client chmod a+xwr $dir &&
493                 ha_on $client "su $mpiuser sh -c \" $mpirun $mpirunoptions \
494                         -np $((${#ha_clients[@]} * mpi_threads_per_client / ha_nclientsset)) \
495                         $machines $cmd \" " || rc=$?
496                 [[ -n "$ha_postcmd" ]] && ha_info "$ha_postcmd" &&
497                         ha_on $client "$ha_postcmd" >>"$log" 2>&1
498                 (( ((rc == 0)) && (( mustpass != 0 )) )) ||
499                 (( ((rc != 0)) && (( mustpass == 0 )) )) &&
500                         ha_on $client rm -rf "$dir";
501                 } >>"$log" 2>&1 || rc=$?
502
503                 ha_info $client: rc=$rc mustpass=$mustpass
504
505                 # mustpass=0 means that failure is expected
506                 if (( rc !=0 )); then
507                         if (( mustpass != 0 )); then
508                                 touch "$ha_fail_file"
509                                 touch "$ha_stop_file"
510                                 ha_dump_logs "${ha_clients[*]} ${ha_servers[*]}"
511                         else
512                                 # Ok to fail
513                                 rc=0
514                         fi
515                 elif (( mustpass == 0 )); then
516                         touch "$ha_fail_file"
517                         touch "$ha_stop_file"
518                         ha_dump_logs "${ha_clients[*]} ${ha_servers[*]}"
519                 fi
520                 echo rc=$rc mustpass=$mustpass >"$status"
521
522                 nr_loops=$((nr_loops + 1))
523         done
524
525         [ $nr_loops -ne 0 ] &&
526                 avg_loop_time=$((($(date +%s) - start_time) / nr_loops))
527
528         ha_info "$tag stopped: rc=$rc mustpass=$mustpass \
529                 avg loop time $avg_loop_time"
530 }
531
532 ha_start_mpi_loads()
533 {
534         local client
535         local load
536         local tag
537         local status
538         local n
539         local nparam
540         local machines
541         local m
542         local -a mach
543         local mpiuser
544         local nmpi
545
546         # ha_mpi_instances defines the number of
547         # clients start mpi loads; should be <= ${#ha_clients[@]}
548         # do nothing if
549         #    ha_mpi_instances = 0
550         # or
551         #    ${#ha_mpi_load_tags[@]} =0
552         local inst=$ha_mpi_instances
553         (( inst == 0 )) || (( ${#ha_mpi_load_tags[@]} == 0 )) &&
554                 ha_info "no mpi load to start" &&
555                 return 0
556
557         (( inst <= ${#ha_clients[@]} )) || inst=${#ha_clients[@]}
558
559         # Define names for machinefiles for each client set
560         for (( n=0; n < $ha_nclientsset; n++ )); do
561                 mach[$n]=$ha_machine_file$n
562         done
563
564         for ((n = 0; n < ${#ha_clients[@]}; n++)); do
565                 m=$(( n % ha_nclientsset))
566                 machines=${mach[m]}
567                 ha_info machine_file=$machines
568                 echo ${ha_clients[n]} >> $machines
569         done
570         local dirname=$(dirname $ha_machine_file)
571         for client in ${ha_clients[@]}; do
572                 ha_on $client mkdir -p $dirname
573                 scp $ha_machine_file* $client:$dirname
574         done
575
576         local ndir
577         for ((n = 0; n < $inst; n++)); do
578                 client=${ha_clients[n]}
579                 nmpi=$((n % ${#ha_users[@]}))
580                 mpiuser=${ha_users[nmpi]}
581                 ndir=$((n % ${#ha_testdirs[@]}))
582                 test_dir=${ha_testdirs[ndir]}
583                 for ((load = 0; load < ${#ha_mpi_load_tags[@]}; load++)); do
584                         tag=${ha_mpi_load_tags[$load]}
585                         status=$ha_status_file_prefix-$tag-$client
586                         # ha_nparams_ior
587                         # ha_nparams_simul
588                         local num=ha_nparams_$tag
589                         nparam=$((n % num))
590                         local aref=ha_params_$tag[nparam]
591                         local parameter=${!aref}
592                         local nstripe=$((n % ha_nstripe_clients))
593                         aref=ha_stripe_clients[nstripe]
594                         local stripe=${!aref}
595                         local m=$(( n % ha_nclientsset))
596                         machines=${mach[m]}
597                         local mustpass=1
598                         [[ $ha_ninstmustfail == 0 ]] ||
599                                 mustpass=$(( n % ha_ninstmustfail ))
600                         ha_repeat_mpi_load $client $load $status "$parameter" \
601                                 $machines "$stripe" "$mpiuser" "$mustpass" \
602                                 "${ha_mpiopts[$mpiuser]} $ha_mpirun_options" "$test_dir" &
603                                 ha_status_files+=("$status")
604                 done
605         done
606 }
607
608 ha_repeat_nonmpi_load()
609 {
610         local client=$1
611         local load=$2
612         local status=$3
613         local tag=${ha_nonmpi_load_tags[$load]}
614         local cmd=${ha_nonmpi_load_cmds[$tag]}
615         local test_dir=$4
616         local dir=$test_dir/$client-$tag
617         local log=$ha_tmp_dir/$client-$tag
618         local rc=0
619         local nr_loops=0
620         local avg_loop_time=0
621         local start_time=$(date +%s)
622
623         cmd=${cmd//"{}"/$dir}
624
625         ha_info "Starting $tag on $client on $dir"
626
627         while [ ! -e "$ha_stop_file" ] && ((rc == 0)); do
628                 ha_info "$client Starts: $cmd" 2>&1 |  tee -a $log
629                 ha_on $client "mkdir -p $dir &&                              \
630                         $cmd &&                                              \
631                         rm -rf $dir" >>"$log" 2>&1 || rc=$?
632
633                 if ((rc != 0)); then
634                         ha_dump_logs "${ha_clients[*]} ${ha_servers[*]}"
635                         touch "$ha_fail_file"
636                         touch "$ha_stop_file"
637                 fi
638                 echo $rc >"$status"
639
640                 nr_loops=$((nr_loops + 1))
641         done
642
643         [ $nr_loops -ne 0 ] &&
644                 avg_loop_time=$((($(date +%s) - start_time) / nr_loops))
645
646         ha_info "$tag on $client stopped: rc $rc avg loop time ${avg_loop_time}s"
647 }
648
649 ha_start_nonmpi_loads()
650 {
651         local client
652         local load
653         local tag
654         local status
655         local n
656         local test_dir
657         local ndir
658
659         for (( n = 0; n < ${#ha_clients[@]}; n++)); do
660                 client=${ha_clients[n]}
661                 ndir=$((n % ${#ha_testdirs[@]}))
662                 test_dir=${ha_testdirs[ndir]}
663                 for ((load = 0; load < ${#ha_nonmpi_load_tags[@]}; load++)); do
664                         tag=${ha_nonmpi_load_tags[$load]}
665                         status=$ha_status_file_prefix-$tag-$client
666                         ha_repeat_nonmpi_load $client $load $status $test_dir &
667                         ha_status_files+=("$status")
668                 done
669         done
670 }
671
672 declare ha_bgcmd=${ha_bgcmd:-""}
673 declare ha_bgcmd_log=$ha_tmp_dir/bgcmdlog
674
675 ha_cmd_bg () {
676         [[ -z "$ha_bgcmd" ]] && return 0
677         for ((i=0; i<${#ha_testdirs[@]}; i++)); do
678                 ha_bgcmd=${ha_bgcmd//"{}"/${ha_testdirs[i]}}
679         done
680
681         ha_info "BG cmd: $ha_bgcmd"
682         while [ true ]; do
683                 [ -f $ha_stop_file ] &&
684                         ha_info "$ha_stop_file found! $ha_bgcmd no started" &&
685                         break
686                 eval $ha_bgcmd 2>&1 | tee -a $ha_bgcmd_log
687                 sleep 1
688         done &
689         CMD_BG_PID=$!
690         ha_info CMD BG PID: $CMD_BG_PID
691         ps aux | grep $CMD_BG_PID
692 }
693
694 ha_lfsck_bg () {
695         rm -f $ha_lfsck_log
696         rm -f $ha_lfsck_stop
697
698         ha_info "LFSCK BG"
699         while [ true ]; do
700                 [ -f $ha_lfsck_stop ] && ha_info "LFSCK stopped" && break
701                 [ -f $ha_stop_file ] &&
702                         ha_info "$ha_stop_file found! LFSCK not started" &&
703                         break
704                 ha_start_lfsck 2>&1 | tee -a $ha_lfsck_log
705                 sleep 1
706         done &
707         LFSCK_BG_PID=$!
708         ha_info LFSCK BG PID: $LFSCK_BG_PID
709 }
710
711 ha_wait_lfsck_completed () {
712         local -a status
713         local -a types=($ha_lfsck_types)
714         local type
715         local s
716
717         local nodes="${ha_servers[@]}"
718         nodes=${nodes// /,}
719
720         # -A start LFSCK on all nodes
721         # -t default all
722         [ ${#types[@]} -eq 0 ] && types=(namespace layout)
723         ha_info "Waiting LFSCK completed in $ha_lfsck_wait sec: types ${types[@]}"
724         for type in ${types[@]}; do
725                 eval var_$type=0
726                 for (( i=0; i<=ha_lfsck_wait; i++)); do
727                         status=($(ha_on $nodes lctl get_param -n *.*.lfsck_$type 2>/dev/null | \
728                                 awk '/status/ { print $3 }'))
729                         for (( s=0; s<${#status[@]}; s++ )); do
730                                 # "partial" is expected after HARD failover
731                                 [[ "${status[s]}" = "completed" ]] ||
732                                 [[ "${status[s]}" = "partial" ]] ||  break
733                         done
734                         [[ $s -eq ${#status[@]} ]] && eval var_$type=1 && break
735                         sleep 1
736                 done
737                 ha_info "LFSCK $type status in $i sec:"
738                 ha_on $nodes lctl get_param -n *.*.lfsck_$type 2>/dev/null | grep status
739
740         done
741
742         for type in ${types[@]}; do
743                 local var=var_$type
744                 ha_on $nodes lctl get_param -n *.*.lfsck_$type 2>/dev/null
745                 [[ ${!var} -eq 1 ]] ||
746                         { ha_info "lfsck not completed in $ha_lfsck_wait sec";
747                         return 1; }
748         done
749         return 0
750 }
751
752 ha_start_lfsck()
753 {
754         local -a types=($ha_lfsck_types)
755         local rc=0
756
757         # -A: start LFSCK on all nodes via the specified MDT device
758         # (see "-M" option) by single LFSCK command
759         local params=" -A -r $ha_lfsck_custom_params"
760
761         # use specified device if set
762         [ -n "$ha_lfsck_device" ] && params="-M $ha_lfsck_device $params"
763
764         # -t: check type(s) to be performed (default all)
765         # check only specified types if set
766         if [ ${#types[@]} -ne 0 ]; then
767                 local type="${types[@]}"
768                 params="$params -t ${type// /,}"
769         fi
770
771         ha_info "LFSCK start $params"
772         ha_on $ha_lfsck_node "lctl lfsck_start $params" || rc=1
773         if [ $rc -ne 0 ]; then
774                 if [ -e $ha_lfsck_lock ]; then
775                         rc=0
776                         ha_wait_unlock $ha_lfsck_lock
777                         ha_sleep 120
778                         ha_on $ha_lfsck_node "lctl lfsck_start $params" || rc=1
779                 fi
780         fi
781
782         [ $rc -eq 0 ] ||
783                 { touch "$ha_fail_file"; touch "$ha_stop_file";
784                 touch $ha_lfsck_stop; return 1; }
785
786         ha_wait_lfsck_completed ||
787                 { touch "$ha_fail_file"; touch "$ha_stop_file";
788                 touch $ha_lfsck_stop; return 1; }
789
790         return 0
791 }
792
793 ha_lfsck_repaired()
794 {
795         local n=0
796
797         n=$(cat $ha_lfsck_log | awk '/repaired/ {print $3}' |\
798                 awk '{sum += $1} END { print sum }')
799         [ $n -eq 0] ||
800                 { ha_info "Total repaired: $n";
801                 touch "$ha_fail_file"; return 1; }
802         return 0
803 }
804
805 ha_start_loads()
806 {
807         ha_cmd_bg
808         $ha_lfsck_bg && ha_lfsck_bg
809         trap ha_trap_stop_signals $ha_stop_signals
810         ha_start_nonmpi_loads
811         ha_start_mpi_loads
812 }
813
814 ha_stop_loads()
815 {
816         touch $ha_stop_file
817         [[ -n $CMD_BG_PID ]] && wait $CMD_BG_PID || true
818         # true because of lfsck_bg could be stopped already
819         $ha_lfsck_bg && wait $LFSCK_BG_PID || true
820         trap - $ha_stop_signals
821         ha_info "Waiting for workloads to stop"
822         wait
823 }
824
825 ha_wait_loads()
826 {
827     local file
828     local end=$(($(date +%s) + ha_load_timeout))
829
830     ha_info "Waiting $ha_load_timeout sec for workload status..."
831     rm -f "${ha_status_files[@]}"
832
833         #
834         # return immediately if ha_stop_file exists,
835         # all status_files not needed to be checked
836         #
837         for file in "${ha_status_files[@]}"; do
838                 if [ -e "$ha_stop_file" ]; then
839                         ha_info "$ha_stop_file found! Stop."
840                         break
841                 fi
842                 #
843                 # Wait status file created during ha_load_timeout.
844                 # Existing file guarantees that some application
845                 # is completed. If no status file was created
846                 # this function guarantees that we allow
847                 # applications to continue after/before
848                 # failover/failback during ha_load_timeout time.
849                 #
850                 until [ -e "$file" ] || (($(date +%s) >= end)); do
851                         #
852                         # check ha_stop_file again, it could appear
853                         # during ha_load_timeout
854                         #
855                         if [ -e "$ha_stop_file" ]; then
856                                 ha_info "$ha_stop_file found! Stop."
857                                 break
858                         fi
859                         ha_sleep 1 >/dev/null
860                 done
861         done
862 }
863
864 ha_powermanage()
865 {
866         local nodes=$1
867         local expected_state=$2
868         local state
869         local -a states
870         local i
871         local rc=0
872
873         # store pm -x -q $nodes results in a file to have
874         # more information about nodes statuses
875         ha_on $ha_pm_host pm -x -q $nodes | awk '{print $2 $3}' > $ha_pm_states
876         rc=${PIPESTATUS[0]}
877         echo pmrc=$rc
878
879         while IFS=": " read node state; do
880                 [[ "$state" = "$expected_state" ]] && {
881                         nodes=${nodes/$node/}
882                         nodes=${nodes//,,/,}
883                         nodes=${nodes/#,}
884                         nodes=${nodes/%,}
885                 }
886         done < $ha_pm_states
887
888         if [ -n "$nodes" ]; then
889                 cat $ha_pm_states
890                 return 1
891         fi
892         return 0
893 }
894
895 ha_power_down_cmd_fn()
896 {
897         local nodes=$1
898         local cmd
899
900         case $ha_power_down_cmd in
901         # format is: POWER_DOWN=sysrqcrash
902         sysrqcrash) cmd="pdsh -S -w $nodes 'echo c > /proc/sysrq-trigger' &" ;;
903         *) cmd="$ha_power_down_cmd $nodes" ;;
904         esac
905
906         eval $cmd
907 }
908
909 ha_power_down()
910 {
911         local nodes=$1
912         local rc=1
913         local i
914         local state
915
916         case $ha_power_down_cmd in
917                 *pm*) state=off ;;
918                 sysrqcrash) state=off ;;
919                 *) state=on;;
920         esac
921
922         if $ha_lfsck_bg && [[ ${nodes//,/ /} =~ $ha_lfsck_node ]]; then
923                 ha_info "$ha_lfsck_node down, delay start LFSCK"
924                 ha_lock $ha_lfsck_lock
925         fi
926
927         ha_info "Powering down $nodes : cmd: $ha_power_down_cmd"
928         for (( i=0; i<10; i++ )) {
929                 ha_info "attempt: $i"
930                 ha_power_down_cmd_fn $nodes &&
931                         ha_powermanage $nodes $state && rc=0 && break
932                 sleep $ha_power_delay
933         }
934
935         [ $rc -eq 0 ] || {
936                 ha_info "Failed Powering down in $i attempts:" \
937                         "$ha_power_down_cmd"
938                 cat $ha_pm_states
939                 exit 1
940         }
941 }
942
943 ha_get_pair()
944 {
945         local node=$1
946         local i
947
948         for ((i=0; i<${#ha_victims[@]}; i++)) {
949                 [[ ${ha_victims[i]} == $node ]] && echo ${ha_victims_pair[i]} &&
950                         return
951         }
952         [[ $i -ne ${#ha_victims[@]} ]] ||
953                 ha_error "No pair found!"
954 }
955
956 ha_power_up_delay()
957 {
958         local nodes=$1
959         local end=$(($(date +%s) + ha_node_up_delay))
960         local rc
961
962         if [[ ${#ha_victims_pair[@]} -eq 0 ]]; then
963                 ha_sleep $ha_node_up_delay
964                 return 0
965         fi
966
967         # Check CRM status on failover pair
968         while (($(date +%s) <= end)); do
969                 rc=0
970                 for n in ${nodes//,/ }; do
971                         local pair=$(ha_get_pair $n)
972                         local status=$(ha_on $pair crm_mon -1rQ | \
973                                 grep -w $n | head -1)
974
975                         ha_info "$n pair: $pair status: $status"
976                         [[ "$status" == *OFFLINE* ]] ||
977                                 rc=$((rc + $?))
978                         ha_info "rc: $rc"
979                 done
980
981                 if [[ $rc -eq 0 ]];  then
982                         ha_info "CRM: Got all victims status OFFLINE"
983                         return 0
984                 fi
985                 sleep 60
986         done
987
988         ha_info "$nodes CRM status not OFFLINE"
989         for n in ${nodes//,/ }; do
990                 local pair=$(ha_get_pair $n)
991
992                 ha_info "CRM --- $n"
993                 ha_on $pair crm_mon -1rQ
994         done
995         ha_error "CRM: some of $nodes are not OFFLINE in $ha_node_up_delay sec"
996         exit 1
997 }
998
999 ha_power_up()
1000 {
1001         local nodes=$1
1002         local rc=1
1003         local i
1004
1005         ha_power_up_delay $nodes
1006         ha_info "Powering up $nodes : cmd: $ha_power_up_cmd"
1007         for (( i=0; i<10; i++ )) {
1008                 ha_info "attempt: $i"
1009                 $ha_power_up_cmd $nodes &&
1010                         ha_powermanage $nodes on && rc=0 && break
1011                 sleep $ha_power_delay
1012         }
1013
1014         [ $rc -eq 0 ] || {
1015                 ha_info "Failed Powering up in $i attempts: $ha_power_up_cmd"
1016                 cat $ha_pm_states
1017                 exit 1
1018         }
1019 }
1020
1021 #
1022 # rand MAX
1023 #
1024 # Print a random integer within [0, MAX).
1025 #
1026 ha_rand()
1027 {
1028     local max=$1
1029
1030     #
1031     # See "5.2 Bash Variables" from "info bash".
1032     #
1033     echo -n $((RANDOM * max / 32768))
1034 }
1035
1036 ha_aim()
1037 {
1038         local i
1039         local nodes
1040
1041         if $ha_simultaneous ; then
1042                 nodes=$(echo ${ha_victims[@]})
1043                 nodes=${nodes// /,}
1044         else
1045                 i=$(ha_rand ${#ha_victims[@]})
1046                 nodes=${ha_victims[$i]}
1047         fi
1048
1049         echo -n $nodes
1050 }
1051
1052 ha_wait_nodes()
1053 {
1054         local nodes=$1
1055         local end=$(($(date +%s) + 10 * 60))
1056
1057         ha_info "Waiting for $nodes to boot up"
1058         until ha_on $nodes hostname >/dev/null 2>&1 ||
1059                 [ -e "$ha_stop_file" ] ||
1060                         (($(date +%s) >= end)); do
1061                 ha_sleep 1 >/dev/null
1062         done
1063 }
1064
1065 ha_failback()
1066 {
1067         local nodes=$1
1068         ha_info "Failback resources on $nodes in $ha_failback_delay sec"
1069
1070         ha_sleep $ha_failback_delay
1071         [ "$ha_failback_cmd" ] ||
1072         {
1073                 ha_info "No failback command set, skiping"
1074                 return 0
1075         }
1076
1077         $ha_failback_cmd $nodes
1078         [ -e $ha_lfsck_lock ] && ha_unlock $ha_lfsck_lock || true
1079 }
1080
1081 ha_summarize()
1082 {
1083     ha_info "---------------8<---------------"
1084     ha_info "Summary:"
1085     ha_info "    Duration: $(($(date +%s) - $ha_start_time))s"
1086     ha_info "    Loops: $ha_nr_loops"
1087 }
1088
1089 ha_killer()
1090 {
1091         local nodes
1092
1093         while (($(date +%s) < ha_start_time + ha_expected_duration)) &&
1094                         [ ! -e "$ha_stop_file" ]; do
1095                 ha_info "---------------8<---------------"
1096
1097                 $ha_workloads_only || nodes=$(ha_aim)
1098
1099                 ha_info "Failing $nodes"
1100                 $ha_workloads_only && ha_info "    is skipped: workload only..."
1101
1102                 ha_sleep $(ha_rand $ha_max_failover_period)
1103                 $ha_workloads_only || ha_power_down $nodes
1104                 ha_sleep 10
1105                 ha_wait_loads || return
1106
1107                 if [ -e $ha_stop_file ]; then
1108                         $ha_workloads_only || ha_power_up $nodes
1109                         break
1110                 fi
1111
1112                 ha_info "Bringing $nodes back"
1113                 ha_sleep $(ha_rand 10)
1114                 $ha_workloads_only ||
1115                 {
1116                         ha_power_up $nodes
1117                         ha_wait_nodes $nodes
1118                         ha_failback $nodes
1119                 }
1120
1121                 #
1122                 # Wait for the failback to start.
1123                 #
1124                 ha_sleep 60
1125                 ha_wait_loads || return
1126
1127                 ha_sleep $(ha_rand 20)
1128
1129                 ha_nr_loops=$((ha_nr_loops + 1))
1130                 ha_info "Loop $ha_nr_loops done"
1131         done
1132         ha_summarize
1133 }
1134
1135 ha_main()
1136 {
1137         ha_process_arguments "$@"
1138         ha_check_env
1139
1140         ha_log "${ha_clients[*]} ${ha_servers[*]}" \
1141                 "START: $0: $(date +%H:%M:%S' '%s)"
1142         trap ha_trap_exit EXIT
1143         mkdir "$ha_tmp_dir"
1144
1145         local mdt_index
1146         if $ha_test_dir_mdt_index_random &&
1147                 [ $ha_test_dir_mdt_index -ne 0 ]; then
1148                 mdt_index=$(ha_rand $ha_test_dir_mdt_index)
1149         else
1150                 mdt_index=$ha_test_dir_mdt_index
1151         fi
1152
1153         local dir
1154         test_dir=${ha_testdirs[0]}
1155         ha_on ${ha_clients[0]} "$LFS mkdir -i$mdt_index \
1156                 -c$ha_test_dir_stripe_count $test_dir"
1157         for ((i=0; i<${#ha_testdirs[@]}; i++)); do
1158                 test_dir=${ha_testdirs[i]}
1159                 ha_on ${ha_clients[0]} $LFS getdirstripe $test_dir
1160                 ha_on ${ha_clients[0]} " \
1161                         $LFS setstripe $ha_stripe_params $test_dir"
1162         done
1163
1164         ha_start_loads
1165         ha_wait_loads
1166
1167         if $ha_workloads_dry_run; then
1168                 ha_sleep 5
1169         else
1170                 ha_killer
1171                 ha_dump_logs "${ha_clients[*]} ${ha_servers[*]}"
1172         fi
1173
1174         ha_stop_loads
1175
1176         $ha_lfsck_after && ha_start_lfsck | tee -a $ha_lfsck_log
1177
1178         $ha_lfsck_fail_on_repaired && ha_lfsck_repaired
1179
1180         if [ -e "$ha_fail_file" ]; then
1181                 exit 1
1182         else
1183                 ha_log "${ha_clients[*]} ${ha_servers[*]}" \
1184                         "END: $0: $(date +%H:%M:%S' '%s)"
1185                 exit 0
1186         fi
1187 }
1188
1189 ha_main "$@"