Whamcloud - gitweb
2f798525b3974eaad7cd03ce07de07febc9d6127
[fs/lustre-release.git] / lustre / tests / test-framework.sh
1 #!/bin/bash
2
3 trap 'print_summary && print_stack_trace | tee $TF_FAIL && \
4     echo "$TESTSUITE: FAIL: test-framework exiting on error"' ERR
5 set -e
6
7 export LANG=en_US
8 export REFORMAT=${REFORMAT:-""}
9 export WRITECONF=${WRITECONF:-""}
10 export VERBOSE=${VERBOSE:-false}
11 export GSS=${GSS:-false}
12 export GSS_SK=${GSS_SK:-false}
13 export GSS_KRB5=false
14 export SHARED_KEY=${SHARED_KEY:-false}
15 export SK_PATH=${SK_PATH:-/tmp/test-framework-keys}
16 export SK_OM_PATH=$SK_PATH'/tmp-request-mount'
17 export SK_MOUNTED=${SK_MOUNTED:-false}
18 export SK_FLAVOR=${SK_FLAVOR:-ski}
19 export SK_NO_KEY=${SK_NO_KEY:-true}
20 export SK_UNIQUE_NM=${SK_UNIQUE_NM:-false}
21 export SK_S2S=${SK_S2S:-false}
22 export SK_S2SNM=${SK_S2SNM:-TestFrameNM}
23 export SK_S2SNMCLI=${SK_S2SNMCLI:-TestFrameNMCli}
24 export SK_SKIPFIRST=${SK_SKIPFIRST:-true}
25 # whether identity upcall is enabled (true), disabled (false), or default
26 export IDENTITY_UPCALL=${IDENTITY_UPCALL:-default}
27 export QUOTA_AUTO=1
28 export FLAKEY=${FLAKEY:-true}
29 # specify environment variable containing batch job name for server statistics
30 export JOBID_VAR=${JOBID_VAR:-"procname_uid"}  # or "existing" or "disable"
31
32 #export PDSH="pdsh -S -Rssh -w"
33 export MOUNT_CMD=${MOUNT_CMD:-"mount -t lustre"}
34 export UMOUNT=${UMOUNT:-"umount -d"}
35
36 export LSNAPSHOT_CONF="/etc/ldev.conf"
37 export LSNAPSHOT_LOG="/var/log/lsnapshot.log"
38
39 export DATA_SEQ_MAX_WIDTH=0x1ffffff
40
41 # sles12 umount has a issue with -d option
42 [ -e /etc/SuSE-release ] && grep -w VERSION /etc/SuSE-release | grep -wq 12 && {
43         export UMOUNT="umount"
44 }
45
46 # function used by scripts run on remote nodes
47 LUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}
48 . $LUSTRE/tests/functions.sh
49 . $LUSTRE/tests/yaml.sh
50
51 export LD_LIBRARY_PATH=${LUSTRE}/utils/.libs:${LUSTRE}/utils:${LD_LIBRARY_PATH}
52
53 LUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}
54
55 EXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}
56
57 if [ -f "$EXCEPT_LIST_FILE" ]; then
58         echo "Reading test skip list from $EXCEPT_LIST_FILE"
59         cat $EXCEPT_LIST_FILE
60         . $EXCEPT_LIST_FILE
61 fi
62
63 # check config files for options in decreasing order of preference
64 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/lustre.conf ] &&
65     MODPROBECONF=/etc/modprobe.d/lustre.conf
66 [ -z "$MODPROBECONF" -a -f /etc/modprobe.d/Lustre ] &&
67     MODPROBECONF=/etc/modprobe.d/Lustre
68 [ -z "$MODPROBECONF" -a -f /etc/modprobe.conf ] &&
69     MODPROBECONF=/etc/modprobe.conf
70
71 sanitize_parameters() {
72         for i in DIR DIR1 DIR2 MOUNT MOUNT1 MOUNT2
73         do
74                 local path=${!i}
75
76                 if [ -d "$path" ]; then
77                         eval export $i=$(echo $path | sed -r 's/\/+$//g')
78                 fi
79         done
80 }
81 assert_DIR () {
82         local failed=""
83         [[ $DIR/ = $MOUNT/* ]] ||
84                 { failed=1 && echo "DIR=$DIR not in $MOUNT. Aborting."; }
85         [[ $DIR1/ = $MOUNT1/* ]] ||
86                 { failed=1 && echo "DIR1=$DIR1 not in $MOUNT1. Aborting."; }
87         [[ $DIR2/ = $MOUNT2/* ]] ||
88                 { failed=1 && echo "DIR2=$DIR2 not in $MOUNT2. Aborting"; }
89
90         [ -n "$failed" ] && exit 99 || true
91 }
92
93 usage() {
94         echo "usage: $0 [-r] [-f cfgfile]"
95         echo "       -r: reformat"
96
97         exit
98 }
99
100 print_summary () {
101         trap 0
102         [ -z "$DEFAULT_SUITES" ] && return 0
103         [ -n "$ONLY" ] && echo "WARNING: ONLY is set to $(echo $ONLY)"
104         local details
105         local form="%-13s %-17s %-9s %s %s\n"
106
107         printf "$form" "status" "script" "Total(sec)" "E(xcluded) S(low)"
108         echo "---------------------------------------------------------------"
109         for O in $DEFAULT_SUITES; do
110                 O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
111                 [ "${!O}" = "no" ] && continue || true
112                 local o=$(echo $O  | tr "[:upper:]_" "[:lower:]-")
113                 local log=${TMP}/${o}.log
114
115                 if is_sanity_benchmark $o; then
116                     log=${TMP}/sanity-benchmark.log
117                 fi
118                 local slow=
119                 local skipped=
120                 local total=
121                 local status=Unfinished
122
123                 if [ -f $log ]; then
124                         skipped=$(grep excluded $log |
125                                 awk '{ printf " %s", $3 }' | sed 's/test_//g')
126                         slow=$(egrep "^PASS|^FAIL" $log |
127                                 tr -d "("| sed s/s\)$//g | sort -nr -k 3 |
128                                 head -n5 |  awk '{ print $2":"$3"s" }')
129                         total=$(grep duration $log | awk '{ print $2 }')
130                         if [ "${!O}" = "done" ]; then
131                                 status=Done
132                         fi
133                         if $DDETAILS; then
134                                 local durations=$(egrep "^PASS|^FAIL" $log |
135                                         tr -d "("| sed s/s\)$//g |
136                                         awk '{ print $2":"$3"|" }')
137                                 details=$(printf "%s\n%s %s %s\n" "$details" \
138                                         "DDETAILS" "$O" "$(echo $durations)")
139                         fi
140                 fi
141                 printf "$form" $status "$O" "${total}" "E=$skipped"
142                 printf "$form" "-" "-" "-" "S=$(echo $slow)"
143         done
144
145         for O in $DEFAULT_SUITES; do
146                 O=$(echo $O  | tr "-" "_" | tr "[:lower:]" "[:upper:]")
147                         if [ "${!O}" = "no" ]; then
148                                 printf "$form" "Skipped" "$O" ""
149                         fi
150         done
151
152         # print the detailed tests durations if DDETAILS=true
153         if $DDETAILS; then
154                 echo "$details"
155         fi
156 }
157
158 reset_lustre() {
159         if $do_reset; then
160                 stopall
161                 setupall
162         fi
163 }
164
165 setup_if_needed() {
166         ! ${do_setup} && return
167         nfs_client_mode && return
168         AUSTER_CLEANUP=false
169
170         local MOUNTED=$(mounted_lustre_filesystems)
171
172         if $(echo $MOUNTED' ' | grep -w -q $MOUNT' '); then
173                 check_config_clients $MOUNT
174                 # init_facets_vars
175                 # init_param_vars
176                 return
177         fi
178
179         echo "Lustre is not mounted, trying to do setup ... "
180         $reformat && CLEANUP_DM_DEV=true formatall
181         setupall
182
183         MOUNTED=$(mounted_lustre_filesystems)
184         if ! $(echo $MOUNTED' ' | grep -w -q $MOUNT' '); then
185                 echo "Lustre is not mounted after setup! "
186                 exit 1
187         fi
188         AUSTER_CLEANUP=true
189 }
190
191 cleanup_if_needed() {
192         if $AUSTER_CLEANUP; then
193                 cleanupall
194         fi
195 }
196
197 find_script_in_path() {
198         target=$1
199         path=$2
200         for dir in $(tr : " " <<< $path); do
201                 if [ -f $dir/$target ]; then
202                         echo $dir/$target
203                         return 0
204                 fi
205                 if [ -f $dir/$target.sh ]; then
206                         echo $dir/$target.sh
207                         return 0
208                 fi
209         done
210         return 1
211 }
212
213 title() {
214         log "-----============= acceptance-small: "$*" ============----- `date`"
215 }
216
217 doit() {
218         if $dry_run; then
219                 printf "Would have run: %s\n" "$*"
220                 return 0
221         fi
222         if $verbose; then
223                 printf "Running: %s\n" "$*"
224         fi
225         "$@"
226 }
227
228
229 run_suite() {
230         local suite_name=$1
231         local suite_script=$2
232
233         title $suite_name
234         log_test $suite_name
235
236         rm -f $TF_FAIL
237         touch $TF_SKIP
238
239         local start_ts=$(date +%s)
240
241         doit $script_lang $suite_script
242
243         local rc=$?
244         local duration=$(($(date +%s) - $start_ts))
245         local status="PASS"
246
247         if [[ $rc -ne 0 || -f $TF_FAIL ]]; then
248                 status="FAIL"
249         elif [[ -f $TF_SKIP ]]; then
250                 status="SKIP"
251         fi
252         log_test_status $duration $status
253         [[ ! -f $TF_SKIP ]] || rm -f $TF_SKIP
254
255         reset_lustre
256
257         return $rc
258 }
259
260 run_suite_logged() {
261         local suite_name=${1%.sh}
262         local suite=$(echo ${suite_name} | tr "[:lower:]-" "[:upper:]_")
263
264         suite_script=$(find_script_in_path $suite_name $LUSTRE/tests)
265
266         if [[ -z $suite_script ]]; then
267                 echo "Can't find test script for $suite_name"
268                 return 1
269         fi
270
271         echo "run_suite $suite_name $suite_script"
272
273         local log_name=${suite_name}.suite_log.$(hostname -s).log
274
275         if $verbose; then
276                 run_suite $suite_name $suite_script 2>&1 |tee  $LOGDIR/$log_name
277         else
278                 run_suite $suite_name $suite_script > $LOGDIR/$log_name 2>&1
279         fi
280
281         return ${PIPESTATUS[0]}
282 }
283
284 reset_logging() {
285         export LOGDIR=$1
286
287         unset YAML_LOG
288         init_logging
289 }
290
291 split_commas() {
292         echo "${*//,/ }"
293 }
294
295 run_suites() {
296         local n=0
297         local argv=("$@")
298
299         while ((n < repeat_count)); do
300                 local RC=0
301                 local logdir=${test_logs_dir}
302                 local first_suite=$FIRST_SUITE
303
304                 ((repeat_count > 1)) && logdir="$logdir/$n"
305                 reset_logging $logdir
306                 set -- "${argv[@]}"
307                 while [[ -n $1 ]]; do
308                         unset ONLY EXCEPT START_AT STOP_AT
309                         local opts=""
310                         local time_limit=""
311
312                         suite=$1
313                         shift;
314                         while [[ -n $1 ]]; do
315                         case "$1" in
316                                 --only)
317                                         shift;
318                                         export ONLY=$(split_commas $1)
319
320                                         opts+="ONLY=$ONLY ";;
321                                 --suite)
322                                         shift;
323                                         export SUITE=$(split_commas $1)
324
325                                         opts+="SUITE=$SUITE ";;
326                                 --pattern)
327                                         shift;
328                                         export PATTERN=$(split_commas $1)
329
330                                         opts+="PATTERN=$PATTERN ";;
331                                 --except)
332                                         shift;
333                                         export EXCEPT=$(split_commas $1)
334
335                                         opts+="EXCEPT=$EXCEPT ";;
336                                 --start-at)
337                                         shift;
338                                         export START_AT=$1
339
340                                         opts+="START_AT=$START_AT ";;
341                                 --stop-at)
342                                         shift;
343                                         export STOP_AT=$1
344
345                                         opts+="STOP_AT=$STOP_AT ";;
346                                 --time-limit)
347                                         shift;
348                                         time_limit=$1;;
349                                 *)
350                                         break;;
351                         esac
352                         shift
353                         done
354
355                 # If first_suite not set or this is the first suite
356                 if [ "x"$first_suite == "x" ] || [ $first_suite == $suite ]; then
357                         echo "running: $suite $opts"
358                         run_suite_logged $suite || RC=$?
359                         unset first_suite
360                         echo $suite returned $RC
361                 fi
362                 done
363         if $upload_logs; then
364                 $upload_script $LOGDIR
365         fi
366         n=$((n + 1))
367         done
368 }
369
370 # Get information about the Lustre environment. The information collected
371 # will be used in Lustre tests.
372 # usage: get_lustre_env
373 # input: No required or optional arguments
374 # output: No return values, environment variables are exported
375
376 get_lustre_env() {
377         if ! $RPC_MODE; then
378                 export mds1_FSTYPE=${mds1_FSTYPE:-$(facet_fstype mds1)}
379                 export ost1_FSTYPE=${ost1_FSTYPE:-$(facet_fstype ost1)}
380
381                 export MGS_VERSION=$(lustre_version_code mgs)
382                 export MDS1_VERSION=$(lustre_version_code mds1)
383                 export OST1_VERSION=$(lustre_version_code ost1)
384                 export CLIENT_VERSION=$(lustre_version_code client)
385         fi
386
387         # Prefer using "mds1" directly instead of SINGLEMDS.
388         # Keep this for compat until it is removed from scripts.
389         export SINGLEMDS=${SINGLEMDS:-mds1}
390 }
391
392 init_test_env() {
393         export LUSTRE=$(absolute_path $LUSTRE)
394         export TESTSUITE=$(basename $0 .sh)
395         export TEST_FAILED=false
396         export FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}
397         export RPC_MODE=${RPC_MODE:-false}
398         export DO_CLEANUP=${DO_CLEANUP:-true}
399         export KEEP_ZPOOL=${KEEP_ZPOOL:-false}
400         export CLEANUP_DM_DEV=false
401         export PAGE_SIZE=$(get_page_size client)
402         export NAME=${NAME:-local}
403
404         . ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}
405
406         export MKE2FS=$MKE2FS
407         if [ -z "$MKE2FS" ]; then
408                 if which mkfs.ldiskfs >/dev/null 2>&1; then
409                         export MKE2FS=mkfs.ldiskfs
410                 else
411                         export MKE2FS=mke2fs
412                 fi
413         fi
414
415         export DEBUGFS=$DEBUGFS
416         if [ -z "$DEBUGFS" ]; then
417                 if which debugfs.ldiskfs >/dev/null 2>&1; then
418                         export DEBUGFS=debugfs.ldiskfs
419                 else
420                         export DEBUGFS=debugfs
421                 fi
422         fi
423
424         export TUNE2FS=$TUNE2FS
425         if [ -z "$TUNE2FS" ]; then
426                 if which tunefs.ldiskfs >/dev/null 2>&1; then
427                         export TUNE2FS=tunefs.ldiskfs
428                 else
429                         export TUNE2FS=tune2fs
430                 fi
431         fi
432
433         export E2LABEL=$E2LABEL
434         if [ -z "$E2LABEL" ]; then
435                 if which label.ldiskfs >/dev/null 2>&1; then
436                         export E2LABEL=label.ldiskfs
437                 else
438                         export E2LABEL=e2label
439                 fi
440         fi
441
442         export DUMPE2FS=$DUMPE2FS
443         if [ -z "$DUMPE2FS" ]; then
444                 if which dumpfs.ldiskfs >/dev/null 2>&1; then
445                         export DUMPE2FS=dumpfs.ldiskfs
446                 else
447                         export DUMPE2FS=dumpe2fs
448                 fi
449         fi
450
451         export E2FSCK=$E2FSCK
452         if [ -z "$E2FSCK" ]; then
453                 if which fsck.ldiskfs >/dev/null 2>&1; then
454                         export E2FSCK=fsck.ldiskfs
455                 else
456                          export E2FSCK=e2fsck
457                 fi
458         fi
459
460         export RESIZE2FS=$RESIZE2FS
461         if [ -z "$RESIZE2FS" ]; then
462                 if which resizefs.ldiskfs >/dev/null 2>&1; then
463                         export RESIZE2FS=resizefs.ldiskfs
464                 else
465                         export RESIZE2FS=resize2fs
466                 fi
467         fi
468
469         export LFSCK_ALWAYS=${LFSCK_ALWAYS:-"no"} # check fs after test suite
470         export FSCK_MAX_ERR=4   # File system errors left uncorrected
471
472         export ZFS=${ZFS:-zfs}
473         export ZPOOL=${ZPOOL:-zpool}
474         export ZDB=${ZDB:-zdb}
475         export PARTPROBE=${PARTPROBE:-partprobe}
476
477         #[ -d /r ] && export ROOT=${ROOT:-/r}
478         export TMP=${TMP:-$ROOT/tmp}
479         export TESTSUITELOG=${TMP}/${TESTSUITE}.log
480         export LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}
481         export TESTLOG_PREFIX=$LOGDIR/$TESTSUITE
482
483         export HOSTNAME=${HOSTNAME:-$(hostname -s)}
484         if ! echo $PATH | grep -q $LUSTRE/utils; then
485                 export PATH=$LUSTRE/utils:$PATH
486         fi
487         if ! echo $PATH | grep -q $LUSTRE/utils/gss; then
488                 export PATH=$LUSTRE/utils/gss:$PATH
489         fi
490         if ! echo $PATH | grep -q $LUSTRE/tests; then
491                 export PATH=$LUSTRE/tests:$PATH
492         fi
493         if ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then
494                 export PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH
495         fi
496         export LST=${LST:-"$LUSTRE/../lnet/utils/lst"}
497         [ ! -f "$LST" ] && export LST=$(which lst)
498         export LSTSH=${LSTSH:-"$LUSTRE/../lustre-iokit/lst-survey/lst.sh"}
499         [ ! -f "$LSTSH" ] && export LSTSH=$(which lst.sh)
500         export SGPDDSURVEY=${SGPDDSURVEY:-"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey")}
501         [ ! -f "$SGPDDSURVEY" ] && export SGPDDSURVEY=$(which sgpdd-survey)
502         export MCREATE=${MCREATE:-mcreate}
503         export MULTIOP=${MULTIOP:-multiop}
504         export MMAP_CAT=${MMAP_CAT:-mmap_cat}
505         export STATX=${STATX:-statx}
506         # Ubuntu, at least, has a truncate command in /usr/bin
507         # so fully path our truncate command.
508         export TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}
509         export FSX=${FSX:-$LUSTRE/tests/fsx}
510         export MDSRATE=${MDSRATE:-"$LUSTRE/tests/mpi/mdsrate"}
511         [ ! -f "$MDSRATE" ] && export MDSRATE=$(which mdsrate 2> /dev/null)
512         if ! echo $PATH | grep -q $LUSTRE/tests/racer; then
513                 export PATH=$LUSTRE/tests/racer:$PATH:
514         fi
515         if ! echo $PATH | grep -q $LUSTRE/tests/mpi; then
516                 export PATH=$LUSTRE/tests/mpi:$PATH
517         fi
518
519         export LNETCTL=${LNETCTL:-"$LUSTRE/../lnet/utils/lnetctl"}
520         [ ! -f "$LNETCTL" ] && export LNETCTL=$(which lnetctl 2> /dev/null)
521         export LCTL=${LCTL:-"$LUSTRE/utils/lctl"}
522         [ ! -f "$LCTL" ] && export LCTL=$(which lctl)
523         export LFS=${LFS:-"$LUSTRE/utils/lfs"}
524         [ ! -f "$LFS" ] && export LFS=$(which lfs)
525         export KSOCKLND_CONFIG=${KSOCKLND_CONFIG:-"$LUSTRE/scripts/ksocklnd-config"}
526         [ ! -f "$KSOCKLND_CONFIG" ] &&
527                 export KSOCKLND_CONFIG=$(which ksocklnd-config 2> /dev/null)
528
529         export PERM_CMD=$(echo ${PERM_CMD:-"$LCTL conf_param"})
530
531         export L_GETIDENTITY=${L_GETIDENTITY:-"$LUSTRE/utils/l_getidentity"}
532         if [ ! -f "$L_GETIDENTITY" ]; then
533                 if $(which l_getidentity > /dev/null 2>&1); then
534                         export L_GETIDENTITY=$(which l_getidentity)
535                 else
536                         export L_GETIDENTITY=NONE
537                 fi
538         fi
539         export LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-"$LUSTRE/utils/ll_decode_filter_fid"}
540         [ ! -f "$LL_DECODE_FILTER_FID" ] &&
541                 export LL_DECODE_FILTER_FID="ll_decode_filter_fid"
542         export LL_DECODE_LINKEA=${LL_DECODE_LINKEA:-"$LUSTRE/utils/ll_decode_linkea"}
543         [ ! -f "$LL_DECODE_LINKEA" ] &&
544                 export LL_DECODE_LINKEA="ll_decode_linkea"
545         export MKFS=${MKFS:-"$LUSTRE/utils/mkfs.lustre"}
546         [ ! -f "$MKFS" ] && export MKFS="mkfs.lustre"
547         export TUNEFS=${TUNEFS:-"$LUSTRE/utils/tunefs.lustre"}
548         [ ! -f "$TUNEFS" ] && export TUNEFS="tunefs.lustre"
549         export CHECKSTAT="${CHECKSTAT:-"checkstat -v"} "
550         export LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}
551         [ ! -f "$LUSTRE_RMMOD" ] &&
552                 export LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)
553         export LUSTRE_ROUTES_CONVERSION=${LUSTRE_ROUTES_CONVERSION:-$LUSTRE/scripts/lustre_routes_conversion}
554         [ ! -f "$LUSTRE_ROUTES_CONVERSION" ] &&
555                 export LUSTRE_ROUTES_CONVERSION=$(which lustre_routes_conversion 2> /dev/null)
556         export LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}
557         [ ! -f "$LFS_MIGRATE" ] &&
558                 export LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)
559         export LR_READER=${LR_READER:-"$LUSTRE/utils/lr_reader"}
560         [ ! -f "$LR_READER" ] &&
561                 export LR_READER=$(which lr_reader 2> /dev/null)
562         [ -z "$LR_READER" ] && export LR_READER="/usr/sbin/lr_reader"
563         export LSOM_SYNC=${LSOM_SYNC:-"$LUSTRE/utils/llsom_sync"}
564         [ ! -f "$LSOM_SYNC" ] &&
565                 export LSOM_SYNC=$(which llsom_sync 2> /dev/null)
566         [ -z "$LSOM_SYNC" ] && export LSOM_SYNC="/usr/sbin/llsom_sync"
567         export L_GETAUTH=${L_GETAUTH:-"$LUSTRE/utils/gss/l_getauth"}
568         [ ! -f "$L_GETAUTH" ] && export L_GETAUTH=$(which l_getauth 2> /dev/null)
569         export LSVCGSSD=${LSVCGSSD:-"$LUSTRE/utils/gss/lsvcgssd"}
570         [ ! -f "$LSVCGSSD" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)
571         export KRB5DIR=${KRB5DIR:-"/usr/kerberos"}
572         export DIR2
573         export SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}
574         export AT_MAX_PATH
575         export LDEV=${LDEV:-"$LUSTRE/scripts/ldev"}
576         [ ! -f "$LDEV" ] && export LDEV=$(which ldev 2> /dev/null)
577
578         export DMSETUP=${DMSETUP:-dmsetup}
579         export DM_DEV_PATH=${DM_DEV_PATH:-/dev/mapper}
580         export LOSETUP=${LOSETUP:-losetup}
581
582         if [ "$ACCEPTOR_PORT" ]; then
583                 export PORT_OPT="--port $ACCEPTOR_PORT"
584         fi
585
586         if $SHARED_KEY; then
587                 $RPC_MODE || echo "Using GSS shared-key feature"
588                 [ -n "$LGSS_SK" ] ||
589                         export LGSS_SK=$(which lgss_sk 2> /dev/null)
590                 [ -n "$LGSS_SK" ] ||
591                         export LGSS_SK="$LUSTRE/utils/gss/lgss_sk"
592                 [ -n "$LGSS_SK" ] ||
593                         error_exit "built with lgss_sk disabled! SEC=$SEC"
594                 GSS=true
595                 GSS_SK=true
596                 SEC=$SK_FLAVOR
597         fi
598
599         case "x$SEC" in
600                 xkrb5*)
601                 $RPC_MODE || echo "Using GSS/krb5 ptlrpc security flavor"
602                 which lgss_keyring > /dev/null 2>&1 ||
603                         error_exit "built with gss disabled! SEC=$SEC"
604                 GSS=true
605                 GSS_KRB5=true
606                 ;;
607         esac
608
609         export LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}
610
611         # Paths on remote nodes, if different
612         export RLUSTRE=${RLUSTRE:-$LUSTRE}
613         export RPWD=${RPWD:-$PWD}
614         export I_MOUNTED=${I_MOUNTED:-"no"}
615         export AUSTER_CLEANUP=${AUSTER_CLEANUP:-false}
616         if [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \
617              ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \
618              ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \
619              ! -f $LUSTRE/mdt/mdt.ko ]; then
620             export CLIENTMODSONLY=yes
621         fi
622
623         export SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}
624         export OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-"yes"}
625
626         # command line
627
628         while getopts "rvwf:" opt $*; do
629                 case $opt in
630                         f) CONFIG=$OPTARG;;
631                         r) REFORMAT=yes;;
632                         v) VERBOSE=true;;
633                         w) WRITECONF=writeconf;;
634                         \?) usage;;
635                 esac
636         done
637
638         shift $((OPTIND - 1))
639         ONLY=${ONLY:-$*}
640
641         # print the durations of each test if "true"
642         DDETAILS=${DDETAILS:-false}
643         [ "$TESTSUITELOG" ] && rm -f $TESTSUITELOG || true
644         if ! $RPC_MODE; then
645                 rm -f $TMP/*active
646         fi
647
648         export TF_FAIL=${TF_FAIL:-$TMP/tf.fail}
649
650         # Constants used in more than one test script
651         export LOV_MAX_STRIPE_COUNT=2000
652         export LMV_MAX_STRIPES_PER_MDT=5
653         export DELETE_OLD_POOLS=${DELETE_OLD_POOLS:-false}
654         export KEEP_POOLS=${KEEP_POOLS:-false}
655         export PARALLEL=${PARALLEL:-"no"}
656
657         export BLCKSIZE=${BLCKSIZE:-4096}
658         export MACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}
659         get_lustre_env
660
661         # use localrecov to enable recovery for local clients, LU-12722
662         [[ $MDS1_VERSION -lt $(version_code 2.13.52) ]] || {
663                 export MDS_MOUNT_OPTS=${MDS_MOUNT_OPTS:-"-o localrecov"}
664                 export MGS_MOUNT_OPTS=${MGS_MOUNT_OPTS:-"-o localrecov"}
665         }
666
667         [[ $OST1_VERSION -lt $(version_code 2.13.52) ]] ||
668                 export OST_MOUNT_OPTS=${OST_MOUNT_OPTS:-"-o localrecov"}
669 }
670
671 check_cpt_number() {
672         local facet=$1
673         local ncpts
674
675         ncpts=$(do_facet $facet "lctl get_param -n " \
676                 "cpu_partition_table 2>/dev/null| wc -l" || echo 1)
677
678         if [ $ncpts -eq 0 ]; then
679                 echo "1"
680         else
681                 echo $ncpts
682         fi
683 }
684
685 # Return a numeric version code based on a version string.  The version
686 # code is useful for comparison two version strings to see which is newer.
687 version_code() {
688         # split arguments like "1.8.6-wc3" into "1", "8", "6", "3"
689         eval set -- $(tr "[:punct:][a-zA-Z]" " " <<< $*)
690
691         echo -n $(((${1:-0}<<24) | (${2:-0}<<16) | (${3:-0}<<8) | (${4:-0})))
692 }
693
694 export LINUX_VERSION=$(uname -r | sed -e "s/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/")
695 export LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\./ })
696
697 # Report the Lustre build version string (e.g. 1.8.7.3 or 2.4.1).
698 #
699 # usage: lustre_build_version
700 #
701 # All Lustre versions support "lctl get_param" to report the version of the
702 # code running in the kernel (what our tests are interested in), but it
703 # doesn't work without modules loaded.  After 2.9.53 and in upstream kernels
704 # the "version" parameter doesn't include "lustre: " at the beginning.
705 # If that fails, call "lctl lustre_build_version" which prints either (or both)
706 # the userspace and kernel build versions, but until 2.8.55 required root
707 # access to get the Lustre kernel version.  If that also fails, fall back to
708 # using "lctl --version", which is easy to parse and works without the kernel
709 # modules, but was only added in 2.6.50 and only prints the lctl tool version,
710 # not the module version, though they are usually the same.
711 #
712 # Various commands and their output format for different Lustre versions:
713 # lctl get_param version:       2.9.55
714 # lctl get_param version:       lustre: 2.8.53
715 # lctl get_param version:       lustre: 2.6.52
716 #                               kernel: patchless_client
717 #                               build: v2_6_92_0-2.6.32-431.el6_lustre.x86_64
718 # lctl lustre_build_version:    Lustre version: 2.8.53_27_gae67fc01
719 # lctl lustre_build_version:    error: lustre_build_version: Permission denied
720 #       (as non-root user)      lctl   version: v2_6_92_0-2.6.32-431.el6.x86_64
721 # lctl lustre_build_version:    Lustre version: 2.5.3-2.6.32.26-175.fc12.x86_64
722 #                               lctl   version: 2.5.3-2.6.32..26-175fc12.x86_64
723 # lctl --version:               lctl 2.6.50
724 #
725 # output: prints version string to stdout in (up to 4) dotted-decimal values
726 lustre_build_version() {
727         local facet=${1:-client}
728         local facet_version=${facet}_VERSION
729
730         # if the global variable is already set, then use that
731         [ -n "${!facet_version}" ] && echo ${!facet_version} && return
732
733         # this is the currently-running version of the kernel modules
734         local ver=$(do_facet $facet "$LCTL get_param -n version 2>/dev/null")
735         # we mostly test 2.10+ systems, only try others if the above fails
736         if [ -z "$ver" ]; then
737                 ver=$(do_facet $facet "$LCTL lustre_build_version 2>/dev/null")
738         fi
739         if [ -z "$ver" ]; then
740                 ver=$(do_facet $facet "$LCTL --version 2>/dev/null" |
741                       cut -d' ' -f2)
742         fi
743         local lver=$(egrep -i "lustre: |version: " <<<"$ver" | head -n 1)
744         [ -n "$lver" ] && ver="$lver"
745
746         lver=$(sed -e 's/[^:]*: //' -e 's/^v//' -e 's/[ -].*//' <<<$ver |
747                tr _ . | cut -d. -f1-4)
748
749         # save in global variable for the future
750         export $facet_version=$lver
751
752         echo $lver
753 }
754
755 # Report the Lustre numeric build version code for the supplied facet.
756 lustre_version_code() {
757         version_code $(lustre_build_version $1)
758 }
759
760 module_loaded () {
761         /sbin/lsmod | grep -q "^\<$1\>"
762 }
763
764 check_lfs_df_ret_val() {
765         # Ignore only EOPNOTSUPP (which is 95; Operation not supported) error
766         # returned by 'lfs df' for valid dentry but not a lustrefs.
767         #
768         # 'lfs df' historically always returned success(0) instead of
769         # EOPNOTSUPP. This function for compatibility reason, ignores and
770         # masquerades EOPNOTSUPP as success.
771         [[ $1 -eq 95 ]] && return 0
772         return $1
773 }
774
775 PRLFS=false
776 lustre_insmod() {
777         local module=$1
778         shift
779         local args="$@"
780         local msg
781         local rc=0
782
783         if ! $PRLFS; then
784                 msg="$(insmod $module $args 2>&1)" && return 0 || rc=$?
785         fi
786
787         # parallels can't load modules directly from prlfs, use /tmp instead
788         if $PRLFS || [[ "$(stat -f -c%t $module)" == "7c7c6673" ]]; then
789                 local target="$(mktemp)"
790
791                 cp "$module" "$target"
792                 insmod $target $args
793                 rc=$?
794                 [[ $rc == 0 ]] && PRLFS=true
795                 rm -f $target
796         else
797                 echo "$msg"
798         fi
799         return $rc
800 }
801
802 # Load a module on the system where this is running.
803 #
804 # usage: load_module module_name [module arguments for insmod/modprobe]
805 #
806 # If module arguments are not given but MODOPTS_<MODULE> is set, then its value
807 # will be used as the arguments.  Otherwise arguments will be obtained from
808 # /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.
809 #
810 load_module() {
811         local module=$1 # '../libcfs/libcfs/libcfs', 'obdclass/obdclass', ...
812         shift
813         local ext=".ko"
814         local base=$(basename $module $ext)
815         local path
816         local -A module_is_loaded_aa
817         local optvar
818         local mod
819
820         for mod in $(lsmod | awk '{ print $1; }'); do
821                 module_is_loaded_aa[${mod//-/_}]=true
822         done
823
824         module_is_loaded() {
825                 ${module_is_loaded_aa[${1//-/_}]:-false}
826         }
827
828         if module_is_loaded $base; then
829                 return
830         fi
831
832         if [[ -f $LUSTRE/$module$ext ]]; then
833                 path=$LUSTRE/$module$ext
834         elif [[ "$base" == lnet_selftest ]] &&
835              [[ -f $LUSTRE/../lnet/selftest/$base$ext ]]; then
836                 path=$LUSTRE/../lnet/selftest/$base$ext
837         else
838                 path=''
839         fi
840
841         if [[ -n "$path" ]]; then
842                 # Try to load any non-Lustre modules that $module depends on.
843                 for mod in $(modinfo --field=depends $path | tr ',' ' '); do
844                         if ! module_is_loaded $mod; then
845                                 modprobe $mod
846                         fi
847                 done
848         fi
849
850         # If no module arguments were passed then get them from
851         # $MODOPTS_<MODULE>, otherwise from modprobe.conf.
852         if [ $# -eq 0 ]; then
853                 # $MODOPTS_<MODULE>; we could use associative arrays, but that's
854                 # not in Bash until 4.x, so we resort to eval.
855                 optvar="MODOPTS_$(basename $module | tr a-z A-Z)"
856                 eval set -- \$$optvar
857                 if [ $# -eq 0 -a -n "$MODPROBECONF" ]; then
858                         # Nothing in $MODOPTS_<MODULE>; try modprobe.conf
859                         local opt
860                         opt=$(awk -v var="^options $base" '$0 ~ var \
861                               {gsub("'"options $base"'",""); print}' \
862                                 $MODPROBECONF)
863                         set -- $(echo -n $opt)
864
865                         # Ensure we have accept=all for lnet
866                         if [[ "$base" == lnet ]]; then
867                                 # OK, this is a bit wordy...
868                                 local arg accept_all_present=false
869
870                                 for arg in "$@"; do
871                                         [[ "$arg" == accept=all ]] &&
872                                                 accept_all_present=true
873                                 done
874
875                                 $accept_all_present || set -- "$@" accept=all
876                         fi
877
878                         export $optvar="$*"
879                 fi
880         fi
881
882         [ $# -gt 0 ] && echo "${module} options: '$*'"
883
884         # Note that insmod will ignore anything in modprobe.conf, which is why
885         # we're passing options on the command-line. If $path does not exist
886         # then we must be testing a "make install" or"rpm" installation. Also
887         # note that failing to load ptlrpc_gss is not considered fatal.
888         if [[ -n "$path" ]]; then
889                 lustre_insmod $path "$@"
890         elif [[ "$base" == ptlrpc_gss ]]; then
891                 if ! modprobe $base "$@" 2>/dev/null; then
892                         echo "gss/krb5 is not supported"
893                 fi
894         else
895                 modprobe $base "$@"
896         fi
897 }
898
899 do_lnetctl() {
900         $LCTL mark "$LNETCTL $*"
901         echo "$LNETCTL $*"
902         $LNETCTL "$@"
903 }
904
905 load_lnet() {
906         # For kmemleak-enabled kernels we need clear all past state
907         # that obviously has nothing to do with this Lustre run
908         # Disable automatic memory scanning to avoid perf hit.
909         if [ -f /sys/kernel/debug/kmemleak ] ; then
910                 echo scan=off > /sys/kernel/debug/kmemleak || true
911                 echo scan > /sys/kernel/debug/kmemleak || true
912                 echo clear > /sys/kernel/debug/kmemleak || true
913         fi
914
915         echo Loading modules from $LUSTRE
916
917         local ncpus
918
919         if [ -f /sys/devices/system/cpu/online ]; then
920                 ncpus=$(($(cut -d "-" -f 2 /sys/devices/system/cpu/online) + 1))
921                 echo "detected $ncpus online CPUs by sysfs"
922         else
923                 ncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)
924                 local rc=$?
925
926                 if [ $rc -eq 0 ]; then
927                         echo "detected $ncpus online CPUs by getconf"
928                 else
929                         echo "Can't detect number of CPUs"
930                         ncpus=1
931                 fi
932         fi
933
934         # if there is only one CPU core, libcfs can only create one partition
935         # if there is more than 4 CPU cores, libcfs should create multiple CPU
936         # partitions. So we just force libcfs to create 2 partitions for
937         # system with 2 or 4 cores
938         local saved_opts="$MODOPTS_LIBCFS"
939
940         if [ $ncpus -le 4 ] && [ $ncpus -gt 1 ]; then
941                 # force to enable multiple CPU partitions
942                 echo "Force libcfs to create 2 CPU partitions"
943                 MODOPTS_LIBCFS="cpu_npartitions=2 $MODOPTS_LIBCFS"
944         else
945                 echo "libcfs will create CPU partition based on online CPUs"
946         fi
947
948         load_module ../libcfs/libcfs/libcfs
949         # Prevent local MODOPTS_LIBCFS being passed as part of environment
950         # variable to remote nodes
951         unset MODOPTS_LIBCFS
952
953         set_default_debug "neterror net nettrace malloc"
954         if [ "$1" = "config_on_load=1" ]; then
955                 load_module ../lnet/lnet/lnet
956         else
957                 load_module ../lnet/lnet/lnet "$@"
958         fi
959
960         LNDPATH=${LNDPATH:-"../lnet/klnds"}
961         if [ -z "$LNETLND" ]; then
962                 case $NETTYPE in
963                 o2ib*)  LNETLND="o2iblnd/ko2iblnd" ;;
964                 tcp*)   LNETLND="socklnd/ksocklnd" ;;
965                 kfi*)   LNETLND="kfilnd/kkfilnd" ;;
966                 gni*)   LNETLND="gnilnd/kgnilnd" ;;
967                 *)      local lnd="${NETTYPE%%[0-9]}lnd"
968                         [ -f "$LNDPATH/$lnd/k$lnd.ko" ] &&
969                                 LNETLND="$lnd/k$lnd" ||
970                                 LNETLND="socklnd/ksocklnd"
971                 esac
972         fi
973         load_module ../lnet/klnds/$LNETLND
974
975         if [ "$1" = "config_on_load=1" ]; then
976                 do_lnetctl lnet configure --all ||
977                         return $?
978         fi
979 }
980
981 load_modules_local() {
982         if [ -n "$MODPROBE" ]; then
983                 # use modprobe
984                 echo "Using modprobe to load modules"
985                 return 0
986         fi
987
988         # Create special udev test rules on every node
989         if [ -f $LUSTRE/lustre/conf/99-lustre.rules ]; then {
990                 sed -e 's|/usr/sbin/lctl|$LCTL|g' $LUSTRE/lustre/conf/99-lustre.rules > /etc/udev/rules.d/99-lustre-test.rules
991         } else {
992                 echo "SUBSYSTEM==\"lustre\", ACTION==\"change\", ENV{PARAM}==\"?*\", RUN+=\"$LCTL set_param '\$env{PARAM}=\$env{SETTING}'\"" > /etc/udev/rules.d/99-lustre-test.rules
993         } fi
994         udevadm control --reload-rules
995         udevadm trigger
996
997         load_lnet
998
999         load_module obdclass/obdclass
1000         if ! client_only; then
1001                 MODOPTS_PTLRPC=${MODOPTS_PTLRPC:-"lbug_on_grant_miscount=1"}
1002         fi
1003         load_module ptlrpc/ptlrpc
1004         load_module ptlrpc/gss/ptlrpc_gss
1005         load_module fld/fld
1006         load_module fid/fid
1007         load_module lmv/lmv
1008         load_module osc/osc
1009         load_module lov/lov
1010         load_module mdc/mdc
1011         load_module mgc/mgc
1012         load_module obdecho/obdecho
1013         if ! client_only; then
1014                 load_module lfsck/lfsck
1015                 [ "$LQUOTA" != "no" ] &&
1016                         load_module quota/lquota $LQUOTAOPTS
1017                 if [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then
1018                         load_module osd-zfs/osd_zfs
1019                 elif [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
1020                         load_module ../ldiskfs/ldiskfs
1021                         load_module osd-ldiskfs/osd_ldiskfs
1022                 fi
1023                 load_module mgs/mgs
1024                 load_module mdd/mdd
1025                 load_module mdt/mdt
1026                 # don't fail if ost module doesn't exist
1027                 load_module ost/ost 2>/dev/null || true;
1028                 load_module lod/lod
1029                 load_module ofd/ofd
1030                 load_module osp/osp
1031         fi
1032
1033         load_module llite/lustre
1034         [ -d /r ] && OGDB=${OGDB:-"/r/tmp"}
1035         OGDB=${OGDB:-$TMP}
1036         rm -f $OGDB/ogdb-$HOSTNAME
1037         $LCTL modules > $OGDB/ogdb-$HOSTNAME
1038
1039         # 'mount' doesn't look in $PATH, just sbin
1040         local mount_lustre=$LUSTRE/utils/mount.lustre
1041         if [ -f $mount_lustre ]; then
1042                 local sbin_mount=$(readlink -f /sbin)/mount.lustre
1043                 if grep -qw "$sbin_mount" /proc/mounts; then
1044                         cmp -s $mount_lustre $sbin_mount || umount $sbin_mount
1045                 fi
1046                 if ! grep -qw "$sbin_mount" /proc/mounts; then
1047                         [ ! -f "$sbin_mount" ] && touch "$sbin_mount"
1048                         if [ ! -s "$sbin_mount" -a -w "$sbin_mount" ]; then
1049                                 cat <<- EOF > "$sbin_mount"
1050                                 #!/bin/bash
1051                                 #STUB MARK
1052                                 echo "This $sbin_mount just a mountpoint." 1>&2
1053                                 echo "It is never supposed to be run." 1>&2
1054                                 logger -p emerg -- "using stub $sbin_mount $@"
1055                                 exit 1
1056                                 EOF
1057                                 chmod a+x $sbin_mount
1058                         fi
1059                         mount --bind $mount_lustre $sbin_mount ||
1060                                 error "can't bind $mount_lustre to $sbin_mount"
1061                 fi
1062         fi
1063 }
1064
1065 load_modules () {
1066         local facets
1067         local facet
1068         local failover
1069         load_modules_local
1070         # bug 19124
1071         # load modules on remote nodes optionally
1072         # lustre-tests have to be installed on these nodes
1073         if $LOAD_MODULES_REMOTE; then
1074                 local list=$(comma_list $(remote_nodes_list))
1075
1076                 # include failover nodes in case they are not in the list yet
1077                 facets=$(get_facets)
1078                 for facet in ${facets//,/ }; do
1079                         failover=$(facet_failover_host $facet)
1080                         [ -n "$list" ] && [[ ! "$list" =~ "$failover" ]] &&
1081                                 list="$list,$failover"
1082                 done
1083
1084                 if [ -n "$list" ]; then
1085                         echo "loading modules on: '$list'"
1086                         do_rpc_nodes "$list" load_modules_local
1087                 fi
1088         fi
1089 }
1090
1091 check_mem_leak () {
1092         LEAK_LUSTRE=$(dmesg | tail -n 30 | grep "obd_memory.*leaked" || true)
1093         LEAK_PORTALS=$(dmesg | tail -n 20 | egrep -i "libcfs.*memory leaked" ||
1094                 true)
1095         if [ "$LEAK_LUSTRE" -o "$LEAK_PORTALS" ]; then
1096                 echo "$LEAK_LUSTRE" 1>&2
1097                 echo "$LEAK_PORTALS" 1>&2
1098                 mv $TMP/debug $TMP/debug-leak.`date +%s` || true
1099                 echo "Memory leaks detected"
1100                 [ -n "$IGNORE_LEAK" ] &&
1101                         { echo "ignoring leaks" && return 0; } || true
1102                 return 1
1103         fi
1104 }
1105
1106 unload_modules_local() {
1107         $LUSTRE_RMMOD ldiskfs || return 2
1108
1109         [ -f /etc/udev/rules.d/99-lustre-test.rules ] &&
1110                 rm /etc/udev/rules.d/99-lustre-test.rules
1111         udevadm control --reload-rules
1112         udevadm trigger
1113
1114         check_mem_leak || return 254
1115
1116         return 0
1117 }
1118
1119 unload_modules() {
1120         local rc=0
1121
1122         wait_exit_ST client # bug 12845
1123
1124         unload_modules_local || rc=$?
1125
1126         if $LOAD_MODULES_REMOTE; then
1127                 local list=$(comma_list $(remote_nodes_list))
1128                 if [ -n "$list" ]; then
1129                         echo "unloading modules on: '$list'"
1130                         do_rpc_nodes "$list" unload_modules_local
1131                 fi
1132         fi
1133
1134         local sbin_mount=$(readlink -f /sbin)/mount.lustre
1135         if grep -qe "$sbin_mount " /proc/mounts; then
1136                 umount $sbin_mount || true
1137                 [ -s $sbin_mount ] && ! grep -q "STUB MARK" $sbin_mount ||
1138                         rm -f $sbin_mount
1139         fi
1140
1141         [[ $rc -eq 0 ]] && echo "modules unloaded."
1142
1143         return $rc
1144 }
1145
1146 fs_log_size() {
1147         local facet=${1:-ost1}
1148         local size=0
1149         local mult=$OSTCOUNT
1150
1151         case $(facet_fstype $facet) in
1152                 ldiskfs) size=32;; # largest seen is 64 with multiple OSTs
1153                 # grant_block_size is in bytes, allow at least 2x max blocksize
1154                 zfs)     size=$(lctl get_param osc.$FSNAME*.import |
1155                                 awk '/grant_block_size:/ {print $2/512; exit;}')
1156                           ;;
1157         esac
1158
1159         [[ $facet =~ mds ]] && mult=$MDTCOUNT
1160         echo -n $((size * mult))
1161 }
1162
1163 fs_inode_ksize() {
1164         local facet=${1:-$SINGLEMDS}
1165         local fstype=$(facet_fstype $facet)
1166         local size=0
1167         case $fstype in
1168                 ldiskfs) size=4;;  # ~4KB per inode
1169                 zfs)     size=11;; # 10 to 11KB per inode
1170         esac
1171
1172         echo -n $size
1173 }
1174
1175 runas_su() {
1176         local user=$1
1177         local cmd=$2
1178         shift 2
1179         local opts="$*"
1180
1181         if $VERBOSE; then
1182                 echo Running as $user: $cmd $opts
1183         fi
1184         cmd=$(which $cmd)
1185         su - $user -c "$cmd $opts"
1186 }
1187
1188 check_gss_daemon_nodes() {
1189         local list=$1
1190         local dname=$2
1191         local loopmax=10
1192         local loop
1193         local node
1194         local ret
1195
1196         dname=$(basename "$dname" | awk '{print $1}')
1197         do_nodesv $list "num=0;
1198 for proc in \\\$(pgrep $dname); do
1199 [ \\\$(ps -o ppid= -p \\\$proc) -ne 1 ] || ((num++))
1200 done;
1201 if [ \\\"\\\$num\\\" -ne 1 ]; then
1202     echo \\\$num instance of $dname;
1203     exit 1;
1204 fi; "
1205         ret=$?
1206         (( $ret == 0 )) || return $ret
1207
1208         for node in ${list//,/ }; do
1209                 loop=0
1210                 while (( $loop < $loopmax )); do
1211                         do_nodesv $node "$L_GETAUTH -d"
1212                         ret=$?
1213                         (( $ret == 0 )) && break
1214                         loop=$((loop + 1))
1215                         sleep 5
1216                 done
1217                 (( $loop < $loopmax )) || return 1
1218         done
1219         return 0
1220 }
1221
1222 check_gss_daemon_facet() {
1223         local facet=$1
1224         local dname=$2
1225
1226         dname=$(basename "$dname" | awk '{print $1}')
1227         num=$(do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l)
1228         if [ $num -ne 1 ]; then
1229                 echo "$num instance of $dname on $facet"
1230                 return 1
1231         fi
1232         return 0
1233 }
1234
1235 send_sigint() {
1236         local list=$1
1237
1238         shift
1239         echo "Stopping "$@" on $list"
1240         do_nodes $list "killall -2 $* 2>/dev/null || true"
1241 }
1242
1243 # start gss daemons on all nodes, or "daemon" on "nodes" if set
1244 start_gss_daemons() {
1245         local nodes=$1
1246         local daemon=$2
1247         local options=$3
1248
1249         if [ "$nodes" ] && [ "$daemon" ] ; then
1250                 echo "Starting gss daemon on nodes: $nodes"
1251                 do_nodes $nodes "$daemon" "$options" || return 8
1252                 check_gss_daemon_nodes $nodes "$daemon" || return 9
1253                 return 0
1254         fi
1255
1256         nodes=$(comma_list $(mdts_nodes))
1257         echo "Starting gss daemon on mds: $nodes"
1258         if $GSS_SK; then
1259                 # Start all versions, in case of switching
1260                 do_nodes $nodes "$LSVCGSSD -vvv -s -m -o -z $options" ||
1261                         return 1
1262         else
1263                 do_nodes $nodes "$LSVCGSSD -vvv $options" || return 1
1264         fi
1265
1266         nodes=$(comma_list $(osts_nodes))
1267         echo "Starting gss daemon on ost: $nodes"
1268         if $GSS_SK; then
1269                 # Start all versions, in case of switching
1270                 do_nodes $nodes "$LSVCGSSD -vvv -s -m -o -z $options" ||
1271                         return 3
1272         else
1273                 do_nodes $nodes "$LSVCGSSD -vvv $options" || return 3
1274         fi
1275         # starting on clients
1276
1277         local clients=${CLIENTS:-$HOSTNAME}
1278
1279         #
1280         # check daemons are running
1281         #
1282         nodes=$(comma_list $(mdts_nodes) $(osts_nodes))
1283         check_gss_daemon_nodes $nodes "$LSVCGSSD" || return 5
1284 }
1285
1286 stop_gss_daemons() {
1287         local nodes=$(comma_list $(mdts_nodes))
1288
1289         send_sigint $nodes lsvcgssd lgssd
1290
1291         nodes=$(comma_list $(osts_nodes))
1292         send_sigint $nodes lsvcgssd
1293
1294         nodes=${CLIENTS:-$HOSTNAME}
1295         send_sigint $nodes lgssd
1296 }
1297
1298 add_sk_mntflag() {
1299         # Add mount flags for shared key
1300         local mt_opts=$@
1301
1302         if grep -q skpath <<< "$mt_opts" ; then
1303                 mt_opts=$(echo $mt_opts |
1304                         sed -e "s#skpath=[^ ,]*#skpath=$SK_PATH#")
1305         else
1306                 if [ -z "$mt_opts" ]; then
1307                         mt_opts="-o skpath=$SK_PATH"
1308                 else
1309                         mt_opts="$mt_opts,skpath=$SK_PATH"
1310                 fi
1311         fi
1312         echo -n $mt_opts
1313 }
1314
1315 from_build_tree() {
1316         local from_tree
1317
1318         case $LUSTRE in
1319         /usr/lib/lustre/* | /usr/lib64/lustre/* | /usr/lib/lustre | \
1320         /usr/lib64/lustre )
1321                 from_tree=false
1322                 ;;
1323         *)
1324                 from_tree=true
1325                 ;;
1326         esac
1327
1328         [ $from_tree = true ]
1329 }
1330
1331 init_gss() {
1332         if $SHARED_KEY; then
1333                 GSS=true
1334                 GSS_SK=true
1335         fi
1336
1337         if ! $GSS; then
1338                 return
1339         fi
1340
1341         if ! module_loaded ptlrpc_gss; then
1342                 load_module ptlrpc/gss/ptlrpc_gss
1343                 module_loaded ptlrpc_gss ||
1344                         error_exit "init_gss: GSS=$GSS, but gss/krb5 missing"
1345         fi
1346
1347         if $GSS_KRB5 || $GSS_SK; then
1348                 start_gss_daemons || error_exit "start gss daemon failed! rc=$?"
1349         fi
1350
1351         if $GSS_SK && ! $SK_NO_KEY; then
1352                 echo "Loading basic SSK keys on all servers"
1353                 do_nodes $(comma_list $(all_server_nodes)) \
1354                         "$LGSS_SK -t server -l $SK_PATH/$FSNAME.key || true"
1355                 do_nodes $(comma_list $(all_server_nodes)) \
1356                                 "keyctl show | grep lustre | cut -c1-11 |
1357                                 sed -e 's/ //g;' |
1358                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
1359         fi
1360
1361         if $GSS_SK && $SK_NO_KEY; then
1362                 local numclients=${1:-$CLIENTCOUNT}
1363                 local clients=${CLIENTS:-$HOSTNAME}
1364
1365                 # security ctx config for keyring
1366                 SK_NO_KEY=false
1367                 local lgssc_conf_file="/etc/request-key.d/lgssc.conf"
1368
1369                 if from_build_tree; then
1370                         mkdir -p $SK_OM_PATH
1371                         if grep -q request-key /proc/mounts > /dev/null; then
1372                                 echo "SSK: Request key already mounted."
1373                         else
1374                                 mount -o bind $SK_OM_PATH /etc/request-key.d/
1375                         fi
1376                         local lgssc_conf_line='create lgssc * * '
1377                         lgssc_conf_line+=$(which lgss_keyring)
1378                         lgssc_conf_line+=' %o %k %t %d %c %u %g %T %P %S'
1379                         echo "$lgssc_conf_line" > $lgssc_conf_file
1380                 fi
1381
1382                 [ -e $lgssc_conf_file ] ||
1383                         error_exit "Could not find key options in $lgssc_conf_file"
1384                 echo "$lgssc_conf_file content is:"
1385                 cat $lgssc_conf_file
1386
1387                 if ! local_mode; then
1388                         if from_build_tree; then
1389                                 do_nodes $(comma_list $(all_nodes)) "mkdir -p \
1390                                         $SK_OM_PATH"
1391                                 do_nodes $(comma_list $(all_nodes)) "mount \
1392                                         -o bind $SK_OM_PATH \
1393                                         /etc/request-key.d/"
1394                                 do_nodes $(comma_list $(all_nodes)) "rsync \
1395                                         -aqv $HOSTNAME:$lgssc_conf_file \
1396                                         $lgssc_conf_file >/dev/null 2>&1"
1397                         else
1398                                 do_nodes $(comma_list $(all_nodes)) \
1399                                         "echo $lgssc_conf_file: ; \
1400                                         cat $lgssc_conf_file"
1401                         fi
1402                 fi
1403
1404                 # create shared key on all nodes
1405                 mkdir -p $SK_PATH/nodemap
1406                 rm -f $SK_PATH/$FSNAME.key $SK_PATH/nodemap/c*.key \
1407                         $SK_PATH/$FSNAME-*.key
1408                 # for nodemap testing each client may need own key,
1409                 # and S2S now requires keys as well, both for "client"
1410                 # and for "server"
1411                 if $SK_S2S; then
1412                         $LGSS_SK -t server -f$FSNAME -n $SK_S2SNMCLI \
1413                                 -w $SK_PATH/$FSNAME-nmclient.key \
1414                                 -d /dev/urandom >/dev/null 2>&1
1415                         $LGSS_SK -t mgs,server -f$FSNAME -n $SK_S2SNM \
1416                                 -w $SK_PATH/$FSNAME-s2s-server.key \
1417                                 -d /dev/urandom >/dev/null 2>&1
1418                 fi
1419                 # basic key create
1420                 $LGSS_SK -t server -f$FSNAME -w $SK_PATH/$FSNAME.key \
1421                         -d /dev/urandom >/dev/null 2>&1
1422                 # per-nodemap keys
1423                 for i in $(seq 0 $((numclients - 1))); do
1424                         $LGSS_SK -t server -f$FSNAME -n c$i \
1425                                 -w $SK_PATH/nodemap/c$i.key -d /dev/urandom \
1426                                 >/dev/null 2>&1
1427                 done
1428                 # Distribute keys
1429                 if ! local_mode; then
1430                         for lnode in $(all_nodes); do
1431                                 scp -r $SK_PATH ${lnode}:$(dirname $SK_PATH)/
1432                         done
1433                 fi
1434                 # Set client keys to client type to generate prime P
1435                 if local_mode; then
1436                         do_nodes $(all_nodes) "$LGSS_SK -t client,server -m \
1437                                 $SK_PATH/$FSNAME.key >/dev/null 2>&1"
1438                 else
1439                         do_nodes $clients "$LGSS_SK -t client -m \
1440                                 $SK_PATH/$FSNAME.key >/dev/null 2>&1"
1441                         do_nodes $clients "find $SK_PATH/nodemap \
1442                                 -name \*.key | xargs -IX $LGSS_SK -t client \
1443                                 -m X >/dev/null 2>&1"
1444                         # also have a client key available on server side,
1445                         # for local client mount
1446                         do_nodes $(comma_list $(all_server_nodes)) \
1447                         "cp $SK_PATH/$FSNAME.key $SK_PATH/${FSNAME}_cli.key && \
1448                          $LGSS_SK -t client -m \
1449                                 $SK_PATH/${FSNAME}_cli.key >/dev/null 2>&1"
1450                 fi
1451                 # This is required for servers as well, if S2S in use
1452                 if $SK_S2S; then
1453                         do_nodes $(comma_list $(mdts_nodes)) \
1454                                 "cp $SK_PATH/$FSNAME-s2s-server.key \
1455                                 $SK_PATH/$FSNAME-s2s-client.key; $LGSS_SK \
1456                                 -t client -m $SK_PATH/$FSNAME-s2s-client.key \
1457                                 >/dev/null 2>&1"
1458                         do_nodes $(comma_list $(osts_nodes)) \
1459                                 "cp $SK_PATH/$FSNAME-s2s-server.key \
1460                                 $SK_PATH/$FSNAME-s2s-client.key; $LGSS_SK \
1461                                 -t client -m $SK_PATH/$FSNAME-s2s-client.key \
1462                                 >/dev/null 2>&1"
1463                         do_nodes $clients "$LGSS_SK -t client \
1464                                 -m $SK_PATH/$FSNAME-nmclient.key \
1465                                  >/dev/null 2>&1"
1466                 fi
1467         fi
1468         if $GSS_SK; then
1469                 # mount options for servers and clients
1470                 MGS_MOUNT_OPTS=$(add_sk_mntflag $MGS_MOUNT_OPTS)
1471                 MDS_MOUNT_OPTS=$(add_sk_mntflag $MDS_MOUNT_OPTS)
1472                 OST_MOUNT_OPTS=$(add_sk_mntflag $OST_MOUNT_OPTS)
1473                 MOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)
1474                 SEC=$SK_FLAVOR
1475                 if [ -z "$LGSS_KEYRING_DEBUG" ]; then
1476                         LGSS_KEYRING_DEBUG=4
1477                 fi
1478         fi
1479
1480         if [ -n "$LGSS_KEYRING_DEBUG" ] && \
1481                ( local_mode || from_build_tree ); then
1482                 lctl set_param -n \
1483                      sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG
1484         elif [ -n "$LGSS_KEYRING_DEBUG" ]; then
1485                 do_nodes $(comma_list $(all_nodes)) "modprobe ptlrpc_gss && \
1486                 lctl set_param -n \
1487                    sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG"
1488         fi
1489
1490         do_nodesv $(comma_list $(all_server_nodes)) \
1491                 "$LCTL set_param sptlrpc.gss.rsi_upcall=$L_GETAUTH"
1492 }
1493
1494 cleanup_gss() {
1495         if $GSS; then
1496                 stop_gss_daemons
1497                 # maybe cleanup credential cache?
1498         fi
1499 }
1500
1501 cleanup_sk() {
1502         if $GSS_SK; then
1503                 if $SK_S2S; then
1504                         do_node $(mgs_node) "$LCTL nodemap_del $SK_S2SNM"
1505                         do_node $(mgs_node) "$LCTL nodemap_del $SK_S2SNMCLI"
1506                         $RPC_MODE || echo "Sleeping for 10 sec for Nodemap.."
1507                         sleep 10
1508                 fi
1509                 stop_gss_daemons
1510                 $RPC_MODE || echo "Cleaning up Shared Key.."
1511                 do_nodes $(comma_list $(all_nodes)) "rm -f \
1512                         $SK_PATH/$FSNAME*.key $SK_PATH/nodemap/$FSNAME*.key"
1513                 do_nodes $(comma_list $(all_nodes)) "keyctl show | \
1514                   awk '/lustre/ { print \\\$1 }' | xargs -IX keyctl unlink X"
1515                 if from_build_tree; then
1516                         # Remove the mount and clean up the files we added to
1517                         # SK_PATH
1518                         do_nodes $(comma_list $(all_nodes)) "while grep -q \
1519                                 request-key.d /proc/mounts; do umount \
1520                                 /etc/request-key.d/; done"
1521                         do_nodes $(comma_list $(all_nodes)) "rm -f \
1522                                 $SK_OM_PATH/lgssc.conf"
1523                         do_nodes $(comma_list $(all_nodes)) "rmdir $SK_OM_PATH"
1524                 fi
1525                 SK_NO_KEY=true
1526         fi
1527 }
1528
1529 facet_svc() {
1530         local facet=$1
1531         local var=${facet}_svc
1532
1533         echo -n ${!var}
1534 }
1535
1536 facet_type() {
1537         local facet=$1
1538
1539         echo -n $facet | sed -e 's/^fs[0-9]\+//' -e 's/[0-9_]\+//' |
1540                 tr '[:lower:]' '[:upper:]'
1541 }
1542
1543 facet_number() {
1544         local facet=$1
1545
1546         if [ $facet == mgs ] || [ $facet == client ]; then
1547                 return 1
1548         fi
1549
1550         echo -n $facet | sed -e 's/^fs[0-9]\+//' | sed -e 's/^[a-z]\+//'
1551 }
1552
1553 facet_fstype() {
1554         local facet=$1
1555         local var
1556
1557         var=${facet}_FSTYPE
1558         if [ -n "${!var}" ]; then
1559                 echo -n ${!var}
1560                 return
1561         fi
1562
1563         var=$(facet_type $facet)FSTYPE
1564         if [ -n "${!var}" ]; then
1565                 echo -n ${!var}
1566                 return
1567         fi
1568
1569         if [ -n "$FSTYPE" ]; then
1570                 echo -n $FSTYPE
1571                 return
1572         fi
1573
1574         if [[ $facet == mgs ]] && combined_mgs_mds; then
1575                 facet_fstype mds1
1576                 return
1577         fi
1578
1579         return 1
1580 }
1581
1582 node_fstypes() {
1583         local node=$1
1584         local fstypes
1585         local fstype
1586         local facets=$(get_facets)
1587         local facet
1588
1589         for facet in ${facets//,/ }; do
1590                 if [[ $node == $(facet_host $facet) ]] ||
1591                    [[ $node == "$(facet_failover_host $facet)" ]]; then
1592                         fstype=$(facet_fstype $facet)
1593                         if [[ $fstypes != *$fstype* ]]; then
1594                                 fstypes+="${fstypes:+,}$fstype"
1595                         fi
1596                 fi
1597         done
1598         echo -n $fstypes
1599 }
1600
1601 facet_index() {
1602         local facet=$1
1603         local num=$(facet_number $facet)
1604         local index
1605
1606         if [[ $(facet_type $facet) = OST ]]; then
1607                 index=OSTINDEX${num}
1608                 if [[ -n "${!index}" ]]; then
1609                         echo -n ${!index}
1610                         return
1611                 fi
1612
1613                 index=${OST_INDICES[num - 1]}
1614         fi
1615
1616         [[ -n "$index" ]] || index=$((num - 1))
1617         echo -n $index
1618 }
1619
1620 devicelabel() {
1621         local facet=$1
1622         local dev=$2
1623         local label
1624         local fstype=$(facet_fstype $facet)
1625
1626         case $fstype in
1627         ldiskfs)
1628                 label=$(do_facet ${facet} "$E2LABEL ${dev} 2>/dev/null");;
1629         zfs)
1630                 label=$(do_facet ${facet} "$ZFS get -H -o value lustre:svname \
1631                                            ${dev} 2>/dev/null");;
1632         *)
1633                 error "unknown fstype!";;
1634         esac
1635
1636         echo -n $label
1637 }
1638
1639 #
1640 # Get the device of a facet.
1641 #
1642 facet_device() {
1643         local facet=$1
1644         local device
1645
1646         case $facet in
1647                 mgs) device=$(mgsdevname) ;;
1648                 mds*) device=$(mdsdevname $(facet_number $facet)) ;;
1649                 ost*) device=$(ostdevname $(facet_number $facet)) ;;
1650                 fs2mds) device=$(mdsdevname 1_2) ;;
1651                 fs2ost) device=$(ostdevname 1_2) ;;
1652                 fs3ost) device=$(ostdevname 2_2) ;;
1653                 *) ;;
1654         esac
1655
1656         echo -n $device
1657 }
1658
1659 #
1660 # Get the virtual device of a facet.
1661 #
1662 facet_vdevice() {
1663         local facet=$1
1664         local device
1665
1666         case $facet in
1667                 mgs) device=$(mgsvdevname) ;;
1668                 mds*) device=$(mdsvdevname $(facet_number $facet)) ;;
1669                 ost*) device=$(ostvdevname $(facet_number $facet)) ;;
1670                 fs2mds) device=$(mdsvdevname 1_2) ;;
1671                 fs2ost) device=$(ostvdevname 1_2) ;;
1672                 fs3ost) device=$(ostvdevname 2_2) ;;
1673                 *) ;;
1674         esac
1675
1676         echo -n $device
1677 }
1678
1679 running_in_vm() {
1680         local virt=$(virt-what 2> /dev/null)
1681
1682         [ $? -eq 0 ] && [ -n "$virt" ] && { echo $virt; return; }
1683
1684         virt=$(dmidecode -s system-product-name | awk '{print $1}')
1685
1686         case $virt in
1687                 VMware|KVM|VirtualBox|Parallels|Bochs)
1688                         echo $virt | tr '[A-Z]' '[a-z]' && return;;
1689
1690                 *) ;;
1691         esac
1692
1693         virt=$(dmidecode -s system-manufacturer | awk '{print $1}')
1694         case $virt in
1695                 QEMU)
1696                         echo $virt | tr '[A-Z]' '[a-z]' && return;;
1697                 *) ;;
1698         esac
1699 }
1700
1701 #
1702 # Re-read the partition table on failover partner host.
1703 # After a ZFS storage pool is created on a shared device, the partition table
1704 # on the device may change. However, the operating system on the failover
1705 # host may not notice the change automatically. Without the up-to-date partition
1706 # block devices, 'zpool import ..' cannot find the labels, whose positions are
1707 # relative to partition rather than disk beginnings.
1708 #
1709 # This function performs partprobe on the failover host to make it re-read the
1710 # partition table.
1711 #
1712 refresh_partition_table() {
1713         local facet=$1
1714         local device=$2
1715         local host
1716
1717         host=$(facet_passive_host $facet)
1718         if [[ -n "$host" ]]; then
1719                 do_node $host "$PARTPROBE $device"
1720         fi
1721 }
1722
1723 #
1724 # Get ZFS storage pool name.
1725 #
1726 zpool_name() {
1727         local facet=$1
1728         local device
1729         local poolname
1730
1731         device=$(facet_device $facet)
1732         # poolname is string before "/"
1733         poolname="${device%%/*}"
1734
1735         echo -n $poolname
1736 }
1737
1738 #
1739 #
1740 # Get ZFS local fsname.
1741 #
1742 zfs_local_fsname() {
1743         local facet=$1
1744         local lfsname=$(basename $(facet_device $facet))
1745
1746         echo -n $lfsname
1747 }
1748
1749 #
1750 # Create ZFS storage pool.
1751 #
1752 create_zpool() {
1753         local facet=$1
1754         local poolname=$2
1755         local vdev=$3
1756         shift 3
1757         local opts=${@:-"-o cachefile=none"}
1758
1759         do_facet $facet "lsmod | grep zfs >&/dev/null || modprobe zfs;
1760                 $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1761                 $ZPOOL create -f $opts $poolname $vdev"
1762 }
1763
1764 #
1765 # Create ZFS file system.
1766 #
1767 create_zfs() {
1768         local facet=$1
1769         local dataset=$2
1770         shift 2
1771         local opts=${@:-"-o mountpoint=legacy"}
1772
1773         do_facet $facet "$ZFS list -H $dataset >/dev/null 2>&1 ||
1774                 $ZFS create $opts $dataset"
1775 }
1776
1777 #
1778 # Export ZFS storage pool.
1779 # Before exporting the pool, all datasets within the pool should be unmounted.
1780 #
1781 export_zpool() {
1782         local facet=$1
1783         shift
1784         local opts="$@"
1785         local poolname
1786
1787         poolname=$(zpool_name $facet)
1788
1789         if [[ -n "$poolname" ]]; then
1790                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1791                         grep -q ^$poolname/ /proc/mounts ||
1792                         $ZPOOL export $opts $poolname"
1793         fi
1794 }
1795
1796 #
1797 # Destroy ZFS storage pool.
1798 # Destroy the given pool and free up any devices for other use. This command
1799 # tries to unmount any active datasets before destroying the pool.
1800 # -f    Force any active datasets contained within the pool to be unmounted.
1801 #
1802 destroy_zpool() {
1803         local facet=$1
1804         local poolname=${2:-$(zpool_name $facet)}
1805
1806         if [[ -n "$poolname" ]]; then
1807                 do_facet $facet "! $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1808                         $ZPOOL destroy -f $poolname"
1809         fi
1810 }
1811
1812 #
1813 # Import ZFS storage pool.
1814 # Force importing, even if the pool appears to be potentially active.
1815 #
1816 import_zpool() {
1817         local facet=$1
1818         shift
1819         local opts=${@:-"-o cachefile=none -o failmode=panic"}
1820         local poolname
1821
1822         poolname=$(zpool_name $facet)
1823
1824         if [[ -n "$poolname" ]]; then
1825                 opts+=" -d $(dirname $(facet_vdevice $facet))"
1826                 do_facet $facet "lsmod | grep zfs >&/dev/null || modprobe zfs;
1827                         $ZPOOL list -H $poolname >/dev/null 2>&1 ||
1828                         $ZPOOL import -f $opts $poolname"
1829         fi
1830 }
1831
1832 #
1833 # Reimport ZFS storage pool with new name
1834 #
1835 reimport_zpool() {
1836         local facet=$1
1837         local newpool=$2
1838         local opts="-o cachefile=none"
1839         local poolname=$(zpool_name $facet)
1840
1841         opts+=" -d $(dirname $(facet_vdevice $facet))"
1842         do_facet $facet "$ZPOOL export $poolname;
1843                          $ZPOOL import $opts $poolname $newpool"
1844 }
1845
1846 #
1847 # Set the "cachefile=none" property on ZFS storage pool so that the pool
1848 # is not automatically imported on system startup.
1849 #
1850 # In a failover environment, this will provide resource level fencing which
1851 # will ensure that the same ZFS storage pool will not be imported concurrently
1852 # on different nodes.
1853 #
1854 disable_zpool_cache() {
1855         local facet=$1
1856         local poolname
1857
1858         poolname=$(zpool_name $facet)
1859
1860         if [[ -n "$poolname" ]]; then
1861                 do_facet $facet "$ZPOOL set cachefile=none $poolname"
1862         fi
1863 }
1864
1865 #
1866 # This and set_osd_param() shall be used to access OSD parameters
1867 # once existed under "obdfilter":
1868 #
1869 #   mntdev
1870 #   stats
1871 #   read_cache_enable
1872 #   writethrough_cache_enable
1873 #
1874 get_osd_param() {
1875         local nodes=$1
1876         local device=${2:-$FSNAME-OST*}
1877         local name=$3
1878
1879         do_nodes $nodes "$LCTL get_param -n osd-*.$device.$name"
1880 }
1881
1882 set_osd_param() {
1883         local nodes=$1
1884         local device=${2:-$FSNAME-OST*}
1885         local name=$3
1886         local value=$4
1887
1888         do_nodes $nodes "$LCTL set_param -n osd-*.$device.$name=$value"
1889 }
1890
1891 set_default_debug () {
1892         local debug=${1:-"$PTLDEBUG"}
1893         local subsys=${2:-"$SUBSYSTEM"}
1894         local debug_size=${3:-$DEBUG_SIZE}
1895
1896         [ -n "$debug" ] && lctl set_param debug="$debug" >/dev/null
1897         [ -n "$subsys" ] &&
1898                 lctl set_param subsystem_debug="${subsys# }" >/dev/null
1899         [ -n "$debug_size" ] &&
1900                 lctl set_param debug_mb="$debug_size" >/dev/null
1901
1902         return 0
1903 }
1904
1905 set_default_debug_nodes () {
1906         local nodes="$1"
1907         local debug="${2:-"$PTLDEBUG"}"
1908         local subsys="${3:-"$SUBSYSTEM"}"
1909         local debug_size="${4:-$DEBUG_SIZE}"
1910
1911         if [[ ,$nodes, = *,$HOSTNAME,* ]]; then
1912                 nodes=$(exclude_items_from_list "$nodes" "$HOSTNAME")
1913                 set_default_debug
1914         fi
1915
1916         [[ -z "$nodes" ]] ||
1917                 do_rpc_nodes "$nodes" set_default_debug \
1918                         \\\"$debug\\\" \\\"$subsys\\\" $debug_size || true
1919 }
1920
1921 set_default_debug_facet () {
1922         local facet=$1
1923         local debug="${2:-"$PTLDEBUG"}"
1924         local subsys="${3:-"$SUBSYSTEM"}"
1925         local debug_size="${4:-$DEBUG_SIZE}"
1926         local node=$(facet_active_host $facet)
1927
1928         [ -n "$node" ] || error "No host defined for facet $facet"
1929
1930         set_default_debug_nodes $node "$debug" "$subsys" $debug_size
1931 }
1932
1933 set_params_nodes() {
1934         local nodes=$1
1935         shift
1936         local params="$@"
1937
1938         [[ -n "$params" ]] || return 0
1939
1940         do_nodes $nodes "$LCTL set_param $params"
1941 }
1942
1943 set_params_clients() {
1944         (( $# >= 2 )) || return 0
1945         local clients=${1:-$CLIENTS}
1946         shift
1947         local params="${@:-$CLIENT_LCTL_SETPARAM_PARAM}"
1948
1949         set_params_nodes $clients $params
1950 }
1951
1952 set_params_mdts() {
1953         (( $# >= 2 )) || return 0
1954         local mdts=${1:-$(comma_list $(mdts_nodes))}
1955         shift
1956         local params="${@:-$MDS_LCTL_SETPARAM_PARAM}"
1957
1958         set_params_nodes $mdts $params
1959 }
1960
1961 set_params_osts() {
1962         (( $# >= 2 )) || return 0
1963         local osts=${1:-$(comma_list $(osts_nodes))}
1964         shift
1965         local params="${@:-$OSS_LCTL_SETPARAM_PARAM}"
1966
1967         set_params_nodes $osts $params
1968 }
1969
1970 set_hostid () {
1971         local hostid=${1:-$(hostid)}
1972
1973         if [ ! -s /etc/hostid ]; then
1974                 printf $(echo -n $hostid |
1975             sed 's/\(..\)\(..\)\(..\)\(..\)/\\x\4\\x\3\\x\2\\x\1/') >/etc/hostid
1976         fi
1977 }
1978
1979 # Facet functions
1980 mount_facets () {
1981         local facets=${1:-$(get_facets)}
1982         local facet
1983         local -a mountpids
1984         local total=0
1985         local ret=0
1986
1987         for facet in ${facets//,/ }; do
1988                 mount_facet $facet &
1989                 mountpids[total]=$!
1990                 total=$((total+1))
1991         done
1992         for ((index=0; index<$total; index++)); do
1993                 wait ${mountpids[index]}
1994                 local RC=$?
1995                 [ $RC -eq 0 ] && continue
1996
1997                 if [ "$TESTSUITE.$TESTNAME" = "replay-dual.test_0a" ]; then
1998                         skip_noexit "Restart of $facet failed!." &&
1999                                 touch $LU482_FAILED
2000                 else
2001                         error "Restart of $facet failed!"
2002                 fi
2003                 ret=$RC
2004         done
2005         return $ret
2006 }
2007
2008 #
2009 # Add argument "arg" (e.g., "loop") to the comma-separated list
2010 # of arguments for option "opt" (e.g., "-o") on command
2011 # line "opts" (e.g., "-o flock").
2012 #
2013 csa_add() {
2014         local opts=$1
2015         local opt=$2
2016         local arg=$3
2017         local opt_pattern="\([[:space:]]\+\|^\)$opt"
2018
2019         if echo "$opts" | grep -q $opt_pattern; then
2020                 opts=$(echo "$opts" | sed -e \
2021                         "s/$opt_pattern[[:space:]]*[^[:space:]]\+/&,$arg/")
2022         else
2023                 opts+="${opts:+ }$opt $arg"
2024         fi
2025         echo -n "$opts"
2026 }
2027
2028 #
2029 # Associate loop device with a given regular file.
2030 # Return the loop device.
2031 #
2032 setup_loop_device() {
2033         local facet=$1
2034         local file=$2
2035
2036         do_facet $facet "loop_dev=\\\$($LOSETUP -j $file | cut -d : -f 1);
2037                          if [[ -z \\\$loop_dev ]]; then
2038                                 loop_dev=\\\$($LOSETUP -f);
2039                                 $LOSETUP \\\$loop_dev $file || loop_dev=;
2040                          fi;
2041                          echo -n \\\$loop_dev"
2042 }
2043
2044 #
2045 # Detach a loop device.
2046 #
2047 cleanup_loop_device() {
2048         local facet=$1
2049         local loop_dev=$2
2050
2051         do_facet $facet "! $LOSETUP $loop_dev >/dev/null 2>&1 ||
2052                          $LOSETUP -d $loop_dev"
2053 }
2054
2055 #
2056 # Check if a given device is a block device.
2057 #
2058 is_blkdev() {
2059         local facet=$1
2060         local dev=$2
2061         local size=${3:-""}
2062
2063         [[ -n "$dev" ]] || return 1
2064         do_facet $facet "test -b $dev" || return 1
2065         if [[ -n "$size" ]]; then
2066                 local in=$(do_facet $facet "dd if=$dev of=/dev/null bs=1k \
2067                                             count=1 skip=$size 2>&1" |
2068                                             awk '($3 == "in") { print $1 }')
2069                 [[ "$in" = "1+0" ]] || return 1
2070         fi
2071 }
2072
2073 #
2074 # Check if a given device is a device-mapper device.
2075 #
2076 is_dm_dev() {
2077         local facet=$1
2078         local dev=$2
2079
2080         [[ -n "$dev" ]] || return 1
2081         do_facet $facet "$DMSETUP status $dev >/dev/null 2>&1"
2082 }
2083
2084 #
2085 # Check if a given device is a device-mapper flakey device.
2086 #
2087 is_dm_flakey_dev() {
2088         local facet=$1
2089         local dev=$2
2090         local type
2091
2092         [[ -n "$dev" ]] || return 1
2093
2094         type=$(do_facet $facet "$DMSETUP status $dev 2>&1" |
2095                awk '{print $3}')
2096         [[ $type = flakey ]] && return 0 || return 1
2097 }
2098
2099 #
2100 # Check if device-mapper flakey device is supported by the kernel
2101 # of $facet node or not.
2102 #
2103 dm_flakey_supported() {
2104         local facet=$1
2105
2106         $FLAKEY || return 1
2107         do_facet $facet "modprobe dm-flakey;
2108                          $DMSETUP targets | grep -q flakey" &> /dev/null
2109 }
2110
2111 #
2112 # Get the device-mapper flakey device name of a given facet.
2113 #
2114 dm_facet_devname() {
2115         local facet=$1
2116         [[ $facet = mgs ]] && combined_mgs_mds && facet=mds1
2117
2118         echo -n ${facet}_flakey
2119 }
2120
2121 #
2122 # Get the device-mapper flakey device of a given facet.
2123 # A device created by dmsetup will appear as /dev/mapper/<device-name>.
2124 #
2125 dm_facet_devpath() {
2126         local facet=$1
2127
2128         echo -n $DM_DEV_PATH/$(dm_facet_devname $facet)
2129 }
2130
2131 #
2132 # Set a device-mapper device with a new table.
2133 #
2134 # The table has the following format:
2135 # <logical_start_sector> <num_sectors> <target_type> <target_args>
2136 #
2137 # flakey <target_args> includes:
2138 # <destination_device> <offset> <up_interval> <down_interval> \
2139 # [<num_features> [<feature_arguments>]]
2140 #
2141 # linear <target_args> includes:
2142 # <destination_device> <start_sector>
2143 #
2144 dm_set_dev_table() {
2145         local facet=$1
2146         local dm_dev=$2
2147         local target_type=$3
2148         local num_sectors
2149         local real_dev
2150         local tmp
2151         local table
2152
2153         read tmp num_sectors tmp real_dev tmp \
2154                 <<< $(do_facet $facet "$DMSETUP table $dm_dev")
2155
2156         case $target_type in
2157         flakey)
2158                 table="0 $num_sectors flakey $real_dev 0 0 1800 1 drop_writes"
2159                 ;;
2160         linear)
2161                 table="0 $num_sectors linear $real_dev 0"
2162                 ;;
2163         *) error "invalid target type $target_type" ;;
2164         esac
2165
2166         do_facet $facet "$DMSETUP suspend --nolockfs --noflush $dm_dev" ||
2167                 error "failed to suspend $dm_dev"
2168         do_facet $facet "$DMSETUP load $dm_dev --table \\\"$table\\\"" ||
2169                 error "failed to load $target_type table into $dm_dev"
2170         do_facet $facet "$DMSETUP resume $dm_dev" ||
2171                 error "failed to resume $dm_dev"
2172 }
2173
2174 #
2175 # Set a device-mapper flakey device as "read-only" by using the "drop_writes"
2176 # feature parameter.
2177 #
2178 # drop_writes:
2179 #       All write I/O is silently ignored.
2180 #       Read I/O is handled correctly.
2181 #
2182 dm_set_dev_readonly() {
2183         local facet=$1
2184         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2185
2186         dm_set_dev_table $facet $dm_dev flakey
2187 }
2188
2189 #
2190 # Set a device-mapper device to traditional linear mapping mode.
2191 #
2192 dm_clear_dev_readonly() {
2193         local facet=$1
2194         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2195
2196         dm_set_dev_table $facet $dm_dev linear
2197 }
2198
2199 #
2200 # Set the device of a given facet as "read-only".
2201 #
2202 set_dev_readonly() {
2203         local facet=$1
2204         local svc=${facet}_svc
2205
2206         if [[ $(facet_fstype $facet) = zfs ]] ||
2207            ! dm_flakey_supported $facet; then
2208                 do_facet $facet $LCTL --device ${!svc} readonly
2209         else
2210                 dm_set_dev_readonly $facet
2211         fi
2212 }
2213
2214 #
2215 # Get size in 512-byte sectors (BLKGETSIZE64 / 512) of a given device.
2216 #
2217 get_num_sectors() {
2218         local facet=$1
2219         local dev=$2
2220         local num_sectors
2221
2222         num_sectors=$(do_facet $facet "blockdev --getsz $dev 2>/dev/null")
2223         [[ ${PIPESTATUS[0]} = 0 && -n "$num_sectors" ]] || num_sectors=0
2224         echo -n $num_sectors
2225 }
2226
2227 #
2228 # Create a device-mapper device with a given block device or regular file (will
2229 # be associated with loop device).
2230 # Return the full path of the device-mapper device.
2231 #
2232 dm_create_dev() {
2233         local facet=$1
2234         local real_dev=$2                                  # destination device
2235         local dm_dev_name=${3:-$(dm_facet_devname $facet)} # device name
2236         local dm_dev=$DM_DEV_PATH/$dm_dev_name            # device-mapper device
2237
2238         # check if the device-mapper device to be created already exists
2239         if is_dm_dev $facet $dm_dev; then
2240                 # if the existing device was set to "read-only", then clear it
2241                 ! is_dm_flakey_dev $facet $dm_dev ||
2242                         dm_clear_dev_readonly $facet $dm_dev
2243
2244                 echo -n $dm_dev
2245                 return 0
2246         fi
2247
2248         # check if the destination device is a block device, and if not,
2249         # associate it with a loop device
2250         is_blkdev $facet $real_dev ||
2251                 real_dev=$(setup_loop_device $facet $real_dev)
2252         [[ -n "$real_dev" ]] || { echo -n $real_dev; return 2; }
2253
2254         # now create the device-mapper device
2255         local num_sectors=$(get_num_sectors $facet $real_dev)
2256         local table="0 $num_sectors linear $real_dev 0"
2257         local rc=0
2258
2259         do_facet $facet "$DMSETUP create $dm_dev_name --table \\\"$table\\\"" ||
2260                 { rc=${PIPESTATUS[0]}; dm_dev=; }
2261         do_facet $facet "$DMSETUP mknodes >/dev/null 2>&1"
2262
2263         echo -n $dm_dev
2264         return $rc
2265 }
2266
2267 #
2268 # Map the facet name to its device variable name.
2269 #
2270 facet_device_alias() {
2271         local facet=$1
2272         local dev_alias=$facet
2273
2274         case $facet in
2275                 fs2mds) dev_alias=mds1_2 ;;
2276                 fs2ost) dev_alias=ost1_2 ;;
2277                 fs3ost) dev_alias=ost2_2 ;;
2278                 *) ;;
2279         esac
2280
2281         echo -n $dev_alias
2282 }
2283
2284 #
2285 # Save the original value of the facet device and export the new value.
2286 #
2287 export_dm_dev() {
2288         local facet=$1
2289         local dm_dev=$2
2290
2291         local active_facet=$(facet_active $facet)
2292         local dev_alias=$(facet_device_alias $active_facet)
2293         local dev_name=${dev_alias}_dev
2294         local dev=${!dev_name}
2295
2296         if [[ $active_facet = $facet ]]; then
2297                 local failover_dev=${dev_alias}failover_dev
2298                 if [[ ${!failover_dev} = $dev ]]; then
2299                         eval export ${failover_dev}_saved=$dev
2300                         eval export ${failover_dev}=$dm_dev
2301                 fi
2302         else
2303                 dev_alias=$(facet_device_alias $facet)
2304                 local facet_dev=${dev_alias}_dev
2305                 if [[ ${!facet_dev} = $dev ]]; then
2306                         eval export ${facet_dev}_saved=$dev
2307                         eval export ${facet_dev}=$dm_dev
2308                 fi
2309         fi
2310
2311         eval export ${dev_name}_saved=$dev
2312         eval export ${dev_name}=$dm_dev
2313 }
2314
2315 #
2316 # Restore the saved value of the facet device.
2317 #
2318 unexport_dm_dev() {
2319         local facet=$1
2320
2321         [[ $facet = mgs ]] && combined_mgs_mds && facet=mds1
2322         local dev_alias=$(facet_device_alias $facet)
2323
2324         local saved_dev=${dev_alias}_dev_saved
2325         [[ -z ${!saved_dev} ]] ||
2326                 eval export ${dev_alias}_dev=${!saved_dev}
2327
2328         saved_dev=${dev_alias}failover_dev_saved
2329         [[ -z ${!saved_dev} ]] ||
2330                 eval export ${dev_alias}failover_dev=${!saved_dev}
2331 }
2332
2333 #
2334 # Remove a device-mapper device.
2335 # If the destination device is a loop device, then also detach it.
2336 #
2337 dm_cleanup_dev() {
2338         local facet=$1
2339         local dm_dev=${2:-$(dm_facet_devpath $facet)}
2340         local major
2341         local minor
2342
2343         is_dm_dev $facet $dm_dev || return 0
2344
2345         read major minor <<< $(do_facet $facet "$DMSETUP table $dm_dev" |
2346                 awk '{ print $4 }' | awk -F: '{ print $1" "$2 }')
2347
2348         do_facet $facet "$DMSETUP remove $dm_dev"
2349         do_facet $facet "$DMSETUP mknodes >/dev/null 2>&1"
2350
2351         unexport_dm_dev $facet
2352
2353         # detach a loop device
2354         [[ $major -ne 7 ]] || cleanup_loop_device $facet /dev/loop$minor
2355
2356         # unload dm-flakey module
2357         do_facet $facet "modprobe -r dm-flakey" || true
2358 }
2359
2360 mount_facet() {
2361         local facet=$1
2362         shift
2363         local active_facet=$(facet_active $facet)
2364         local dev_alias=$(facet_device_alias $active_facet)
2365         local dev=${dev_alias}_dev
2366         local opt=${facet}_opt
2367         local mntpt=$(facet_mntpt $facet)
2368         local opts="${!opt} $@"
2369         local fstype=$(facet_fstype $facet)
2370         local devicelabel
2371         local dm_dev=${!dev}
2372
2373         [[ $dev == "mgsfailover_dev" ]] && combined_mgs_mds &&
2374                 dev=mds1failover_dev
2375
2376         module_loaded lustre || load_modules
2377
2378         case $fstype in
2379         ldiskfs)
2380                 if dm_flakey_supported $facet; then
2381                         dm_dev=$(dm_create_dev $facet ${!dev})
2382                         [[ -n "$dm_dev" ]] || dm_dev=${!dev}
2383                 fi
2384
2385                 is_blkdev $facet $dm_dev || opts=$(csa_add "$opts" -o loop)
2386
2387                 devicelabel=$(do_facet ${facet} "$E2LABEL $dm_dev");;
2388         zfs)
2389                 # import ZFS storage pool
2390                 import_zpool $facet || return ${PIPESTATUS[0]}
2391
2392                 devicelabel=$(do_facet ${facet} "$ZFS get -H -o value \
2393                                                 lustre:svname $dm_dev");;
2394         *)
2395                 error "unknown fstype!";;
2396         esac
2397
2398         echo "Starting ${facet}: $opts $dm_dev $mntpt"
2399         # for testing LU-482 error handling in mount_facets() and test_0a()
2400         if [ -f $TMP/test-lu482-trigger ]; then
2401                 RC=2
2402         else
2403                 local seq_width=$(($OSTSEQWIDTH / $OSTCOUNT))
2404                 (( $seq_width >= 16384 )) || seq_width=16384
2405                 do_facet ${facet} \
2406                         "mkdir -p $mntpt; $MOUNT_CMD $opts $dm_dev $mntpt"
2407                 RC=${PIPESTATUS[0]}
2408                 if [[ ${facet} =~ ost ]]; then
2409                         do_facet ${facet} "$LCTL set_param \
2410                                 seq.cli-$(devicelabel $facet $dm_dev)-super.width=$seq_width"
2411                 fi
2412         fi
2413
2414         if [ $RC -ne 0 ]; then
2415                 echo "Start of $dm_dev on ${facet} failed ${RC}"
2416                 return $RC
2417         fi
2418
2419         health=$(do_facet ${facet} "$LCTL get_param -n health_check")
2420         if [[ "$health" != "healthy" ]]; then
2421                 error "$facet is in a unhealthy state"
2422         fi
2423
2424         set_default_debug_facet $facet
2425
2426         if [[ $opts =~ .*nosvc.* ]]; then
2427                 echo "Start $dm_dev without service"
2428         else
2429
2430                 case $fstype in
2431                 ldiskfs)
2432                         wait_update_facet ${facet} "$E2LABEL $dm_dev \
2433                                 2>/dev/null | grep -E ':[a-zA-Z]{3}[0-9]{4}'" \
2434                                 "" || error "$dm_dev failed to initialize!";;
2435                 zfs)
2436                         wait_update_facet ${facet} "$ZFS get -H -o value \
2437                                 lustre:svname $dm_dev 2>/dev/null | \
2438                                 grep -E ':[a-zA-Z]{3}[0-9]{4}'" "" ||
2439                                 error "$dm_dev failed to initialize!";;
2440
2441                 *)
2442                         error "unknown fstype!";;
2443                 esac
2444         fi
2445
2446         # commit the device label change to disk
2447         if [[ $devicelabel =~ (:[a-zA-Z]{3}[0-9]{4}) ]]; then
2448                 echo "Commit the device label on ${!dev}"
2449                 do_facet $facet "sync; sleep 1; sync"
2450         fi
2451
2452
2453         label=$(devicelabel ${facet} $dm_dev)
2454         [ -z "$label" ] && echo no label for $dm_dev && exit 1
2455         eval export ${facet}_svc=${label}
2456         echo Started ${label}
2457
2458         export_dm_dev $facet $dm_dev
2459
2460         return $RC
2461 }
2462
2463 # start facet device options
2464 start() {
2465         local facet=$1
2466         shift
2467         local device=$1
2468         shift
2469         local dev_alias=$(facet_device_alias $facet)
2470
2471         eval export ${dev_alias}_dev=${device}
2472         eval export ${facet}_opt=\"$*\"
2473
2474         combined_mgs_mds && [[ ${dev_alias} == mds1 ]] &&
2475                 eval export mgs_dev=${device}
2476
2477         local varname=${dev_alias}failover_dev
2478         if [ -n "${!varname}" ] ; then
2479                 eval export ${dev_alias}failover_dev=${!varname}
2480         else
2481                 eval export ${dev_alias}failover_dev=$device
2482                 combined_mgs_mds && [[ ${dev_alias} == mds1 ]] &&
2483                         eval export mgsfailover_dev=${device}
2484
2485         fi
2486
2487         local mntpt=$(facet_mntpt $facet)
2488         do_facet ${facet} mkdir -p $mntpt
2489         eval export ${facet}_MOUNT=$mntpt
2490         mount_facet ${facet}
2491         RC=$?
2492
2493         return $RC
2494 }
2495
2496 stop() {
2497         local running
2498         local facet=$1
2499         shift
2500         local HOST=$(facet_active_host $facet)
2501         [[ -z $HOST ]] && echo stop: no host for $facet && return 0
2502
2503         local mntpt=$(facet_mntpt $facet)
2504         running=$(do_facet ${facet} "grep -c $mntpt' ' /proc/mounts || true")
2505         if [ ${running} -ne 0 ]; then
2506                 echo "Stopping $mntpt (opts:$*) on $HOST"
2507                 do_facet ${facet} $UMOUNT "$@" $mntpt
2508         fi
2509
2510         # umount should block, but we should wait for unrelated obd's
2511         # like the MGS or MGC to also stop.
2512         wait_exit_ST ${facet} || return ${PIPESTATUS[0]}
2513
2514         if [[ $(facet_fstype $facet) == zfs ]]; then
2515                 # export ZFS storage pool
2516                 [ "$KEEP_ZPOOL" = "true" ] || export_zpool $facet
2517         elif dm_flakey_supported $facet; then
2518                 local host=${facet}_HOST
2519                 local failover_host=${facet}failover_HOST
2520                 if [[ -n ${!failover_host} && ${!failover_host} != ${!host} ]]||
2521                         $CLEANUP_DM_DEV || [[ $facet = fs* ]]; then
2522                         dm_cleanup_dev $facet
2523                 fi
2524         fi
2525 }
2526
2527 # get mdt quota type
2528 mdt_quota_type() {
2529         local varsvc=${SINGLEMDS}_svc
2530         do_facet $SINGLEMDS $LCTL get_param -n \
2531                 osd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled
2532 }
2533
2534 # get ost quota type
2535 ost_quota_type() {
2536         # All OSTs should have same quota type
2537         local varsvc=ost1_svc
2538         do_facet ost1 $LCTL get_param -n \
2539                 osd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled
2540 }
2541
2542 # restore old quota type settings
2543 restore_quota() {
2544         for usr in $QUOTA_USERS; do
2545                 echo "Setting up quota on $HOSTNAME:$MOUNT for $usr..."
2546                 for type in u g; do
2547                         cmd="$LFS setquota -$type $usr -b 0"
2548                         cmd="$cmd -B 0 -i 0 -I 0 $MOUNT"
2549                         echo "+ $cmd"
2550                         eval $cmd || error "$cmd FAILED!"
2551                 done
2552                 # display the quota status
2553                 echo "Quota settings for $usr : "
2554                 $LFS quota -v -u $usr $MOUNT || true
2555         done
2556         if [ "$old_MDT_QUOTA_TYPE" ]; then
2557                 if [[ $PERM_CMD == *"set_param -P"* ]]; then
2558                         do_facet mgs $PERM_CMD \
2559                                 osd-*.$FSNAME-MDT*.quota_slave.enabled = \
2560                                 $old_MDT_QUOTA_TYPE
2561                 else
2562                         do_facet mgs $PERM_CMD \
2563                                 $FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE
2564                 fi
2565         fi
2566         if [ "$old_OST_QUOTA_TYPE" ]; then
2567                 if [[ $PERM_CMD == *"set_param -P"* ]]; then
2568                         do_facet mgs $PERM_CMD \
2569                                 osd-*.$FSNAME-OST*.quota_slave.enabled = \
2570                                 $old_OST_QUOTA_TYPE
2571                 else
2572                         do_facet mgs $LCTL conf_param \
2573                                 $FSNAME.quota.ost=$old_OST_QUOTA_TYPE
2574                 fi
2575         fi
2576 }
2577
2578 # Handle the case when there is a space in the lfs df
2579 # "filesystem summary" line the same as when there is no space.
2580 # This will allow fixing the "lfs df" summary line in the future.
2581 lfs_df() {
2582         $LFS df $* | sed -e 's/filesystem /filesystem_/'
2583         check_lfs_df_ret_val ${PIPESTATUS[0]}
2584 }
2585
2586 # Get free inodes on the MDT specified by mdt index, free indoes on
2587 # the whole filesystem will be returned when index == -1.
2588 mdt_free_inodes() {
2589         local index=$1
2590         local free_inodes
2591         local mdt_uuid
2592
2593         if [ $index -eq -1 ]; then
2594                 mdt_uuid="summary"
2595         else
2596                 mdt_uuid=$(mdtuuid_from_index $index)
2597         fi
2598
2599         free_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')
2600         echo $free_inodes
2601 }
2602
2603 #
2604 # Get the OST device status from 'lfs df' with a given OST index.
2605 #
2606 ost_dev_status() {
2607         local ost_idx=$1
2608         local mnt_pnt=${2:-$MOUNT}
2609         local opts=$3
2610         local ost_uuid
2611
2612         ost_uuid=$(ostuuid_from_index $ost_idx $mnt_pnt)
2613         lfs_df $opts $mnt_pnt | awk '/'$ost_uuid'/ { print $7 }'
2614 }
2615
2616 setup_quota(){
2617         local mntpt=$1
2618
2619         # save old quota type & set new quota type
2620         local mdt_qtype=$(mdt_quota_type)
2621         local ost_qtype=$(ost_quota_type)
2622
2623         echo "[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]" \
2624                 "[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]"
2625
2626         export old_MDT_QUOTA_TYPE=$mdt_qtype
2627         export old_OST_QUOTA_TYPE=$ost_qtype
2628
2629         if [[ $PERM_CMD == *"set_param -P"* ]]; then
2630                 do_facet mgs $PERM_CMD \
2631                         osd-*.$FSNAME-MDT*.quota_slave.enabled=$QUOTA_TYPE
2632                 do_facet mgs $PERM_CMD \
2633                         osd-*.$FSNAME-OST*.quota_slave.enabled=$QUOTA_TYPE
2634         else
2635                 do_facet mgs $PERM_CMD $FSNAME.quota.mdt=$QUOTA_TYPE ||
2636                         error "set mdt quota type failed"
2637                 do_facet mgs $PERM_CMD $FSNAME.quota.ost=$QUOTA_TYPE ||
2638                         error "set ost quota type failed"
2639         fi
2640
2641         local quota_usrs=$QUOTA_USERS
2642
2643         # get_filesystem_size
2644         local disksz=$(lfs_df $mntpt | grep "summary" | awk '{print $2}')
2645         local blk_soft=$((disksz + 1024))
2646         local blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over
2647
2648         local inodes=$(lfs_df -i $mntpt | grep "summary" | awk '{print $2}')
2649         local i_soft=$inodes
2650         local i_hard=$((i_soft + i_soft / 20))
2651
2652         echo "Total disk size: $disksz  block-softlimit: $blk_soft" \
2653                 "block-hardlimit: $blk_hard inode-softlimit: $i_soft" \
2654                 "inode-hardlimit: $i_hard"
2655
2656         local cmd
2657         for usr in $quota_usrs; do
2658                 echo "Setting up quota on $HOSTNAME:$mntpt for $usr..."
2659                 for type in u g; do
2660                         cmd="$LFS setquota -$type $usr -b $blk_soft"
2661                         cmd="$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt"
2662                         echo "+ $cmd"
2663                         eval $cmd || error "$cmd FAILED!"
2664                 done
2665                 # display the quota status
2666                 echo "Quota settings for $usr : "
2667                 $LFS quota -v -u $usr $mntpt || true
2668         done
2669 }
2670
2671 zconf_mount() {
2672         local client=$1
2673         local mnt=$2
2674         local opts=${3:-$MOUNT_OPTS}
2675         opts=${opts:+-o $opts}
2676         local flags=${4:-$MOUNT_FLAGS}
2677
2678         local device=$MGSNID:/$FSNAME$FILESET
2679         if [ -z "$mnt" -o -z "$FSNAME" ]; then
2680                 echo "Bad mount command: opt=$flags $opts dev=$device " \
2681                      "mnt=$mnt"
2682                 exit 1
2683         fi
2684
2685         if $GSS_SK; then
2686                 # update mount option with skpath
2687                 opts=$(add_sk_mntflag $opts)
2688         fi
2689
2690         echo "Starting client: $client: $flags $opts $device $mnt"
2691         do_node $client mkdir -p $mnt
2692         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ];then
2693                 do_node $client $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \
2694                         $mnt || return 1
2695                 #disable FILESET if not supported
2696                 do_nodes $client lctl get_param -n \
2697                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
2698                                 device=$MGSNID:/$FSNAME
2699                 do_node $client mkdir -p $mnt/$FILESET
2700                 do_node $client "! grep -q $mnt' ' /proc/mounts ||
2701                         umount $mnt"
2702         fi
2703         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2704                 # Mount using nodemap key
2705                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
2706                 if $SK_UNIQUE_NM; then
2707                         mountkey=$SK_PATH/nodemap/c0.key
2708                 fi
2709                 local prunedopts=$(echo $opts |
2710                                 sed -e "s#skpath=[^,^ ]*#skpath=$mountkey#g")
2711                 do_node $client $MOUNT_CMD $flags $prunedopts $device $mnt ||
2712                                 return 1
2713         else
2714                 do_node $client $MOUNT_CMD $flags $opts $device $mnt ||
2715                                 return 1
2716         fi
2717
2718         set_default_debug_nodes $client
2719         set_params_clients $client
2720
2721         return 0
2722 }
2723
2724 zconf_umount() {
2725         local client=$1
2726         local mnt=$2
2727         local force
2728         local busy
2729         local need_kill
2730         local running=$(do_node $client "grep -c $mnt' ' /proc/mounts") || true
2731
2732         [ "$3" ] && force=-f
2733         [ $running -eq 0 ] && return 0
2734
2735         echo "Stopping client $client $mnt (opts:$force)"
2736         do_node $client lsof -t $mnt || need_kill=no
2737         if [ "x$force" != "x" ] && [ "x$need_kill" != "xno" ]; then
2738                 pids=$(do_node $client lsof -t $mnt | sort -u);
2739                 if [ -n "$pids" ]; then
2740                         do_node $client kill -9 $pids || true
2741                 fi
2742         fi
2743
2744         busy=$(do_node $client "umount $force $mnt 2>&1" | grep -c "busy") ||
2745                 true
2746         if [ $busy -ne 0 ] ; then
2747                 echo "$mnt is still busy, wait one second" && sleep 1
2748                 do_node $client umount $force $mnt
2749         fi
2750 }
2751
2752 # Mount the file system on the MDS
2753 mount_mds_client() {
2754         local host=$(facet_active_host $SINGLEMDS)
2755         echo $host
2756         zconf_mount $host $MOUNT2 $MOUNT_OPTS ||
2757                 error "unable to mount $MOUNT2 on $host"
2758 }
2759
2760 # Unmount the file system on the MDS
2761 umount_mds_client() {
2762         local host=$(facet_active_host $SINGLEMDS)
2763         zconf_umount $host $MOUNT2
2764         do_facet $SINGLEMDS "rmdir $MOUNT2"
2765 }
2766
2767 # nodes is comma list
2768 sanity_mount_check_nodes () {
2769         local nodes=$1
2770         shift
2771         local mnts="$@"
2772         local mnt
2773
2774         # FIXME: assume that all cluster nodes run the same os
2775         [ "$(uname)" = Linux ] || return 0
2776
2777         local rc=0
2778         for mnt in $mnts ; do
2779                 do_nodes $nodes "running=\\\$(grep -c $mnt' ' /proc/mounts);
2780 mpts=\\\$(mount | grep -c $mnt' ');
2781 if [ \\\$running -ne \\\$mpts ]; then
2782     echo \\\$(hostname) env are INSANE!;
2783     exit 1;
2784 fi"
2785                 [ $? -eq 0 ] || rc=1
2786         done
2787         return $rc
2788 }
2789
2790 sanity_mount_check_servers () {
2791         [ -n "$CLIENTONLY" ] &&
2792                 { echo "CLIENTONLY mode, skip mount_check_servers"; return 0; } || true
2793         echo Checking servers environments
2794
2795         # FIXME: modify get_facets to display all facets wo params
2796         local facets="$(get_facets OST),$(get_facets MDS),mgs"
2797         local node
2798         local mntpt
2799         local facet
2800         for facet in ${facets//,/ }; do
2801         node=$(facet_host ${facet})
2802         mntpt=$(facet_mntpt $facet)
2803         sanity_mount_check_nodes $node $mntpt ||
2804                 { error "server $node environments are insane!"; return 1; }
2805         done
2806 }
2807
2808 sanity_mount_check_clients () {
2809         local clients=${1:-$CLIENTS}
2810         local mntpt=${2:-$MOUNT}
2811         local mntpt2=${3:-$MOUNT2}
2812
2813         [ -z $clients ] && clients=$(hostname)
2814         echo Checking clients $clients environments
2815
2816         sanity_mount_check_nodes $clients $mntpt $mntpt2 ||
2817                 error "clients environments are insane!"
2818 }
2819
2820 sanity_mount_check () {
2821         sanity_mount_check_servers || return 1
2822         sanity_mount_check_clients || return 2
2823 }
2824
2825 # mount clients if not mouted
2826 zconf_mount_clients() {
2827         local clients=$1
2828         local mnt=$2
2829         local opts=${3:-$MOUNT_OPTS}
2830         opts=${opts:+-o $opts}
2831         local flags=${4:-$MOUNT_FLAGS}
2832         local device=$MGSNID:/$FSNAME$FILESET
2833         if [ -z "$mnt" -o -z "$FSNAME" ]; then
2834                 echo "Bad conf mount command: opt=$flags $opts dev=$device " \
2835                      "mnt=$mnt"
2836                 exit 1
2837         fi
2838
2839         echo "Starting client $clients: $flags $opts $device $mnt"
2840         do_nodes $clients mkdir -p $mnt
2841         if [ -n "$FILESET" -a -z "$SKIP_FILESET" ]; then
2842                 if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2843                         # Mount with own nodemap key
2844                         local i=0
2845                         # Mount all server nodes first with per-NM keys
2846                         for nmclient in ${clients//,/ }; do
2847                                 do_nodes $(comma_list $(all_server_nodes)) \
2848                                 "$LGSS_SK -t server -l $SK_PATH/nodemap/c$i.key"
2849                                 i=$((i + 1))
2850                         done
2851                         # set perms for per-nodemap keys else permission denied
2852                         do_nodes $(comma_list $(all_nodes)) \
2853                                 "keyctl show | grep lustre | cut -c1-11 |
2854                                 sed -e 's/ //g;' |
2855                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
2856                         local mountkey=$SK_PATH/$FSNAME-nmclient.key
2857                         i=0
2858                         for nmclient in ${clients//,/ }; do
2859                                 if $SK_UNIQUE_NM; then
2860                                         mountkey=$SK_PATH/nodemap/c$i.key
2861                                 fi
2862                                 do_node $nmclient "! grep -q $mnt' ' \
2863                                         /proc/mounts || umount $mnt"
2864                                 local prunedopts=$(add_sk_mntflag $opts);
2865                                 prunedopts=$(echo $prunedopts | sed -e \
2866                                         "s#skpath=[^ ^,]*#skpath=$mountkey#g")
2867                                 set -x
2868                                 do_nodes $(comma_list $(all_server_nodes)) \
2869                                         "keyctl show"
2870                                 set +x
2871                                 do_node $nmclient $MOUNT_CMD $flags \
2872                                         $prunedopts $MGSNID:/$FSNAME $mnt ||
2873                                         return 1
2874                                 i=$((i + 1))
2875                         done
2876                 else
2877                         do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
2878                                         umount $mnt"
2879                         do_nodes $clients $MOUNT_CMD $flags $opts \
2880                                         $MGSNID:/$FSNAME $mnt || return 1
2881                 fi
2882                 #disable FILESET if not supported
2883                 do_nodes $clients lctl get_param -n \
2884                         mdc.$FSNAME-MDT0000*.import | grep -q subtree ||
2885                                 device=$MGSNID:/$FSNAME
2886                 do_nodes $clients mkdir -p $mnt/$FILESET
2887                 do_nodes $clients "! grep -q $mnt' ' /proc/mounts ||
2888                         umount $mnt"
2889         fi
2890
2891         if $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then
2892                 # Mount with nodemap key
2893                 local i=0
2894                 local mountkey=$SK_PATH/$FSNAME-nmclient.key
2895                 for nmclient in ${clients//,/ }; do
2896                         if $SK_UNIQUE_NM; then
2897                                 mountkey=$SK_PATH/nodemap/c$i.key
2898                         fi
2899                         local prunedopts=$(echo $opts | sed -e \
2900                                 "s#skpath=[^ ^,]*#skpath=$mountkey#g");
2901                         do_node $nmclient "! grep -q $mnt' ' /proc/mounts ||
2902                                 umount $mnt"
2903                         do_node $nmclient "
2904                 running=\\\$(mount | grep -c $mnt' ');
2905                 rc=0;
2906                 if [ \\\$running -eq 0 ] ; then
2907                         mkdir -p $mnt;
2908                         $MOUNT_CMD $flags $prunedopts $device $mnt;
2909                         rc=\\\$?;
2910                 else
2911                         lustre_mnt_count=\\\$(mount | grep $mnt' ' | \
2912                                 grep 'type lustre' | wc -l);
2913                         if [ \\\$running -ne \\\$lustre_mnt_count ] ; then
2914                                 echo zconf_mount_clients FAILED: \
2915                                         mount count \\\$running, not matching \
2916                                         with mount count of 'type lustre' \
2917                                         \\\$lustre_mnt_count;
2918                                 rc=1;
2919                         fi;
2920                 fi;
2921         exit \\\$rc" || return ${PIPESTATUS[0]}
2922
2923                         i=$((i + 1))
2924                 done
2925         else
2926
2927                 local tmpopts=$opts
2928                 if $SHARED_KEY; then
2929                         tmpopts=$(add_sk_mntflag $opts)
2930                 fi
2931                 do_nodes $clients "
2932 running=\\\$(mount | grep -c $mnt' ');
2933 rc=0;
2934 if [ \\\$running -eq 0 ] ; then
2935         mkdir -p $mnt;
2936         $MOUNT_CMD $flags $tmpopts $device $mnt;
2937         rc=\\\$?;
2938 fi;
2939 exit \\\$rc" || return ${PIPESTATUS[0]}
2940         fi
2941
2942         echo "Started clients $clients: "
2943         do_nodes $clients "mount | grep $mnt' '"
2944
2945         set_default_debug_nodes $clients
2946         set_params_clients $clients
2947
2948         return 0
2949 }
2950
2951 zconf_umount_clients() {
2952         local clients=$1
2953         local mnt=$2
2954         local force
2955
2956         [ "$3" ] && force=-f
2957
2958         echo "Stopping clients: $clients $mnt (opts:$force)"
2959         do_nodes $clients "running=\\\$(grep -c $mnt' ' /proc/mounts);
2960 if [ \\\$running -ne 0 ] ; then
2961 echo Stopping client \\\$(hostname) $mnt opts:$force;
2962 lsof $mnt || need_kill=no;
2963 if [ "x$force" != "x" -a "x\\\$need_kill" != "xno" ]; then
2964     pids=\\\$(lsof -t $mnt | sort -u);
2965     if [ -n \\\"\\\$pids\\\" ]; then
2966              kill -9 \\\$pids;
2967     fi
2968 fi;
2969 while umount $force $mnt 2>&1 | grep -q "busy"; do
2970     echo "$mnt is still busy, wait one second" && sleep 1;
2971 done;
2972 fi"
2973 }
2974
2975 shutdown_node () {
2976         local node=$1
2977
2978         echo + $POWER_DOWN $node
2979         $POWER_DOWN $node
2980 }
2981
2982 shutdown_node_hard () {
2983         local host=$1
2984         local attempts=$SHUTDOWN_ATTEMPTS
2985
2986         for i in $(seq $attempts) ; do
2987                 shutdown_node $host
2988                 sleep 1
2989                 wait_for_function --quiet "! ping -w 3 -c 1 $host" 5 1 &&
2990                         return 0
2991                 echo "waiting for $host to fail attempts=$attempts"
2992                 [ $i -lt $attempts ] ||
2993                         { echo "$host still pingable after power down! attempts=$attempts" && return 1; }
2994         done
2995 }
2996
2997 shutdown_client() {
2998         local client=$1
2999         local mnt=${2:-$MOUNT}
3000         local attempts=3
3001
3002         if [ "$FAILURE_MODE" = HARD ]; then
3003                 shutdown_node_hard $client
3004         else
3005                 zconf_umount_clients $client $mnt -f
3006         fi
3007 }
3008
3009 facets_on_host () {
3010         local affected
3011         local host=$1
3012         local facets="$(get_facets OST),$(get_facets MDS)"
3013
3014         combined_mgs_mds || facets="$facets,mgs"
3015
3016         for facet in ${facets//,/ }; do
3017                 if [ $(facet_active_host $facet) == $host ]; then
3018                         affected="$affected $facet"
3019                 fi
3020         done
3021
3022         echo $(comma_list $affected)
3023 }
3024
3025 facet_up() {
3026         local facet=$1
3027         local host=${2:-$(facet_host $facet)}
3028
3029         local label=$(convert_facet2label $facet)
3030         do_node $host $LCTL dl | awk '{ print $4 }' | grep -q "^$label\$"
3031 }
3032
3033 facets_up_on_host () {
3034         local affected_up
3035         local host=$1
3036         local facets=$(facets_on_host $host)
3037
3038         for facet in ${facets//,/ }; do
3039                 if $(facet_up $facet $host); then
3040                         affected_up="$affected_up $facet"
3041                 fi
3042         done
3043
3044         echo $(comma_list $affected_up)
3045 }
3046
3047 shutdown_facet() {
3048         local facet=$1
3049         local affected_facet
3050         local affected_facets
3051
3052         if [[ "$FAILURE_MODE" = HARD ]]; then
3053                 if [[ $(facet_fstype $facet) = ldiskfs ]] &&
3054                         dm_flakey_supported $facet; then
3055                         affected_facets=$(affected_facets $facet)
3056                         for affected_facet in ${affected_facets//,/ }; do
3057                                 unexport_dm_dev $affected_facet
3058                         done
3059                 fi
3060
3061                 shutdown_node_hard $(facet_active_host $facet)
3062         else
3063                 stop $facet
3064         fi
3065 }
3066
3067 reboot_node() {
3068         local node=$1
3069
3070         echo + $POWER_UP $node
3071         $POWER_UP $node
3072 }
3073
3074 remount_facet() {
3075         local facet=$1
3076
3077         stop $facet
3078         mount_facet $facet
3079 }
3080
3081 reboot_facet() {
3082         local facet=$1
3083         local node=$(facet_active_host $facet)
3084         local sleep_time=${2:-10}
3085
3086         if [ "$FAILURE_MODE" = HARD ]; then
3087                 boot_node $node
3088         else
3089                 sleep $sleep_time
3090         fi
3091 }
3092
3093 boot_node() {
3094         local node=$1
3095
3096         if [ "$FAILURE_MODE" = HARD ]; then
3097                 reboot_node $node
3098                 wait_for_host $node
3099                 if $LOAD_MODULES_REMOTE; then
3100                         echo "loading modules on $node: $facet"
3101                         do_rpc_nodes $node load_modules_local
3102                 fi
3103         fi
3104 }
3105
3106 facets_hosts () {
3107         local hosts
3108         local facets=$1
3109
3110         for facet in ${facets//,/ }; do
3111                 hosts=$(expand_list $hosts $(facet_host $facet) )
3112         done
3113
3114         echo $hosts
3115 }
3116
3117 _check_progs_installed () {
3118         local progs=$@
3119         local rc=0
3120
3121         for prog in $progs; do
3122                 if ! [ "$(which $prog)"  -o  "${!prog}" ]; then
3123                         echo $prog missing on $(hostname)
3124                         rc=1
3125                 fi
3126         done
3127         return $rc
3128 }
3129
3130 check_progs_installed () {
3131         local nodes=$1
3132         shift
3133
3134         do_rpc_nodes "$nodes" _check_progs_installed "$@"
3135 }
3136
3137 # recovery-scale functions
3138 node_var_name() {
3139     echo __$(echo $1 | tr '-' '_' | tr '.' '_')
3140 }
3141
3142 start_client_load() {
3143         local client=$1
3144         local load=$2
3145         local var=$(node_var_name $client)_load
3146         eval export ${var}=$load
3147
3148         do_node $client "PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \
3149                         BREAK_ON_ERROR=$BREAK_ON_ERROR \
3150                         END_RUN_FILE=$END_RUN_FILE \
3151                         LOAD_PID_FILE=$LOAD_PID_FILE \
3152                         TESTLOG_PREFIX=$TESTLOG_PREFIX \
3153                         TESTNAME=$TESTNAME \
3154                         DBENCH_LIB=$DBENCH_LIB \
3155                         DBENCH_SRC=$DBENCH_SRC \
3156                         CLIENT_COUNT=$((CLIENTCOUNT - 1)) \
3157                         LFS=$LFS \
3158                         LCTL=$LCTL \
3159                         FSNAME=$FSNAME \
3160                         MPIRUN=$MPIRUN \
3161                         MPIRUN_OPTIONS=\\\"$MPIRUN_OPTIONS\\\" \
3162                         MACHINEFILE_OPTION=\\\"$MACHINEFILE_OPTION\\\" \
3163                         num_clients=$(get_node_count ${CLIENTS//,/ }) \
3164                         ior_THREADS=$ior_THREADS ior_iteration=$ior_iteration \
3165                         ior_blockSize=$ior_blockSize \
3166                         ior_blockUnit=$ior_blockUnit \
3167                         ior_xferSize=$ior_xferSize ior_type=$ior_type \
3168                         ior_DURATION=$ior_DURATION \
3169                         ior_stripe_params=\\\"$ior_stripe_params\\\" \
3170                         ior_custom_params=\\\"$ior_custom_param\\\" \
3171                         mpi_ior_custom_threads=$mpi_ior_custom_threads \
3172                         run_${load}.sh" &
3173         local ppid=$!
3174         log "Started client load: ${load} on $client"
3175
3176         # get the children process IDs
3177         local pids=$(ps --ppid $ppid -o pid= | xargs)
3178         CLIENT_LOAD_PIDS="$CLIENT_LOAD_PIDS $ppid $pids"
3179         return 0
3180 }
3181
3182 start_client_loads () {
3183         local -a clients=(${1//,/ })
3184         local numloads=${#CLIENT_LOADS[@]}
3185
3186         for ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do
3187                 local load=$((nodenum % numloads))
3188                 start_client_load ${clients[nodenum]} ${CLIENT_LOADS[load]}
3189         done
3190         # bug 22169: wait the background threads to start
3191         sleep 2
3192 }
3193
3194 # only for remote client
3195 check_client_load () {
3196         local client=$1
3197         local var=$(node_var_name $client)_load
3198         local testload=run_${!var}.sh
3199
3200         ps auxww | grep -v grep | grep $client | grep -q $testload || return 1
3201
3202         # bug 18914: try to connect several times not only when
3203         # check ps, but  while check_node_health also
3204
3205         local tries=3
3206         local RC=254
3207         while [ $RC = 254 -a $tries -gt 0 ]; do
3208                 let tries=$tries-1
3209                 # assume success
3210                 RC=0
3211                 if ! check_node_health $client; then
3212                         RC=${PIPESTATUS[0]}
3213                         if [ $RC -eq 254 ]; then
3214                                 # FIXME: not sure how long we shuold sleep here
3215                                 sleep 10
3216                                 continue
3217                         fi
3218                         echo "check node health failed: RC=$RC "
3219                         return $RC
3220                 fi
3221         done
3222         # We can continue try to connect if RC=254
3223         # Just print the warning about this
3224         if [ $RC = 254 ]; then
3225                 echo "got a return status of $RC from do_node while checking " \
3226                 "node health on $client"
3227         fi
3228
3229         # see if the load is still on the client
3230         tries=3
3231         RC=254
3232         while [ $RC = 254 -a $tries -gt 0 ]; do
3233                 let tries=$tries-1
3234                 # assume success
3235                 RC=0
3236                 if ! do_node $client \
3237                         "ps auxwww | grep -v grep | grep -q $testload"; then
3238                         RC=${PIPESTATUS[0]}
3239                         sleep 30
3240                 fi
3241         done
3242         if [ $RC = 254 ]; then
3243                 echo "got a return status of $RC from do_node while checking " \
3244                 "(node health and 'ps') the client load on $client"
3245                 # see if we can diagnose a bit why this is
3246         fi
3247
3248         return $RC
3249 }
3250 check_client_loads () {
3251         local clients=${1//,/ }
3252         local client=
3253         local rc=0
3254
3255         for client in $clients; do
3256                 check_client_load $client
3257                 rc=${PIPESTATUS[0]}
3258                 if [ "$rc" != 0 ]; then
3259                         log "Client load failed on node $client, rc=$rc"
3260                         return $rc
3261                 fi
3262         done
3263 }
3264
3265 restart_client_loads () {
3266         local clients=${1//,/ }
3267         local expectedfail=${2:-""}
3268         local client=
3269         local rc=0
3270
3271         for client in $clients; do
3272                 check_client_load $client
3273                 rc=${PIPESTATUS[0]}
3274                 if [ "$rc" != 0 -a "$expectedfail" ]; then
3275                         local var=$(node_var_name $client)_load
3276
3277                         start_client_load $client ${!var}
3278                         echo "Restarted client load ${!var}: on $client. Checking ..."
3279                         check_client_load $client
3280                         rc=${PIPESTATUS[0]}
3281                         if [ "$rc" != 0 ]; then
3282                                 log "Client load failed to restart on node $client, rc=$rc"
3283                                 # failure one client load means test fail
3284                                 # we do not need to check other
3285                                 return $rc
3286                         fi
3287                 else
3288                         return $rc
3289                 fi
3290         done
3291 }
3292
3293 # Start vmstat and save its process ID in a file.
3294 start_vmstat() {
3295         local nodes=$1
3296         local pid_file=$2
3297
3298         [ -z "$nodes" -o -z "$pid_file" ] && return 0
3299
3300         do_nodes $nodes \
3301         "vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\$(hostname -s).log \
3302         2>/dev/null </dev/null & echo \\\$! > $pid_file"
3303 }
3304
3305 # Display the nodes on which client loads failed.
3306 print_end_run_file() {
3307         local file=$1
3308         local node
3309
3310         [ -s $file ] || return 0
3311
3312         echo "Found the END_RUN_FILE file: $file"
3313         cat $file
3314
3315         # A client load will stop if it finds the END_RUN_FILE file.
3316         # That does not mean the client load actually failed though.
3317         # The first node in END_RUN_FILE is the one we are interested in.
3318         read node < $file
3319
3320         if [ -n "$node" ]; then
3321                 local var=$(node_var_name $node)_load
3322
3323                 local prefix=$TESTLOG_PREFIX
3324                 [ -n "$TESTNAME" ] && prefix=$prefix.$TESTNAME
3325                 local stdout_log=$prefix.run_${!var}_stdout.$node.log
3326                 local debug_log=$(echo $stdout_log |
3327                         sed 's/\(.*\)stdout/\1debug/')
3328
3329                 echo "Client load ${!var} failed on node $node:"
3330                 echo "$stdout_log"
3331                 echo "$debug_log"
3332         fi
3333 }
3334
3335 # Stop the process which had its PID saved in a file.
3336 stop_process() {
3337         local nodes=$1
3338         local pid_file=$2
3339
3340         [ -z "$nodes" -o -z "$pid_file" ] && return 0
3341
3342         do_nodes $nodes "test -f $pid_file &&
3343                 { kill -s TERM \\\$(cat $pid_file); rm -f $pid_file; }" || true
3344 }
3345
3346 # Stop all client loads.
3347 stop_client_loads() {
3348         local nodes=${1:-$CLIENTS}
3349         local pid_file=$2
3350
3351         # stop the client loads
3352         stop_process $nodes $pid_file
3353
3354         # clean up the processes that started them
3355         [ -n "$CLIENT_LOAD_PIDS" ] &&
3356                 kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true
3357 }
3358 # End recovery-scale functions
3359
3360 ##
3361 # wait for a command to return the expected result
3362 #
3363 # This will run @check on @node repeatedly until the output matches @expect
3364 # based on the supplied condition, or until @max_wait seconds have elapsed,
3365 # whichever comes first.  @cond may be one of the normal bash operators,
3366 # "-gt", "-ge", "-eq", "-le", "-lt", "==", "!=", or "=~", and must be quoted
3367 # in the caller to avoid unintentional evaluation by the shell in the caller.
3368 #
3369 # If @max_wait is not specified, the condition will be checked for up to 90s.
3370 #
3371 # If --verbose is passed as the first argument, the result is printed on each
3372 # value change, otherwise it is only printed after every 10s interval.
3373 #
3374 # If --quiet is passed as the first/second argument, the do_node() command
3375 # will not print the remote command before executing it each time.
3376 #
3377 # Using wait_update_cond() or related helper function is preferable to adding
3378 # a "long enough" wait for some state to change in the background, since
3379 # "long enough" may be too short due to tunables, system config, or running in
3380 # a VM, and must by necessity wait too long for most cases or risk failure.
3381 #
3382 # usage: wait_update_cond [--verbose] [--quiet] node check cond expect [max_wait]
3383 wait_update_cond() {
3384         local verbose
3385         local quiet
3386
3387         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3388         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3389
3390         local node=$1
3391         local check="$2"
3392         local cond="$3"
3393         local expect="$4"
3394         local max_wait=${5:-90}
3395         local result
3396         local prev_result
3397         local waited=0
3398         local begin=$SECONDS
3399         local sleep=1
3400         local print=10
3401
3402         while (( $waited <= $max_wait )); do
3403                 result=$(do_node $quiet $node "$check")
3404
3405                 eval [[ "'$result'" $cond "'$expect'" ]]
3406                 if [[ $? == 0 ]]; then
3407                         [[ -n "$quiet" ]] && return 0
3408                         [[ -z "$result" || $waited -le $sleep ]] ||
3409                                 echo "Updated after ${waited}s: want '$expect' got '$result'"
3410                         return 0
3411                 fi
3412                 if [[ -n "$verbose" && "$result" != "$prev_result" ]]; then
3413                         [[ -z "$quiet" && -n "$prev_result" ]] &&
3414                                 echo "Changed after ${waited}s: from '$prev_result' to '$result'"
3415                         prev_result="$result"
3416                 fi
3417                 (( $waited % $print == 0 )) && {
3418                         [[ -z "$quiet" ]] &&
3419                         echo "Waiting $((max_wait - waited))s for '$expect'"
3420                 }
3421
3422                 sleep $sleep
3423                 waited=$((SECONDS - begin))
3424         done
3425
3426         [[ -z "$quiet" ]] &&
3427         echo "Update not seen after ${max_wait}s: want '$expect' got '$result'"
3428
3429         return 3
3430 }
3431
3432 # usage: wait_update [--verbose] [--quiet] node check expect [max_wait]
3433 wait_update() {
3434         local verbose
3435         local quiet
3436
3437         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3438         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3439
3440         local node="$1"
3441         local check="$2"
3442         local expect="$3"
3443         local max_wait=$4
3444
3445         wait_update_cond $verbose $quiet $node "$check" "==" "$expect" $max_wait
3446 }
3447
3448 # usage: wait_update_facet_cond [--verbose] facet check cond expect [max_wait]
3449 wait_update_facet_cond() {
3450         local verbose
3451         local quiet
3452
3453         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3454         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3455
3456         local node=$(facet_active_host $1)
3457         local check="$2"
3458         local cond="$3"
3459         local expect="$4"
3460         local max_wait=$5
3461
3462         wait_update_cond $verbose $quiet $node "$check" "$cond" "$expect" $max_wait
3463 }
3464
3465 # usage: wait_update_facet [--verbose] facet check expect [max_wait]
3466 wait_update_facet() {
3467         local verbose
3468         local quiet
3469
3470         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
3471         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
3472
3473         local node=$(facet_active_host $1)
3474         local check="$2"
3475         local expect="$3"
3476         local max_wait=$4
3477
3478         wait_update_cond $verbose $quiet $node "$check" "==" "$expect" $max_wait
3479 }
3480
3481 sync_all_data() {
3482         do_nodes $(comma_list $(mdts_nodes)) \
3483             "lctl set_param -n os[cd]*.*MDT*.force_sync=1"
3484         do_nodes $(comma_list $(osts_nodes)) \
3485             "lctl set_param -n osd*.*OS*.force_sync=1" 2>&1 |
3486                 grep -v 'Found no match'
3487 }
3488
3489 wait_zfs_commit() {
3490         local zfs_wait=${2:-5}
3491
3492         # the occupied disk space will be released
3493         # only after TXGs are committed
3494         if [[ $(facet_fstype $1) == zfs ]]; then
3495                 echo "sleep $zfs_wait for ZFS $(facet_fstype $1)"
3496                 sleep $zfs_wait
3497         fi
3498 }
3499
3500 fill_ost() {
3501         local filename=$1
3502         local ost_idx=$2
3503         local lwm=$3  #low watermark
3504         local size_mb #how many MB should we write to pass watermark
3505         local ost_name=$(ostname_from_index $ost_idx)
3506
3507         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3508         size_mb=0
3509         if (( $free_kb / 1024 > lwm )); then
3510                 size_mb=$((free_kb / 1024 - lwm))
3511         fi
3512         #If 10% of free space cross low watermark use it
3513         if (( $free_kb / 10240 > size_mb )); then
3514                 size_mb=$((free_kb / 10240))
3515         else
3516                 #At least we need to store 1.1 of difference between
3517                 #free space and low watermark
3518                 size_mb=$((size_mb + size_mb / 10))
3519         fi
3520         if (( lwm <= $free_kb / 1024 )) ||
3521            [ ! -f $DIR/${filename}.fill_ost$ost_idx ]; then
3522                 $LFS setstripe -i $ost_idx -c1 $DIR/${filename}.fill_ost$ost_idx
3523                 dd if=/dev/zero of=$DIR/${filename}.fill_ost$ost_idx bs=1M \
3524                         count=$size_mb oflag=append conv=notrunc
3525         fi
3526
3527         sleep_maxage
3528
3529         free_kb=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3530         echo "OST still has $((free_kb / 1024)) MB free"
3531 }
3532
3533 # This checks only the primary MDS
3534 ost_watermarks_get() {
3535         local ost_idx=$1
3536         local ost_name=$(ostname_from_index $ost_idx)
3537         local mdtosc_proc=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)
3538
3539         local hwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3540                         osp.$mdtosc_proc.reserved_mb_high)
3541         local lwm=$(do_facet $SINGLEMDS $LCTL get_param -n \
3542                         osp.$mdtosc_proc.reserved_mb_low)
3543
3544         echo "$lwm $hwm"
3545 }
3546
3547 # Note that we set watermarks on all MDSes (necessary for striped dirs)
3548 ost_watermarks_set() {
3549         local ost_idx=$1
3550         local lwm=$2
3551         local hwm=$3
3552         local ost_name=$(ostname_from_index $ost_idx)
3553         local facets=$(get_facets MDS)
3554
3555         do_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \
3556                 osp.*$ost_name*.reserved_mb_low=$lwm \
3557                 osp.*$ost_name*.reserved_mb_high=$hwm > /dev/null
3558
3559         # sleep to ensure we see the change
3560         sleep_maxage
3561 }
3562
3563 ost_watermarks_set_low_space() {
3564         local ost_idx=$1
3565         local wms=$(ost_watermarks_get $ost_idx)
3566         local ost_name=$(ostname_from_index $ost_idx)
3567
3568         local old_lwm=$(echo $wms | awk '{ print $1 }')
3569         local old_hwm=$(echo $wms | awk '{ print $2 }')
3570
3571         local blocks=$($LFS df $MOUNT | awk "/$ost_name/ { print \$4 }")
3572         # minimal extension size is 64M
3573         local new_lwm=50
3574         if (( $blocks / 1024 > 50 )); then
3575                 new_lwm=$((blocks / 1024 - 50))
3576         fi
3577         local new_hwm=$((new_lwm + 5))
3578
3579         ost_watermarks_set $ost_idx $new_lwm $new_hwm
3580         echo "watermarks: $old_lwm $old_hwm $new_lwm $new_hwm"
3581 }
3582
3583 # Set watermarks to ~current available space & then write data to fill it
3584 # Note OST is not *actually* full after this, it just reports ENOSPC in the
3585 # internal statfs used by the stripe allocator
3586 #
3587 # first parameter is the filename-prefix, which must get under t-f cleanup
3588 # requirements (rm -rf $DIR/[Rdfs][0-9]*), i.e. $tfile work fine
3589 ost_watermarks_set_enospc() {
3590         local filename=$1
3591         local ost_idx=$2
3592         # on the mdt's osc
3593         local ost_name=$(ostname_from_index $ost_idx)
3594         local facets=$(get_facets MDS)
3595         local wms
3596         local MDS
3597
3598         for MDS in ${facets//,/ }; do
3599                 local mdtosc_proc=$(get_mdtosc_proc_path $MDS $ost_name)
3600
3601                 do_facet $MDS $LCTL get_param -n \
3602                         osp.$mdtosc_proc.reserved_mb_high ||
3603                         skip  "remote MDS does not support reserved_mb_high"
3604         done
3605
3606         wms=$(ost_watermarks_set_low_space $ost_idx)
3607         local new_lwm=$(echo $wms | awk '{ print $4 }')
3608         fill_ost $filename $ost_idx $new_lwm
3609         #First enospc could execute orphan deletion so repeat
3610         fill_ost $filename $ost_idx $new_lwm
3611         echo $wms
3612 }
3613
3614 ost_watermarks_enospc_delete_files() {
3615         local filename=$1
3616         local ost_idx=$2
3617
3618         rm -f $DIR/${filename}.fill_ost$ost_idx
3619
3620         wait_delete_completed
3621         wait_mds_ost_sync
3622 }
3623
3624 # clean up from "ost_watermarks_set_enospc"
3625 ost_watermarks_clear_enospc() {
3626         local filename=$1
3627         local ost_idx=$2
3628         local old_lwm=$4
3629         local old_hwm=$5
3630
3631         ost_watermarks_enospc_delete_files $filename $ost_idx
3632         ost_watermarks_set $ost_idx $old_lwm $old_hwm
3633         echo "set OST$ost_idx lwm back to $old_lwm, hwm back to $old_hwm"
3634 }
3635
3636 wait_delete_completed_mds() {
3637         local max_wait=${1:-20}
3638         local mds2sync=""
3639         local stime=$(date +%s)
3640         local etime
3641         local node
3642         local changes
3643
3644         # find MDS with pending deletions
3645         for node in $(mdts_nodes); do
3646                 changes=$(do_node $node "$LCTL get_param -n osc.*MDT*.sync_*" \
3647                         2>/dev/null | calc_sum)
3648                 if [[ $changes -eq 0 ]]; then
3649                         continue
3650                 fi
3651                 mds2sync="$mds2sync $node"
3652         done
3653         if [ -z "$mds2sync" ]; then
3654                 wait_zfs_commit $SINGLEMDS
3655                 return 0
3656         fi
3657         mds2sync=$(comma_list $mds2sync)
3658
3659         # sync MDS transactions
3660         do_nodes $mds2sync "$LCTL set_param -n os[cd]*.*MD*.force_sync 1"
3661
3662         # wait till all changes are sent and commmitted by OSTs
3663         # for ldiskfs space is released upon execution, but DMU
3664         # do this upon commit
3665
3666         local WAIT=0
3667         while [[ $WAIT -ne $max_wait ]]; do
3668                 changes=$(do_nodes $mds2sync \
3669                         "$LCTL get_param -n osc.*MDT*.sync_*" | calc_sum)
3670                 #echo "$node: $changes changes on all"
3671                 if [[ $changes -eq 0 ]]; then
3672                         wait_zfs_commit $SINGLEMDS
3673
3674                         # the occupied disk space will be released
3675                         # only after TXGs are committed
3676                         wait_zfs_commit ost1
3677                         return 0
3678                 fi
3679                 sleep 1
3680                 WAIT=$((WAIT + 1))
3681         done
3682
3683         etime=$(date +%s)
3684         echo "Delete is not completed in $((etime - stime)) seconds"
3685         do_nodes $mds2sync "$LCTL get_param osc.*MDT*.sync_*"
3686         return 1
3687 }
3688
3689 wait_for_host() {
3690         local hostlist=$1
3691
3692         # we can use "for" here because we are waiting the slowest
3693         for host in ${hostlist//,/ }; do
3694                 check_network "$host" 900
3695         done
3696         while ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done
3697 }
3698
3699 wait_for_facet() {
3700         local facetlist=$1
3701         local hostlist
3702
3703         for facet in ${facetlist//,/ }; do
3704                 hostlist=$(expand_list $hostlist $(facet_active_host $facet))
3705         done
3706         wait_for_host $hostlist
3707 }
3708
3709 _wait_recovery_complete () {
3710         local param=$1
3711
3712         # Use default policy if $2 is not passed by caller.
3713         local MAX=${2:-$(max_recovery_time)}
3714
3715         local WAIT=0
3716         local STATUS=
3717
3718         while [ $WAIT -lt $MAX ]; do
3719                 STATUS=$(lctl get_param -n $param | grep status)
3720                 echo $param $STATUS
3721                 [[ $STATUS == "status: COMPLETE" ||
3722                         $STATUS == "status: INACTIVE" ]] && return 0
3723                 sleep 5
3724                 WAIT=$((WAIT + 5))
3725                 echo "Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS"
3726         done
3727         echo "$param recovery not done in $MAX sec. $STATUS"
3728         return 1
3729 }
3730
3731 wait_recovery_complete () {
3732         local facet=$1
3733
3734         # with an assumption that at_max is the same on all nodes
3735         local MAX=${2:-$(max_recovery_time)}
3736
3737         local facets=$facet
3738         if [ "$FAILURE_MODE" = HARD ]; then
3739                 facets=$(facets_on_host $(facet_active_host $facet))
3740         fi
3741         echo affected facets: $facets
3742
3743         facets=${facets//,/ }
3744         # We can use "for" here because we are waiting the slowest.
3745         # The mgs not having the recovery_status proc entry, exclude it
3746         # from the facet list.
3747         for facet in ${facets//mgs/ }; do
3748                 local var_svc=${facet}_svc
3749                 local param="*.${!var_svc}.recovery_status"
3750
3751                 local host=$(facet_active_host $facet)
3752                 do_rpc_nodes "$host" _wait_recovery_complete $param $MAX
3753         done
3754 }
3755
3756 wait_mds_ost_sync () {
3757         # just because recovery is done doesn't mean we've finished
3758         # orphan cleanup. Wait for llogs to get synchronized.
3759         echo "Waiting for orphan cleanup..."
3760         # MAX value includes time needed for MDS-OST reconnection
3761         local MAX=$(( TIMEOUT * 2 ))
3762         local WAIT_TIMEOUT=${1:-$MAX}
3763         local WAIT=0
3764         local new_wait=true
3765         local list=$(comma_list $(mdts_nodes))
3766         local cmd="$LCTL get_param -n osp.*osc*.old_sync_processed"
3767         if ! do_facet $SINGLEMDS \
3768                 "$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null"
3769         then
3770                 # old way, use mds_sync
3771                 new_wait=false
3772                 list=$(comma_list $(osts_nodes))
3773                 cmd="$LCTL get_param -n obdfilter.*.mds_sync"
3774         fi
3775
3776         echo "wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done."
3777         while [ $WAIT -lt $WAIT_TIMEOUT ]; do
3778                 local -a sync=($(do_nodes $list "$cmd"))
3779                 local con=1
3780                 local i
3781                 for ((i=0; i<${#sync[@]}; i++)); do
3782                         if $new_wait; then
3783                                 [ ${sync[$i]} -eq 1 ] && continue
3784                         else
3785                                 [ ${sync[$i]} -eq 0 ] && continue
3786                         fi
3787                         # there is a not finished MDS-OST synchronization
3788                         con=0
3789                         break;
3790                 done
3791                 sleep 2 # increase waiting time and cover statfs cache
3792                 [ ${con} -eq 1 ] && return 0
3793                 echo "Waiting $WAIT secs for $list $i mds-ost sync done."
3794                 WAIT=$((WAIT + 2))
3795         done
3796
3797         # show which nodes are not finished.
3798         cmd=$(echo $cmd | sed 's/-n//')
3799         do_nodes $list "$cmd"
3800         echo "$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS"
3801         return 1
3802 }
3803
3804 # Wait OSTs to be active on both client and MDT side.
3805 wait_osts_up() {
3806         local cmd="$LCTL get_param -n lov.$FSNAME-clilov-*.target_obd |
3807                 awk 'BEGIN {c = 0} /ACTIVE/{c += 1} END {printf \\\"%d\\\", c}'"
3808         wait_update $HOSTNAME "eval $cmd" $OSTCOUNT ||
3809                 error "wait_update OSTs up on client failed"
3810
3811         cmd="$LCTL get_param osp.$FSNAME-OST*-MDT0000.prealloc_last_id |
3812              awk '/=[1-9][0-9]/ { c += 1 } END { printf \\\"%d\\\", c }'"
3813         wait_update_facet $SINGLEMDS "eval $cmd" $OSTCOUNT ||
3814                 error "wait_update OSTs up on MDT0000 failed"
3815 }
3816
3817 wait_destroy_complete () {
3818         echo "Waiting for MDT destroys to complete"
3819         # MAX value shouldn't be big as this mean server responsiveness
3820         # never increase this just to make test pass but investigate
3821         # why it takes so long time
3822         local MAX=${1:-5}
3823         local WAIT=0
3824         local list=$(comma_list $(mdts_nodes))
3825         while [ $WAIT -lt $MAX ]; do
3826                 local -a RPCs=($(do_nodes $list $LCTL get_param -n osp.*.destroys_in_flight))
3827                 local con=1
3828                 local i
3829
3830                 for ((i=0; i<${#RPCs[@]}; i++)); do
3831                         [ ${RPCs[$i]} -eq 0 ] && continue
3832                         # there are still some destroy RPCs in flight
3833                         con=0
3834                         break;
3835                 done
3836                 [ ${con} -eq 1 ] && return 0 # done waiting
3837                 sleep 1
3838                 echo "Waiting ${WAIT}s for local destroys to complete"
3839                 WAIT=$((WAIT + 1))
3840         done
3841         echo "MDT destroys weren't done in $MAX sec."
3842         return 1
3843 }
3844
3845 wait_delete_completed() {
3846         wait_delete_completed_mds $1 || return $?
3847         wait_destroy_complete || return $?
3848 }
3849
3850 wait_exit_ST () {
3851         local facet=$1
3852
3853         local WAIT=0
3854         local INTERVAL=1
3855         local running
3856         # conf-sanity 31 takes a long time cleanup
3857         while [ $WAIT -lt 300 ]; do
3858                 running=$(do_facet ${facet} "lsmod | grep lnet > /dev/null &&
3859 lctl dl | grep ' ST ' || true")
3860                 [ -z "${running}" ] && return 0
3861                 echo "waited $WAIT for${running}"
3862                 [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))
3863                 sleep $INTERVAL
3864                 WAIT=$((WAIT + INTERVAL))
3865         done
3866         echo "service didn't stop after $WAIT seconds.  Still running:"
3867         echo ${running}
3868         return 1
3869 }
3870
3871 wait_remote_prog () {
3872         local prog=$1
3873         local WAIT=0
3874         local INTERVAL=5
3875         local rc=0
3876
3877         [ "$PDSH" = "no_dsh" ] && return 0
3878
3879         while [ $WAIT -lt $2 ]; do
3880                 running=$(ps uax | grep "$PDSH.*$prog.*$MOUNT" |
3881                         grep -v grep) || true
3882                 [ -z "${running}" ] && return 0 || true
3883                 echo "waited $WAIT for: "
3884                 echo "$running"
3885                 [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))
3886                 sleep $INTERVAL
3887                 WAIT=$((WAIT + INTERVAL))
3888         done
3889         local pids=$(ps  uax | grep "$PDSH.*$prog.*$MOUNT" |
3890                         grep -v grep | awk '{print $2}')
3891         [ -z "$pids" ] && return 0
3892         echo "$PDSH processes still exists after $WAIT seconds.  Still running: $pids"
3893         # FIXME: not portable
3894         for pid in $pids; do
3895                 cat /proc/${pid}/status || true
3896                 cat /proc/${pid}/wchan || true
3897                 echo "Killing $pid"
3898                 kill -9 $pid || true
3899                 sleep 1
3900                 ps -P $pid && rc=1
3901         done
3902
3903         return $rc
3904 }
3905
3906 _lfs_df_check() {
3907         local clients=${1:-$CLIENTS}
3908         local rc=0
3909
3910         if [[ -z "$clients" ]]; then
3911                 $LFS df $MOUNT > /dev/null || rc=$?
3912         else
3913                 $PDSH $clients "$LFS df $MOUNT" > /dev/null || rc=$?
3914         fi
3915
3916         return $rc
3917 }
3918
3919 lfs_df_check() {
3920         local clients=${1:-$CLIENTS}
3921         local rc=0
3922
3923         _lfs_df_check "$clients" || rc=$?
3924
3925         check_lfs_df_ret_val $rc
3926 }
3927
3928 clients_up() {
3929         # not every config has many clients
3930         sleep 1
3931         lfs_df_check
3932 }
3933
3934 all_mds_up() {
3935         (( MDSCOUNT == 1 )) && return
3936
3937         # wait so that statfs data on MDT expire
3938         local delay=$(do_facet mds1 $LCTL \
3939                 get_param -n osp.*MDT*MDT0000.maxage | sort -n | tail -1)
3940
3941         [ -n "$delay" ] || error "fail to get maxage"
3942         sleep $delay
3943         local nodes=$(comma_list $(mdts_nodes))
3944         # initiate statfs RPC, all to all MDTs
3945         do_nodes $nodes $LCTL get_param -N osp.*MDT*MDT*.filesfree >&/dev/null
3946         do_nodes $nodes $LCTL get_param -N osp.*MDT*MDT*.filesfree >&/dev/null
3947 }
3948
3949 client_up() {
3950         # usually checked on particular client or locally
3951         sleep 1
3952         lfs_df_check $1
3953 }
3954
3955 client_evicted() {
3956         sleep 1
3957         ! _lfs_df_check $1
3958 }
3959
3960 client_reconnect_try() {
3961         local f=$MOUNT/recon
3962
3963         uname -n >> $f
3964         if [ -z "$CLIENTS" ]; then
3965                 $LFS df $MOUNT; uname -n >> $f
3966         else
3967                 do_nodes $CLIENTS "$LFS df $MOUNT; uname -n >> $f" > /dev/null
3968         fi
3969         echo "Connected clients: $(cat $f)"
3970         ls -l $f > /dev/null
3971         rm $f
3972 }
3973
3974 client_reconnect() {
3975         # one client_reconnect_try call does not always do the job...
3976         while true ; do
3977                 client_reconnect_try && break
3978                 sleep 1
3979         done
3980 }
3981
3982 affected_facets () {
3983         local facet=$1
3984
3985         local host=$(facet_active_host $facet)
3986         local affected=$facet
3987
3988         if [ "$FAILURE_MODE" = HARD ]; then
3989                 affected=$(facets_up_on_host $host)
3990         fi
3991         echo $affected
3992 }
3993
3994 facet_failover() {
3995         local E2FSCK_ON_MDT0=false
3996         if [ "$1" == "--fsck" ]; then
3997                 shift
3998                 [ $(facet_fstype $SINGLEMDS) == ldiskfs ] &&
3999                         E2FSCK_ON_MDT0=true
4000         fi
4001
4002         local facets=$1
4003         local sleep_time=$2
4004         local -a affecteds
4005         local facet
4006         local total=0
4007         local index=0
4008         local skip
4009
4010         #Because it will only get up facets, we need get affected
4011         #facets before shutdown
4012         #For HARD Failure mode, it needs make sure facets on the same
4013         #HOST will only be shutdown and reboot once
4014         for facet in ${facets//,/ }; do
4015                 local affected_facet
4016                 skip=0
4017                 #check whether facet has been included in other affected facets
4018                 for ((index=0; index<$total; index++)); do
4019                         [[ ,${affecteds[index]}, == *,$facet,* ]] && skip=1
4020                 done
4021
4022                 if [ $skip -eq 0 ]; then
4023                         affecteds[$total]=$(affected_facets $facet)
4024                         total=$((total+1))
4025                 fi
4026         done
4027
4028         for ((index=0; index<$total; index++)); do
4029                 facet=$(echo ${affecteds[index]} | tr -s " " | cut -d"," -f 1)
4030                 local host=$(facet_active_host $facet)
4031                 echo "Failing ${affecteds[index]} on $host"
4032                 shutdown_facet $facet
4033         done
4034
4035         echo "$(date +'%H:%M:%S (%s)') shut down"
4036
4037         local hostlist
4038         local waithostlist
4039
4040         for facet in ${facets//,/ }; do
4041                 local host=$(facet_active_host $facet)
4042
4043                 hostlist=$(expand_list $hostlist $host)
4044                 if [ $(facet_host $facet) = \
4045                         $(facet_failover_host $facet) ]; then
4046                         waithostlist=$(expand_list $waithostlist $host)
4047                 fi
4048         done
4049
4050         if [ "$FAILURE_MODE" = HARD ]; then
4051                 for host in ${hostlist//,/ }; do
4052                         reboot_node $host
4053                 done
4054                 echo "$(date +'%H:%M:%S (%s)') $hostlist rebooted"
4055                 # We need to wait the rebooted hosts in case if
4056                 # facet_HOST == facetfailover_HOST
4057                 if ! [ -z "$waithostlist" ]; then
4058                         wait_for_host $waithostlist
4059                         if $LOAD_MODULES_REMOTE; then
4060                                 echo "loading modules on $waithostlist"
4061                                 do_rpc_nodes $waithostlist load_modules_local
4062                         fi
4063                 fi
4064         else
4065                 sleep 10
4066         fi
4067
4068         if [[ " ${affecteds[@]} " =~ " $SINGLEMDS " ]]; then
4069                 change_active $SINGLEMDS
4070         fi
4071
4072         $E2FSCK_ON_MDT0 && (run_e2fsck $(facet_active_host $SINGLEMDS) \
4073                 $(facet_device $SINGLEMDS) "-n" || error "Running e2fsck")
4074
4075         local -a mountpids
4076
4077         for ((index=0; index<$total; index++)); do
4078                 if [[ ${affecteds[index]} != $SINGLEMDS ]]; then
4079                         change_active ${affecteds[index]}
4080                 fi
4081                 if $GSS_SK; then
4082                         init_gss
4083                         init_facets_vars_simple
4084                 fi
4085                 # start mgs first if it is affected
4086                 if ! combined_mgs_mds &&
4087                         list_member ${affecteds[index]} mgs; then
4088                         mount_facet mgs || error "Restart of mgs failed"
4089                         affecteds[index]=$(exclude_items_from_list \
4090                                 ${affecteds[index]} mgs)
4091                 fi
4092                 if [ -n "${affecteds[index]}" ]; then
4093                         echo mount facets: ${affecteds[index]}
4094                         mount_facets ${affecteds[index]} &
4095                         mountpids[index]=$!
4096                 fi
4097         done
4098         for ((index=0; index<$total; index++)); do
4099                 if [ -n "${affecteds[index]}" ]; then
4100                         wait ${mountpids[index]}
4101                 fi
4102
4103                 if $GSS_SK; then
4104                         do_nodes $(comma_list $(all_nodes)) \
4105                                 "keyctl show | grep lustre | cut -c1-11 |
4106                                 sed -e 's/ //g;' |
4107                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
4108                 fi
4109         done
4110         echo "$(date +'%H:%M:%S (%s)') targets are mounted"
4111
4112         if [ "$FAILURE_MODE" = HARD ]; then
4113                 hostlist=$(exclude_items_from_list $hostlist $waithostlist)
4114                 if ! [ -z "$hostlist" ]; then
4115                         wait_for_host $hostlist
4116                         if $LOAD_MODULES_REMOTE; then
4117                                 echo "loading modules on $hostlist"
4118                                 do_rpc_nodes $hostlist load_modules_local
4119                         fi
4120                 fi
4121         fi
4122
4123         echo "$(date +'%H:%M:%S (%s)') facet_failover done"
4124 }
4125
4126 replay_barrier() {
4127         local facet=$1
4128         do_facet $facet "sync; sync; sync"
4129         $LFS df $MOUNT
4130
4131         # make sure there will be no seq change
4132         local clients=${CLIENTS:-$HOSTNAME}
4133         local f=fsa-\\\$\(hostname\)
4134         do_nodes $clients "mcreate $MOUNT/$f; rm $MOUNT/$f"
4135         do_nodes $clients "if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi"
4136
4137         local svc=${facet}_svc
4138         do_facet $facet $LCTL --device ${!svc} notransno
4139         #
4140         # If a ZFS OSD is made read-only here, its pool is "freezed". This
4141         # in-memory state has to be cleared by either rebooting the host or
4142         # exporting and reimporting the pool.
4143         #
4144         # Although the uberblocks are not updated when a pool is freezed,
4145         # transactions are still written to the disks. Modified blocks may be
4146         # cached in memory when tests try reading them back. The
4147         # export-and-reimport process also evicts any cached pool data from
4148         # memory to provide the correct "data loss" semantics.
4149         #
4150         # In the test framework, the exporting and importing operations are
4151         # handled by stop() and mount_facet() separately, which are used
4152         # inside fail() and fail_abort().
4153         #
4154         set_dev_readonly $facet
4155         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
4156         $LCTL mark "local REPLAY BARRIER on ${!svc}"
4157 }
4158
4159 replay_barrier_nodf() {
4160         local facet=$1    echo running=${running}
4161         do_facet $facet "sync; sync; sync"
4162         local svc=${facet}_svc
4163         echo Replay barrier on ${!svc}
4164         do_facet $facet $LCTL --device ${!svc} notransno
4165         set_dev_readonly $facet
4166         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
4167         $LCTL mark "local REPLAY BARRIER on ${!svc}"
4168 }
4169
4170 replay_barrier_nosync() {
4171         local facet=$1    echo running=${running}
4172         local svc=${facet}_svc
4173         echo Replay barrier on ${!svc}
4174         do_facet $facet $LCTL --device ${!svc} notransno
4175         set_dev_readonly $facet
4176         do_facet $facet $LCTL mark "$facet REPLAY BARRIER on ${!svc}"
4177         $LCTL mark "local REPLAY BARRIER on ${!svc}"
4178 }
4179
4180 #
4181 # Get Lustre client uuid for a given Lustre mount point.
4182 #
4183 get_client_uuid() {
4184         local mntpnt=${1:-$MOUNT}
4185
4186         local name=$($LFS getname $mntpnt | cut -d' ' -f1)
4187         local uuid=$($LCTL get_param -n llite.$name.uuid)
4188
4189         echo -n $uuid
4190 }
4191
4192 mds_evict_client() {
4193         local mntpnt=${1:-$MOUNT}
4194         local uuid=$(get_client_uuid $mntpnt)
4195
4196         do_facet $SINGLEMDS \
4197                 "$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid"
4198 }
4199
4200 ost_evict_client() {
4201         local mntpnt=${1:-$MOUNT}
4202         local uuid=$(get_client_uuid $mntpnt)
4203
4204         do_facet ost1 \
4205                 "$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid"
4206 }
4207
4208 fail() {
4209         local facets=$1
4210         local clients=${CLIENTS:-$HOSTNAME}
4211
4212         SK_NO_KEY_save=$SK_NO_KEY
4213         if $GSS_SK; then
4214                 export SK_NO_KEY=false
4215         fi
4216         facet_failover $* || error "failover: $?"
4217         export SK_NO_KEY=$SK_NO_KEY_save
4218         # to initiate all OSC idling connections
4219         clients_up
4220         wait_clients_import_ready "$clients" "$facets"
4221         clients_up || error "post-failover stat: $?"
4222 }
4223
4224 fail_nodf() {
4225         local facet=$1
4226
4227         facet_failover $facet
4228 }
4229
4230 fail_abort() {
4231         local facet=$1
4232         local abort_type=${2:-"abort_recovery"}
4233
4234         stop $facet
4235         change_active $facet
4236         wait_for_facet $facet
4237         mount_facet $facet -o $abort_type
4238         clients_up || echo "first stat failed: $?"
4239         clients_up || error "post-failover stat: $?"
4240         all_mds_up
4241 }
4242
4243 # LU-16159: abort recovery will cancel update logs, which may leave broken
4244 # directories in the system, remove name entry if necessary
4245 fail_abort_cleanup() {
4246         rm -rf $DIR/$tdir/*
4247         find $DIR/$tdir -depth | while read D; do
4248                 rmdir "$D" || $LFS rm_entry "$D" || error "rm $D failed"
4249         done
4250 }
4251
4252 host_nids_address() {
4253         local nodes=$1
4254         local net=${2:-"."}
4255
4256         do_nodes $nodes "$LCTL list_nids | grep -w $net | cut -f 1 -d @"
4257 }
4258
4259 h2name_or_ip() {
4260         if [ "$1" = "'*'" ]; then echo \'*\'; else
4261                 echo $1"@$2"
4262         fi
4263 }
4264
4265 h2nettype() {
4266         if [[ -n "$NETTYPE" ]]; then
4267                 h2name_or_ip "$1" "$NETTYPE"
4268         else
4269                 h2name_or_ip "$1" "$2"
4270         fi
4271 }
4272 declare -fx h2nettype
4273
4274 # This enables variables in cfg/"setup".sh files to support the pdsh HOSTLIST
4275 # expressions format. As a bonus we can then just pass in those variables
4276 # to pdsh. What this function does is take a HOSTLIST type string and
4277 # expand it into a space deliminated list for us.
4278 hostlist_expand() {
4279         local hostlist=$1
4280         local offset=$2
4281         local myList
4282         local item
4283         local list
4284
4285         [ -z "$hostlist" ] && return
4286
4287         # Translate the case of [..],..,[..] to [..] .. [..]
4288         list="${hostlist/],/] }"
4289         front=${list%%[*}
4290         [[ "$front" == *,* ]] && {
4291                 new="${list%,*} "
4292                 old="${list%,*},"
4293                 list=${list/${old}/${new}}
4294         }
4295
4296         for item in $list; do
4297         # Test if we have any []'s at all
4298                 if [ "$item" != "${item/\[/}" ]; then {
4299                 # Expand the [*] into list
4300                 name=${item%%[*}
4301                 back=${item#*]}
4302
4303                         if [ "$name" != "$item" ]; then
4304                                 group=${item#$name[*}
4305                                 group=${group%%]*}
4306
4307                                 for range in ${group//,/ }; do
4308                                         local order
4309
4310                                         begin=${range%-*}
4311                                         end=${range#*-}
4312
4313                                         # Number of leading zeros
4314                                         padlen=${#begin}
4315                                         padlen2=${#end}
4316                                         end=$(echo $end | sed 's/0*//')
4317                                         [[ -z "$end" ]] && end=0
4318                                         [[ $padlen2 -gt $padlen ]] && {
4319                                                 [[ $padlen2 -eq ${#end} ]] &&
4320                                                         padlen2=0
4321                                                 padlen=$padlen2
4322                                         }
4323                                         begin=$(echo $begin | sed 's/0*//')
4324                                         [ -z $begin ] && begin=0
4325
4326                                         if [ ! -z "${begin##[!0-9]*}" ]; then
4327                                                 order=$(seq -f "%0${padlen}g" $begin $end)
4328                                         else
4329                                                 order=$(eval echo {$begin..$end});
4330                                         fi
4331
4332                                         for num in $order; do
4333                                                 value="${name#*,}${num}${back}"
4334
4335                                                 [ "$value" != "${value/\[/}" ] && {
4336                                                     value=$(hostlist_expand "$value")
4337                                                 }
4338                                                 myList="$myList $value"
4339                                         done
4340                                 done
4341                         fi
4342                 } else {
4343                         myList="$myList $item"
4344                 } fi
4345         done
4346         myList=${myList//,/ }
4347         myList=${myList:1} # Remove first character which is a space
4348
4349         # Filter any duplicates without sorting
4350         list="$myList "
4351         myList="${list%% *}"
4352
4353         while [[ "$list" != ${myList##* } ]]; do
4354                 local tlist=" $list"
4355
4356                 list=${tlist// ${list%% *} / }
4357                 list=${list:1}
4358                 myList="$myList ${list%% *}"
4359         done
4360         myList="${myList%* }";
4361
4362         # We can select an object at an offset in the list
4363         [ $# -eq 2 ] && {
4364         cnt=0
4365         for item in $myList; do
4366                 let cnt=cnt+1
4367                 [ $cnt -eq $offset ] && {
4368                         myList=$item
4369                 }
4370         done
4371         [ $(get_node_count $myList) -ne 1 ] && myList=""
4372         }
4373         echo $myList
4374 }
4375
4376 facet_host() {
4377         local facet=$1
4378         local varname
4379
4380         [ "$facet" == client ] && echo -n $HOSTNAME && return
4381         varname=${facet}_HOST
4382         if [ -z "${!varname}" ]; then
4383                 if [ "${facet:0:3}" == "ost" ]; then
4384                         local fh=${facet%failover}_HOST
4385                         eval export ${facet}_HOST=${!fh}
4386                         if [ -z "${!varname}" ]; then
4387                                 eval export ${facet}_HOST=${ost_HOST}
4388                         fi
4389                 elif [ "${facet:0:3}" == "mdt" -o \
4390                         "${facet:0:3}" == "mds" -o \
4391                         "${facet:0:3}" == "mgs" ]; then
4392                         local temp
4393                         if [ "${facet}" == "mgsfailover" ] &&
4394                            [ -n "$mds1failover_HOST" ]; then
4395                                 temp=$mds1failover_HOST
4396                         else
4397                                 temp=${mds_HOST}
4398                         fi
4399                         eval export ${facet}_HOST=$temp
4400                 fi
4401         fi
4402         echo -n ${!varname}
4403 }
4404
4405 facet_failover_host() {
4406         local facet=$1
4407         local varname
4408
4409         var=${facet}failover_HOST
4410         if [ -n "${!var}" ]; then
4411                 echo ${!var}
4412                 return
4413         fi
4414
4415         if combined_mgs_mds && [ $facet == "mgs" ] &&
4416                 [ -n "$mds1failover_HOST" ]; then
4417                 echo $mds1failover_HOST
4418                 return
4419         fi
4420
4421         if [ "${facet:0:3}" == "mdt" -o "${facet:0:3}" == "mds" -o \
4422              "${facet:0:3}" == "mgs" ]; then
4423
4424                 eval export ${facet}failover_host=${mds_HOST}
4425                 echo ${mds_HOST}
4426                 return
4427         fi
4428
4429         if [[ $facet == ost* ]]; then
4430                 eval export ${facet}failover_host=${ost_HOST}
4431                 echo ${ost_HOST}
4432                 return
4433         fi
4434 }
4435
4436 facet_active() {
4437         local facet=$1
4438         local activevar=${facet}active
4439
4440         if [ -f $TMP/${facet}active ] ; then
4441                 source $TMP/${facet}active
4442         fi
4443
4444         active=${!activevar}
4445         if [ -z "$active" ] ; then
4446                 echo -n ${facet}
4447         else
4448                 echo -n ${active}
4449         fi
4450 }
4451
4452 facet_active_host() {
4453         facet_host $(facet_active $1)
4454 }
4455
4456 # Get the passive failover partner host of facet.
4457 facet_passive_host() {
4458         local facet=$1
4459         [[ $facet = client ]] && return
4460
4461         local host=${facet}_HOST
4462         local failover_host=${facet}failover_HOST
4463         local active_host=$(facet_active_host $facet)
4464
4465         [[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return
4466
4467         if [[ $active_host = ${!host} ]]; then
4468                 echo -n ${!failover_host}
4469         else
4470                 echo -n ${!host}
4471         fi
4472 }
4473
4474 change_active() {
4475         local facetlist=$1
4476         local facet
4477
4478         for facet in ${facetlist//,/ }; do
4479                 local failover=${facet}failover
4480                 local host=`facet_host $failover`
4481
4482                 [ -z "$host" ] && return
4483
4484                 local curactive=`facet_active $facet`
4485
4486                 if [ -z "${curactive}" -o "$curactive" == "$failover" ] ; then
4487                         eval export ${facet}active=$facet
4488                 else
4489                         eval export ${facet}active=$failover
4490                 fi
4491                 # save the active host for this facet
4492                 local activevar=${facet}active
4493
4494                 echo "$activevar=${!activevar}" > $TMP/$activevar
4495                 [[ $facet = mds1 ]] && combined_mgs_mds && \
4496                 echo "mgsactive=${!activevar}" > $TMP/mgsactive
4497                 local TO=`facet_active_host $facet`
4498                 echo "Failover $facet to $TO"
4499         done
4500 }
4501
4502 do_node() {
4503         local verbose
4504         local quiet
4505
4506         # do not strip off hostname if verbose, b=19215
4507         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
4508         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
4509
4510         local HOST=$1
4511         shift
4512         local myPDSH=$PDSH
4513
4514         if [ "$HOST" = "$HOSTNAME" ]; then
4515                 myPDSH="no_dsh"
4516         elif [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" ]; then
4517                 echo "cannot run remote command on $HOST with $myPDSH"
4518                 return 128
4519         fi
4520         if $VERBOSE && [[ -z "$quiet" ]]; then
4521                 echo "CMD: $HOST $*" >&2
4522                 $myPDSH $HOST "$LCTL mark \"$*\"" > /dev/null 2>&1 || :
4523         fi
4524
4525         if [[ "$myPDSH" == "rsh" ]] ||
4526            [[ "$myPDSH" == *pdsh* && "$myPDSH" != *-S* ]]; then
4527                 # we need this because rsh and pdsh do not return
4528                 # exit code of an executed command
4529                 local command_status="$TMP/cs"
4530                 eval $myPDSH $HOST ":> $command_status"
4531                 eval $myPDSH $HOST "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests;
4532                                      PATH=\$PATH:/sbin:/usr/sbin;
4533                                      cd $RPWD;
4534                                      LUSTRE=\"$RLUSTRE\" bash -c \"$*\") ||
4535                                      echo command failed >$command_status"
4536                 [[ -n "$($myPDSH $HOST cat $command_status)" ]] && return 1 ||
4537                         return 0
4538         fi
4539
4540         if [[ -n "$verbose" ]]; then
4541                 # print HOSTNAME for myPDSH="no_dsh"
4542                 if [[ $myPDSH = no_dsh ]]; then
4543                         $myPDSH $HOST \
4544                         "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;\
4545                         cd $RPWD; LUSTRE=\"$RLUSTRE\" bash -c \"$*\")" |
4546                         sed -e "s/^/${HOSTNAME}: /"
4547                 else
4548                         $myPDSH $HOST \
4549                         "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;\
4550                         cd $RPWD; LUSTRE=\"$RLUSTRE\" bash -c \"$*\")"
4551                 fi
4552         else
4553                 $myPDSH $HOST \
4554                 "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin;\
4555                 cd $RPWD; LUSTRE=\"$RLUSTRE\" bash -c \"$*\")" |
4556                 sed "s/^${HOST}: //"
4557         fi
4558         return ${PIPESTATUS[0]}
4559 }
4560
4561 ##
4562 # Execute exact command line on host
4563 #
4564 # The \a host may be on a local or remote node, which is determined at
4565 # the time the command is run. Does careful argument quotation to
4566 # ensure that the exact command line is executed without any globbing,
4567 # substitution, or shell interpretation on the remote side. Does not
4568 # support --verbose or --quiet. Does not include "$host: " prefixes on
4569 # output. See also do_facet_vp().
4570 #
4571 # usage: do_node_vp "$host" "$command" "$arg"...
4572 do_node_vp() {
4573         local host="$1"
4574         shift
4575
4576         if [[ "$host" == "$HOSTNAME" ]]; then
4577                 bash -c "$(printf -- ' %q' "$@")"
4578                 return $?
4579         fi
4580
4581         if [[ "${PDSH}" != *pdsh* || "${PDSH}" != *-S* ]]; then
4582                 echo "cannot run '$*' on host '${host}' with PDSH='${PDSH}'" >&2
4583                 return 128
4584         fi
4585
4586         # -N Disable hostname: prefix on lines of output.
4587
4588         $PDSH "${host}" -N "cd $RPWD; PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; export LUSTRE=$RLUSTRE; $(printf -- ' %q' "$@")"
4589 }
4590
4591 single_local_node () {
4592         [ "$1" = "$HOSTNAME" ]
4593 }
4594
4595 # Outputs environment variable assignments that should be passed to remote nodes
4596 get_env_vars() {
4597         local var
4598         local value
4599         local facets=$(get_facets)
4600         local facet
4601
4602         for var in ${!MODOPTS_*}; do
4603                 value=${!var//\"/\\\"}
4604                 echo -n " ${var}=\"$value\""
4605         done
4606
4607         for facet in ${facets//,/ }; do
4608                 var=${facet}_FSTYPE
4609                 if [ -n "${!var}" ]; then
4610                         echo -n " $var=${!var}"
4611                 fi
4612         done
4613
4614         for var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do
4615                 if [ -n "${!var}" ]; then
4616                         echo -n " $var=${!var}"
4617                 fi
4618         done
4619
4620         for var in VERBOSE; do
4621                 if [ -n "${!var}" ]; then
4622                         echo -n " $var=${!var}"
4623                 fi
4624         done
4625
4626         if [ -n "$FSTYPE" ]; then
4627                 echo -n " FSTYPE=$FSTYPE"
4628         fi
4629
4630         for var in LNETLND NETTYPE; do
4631                 if [ -n "${!var}" ]; then
4632                         echo -n " $var=${!var}"
4633                 fi
4634         done
4635 }
4636
4637 do_nodes() {
4638         local verbose
4639         local quiet
4640
4641         # do not strip off hostname if verbose, b=19215
4642         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
4643         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
4644
4645         local rnodes=$1
4646         shift
4647
4648         if single_local_node $rnodes; then
4649                 do_node $verbose $quiet $rnodes "$@"
4650                 return $?
4651         fi
4652
4653         # This is part from do_node
4654         local myPDSH=$PDSH
4655
4656         [ -z "$myPDSH" -o "$myPDSH" = "no_dsh" -o "$myPDSH" = "rsh" ] &&
4657                 echo "cannot run remote command on $rnodes with $myPDSH" &&
4658                 return 128
4659
4660         export FANOUT=$(get_node_count "${rnodes//,/ }")
4661         if $VERBOSE && [[ -z "$quiet" ]]; then
4662                 echo "CMD: $rnodes $*" >&2
4663                 $myPDSH $rnodes "$LCTL mark \"$*\"" > /dev/null 2>&1 || :
4664         fi
4665
4666         # do not replace anything from pdsh output if -N is used
4667         # -N     Disable hostname: prefix on lines of output.
4668         if [[ -n "$verbose" || $myPDSH = *-N* ]]; then
4669                 $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) bash -c \"$*\")"
4670         else
4671                 $myPDSH $rnodes "(PATH=\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\"$RLUSTRE\" $(get_env_vars) bash -c \"$*\")" | sed -re "s/^[^:]*: //g"
4672         fi
4673         return ${PIPESTATUS[0]}
4674 }
4675
4676 ##
4677 # Execute commands on a single service's host
4678 #
4679 # The \a facet (service) may be on a local or remote node, which is
4680 # determined at the time the command is run.
4681 #
4682 # usage: do_facet $facet command [arg ...]
4683 do_facet() {
4684         local verbose
4685         local quiet
4686
4687         [[ "$1" == "--verbose" ]] && verbose="$1" && shift
4688         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
4689
4690         local facet=$1
4691         shift
4692         local host=$(facet_active_host $facet)
4693
4694         [ -z "$host" ] && echo "No host defined for facet ${facet}" && exit 1
4695         do_node $verbose $quiet $host "$@"
4696 }
4697
4698 ##
4699 # Execute exact command line on the host of a facet
4700 #
4701 # The \a facet (service) may be on a local or remote node, which is
4702 # determined at the time the command is run. Does careful argument
4703 # quotation to ensure that the exact command line is executed without
4704 # any globbing, substitution, or shell interpretation on the remote
4705 # side. Does not support --verbose or --quiet. Does not include
4706 # "$host: " prefixes on output.
4707 #
4708 # usage: do_facet_vp "$facet" "$command" "$arg"...
4709 do_facet_vp() {
4710         local facet="$1"
4711         local host=$(facet_active_host "$facet")
4712         shift
4713
4714         if [[ -z "$host" ]]; then
4715                 echo "no host defined for facet ${facet}" >&2
4716                 exit 1
4717         fi
4718
4719         do_node_vp "$host" "$@"
4720 }
4721
4722 # Function: do_facet_random_file $FACET $FILE $SIZE
4723 # Creates FILE with random content on the given FACET of given SIZE
4724
4725 do_facet_random_file() {
4726         local facet="$1"
4727         local fpath="$2"
4728         local fsize="$3"
4729         local cmd="dd if=/dev/urandom of='$fpath' bs=$fsize count=1"
4730         do_facet $facet "$cmd 2>/dev/null"
4731 }
4732
4733 do_facet_create_file() {
4734         local facet="$1"
4735         local fpath="$2"
4736         local fsize="$3"
4737         local cmd="dd if=/dev/zero of='$fpath' bs=$fsize count=1"
4738         do_facet $facet "$cmd 2>/dev/null"
4739 }
4740
4741 do_nodesv() {
4742         do_nodes --verbose "$@"
4743 }
4744
4745 add() {
4746         local facet=$1
4747         shift
4748         # make sure its not already running
4749         stop ${facet} -f
4750         rm -f $TMP/${facet}active
4751         [[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive
4752
4753         # make sure in-tree ldiskfs is loaded before mkfs
4754         if local_mode && [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then
4755                 load_module ../ldiskfs/ldiskfs
4756         fi
4757
4758         do_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}
4759
4760         if [[ $(facet_fstype $facet) == zfs ]]; then
4761                 #
4762                 # After formatting a ZFS target, "cachefile=none" property will
4763                 # be set on the ZFS storage pool so that the pool is not
4764                 # automatically imported on system startup. And then the pool
4765                 # will be exported so as to leave the importing and exporting
4766                 # operations handled by mount_facet() and stop() separately.
4767                 #
4768                 refresh_partition_table $facet $(facet_vdevice $facet)
4769                 disable_zpool_cache $facet
4770                 export_zpool $facet
4771         fi
4772 }
4773
4774 # Device formatted as ost
4775 ostdevname() {
4776         local num=$1
4777         local DEVNAME=OSTDEV$num
4778
4779         local fstype=$(facet_fstype ost$num)
4780
4781         case $fstype in
4782                 ldiskfs )
4783                         local dev=ost${num}_dev
4784                         [[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||
4785                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE + num
4786                         eval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
4787                 zfs )
4788                         #try $OSTZFSDEVn - independent of vdev
4789                         DEVNAME=OSTZFSDEV$num
4790                         eval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;
4791                 * )
4792                         error "unknown fstype!";;
4793         esac
4794
4795         echo -n $DEVPTR
4796 }
4797
4798 # Physical device location of data
4799 ostvdevname() {
4800         local num=$1
4801         local DEVNAME
4802         local VDEVPTR
4803
4804         local fstype=$(facet_fstype ost$num)
4805
4806         case $fstype in
4807                 ldiskfs )
4808                         # vdevs are not supported by ldiskfs
4809                         eval VDEVPTR="";;
4810                 zfs )
4811                         #if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}
4812                         # Device formatted by zfs
4813                         DEVNAME=OSTDEV$num
4814                         eval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;
4815                 * )
4816                         error "unknown fstype!";;
4817         esac
4818
4819         echo -n $VDEVPTR
4820 }
4821
4822 # Logical device formatted for lustre
4823 mdsdevname() {
4824         local num=$1
4825         local DEVNAME=MDSDEV$num
4826
4827         local fstype=$(facet_fstype mds$num)
4828
4829         case $fstype in
4830                 ldiskfs )
4831                         local dev=mds${num}_dev
4832                         [[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||
4833                         #if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
4834                         eval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
4835                 zfs )
4836                         # try $MDSZFSDEVn - independent of vdev
4837                         DEVNAME=MDSZFSDEV$num
4838                         eval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;
4839                 * )
4840                         error "unknown fstype!";;
4841         esac
4842
4843         echo -n $DEVPTR
4844 }
4845
4846 # Physical location of data
4847 mdsvdevname() {
4848         local VDEVPTR=""
4849         local num=$1
4850         local fstype=$(facet_fstype mds$num)
4851
4852         case $fstype in
4853                 ldiskfs )
4854                         # vdevs are not supported by ldiskfs
4855                         eval VDEVPTR="";;
4856                 zfs )
4857                         # if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}
4858                         # Device formatted by ZFS
4859                         local DEVNAME=MDSDEV$num
4860                         eval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;
4861                 * )
4862                         error "unknown fstype!";;
4863         esac
4864
4865         echo -n $VDEVPTR
4866 }
4867
4868 mgsdevname() {
4869         local DEVPTR
4870         local fstype=$(facet_fstype mgs)
4871
4872         case $fstype in
4873         ldiskfs )
4874                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
4875                    ( [ -z "$MGSDEV" ] || [ $MGSDEV = $MDSDEV1 ] ); then
4876                         DEVPTR=$(mdsdevname 1)
4877                 else
4878                         [[ -n $mgs_dev ]] && DEVPTR=$mgs_dev ||
4879                         DEVPTR=$MGSDEV
4880                 fi;;
4881         zfs )
4882                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
4883                     ( [ -z "$MGSZFSDEV" ] &&
4884                         [ -z "$MGSDEV" -o "$MGSDEV" = $(mdsvdevname 1) ] ); then
4885                         DEVPTR=$(mdsdevname 1)
4886                 else
4887                         DEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}
4888                 fi;;
4889         * )
4890                 error "unknown fstype!";;
4891         esac
4892
4893         echo -n $DEVPTR
4894 }
4895
4896 mgsvdevname() {
4897         local VDEVPTR=""
4898
4899         local fstype=$(facet_fstype mgs)
4900
4901         case $fstype in
4902         ldiskfs )
4903                 # vdevs are not supported by ldiskfs
4904                 ;;
4905         zfs )
4906                 if [ $(facet_host mgs) = $(facet_host mds1) ] &&
4907                    ( [ -z "$MGSDEV" ] &&
4908                        [ -z "$MGSZFSDEV" -o "$MGSZFSDEV" = $(mdsdevname 1) ]); then
4909                         VDEVPTR=$(mdsvdevname 1)
4910                 elif [ -n "$MGSDEV" ]; then
4911                         VDEVPTR=$MGSDEV
4912                 fi;;
4913         * )
4914                 error "unknown fstype!";;
4915         esac
4916
4917         echo -n $VDEVPTR
4918 }
4919
4920 facet_mntpt () {
4921         local facet=$1
4922         [[ $facet = mgs ]] && combined_mgs_mds && facet="mds1"
4923
4924         local var=${facet}_MOUNT
4925         eval mntpt=${!var:-${MOUNT}-$facet}
4926
4927         echo -n $mntpt
4928 }
4929
4930 mount_ldiskfs() {
4931         local facet=$1
4932         local dev=$(facet_device $facet)
4933         local mnt=${2:-$(facet_mntpt $facet)}
4934         local opts
4935         local dm_dev=$dev
4936
4937         if dm_flakey_supported $facet; then
4938                 dm_dev=$(dm_create_dev $facet $dev)
4939                 [[ -n "$dm_dev" ]] || dm_dev=$dev
4940         fi
4941         is_blkdev $facet $dm_dev || opts=$(csa_add "$opts" -o loop)
4942         export_dm_dev $facet $dm_dev
4943
4944         do_facet $facet mount -t ldiskfs $opts $dm_dev $mnt
4945 }
4946
4947 unmount_ldiskfs() {
4948         local facet=$1
4949         local dev=$(facet_device $facet)
4950         local mnt=${2:-$(facet_mntpt $facet)}
4951
4952         do_facet $facet $UMOUNT $mnt
4953 }
4954
4955 var_name() {
4956         echo -n "$1" | tr -c '[:alnum:]\n' '_'
4957 }
4958
4959 mount_zfs() {
4960         local facet=$1
4961         local ds=$(facet_device $facet)
4962         local mnt=${2:-$(facet_mntpt $facet)}
4963         local canmnt
4964         local mntpt
4965
4966         import_zpool $facet
4967         canmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)
4968         mntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)
4969         do_facet $facet $ZFS set canmount=noauto $ds
4970         #
4971         # The "legacy" mount method is used here because "zfs unmount $mnt"
4972         # calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain
4973         # targets are not available at the time, the stat(2) on $MOUNT will
4974         # hang.
4975         #
4976         do_facet $facet $ZFS set mountpoint=legacy $ds
4977         do_facet $facet mount -t zfs $ds $mnt
4978         eval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt
4979         eval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt
4980 }
4981
4982 unmount_zfs() {
4983         local facet=$1
4984         local ds=$(facet_device $facet)
4985         local mnt=${2:-$(facet_mntpt $facet)}
4986         local var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint
4987         local var_canmnt=mz_$(var_name ${facet}_$ds)_canmount
4988         local mntpt=${!var_mntpt}
4989         local canmnt=${!var_canmnt}
4990
4991         unset $var_mntpt
4992         unset $var_canmnt
4993         do_facet $facet umount $mnt
4994         do_facet $facet $ZFS set mountpoint=$mntpt $ds
4995         do_facet $facet $ZFS set canmount=$canmnt $ds
4996         export_zpool $facet
4997 }
4998
4999 mount_fstype() {
5000         local facet=$1
5001         local mnt=$2
5002         local fstype=$(facet_fstype $facet)
5003
5004         mount_$fstype $facet $mnt
5005 }
5006
5007 unmount_fstype() {
5008         local facet=$1
5009         local mnt=$2
5010         local fstype=$(facet_fstype $facet)
5011
5012         unmount_$fstype $facet $mnt
5013 }
5014
5015 ########
5016 ## MountConf setup
5017
5018 stopall() {
5019         # make sure we are using the primary server, so test-framework will
5020         # be able to clean up properly.
5021         activemds=`facet_active mds1`
5022         if [ $activemds != "mds1" ]; then
5023                 fail mds1
5024         fi
5025
5026         local clients=$CLIENTS
5027         [ -z $clients ] && clients=$(hostname)
5028
5029         zconf_umount_clients $clients $MOUNT "$*" || true
5030         [ -n "$MOUNT2" ] && zconf_umount_clients $clients $MOUNT2 "$*" || true
5031
5032         [ -n "$CLIENTONLY" ] && return
5033
5034         # The add fn does rm ${facet}active file, this would be enough
5035         # if we use do_facet <facet> only after the facet added, but
5036         # currently we use do_facet mds in local.sh
5037         local num
5038         for num in `seq $MDSCOUNT`; do
5039                 stop mds$num -f
5040                 rm -f ${TMP}/mds${num}active
5041         done
5042         combined_mgs_mds && rm -f $TMP/mgsactive
5043
5044         for num in `seq $OSTCOUNT`; do
5045                 stop ost$num -f
5046                 rm -f $TMP/ost${num}active
5047         done
5048
5049         if ! combined_mgs_mds ; then
5050                 stop mgs
5051         fi
5052
5053         if $SHARED_KEY; then
5054                 export SK_MOUNTED=false
5055         fi
5056
5057         return 0
5058 }
5059
5060 cleanup_echo_devs () {
5061         trap 0
5062         local dev
5063         local devs=$($LCTL dl | grep echo | awk '{print $4}')
5064
5065         for dev in $devs; do
5066                 $LCTL --device $dev cleanup
5067                 $LCTL --device $dev detach
5068         done
5069 }
5070
5071 cleanupall() {
5072         nfs_client_mode && return
5073         cifs_client_mode && return
5074
5075         cleanup_echo_devs
5076         CLEANUP_DM_DEV=true stopall $*
5077
5078         unload_modules
5079         cleanup_sk
5080         cleanup_gss
5081 }
5082
5083 combined_mgs_mds () {
5084         [[ "$(mdsdevname 1)" = "$(mgsdevname)" ]] &&
5085                 [[ "$(facet_host mds1)" = "$(facet_host mgs)" ]]
5086 }
5087
5088 lower() {
5089         echo -n "$1" | tr '[:upper:]' '[:lower:]'
5090 }
5091
5092 upper() {
5093         echo -n "$1" | tr '[:lower:]' '[:upper:]'
5094 }
5095
5096 squash_opt() {
5097         local var="$*"
5098         local other=""
5099         local opt_o=""
5100         local opt_e=""
5101         local first_e=0
5102         local first_o=0
5103         local take=""
5104
5105         var=$(echo "$var" | sed -e 's/,\( \)*/,/g')
5106         for i in $(echo "$var"); do
5107                 if [ "$i" == "-O" ]; then
5108                         take="o";
5109                         first_o=$(($first_o + 1))
5110                         continue;
5111                 fi
5112                 if [ "$i" == "-E" ]; then
5113                         take="e";
5114                         first_e=$(($first_e + 1 ))
5115                         continue;
5116                 fi
5117                 case $take in
5118                         "o")
5119                                 [ $first_o -gt 1 ] && opt_o+=",";
5120                                 opt_o+="$i";
5121                                 ;;
5122                         "e")
5123                                 [ $first_e -gt 1 ] && opt_e+=",";
5124                                 opt_e+="$i";
5125                                 ;;
5126                         *)
5127                                 other+=" $i";
5128                                 ;;
5129                 esac
5130                 take=""
5131         done
5132
5133         echo -n "$other"
5134         [ -n "$opt_o" ] && echo " -O $opt_o"
5135         [ -n "$opt_e" ] && echo " -E $opt_e"
5136 }
5137
5138 mkfs_opts() {
5139         local facet=$1
5140         local dev=$2
5141         local fsname=${3:-"$FSNAME"}
5142         local type=$(facet_type $facet)
5143         local index=$(facet_index $facet)
5144         local fstype=$(facet_fstype $facet)
5145         local host=$(facet_host $facet)
5146         local opts
5147         local fs_mkfs_opts
5148         local var
5149         local varbs=${facet}_BLOCKSIZE
5150
5151         if [ $type == MGS ] || ( [ $type == MDS ] &&
5152                                  [ "$dev" == $(mgsdevname) ] &&
5153                                  [ "$host" == "$(facet_host mgs)" ] ); then
5154                 opts="--mgs"
5155         else
5156                 opts="--mgsnode=$MGSNID"
5157         fi
5158
5159         if [ $type != MGS ]; then
5160                 opts+=" --fsname=$fsname --$(lower ${type/MDS/MDT}) \
5161                         --index=$index"
5162         fi
5163
5164         var=${facet}failover_HOST
5165         if [ -n "${!var}" ] && [ ${!var} != $(facet_host $facet) ]; then
5166                 opts+=" --failnode=$(h2nettype ${!var})"
5167         fi
5168
5169         opts+=${TIMEOUT:+" --param=sys.timeout=$TIMEOUT"}
5170         opts+=${LDLM_TIMEOUT:+" --param=sys.ldlm_timeout=$LDLM_TIMEOUT"}
5171
5172         if [ $type == MDS ]; then
5173                 opts+=${DEF_STRIPE_SIZE:+" --param=lov.stripesize=$DEF_STRIPE_SIZE"}
5174                 opts+=${DEF_STRIPE_COUNT:+" --param=lov.stripecount=$DEF_STRIPE_COUNT"}
5175                 opts+=${L_GETIDENTITY:+" --param=mdt.identity_upcall=$L_GETIDENTITY"}
5176
5177                 if [ $fstype == ldiskfs ]; then
5178                         var=${facet}_JRN
5179                         if [ -n "${!var}" ]; then
5180                                 fs_mkfs_opts+=" -J device=${!var}"
5181                         else
5182                                 fs_mkfs_opts+=${MDSJOURNALSIZE:+" -J size=$MDSJOURNALSIZE"}
5183                         fi
5184                         fs_mkfs_opts+=${MDSISIZE:+" -i $MDSISIZE"}
5185                 fi
5186         fi
5187
5188         if [ $type == OST ]; then
5189                 if [ $fstype == ldiskfs ]; then
5190                         var=${facet}_JRN
5191                         if [ -n "${!var}" ]; then
5192                                 fs_mkfs_opts+=" -J device=${!var}"
5193                         else
5194                                 fs_mkfs_opts+=${OSTJOURNALSIZE:+" -J size=$OSTJOURNALSIZE"}
5195                         fi
5196                 fi
5197         fi
5198
5199         opts+=" --backfstype=$fstype"
5200
5201         var=${type}SIZE
5202         if [ -n "${!var}" ]; then
5203                 opts+=" --device-size=${!var}"
5204         fi
5205
5206         var=$(upper $fstype)_MKFS_OPTS
5207         fs_mkfs_opts+=${!var:+" ${!var}"}
5208
5209         var=${type}_FS_MKFS_OPTS
5210         fs_mkfs_opts+=${!var:+" ${!var}"}
5211
5212         [[ "$QUOTA_TYPE" =~ "p" ]] && fs_mkfs_opts+=" -O project"
5213
5214         [ $fstype == ldiskfs ] && fs_mkfs_opts+=" -b ${!varbs:-$BLCKSIZE}"
5215         [ $fstype == ldiskfs ] && fs_mkfs_opts=$(squash_opt $fs_mkfs_opts)
5216
5217         if [ -n "${fs_mkfs_opts## }" ]; then
5218                 opts+=" --mkfsoptions=\\\"${fs_mkfs_opts## }\\\""
5219         fi
5220
5221         var=${type}OPT
5222         opts+=${!var:+" ${!var}"}
5223
5224         echo -n "$opts"
5225 }
5226
5227 mountfs_opts() {
5228         local facet=$1
5229         local type=$(facet_type $facet)
5230         local var=${type}_MOUNT_FS_OPTS
5231         local opts=""
5232         if [ -n "${!var}" ]; then
5233                 opts+=" --mountfsoptions=${!var}"
5234         fi
5235         echo -n "$opts"
5236 }
5237
5238 check_ost_indices() {
5239         local index_count=${#OST_INDICES[@]}
5240         [[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0
5241
5242         # OST count is greater than the index count in $OST_INDEX_LIST.
5243         # We need check whether there are duplicate indices.
5244         local i
5245         local j
5246         local index
5247         for i in $(seq $((index_count + 1)) $OSTCOUNT); do
5248                 index=$(facet_index ost$i)
5249                 for j in $(seq 0 $((index_count - 1))); do
5250                         [[ $index -ne ${OST_INDICES[j]} ]] ||
5251                         error "ost$i has the same index $index as ost$((j+1))"
5252                 done
5253         done
5254 }
5255
5256 __touch_device()
5257 {
5258         local facet_type=$1 # mgs || mds || ost
5259         local facet_num=$2
5260         local facet=${1}${2}
5261         local device
5262
5263         case "$(facet_fstype $facet)" in
5264         ldiskfs)
5265                 device=$(${facet_type}devname $facet_num)
5266                 ;;
5267         zfs)
5268                 device=$(${facet_type}vdevname $facet_num)
5269                 ;;
5270         *)
5271                 error "Unhandled filesystem type"
5272                 ;;
5273         esac
5274
5275         do_facet $facet "[ -e \"$device\" ]" && return
5276
5277         # Note: the following check only works with absolute paths
5278         [[ ! "$device" =~ ^/dev/ ]] || [[ "$device" =~ ^/dev/shm/ ]] ||
5279                 error "$facet: device '$device' does not exist"
5280
5281         # zpool create doesn't like empty files
5282         [[ $(facet_fstype $facet) == zfs ]] && return 0
5283
5284         do_facet $facet "touch \"${device}\""
5285 }
5286
5287 format_mgs() {
5288         local quiet
5289
5290         if ! $VERBOSE; then
5291                 quiet=yes
5292         fi
5293         echo "Format mgs: $(mgsdevname)"
5294         reformat_external_journal mgs
5295
5296         # touch "device" in case it is a loopback file for testing and needs to
5297         # be created. mkfs.lustre doesn't do this to avoid accidentally writing
5298         # to non-existent files in /dev if the admin made a typo during setup
5299         __touch_device mgs
5300
5301         add mgs $(mkfs_opts mgs $(mgsdevname)) $(mountfs_opts mgs) --reformat \
5302                 $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10
5303 }
5304
5305 format_mdt() {
5306         local num=$1
5307         local quiet
5308
5309         if ! $VERBOSE; then
5310                 quiet=yes
5311         fi
5312         echo "Format mds$num: $(mdsdevname $num)"
5313         reformat_external_journal mds$num
5314
5315         __touch_device mds $num
5316
5317         add mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \
5318                 $(mountfs_opts mds$num) --reformat $(mdsdevname $num) \
5319                 $(mdsvdevname $num) ${quiet:+>/dev/null} || exit 10
5320 }
5321
5322 format_ost() {
5323         local num=$1
5324
5325         if ! $VERBOSE; then
5326                 quiet=yes
5327         fi
5328         echo "Format ost$num: $(ostdevname $num)"
5329         reformat_external_journal ost$num
5330
5331         __touch_device ost $num
5332
5333         add ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \
5334                 $(mountfs_opts ost$num) --reformat $(ostdevname $num) \
5335                 $(ostvdevname ${num}) ${quiet:+>/dev/null} || exit 10
5336 }
5337
5338 formatall() {
5339         stopall -f
5340         # Set hostid for ZFS/SPL zpool import protection
5341         # (Assumes MDS version is also OSS version)
5342         if [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.8.54) ];
5343         then
5344                 do_rpc_nodes "$(comma_list $(all_server_nodes))" set_hostid
5345         fi
5346
5347         # We need ldiskfs here, may as well load them all
5348         load_modules
5349         [ -n "$CLIENTONLY" ] && return
5350         echo Formatting mgs, mds, osts
5351         if ! combined_mgs_mds ; then
5352                 format_mgs
5353         fi
5354
5355         for num in $(seq $MDSCOUNT); do
5356                 format_mdt $num
5357         done
5358
5359         export OST_INDICES=($(hostlist_expand "$OST_INDEX_LIST"))
5360         check_ost_indices
5361         for num in $(seq $OSTCOUNT); do
5362                 format_ost $num
5363         done
5364 }
5365
5366 mount_client() {
5367         grep " $1 " /proc/mounts || zconf_mount $HOSTNAME $*
5368 }
5369
5370 umount_client() {
5371         grep " $1 " /proc/mounts && zconf_umount $HOSTNAME $*
5372 }
5373
5374 # usage: switch_identity MDSNUM ENABLE_UPCALL
5375 #
5376 # return values:
5377 # 0: success, the identity upcall was previously enabled already.
5378 # 1: success, the identity upcall was previously disabled.
5379 # 2: fail.
5380 switch_identity() {
5381         local num=$1
5382         local enable=$2
5383         local facet=mds$num
5384         local MDT="$(mdtname_from_index $((num - 1)) $MOUNT)"
5385         local upcall="$L_GETIDENTITY"
5386
5387         [[ -n "$MDT" ]] || return 2
5388
5389         local param="mdt.$MDT.identity_upcall"
5390         local old="$(do_facet $facet "lctl get_param -n $param")"
5391
5392         [[ "$enable" == "true" ]] || upcall="NONE"
5393
5394         do_facet $facet "lctl set_param -n $param='$upcall'" || return 2
5395         do_facet $facet "lctl set_param -n mdt.$MDT.identity_flush=-1"
5396
5397         [[ "$old" != "NONE" ]] # implicit "&& return 0 || return 1"
5398 }
5399
5400 remount_client()
5401 {
5402         zconf_umount $HOSTNAME $1 || error "umount failed"
5403         zconf_mount $HOSTNAME $1 || error "mount failed"
5404 }
5405
5406 writeconf_facet() {
5407         local facet=$1
5408         local dev=$2
5409
5410         stop ${facet} -f
5411         rm -f $TMP/${facet}active
5412         do_facet ${facet} "$TUNEFS --quiet --writeconf $dev" || return 1
5413         return 0
5414 }
5415
5416 writeconf_all () {
5417         local mdt_count=${1:-$MDSCOUNT}
5418         local ost_count=${2:-$OSTCOUNT}
5419         local rc=0
5420
5421         for num in $(seq $mdt_count); do
5422                 DEVNAME=$(mdsdevname $num)
5423                 writeconf_facet mds$num $DEVNAME || rc=$?
5424         done
5425
5426         for num in $(seq $ost_count); do
5427                 DEVNAME=$(ostdevname $num)
5428                 writeconf_facet ost$num $DEVNAME || rc=$?
5429         done
5430         return $rc
5431 }
5432
5433 mountmgs() {
5434         if ! combined_mgs_mds ; then
5435                 start mgs $(mgsdevname) $MGS_MOUNT_OPTS
5436         fi
5437 }
5438
5439 mountmds() {
5440         local num
5441         local devname
5442         local host
5443         local varname
5444         for num in $(seq $MDSCOUNT); do
5445                 devname=$(mdsdevname $num)
5446                 start mds$num $devname $MDS_MOUNT_OPTS
5447
5448                 # We started mds$num, now we should set mds${num}_HOST
5449                 # and mds${num}failover_HOST variables properly if they
5450                 # are not set.
5451                 host=$(facet_host mds$num)
5452                 for varname in mds${num}_HOST mds${num}failover_HOST; do
5453                         if [[ -z "${!varname}" ]]; then
5454                                 eval $varname=$host
5455                         fi
5456                 done
5457                 if [[ "$IDENTITY_UPCALL" != "default" ]]; then
5458                         switch_identity $num $IDENTITY_UPCALL
5459                 fi
5460         done
5461 }
5462
5463 unmountoss() {
5464         local num
5465
5466         for num in $(seq $OSTCOUNT); do
5467                 stop ost$num -f
5468                 rm -f $TMP/ost${num}active
5469         done
5470 }
5471
5472 mountoss() {
5473         local num
5474         local devname
5475         local host
5476         local varname
5477         for num in $(seq $OSTCOUNT); do
5478                 devname=$(ostdevname $num)
5479                 start ost$num $devname $OST_MOUNT_OPTS
5480
5481                 # We started ost$num, now we should set ost${num}_HOST
5482                 # and ost${num}failover_HOST variables properly if they
5483                 # are not set.
5484                 host=$(facet_host ost$num)
5485                 for varname in ost${num}_HOST ost${num}failover_HOST; do
5486                         if [[ -z "${!varname}" ]]; then
5487                                 eval $varname=$host
5488                         fi
5489                 done
5490         done
5491 }
5492
5493 mountcli() {
5494         [ "$DAEMONFILE" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE
5495         if [ ! -z $arg1 ]; then
5496                 [ "$arg1" = "server_only" ] && return
5497         fi
5498         mount_client $MOUNT
5499         if [ -n "$CLIENTS" ]; then
5500                 zconf_mount_clients $CLIENTS $MOUNT
5501         fi
5502         clients_up
5503
5504         if [ "$MOUNT_2" ]; then
5505                 mount_client $MOUNT2
5506                 if [ -n "$CLIENTS" ]; then
5507                         zconf_mount_clients $CLIENTS $MOUNT2
5508                 fi
5509         fi
5510 }
5511
5512 sk_nodemap_setup() {
5513         local sk_map_name=${1:-$SK_S2SNM}
5514         local sk_map_nodes=${2:-$HOSTNAME}
5515         do_node $(mgs_node) "$LCTL nodemap_add $sk_map_name"
5516         for servernode in $sk_map_nodes; do
5517                 local nids=$(do_nodes $servernode "$LCTL list_nids")
5518                 for nid in $nids; do
5519                         do_node $(mgs_node) "$LCTL nodemap_add_range --name \
5520                                 $sk_map_name --range $nid"
5521                 done
5522         done
5523 }
5524
5525 setupall() {
5526         local arg1=$1
5527
5528         nfs_client_mode && return
5529         cifs_client_mode && return
5530
5531         sanity_mount_check || error "environments are insane!"
5532
5533         load_modules
5534
5535         init_gss
5536
5537         if [ -z "$CLIENTONLY" ]; then
5538                 echo Setup mgs, mdt, osts
5539                 echo $WRITECONF | grep -q "writeconf" && writeconf_all
5540
5541                 if $SK_MOUNTED; then
5542                         echo "Shared Key file system already mounted"
5543                 else
5544                         mountmgs
5545                         mountmds
5546                         mountoss
5547                         if $SHARED_KEY; then
5548                                 export SK_MOUNTED=true
5549                         fi
5550                 fi
5551                 if $GSS_SK; then
5552                         echo "GSS_SK: setting kernel keyring perms"
5553                         do_nodes $(comma_list $(all_nodes)) \
5554                                 "keyctl show | grep lustre | cut -c1-11 |
5555                                 sed -e 's/ //g;' |
5556                                 xargs -IX keyctl setperm X 0x3f3f3f3f"
5557
5558                         if $SK_S2S; then
5559                                 # Need to start one nodemap for servers,
5560                                 # and one for clients.
5561                                 sk_nodemap_setup $SK_S2SNM \
5562                                         $(comma_list $(all_server_nodes))
5563                                 mountcli
5564                                 sk_nodemap_setup $SK_S2SNMCLI \
5565                                         ${CLIENTS:-$HOSTNAME}
5566                                 echo "Nodemap set up for SK S2S, remounting."
5567                                 stopall
5568                                 mountmgs
5569                                 mountmds
5570                                 mountoss
5571                         fi
5572                 fi
5573         fi
5574
5575         # wait a while to allow sptlrpc configuration be propogated to targets,
5576         # only needed when mounting new target devices.
5577         if $GSS; then
5578                 sleep 10
5579         fi
5580
5581         mountcli
5582         init_param_vars
5583
5584         # by remounting mdt before ost, initial connect from mdt to ost might
5585         # timeout because ost is not ready yet. wait some time to its fully
5586         # recovery. initial obd_connect timeout is 5s; in GSS case it's
5587         # preceeded by a context negotiation rpc with $TIMEOUT.
5588         # FIXME better by monitoring import status.
5589         if $GSS; then
5590                 if $GSS_SK; then
5591                         set_rule $FSNAME any cli2mdt $SK_FLAVOR
5592                         set_rule $FSNAME any cli2ost $SK_FLAVOR
5593                         if $SK_SKIPFIRST; then
5594                                 export SK_SKIPFIRST=false
5595
5596                                 sleep 30
5597                                 do_nodes $CLIENTS \
5598                                          "lctl set_param osc.*.idle_connect=1"
5599                                 return
5600                         else
5601                                 wait_flavor cli2mdt $SK_FLAVOR
5602                                 wait_flavor cli2ost $SK_FLAVOR
5603                         fi
5604                 else
5605                         set_flavor_all $SEC
5606                 fi
5607                 sleep $((TIMEOUT + 5))
5608         else
5609                 sleep 5
5610         fi
5611 }
5612
5613 mounted_lustre_filesystems() {
5614         awk '($3 ~ "lustre" && $1 ~ ":") { print $2 }' /proc/mounts
5615 }
5616
5617 init_facet_vars () {
5618         [ -n "$CLIENTONLY" ] && return 0
5619         local facet=$1
5620         shift
5621         local device=$1
5622
5623         shift
5624
5625         eval export ${facet}_dev=${device}
5626         eval export ${facet}_opt=\"$*\"
5627
5628         local dev=${facet}_dev
5629
5630         # We need to loop for the label
5631         # in case its not initialized yet.
5632         for wait_time in {0,1,3,5,10}; do
5633
5634                 if [ $wait_time -gt 0 ]; then
5635                         echo "${!dev} not yet initialized,"\
5636                                 "waiting ${wait_time} seconds."
5637                         sleep $wait_time
5638                 fi
5639
5640                 local label=$(devicelabel ${facet} ${!dev})
5641
5642                 # Check to make sure the label does
5643                 # not include ffff at the end of the label.
5644                 # This indicates it has not been initialized yet.
5645
5646                 if [[ $label =~ [f|F]{4}$ ]]; then
5647                         # label is not initialized, unset the result
5648                         # and either try again or fail
5649                         unset label
5650                 else
5651                         break
5652                 fi
5653         done
5654
5655         [ -z "$label" ] && echo no label for ${!dev} && exit 1
5656
5657         eval export ${facet}_svc=${label}
5658
5659         local varname=${facet}failover_HOST
5660         if [ -z "${!varname}" ]; then
5661                 local temp
5662                 if combined_mgs_mds && [ $facet == "mgs" ] &&
5663                    [ -n "$mds1failover_HOST" ]; then
5664                         temp=$mds1failover_HOST
5665                 else
5666                         temp=$(facet_host $facet)
5667                 fi
5668                 eval export $varname=$temp
5669         fi
5670
5671         varname=${facet}_HOST
5672         if [ -z "${!varname}" ]; then
5673                 eval export $varname=$(facet_host $facet)
5674         fi
5675
5676         # ${facet}failover_dev is set in cfg file
5677         varname=${facet}failover_dev
5678         if [ -n "${!varname}" ] ; then
5679                 eval export ${facet}failover_dev=${!varname}
5680         else
5681                 eval export ${facet}failover_dev=$device
5682         fi
5683
5684         # get mount point of already mounted device
5685         # is facet_dev is already mounted then use the real
5686         #  mount point of this facet; otherwise use $(facet_mntpt $facet)
5687         # i.e. ${facet}_MOUNT if specified by user or default
5688         local mntpt=$(do_facet ${facet} cat /proc/mounts | \
5689                         awk '"'${!dev}'" == $1 && $3 == "lustre" { print $2 }')
5690         if [ -z $mntpt ]; then
5691                 mntpt=$(facet_mntpt $facet)
5692         fi
5693         eval export ${facet}_MOUNT=$mntpt
5694 }
5695
5696 init_facets_vars () {
5697         local DEVNAME
5698
5699         if ! remote_mds_nodsh; then
5700                 for num in $(seq $MDSCOUNT); do
5701                         DEVNAME=$(mdsdevname $num)
5702                         init_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS
5703                 done
5704         fi
5705
5706         init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS
5707
5708         if ! remote_ost_nodsh; then
5709                 for num in $(seq $OSTCOUNT); do
5710                         DEVNAME=$(ostdevname $num)
5711                         init_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS
5712                 done
5713         fi
5714 }
5715
5716 init_facets_vars_simple () {
5717         local devname
5718
5719         if ! remote_mds_nodsh; then
5720                 for num in $(seq $MDSCOUNT); do
5721                         devname=$(mdsdevname $num)
5722                         eval export mds${num}_dev=${devname}
5723                         eval export mds${num}_opt=\"${MDS_MOUNT_OPTS}\"
5724                 done
5725         fi
5726
5727         if ! combined_mgs_mds ; then
5728                 eval export mgs_dev=$(mgsdevname)
5729                 eval export mgs_opt=\"${MGS_MOUNT_OPTS}\"
5730         fi
5731
5732         if ! remote_ost_nodsh; then
5733                 for num in $(seq $OSTCOUNT); do
5734                         devname=$(ostdevname $num)
5735                         eval export ost${num}_dev=${devname}
5736                         eval export ost${num}_opt=\"${OST_MOUNT_OPTS}\"
5737                 done
5738         fi
5739 }
5740
5741 osc_ensure_active () {
5742         local facet=$1
5743         local timeout=$2
5744         local period=0
5745
5746         while [ $period -lt $timeout ]; do
5747                 count=$(do_facet $facet "lctl dl | grep ' IN osc ' 2>/dev/null | wc -l")
5748                 if [ $count -eq 0 ]; then
5749                         break
5750                 fi
5751
5752                 echo "$count OST inactive, wait $period seconds, and try again"
5753                 sleep 3
5754                 period=$((period+3))
5755         done
5756
5757         [ $period -lt $timeout ] ||
5758                 log "$count OST are inactive after $timeout seconds, give up"
5759 }
5760
5761 set_conf_param_and_check() {
5762         local myfacet=$1
5763         local TEST=$2
5764         local PARAM=$3
5765         local ORIG=$(do_facet $myfacet "$TEST")
5766         if [ $# -gt 3 ]; then
5767                 local FINAL=$4
5768         else
5769                 local -i FINAL
5770                 FINAL=$((ORIG + 5))
5771         fi
5772         echo "Setting $PARAM from $ORIG to $FINAL"
5773         do_facet mgs "$LCTL conf_param $PARAM='$FINAL'" ||
5774                 error "conf_param $PARAM failed"
5775
5776         wait_update_facet $myfacet "$TEST" "$FINAL" ||
5777                 error "check $PARAM failed!"
5778 }
5779
5780 set_persistent_param() {
5781         local myfacet=$1
5782         local test_param=$2
5783         local param=$3
5784         local orig=$(do_facet $myfacet "$LCTL get_param -n $test_param")
5785
5786         if [ $# -gt 3 ]; then
5787                 local final=$4
5788         else
5789                 local -i final
5790                 final=$((orig + 5))
5791         fi
5792
5793         if [[ $PERM_CMD == *"set_param -P"* ]]; then
5794                 echo "Setting $test_param from $orig to $final"
5795                 do_facet mgs "$PERM_CMD $test_param='$final'" ||
5796                         error "$PERM_CMD $test_param failed"
5797         else
5798                 echo "Setting $param from $orig to $final"
5799                 do_facet mgs "$PERM_CMD $param='$final'" ||
5800                         error "$PERM_CMD $param failed"
5801         fi
5802 }
5803
5804 set_persistent_param_and_check() {
5805         local myfacet=$1
5806         local test_param=$2
5807         local param=$3
5808         local orig=$(do_facet $myfacet "$LCTL get_param -n $test_param")
5809
5810         if [ $# -gt 3 ]; then
5811                 local final=$4
5812         else
5813                 local -i final
5814                 final=$((orig + 5))
5815         fi
5816
5817         set_persistent_param $myfacet $test_param $param "$final"
5818
5819         wait_update_facet $myfacet "$LCTL get_param -n $test_param" "$final" ||
5820                 error "check $param failed!"
5821 }
5822
5823 init_param_vars () {
5824         TIMEOUT=$(lctl get_param -n timeout)
5825         TIMEOUT=${TIMEOUT:-20}
5826
5827         if [ -n "$arg1" ]; then
5828                 [ "$arg1" = "server_only" ] && return
5829         fi
5830
5831         remote_mds_nodsh && log "Using TIMEOUT=$TIMEOUT" && return 0
5832
5833         TIMEOUT=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
5834         log "Using TIMEOUT=$TIMEOUT"
5835
5836         # tune down to speed up testing on (usually) small setups
5837         local mgc_timeout=/sys/module/mgc/parameters/mgc_requeue_timeout_min
5838         do_nodes $(comma_list $(nodes_list)) \
5839                 "[ -f $mgc_timeout ] && echo 1 > $mgc_timeout; exit 0"
5840
5841         osc_ensure_active $SINGLEMDS $TIMEOUT
5842         osc_ensure_active client $TIMEOUT
5843         $LCTL set_param osc.*.idle_timeout=debug
5844
5845         if [ -n "$(lctl get_param -n mdc.*.connect_flags|grep jobstats)" ]; then
5846                 local current_jobid_var=$($LCTL get_param -n jobid_var)
5847
5848                 if [ $JOBID_VAR = "existing" ]; then
5849                         echo "keeping jobstats as $current_jobid_var"
5850                 elif [ $current_jobid_var != $JOBID_VAR ]; then
5851                         echo "setting jobstats to $JOBID_VAR"
5852
5853                         set_persistent_param_and_check client \
5854                                 "jobid_var" "$FSNAME.sys.jobid_var" $JOBID_VAR
5855                 fi
5856         else
5857                 echo "jobstats not supported by server"
5858         fi
5859
5860         if [ $QUOTA_AUTO -ne 0 ]; then
5861                 if [ "$ENABLE_QUOTA" ]; then
5862                         echo "enable quota as required"
5863                         setup_quota $MOUNT || return 2
5864                 else
5865                         echo "disable quota as required"
5866                         # $LFS quotaoff -ug $MOUNT > /dev/null 2>&1
5867                 fi
5868         fi
5869
5870         (( MDS1_VERSION <= $(version_code 2.13.52) )) ||
5871                 do_facet mgs "$LCTL set_param -P lod.*.mdt_hash=crush"
5872         return 0
5873 }
5874
5875 nfs_client_mode () {
5876         if [ "$NFSCLIENT" ]; then
5877                 echo "NFSCLIENT mode: setup, cleanup, check config skipped"
5878                 local clients=$CLIENTS
5879
5880                 [ -z $clients ] && clients=$(hostname)
5881
5882                 # FIXME: remove hostname when 19215 fixed
5883                 do_nodes $clients "echo \\\$(hostname); grep ' '$MOUNT' ' /proc/mounts"
5884                 declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts |
5885                         awk '{print $1}' | awk -F: '{print $1 " "  $2}'`)
5886                 if [[ ${#nfsexport[@]} -eq 0 ]]; then
5887                         error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!
5888                 fi
5889                 do_nodes ${nfsexport[0]} "echo \\\$(hostname); df -T  ${nfsexport[1]}"
5890                 return
5891         fi
5892         return 1
5893 }
5894
5895 cifs_client_mode () {
5896         [ x$CIFSCLIENT = xyes ] &&
5897                 echo "CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped"
5898 }
5899
5900 check_config_client () {
5901         local mntpt=$1
5902         local mounted=$(mount | grep " $mntpt ")
5903
5904         if [ -n "$CLIENTONLY" ]; then
5905                 # bug 18021
5906                 # CLIENTONLY should not depend on *_HOST settings
5907                 local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')
5908                 # in theory someone could create a new,
5909                 # client-only config file that assumed lustre was already
5910                 # configured and didn't set the MGSNID. If MGSNID is not set,
5911                 # then we should use the mgs nid currently being used
5912                 # as the default value. bug 18021
5913                 [[ x$MGSNID = x ]] &&
5914                 MGSNID=${mgc//MGC/}
5915
5916                 if [[ x$mgc != xMGC$MGSNID ]]; then
5917                         if [ "$mgs_HOST" ]; then
5918                                 local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST |
5919                                         grep PING | awk '{print $3}' |
5920                                         sed -e "s/(//g" -e "s/)//g")
5921
5922                                 # [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||
5923                                 # error_exit "MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc"
5924                         fi
5925                 fi
5926                 return 0
5927         fi
5928
5929         echo Checking config lustre mounted on $mntpt
5930         local mgshost=$(mount | grep " $mntpt " | awk -F@ '{print $1}')
5931         mgshost=$(echo $mgshost | awk -F: '{print $1}')
5932
5933 }
5934
5935 check_config_clients () {
5936         local clients=${CLIENTS:-$HOSTNAME}
5937         local mntpt=$1
5938
5939         nfs_client_mode && return
5940         cifs_client_mode && return
5941
5942         do_rpc_nodes "$clients" check_config_client $mntpt
5943
5944         sanity_mount_check || error "environments are insane!"
5945 }
5946
5947 check_timeout () {
5948         local mdstimeout=$(do_facet $SINGLEMDS "lctl get_param -n timeout")
5949         local cltimeout=$(lctl get_param -n timeout)
5950         if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then
5951                 error "timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT"
5952                 return 1
5953         fi
5954 }
5955
5956 is_mounted () {
5957         local mntpt=$1
5958         [ -z $mntpt ] && return 1
5959         local mounted=$(mounted_lustre_filesystems)
5960
5961         echo $mounted' ' | grep -w -q $mntpt' '
5962 }
5963
5964 create_pools () {
5965         local pool=$1
5966         local ostsn=${2:-$OSTCOUNT}
5967         local npools=${FS_NPOOLS:-$((OSTCOUNT / ostsn))}
5968         local n
5969
5970         echo ostsn=$ostsn npools=$npools
5971         if [[ $ostsn -gt $OSTCOUNT ]];  then
5972                 echo "request to use $ostsn OSTs in the pool, \
5973                         using max available OSTCOUNT=$OSTCOUNT"
5974                 ostsn=$OSTCOUNT
5975         fi
5976         for (( n=0; n < $npools; n++ )); do
5977                 p=${pool}$n
5978                 if ! $DELETE_OLD_POOLS; then
5979                         log "request to not delete old pools: $FSNAME.$p exist?"
5980                         if ! check_pool_not_exist $FSNAME.$p; then
5981                                 echo "Using existing $FSNAME.$p"
5982                                 $LCTL pool_list $FSNAME.$p
5983                                 continue
5984                         fi
5985                 fi
5986                 create_pool $FSNAME.$p $KEEP_POOLS ||
5987                         error "create_pool $FSNAME.$p failed"
5988
5989                 local first=$(( (n * ostsn) % OSTCOUNT ))
5990                 local last=$(( (first + ostsn - 1) % OSTCOUNT ))
5991                 if [[ $first -le $last ]]; then
5992                         pool_add_targets $p $first $last ||
5993                                 error "pool_add_targets $p $first $last failed"
5994                 else
5995                         pool_add_targets $p $first $(( OSTCOUNT - 1 )) ||
5996                                 error "pool_add_targets $p $first \
5997                                         $(( OSTCOUNT - 1 )) failed"
5998                         pool_add_targets $p 0 $last ||
5999                                 error "pool_add_targets $p 0 $last failed"
6000                 fi
6001         done
6002 }
6003
6004 set_pools_quota () {
6005         local u
6006         local o
6007         local p
6008         local i
6009         local j
6010
6011         [[ $ENABLE_QUOTA ]] || error "Required Pool Quotas: \
6012                 $POOLS_QUOTA_USERS_SET, but ENABLE_QUOTA not set!"
6013
6014         # POOLS_QUOTA_USERS_SET=
6015         #              "quota15_1:20M          -- for all of the found pools
6016         #               quota15_2:1G:gpool0
6017         #               quota15_3              -- for global limit only
6018         #               quota15_4:200M:gpool0
6019         #               quota15_4:200M:gpool1"
6020
6021         declare -a pq_userset=(${POOLS_QUOTA_USERS_SET="mpiuser"})
6022         declare -a pq_users
6023         declare -A pq_limits
6024
6025         for ((i=0; i<${#pq_userset[@]}; i++)); do
6026                 u=${pq_userset[i]%%:*}
6027                 o=""
6028                 # user gets no pool limits if
6029                 # POOLS_QUOTA_USERS_SET does not specify it
6030                 [[ ${pq_userset[i]} =~ : ]] && o=${pq_userset[i]##$u:}
6031                 pq_limits[$u]+=" $o"
6032         done
6033         pq_users=(${!pq_limits[@]})
6034
6035         declare -a opts
6036         local pool
6037
6038         for ((i=0; i<${#pq_users[@]}; i++)); do
6039                 u=${pq_users[i]}
6040                 # set to max limit (_u64)
6041                 $LFS setquota -u $u -B $((2**24 - 1))T $DIR
6042                 opts=(${pq_limits[$u]})
6043                 for ((j=0; j<${#opts[@]}; j++)); do
6044                         p=${opts[j]##*:}
6045                         o=${opts[j]%%:*}
6046                         # Set limit for all existing pools if
6047                         # no pool specified
6048                         if [ $p == $o ];  then
6049                                 p=$(list_pool $FSNAME | sed "s/$FSNAME.//")
6050                                 echo "No pool specified for $u,
6051                                         set limit $o for all existing pools"
6052                         fi
6053                         for pool in $p; do
6054                                 $LFS setquota -u $u -B $o --pool $pool $DIR ||
6055                                         error "setquota -u $u -B $o \
6056                                                 --pool $pool failed"
6057                         done
6058                 done
6059                 $LFS quota -uv $u --pool  $DIR
6060         done
6061 }
6062
6063 do_check_and_setup_lustre() {
6064         # If auster does not want us to setup, then don't.
6065         ! ${do_setup} && return
6066
6067         echo "=== $TESTSUITE: start setup $(date +'%H:%M:%S (%s)') ==="
6068
6069         sanitize_parameters
6070         nfs_client_mode && return
6071         cifs_client_mode && return
6072
6073         local MOUNTED=$(mounted_lustre_filesystems)
6074
6075         local do_check=true
6076         # 1.
6077         # both MOUNT and MOUNT2 are not mounted
6078         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
6079                 [ "$REFORMAT" = "yes" ] && CLEANUP_DM_DEV=true formatall
6080                 # setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)
6081                 setupall
6082                 is_mounted $MOUNT || error "NAME=$NAME not mounted"
6083                 export I_MOUNTED=yes
6084                 do_check=false
6085         # 2.
6086         # MOUNT2 is mounted
6087         elif is_mounted $MOUNT2; then
6088                 # 3.
6089                 # MOUNT2 is mounted, while MOUNT_2 is not set
6090                 if ! [ "$MOUNT_2" ]; then
6091                         cleanup_mount $MOUNT2
6092                         export I_UMOUNTED2=yes
6093
6094                 # 4.
6095                 # MOUNT2 is mounted, MOUNT_2 is set
6096                 else
6097                         # FIXME: what to do if check_config failed?
6098                         # i.e. if:
6099                         # 1) remote client has mounted other Lustre fs ?
6100                         # 2) it has insane env ?
6101                         # try to umount MOUNT2 on all clients and mount again:
6102                         if ! check_config_clients $MOUNT2; then
6103                                 cleanup_mount $MOUNT2
6104                                 restore_mount $MOUNT2
6105                                 export I_MOUNTED2=yes
6106                         fi
6107                 fi
6108         # 5.
6109         # MOUNT is mounted MOUNT2 is not mounted
6110         elif [ "$MOUNT_2" ]; then
6111                 restore_mount $MOUNT2
6112                 export I_MOUNTED2=yes
6113         fi
6114
6115         if $do_check; then
6116                 # FIXME: what to do if check_config failed?
6117                 # i.e. if:
6118                 # 1) remote client has mounted other Lustre fs?
6119                 # 2) lustre is mounted on remote_clients atall ?
6120                 check_config_clients $MOUNT
6121                 init_facets_vars
6122                 init_param_vars
6123
6124                 set_default_debug_nodes $(comma_list $(nodes_list))
6125                 set_params_clients
6126         fi
6127
6128         if [ -z "$CLIENTONLY" -a $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ]; then
6129                 local facets=""
6130                 [ "$(facet_fstype ost1)" = "ldiskfs" ] &&
6131                         facets="$(get_facets OST)"
6132                 [ "$(facet_fstype mds1)" = "ldiskfs" ] &&
6133                         facets="$facets,$(get_facets MDS)"
6134                 [ "$(facet_fstype mgs)" = "ldiskfs" ] &&
6135                         facets="$facets,mgs"
6136                 local nodes="$(facets_hosts ${facets})"
6137                 if [ -n "$nodes" ] ; then
6138                         do_nodes $nodes "$LCTL set_param \
6139                                  osd-ldiskfs.track_declares_assert=1 || true"
6140                 fi
6141         fi
6142
6143         if [ -n "$fs_STRIPEPARAMS" ]; then
6144                 setstripe_getstripe $MOUNT $fs_STRIPEPARAMS
6145         fi
6146
6147         if $GSS_SK; then
6148                 set_flavor_all null
6149         elif $GSS; then
6150                 set_flavor_all $SEC
6151         fi
6152
6153         if $DELETE_OLD_POOLS; then
6154                 destroy_all_pools
6155         fi
6156
6157         if [[ -n "$FS_POOL" ]]; then
6158                 create_pools $FS_POOL $FS_POOL_NOSTS
6159         fi
6160
6161         if [[ -n "$POOLS_QUOTA_USERS_SET" ]]; then
6162                 set_pools_quota
6163         fi
6164
6165         # set tunable parameters passed to test environment
6166         set_params_clients
6167         set_params_mdts
6168         set_params_osts
6169         echo "=== $TESTSUITE: finish setup $(date +'%H:%M:%S (%s)') ==="
6170
6171         if [[ "$ONLY" == "setup" ]]; then
6172                 exit 0
6173         fi
6174 }
6175
6176 check_and_setup_lustre() {
6177         local start_stamp=$(date +%s)
6178         local saved_umask=$(umask)
6179         local log=$TESTLOG_PREFIX.test_setup.test_log.$(hostname -s).log
6180         local status='PASS'
6181         local stop_stamp=0
6182         local duration=0
6183         local error=''
6184         local rc=0
6185
6186         umask 0022
6187
6188         log_sub_test_begin test_setup
6189
6190         if ! do_check_and_setup_lustre 2>&1 > >(tee -i $log); then
6191                 error=$(tail -1 $log)
6192                 status='FAIL'
6193                 rc=1
6194         fi
6195
6196         stop_stamp=$(date +%s)
6197         duration=$((stop_stamp - start_stamp))
6198
6199         log_sub_test_end "$status" "$duration" "$rc" "$error"
6200
6201         umask $saved_umask
6202
6203         return $rc
6204 }
6205
6206 restore_mount () {
6207         local clients=${CLIENTS:-$HOSTNAME}
6208         local mntpt=$1
6209
6210         zconf_mount_clients $clients $mntpt
6211 }
6212
6213 cleanup_mount () {
6214         local clients=${CLIENTS:-$HOSTNAME}
6215         local mntpt=$1
6216
6217         zconf_umount_clients $clients $mntpt
6218 }
6219
6220 cleanup_and_setup_lustre() {
6221         if [[ "$ONLY" == "cleanup" ]] || grep -q "$MOUNT" /proc/mounts; then
6222                 lctl set_param debug=0 || true
6223                 cleanupall
6224
6225                 if [[ "$ONLY" == "cleanup" ]]; then
6226                         exit 0
6227                 fi
6228         fi
6229
6230         do_check_and_setup_lustre
6231 }
6232
6233 # Run e2fsck on MDT or OST device.
6234 run_e2fsck() {
6235         local node=$1
6236         local target_dev=$2
6237         local extra_opts=$3
6238         local cmd="$E2FSCK -d -v -t -t -f $extra_opts $target_dev"
6239         local log=$TMP/e2fsck.log
6240         local rc=0
6241
6242         # turn on pfsck if it is supported
6243         do_node $node $E2FSCK -h 2>&1 | grep -qw -- -m && cmd+=" -m8"
6244         echo $cmd
6245         do_node $node $cmd 2>&1 | tee $log
6246         rc=${PIPESTATUS[0]}
6247         if [ -n "$(grep "DNE mode isn't supported" $log)" ]; then
6248                 rm -f $log
6249                 if [ $MDSCOUNT -gt 1 ]; then
6250                         skip_noexit "DNE mode isn't supported!"
6251                         cleanupall
6252                         exit_status
6253                 else
6254                         error "It's not DNE mode."
6255                 fi
6256         fi
6257         rm -f $log
6258
6259         [ $rc -le $FSCK_MAX_ERR ] ||
6260                 error "$cmd returned $rc, should be <= $FSCK_MAX_ERR"
6261
6262         return 0
6263 }
6264
6265 #
6266 # Run resize2fs on MDT or OST device.
6267 #
6268 run_resize2fs() {
6269         local facet=$1
6270         local device=$2
6271         local size=$3
6272         shift 3
6273         local opts="$@"
6274
6275         do_facet $facet "$RESIZE2FS $opts $device $size"
6276 }
6277
6278 # verify a directory is shared among nodes.
6279 check_shared_dir() {
6280         local dir=$1
6281         local list=${2:-$(comma_list $(nodes_list))}
6282
6283         [ -z "$dir" ] && return 1
6284         do_rpc_nodes "$list" check_logdir $dir
6285         check_write_access $dir "$list" || return 1
6286         return 0
6287 }
6288
6289 run_lfsck() {
6290         do_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \
6291                 $LCTL set_param printk=+lfsck
6292         do_facet $SINGLEMDS "$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all"
6293
6294         for k in $(seq $MDSCOUNT); do
6295                 # wait up to 10+1 minutes for LFSCK to complete
6296                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
6297                         mdd.$(facet_svc mds${k}).lfsck_layout |
6298                         awk '/^status/ { print \\\$2 }'" "completed" 600 ||
6299                         error "MDS${k} layout isn't the expected 'completed'"
6300                 wait_update_facet --verbose mds${k} "$LCTL get_param -n \
6301                         mdd.$(facet_svc mds${k}).lfsck_namespace |
6302                         awk '/^status/ { print \\\$2 }'" "completed" 60 ||
6303                         error "MDS${k} namespace isn't the expected 'completed'"
6304         done
6305         local rep_mdt=$(do_nodes $(comma_list $(mdts_nodes)) \
6306                         $LCTL get_param -n mdd.$FSNAME-*.lfsck_* |
6307                         awk '/repaired/ { print $2 }' | calc_sum)
6308         local rep_ost=$(do_nodes $(comma_list $(osts_nodes)) \
6309                         $LCTL get_param -n obdfilter.$FSNAME-*.lfsck_* |
6310                         awk '/repaired/ { print $2 }' | calc_sum)
6311         local repaired=$((rep_mdt + rep_ost))
6312         [ $repaired -eq 0 ] ||
6313                 error "lfsck repaired $rep_mdt MDT and $rep_ost OST errors"
6314 }
6315
6316 dump_file_contents() {
6317         local nodes=$1
6318         local dir=$2
6319         local logname=$3
6320         local node
6321
6322         if [ -z "$nodes" -o -z "$dir" -o -z "$logname" ]; then
6323                 error_noexit false \
6324                         "Invalid parameters for dump_file_contents()"
6325                 return 1
6326         fi
6327         for node in ${nodes}; do
6328                 do_node $node "for i in \\\$(find $dir -type f); do
6329                                 echo ====\\\${i}=======================;
6330                                 cat \\\${i};
6331                                 done" >> ${logname}.${node}.log
6332         done
6333 }
6334
6335 dump_command_output() {
6336         local nodes=$1
6337         local cmd=$2
6338         local logname=$3
6339         local node
6340
6341         if [ -z "$nodes" -o -z "$cmd" -o -z "$logname" ]; then
6342                 error_noexit false \
6343                         "Invalid parameters for dump_command_output()"
6344                 return 1
6345         fi
6346
6347         for node in ${nodes}; do
6348                 do_node $node "echo ====${cmd}=======================;
6349                                 $cmd" >> ${logname}.${node}.log
6350         done
6351 }
6352
6353 log_zfs_info() {
6354         local logname=$1
6355
6356         # dump file contents from /proc/spl in case of zfs test
6357         if [ "$(facet_fstype ost1)" = "zfs" ]; then
6358                 dump_file_contents "$(osts_nodes)" "/proc/spl" "${logname}"
6359                 dump_command_output \
6360                         "$(osts_nodes)" "zpool events -v" "${logname}"
6361         fi
6362
6363         if [ "$(facet_fstype $SINGLEMDS)" = "zfs" ]; then
6364                 dump_file_contents "$(mdts_nodes)" "/proc/spl" "${logname}"
6365                 dump_command_output \
6366                         "$(mdts_nodes)" "zpool events -v" "${logname}"
6367         fi
6368 }
6369
6370 do_check_and_cleanup_lustre() {
6371         echo "=== $TESTSUITE: start cleanup $(date +'%H:%M:%S (%s)') ==="
6372
6373         if [[ "$LFSCK_ALWAYS" == "yes" && "$TESTSUITE" != "sanity-lfsck" && \
6374               "$TESTSUITE" != "sanity-scrub" ]]; then
6375                 run_lfsck
6376         fi
6377
6378         if is_mounted $MOUNT; then
6379                 if $DO_CLEANUP; then
6380                         [[ -n "$DIR" ]] && rm -rf $DIR/[Rdfs][0-9]* ||
6381                                 error "remove sub-test dirs failed"
6382                 else
6383                         echo "skip cleanup"
6384                 fi
6385                 [[ -n "$ENABLE_QUOTA" ]] && restore_quota || true
6386         fi
6387
6388         if [[ "$I_UMOUNTED2" == "yes" ]]; then
6389                 restore_mount $MOUNT2 || error "restore $MOUNT2 failed"
6390         fi
6391
6392         if [[ "$I_MOUNTED2" == "yes" ]]; then
6393                 cleanup_mount $MOUNT2
6394         fi
6395
6396         if [[ "$I_MOUNTED" == "yes" ]] && ! $AUSTER_CLEANUP; then
6397                 cleanupall -f || error "cleanup failed"
6398                 unset I_MOUNTED
6399         fi
6400
6401         echo "=== $TESTSUITE: finish cleanup $(date +'%H:%M:%S (%s)') ==="
6402 }
6403
6404 check_and_cleanup_lustre() {
6405         local start_stamp=$(date +%s)
6406         local saved_umask=$(umask)
6407         local log=$TESTLOG_PREFIX.test_cleanup.test_log.$(hostname -s).log
6408         local status='PASS'
6409         local stop_stamp=0
6410         local duration=0
6411         local error=''
6412         local rc=0
6413
6414         umask 0022
6415
6416         log_sub_test_begin test_cleanup
6417
6418         if ! do_check_and_cleanup_lustre 2>&1 > >(tee -i $log); then
6419                 error=$(tail -1 $log)
6420                 status='FAIL'
6421                 rc=1
6422         fi
6423
6424         stop_stamp=$(date +%s)
6425         duration=$((stop_stamp - start_stamp))
6426
6427         log_sub_test_end "$status" "$duration" "$rc" "$error"
6428
6429         umask $saved_umask
6430
6431         return $rc
6432 }
6433
6434 #######
6435 # General functions
6436
6437 wait_for_function () {
6438         local quiet=""
6439
6440         # suppress fn both stderr and stdout
6441         if [ "$1" = "--quiet" ]; then
6442                 shift
6443                 quiet=" > /dev/null 2>&1"
6444         fi
6445
6446         local fn=$1
6447         local max=${2:-900}
6448         local sleep=${3:-5}
6449
6450         local wait=0
6451
6452         while true; do
6453
6454                 eval $fn $quiet && return 0
6455
6456                 [ $wait -lt $max ] || return 1
6457                 echo waiting $fn, $((max - wait)) secs left ...
6458                 wait=$((wait + sleep))
6459                 [ $wait -gt $max ] && ((sleep -= wait - max))
6460                 sleep $sleep
6461         done
6462 }
6463
6464 check_network() {
6465         local host=$1
6466         local max=$2
6467         local sleep=${3:-5}
6468
6469         [ "$host" = "$HOSTNAME" ] && return 0
6470
6471         if ! wait_for_function --quiet "ping -c 1 -w 3 $host" $max $sleep; then
6472                 echo "$(date +'%H:%M:%S (%s)') waited for $host network ${max}s"
6473                 exit 1
6474         fi
6475 }
6476
6477 no_dsh() {
6478         shift
6479         eval "$@"
6480 }
6481
6482 # Convert a space-delimited list to a comma-delimited list.  If the input is
6483 # only whitespace, ensure the output is empty (i.e. "") so [ -n $list ] works
6484 comma_list() {
6485         # echo is used to convert newlines to spaces, since it doesn't
6486         # introduce a trailing space as using "tr '\n' ' '" does
6487         echo $(tr -s " " "\n" <<< $* | sort -b -u) | tr ' ' ','
6488 }
6489
6490 list_member () {
6491         local list=$1
6492         local item=$2
6493         echo $list | grep -qw $item
6494 }
6495
6496 # list, excluded are the comma separated lists
6497 exclude_items_from_list () {
6498         local list=$1
6499         local excluded=$2
6500         local item
6501
6502         list=${list//,/ }
6503         for item in ${excluded//,/ }; do
6504                 list=$(echo " $list " | sed -re "s/\s+$item\s+/ /g")
6505         done
6506         echo $(comma_list $list)
6507 }
6508
6509 # list, expand  are the comma separated lists
6510 expand_list () {
6511         local list=${1//,/ }
6512         local expand=${2//,/ }
6513         local expanded=
6514
6515         expanded=$(for i in $list $expand; do echo $i; done | sort -u)
6516         echo $(comma_list $expanded)
6517 }
6518
6519 testslist_filter () {
6520         local script=$LUSTRE/tests/${TESTSUITE}.sh
6521
6522         [ -f $script ] || return 0
6523
6524         local start_at=$START_AT
6525         local stop_at=$STOP_AT
6526
6527         local var=${TESTSUITE//-/_}_START_AT
6528         [ x"${!var}" != x ] && start_at=${!var}
6529         var=${TESTSUITE//-/_}_STOP_AT
6530         [ x"${!var}" != x ] && stop_at=${!var}
6531
6532         sed -n 's/^test_\([^ (]*\).*/\1/p' $script |
6533         awk ' BEGIN { if ("'${start_at:-0}'" != 0) flag = 1 }
6534             /^'${start_at}'$/ {flag = 0}
6535             {if (flag == 1) print $0}
6536             /^'${stop_at}'$/ { flag = 1 }'
6537 }
6538
6539 absolute_path() {
6540         (cd `dirname $1`; echo $PWD/`basename $1`)
6541 }
6542
6543 get_facets () {
6544         local types=${1:-"OST MDS MGS"}
6545
6546         local list=""
6547
6548         for entry in $types; do
6549                 local name=$(echo $entry | tr "[:upper:]" "[:lower:]")
6550                 local type=$(echo $entry | tr "[:lower:]" "[:upper:]")
6551
6552                 case $type in
6553                         MGS ) list="$list $name";;
6554                         MDS|OST|AGT ) local count=${type}COUNT
6555                                 for ((i=1; i<=${!count}; i++)) do
6556                                         list="$list ${name}$i"
6557                                 done;;
6558                         * ) error "Invalid facet type"
6559                                 exit 1;;
6560                 esac
6561         done
6562         echo $(comma_list $list)
6563 }
6564
6565 ##################################
6566 # Adaptive Timeouts funcs
6567
6568 at_is_enabled() {
6569         # only check mds, we assume at_max is the same on all nodes
6570         local at_max=$(do_facet $SINGLEMDS "lctl get_param -n at_max")
6571
6572         if [ $at_max -eq 0 ]; then
6573                 return 1
6574         else
6575                 return 0
6576         fi
6577 }
6578
6579 at_get() {
6580         local facet=$1
6581         local at=$2
6582
6583         # suppose that all ost-s have the same $at value set
6584         [ $facet != "ost" ] || facet=ost1
6585
6586         do_facet $facet "lctl get_param -n $at"
6587 }
6588
6589 at_max_get() {
6590         at_get $1 at_max
6591 }
6592
6593 at_max_set() {
6594         local at_max=$1
6595         shift
6596
6597         local facet
6598         local hosts
6599
6600         for facet in "$@"; do
6601                 if [ $facet == "ost" ]; then
6602                         facet=$(get_facets OST)
6603                 elif [ $facet == "mds" ]; then
6604                         facet=$(get_facets MDS)
6605                 fi
6606                 hosts=$(expand_list $hosts $(facets_hosts $facet))
6607         done
6608
6609         do_nodes $hosts lctl set_param at_max=$at_max
6610 }
6611
6612 at_min_get() {
6613         at_get $1 at_min
6614 }
6615
6616 at_min_set() {
6617         local at_min=$1
6618         shift
6619
6620         local facet
6621         local hosts
6622
6623         for facet in "$@"; do
6624                 if [ $facet == "ost" ]; then
6625                         facet=$(get_facets OST)
6626                 elif [ $facet == "mds" ]; then
6627                         facet=$(get_facets MDS)
6628                 fi
6629                 hosts=$(expand_list $hosts $(facets_hosts $facet))
6630         done
6631
6632         do_nodes $hosts lctl set_param at_min=$at_min
6633 }
6634
6635 ##################################
6636 # OBD_FAIL funcs
6637
6638 drop_request() {
6639 # OBD_FAIL_MDS_ALL_REQUEST_NET
6640         RC=0
6641         do_facet $SINGLEMDS lctl set_param fail_val=0 fail_loc=0x123
6642         do_facet client "$1" || RC=$?
6643         do_facet $SINGLEMDS lctl set_param fail_loc=0
6644         return $RC
6645 }
6646
6647 drop_reply() {
6648 # OBD_FAIL_MDS_ALL_REPLY_NET
6649         RC=0
6650         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x122
6651         eval "$@" || RC=$?
6652         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
6653         return $RC
6654 }
6655
6656 drop_reint_reply() {
6657 # OBD_FAIL_MDS_REINT_NET_REP
6658         RC=0
6659         do_facet $SINGLEMDS $LCTL set_param fail_loc=0x119
6660         eval "$@" || RC=$?
6661         do_facet $SINGLEMDS $LCTL set_param fail_loc=0
6662         return $RC
6663 }
6664
6665 drop_update_reply() {
6666 # OBD_FAIL_OUT_UPDATE_NET_REP
6667         local index=$1
6668         shift 1
6669         RC=0
6670         do_facet mds${index} lctl set_param fail_loc=0x1701
6671         do_facet client "$@" || RC=$?
6672         do_facet mds${index} lctl set_param fail_loc=0
6673         return $RC
6674 }
6675
6676 pause_bulk() {
6677 #define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214
6678         RC=0
6679
6680         local timeout=${2:-0}
6681         # default is (obd_timeout / 4) if unspecified
6682         echo "timeout is $timeout/$2"
6683         do_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214
6684         do_facet client "$1" || RC=$?
6685         do_facet client "sync"
6686         do_facet ost1 lctl set_param fail_loc=0
6687         return $RC
6688 }
6689
6690 drop_ldlm_cancel() {
6691 #define OBD_FAIL_LDLM_CANCEL_NET                        0x304
6692         local RC=0
6693         local list=$(comma_list $(mdts_nodes) $(osts_nodes))
6694         do_nodes $list lctl set_param fail_loc=0x304
6695
6696         do_facet client "$@" || RC=$?
6697
6698         do_nodes $list lctl set_param fail_loc=0
6699         return $RC
6700 }
6701
6702 drop_bl_callback_once() {
6703         local rc=0
6704         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
6705 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
6706         do_facet client lctl set_param fail_loc=0x80000305
6707         do_facet client "$@" || rc=$?
6708         do_facet client lctl set_param fail_loc=0
6709         do_facet client lctl set_param fail_val=0
6710         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
6711         return $rc
6712 }
6713
6714 drop_bl_callback() {
6715         rc=0
6716         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0
6717 #define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305
6718         do_facet client lctl set_param fail_loc=0x305
6719         do_facet client "$@" || rc=$?
6720         do_facet client lctl set_param fail_loc=0
6721         do_facet client lctl set_param fail_val=0
6722         do_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1
6723         return $rc
6724 }
6725
6726 drop_mdt_ldlm_reply() {
6727 #define OBD_FAIL_MDS_LDLM_REPLY_NET     0x157
6728         RC=0
6729         local list=$(comma_list $(mdts_nodes))
6730
6731         do_nodes $list lctl set_param fail_loc=0x157
6732
6733         do_facet client "$@" || RC=$?
6734
6735         do_nodes $list lctl set_param fail_loc=0
6736         return $RC
6737 }
6738
6739 drop_mdt_ldlm_reply_once() {
6740 #define OBD_FAIL_MDS_LDLM_REPLY_NET     0x157
6741         RC=0
6742         local list=$(comma_list $(mdts_nodes))
6743
6744         do_nodes $list lctl set_param fail_loc=0x80000157
6745
6746         do_facet client "$@" || RC=$?
6747
6748         do_nodes $list lctl set_param fail_loc=0
6749         return $RC
6750 }
6751
6752 clear_failloc() {
6753         facet=$1
6754         pause=$2
6755         sleep $pause
6756         echo "clearing fail_loc on $facet"
6757         do_facet $facet "lctl set_param fail_loc=0 2>/dev/null || true"
6758 }
6759
6760 set_nodes_failloc () {
6761         local fv=${3:-0}
6762         do_nodes $(comma_list $1)  lctl set_param fail_val=$fv fail_loc=$2
6763 }
6764
6765 # Print the total of the lock_unused_count across all namespaces containing the
6766 # given wildcard. If the namespace wildcard is omitted, all namespaces will be
6767 # matched.
6768 # Usage: total_unused_locks [namespace_wildcard]
6769 total_unused_locks() {
6770         $LCTL get_param -n "ldlm.namespaces.*$1*.lock_unused_count" | calc_sum
6771 }
6772
6773 # Print the total of the lock_count across all namespaces containing the given
6774 # wildcard. If the namespace wilcard is omitted, all namespaces will be matched.
6775 # Usage: total_used_locks [namespace_wildcard]
6776 total_used_locks() {
6777         $LCTL get_param -n "ldlm.namespaces.*$1*.lock_count" | calc_sum
6778 }
6779
6780 # Cancel lru locks across all namespaces containing the given wildcard. If the
6781 # wilcard is omitted, lru locks will be canceled across all namespaces.
6782 # Usage: cancel_lru_locks [namespace_wildcard]
6783 cancel_lru_locks() {
6784         #$LCTL mark "cancel_lru_locks $1 start"
6785         $LCTL set_param -t4 -n "ldlm.namespaces.*$1*.lru_size=clear"
6786         $LCTL get_param "ldlm.namespaces.*$1*.lock_unused_count" | grep -v '=0'
6787         #$LCTL mark "cancel_lru_locks $1 stop"
6788 }
6789
6790 default_lru_size()
6791 {
6792         local nr_cpu=$(grep -c "processor" /proc/cpuinfo)
6793
6794         echo $((100 * nr_cpu))
6795 }
6796
6797 lru_resize_enable()
6798 {
6799         lctl set_param ldlm.namespaces.*$1*.lru_size=0
6800 }
6801
6802 lru_resize_disable()
6803 {
6804         local dev=${1}
6805         local lru_size=${2:-$(default_lru_size)}
6806
6807         $LCTL set_param ldlm.namespaces.*$dev*.lru_size=$lru_size
6808 }
6809
6810 flock_is_enabled()
6811 {
6812         local mountpath=${1:-$MOUNT}
6813         local RC=0
6814
6815         [ -z "$(mount | grep "$mountpath .*flock" | grep -v noflock)" ] && RC=1
6816         return $RC
6817 }
6818
6819 pgcache_empty() {
6820         local FILE
6821
6822         for FILE in `lctl get_param -N "llite.*.dump_page_cache"`; do
6823                 if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then
6824                         echo there is still data in page cache $FILE ?
6825                         lctl get_param -n $FILE
6826                         return 1
6827                 fi
6828         done
6829         return 0
6830 }
6831
6832 debugsave() {
6833         DEBUGSAVE="$(lctl get_param -n debug)"
6834         DEBUGSAVE_SERVER=$(do_facet $SINGLEMDS "$LCTL get_param -n debug")
6835 }
6836
6837 debugrestore() {
6838         [ -n "$DEBUGSAVE" ] &&
6839                 do_nodes $CLIENTS "$LCTL set_param debug=\\\"${DEBUGSAVE}\\\""||
6840                 true
6841         DEBUGSAVE=""
6842
6843         [ -n "$DEBUGSAVE_SERVER" ] &&
6844                 do_nodes $(comma_list $(all_server_nodes)) \
6845                          "$LCTL set_param debug=\\\"${DEBUGSAVE_SERVER}\\\"" ||
6846                          true
6847         DEBUGSAVE_SERVER=""
6848 }
6849
6850 debug_size_save() {
6851         DEBUG_SIZE_SAVED="$(lctl get_param -n debug_mb)"
6852 }
6853
6854 debug_size_restore() {
6855         [ -n "$DEBUG_SIZE_SAVED" ] &&
6856                 do_nodes $(comma_list $(nodes_list)) "$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED"
6857         DEBUG_SIZE_SAVED=""
6858 }
6859
6860 start_full_debug_logging() {
6861         debugsave
6862         debug_size_save
6863
6864         local fulldebug=-1
6865         local debug_size=150
6866         local nodes=$(comma_list $(nodes_list))
6867
6868         do_nodes $nodes "$LCTL set_param debug=$fulldebug debug_mb=$debug_size"
6869 }
6870
6871 stop_full_debug_logging() {
6872         debug_size_restore
6873         debugrestore
6874 }
6875
6876 # prints bash call stack
6877 print_stack_trace() {
6878         local skip=${1:-1}
6879         echo "  Trace dump:"
6880         for (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do
6881                 local src=${BASH_SOURCE[$i]}
6882                 local lineno=${BASH_LINENO[$i-1]}
6883                 local funcname=${FUNCNAME[$i]}
6884                 echo "  = $src:$lineno:$funcname()"
6885         done
6886 }
6887
6888 report_error() {
6889         local TYPE=${TYPE:-"FAIL"}
6890
6891         local dump=true
6892         # do not dump logs if $1=false
6893         if [ "x$1" = "xfalse" ]; then
6894                 shift
6895                 dump=false
6896         fi
6897
6898         log " ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $* "
6899         (print_stack_trace 2) >&2
6900         mkdir -p $LOGDIR
6901         # We need to dump the logs on all nodes
6902         if $dump; then
6903                 gather_logs $(comma_list $(nodes_list))
6904         fi
6905
6906         debugrestore
6907         [ "$TESTSUITELOG" ] &&
6908                 echo "$TESTSUITE: $TYPE: $TESTNAME $*" >> $TESTSUITELOG
6909         if [ -z "$*" ]; then
6910                 echo "error() without useful message, please fix" > $LOGDIR/err
6911         else
6912                 if [[ `echo $TYPE | grep ^IGNORE` ]]; then
6913                         echo "$@" > $LOGDIR/ignore
6914                 else
6915                         echo "$@" > $LOGDIR/err
6916                 fi
6917         fi
6918
6919         # cleanup the env for failed tests
6920         reset_fail_loc
6921 }
6922
6923 ##################################
6924 # Test interface
6925 ##################################
6926
6927 # usage: stack_trap arg sigspec
6928 #
6929 # stack_trap() behaves like bash's built-in trap, except that it "stacks" the
6930 # command "arg" on top of previously defined commands for "sigspec" instead
6931 # of overwriting them.
6932 # stacked traps are executed in reverse order of their registration
6933 #
6934 # arg and sigspec have the same meaning as in man (1) trap
6935 stack_trap()
6936 {
6937         local arg="$1"
6938         local sigspec="${2:-EXIT}"
6939
6940         # Use "trap -p" to get the quoting right
6941         local old_trap="$(trap -p "$sigspec")"
6942         # Append ";" and remove the leading "trap -- '" added by "trap -p"
6943         old_trap="${old_trap:+"; ${old_trap#trap -- \'}"}"
6944
6945         # Once again, use "trap -p" to get the quoting right
6946         local new_trap="$(trap -- "$arg" "$sigspec"
6947                           trap -p "$sigspec"
6948                           trap -- '' "$sigspec")"
6949
6950         # Remove the trailing "' $sigspec" part added by "trap -p" and merge
6951         #
6952         # The resulting string should be safe to "eval" as it is (supposedly
6953         # correctly) quoted by "trap -p"
6954         eval "${new_trap%\' $sigspec}${old_trap:-"' $sigspec"}"
6955 }
6956
6957 error_noexit() {
6958         report_error "$@"
6959 }
6960
6961 exit_status () {
6962         local status=0
6963         local logs="$TESTSUITELOG $1"
6964
6965         for log in $logs; do
6966                 if [ -f "$log" ]; then
6967                         grep -qw FAIL $log && status=1
6968                 fi
6969         done
6970
6971         exit $status
6972 }
6973
6974 error() {
6975         report_error "$@"
6976         exit 1
6977 }
6978
6979 error_exit() {
6980         report_error "$@"
6981         exit 1
6982 }
6983
6984 # use only if we are ignoring failures for this test, bugno required.
6985 # (like ALWAYS_EXCEPT, but run the test and ignore the results.)
6986 # e.g. error_ignore bz5494 "your message" or
6987 # error_ignore LU-5494 "your message"
6988 error_ignore() {
6989         local TYPE="IGNORE ($1)"
6990         shift
6991         report_error "$@"
6992 }
6993
6994 error_and_remount() {
6995         report_error "$@"
6996         remount_client $MOUNT
6997         exit 1
6998 }
6999
7000 # Throw an error if it's not running in vm - usually for performance
7001 # verification
7002 error_not_in_vm() {
7003         local virt=$(running_in_vm)
7004         if [[ -n "$virt" ]]; then
7005                 echo "running in VM '$virt', ignore error"
7006                 error_ignore env=$virt "$@"
7007         else
7008                 error "$@"
7009         fi
7010 }
7011
7012 #
7013 # Function: skip_env()
7014 # Purpose:  to skip a test during developer testing because some tool
7015 #           is missing, but fail the test in release testing because the test
7016 #           environment is not configured properly".
7017 #
7018 skip_env () {
7019         $FAIL_ON_SKIP_ENV && error false "$@" || skip "$@"
7020 }
7021
7022 skip_noexit() {
7023         echo
7024         log " SKIP: $TESTSUITE $TESTNAME $*"
7025
7026         if [[ -n "$ALWAYS_SKIPPED" ]]; then
7027                 skip_logged $TESTNAME "$@"
7028         else
7029                 mkdir -p $LOGDIR
7030                 echo "$@" > $LOGDIR/skip
7031         fi
7032
7033         [[ -n "$TESTSUITELOG" ]] &&
7034                 echo "$TESTSUITE: SKIP: $TESTNAME $*" >> $TESTSUITELOG || true
7035         unset TESTNAME
7036 }
7037
7038 skip() {
7039         skip_noexit "$@"
7040         exit 0
7041 }
7042
7043 #
7044 # For interop testing treate EOPNOTSUPP as success
7045 # and skip
7046 #
7047 skip_eopnotsupp() {
7048         local retstr=$@
7049
7050         echo $retstr | awk -F'|' '{print $1}' |
7051                 grep -E unsupported\|"(Operation not supported)"
7052         (( $? == 0 )) || error "$retstr"
7053         skip $retstr
7054 }
7055
7056 # Add a list of tests to ALWAYS_EXCEPT due to an issue.
7057 # Usage: always_except LU-4815 23 42q ...
7058 #
7059 function always_except() {
7060         local issue="${1:-}" # single jira style issue ("LU-4815")
7061         local test_num
7062
7063         shift
7064
7065         if ! [[ "$issue" =~ ^[[:upper:]]+-[[:digit:]]+$ ]]; then
7066                 error "always_except: invalid issue '$issue' for tests '$*'"
7067         fi
7068
7069         for test_num in "$@"; do
7070                 ALWAYS_EXCEPT+=" $test_num"
7071         done
7072 }
7073
7074 build_test_filter() {
7075         EXCEPT="$EXCEPT $(testslist_filter)"
7076
7077         # allow test numbers separated by '+', or ',', in addition to ' '
7078         # to avoid issues with multiple arguments handling by shell/autotest
7079         for O in ${ONLY//[+,]/ }; do
7080                 if [[ $O =~ [0-9]*-[0-9]* ]]; then
7081                         for ((num=${O%-[0-9]*}; num <= ${O#[0-9]*-}; num++)); do
7082                                 eval ONLY_$num=true
7083                         done
7084                 else
7085                         eval ONLY_${O}=true
7086                 fi
7087         done
7088
7089         [[ -z "$EXCEPT$ALWAYS_EXCEPT" ]] ||
7090                 log "excepting tests: $(echo $EXCEPT $ALWAYS_EXCEPT)"
7091         [[ -z "$EXCEPT_SLOW" ]] ||
7092                 log "skipping tests SLOW=no: $(echo $EXCEPT_SLOW)"
7093         for E in ${EXCEPT//[+,]/ }; do
7094                 eval EXCEPT_${E}=true
7095         done
7096         for E in ${ALWAYS_EXCEPT//[+,]/ }; do
7097                 eval EXCEPT_ALWAYS_${E}=true
7098         done
7099         for E in ${EXCEPT_SLOW//[+,]/ }; do
7100                 eval EXCEPT_SLOW_${E}=true
7101         done
7102         for G in ${GRANT_CHECK_LIST//[+,]/ }; do
7103                 eval GCHECK_ONLY_${G}=true
7104         done
7105 }
7106
7107 basetest() {
7108         if [[ $1 = [a-z]* ]]; then
7109                 echo $1
7110         else
7111                 echo ${1%%[a-zA-Z]*}
7112         fi
7113 }
7114
7115 # print a newline if the last test was skipped
7116 export LAST_SKIPPED=
7117 export ALWAYS_SKIPPED=
7118 #
7119 # Main entry into test-framework. This is called with the number and
7120 # description of a test. The number is used to find the function to run
7121 # the test using "test_$name".
7122 #
7123 # This supports a variety of methods of specifying specific test to
7124 # run or not run:
7125 # - ONLY= env variable with space-separated list of test numbers to run
7126 # - EXCEPT= env variable with space-separated list of test numbers to exclude
7127 #
7128 run_test() {
7129         assert_DIR
7130         local testnum=$1
7131         local testmsg=$2
7132         export base=$(basetest $testnum)
7133         export TESTNAME=test_$testnum
7134         LAST_SKIPPED=
7135         ALWAYS_SKIPPED=
7136
7137         # Check the EXCEPT, ALWAYS_EXCEPT and SLOW lists to see if we
7138         # need to skip the current test. If so, set the ALWAYS_SKIPPED flag.
7139         local isexcept=EXCEPT_$testnum
7140         local isexcept_base=EXCEPT_$base
7141         if [ ${!isexcept}x != x ]; then
7142                 ALWAYS_SKIPPED="y"
7143                 skip_message="skipping excluded test $testnum"
7144         elif [ ${!isexcept_base}x != x ]; then
7145                 ALWAYS_SKIPPED="y"
7146                 skip_message="skipping excluded test $testnum (base $base)"
7147         fi
7148
7149         isexcept=EXCEPT_ALWAYS_$testnum
7150         isexcept_base=EXCEPT_ALWAYS_$base
7151         if [ ${!isexcept}x != x ]; then
7152                 ALWAYS_SKIPPED="y"
7153                 skip_message="skipping ALWAYS excluded test $testnum"
7154         elif [ ${!isexcept_base}x != x ]; then
7155                 ALWAYS_SKIPPED="y"
7156                 skip_message="skipping ALWAYS excluded test $testnum (base $base)"
7157         fi
7158
7159         isexcept=EXCEPT_SLOW_$testnum
7160         isexcept_base=EXCEPT_SLOW_$base
7161         if [ ${!isexcept}x != x ]; then
7162                 ALWAYS_SKIPPED="y"
7163                 skip_message="skipping SLOW test $testnum"
7164         elif [ ${!isexcept_base}x != x ]; then
7165                 ALWAYS_SKIPPED="y"
7166                 skip_message="skipping SLOW test $testnum (base $base)"
7167         fi
7168
7169         # If there are tests on the ONLY list, check if the current test
7170         # is on that list and, if so, check if the test is to be skipped
7171         # and if we are supposed to honor the skip lists.
7172         if [ -n "$ONLY" ]; then
7173                 local isonly=ONLY_$testnum
7174                 local isonly_base=ONLY_$base
7175                 if [[ ${!isonly}x != x || ${!isonly_base}x != x ]]; then
7176
7177                         if [[ -n "$ALWAYS_SKIPPED" &&
7178                                         -n "$HONOR_EXCEPT" ]]; then
7179                                 LAST_SKIPPED="y"
7180                                 skip_noexit "$skip_message"
7181                                 return 0
7182                         else
7183                                 [ -n "$LAST_SKIPPED" ] &&
7184                                         echo "" && LAST_SKIPPED=
7185                                 ALWAYS_SKIPPED=
7186                                 run_one_logged $testnum "$testmsg"
7187                                 return $?
7188                         fi
7189
7190                 else
7191                         LAST_SKIPPED="y"
7192                         return 0
7193                 fi
7194         fi
7195
7196         if [ -n "$ALWAYS_SKIPPED" ]; then
7197                 LAST_SKIPPED="y"
7198                 skip_noexit "$skip_message"
7199                 return 0
7200         else
7201                 run_one_logged $testnum "$testmsg"
7202                 return $?
7203         fi
7204 }
7205
7206 log() {
7207         echo "$*" >&2
7208         load_module ../libcfs/libcfs/libcfs
7209
7210         local MSG="$*"
7211         # Get rid of '
7212         MSG=${MSG//\'/\\\'}
7213         MSG=${MSG//\*/\\\*}
7214         MSG=${MSG//\(/\\\(}
7215         MSG=${MSG//\)/\\\)}
7216         MSG=${MSG//\;/\\\;}
7217         MSG=${MSG//\|/\\\|}
7218         MSG=${MSG//\>/\\\>}
7219         MSG=${MSG//\</\\\<}
7220         MSG=${MSG//\//\\\/}
7221         do_nodes $(comma_list $(nodes_list)) $LCTL mark "$MSG" 2> /dev/null || true
7222 }
7223
7224 trace() {
7225         log "STARTING: $*"
7226         strace -o $TMP/$1.strace -ttt $*
7227         RC=$?
7228         log "FINISHED: $*: rc $RC"
7229         return 1
7230 }
7231
7232 complete_test() {
7233         local duration=$1
7234
7235         banner "test complete, duration $duration sec"
7236         [ -f "$TESTSUITELOG" ] && egrep .FAIL $TESTSUITELOG || true
7237         echo "duration $duration" >>$TESTSUITELOG
7238 }
7239
7240 pass() {
7241         # Set TEST_STATUS here. It will be used for logging the result.
7242         TEST_STATUS="PASS"
7243
7244         if [[ -f $LOGDIR/err ]]; then
7245                 TEST_STATUS="FAIL"
7246         elif [[ -f $LOGDIR/skip ]]; then
7247                 TEST_STATUS="SKIP"
7248         fi
7249         echo "$TEST_STATUS $*" 2>&1 | tee -a $TESTSUITELOG
7250 }
7251
7252 check_mds() {
7253         local FFREE=$(do_node $SINGLEMDS \
7254         lctl get_param -n osd*.*MDT*.filesfree | calc_sum)
7255         local FTOTAL=$(do_node $SINGLEMDS \
7256         lctl get_param -n osd*.*MDT*.filestotal | calc_sum)
7257
7258         [ $FFREE -ge $FTOTAL ] && error "files free $FFREE > total $FTOTAL" ||
7259                 true
7260 }
7261
7262 reset_fail_loc () {
7263         #echo -n "Resetting fail_loc on all nodes..."
7264         do_nodes --quiet $(comma_list $(nodes_list)) \
7265                 "lctl set_param -n fail_loc=0 fail_val=0 2>/dev/null" || true
7266         #echo done.
7267 }
7268
7269
7270 #
7271 # Log a message (on all nodes) padded with "=" before and after.
7272 # Also appends a timestamp and prepends the testsuite name.
7273 #
7274
7275 # ======================================================== 15:06:12 (1624050372)
7276 EQUALS="========================================================"
7277 banner() {
7278         msg="== ${TESTSUITE} $*"
7279         last=${msg: -1:1}
7280         [[ $last != "=" && $last != " " ]] && msg="$msg "
7281         msg=$(printf '%s%.*s'  "$msg"  $((${#EQUALS} - ${#msg})) $EQUALS )
7282         # always include at least == after the message
7283         log "$msg== $(date +"%H:%M:%S (%s)")"
7284 }
7285
7286 check_dmesg_for_errors() {
7287         local res
7288         local errors="VFS: Busy inodes after unmount of\|\
7289 ldiskfs_check_descriptors: Checksum for group 0 failed\|\
7290 group descriptors corrupted"
7291
7292         res=$(do_nodes -q $(comma_list $(nodes_list)) "dmesg" | grep "$errors")
7293         [ -z "$res" ] && return 0
7294         echo "Kernel error detected: $res"
7295         return 1
7296 }
7297
7298 #
7299 # Run a single test function and cleanup after it.
7300 #
7301 # This function should be run in a subshell so the test func can
7302 # exit() without stopping the whole script.
7303 #
7304 run_one() {
7305         local testnum=$1
7306         local testmsg="$2"
7307         local SAVE_UMASK=`umask`
7308         umask 0022
7309
7310         if ! grep -q $DIR /proc/mounts; then
7311                 $SETUP
7312         fi
7313
7314         banner "test $testnum: $testmsg"
7315         test_${testnum} || error "test_$testnum failed with $?"
7316         cd $SAVE_PWD
7317         reset_fail_loc
7318         check_grant ${testnum} || error "check_grant $testnum failed with $?"
7319         check_node_health
7320         check_dmesg_for_errors || error "Error in dmesg detected"
7321         if [ "$PARALLEL" != "yes" ]; then
7322                 ps auxww | grep -v grep | grep -q "multiop " &&
7323                                         error "multiop still running"
7324         fi
7325         umask $SAVE_UMASK
7326         $CLEANUP
7327         return 0
7328 }
7329
7330 #
7331 # Wrapper around run_one to ensure:
7332 #  - test runs in subshell
7333 #  - output of test is saved to separate log file for error reporting
7334 #  - test result is saved to data file
7335 #
7336 run_one_logged() {
7337         local before=$SECONDS
7338         local testnum=$1
7339         local testmsg=$2
7340         export tfile=f${testnum}.${TESTSUITE}
7341         export tdir=d${testnum}.${TESTSUITE}
7342         local test_log=$TESTLOG_PREFIX.$TESTNAME.test_log.$(hostname -s).log
7343         local zfs_debug_log=$TESTLOG_PREFIX.$TESTNAME.zfs_log
7344         local SAVE_UMASK=$(umask)
7345         local rc=0
7346         local node
7347         declare -A kptr_restrict
7348         declare -A debug_raw
7349         umask 0022
7350
7351         for node in $(all_nodes); do
7352                 kptr_restrict[$node]=$(do_node $node "sysctl --values kernel/kptr_restrict")
7353                 do_node $node "sysctl -wq kernel/kptr_restrict=1"
7354                 # Enable %p to be unhashed (if supported)
7355                 debug_raw[$node]=$(do_node $node "$LCTL get_param -n debug_raw_pointers" || echo 0)
7356                 do_node $node "$LCTL set_param debug_raw_pointers=Y || true"
7357         done
7358
7359         rm -f $LOGDIR/err $LOGDIR/ignore $LOGDIR/skip
7360         echo
7361         # if $ONLY is set, repeat subtest $ONLY_REPEAT times, otherwise once
7362         local repeat=${ONLY:+$ONLY_REPEAT}
7363
7364         for ((testiter=0; testiter < ${repeat:-1}; testiter++)); do
7365                 local before_sub=$SECONDS
7366
7367                 log_sub_test_begin $TESTNAME
7368                 # remove temp files between repetitions to avoid test failures
7369                 if [[ -n "$append" ]]; then
7370                         [[ -n "$tdir" ]] && rm -rvf $DIR/$tdir*
7371                         [[ -n "$tfile" ]] && rm -vf $DIR/$tfile*
7372                         echo "subtest iteration $testiter/$repeat"
7373                 fi
7374                 # loop around subshell so stack_trap EXIT triggers each time
7375                 (run_one $testnum "$testmsg") 2>&1 | tee -i $append $test_log
7376                 rc=${PIPESTATUS[0]}
7377                 local append=-a
7378                 local duration_sub=$((SECONDS - before_sub))
7379                 local test_error
7380
7381                 [[ $rc != 0 && ! -f $LOGDIR/err ]] &&
7382                         echo "$TESTNAME returned $rc" | tee $LOGDIR/err
7383
7384                 if [[ -f $LOGDIR/err ]]; then
7385                         test_error=$(cat $LOGDIR/err)
7386                         TEST_STATUS="FAIL"
7387                 elif [[ -f $LOGDIR/ignore ]]; then
7388                         test_error=$(cat $LOGDIR/ignore)
7389                 elif [[ -f $LOGDIR/skip ]]; then
7390                         test_error=$(cat $LOGDIR/skip)
7391                         TEST_STATUS="SKIP"
7392                 else
7393                         TEST_STATUS="PASS"
7394                 fi
7395
7396                 pass "$testnum" "(${duration_sub}s)"
7397                 if [ -n "${DUMP_OK}" ]; then
7398                         gather_logs $(comma_list $(nodes_list))
7399                 fi
7400
7401                 log_sub_test_end $TEST_STATUS $duration_sub "$rc" "$test_error"
7402                 [[ $rc != 0 || "$TEST_STATUS" != "PASS" ]] && break
7403         done
7404
7405         local param
7406         for node in $(all_nodes); do
7407                 param="kernel/kptr_restrict=${kptr_restrict[$node]}"
7408                 do_node $node "sysctl -wq ${param} || true"
7409                 # Restore %p to initial state
7410                 param="debug_raw_pointers=${debug_raw[$node]}"
7411                 do_node $node "$LCTL set_param ${param} || true"
7412         done
7413
7414         if [[ "$TEST_STATUS" != "SKIP" && -f $TF_SKIP ]]; then
7415                 rm -f $TF_SKIP
7416         fi
7417
7418         if [ -f $LOGDIR/err ]; then
7419                 log_zfs_info "$zfs_debug_log"
7420                 $FAIL_ON_ERROR && exit $rc
7421         fi
7422
7423         umask $SAVE_UMASK
7424
7425         unset TESTNAME
7426         unset tdir
7427         unset tfile
7428
7429         return 0
7430 }
7431
7432 #
7433 # Print information of skipped tests to result.yml
7434 #
7435 skip_logged(){
7436         log_sub_test_begin $1
7437         shift
7438         log_sub_test_end "SKIP" "0" "0" "$@"
7439 }
7440
7441 grant_from_clients() {
7442         local nodes="$1"
7443
7444         # get client grant
7445         do_nodes $nodes "$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes" |
7446                 calc_sum
7447 }
7448
7449 grant_from_servers() {
7450         local nodes="$1"
7451
7452         # get server grant
7453         # which is tot_granted less grant_precreate
7454         do_nodes $nodes "$LCTL get_param obdfilter.${FSNAME}-OST*.tot_granted" \
7455                 " obdfilter.${FSNAME}-OST*.tot_pending" \
7456                 " obdfilter.${FSNAME}-OST*.grant_precreate" |
7457                 tr '=' ' ' | awk '/tot_granted/{ total += $2 };
7458                                   /tot_pending/{ total -= $2 };
7459                                   /grant_precreate/{ total -= $2 };
7460                                   END { printf("%0.0f", total) }'
7461 }
7462
7463 check_grant() {
7464         export base=$(basetest $1)
7465         [ "$CHECK_GRANT" == "no" ] && return 0
7466
7467         local isonly_base=GCHECK_ONLY_${base}
7468         local isonly=GCHECK_ONLY_$1
7469         [ ${!isonly_base}x == x -a ${!isonly}x == x ] && return 0
7470
7471         echo -n "checking grant......"
7472
7473         local osts=$(comma_list $(osts_nodes))
7474         local clients=$CLIENTS
7475         [ -z "$clients" ] && clients=$(hostname)
7476
7477         # sync all the data and make sure no pending data on server
7478         do_nodes $clients sync
7479         do_nodes $clients $LFS df # initiate all idling connections
7480
7481         # get client grant
7482         cli_grant=$(grant_from_clients $clients)
7483
7484         # get server grant
7485         # which is tot_granted less grant_precreate
7486         srv_grant=$(grant_from_servers $osts)
7487
7488         count=0
7489         # check whether client grant == server grant
7490         while [[ $cli_grant != $srv_grant && count++ -lt 30 ]]; do
7491                 echo "wait for client:$cli_grant == server:$srv_grant"
7492                 sleep 1
7493                 cli_grant=$(grant_from_clients $clients)
7494                 srv_grant=$(grant_from_servers $osts)
7495         done
7496         if [[ $cli_grant -ne $srv_grant ]]; then
7497                 do_nodes $(comma_list $(osts_nodes)) \
7498                         "$LCTL get_param obdfilter.${FSNAME}-OST*.tot*" \
7499                         "obdfilter.${FSNAME}-OST*.grant_*"
7500                 do_nodes $clients "$LCTL get_param osc.${FSNAME}-*.cur_*_bytes"
7501                 error "failed grant check: client:$cli_grant server:$srv_grant"
7502         else
7503                 echo "pass grant check: client:$cli_grant server:$srv_grant"
7504         fi
7505 }
7506
7507 ########################
7508 # helper functions
7509
7510 osc_to_ost() {
7511         local osc=$1
7512
7513         echo ${osc/-osc*/}
7514 }
7515
7516 ostuuid_from_index() {
7517         # only print the first UUID, if 'lfs osts' shows multiple mountpoints
7518         local uuid=($($LFS osts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"))
7519
7520         echo ${uuid}
7521 }
7522
7523 ostname_from_index() {
7524         local uuid=$(ostuuid_from_index $1 $2)
7525
7526         echo ${uuid/_UUID/}
7527 }
7528
7529 mdtuuid_from_index() {
7530         # only print the first UUID, if 'lfs osts' shows multiple mountpoints
7531         local uuid=($($LFS mdts $2 | sed -ne "/^$1: /s/.* \(.*\) .*$/\1/p"))
7532
7533         echo ${uuid}
7534 }
7535
7536 mdtname_from_index() {
7537         local uuid=$(mdtuuid_from_index $1 $2)
7538
7539         echo ${uuid/_UUID/}
7540 }
7541
7542 mdssize_from_index() {
7543         local mdt=$(mdtname_from_index $2)
7544
7545         $LFS df $1 | awk "/$mdt/ { print \$2 }"
7546 }
7547
7548 index_from_ostuuid()
7549 {
7550         # only print the first index, if 'lfs osts' shows multiple mountpoints
7551         local ostidx=($($LFS osts $2 | sed -ne "/${1}/s/\(.*\): .* .*$/\1/p"))
7552
7553         echo ${ostidx}
7554 }
7555
7556 # Description:
7557 #   Return unique identifier for given hostname
7558 host_id() {
7559         local host_name=$1
7560         echo $host_name | md5sum | cut -d' ' -f1
7561 }
7562
7563 # Description:
7564 #   Returns list of ip addresses for each interface
7565 local_addr_list() {
7566         ip addr | awk '/inet / {print $2}' | awk -F/ '{print $1}'
7567 }
7568
7569 # Description:
7570 #   Returns list of interfaces configured for LNet
7571 lnet_if_list() {
7572         local nids=( $($LCTL list_nids | xargs echo) )
7573
7574         [[ -z ${nids[@]} ]] &&
7575                 return 0
7576
7577         if [[ ${NETTYPE} =~ kfi* ]]; then
7578                 $LNETCTL net show 2>/dev/null | awk '/ cxi[0-9]+$/{print $NF}' |
7579                         sort -u | xargs echo
7580                 return 0
7581         fi
7582
7583         declare -a INTERFACES
7584
7585         for ((i = 0; i < ${#nids[@]}; i++)); do
7586                 ip=$(sed 's/^\(.*\)@.*$/\1/'<<<${nids[i]})
7587                 INTERFACES[i]=$(ip -o a s |
7588                                 awk '$4 ~ /^'$ip'\//{print $2}')
7589                 INTERFACES=($(echo "${INTERFACES[@]}" | tr ' ' '\n' | uniq | tr '\n' ' '))
7590                 if [[ -z ${INTERFACES[i]} ]]; then
7591                         error "Can't determine interface name for NID ${nids[i]}"
7592                 elif [[ 1 -ne $(wc -w <<<${INTERFACES[i]}) ]]; then
7593                         error "Found $(wc -w <<<${INTERFACES[i]}) interfaces for NID ${nids[i]}. Expect 1"
7594                 fi
7595         done
7596
7597         echo "${INTERFACES[@]}"
7598
7599         return 0
7600 }
7601
7602 # return 1 if addr is remote
7603 # return 0 if addr is local
7604 is_local_addr() {
7605         local addr=$1
7606         # Cache address list to avoid mutiple execution of local_addr_list
7607         LOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}
7608         local i
7609         for i in $LOCAL_ADDR_LIST ; do
7610                 [[ "$i" == "$addr" ]] && return 0
7611         done
7612         return 1
7613 }
7614
7615 # return true(0) if host_name is local
7616 # return false(1) if host_name is remote
7617 local_node() {
7618         local host_name=$1
7619         local is_local="IS_LOCAL_$(host_id $host_name)"
7620
7621         if [ -z "${!is_local-}" ] ; then
7622                 eval $is_local=false
7623                 local host_ip=$(getent ahostsv4 $host_name |
7624                                         awk 'NR == 1 { print $1 }')
7625                 is_local_addr "$host_ip" && eval $is_local=true
7626         fi
7627         ${!is_local}
7628 }
7629
7630 remote_node () {
7631         local node=$1
7632
7633         ! local_node $node
7634 }
7635
7636 remote_mds ()
7637 {
7638         local node
7639         for node in $(mdts_nodes); do
7640                 remote_node $node && return 0
7641         done
7642         return 1
7643 }
7644
7645 remote_mds_nodsh()
7646 {
7647         [ -n "$CLIENTONLY" ] && return 0 || true
7648         remote_mds && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$mds_HOST" ]
7649 }
7650
7651 require_dsh_mds()
7652 {
7653         remote_mds_nodsh && echo "SKIP: $TESTSUITE: remote MDS with nodsh" &&
7654                 MSKIPPED=1 && return 1
7655         return 0
7656 }
7657
7658 remote_ost ()
7659 {
7660         local node
7661         for node in $(osts_nodes) ; do
7662                 remote_node $node && return 0
7663         done
7664         return 1
7665 }
7666
7667 remote_ost_nodsh()
7668 {
7669         [ -n "$CLIENTONLY" ] && return 0 || true
7670         remote_ost && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
7671 }
7672
7673 require_dsh_ost()
7674 {
7675         remote_ost_nodsh && echo "SKIP: $TESTSUITE: remote OST with nodsh" &&
7676                 OSKIPPED=1 && return 1
7677         return 0
7678 }
7679
7680 remote_mgs_nodsh()
7681 {
7682         [ -n "$CLIENTONLY" ] && return 0 || true
7683         local MGS
7684         MGS=$(facet_host mgs)
7685         remote_node $MGS && [ "$PDSH" = "no_dsh" -o -z "$PDSH" -o -z "$ost_HOST" ]
7686 }
7687
7688 local_mode ()
7689 {
7690         remote_mds_nodsh || remote_ost_nodsh ||
7691                 $(single_local_node $(comma_list $(nodes_list)))
7692 }
7693
7694 remote_servers () {
7695         remote_ost && remote_mds
7696 }
7697
7698 # Get the active nodes for facets.
7699 facets_nodes () {
7700         local facets=$1
7701         local facet
7702         local nodes
7703         local nodes_sort
7704         local i
7705
7706         for facet in ${facets//,/ }; do
7707                 nodes="$nodes $(facet_active_host $facet)"
7708         done
7709
7710         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
7711         echo -n $nodes_sort
7712 }
7713
7714 # Get name of the active MGS node.
7715 mgs_node () {
7716                 echo -n $(facets_nodes $(get_facets MGS))
7717         }
7718
7719 # Get all of the active MDS nodes.
7720 mdts_nodes () {
7721         echo -n $(facets_nodes $(get_facets MDS))
7722 }
7723
7724 # Get all of the active OSS nodes.
7725 osts_nodes () {
7726         echo -n $(facets_nodes $(get_facets OST))
7727 }
7728
7729 # Get all of the client nodes and active server nodes.
7730 nodes_list () {
7731         local nodes=$HOSTNAME
7732         local nodes_sort
7733         local i
7734
7735         # CLIENTS (if specified) contains the local client
7736         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
7737
7738         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
7739                 nodes="$nodes $(facets_nodes $(get_facets))"
7740         fi
7741
7742         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
7743         echo -n $nodes_sort
7744 }
7745
7746 # Get all of the remote client nodes and remote active server nodes.
7747 remote_nodes_list () {
7748         echo -n $(nodes_list) | sed -re "s/\<$HOSTNAME\>//g"
7749 }
7750
7751 # Get all of the MDS nodes, including active and passive nodes.
7752 all_mdts_nodes () {
7753         local host
7754         local failover_host
7755         local nodes
7756         local nodes_sort
7757         local i
7758
7759         for i in $(seq $MDSCOUNT); do
7760                 host=mds${i}_HOST
7761                 failover_host=mds${i}failover_HOST
7762                 nodes="$nodes ${!host} ${!failover_host}"
7763         done
7764
7765         [ -n "$nodes" ] || nodes="${mds_HOST} ${mdsfailover_HOST}"
7766         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
7767         echo -n $nodes_sort
7768 }
7769
7770 # Get all of the OSS nodes, including active and passive nodes.
7771 all_osts_nodes () {
7772         local host
7773         local failover_host
7774         local nodes=
7775         local nodes_sort
7776         local i
7777
7778         for i in $(seq $OSTCOUNT); do
7779                 host=ost${i}_HOST
7780                 failover_host=ost${i}failover_HOST
7781                 nodes="$nodes ${!host} ${!failover_host}"
7782         done
7783
7784         [ -n "$nodes" ] || nodes="${ost_HOST} ${ostfailover_HOST}"
7785         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
7786         echo -n $nodes_sort
7787 }
7788
7789 # Get all of the server nodes, including active and passive nodes.
7790 all_server_nodes () {
7791         local nodes
7792         local nodes_sort
7793         local i
7794
7795         nodes="$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)"
7796
7797         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
7798         echo -n $nodes_sort
7799 }
7800
7801 # Get all of the client and server nodes, including active and passive nodes.
7802 all_nodes () {
7803         local nodes=$HOSTNAME
7804         local nodes_sort
7805         local i
7806
7807         # CLIENTS (if specified) contains the local client
7808         [ -n "$CLIENTS" ] && nodes=${CLIENTS//,/ }
7809
7810         if [ "$PDSH" -a "$PDSH" != "no_dsh" ]; then
7811                 nodes="$nodes $(all_server_nodes)"
7812         fi
7813
7814         nodes_sort=$(for i in $nodes; do echo $i; done | sort -u)
7815         echo -n $nodes_sort
7816 }
7817
7818 init_clients_lists () {
7819         # Sanity check: exclude the local client from RCLIENTS
7820         local clients=$(hostlist_expand "$RCLIENTS")
7821         local rclients=$(exclude_items_from_list "$clients" $HOSTNAME)
7822
7823         # Sanity check: exclude the dup entries
7824         RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)
7825
7826         export CLIENT1=${CLIENT1:-$HOSTNAME}
7827         export SINGLECLIENT=$CLIENT1
7828
7829         clients="$SINGLECLIENT $HOSTNAME $RCLIENTS"
7830
7831         # Sanity check: exclude the dup entries from CLIENTS
7832         # for those configs which has SINGLCLIENT set to local client
7833         clients=$(for i in $clients; do echo $i; done | sort -u)
7834
7835         export CLIENTS=$(comma_list $clients)
7836         local -a remoteclients=($RCLIENTS)
7837         for ((i=0; $i<${#remoteclients[@]}; i++)); do
7838                 varname=CLIENT$((i + 2))
7839
7840                 eval export $varname=${remoteclients[i]}
7841         done
7842
7843         export CLIENTCOUNT=$((${#remoteclients[@]} + 1))
7844 }
7845
7846 get_random_entry () {
7847         local rnodes=$1
7848
7849         rnodes=${rnodes//,/ }
7850
7851         local -a nodes=($rnodes)
7852         local num=${#nodes[@]}
7853         local i=$((RANDOM * num * 2 / 65536))
7854
7855         echo ${nodes[i]}
7856 }
7857
7858 client_only () {
7859         [ -n "$CLIENTONLY" ] || [ "x$CLIENTMODSONLY" = "xyes" ]
7860 }
7861
7862 check_versions () {
7863         # this should already have been called, but just in case
7864         [[ -n "$CLIENT_VERSION" && -n "$MDS1_VERSION" && -n "$OST1_VERSION" ]]||
7865                 get_lustre_env
7866
7867         echo "client=$CLIENT_VERSION MDS=$MDS1_VERSION OSS=$OST1_VERSION"
7868
7869         [[ -n "$CLIENT_VERSION" && -n "$MDS1_VERSION" && -n "$OST1_VERSION" ]]||
7870                 error "unable to determine node versions"
7871
7872         (( "$CLIENT_VERSION" == "$MDS1_VERSION" &&
7873            "$CLIENT_VERSION" == "$OST1_VERSION"))
7874 }
7875
7876 get_node_count() {
7877         local nodes="$@"
7878
7879         echo $nodes | wc -w || true
7880 }
7881
7882 mixed_mdt_devs () {
7883         local nodes=$(mdts_nodes)
7884         local mdtcount=$(get_node_count "$nodes")
7885
7886         [ ! "$MDSCOUNT" = "$mdtcount" ]
7887 }
7888
7889 generate_machine_file() {
7890         local nodes=${1//,/ }
7891         local machinefile=$2
7892
7893         rm -f $machinefile
7894         for node in $nodes; do
7895                 echo $node >>$machinefile ||
7896                         { echo "can not generate machinefile $machinefile" &&
7897                                 return 1; }
7898         done
7899 }
7900
7901 get_stripe () {
7902         local file=$1/stripe
7903
7904         touch $file
7905         $LFS getstripe -v $file || error "getstripe $file failed"
7906         rm -f $file
7907 }
7908
7909 # Check and add a test group.
7910 add_group() {
7911         local group_id=$1
7912         local group_name=$2
7913         local rc=0
7914
7915         local gid=$(getent group $group_name | cut -d: -f3)
7916         if [[ -n "$gid" ]]; then
7917                 [[ "$gid" -eq "$group_id" ]] || {
7918                         error_noexit "inconsistent group ID:" \
7919                                      "new: $group_id, old: $gid"
7920                         rc=1
7921                 }
7922         else
7923                 echo "adding group $group_name:$group_id"
7924                 getent group $group_name || true
7925                 getent group $group_id || true
7926                 groupadd -g $group_id $group_name
7927                 rc=${PIPESTATUS[0]}
7928         fi
7929
7930         return $rc
7931 }
7932
7933 # Check and add a test user.
7934 add_user() {
7935         local user_id=$1
7936         shift
7937         local user_name=$1
7938         shift
7939         local group_name=$1
7940         shift
7941         local home=$1
7942         shift
7943         local opts="$@"
7944         local rc=0
7945
7946         local uid=$(getent passwd $user_name | cut -d: -f3)
7947         if [[ -n "$uid" ]]; then
7948                 if [[ "$uid" -eq "$user_id" ]]; then
7949                         local dir=$(getent passwd $user_name | cut -d: -f6)
7950                         if [[ "$dir" != "$home" ]]; then
7951                                 mkdir -p $home
7952                                 usermod -d $home $user_name
7953                                 rc=${PIPESTATUS[0]}
7954                         fi
7955                 else
7956                         error_noexit "inconsistent user ID:" \
7957                                      "new: $user_id, old: $uid"
7958                         rc=1
7959                 fi
7960         else
7961                 mkdir -p $home
7962                 useradd -M -u $user_id -d $home -g $group_name $opts $user_name
7963                 rc=${PIPESTATUS[0]}
7964         fi
7965
7966         return $rc
7967 }
7968
7969 check_runas_id_ret() {
7970         local myRC=0
7971         local myRUNAS_UID=$1
7972         local myRUNAS_GID=$2
7973         shift 2
7974         local myRUNAS=$@
7975
7976         if [ -z "$myRUNAS" ]; then
7977                 error_exit "check_runas_id_ret requires myRUNAS argument"
7978         fi
7979
7980         $myRUNAS true ||
7981                 error "Unable to execute $myRUNAS"
7982
7983         id $myRUNAS_UID > /dev/null ||
7984                 error "Invalid RUNAS_ID $myRUNAS_UID. Please set RUNAS_ID to " \
7985                       "some UID which exists on MDS and client or add user " \
7986                       "$myRUNAS_UID:$myRUNAS_GID on these nodes."
7987
7988         if $GSS_KRB5; then
7989                 $myRUNAS krb5_login.sh ||
7990                         error "Failed to refresh krb5 TGT for UID $myRUNAS_ID."
7991         fi
7992         mkdir $DIR/d0_runas_test
7993         chmod 0755 $DIR
7994         chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test
7995         $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?
7996         rm -rf $DIR/d0_runas_test
7997         return $myRC
7998 }
7999
8000 check_runas_id() {
8001         local myRUNAS_UID=$1
8002         local myRUNAS_GID=$2
8003         shift 2
8004         local myRUNAS=$@
8005
8006         check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \
8007                 error "unable to write to $DIR/d0_runas_test as " \
8008                       "UID $myRUNAS_UID."
8009 }
8010
8011 # obtain the UID/GID for MPI_USER
8012 get_mpiuser_id() {
8013         local mpi_user=$1
8014
8015         MPI_USER_UID=$(do_facet client "getent passwd $mpi_user | cut -d: -f3;
8016 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the UID for $mpi_user"
8017
8018         MPI_USER_GID=$(do_facet client "getent passwd $mpi_user | cut -d: -f4;
8019 exit \\\${PIPESTATUS[0]}") || error_exit "failed to get the GID for $mpi_user"
8020 }
8021
8022 # Run multiop in the background, but wait for it to print
8023 # "PAUSING" to its stdout before returning from this function.
8024 multiop_bg_pause() {
8025         MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}
8026         FILE=$1
8027         ARGS=$2
8028
8029         TMPPIPE=/tmp/multiop_open_wait_pipe.$$
8030         mkfifo $TMPPIPE
8031
8032         echo "$MULTIOP_PROG $FILE v$ARGS"
8033         $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &
8034         local pid=$!
8035
8036         echo "TMPPIPE=${TMPPIPE}"
8037         read -t 60 multiop_output < $TMPPIPE
8038         if [ $? -ne 0 ]; then
8039                 rm -f $TMPPIPE
8040                 return 1
8041         fi
8042         rm -f $TMPPIPE
8043         if [ "$multiop_output" != "PAUSING" ]; then
8044                 echo "Incorrect multiop output: $multiop_output"
8045                 kill -9 $pid
8046                 return 1
8047         fi
8048
8049         return 0
8050 }
8051
8052 do_and_time () {
8053         local cmd="$1"
8054         local start
8055         local rc
8056
8057         start=$SECONDS
8058         eval '$cmd'
8059         [ ${PIPESTATUS[0]} -eq 0 ] || rc=1
8060
8061         echo $((SECONDS - start))
8062         return $rc
8063 }
8064
8065 inodes_available () {
8066         local IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |
8067                 sort -un | head -n1) || return 1
8068
8069         echo $((IFree))
8070 }
8071
8072 mdsrate_inodes_available () {
8073         local min_inodes=$(inodes_available)
8074
8075         echo $((min_inodes * 99 / 100))
8076 }
8077
8078 bytes_available () {
8079         echo $(df -P -B 1 "$MOUNT" | awk 'END {print $4}')
8080 }
8081
8082 mdsrate_bytes_available () {
8083         local bytes=$(bytes_available)
8084
8085         echo $((bytes * 99 / 100))
8086 }
8087
8088 # reset stat counters
8089 clear_stats() {
8090         local paramfile="$1"
8091
8092         lctl set_param -n $paramfile=0
8093 }
8094
8095 # sum stat items
8096 calc_stats() {
8097         local paramfile="$1"
8098         local stat="$2"
8099
8100         lctl get_param -n $paramfile |
8101                 awk '/^'$stat'/ { sum += $2 } END { printf("%0.0f", sum) }'
8102 }
8103
8104 calc_sum () {
8105         awk '{sum += $1} END { printf("%0.0f", sum) }'
8106 }
8107
8108 calc_osc_kbytes () {
8109         $LFS df $MOUNT > /dev/null
8110         $LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum
8111 }
8112
8113 free_min_max () {
8114         wait_delete_completed
8115         AVAIL=($(lctl get_param -n osc.*[oO][sS][cC]-[^M]*.kbytesavail))
8116         echo "OST kbytes available: ${AVAIL[*]}"
8117         MAXV=${AVAIL[0]}
8118         MAXI=0
8119         MINV=${AVAIL[0]}
8120         MINI=0
8121         for ((i = 0; i < ${#AVAIL[@]}; i++)); do
8122                 #echo OST $i: ${AVAIL[i]}kb
8123                 if [[ ${AVAIL[i]} -gt $MAXV ]]; then
8124                         MAXV=${AVAIL[i]}
8125                         MAXI=$i
8126                 fi
8127                 if [[ ${AVAIL[i]} -lt $MINV ]]; then
8128                         MINV=${AVAIL[i]}
8129                         MINI=$i
8130                 fi
8131         done
8132         echo "Min free space: OST $MINI: $MINV"
8133         echo "Max free space: OST $MAXI: $MAXV"
8134 }
8135
8136 # save_lustre_params(comma separated facet list, parameter_mask)
8137 # generate a stream of formatted strings (<facet> <param name>=<param value>)
8138 save_lustre_params() {
8139         local facets=$1
8140         local facet
8141         local facet_svc
8142
8143         for facet in ${facets//,/ }; do
8144                 facet_svc=$(facet_svc $facet)
8145                 do_facet $facet \
8146                         "params=\\\$($LCTL get_param $2);
8147                          [[ -z \\\"$facet_svc\\\" ]] && param= ||
8148                          param=\\\$(grep $facet_svc <<< \\\"\\\$params\\\");
8149                          [[ -z \\\$param ]] && param=\\\"\\\$params\\\";
8150                          while read s; do echo $facet \\\$s;
8151                          done <<< \\\"\\\$param\\\""
8152         done
8153 }
8154
8155 # restore lustre parameters from input stream, produces by save_lustre_params
8156 restore_lustre_params() {
8157         local facet
8158         local name
8159         local val
8160
8161         while IFS=" =" read facet name val; do
8162                 do_facet $facet "$LCTL set_param -n $name=$val"
8163         done
8164 }
8165
8166 check_node_health() {
8167         local nodes=${1:-$(comma_list $(nodes_list))}
8168         local health=$TMP/node_health.$$
8169
8170         do_nodes -q $nodes "$LCTL get_param catastrophe 2>&1" | tee $health |
8171                 grep "catastrophe=1" && error "LBUG/LASSERT detected"
8172         # Only check/report network health if get_param isn't reported, since
8173         # *clearly* the network is working if get_param returned something.
8174         if (( $(grep -c catastro $health) != $(wc -w <<< ${nodes//,/ }) )); then
8175                 for node in ${nodes//,/ }; do
8176                         check_network $node 5
8177                 done
8178         fi
8179         rm -f $health
8180 }
8181
8182 mdsrate_cleanup () {
8183         if [ -d $4 ]; then
8184                 mpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \
8185                         --nfiles $3 --dir $4 --filefmt $5 $6
8186                 rmdir $4
8187         fi
8188 }
8189
8190 run_mdtest () {
8191         local test_type="$1"
8192         local file_size=0
8193         local num_files=0
8194         local num_cores=0
8195         local num_procs=0
8196         local num_hosts=0
8197         local free_space=0
8198         local num_inodes=0
8199         local num_entries=0
8200         local num_dirs=0
8201         local np=0
8202         local rc=0
8203
8204         local mdtest_basedir
8205         local mdtest_actions
8206         local mdtest_options
8207         local stripe_options
8208         local params_file
8209
8210         case "$test_type" in
8211         create-small)
8212                 stripe_options=(-c 1 -i 0)
8213                 mdtest_actions=(-F -R)
8214                 file_size=1024
8215                 num_files=100000
8216                 ;;
8217         create-large)
8218                 stripe_options=(-c -1)
8219                 mdtest_actions=(-F -R)
8220                 file_size=$((1024 * 1024 * 1024))
8221                 num_files=16
8222                 ;;
8223         lookup-single)
8224                 stripe_options=(-c 1)
8225                 mdtest_actions=(-C -D -E -k -r)
8226                 num_dirs=1
8227                 num_files=100000
8228                 ;;
8229         lookup-multi)
8230                 stripe_options=(-c 1)
8231                 mdtest_actions=(-C -D -E -k -r)
8232                 num_dirs=100
8233                 num_files=1000
8234                 ;;
8235         *)
8236                 stripe_options=(-c -1)
8237                 mdtest_actions=()
8238                 num_files=100000
8239                 ;;
8240         esac
8241
8242         if [[ -n "$MDTEST_DEBUG" ]]; then
8243                 mdtest_options+=(-v -v -v)
8244         fi
8245
8246         num_dirs=${NUM_DIRS:-$num_dirs}
8247         num_files=${NUM_FILES:-$num_files}
8248         file_size=${FILE_SIZE:-$file_size}
8249         free_space=$(mdsrate_bytes_available)
8250
8251         if (( file_size * num_files > free_space )); then
8252                 file_size=$((free_space / num_files))
8253                 log "change file size to $file_size due to" \
8254                         "number of files $num_files and" \
8255                         "free space limit in $free_space"
8256         fi
8257
8258         if (( file_size > 0 )); then
8259                 log "set file size to $file_size"
8260                 mdtest_options+=(-w=$file_size)
8261         fi
8262
8263         params_file=$TMP/$TESTSUITE-$TESTNAME.parameters
8264         mdtest_basedir=$MOUNT/mdtest
8265         mdtest_options+=(-d=$mdtest_basedir)
8266
8267         num_cores=$(nproc)
8268         num_hosts=$(get_node_count ${CLIENTS//,/ })
8269         num_procs=$((num_cores * num_hosts))
8270         num_inodes=$(mdsrate_inodes_available)
8271
8272         if (( num_inodes < num_files )); then
8273                 log "change the number of files $num_files to the" \
8274                         "number of available inodes $num_inodes"
8275                 num_files=$num_inodes
8276         fi
8277
8278         if (( num_dirs > 1 )); then
8279                 num_entries=$((num_files / num_dirs))
8280                 log "split $num_files files to $num_dirs" \
8281                         "with $num_entries files each"
8282                 mdtest_options+=(-I=$num_entries)
8283         fi
8284
8285         generate_machine_file $CLIENTS $MACHINEFILE ||
8286                 error "can not generate machinefile"
8287
8288         install -v -d -m 0777 $mdtest_basedir
8289
8290         setstripe_getstripe $mdtest_basedir ${stripe_options[@]}
8291
8292         save_lustre_params $(get_facets MDS) \
8293                 mdt.*.enable_remote_dir_gid > $params_file
8294
8295         do_nodes $(comma_list $(mdts_nodes)) \
8296                 $LCTL set_param mdt.*.enable_remote_dir_gid=-1
8297
8298         stack_trap "restore_lustre_params < $params_file" EXIT
8299
8300         for np in 1 $num_procs; do
8301                 num_entries=$((num_files / np ))
8302
8303                 mpi_run $MACHINEFILE_OPTION $MACHINEFILE \
8304                         -np $np -npernode $num_cores $MDTEST \
8305                         ${mdtest_options[@]} -n=$num_entries \
8306                         ${mdtest_actions[@]} 2>&1 | tee -a "$LOG"
8307
8308                 rc=${PIPESTATUS[0]}
8309
8310                 if (( rc != 0 )); then
8311                         mpi_run $MACHINEFILE_OPTION $MACHINEFILE \
8312                                 -np $np -npernode $num_cores $MDTEST \
8313                                 ${mdtest_options[@]} -n=$num_entries \
8314                                 -r 2>&1 | tee -a "$LOG"
8315                         break
8316                 fi
8317         done
8318
8319         rmdir -v $mdtest_basedir
8320         rm -v $state $MACHINEFILE
8321
8322         return $rc
8323 }
8324
8325 ########################
8326
8327 convert_facet2label() {
8328         local facet=$1
8329
8330         if [ x$facet = xost ]; then
8331                 facet=ost1
8332         elif [ x$facet = xmgs ] && combined_mgs_mds ; then
8333                 facet=mds1
8334         fi
8335
8336         local varsvc=${facet}_svc
8337
8338         if [ -n "${!varsvc}" ]; then
8339                 echo ${!varsvc}
8340         else
8341                 error "No label for $facet!"
8342         fi
8343 }
8344
8345 get_clientosc_proc_path() {
8346         echo "${1}-osc-[-0-9a-f]*"
8347 }
8348
8349 get_mdtosc_proc_path() {
8350         local mds_facet=$1
8351         local ost_label=${2:-"*OST*"}
8352
8353         [ "$mds_facet" = "mds" ] && mds_facet=$SINGLEMDS
8354         local mdt_label=$(convert_facet2label $mds_facet)
8355         local mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')
8356
8357         if [[ $ost_label = *OST* ]]; then
8358                 echo "${ost_label}-osc-${mdt_index}"
8359         else
8360                 echo "${ost_label}-osp-${mdt_index}"
8361         fi
8362 }
8363
8364 get_osc_import_name() {
8365         local facet=$1
8366         local ost=$2
8367         local label=$(convert_facet2label $ost)
8368
8369         if [ "${facet:0:3}" = "mds" ]; then
8370                 get_mdtosc_proc_path $facet $label
8371                 return 0
8372         fi
8373
8374         get_clientosc_proc_path $label
8375         return 0
8376 }
8377
8378 _wait_import_state () {
8379         local expected="$1"
8380         local CONN_PROC="$2"
8381         local maxtime=${3:-$(max_recovery_time)}
8382         local err_on_fail=${4:-1}
8383         local CONN_STATE
8384         local i=0
8385
8386         CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)
8387         while ! echo "${CONN_STATE}" | egrep -q "^${expected}\$" ; do
8388                 if [[ "${expected}" == "DISCONN" ]]; then
8389                         # for disconn we can check after proc entry is removed
8390                         [[ -z "${CONN_STATE}" ]] && return 0
8391                         # with AT, we can have connect request timeout near
8392                         # reconnect timeout and test can't see real disconnect
8393                         [[ "${CONN_STATE}" == "CONNECTING" ]] && return 0
8394                 fi
8395                 if (( $i >= $maxtime )); then
8396                         (( $err_on_fail != 0 )) &&
8397                                 error "can't put import for $CONN_PROC into ${expected} state after $i sec, have ${CONN_STATE}"
8398                         return 1
8399                 fi
8400                 sleep 1
8401                 # Add uniq for multi-mount case
8402                 CONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null |
8403                              cut -f2 | uniq)
8404                 i=$((i + 1))
8405         done
8406
8407         log "$CONN_PROC in ${CONN_STATE} state after $i sec"
8408         return 0
8409 }
8410
8411 wait_import_state() {
8412         local expected="$1"
8413         local params="$2"
8414         local maxtime=${3:-$(max_recovery_time)}
8415         local err_on_fail=${4:-1}
8416         local param
8417
8418         for param in ${params//,/ }; do
8419                 _wait_import_state "$expected" "$param" $maxtime $err_on_fail ||
8420                 return
8421         done
8422 }
8423
8424 wait_import_state_mount() {
8425         if ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then
8426                 return 0
8427         fi
8428
8429         wait_import_state "$@"
8430 }
8431
8432 # One client request could be timed out because server was not ready
8433 # when request was sent by client.
8434 # The request timeout calculation details :
8435 # ptl_send_rpc ()
8436 #      /* We give the server rq_timeout secs to process the req, and
8437 #      add the network latency for our local timeout. */
8438 #      request->rq_deadline = request->rq_sent + request->rq_timeout +
8439 #           ptlrpc_at_get_net_latency(request) ;
8440 #
8441 # ptlrpc_connect_import ()
8442 #      request->rq_timeout = INITIAL_CONNECT_TIMEOUT
8443 #
8444 # init_imp_at () ->
8445 #   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0
8446 # ptlrpc_at_get_net_latency(request) ->
8447 #       at_get (max (iat_net_latency=0, at_min)) = at_min
8448 #
8449 # i.e.:
8450 # request->rq_timeout + ptlrpc_at_get_net_latency(request) =
8451 # INITIAL_CONNECT_TIMEOUT + at_min
8452 #
8453 # We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT
8454 # because we can not get this value in runtime,
8455 # the value depends on configure options, and it is not stored in /proc.
8456 # obd_support.h:
8457 # #define CONNECTION_SWITCH_MIN 5U
8458 # #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)
8459
8460 request_timeout () {
8461         local facet=$1
8462
8463         # request->rq_timeout = INITIAL_CONNECT_TIMEOUT
8464         local init_connect_timeout=$TIMEOUT
8465         [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5
8466
8467         local at_min=$(at_get $facet at_min)
8468
8469         echo $(( init_connect_timeout + at_min ))
8470 }
8471
8472 _wait_osc_import_state() {
8473         local facet=$1
8474         local ost_facet=$2
8475         local expected=$3
8476         local target=$(get_osc_import_name $facet $ost_facet)
8477         local param="os[cp].${target}.ost_server_uuid"
8478         local params=$param
8479         local i=0
8480
8481         # 1. wait the deadline of client 1st request (it could be skipped)
8482         # 2. wait the deadline of client 2nd request
8483         local maxtime=$(( 2 * $(request_timeout $facet)))
8484
8485         if [[ $facet == client* ]]; then
8486                 # During setup time, the osc might not be setup, it need wait
8487                 # until list_param can return valid value.
8488                 params=$($LCTL list_param $param 2>/dev/null || true)
8489                 while [ -z "$params" ]; do
8490                         if [ $i -ge $maxtime ]; then
8491                                 echo "can't get $param in $maxtime secs"
8492                                 return 1
8493                         fi
8494                         sleep 1
8495                         i=$((i + 1))
8496                         params=$($LCTL list_param $param 2>/dev/null || true)
8497                 done
8498         fi
8499
8500         if [[ $ost_facet = mds* ]]; then
8501                 # no OSP connection to itself
8502                 if [[ $facet = $ost_facet ]]; then
8503                         return 0
8504                 fi
8505                 param="osp.${target}.mdt_server_uuid"
8506                 params=$param
8507         fi
8508
8509         local plist=$(comma_list $params)
8510         if ! do_rpc_nodes "$(facet_active_host $facet)" \
8511                         wait_import_state $expected $plist $maxtime; then
8512                 error "$facet: import is not in $expected state after $maxtime"
8513                 return 1
8514         fi
8515
8516         return 0
8517 }
8518
8519 wait_osc_import_state() {
8520         local facet=$1
8521         local ost_facet=$2
8522         local expected=$3
8523         local num
8524
8525         if [[ $facet = mds ]]; then
8526                 for num in $(seq $MDSCOUNT); do
8527                         _wait_osc_import_state mds$num "$ost_facet" "$expected"
8528                 done
8529         else
8530                 _wait_osc_import_state "$facet" "$ost_facet" "$expected"
8531         fi
8532 }
8533
8534 wait_osc_import_ready() {
8535         wait_osc_import_state $1 $2 "\(FULL\|IDLE\)"
8536 }
8537
8538 _wait_mgc_import_state() {
8539         local facet=$1
8540         local expected=$2
8541         local error_on_failure=${3:-1}
8542         local param="mgc.*.mgs_server_uuid"
8543         local params=$param
8544         local i=0
8545
8546         # 1. wait the deadline of client 1st request (it could be skipped)
8547         # 2. wait the deadline of client 2nd request
8548         local maxtime=$(( 2 * $(request_timeout $facet)))
8549
8550         if [[ $facet == client* ]]; then
8551                 # During setup time, the osc might not be setup, it need wait
8552                 # until list_param can return valid value. And also if there
8553                 # are mulitple osc entries we should list all of them before
8554                 # go to wait.
8555                 params=$($LCTL list_param $param 2>/dev/null || true)
8556                 while [ -z "$params" ]; do
8557                         if [ $i -ge $maxtime ]; then
8558                                 echo "can't get $param in $maxtime secs"
8559                                 return 1
8560                         fi
8561                         sleep 1
8562                         i=$((i + 1))
8563                         params=$($LCTL list_param $param 2>/dev/null || true)
8564                 done
8565         fi
8566         local plist=$(comma_list $params)
8567         if ! do_rpc_nodes "$(facet_active_host $facet)" \
8568                         wait_import_state $expected $plist $maxtime \
8569                                           $error_on_failure; then
8570                 if [ $error_on_failure -ne 0 ]; then
8571                     error "import is not in ${expected} state"
8572                 fi
8573                 return 1
8574         fi
8575
8576         return 0
8577 }
8578
8579 wait_mgc_import_state() {
8580         local facet=$1
8581         local expected=$2
8582         local error_on_failure=${3:-1}
8583         local num
8584
8585         if [[ $facet = mds ]]; then
8586                 for num in $(seq $MDSCOUNT); do
8587                         _wait_mgc_import_state mds$num "$expected" \
8588                                                $error_on_failure || return
8589                 done
8590         else
8591                 _wait_mgc_import_state "$facet" "$expected" \
8592                                        $error_on_failure || return
8593         fi
8594 }
8595
8596 wait_dne_interconnect() {
8597         local num
8598
8599         if [ $MDSCOUNT -gt 1 ]; then
8600                 for num in $(seq $MDSCOUNT); do
8601                         wait_osc_import_ready mds mds$num
8602                 done
8603         fi
8604 }
8605
8606 get_clientmdc_proc_path() {
8607     echo "${1}-mdc-*"
8608 }
8609
8610 get_clientmgc_proc_path() {
8611     echo "*"
8612 }
8613
8614 do_rpc_nodes () {
8615         local quiet
8616
8617         [[ "$1" == "--quiet" || "$1" == "-q" ]] && quiet="$1" && shift
8618
8619         local list=$1
8620         shift
8621
8622         [ -z "$list" ] && return 0
8623
8624         # Add paths to lustre tests for 32 and 64 bit systems.
8625         local LIBPATH="/usr/lib/lustre/tests:/usr/lib64/lustre/tests:"
8626         local TESTPATH="$RLUSTRE/tests:"
8627         local RPATH="PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:"
8628         do_nodes ${quiet:-"--verbose"} $list "${RPATH} NAME=${NAME} \
8629                 TESTLOG_PREFIX=$TESTLOG_PREFIX TESTNAME=$TESTNAME \
8630                 bash rpc.sh $* "
8631 }
8632
8633 wait_clients_import_state () {
8634         local list="$1"
8635         local facet="$2"
8636         local expected="$3"
8637         local facets="$facet"
8638
8639         if [ "$FAILURE_MODE" = HARD ]; then
8640                 facets=$(for f in ${facet//,/ }; do
8641                         facets_on_host $(facet_active_host $f) | tr "," "\n"
8642                 done | sort -u | paste -sd , )
8643         fi
8644
8645         for facet in ${facets//,/ }; do
8646                 local label=$(convert_facet2label $facet)
8647                 local proc_path
8648                 case $facet in
8649                 ost* ) proc_path="osc.$(get_clientosc_proc_path \
8650                                         $label).ost_server_uuid" ;;
8651                 mds* ) proc_path="mdc.$(get_clientmdc_proc_path \
8652                                         $label).mds_server_uuid" ;;
8653                 mgs* ) proc_path="mgc.$(get_clientmgc_proc_path \
8654                                         $label).mgs_server_uuid" ;;
8655                 *) error "unknown facet!" ;;
8656                 esac
8657
8658                 local params=$(expand_list $params $proc_path)
8659         done
8660
8661         if ! do_rpc_nodes "$list" wait_import_state_mount "$expected" $params;
8662         then
8663                 error "import is not in ${expected} state"
8664                 return 1
8665         fi
8666 }
8667
8668 wait_clients_import_ready() {
8669         wait_clients_import_state "$1" "$2" "\(FULL\|IDLE\)"
8670 }
8671
8672 wait_osp_active() {
8673         local facet=$1
8674         local tgt_name=$2
8675         local tgt_idx=$3
8676         local expected=$4
8677         local num
8678
8679         # wait until all MDTs are in the expected state
8680         for ((num = 1; num <= $MDSCOUNT; num++)); do
8681                 local mdtosp=$(get_mdtosc_proc_path mds${num} ${tgt_name})
8682                 local wait=0
8683                 local mproc
8684
8685                 if [ $facet = "mds" ]; then
8686                         mproc="osp.$mdtosp.active"
8687                         [ $num -eq $((tgt_idx + 1)) ] && continue
8688                 else
8689                         mproc="osc.$mdtosp.active"
8690                 fi
8691
8692                 echo "check $mproc"
8693                 while true; do
8694                         sleep 5
8695                         local result=$(do_facet mds${num} "$LCTL get_param -n $mproc")
8696                         local max=30
8697
8698                         [ ${PIPESTATUS[0]} = 0 ] || error "Can't read $mproc"
8699                         if [ $result -eq $expected ]; then
8700                                 echo -n "target updated after "
8701                                 echo "$wait sec (got $result)"
8702                                 break
8703                         fi
8704                         wait=$((wait + 5))
8705                         if [ $wait -eq $max ]; then
8706                                 error "$tgt_name: wanted $expected got $result"
8707                         fi
8708                         echo "Waiting $((max - wait)) secs for $tgt_name"
8709                 done
8710         done
8711 }
8712
8713 oos_full() {
8714         local -a AVAILA
8715         local -a GRANTA
8716         local -a TOTALA
8717         local OSCFULL=1
8718         AVAILA=($(do_nodes $(comma_list $(osts_nodes)) \
8719                   $LCTL get_param obdfilter.*.kbytesavail))
8720         GRANTA=($(do_nodes $(comma_list $(osts_nodes)) \
8721                   $LCTL get_param -n obdfilter.*.tot_granted))
8722         TOTALA=($(do_nodes $(comma_list $(osts_nodes)) \
8723                   $LCTL get_param -n obdfilter.*.kbytestotal))
8724         for ((i=0; i<${#AVAILA[@]}; i++)); do
8725                 local -a AVAIL1=(${AVAILA[$i]//=/ })
8726                 local -a TOTAL=(${TOTALA[$i]//=/ })
8727                 GRANT=$((${GRANTA[$i]}/1024))
8728                 # allow 1% of total space in bavail because of delayed
8729                 # allocation with ZFS which might release some free space after
8730                 # txg commit.  For small devices, we set a mininum of 8MB
8731                 local LIMIT=$((${TOTAL} / 100 + 8000))
8732                 echo -n $(echo ${AVAIL1[0]} | cut -d"." -f2) avl=${AVAIL1[1]} \
8733                         grnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}
8734                 [ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \
8735                         echo " FULL" || echo
8736         done
8737         return $OSCFULL
8738 }
8739
8740 list_pool() {
8741         echo -e "$(do_facet $SINGLEMDS $LCTL pool_list $1 | sed '1d')"
8742 }
8743
8744 check_pool_not_exist() {
8745         local fsname=${1%%.*}
8746         local poolname=${1##$fsname.}
8747         [[ $# -ne 1 ]] && return 0
8748         [[ x$poolname = x ]] &&  return 0
8749         list_pool $fsname | grep -w $1 && return 1
8750         return 0
8751 }
8752
8753 create_pool() {
8754         local fsname=${1%%.*}
8755         local poolname=${1##$fsname.}
8756         local keep_pools=${2:-false}
8757
8758         stack_trap "destroy_test_pools $fsname" EXIT
8759         do_facet mgs lctl pool_new $1
8760         local RC=$?
8761         # get param should return err unless pool is created
8762         [[ $RC -ne 0 ]] && return $RC
8763
8764         for mds_id in $(seq $MDSCOUNT); do
8765                 local mdt_id=$((mds_id-1))
8766                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
8767                 wait_update_facet mds$mds_id \
8768                         "lctl get_param -n lod.$lodname.pools.$poolname \
8769                                 2>/dev/null || echo foo" "" ||
8770                         error "mds$mds_id: pool_new failed $1"
8771         done
8772         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
8773                 2>/dev/null || echo foo" "" || error "pool_new failed $1"
8774
8775         $keep_pools || add_pool_to_list $1
8776         return $RC
8777 }
8778
8779 add_pool_to_list () {
8780         local fsname=${1%%.*}
8781         local poolname=${1##$fsname.}
8782
8783         local listvar=${fsname}_CREATED_POOLS
8784         local temp=${listvar}=$(expand_list ${!listvar} $poolname)
8785         eval export $temp
8786 }
8787
8788 remove_pool_from_list () {
8789         local fsname=${1%%.*}
8790         local poolname=${1##$fsname.}
8791
8792         local listvar=${fsname}_CREATED_POOLS
8793         local temp=${listvar}=$(exclude_items_from_list "${!listvar}" $poolname)
8794         eval export $temp
8795 }
8796
8797 # cleanup all pools exist on $FSNAME
8798 destroy_all_pools () {
8799         local i
8800         for i in $(list_pool $FSNAME); do
8801                 destroy_pool $i
8802         done
8803 }
8804
8805 destroy_pool_int() {
8806         local ost
8807         local OSTS=$(list_pool $1)
8808         for ost in $OSTS; do
8809                 do_facet mgs lctl pool_remove $1 $ost
8810         done
8811         wait_update_facet $SINGLEMDS "lctl pool_list $1 | wc -l" "1" ||
8812                 error "MDS: pool_list $1 failed"
8813         do_facet mgs lctl pool_destroy $1
8814 }
8815
8816 # <fsname>.<poolname> or <poolname>
8817 destroy_pool() {
8818         local fsname=${1%%.*}
8819         local poolname=${1##$fsname.}
8820
8821         [[ x$fsname = x$poolname ]] && fsname=$FSNAME
8822
8823         local RC
8824
8825         check_pool_not_exist $fsname.$poolname && return 0 || true
8826
8827         destroy_pool_int $fsname.$poolname
8828         RC=$?
8829         [[ $RC -ne 0 ]] && return $RC
8830         for mds_id in $(seq $MDSCOUNT); do
8831                 local mdt_id=$((mds_id-1))
8832                 local lodname=$fsname-MDT$(printf "%04x" $mdt_id)-mdtlov
8833                 wait_update_facet mds$mds_id \
8834                         "lctl get_param -n lod.$lodname.pools.$poolname \
8835                                 2>/dev/null || echo foo" "foo" ||
8836                         error "mds$mds_id: destroy pool failed $1"
8837         done
8838         wait_update $HOSTNAME "lctl get_param -n lov.$fsname-*.pools.$poolname \
8839                 2>/dev/null || echo foo" "foo" || error "destroy pool failed $1"
8840
8841         remove_pool_from_list $fsname.$poolname
8842
8843         return $RC
8844 }
8845
8846 destroy_pools () {
8847         local fsname=${1:-$FSNAME}
8848         local poolname
8849         local listvar=${fsname}_CREATED_POOLS
8850
8851         [ x${!listvar} = x ] && return 0
8852
8853         echo "Destroy the created pools: ${!listvar}"
8854         for poolname in ${!listvar//,/ }; do
8855                 destroy_pool $fsname.$poolname
8856         done
8857 }
8858
8859 destroy_test_pools () {
8860         local fsname=${1:-$FSNAME}
8861         destroy_pools $fsname || true
8862 }
8863
8864 gather_logs () {
8865         local list=$1
8866
8867         local ts=$(date +%s)
8868         local docp=true
8869
8870         if [[ ! -f "$YAML_LOG" ]]; then
8871                 # init_logging is not performed before gather_logs,
8872                 # so the $LOGDIR needs to be checked here
8873                 check_shared_dir $LOGDIR && touch $LOGDIR/shared
8874         fi
8875
8876         [ -f $LOGDIR/shared ] && docp=false
8877
8878         # dump lustre logs, dmesg, and journal if GSS_SK=true
8879
8880         prefix="$TESTLOG_PREFIX.$TESTNAME"
8881         suffix="$ts.log"
8882         echo "Dumping lctl log to ${prefix}.*.${suffix}"
8883
8884         if [ -n "$CLIENTONLY" -o "$PDSH" == "no_dsh" ]; then
8885                 echo "Dumping logs only on local client."
8886                 $LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}
8887                 dmesg > ${prefix}.dmesg.$(hostname -s).${suffix}
8888                 [ "$SHARED_KEY" = true ] && find $SK_PATH -name '*.key' -exec \
8889                         $LGSS_SK -r {} \; &> \
8890                         ${prefix}.ssk_keys.$(hostname -s).${suffix}
8891                 [ "$SHARED_KEY" = true ] && lctl get_param 'nodemap.*.*' > \
8892                         ${prefix}.nodemaps.$(hostname -s).${suffix}
8893                 [ "$GSS" = true ] && keyctl show > \
8894                         ${prefix}.keyring.$(hostname -s).${suffix}
8895                 [ "$GSS" = true ] && journalctl -a > \
8896                         ${prefix}.journal.$(hostname -s).${suffix}
8897                 return
8898         fi
8899
8900         do_nodesv $list \
8901                 "$LCTL dk > ${prefix}.debug_log.\\\$(hostname -s).${suffix};
8902                 dmesg > ${prefix}.dmesg.\\\$(hostname -s).${suffix}"
8903         if [ "$SHARED_KEY" = true ]; then
8904                 do_nodesv $list "find $SK_PATH -name '*.key' -exec \
8905                         $LGSS_SK -r {} \; &> \
8906                         ${prefix}.ssk_keys.\\\$(hostname -s).${suffix}"
8907                 do_facet mds1 "lctl get_param 'nodemap.*.*' > \
8908                         ${prefix}.nodemaps.\\\$(hostname -s).${suffix}"
8909         fi
8910         if [ "$GSS" = true ]; then
8911                 do_nodesv $list "keyctl show > \
8912                         ${prefix}.keyring.\\\$(hostname -s).${suffix}"
8913                 do_nodesv $list "journalctl -a > \
8914                         ${prefix}.journal.\\\$(hostname -s).${suffix}"
8915         fi
8916
8917         if [ ! -f $LOGDIR/shared ]; then
8918                 local remote_nodes=$(exclude_items_from_list $list $HOSTNAME)
8919
8920                 for node in ${remote_nodes//,/ }; do
8921                         rsync -az -e ssh $node:${prefix}.'*'.${suffix} $LOGDIR &
8922                 done
8923         fi
8924 }
8925
8926 do_ls () {
8927         local mntpt_root=$1
8928         local num_mntpts=$2
8929         local dir=$3
8930         local i
8931         local cmd
8932         local pids
8933         local rc=0
8934
8935         for i in $(seq 0 $num_mntpts); do
8936                 cmd="ls -laf ${mntpt_root}$i/$dir"
8937                 echo + $cmd;
8938                 $cmd > /dev/null &
8939                 pids="$pids $!"
8940         done
8941         echo pids=$pids
8942         for pid in $pids; do
8943                 wait $pid || rc=$?
8944         done
8945
8946         return $rc
8947 }
8948
8949 # check_and_start_recovery_timer()
8950 #       service_time = at_est2timeout(service_time);
8951 #       service_time += 2 * INITIAL_CONNECT_TIMEOUT;
8952 #       service_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);
8953
8954 #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)
8955 #define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))
8956 #define CONNECTION_SWITCH_MIN 5
8957 #define CONNECTION_SWITCH_INC 5
8958 max_recovery_time() {
8959         local init_connect_timeout=$((TIMEOUT / 20))
8960         ((init_connect_timeout >= 5)) || init_connect_timeout=5
8961
8962         local service_time=$(($(at_max_get client) * 9 / 4 + 5))
8963         service_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))
8964
8965         echo -n $service_time
8966 }
8967
8968 recovery_time_min() {
8969         local connection_switch_min=5
8970         local connection_switch_inc=5
8971         local connection_switch_max
8972         local reconnect_delay_max
8973         local initial_connect_timeout
8974         local max
8975         local timout_20
8976
8977         #connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)
8978         (($connection_switch_min > $TIMEOUT)) &&
8979                 max=$connection_switch_min || max=$TIMEOUT
8980         (($max < 50)) && connection_switch_max=$max || connection_switch_max=50
8981
8982         #initial_connect_timeout = max(connection_switch_min, obd_timeout/20)
8983         timeout_20=$((TIMEOUT/20))
8984         (($connection_switch_min > $timeout_20)) &&
8985                 initial_connect_timeout=$connection_switch_min ||
8986                 initial_connect_timeout=$timeout_20
8987
8988         reconnect_delay_max=$((connection_switch_max + connection_switch_inc +
8989                                initial_connect_timeout))
8990         echo $((2 * reconnect_delay_max))
8991 }
8992
8993 get_clients_mount_count () {
8994         local clients=${CLIENTS:-$HOSTNAME}
8995
8996         # we need to take into account the clients mounts and
8997         # exclude mds/ost mounts if any;
8998         do_nodes $clients cat /proc/mounts | grep lustre |
8999                 grep -w $MOUNT | wc -l
9000 }
9001
9002 # gss functions
9003 PROC_CLI="srpc_info"
9004 PROC_CON="srpc_contexts"
9005
9006 combination()
9007 {
9008         local M=$1
9009         local N=$2
9010         local R=1
9011
9012         if [ $M -lt $N ]; then
9013                 R=0
9014         else
9015                 N=$((N + 1))
9016                 while [ $N -lt $M ]; do
9017                         R=$((R * N))
9018                         N=$((N + 1))
9019                 done
9020         fi
9021
9022         echo $R
9023         return 0
9024 }
9025
9026 calc_connection_cnt() {
9027         local dir=$1
9028
9029         # MDT->MDT = 2 * C(M, 2)
9030         # MDT->OST = M * O
9031         # CLI->OST = C * O
9032         # CLI->MDT = C * M
9033         comb_m2=$(combination $MDSCOUNT 2)
9034
9035         local num_clients=$(get_clients_mount_count)
9036
9037         local cnt_mdt2mdt=$((comb_m2 * 2))
9038         local cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))
9039         local cnt_cli2ost=$((num_clients * OSTCOUNT))
9040         local cnt_cli2mdt=$((num_clients * MDSCOUNT))
9041         if is_mounted $MOUNT2; then
9042                 cnt_cli2mdt=$((cnt_cli2mdt * 2))
9043                 cnt_cli2ost=$((cnt_cli2ost * 2))
9044         fi
9045         if local_mode; then
9046                 cnt_mdt2mdt=0
9047                 cnt_mdt2ost=0
9048                 cnt_cli2ost=2
9049                 cnt_cli2mdt=1
9050         fi
9051         local cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))
9052         local cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))
9053         local cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt \
9054                 + cnt_cli2ost + cnt_cli2mdt))
9055
9056         local var=cnt_$dir
9057         local res=${!var}
9058
9059         echo $res
9060 }
9061
9062 set_rule()
9063 {
9064         local tgt=$1
9065         local net=$2
9066         local dir=$3
9067         local flavor=$4
9068         local cmd="$tgt.srpc.flavor"
9069
9070         if [ $net == "any" ]; then
9071                 net="default"
9072         fi
9073         cmd="$cmd.$net"
9074
9075         if [ $dir != "any" ]; then
9076                 cmd="$cmd.$dir"
9077         fi
9078
9079         cmd="$cmd=$flavor"
9080         log "Setting sptlrpc rule: $cmd"
9081         do_facet mgs "$LCTL conf_param $cmd"
9082 }
9083
9084 count_contexts()
9085 {
9086         local output=$1
9087         local total_ctx=$(echo "$output" | grep -c "expire.*key.*hdl")
9088         echo $total_ctx
9089 }
9090
9091 count_flvr()
9092 {
9093         local output=$1
9094         local flavor=$2
9095         local count=0
9096
9097         rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`
9098         bulkspec=`echo $flavor | awk -F - '{ print $2 }'`
9099
9100         count=`echo "$output" | grep "rpc flavor" | grep $rpc_flvr | wc -l`
9101
9102         if [ "x$bulkspec" != "x" ]; then
9103                 algs=`echo $bulkspec | awk -F : '{ print $2 }'`
9104
9105                 if [ "x$algs" != "x" ]; then
9106                         bulk_count=`echo "$output" | grep "bulk flavor" |
9107                                 grep $algs | wc -l`
9108                 else
9109                         bulk=`echo $bulkspec | awk -F : '{ print $1 }'`
9110
9111                         if [ $bulk == "bulkn" ]; then
9112                                 bulk_count=`echo "$output" |
9113                                         grep "bulk flavor" | grep "null/null" |
9114                                         wc -l`
9115                         elif [ $bulk == "bulki" ]; then
9116                                 bulk_count=`echo "$output" |
9117                                         grep "bulk flavor" | grep "/null" |
9118                                         grep -v "null/" | wc -l`
9119                         else
9120                                 bulk_count=`echo "$output" |
9121                                         grep "bulk flavor" | grep -v "/null" |
9122                                         grep -v "null/" | wc -l`
9123                         fi
9124                 fi
9125                 [ $bulk_count -lt $count ] && count=$bulk_count
9126         fi
9127
9128         echo $count
9129 }
9130
9131 flvr_cnt_cli2mdt()
9132 {
9133         local flavor=$1
9134         local cnt
9135
9136         local clients=${CLIENTS:-$HOSTNAME}
9137
9138         for c in ${clients//,/ }; do
9139                 local output=$(do_node $c lctl get_param -n \
9140                          mdc.*-*-mdc-*.$PROC_CLI 2>/dev/null)
9141                 local tmpcnt=$(count_flvr "$output" $flavor)
9142
9143                 if $GSS_SK && [ $flavor != "null" ]; then
9144                         # tmpcnt=min(contexts,flavors) to ensure SK context is
9145                         # on
9146                         output=$(do_node $c lctl get_param -n \
9147                                  mdc.*-MDT*-mdc-*.$PROC_CON 2>/dev/null)
9148                         local outcon=$(count_contexts "$output")
9149
9150                         if [ "$outcon" -lt "$tmpcnt" ]; then
9151                                 tmpcnt=$outcon
9152                         fi
9153                 fi
9154                 cnt=$((cnt + tmpcnt))
9155         done
9156         echo $cnt
9157 }
9158
9159 flvr_dump_cli2mdt()
9160 {
9161         local clients=${CLIENTS:-$HOSTNAME}
9162
9163         for c in ${clients//,/ }; do
9164                 do_node $c lctl get_param \
9165                          mdc.*-*-mdc-*.$PROC_CLI 2>/dev/null
9166
9167                 if $GSS_SK; then
9168                         do_node $c lctl get_param \
9169                                  mdc.*-MDT*-mdc-*.$PROC_CON 2>/dev/null
9170                 fi
9171         done
9172 }
9173
9174 flvr_cnt_cli2ost()
9175 {
9176         local flavor=$1
9177         local cnt
9178
9179         local clients=${CLIENTS:-$HOSTNAME}
9180
9181         for c in ${clients//,/ }; do
9182                 # reconnect if idle
9183                 do_node $c lctl set_param osc.*.idle_connect=1 >/dev/null 2>&1
9184                 local output=$(do_node $c lctl get_param -n \
9185                          osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null)
9186                 local tmpcnt=$(count_flvr "$output" $flavor)
9187
9188                 if $GSS_SK && [ $flavor != "null" ]; then
9189                         # tmpcnt=min(contexts,flavors) to ensure SK context is on
9190                         output=$(do_node $c lctl get_param -n \
9191                                  osc.*OST*-osc-[^M][^D][^T]*.$PROC_CON 2>/dev/null)
9192                         local outcon=$(count_contexts "$output")
9193
9194                         if [ "$outcon" -lt "$tmpcnt" ]; then
9195                                 tmpcnt=$outcon
9196                         fi
9197                 fi
9198                 cnt=$((cnt + tmpcnt))
9199         done
9200         echo $cnt
9201 }
9202
9203 flvr_dump_cli2ost()
9204 {
9205         local clients=${CLIENTS:-$HOSTNAME}
9206
9207         for c in ${clients//,/ }; do
9208                 do_node $c lctl get_param \
9209                         osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null
9210
9211                 if $GSS_SK; then
9212                         do_node $c lctl get_param \
9213                                osc.*OST*-osc-[^M][^D][^T]*.$PROC_CON 2>/dev/null
9214                 fi
9215         done
9216 }
9217
9218 flvr_cnt_mdt2mdt()
9219 {
9220         local flavor=$1
9221         local cnt=0
9222
9223         if [ $MDSCOUNT -le 1 ]; then
9224                 echo 0
9225                 return
9226         fi
9227
9228         for num in `seq $MDSCOUNT`; do
9229                 local output=$(do_facet mds$num lctl get_param -n \
9230                         osp.*-MDT*osp-MDT*.$PROC_CLI 2>/dev/null)
9231                 local tmpcnt=$(count_flvr "$output" $flavor)
9232
9233                 if $GSS_SK && [ $flavor != "null" ]; then
9234                         # tmpcnt=min(contexts,flavors) to ensure SK context is on
9235                         output=$(do_facet mds$num lctl get_param -n \
9236                                 osp.*-MDT*osp-MDT*.$PROC_CON 2>/dev/null)
9237                         local outcon=$(count_contexts "$output")
9238
9239                         if [ "$outcon" -lt "$tmpcnt" ]; then
9240                                 tmpcnt=$outcon
9241                         fi
9242                 fi
9243                 cnt=$((cnt + tmpcnt))
9244         done
9245         echo $cnt;
9246 }
9247
9248 flvr_dump_mdt2mdt()
9249 {
9250         for num in `seq $MDSCOUNT`; do
9251                 do_facet mds$num lctl get_param \
9252                         osp.*-MDT*osp-MDT*.$PROC_CLI 2>/dev/null
9253
9254                 if $GSS_SK; then
9255                         do_facet mds$num lctl get_param \
9256                                 osp.*-MDT*osp-MDT*.$PROC_CON 2>/dev/null
9257                 fi
9258         done
9259 }
9260
9261 flvr_cnt_mdt2ost()
9262 {
9263         local flavor=$1
9264         local cnt=0
9265         local mdtosc
9266
9267         for num in `seq $MDSCOUNT`; do
9268                 mdtosc=$(get_mdtosc_proc_path mds$num)
9269                 mdtosc=${mdtosc/-MDT*/-MDT\*}
9270                 local output=$(do_facet mds$num lctl get_param -n \
9271                                 os[cp].$mdtosc.$PROC_CLI 2>/dev/null)
9272                 # Ensure SK context is on
9273                 local tmpcnt=$(count_flvr "$output" $flavor)
9274
9275                 if $GSS_SK && [ $flavor != "null" ]; then
9276                         output=$(do_facet mds$num lctl get_param -n \
9277                                  os[cp].$mdtosc.$PROC_CON 2>/dev/null)
9278                         local outcon=$(count_contexts "$output")
9279
9280                         if [ "$outcon" -lt "$tmpcnt" ]; then
9281                                 tmpcnt=$outcon
9282                         fi
9283                 fi
9284                 cnt=$((cnt + tmpcnt))
9285         done
9286         echo $cnt;
9287 }
9288
9289 flvr_dump_mdt2ost()
9290 {
9291         for num in `seq $MDSCOUNT`; do
9292                 mdtosc=$(get_mdtosc_proc_path mds$num)
9293                 mdtosc=${mdtosc/-MDT*/-MDT\*}
9294                 do_facet mds$num lctl get_param \
9295                                 os[cp].$mdtosc.$PROC_CLI 2>/dev/null
9296
9297                 if $GSS_SK; then
9298                         do_facet mds$num lctl get_param \
9299                                 os[cp].$mdtosc.$PROC_CON 2>/dev/null
9300                 fi
9301         done
9302 }
9303
9304 flvr_cnt_mgc2mgs()
9305 {
9306         local flavor=$1
9307
9308         local output=$(do_facet client lctl get_param -n mgc.*.$PROC_CLI \
9309                         2>/dev/null)
9310         count_flvr "$output" $flavor
9311 }
9312
9313 do_check_flavor()
9314 {
9315         local dir=$1        # from to
9316         local flavor=$2     # flavor expected
9317         local res=0
9318
9319         if [ $dir == "cli2mdt" ]; then
9320                 res=`flvr_cnt_cli2mdt $flavor`
9321         elif [ $dir == "cli2ost" ]; then
9322                 res=`flvr_cnt_cli2ost $flavor`
9323         elif [ $dir == "mdt2mdt" ]; then
9324                 res=`flvr_cnt_mdt2mdt $flavor`
9325         elif [ $dir == "mdt2ost" ]; then
9326                 res=`flvr_cnt_mdt2ost $flavor`
9327         elif [ $dir == "all2ost" ]; then
9328                 res1=`flvr_cnt_mdt2ost $flavor`
9329                 res2=`flvr_cnt_cli2ost $flavor`
9330                 res=$((res1 + res2))
9331         elif [ $dir == "all2mdt" ]; then
9332                 res1=`flvr_cnt_mdt2mdt $flavor`
9333                 res2=`flvr_cnt_cli2mdt $flavor`
9334                 res=$((res1 + res2))
9335         elif [ $dir == "all2all" ]; then
9336                 res1=`flvr_cnt_mdt2ost $flavor`
9337                 res2=`flvr_cnt_cli2ost $flavor`
9338                 res3=`flvr_cnt_mdt2mdt $flavor`
9339                 res4=`flvr_cnt_cli2mdt $flavor`
9340                 res=$((res1 + res2 + res3 + res4))
9341         fi
9342
9343         echo $res
9344 }
9345
9346 do_dump_imp_state()
9347 {
9348         local clients=${CLIENTS:-$HOSTNAME}
9349         local type=$1
9350
9351         for c in ${clients//,/ }; do
9352                 [ "$type" == "osc" ] &&
9353                         do_node $c lctl get_param osc.*.idle_timeout
9354                 do_node $c lctl get_param $type.*.import |
9355                         grep -E "name:|state:"
9356         done
9357 }
9358
9359 do_dump_flavor()
9360 {
9361         local dir=$1        # from to
9362
9363         if [ $dir == "cli2mdt" ]; then
9364                 do_dump_imp_state mdc
9365                 flvr_dump_cli2mdt
9366         elif [ $dir == "cli2ost" ]; then
9367                 do_dump_imp_state osc
9368                 flvr_dump_cli2ost
9369         elif [ $dir == "mdt2mdt" ]; then
9370                 flvr_dump_mdt2mdt
9371         elif [ $dir == "mdt2ost" ]; then
9372                 flvr_dump_mdt2ost
9373         elif [ $dir == "all2ost" ]; then
9374                 flvr_dump_mdt2ost
9375                 do_dump_imp_state osc
9376                 flvr_dump_cli2ost
9377         elif [ $dir == "all2mdt" ]; then
9378                 flvr_dump_mdt2mdt
9379                 do_dump_imp_state mdc
9380                 flvr_dump_cli2mdt
9381         elif [ $dir == "all2all" ]; then
9382                 flvr_dump_mdt2ost
9383                 do_dump_imp_state osc
9384                 flvr_dump_cli2ost
9385                 flvr_dump_mdt2mdt
9386                 do_dump_imp_state mdc
9387                 flvr_dump_cli2mdt
9388         fi
9389 }
9390
9391 wait_flavor()
9392 {
9393         local dir=$1        # from to
9394         local flavor=$2     # flavor expected
9395         local expect=${3:-$(calc_connection_cnt $dir)} # number expected
9396         local WAITFLAVOR_MAX=20 # how many retries before abort?
9397
9398         local res=0
9399         for ((i = 0; i < $WAITFLAVOR_MAX; i++)); do
9400                 echo -n "checking $dir..."
9401                 res=$(do_check_flavor $dir $flavor)
9402                 echo "found $res/$expect $flavor connections"
9403                 [ $res -ge $expect ] && return 0
9404                 sleep 4
9405         done
9406
9407         echo "Error checking $flavor of $dir: expect $expect, actual $res"
9408         do_nodes $(comma_list $(all_server_nodes)) "keyctl show"
9409         do_dump_flavor $dir
9410         if $dump; then
9411                 gather_logs $(comma_list $(nodes_list))
9412         fi
9413         return 1
9414 }
9415
9416 restore_to_default_flavor()
9417 {
9418         local proc="mgs.MGS.live.$FSNAME"
9419
9420         echo "restoring to default flavor..."
9421
9422         local nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |
9423                 grep ".srpc.flavor" | wc -l)
9424
9425         # remove all existing rules if any
9426         if [ $nrule -ne 0 ]; then
9427                 echo "$nrule existing rules"
9428                 for rule in $(do_facet mgs lctl get_param -n $proc 2>/dev/null |
9429                     grep ".srpc.flavor."); do
9430                         echo "remove rule: $rule"
9431                         spec=`echo $rule | awk -F = '{print $1}'`
9432                         do_facet mgs "$LCTL conf_param -d $spec"
9433                 done
9434         fi
9435
9436         # verify no rules left
9437         nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |
9438                 grep ".srpc.flavor." | wc -l)
9439         [ $nrule -ne 0 ] && error "still $nrule rules left"
9440
9441         # wait for default flavor to be applied
9442         if $GSS_SK; then
9443                 if $SK_S2S; then
9444                         set_rule $FSNAME any any $SK_FLAVOR
9445                         wait_flavor all2all $SK_FLAVOR
9446                 else
9447                         set_rule $FSNAME any cli2mdt $SK_FLAVOR
9448                         set_rule $FSNAME any cli2ost $SK_FLAVOR
9449                         wait_flavor cli2mdt $SK_FLAVOR
9450                         wait_flavor cli2ost $SK_FLAVOR
9451                 fi
9452                 echo "GSS_SK now at default flavor: $SK_FLAVOR"
9453         else
9454                 wait_flavor all2all null
9455         fi
9456 }
9457
9458 set_flavor_all()
9459 {
9460         local flavor=${1:-null}
9461
9462         echo "setting all flavor to $flavor"
9463
9464         # FIXME need parameter to this fn
9465         # and remove global vars
9466         local cnt_all2all=$(calc_connection_cnt all2all)
9467
9468         local res=$(do_check_flavor all2all $flavor)
9469         if [ $res -eq $cnt_all2all ]; then
9470                 echo "already have total $res $flavor connections"
9471                 return
9472         fi
9473
9474         echo "found $res $flavor out of total $cnt_all2all connections"
9475         restore_to_default_flavor
9476
9477         [[ $flavor = null ]] && return 0
9478
9479         if $GSS_SK && [ $flavor != "null" ]; then
9480                 if $SK_S2S; then
9481                         set_rule $FSNAME any any $flavor
9482                         wait_flavor all2all $flavor
9483                 else
9484                         set_rule $FSNAME any cli2mdt $flavor
9485                         set_rule $FSNAME any cli2ost $flavor
9486                         set_rule $FSNAME any mdt2ost null
9487                         set_rule $FSNAME any mdt2mdt null
9488                         wait_flavor cli2mdt $flavor
9489                         wait_flavor cli2ost $flavor
9490                 fi
9491                 echo "GSS_SK now at flavor: $flavor"
9492         else
9493                 set_rule $FSNAME any cli2mdt $flavor
9494                 set_rule $FSNAME any cli2ost $flavor
9495                 set_rule $FSNAME any mdt2ost null
9496                 set_rule $FSNAME any mdt2mdt null
9497                 wait_flavor cli2mdt $flavor
9498                 wait_flavor cli2ost $flavor
9499         fi
9500 }
9501
9502
9503 check_logdir() {
9504         local dir=$1
9505         # Checking for shared logdir
9506         if [ ! -d $dir ]; then
9507                 # Not found. Create local logdir
9508                 mkdir -p $dir
9509         else
9510                 touch $dir/check_file.$(hostname -s)
9511         fi
9512         return 0
9513 }
9514
9515 check_write_access() {
9516         local dir=$1
9517         local list=${2:-$(comma_list $(nodes_list))}
9518         local node
9519         local file
9520
9521         for node in ${list//,/ }; do
9522                 file=$dir/check_file.$(short_nodename $node)
9523                 if [[ ! -f "$file" ]]; then
9524                         # Logdir not accessible/writable from this node.
9525                         return 1
9526                 fi
9527                 rm -f $file || return 1
9528         done
9529         return 0
9530 }
9531
9532 init_logging() {
9533         [[ -n $YAML_LOG ]] && return
9534         local save_umask=$(umask)
9535         umask 0000
9536
9537         export YAML_LOG=${LOGDIR}/results.yml
9538         mkdir -p $LOGDIR
9539         init_clients_lists
9540
9541         # If the yaml log already exists then we will just append to it
9542         if [ ! -f $YAML_LOG ]; then
9543                 if check_shared_dir $LOGDIR; then
9544                         touch $LOGDIR/shared
9545                         echo "Logging to shared log directory: $LOGDIR"
9546                 else
9547                         echo "Logging to local directory: $LOGDIR"
9548                 fi
9549
9550                 yml_nodes_file $LOGDIR >> $YAML_LOG
9551                 yml_results_file >> $YAML_LOG
9552         fi
9553
9554         umask $save_umask
9555
9556         # log actual client and server versions if needed for debugging
9557         log "Client: $(lustre_build_version client)"
9558         log "MDS: $(lustre_build_version mds1)"
9559         log "OSS: $(lustre_build_version ost1)"
9560 }
9561
9562 log_test() {
9563         yml_log_test $1 >> $YAML_LOG
9564 }
9565
9566 log_test_status() {
9567         yml_log_test_status "$@" >> $YAML_LOG
9568 }
9569
9570 log_sub_test_begin() {
9571         yml_log_sub_test_begin "$@" >> $YAML_LOG
9572 }
9573
9574 log_sub_test_end() {
9575         yml_log_sub_test_end "$@" >> $YAML_LOG
9576 }
9577
9578 run_llverdev()
9579 {
9580         local dev=$1; shift
9581         local llverdev_opts="$*"
9582         local devname=$(basename $dev)
9583         local size=$(awk "/$devname$/ {print \$3}" /proc/partitions)
9584         # loop devices aren't in /proc/partitions
9585         [[ -z "$size" ]] && size=$(stat -c %s $dev)
9586
9587         local size_gb=$((size / 1024 / 1024)) # Gb
9588
9589         local partial_arg=""
9590         # Run in partial (fast) mode if the size of a partition > 1 GB
9591         (( $size == 0 || $size_gb > 1 )) && partial_arg="-p"
9592
9593         llverdev --force $partial_arg $llverdev_opts $dev
9594 }
9595
9596 run_llverfs()
9597 {
9598         local dir=$1
9599         local llverfs_opts=$2
9600         local use_partial_arg=$3
9601         local partial_arg=""
9602         local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB
9603
9604         # Run in partial (fast) mode if the size of a partition > 1 GB
9605         [ "x$use_partial_arg" != "xno" ] && [ $size -gt 1 ] && partial_arg="-p"
9606
9607         llverfs $partial_arg $llverfs_opts $dir
9608 }
9609
9610 run_sgpdd () {
9611         local devs=${1//,/ }
9612         shift
9613         local params=$@
9614         local rslt=$TMP/sgpdd_survey
9615
9616         # sgpdd-survey cleanups ${rslt}.* files
9617
9618         local cmd="rslt=$rslt $params scsidevs=\"$devs\" $SGPDDSURVEY"
9619         echo + $cmd
9620         eval $cmd
9621         cat ${rslt}.detail
9622 }
9623
9624 # returns the canonical name for an ldiskfs device
9625 ldiskfs_canon() {
9626         local dev="$1"
9627         local facet="$2"
9628
9629         do_facet $facet "dv=\\\$($LCTL get_param -n $dev);
9630                          if foo=\\\$(lvdisplay -c \\\$dv 2>/dev/null); then
9631                                 echo dm-\\\${foo##*:};
9632                          else
9633                                 name=\\\$(basename \\\$dv);
9634                                 if [[ \\\$name = *flakey* ]]; then
9635                                         name=\\\$(lsblk -o NAME,KNAME |
9636                                                 awk /\\\$name/'{print \\\$NF}');
9637                                 fi;
9638                                 echo \\\$name;
9639                          fi;"
9640 }
9641
9642 is_sanity_benchmark() {
9643         local benchmarks="dbench bonnie iozone fsx"
9644         local suite=$1
9645
9646         for b in $benchmarks; do
9647                 if [ "$b" == "$suite" ]; then
9648                         return 0
9649                 fi
9650         done
9651         return 1
9652 }
9653
9654 min_ost_size () {
9655         $LFS df | grep OST | awk '{print $4}' | sort -un | head -1
9656 }
9657
9658 #
9659 # Get the available size (KB) of a given obd target.
9660 #
9661 get_obd_size() {
9662         local facet=$1
9663         local obd=$2
9664         local size
9665
9666         [[ $facet != client ]] || return 0
9667
9668         size=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)
9669         echo -n $size
9670 }
9671
9672 #
9673 # Get the page size (bytes) on a given facet node.
9674 # The local client page_size is directly available in PAGE_SIZE.
9675 #
9676 get_page_size() {
9677         local facet=$1
9678         local page_size=$(getconf PAGE_SIZE 2>/dev/null)
9679
9680         [ -z "$CLIENTONLY" -a "$facet" != "client" ] &&
9681                 page_size=$(do_facet $facet getconf PAGE_SIZE)
9682         echo -n ${page_size:-4096}
9683 }
9684
9685 #
9686 # Get the block count of the filesystem.
9687 #
9688 get_block_count() {
9689         local facet=$1
9690         local device=$2
9691         local count
9692
9693         [ -z "$CLIENTONLY" ] &&
9694                 count=$(do_facet $facet "$DUMPE2FS -h $device 2>&1" |
9695                         awk '/^Block count:/ {print $3}')
9696         echo -n ${count:-0}
9697 }
9698
9699 # Check whether the "ea_inode" feature is enabled or not, to allow
9700 # ldiskfs xattrs over one block in size.  Allow both the historical
9701 # Lustre feature name (large_xattr) and the upstream name (ea_inode).
9702 large_xattr_enabled() {
9703         [[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 0
9704
9705         local mds_dev=$(mdsdevname ${SINGLEMDS//mds/})
9706
9707         do_facet $SINGLEMDS "$DUMPE2FS -h $mds_dev 2>&1 |
9708                 grep -E -q '(ea_inode|large_xattr)'"
9709         return ${PIPESTATUS[0]}
9710 }
9711
9712 # Get the maximum xattr size supported by the filesystem.
9713 max_xattr_size() {
9714         $LCTL get_param -n llite.*.max_easize
9715 }
9716
9717 # Dump the value of the named xattr from a file.
9718 get_xattr_value() {
9719         local xattr_name=$1
9720         local file=$2
9721
9722         echo "$(getfattr -n $xattr_name --absolute-names --only-values $file)"
9723 }
9724
9725 # Generate a string with size of $size bytes.
9726 generate_string() {
9727         local size=${1:-1024} # in bytes
9728
9729         echo "$(head -c $size < /dev/zero | tr '\0' y)"
9730 }
9731
9732 reformat_external_journal() {
9733         local facet=$1
9734         local var
9735
9736         var=${facet}_JRN
9737         local varbs=${facet}_BLOCKSIZE
9738         if [ -n "${!var}" ]; then
9739                 local rcmd="do_facet $facet"
9740                 local bs=${!varbs:-$BLCKSIZE}
9741
9742                 bs="-b $bs"
9743                 echo "reformat external journal on $facet:${!var}"
9744                 ${rcmd} mke2fs -O journal_dev $bs ${!var} || return 1
9745         fi
9746 }
9747
9748 # MDT file-level backup/restore
9749 mds_backup_restore() {
9750         local facet=$1
9751         local igif=$2
9752         local devname=$(mdsdevname $(facet_number $facet))
9753         local mntpt=$(facet_mntpt brpt)
9754         local rcmd="do_facet $facet"
9755         local metadata=${TMP}/backup_restore.tgz
9756         local opts=${MDS_MOUNT_FS_OPTS}
9757         local svc=${facet}_svc
9758
9759         if ! ${rcmd} test -b ${devname}; then
9760                 opts=$(csa_add "$opts" -o loop)
9761         fi
9762
9763         echo "file-level backup/restore on $facet:${devname}"
9764
9765         # step 1: build mount point
9766         ${rcmd} mkdir -p $mntpt
9767         # step 2: cleanup old backup
9768         ${rcmd} rm -f $metadata
9769         # step 3: mount dev
9770         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 3
9771         if [ ! -z $igif ]; then
9772                 # step 3.5: rm .lustre
9773                 ${rcmd} rm -rf $mntpt/ROOT/.lustre || return 3
9774         fi
9775         # step 4: backup metadata
9776         echo "backup data"
9777         ${rcmd} tar zcf $metadata --xattrs --xattrs-include="trusted.*" \
9778                 --sparse -C $mntpt/ . > /dev/null 2>&1 || return 4
9779         # step 5: umount
9780         ${rcmd} $UMOUNT $mntpt || return 5
9781         # step 6: reformat dev
9782         echo "reformat new device"
9783         format_mdt $(facet_number $facet)
9784         # step 7: mount dev
9785         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7
9786         # step 8: restore metadata
9787         echo "restore data"
9788         ${rcmd} tar zxfp $metadata --xattrs --xattrs-include="trusted.*" \
9789                 --sparse -C $mntpt > /dev/null 2>&1 || return 8
9790         # step 9: remove recovery logs
9791         echo "remove recovery logs"
9792         ${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS
9793         # step 10: umount dev
9794         ${rcmd} $UMOUNT $mntpt || return 10
9795         # step 11: cleanup tmp backup
9796         ${rcmd} rm -f $metaea $metadata
9797         # step 12: reset device label - it's not virgin on
9798         ${rcmd} e2label $devname ${!svc}
9799 }
9800
9801 # remove OI files
9802 mds_remove_ois() {
9803         local facet=$1
9804         local idx=$2
9805         local devname=$(mdsdevname $(facet_number $facet))
9806         local mntpt=$(facet_mntpt brpt)
9807         local rcmd="do_facet $facet"
9808         local opts=${MDS_MOUNT_FS_OPTS}
9809
9810         if ! ${rcmd} test -b ${devname}; then
9811                 opts=$(csa_add "$opts" -o loop)
9812         fi
9813
9814         echo "removing OI files on $facet: idx=${idx}"
9815
9816         # step 1: build mount point
9817         ${rcmd} mkdir -p $mntpt
9818         # step 2: mount dev
9819         ${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1
9820         if [ -z $idx ]; then
9821                 # step 3: remove all OI files
9822                 ${rcmd} rm -fv $mntpt/oi.16*
9823         elif [ $idx -lt 2 ]; then
9824                 ${rcmd} rm -fv $mntpt/oi.16.${idx}
9825         else
9826                 local i
9827
9828                 # others, rm oi.16.[idx, idx * idx, idx ** ...]
9829                 for ((i=${idx}; i<64; i=$((i * idx)))); do
9830                         ${rcmd} rm -fv $mntpt/oi.16.${i}
9831                 done
9832         fi
9833         # step 4: umount
9834         ${rcmd} $UMOUNT $mntpt || return 2
9835         # OI files will be recreated when mounted as lustre next time.
9836 }
9837
9838 # generate maloo upload-able log file name
9839 # \param logname specify unique part of file name
9840 generate_logname() {
9841         local logname=${1:-"default_logname"}
9842
9843         echo "$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log"
9844 }
9845
9846 # make directory on different MDTs
9847 test_mkdir() {
9848         local path
9849         local p_option
9850         local hash_type
9851         local hash_name=("all_char" "fnv_1a_64" "crush")
9852         local dirstripe_count=${DIRSTRIPE_COUNT:-"2"}
9853         local dirstripe_index=${DIRSTRIPE_INDEX:-$((base % $MDSCOUNT))}
9854         local OPTIND=1
9855         local overstripe_count
9856         local stripe_command="-c"
9857
9858         (( $MDS1_VERSION > $(version_code 2.15.0) )) &&
9859                 hash_name+=("crush2")
9860
9861         while getopts "c:C:H:i:p" opt; do
9862                 case $opt in
9863                         c) dirstripe_count=$OPTARG;;
9864                         C) overstripe_count=$OPTARG;;
9865                         H) hash_type=$OPTARG;;
9866                         i) dirstripe_index=$OPTARG;;
9867                         p) p_option="-p";;
9868                         \?) error "only support -c -H -i -p";;
9869                 esac
9870         done
9871
9872         shift $((OPTIND - 1))
9873         [ $# -eq 1 ] || error "Only creating single directory is supported"
9874         path="$*"
9875
9876         local parent=$(dirname $path)
9877         if [ "$p_option" == "-p" ]; then
9878                 [ -d $path ] && return 0
9879                 if [ ! -d ${parent} ]; then
9880                         mkdir -p ${parent} ||
9881                                 error "mkdir parent '$parent' failed"
9882                 fi
9883         fi
9884
9885         if [[ -n "$overstripe_count" ]]; then
9886                 stripe_command="-C"
9887                 dirstripe_count=$overstripe_count
9888         fi
9889
9890         if [ $MDSCOUNT -le 1 ] || ! is_lustre ${parent}; then
9891                 mkdir $path || error "mkdir '$path' failed"
9892         else
9893                 local mdt_index
9894
9895                 if [ $dirstripe_index -eq -1 ]; then
9896                         mdt_index=$((base % MDSCOUNT))
9897                 else
9898                         mdt_index=$dirstripe_index
9899                 fi
9900
9901                 # randomly choose hash type
9902                 [ -z "$hash_type" ] &&
9903                         hash_type=${hash_name[$((RANDOM % ${#hash_name[@]}))]}
9904
9905                 if (($MDS1_VERSION >= $(version_code 2.8.0))); then
9906                         if [ $dirstripe_count -eq -1 ]; then
9907                                 dirstripe_count=$((RANDOM % MDSCOUNT + 1))
9908                         fi
9909                 else
9910                         dirstripe_count=1
9911                 fi
9912
9913                 echo "striped dir -i$mdt_index $stripe_command$dirstripe_count -H $hash_type $path"
9914                 $LFS mkdir -i$mdt_index $stripe_command$dirstripe_count -H $hash_type $path ||
9915                         error "mkdir -i $mdt_index $stripe_command$dirstripe_count -H $hash_type $path failed"
9916         fi
9917 }
9918
9919 # free_fd: find the smallest and not in use file descriptor [above @last_fd]
9920 #
9921 # If called many times, passing @last_fd will avoid repeated searching
9922 # already-open FDs repeatedly if we know they are still in use.
9923 #
9924 # usage: free_fd [last_fd]
9925 free_fd()
9926 {
9927         local max_fd=$(ulimit -n)
9928         local fd=$((${1:-2} + 1))
9929
9930         while [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do
9931                 ((++fd))
9932         done
9933         [ $fd -lt $max_fd ] || error "finding free file descriptor failed"
9934         echo $fd
9935 }
9936
9937 check_mount_and_prep()
9938 {
9939         is_mounted $MOUNT || setupall
9940
9941         rm -rf $DIR/[df][0-9]* || error "Fail to cleanup the env!"
9942         mkdir_on_mdt0 $DIR/$tdir || error "Fail to mkdir $DIR/$tdir."
9943         for idx in $(seq $MDSCOUNT); do
9944                 local name="MDT$(printf '%04x' $((idx - 1)))"
9945                 rm -rf $MOUNT/.lustre/lost+found/$name/*
9946         done
9947 }
9948
9949 # calcule how many ost-objects to be created.
9950 precreated_ost_obj_count()
9951 {
9952         local mdt_idx=$1
9953         local ost_idx=$2
9954         local mdt_name="MDT$(printf '%04x' $mdt_idx)"
9955         local ost_name="OST$(printf '%04x' $ost_idx)"
9956         local proc_path="${FSNAME}-${ost_name}-osc-${mdt_name}"
9957         local last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
9958                         osp.$proc_path.prealloc_last_id)
9959         local next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \
9960                         osp.$proc_path.prealloc_next_id)
9961         echo $((last_id - next_id + 1))
9962 }
9963
9964 check_file_in_pool()
9965 {
9966         local file=$1
9967         local pool=$2
9968         local tlist="$3"
9969         local res=$($LFS getstripe $file | grep 0x | cut -f2)
9970         for i in $res
9971         do
9972                 for t in $tlist ; do
9973                         [ "$i" -eq "$t" ] && continue 2
9974                 done
9975
9976                 echo "pool list: $tlist"
9977                 echo "striping: $res"
9978                 error_noexit "$file not allocated in $pool"
9979                 return 1
9980         done
9981         return 0
9982 }
9983
9984 pool_add() {
9985         echo "Creating new pool"
9986         local pool=$1
9987
9988         create_pool $FSNAME.$pool ||
9989                 { error_noexit "No pool created, result code $?"; return 1; }
9990         [ $($LFS pool_list $FSNAME | grep -c "$FSNAME.${pool}\$") -eq 1 ] ||
9991                 { error_noexit "$pool not in lfs pool_list"; return 2; }
9992 }
9993
9994 pool_add_targets() {
9995         echo "Adding targets to pool"
9996         local pool=$1
9997         local first=$2
9998         local last=$3
9999         local step=${4:-1}
10000
10001         if [ -z $last ]; then
10002                 local list=$first
10003                 last=$first
10004         else
10005                 local list=$(seq $first $step $last)
10006         fi
10007
10008         local t=$(for i in $list; do printf "$FSNAME-OST%04x_UUID " $i; done)
10009         local tg=$(for i in $list;
10010                 do printf -- "-e $FSNAME-OST%04x_UUID " $i; done)
10011         local firstx=$(printf "%04x" $first)
10012         local lastx=$(printf "%04x" $last)
10013
10014         do_facet mgs $LCTL pool_add \
10015                 $FSNAME.$pool $FSNAME-OST[$firstx-$lastx/$step]
10016         # ignore EEXIST(17)
10017         if (( $? != 0 && $? != 17 )); then
10018                 error_noexit "pool_add $FSNAME-OST[$firstx-$lastx/$step] failed"
10019                 return 3
10020         fi
10021
10022         # wait for OSTs to be added to the pool
10023         for mds_id in $(seq $MDSCOUNT); do
10024                 local mdt_id=$((mds_id-1))
10025                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
10026                 wait_update_facet mds$mds_id \
10027                         "lctl get_param -n lod.$lodname.pools.$pool |
10028                                 grep $tg | sort -u | tr '\n' ' '" "$t" || {
10029                         error_noexit "mds$mds_id: Add to pool failed"
10030                         return 2
10031                 }
10032         done
10033         wait_update $HOSTNAME "lctl get_param -n lov.$FSNAME-*.pools.$pool |
10034                         grep $tg | sort -u | tr '\n' ' ' " "$t" || {
10035                 error_noexit "Add to pool failed"
10036                 return 1
10037         }
10038 }
10039
10040 pool_set_dir() {
10041         local pool=$1
10042         local tdir=$2
10043         echo "Setting pool on directory $tdir"
10044
10045         $LFS setstripe -c 2 -p $pool $tdir && return 0
10046
10047         error_noexit "Cannot set pool $pool to $tdir"
10048         return 1
10049 }
10050
10051 pool_check_dir() {
10052         local pool=$1
10053         local tdir=$2
10054         echo "Checking pool on directory $tdir"
10055
10056         local res=$($LFS getstripe --pool $tdir | sed "s/\s*$//")
10057         [ "$res" = "$pool" ] && return 0
10058
10059         error_noexit "Pool on '$tdir' is '$res', not '$pool'"
10060         return 1
10061 }
10062
10063 pool_dir_rel_path() {
10064         echo "Testing relative path works well"
10065         local pool=$1
10066         local tdir=$2
10067         local root=$3
10068
10069         mkdir -p $root/$tdir/$tdir
10070         cd $root/$tdir
10071         pool_set_dir $pool $tdir          || return 1
10072         pool_set_dir $pool ./$tdir        || return 2
10073         pool_set_dir $pool ../$tdir       || return 3
10074         pool_set_dir $pool ../$tdir/$tdir || return 4
10075         rm -rf $tdir; cd - > /dev/null
10076 }
10077
10078 pool_alloc_files() {
10079         echo "Checking files allocation from directory pool"
10080         local pool=$1
10081         local tdir=$2
10082         local count=$3
10083         local tlist="$4"
10084
10085         local failed=0
10086         for i in $(seq -w 1 $count)
10087         do
10088                 local file=$tdir/file-$i
10089                 touch $file
10090                 check_file_in_pool $file $pool "$tlist" || \
10091                         failed=$((failed + 1))
10092         done
10093         [ "$failed" = 0 ] && return 0
10094
10095         error_noexit "$failed files not allocated in $pool"
10096         return 1
10097 }
10098
10099 pool_create_files() {
10100         echo "Creating files in pool"
10101         local pool=$1
10102         local tdir=$2
10103         local count=$3
10104         local tlist="$4"
10105
10106         mkdir -p $tdir
10107         local failed=0
10108         for i in $(seq -w 1 $count)
10109         do
10110                 local file=$tdir/spoo-$i
10111                 $LFS setstripe -p $pool $file
10112                 check_file_in_pool $file $pool "$tlist" || \
10113                         failed=$((failed + 1))
10114         done
10115         [ "$failed" = 0 ] && return 0
10116
10117         error_noexit "$failed files not allocated in $pool"
10118         return 1
10119 }
10120
10121 pool_lfs_df() {
10122         echo "Checking 'lfs df' output"
10123         local pool=$1
10124
10125         local t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |
10126                         tr '\n' ' ')
10127         local res=$($LFS df --pool $FSNAME.$pool |
10128                         awk '{print $1}' |
10129                         grep "$FSNAME-OST" |
10130                         tr '\n' ' ')
10131         [ "$res" = "$t" ] && return 0
10132
10133         error_noexit "Pools OSTs '$t' is not '$res' that lfs df reports"
10134         return 1
10135 }
10136
10137 pool_file_rel_path() {
10138         echo "Creating files in a pool with relative pathname"
10139         local pool=$1
10140         local tdir=$2
10141
10142         mkdir -p $tdir ||
10143                 { error_noexit "unable to create $tdir"; return 1 ; }
10144         local file="/..$tdir/$tfile-1"
10145         $LFS setstripe -p $pool $file ||
10146                 { error_noexit "unable to create $file" ; return 2 ; }
10147
10148         cd $tdir
10149         $LFS setstripe -p $pool $tfile-2 || {
10150                 error_noexit "unable to create $tfile-2 in $tdir"
10151                 return 3
10152         }
10153 }
10154
10155 pool_remove_first_target() {
10156         echo "Removing first target from a pool"
10157         pool_remove_target $1 -1
10158 }
10159
10160 pool_remove_target() {
10161         local pool=$1
10162         local index=$2
10163
10164         local pname="lov.$FSNAME-*.pools.$pool"
10165         if [ $index -eq -1 ]; then
10166                 local t=$($LCTL get_param -n $pname | head -1)
10167         else
10168                 local t=$(printf "$FSNAME-OST%04x_UUID" $index)
10169         fi
10170
10171         echo "Removing $t from $pool"
10172         do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
10173         for mds_id in $(seq $MDSCOUNT); do
10174                 local mdt_id=$((mds_id-1))
10175                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
10176                 wait_update_facet mds$mds_id \
10177                         "lctl get_param -n lod.$lodname.pools.$pool |
10178                                 grep $t" "" || {
10179                         error_noexit "mds$mds_id: $t not removed from" \
10180                         "$FSNAME.$pool"
10181                         return 2
10182                 }
10183         done
10184         wait_update $HOSTNAME "lctl get_param -n $pname | grep $t" "" || {
10185                 error_noexit "$t not removed from $FSNAME.$pool"
10186                 return 1
10187         }
10188 }
10189
10190 pool_remove_all_targets() {
10191         echo "Removing all targets from pool"
10192         local pool=$1
10193         local file=$2
10194         local pname="lov.$FSNAME-*.pools.$pool"
10195         for t in $($LCTL get_param -n $pname | sort -u)
10196         do
10197                 do_facet mgs $LCTL pool_remove $FSNAME.$pool $t
10198         done
10199         for mds_id in $(seq $MDSCOUNT); do
10200                 local mdt_id=$((mds_id-1))
10201                 local lodname=$FSNAME-MDT$(printf "%04x" $mdt_id)-mdtlov
10202                 wait_update_facet mds$mds_id "lctl get_param -n \
10203                         lod.$lodname.pools.$pool" "" || {
10204                         error_noexit "mds$mds_id: Pool $pool not drained"
10205                         return 4
10206                 }
10207         done
10208         wait_update $HOSTNAME "lctl get_param -n $pname" "" || {
10209                 error_noexit "Pool $FSNAME.$pool cannot be drained"
10210                 return 1
10211         }
10212         # striping on an empty/nonexistant pool should fall back
10213         # to "pool of everything"
10214         touch $file || {
10215                 error_noexit "failed to use fallback striping for empty pool"
10216                 return 2
10217         }
10218         # setstripe on an empty pool should fail
10219         $LFS setstripe -p $pool $file 2>/dev/null && {
10220                 error_noexit "expected failure when creating file" \
10221                                                         "with empty pool"
10222                 return 3
10223         }
10224         return 0
10225 }
10226
10227 pool_remove() {
10228         echo "Destroying pool"
10229         local pool=$1
10230         local file=$2
10231
10232         do_facet mgs $LCTL pool_destroy $FSNAME.$pool
10233
10234         sleep 2
10235         # striping on an empty/nonexistant pool should fall back
10236         # to "pool of everything"
10237         touch $file || {
10238                 error_noexit "failed to use fallback striping for missing pool"
10239                 return 1
10240         }
10241         # setstripe on an empty pool should fail
10242         $LFS setstripe -p $pool $file 2>/dev/null && {
10243                 error_noexit "expected failure when creating file" \
10244                                                         "with missing pool"
10245                 return 2
10246         }
10247
10248         # get param should return err once pool is gone
10249         if wait_update $HOSTNAME "lctl get_param -n \
10250                 lov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo" "foo"
10251         then
10252                 remove_pool_from_list $FSNAME.$pool
10253                 return 0
10254         fi
10255         error_noexit "Pool $FSNAME.$pool is not destroyed"
10256         return 3
10257 }
10258
10259 # Get and check the actual stripe count of one file.
10260 # Usage: check_stripe_count <file> <expected_stripe_count>
10261 check_stripe_count() {
10262         local file=$1
10263         local expected=$2
10264         local actual
10265
10266         [[ -z "$file" || -z "$expected" ]] &&
10267                 error "check_stripe_count: invalid argument"
10268
10269         local cmd="$LFS getstripe -c $file"
10270         actual=$($cmd) || error "$cmd failed"
10271         actual=${actual%% *}
10272
10273         if [[ $actual -ne $expected ]]; then
10274                 [[ $expected -eq -1 ]] || { $LFS getstripe $file;
10275                         error "$cmd not expected ($expected): found $actual"; }
10276                 [[ $actual -eq $OSTCOUNT ]] || { $LFS getstripe $file;
10277                         error "$cmd not OST count ($OSTCOUNT): found $actual"; }
10278         fi
10279 }
10280
10281 # Get and check the actual list of OST indices on one file.
10282 # Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>
10283 check_obdidx() {
10284         local file=$1
10285         local expected=$2
10286         local obdidx
10287
10288         [[ -z "$file" || -z "$expected" ]] &&
10289                 error "check_obdidx: invalid argument!"
10290
10291         obdidx=$(comma_list $($LFS getstripe $file | grep -A $OSTCOUNT obdidx |
10292                               grep -v obdidx | awk '{print $1}' | xargs))
10293
10294         [[ $obdidx = $expected ]] ||
10295                 error "list of OST indices on $file is $obdidx," \
10296                       "should be $expected"
10297 }
10298
10299 # Get and check the actual OST index of the first stripe on one file.
10300 # Usage: check_start_ost_idx <file> <expected_start_ost_idx>
10301 check_start_ost_idx() {
10302         local file=$1
10303         local expected=$2
10304         local start_ost_idx
10305
10306         [[ -z "$file" || -z "$expected" ]] &&
10307                 error "check_start_ost_idx: invalid argument!"
10308
10309         start_ost_idx=$($LFS getstripe $file | grep -A 1 obdidx |
10310                          grep -v obdidx | awk '{print $1}')
10311
10312         [[ $start_ost_idx = $expected ]] ||
10313                 error "OST index of the first stripe on $file is" \
10314                       "$start_ost_idx, should be $expected"
10315 }
10316
10317 killall_process () {
10318         local clients=${1:-$(hostname)}
10319         local name=$2
10320         local signal=$3
10321         local rc=0
10322
10323         do_nodes $clients "killall $signal $name"
10324 }
10325
10326 lsnapshot_create()
10327 {
10328         do_facet mgs "$LCTL snapshot_create -F $FSNAME $*"
10329 }
10330
10331 lsnapshot_destroy()
10332 {
10333         do_facet mgs "$LCTL snapshot_destroy -F $FSNAME $*"
10334 }
10335
10336 lsnapshot_modify()
10337 {
10338         do_facet mgs "$LCTL snapshot_modify -F $FSNAME $*"
10339 }
10340
10341 lsnapshot_list()
10342 {
10343         do_facet mgs "$LCTL snapshot_list -F $FSNAME $*"
10344 }
10345
10346 lsnapshot_mount()
10347 {
10348         do_facet mgs "$LCTL snapshot_mount -F $FSNAME $*"
10349 }
10350
10351 lsnapshot_umount()
10352 {
10353         do_facet mgs "$LCTL snapshot_umount -F $FSNAME $*"
10354 }
10355
10356 lss_err()
10357 {
10358         local msg=$1
10359
10360         do_facet mgs "cat $LSNAPSHOT_LOG"
10361         error $msg
10362 }
10363
10364 lss_cleanup()
10365 {
10366         echo "Cleaning test environment ..."
10367
10368         # Every lsnapshot command takes exclusive lock with others,
10369         # so can NOT destroy the snapshot during list with 'xargs'.
10370         while true; do
10371                 local ssname=$(lsnapshot_list | grep snapshot_name |
10372                         grep lss_ | awk '{ print $2 }' | head -n 1)
10373                 [ -z "$ssname" ] && break
10374
10375                 lsnapshot_destroy -n $ssname -f ||
10376                         lss_err "Fail to destroy $ssname by force"
10377         done
10378 }
10379
10380 lss_gen_conf_one()
10381 {
10382         local facet=$1
10383         local role=$2
10384         local idx=$3
10385
10386         local host=$(facet_active_host $facet)
10387         local dir=$(dirname $(facet_vdevice $facet))
10388         local pool=$(zpool_name $facet)
10389         local lfsname=$(zfs_local_fsname $facet)
10390         local label=${FSNAME}-${role}$(printf '%04x' $idx)
10391
10392         do_facet mgs \
10393                 "echo '$host - $label zfs:${dir}/${pool}/${lfsname} - -' >> \
10394                 $LSNAPSHOT_CONF"
10395 }
10396
10397 lss_gen_conf()
10398 {
10399         do_facet mgs "rm -f $LSNAPSHOT_CONF"
10400         echo "Generating $LSNAPSHOT_CONF on MGS ..."
10401
10402         if ! combined_mgs_mds ; then
10403                 [ $(facet_fstype mgs) != zfs ] &&
10404                         skip "Lustre snapshot 1 only works for ZFS backend"
10405
10406                 local host=$(facet_active_host mgs)
10407                 local dir=$(dirname $(facet_vdevice mgs))
10408                 local pool=$(zpool_name mgs)
10409                 local lfsname=$(zfs_local_fsname mgs)
10410
10411                 do_facet mgs \
10412                         "echo '$host - MGS zfs:${dir}/${pool}/${lfsname} - -' \
10413                         >> $LSNAPSHOT_CONF" || lss_err "generate lss conf (mgs)"
10414         fi
10415
10416         for num in `seq $MDSCOUNT`; do
10417                 [ $(facet_fstype mds$num) != zfs ] &&
10418                         skip "Lustre snapshot 1 only works for ZFS backend"
10419
10420                 lss_gen_conf_one mds$num MDT $((num - 1)) ||
10421                         lss_err "generate lss conf (mds$num)"
10422         done
10423
10424         for num in `seq $OSTCOUNT`; do
10425                 [ $(facet_fstype ost$num) != zfs ] &&
10426                         skip "Lustre snapshot 1 only works for ZFS backend"
10427
10428                 lss_gen_conf_one ost$num OST $((num - 1)) ||
10429                         lss_err "generate lss conf (ost$num)"
10430         done
10431
10432         do_facet mgs "cat $LSNAPSHOT_CONF"
10433 }
10434
10435 # Parse 'lfs getstripe -d <path_with_dir_name>' for non-composite dir
10436 parse_plain_dir_param()
10437 {
10438         local invalues=($1)
10439         local param=""
10440
10441         if [[ ${invalues[0]} =~ "stripe_count:" ]]; then
10442                 param="-c ${invalues[1]}"
10443         fi
10444         if [[ ${invalues[2]} =~ "stripe_size:" ]]; then
10445                 param="$param -S ${invalues[3]}"
10446         fi
10447         if [[ ${invalues[4]} =~ "pattern:" ]]; then
10448                 if [[ ${invalues[5]} =~ "stripe_offset:" ]]; then
10449                         param="$param -i ${invalues[6]}"
10450                 else
10451                         param="$param -L ${invalues[5]} -i ${invalues[7]}"
10452                 fi
10453         elif [[ ${invalues[4]} =~ "stripe_offset:" ]]; then
10454                 param="$param -i ${invalues[5]}"
10455         fi
10456         echo "$param"
10457 }
10458
10459 parse_plain_param()
10460 {
10461         local line=$1
10462         local val=$(awk '{print $2}' <<< $line)
10463
10464         if [[ $line =~ ^"lmm_stripe_count:" ]]; then
10465                 echo "-c $val"
10466         elif [[ $line =~ ^"lmm_stripe_size:" ]]; then
10467                 echo "-S $val"
10468         elif [[ $line =~ ^"lmm_stripe_offset:" && $SKIP_INDEX != yes ]]; then
10469                 echo "-i $val"
10470         elif [[ $line =~ ^"lmm_pattern:" ]]; then
10471                 echo "-L $val"
10472         fi
10473 }
10474
10475 parse_layout_param()
10476 {
10477         local mode=""
10478         local val=""
10479         local param=""
10480
10481         while read line; do
10482                 if [[ ! -z $line ]]; then
10483                         if [[ -z $mode ]]; then
10484                                 if [[ $line =~ ^"stripe_count:" ]]; then
10485                                         mode="plain_dir"
10486                                 elif [[ $line =~ ^"lmm_stripe_count:" ]]; then
10487                                         mode="plain_file"
10488                                 elif [[ $line =~ ^"lcm_layout_gen:" ]]; then
10489                                         mode="pfl"
10490                                 fi
10491                         fi
10492
10493                         if [[ $mode = "plain_dir" ]]; then
10494                                 param=$(parse_plain_dir_param "$line")
10495                         elif [[ $mode = "plain_file" ]]; then
10496                                 val=$(parse_plain_param "$line")
10497                                 [[ ! -z $val ]] && param="$param $val"
10498                         elif [[ $mode = "pfl" ]]; then
10499                                 val=$(echo $line | awk '{print $2}')
10500                                 if [[ $line =~ ^"lcme_extent.e_end:" ]]; then
10501                                         if [[ $val = "EOF" ]]; then
10502                                                 param="$param -E -1"
10503                                         else
10504                                                 param="$param -E $val"
10505                                         fi
10506                                 elif [[ $line =~ ^"stripe_count:" ]]; then
10507                                         # pfl dir
10508                                         val=$(parse_plain_dir_param "$line")
10509                                         param="$param $val"
10510                                 else
10511                                         #pfl file
10512                                         val=$(parse_plain_param "$line")
10513                                         [[ ! -z $val ]] && param="$param $val"
10514                                 fi
10515                         fi
10516                 fi
10517         done
10518         echo "$param"
10519 }
10520
10521 get_layout_param()
10522 {
10523         local param=$($LFS getstripe -d $1 | parse_layout_param)
10524         echo "$param"
10525 }
10526
10527 lfsck_verify_pfid()
10528 {
10529         local f
10530         local rc=0
10531
10532         # Cancel locks before setting lfsck_verify_pfid so that errors are more
10533         # controllable
10534         cancel_lru_locks mdc
10535         cancel_lru_locks osc
10536
10537         # make sure PFID is set correctly for files
10538         do_nodes $(comma_list $(osts_nodes)) \
10539                "$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=1"
10540
10541         for f in "$@"; do
10542                 cat $f &> /dev/nullA ||
10543                         { rc=$?; echo "verify $f failed"; break; }
10544         done
10545
10546         do_nodes $(comma_list $(osts_nodes)) \
10547                "$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=0"
10548         return $rc
10549 }
10550
10551 # check that clients "oscs" was evicted after "before"
10552 check_clients_evicted() {
10553         local before=$1
10554         shift
10555         local oscs=${@}
10556         local osc
10557         local rc=0
10558
10559         for osc in $oscs; do
10560                 echo "Check state for $osc"
10561                 local evicted=$(do_facet client $LCTL get_param osc.$osc.state |
10562                         tail -n 5 | awk -F"[ ,]" \
10563                         '/EVICTED/ { if (mx<$4) { mx=$4; } } END { print mx }')
10564                 if (($? == 0)) && (($evicted > $before)); then
10565                         echo "$osc is evicted at $evicted"
10566                 else
10567                         ((rc++))
10568                         echo "$osc was not evicted after $before:"
10569                         do_facet client $LCTL get_param osc.$osc.state |
10570                                 tail -n 8
10571                 fi
10572         done
10573
10574         [ $rc -eq 0 ] || error "client not evicted from OST"
10575 }
10576
10577 # check that clients OSCS current_state is FULL
10578 check_clients_full() {
10579         local timeout=$1
10580         shift
10581         local oscs=${@}
10582
10583         for osc in $oscs; do
10584                 wait_update_facet client \
10585                         "lctl get_param -n osc.$osc.state |
10586                         grep 'current_state: FULL'" \
10587                         "current_state: FULL" $timeout
10588                 [ $? -eq 0 ] || error "$osc state is not FULL"
10589         done
10590 }
10591
10592 #Changelogs
10593 __changelog_deregister() {
10594         local facet=$1
10595         local mdt="$(facet_svc $facet)"
10596         local cl_user=$2
10597         local rc=0
10598
10599         # skip cleanup if no user registered for this MDT
10600         [ -z "$cl_user" ] && echo "$mdt: no changelog user" && return 0
10601         # user is no longer registered, skip cleanup
10602         changelog_users "$facet" | grep -q "$cl_user" ||
10603                 { echo "$mdt: changelog user '$cl_user' not found"; return 0; }
10604
10605         # From this point, if any operation fails, it is an error
10606         __changelog_clear $facet $cl_user 0 ||
10607                 error_noexit "$mdt: changelog_clear $cl_user 0 fail: $rc"
10608         do_facet $facet $LCTL --device $mdt changelog_deregister $cl_user ||
10609                 error_noexit "$mdt: changelog_deregister '$cl_user' fail: $rc"
10610 }
10611
10612 declare -Ax CL_USERS
10613 changelog_register() {
10614         for M in $(seq $MDSCOUNT); do
10615                 local facet=mds$M
10616                 local mdt="$(facet_svc $facet)"
10617                 local cl_mask
10618
10619                 cl_mask=$(do_facet $facet $LCTL get_param \
10620                              mdd.${mdt}.changelog_mask -n)
10621                 stack_trap "do_facet $facet $LCTL \
10622                         set_param mdd.$mdt.changelog_mask=\'$cl_mask\' -n" EXIT
10623                 do_facet $facet $LCTL set_param mdd.$mdt.changelog_mask=+hsm ||
10624                         error "$mdt: changelog_mask=+hsm failed: $?"
10625
10626                 local cl_user
10627                 cl_user=$(do_facet $facet $LCTL --device $mdt \
10628                         changelog_register -n "$@") ||
10629                         error "$mdt: register changelog user failed: $?"
10630                 stack_trap "__changelog_deregister $facet $cl_user" EXIT
10631
10632                 stack_trap "CL_USERS[$facet]='${CL_USERS[$facet]}'" EXIT
10633                 # Bash does not support nested arrays, but the format of a
10634                 # cl_user is constrained enough to use whitespaces as separators
10635                 CL_USERS[$facet]+="$cl_user "
10636         done
10637         echo "Registered $MDSCOUNT changelog users: '${CL_USERS[*]% }'"
10638 }
10639
10640 changelog_deregister() {
10641         local cl_user
10642         # bash assoc arrays do not guarantee to list keys in created order
10643         # so reorder to get same order than in changelog_register()
10644         local cl_facets=$(echo "${!CL_USERS[@]}" | tr " " "\n" | sort |
10645                           tr "\n" " ")
10646
10647         for facet in $cl_facets; do
10648                 for cl_user in ${CL_USERS[$facet]}; do
10649                         __changelog_deregister $facet $cl_user || return $?
10650                 done
10651                 unset CL_USERS[$facet]
10652         done
10653 }
10654
10655 changelog_users() {
10656         local facet=$1
10657         local service=$(facet_svc $facet)
10658
10659         do_facet $facet $LCTL get_param -n mdd.$service.changelog_users
10660 }
10661
10662 changelog_user_rec() {
10663         local facet=$1
10664         local cl_user=$2
10665         local service=$(facet_svc $facet)
10666
10667         changelog_users $facet | awk '$1 == "'$cl_user'" { print $2 }'
10668 }
10669
10670 changelog_chmask() {
10671         local mask=$1
10672
10673         do_nodes $(comma_list $(mdts_nodes)) \
10674                 $LCTL set_param mdd.*.changelog_mask="$mask"
10675 }
10676
10677 # usage: __changelog_clear FACET CL_USER [+]INDEX
10678 __changelog_clear()
10679 {
10680         local facet=$1
10681         local mdt="$(facet_svc $facet)"
10682         local cl_user=$2
10683         local -i rec
10684
10685         case "$3" in
10686         +*)
10687                 # Remove the leading '+'
10688                 rec=${3:1}
10689                 rec+=$(changelog_user_rec $facet $cl_user)
10690                 ;;
10691         *)
10692                 rec=$3
10693                 ;;
10694         esac
10695
10696         if [ $rec -eq 0 ]; then
10697                 echo "$mdt: clear the changelog for $cl_user of all records"
10698         else
10699                 echo "$mdt: clear the changelog for $cl_user to record #$rec"
10700         fi
10701         $LFS changelog_clear $mdt $cl_user $rec
10702 }
10703
10704 # usage: changelog_clear [+]INDEX [facet]...
10705 #
10706 # If INDEX is prefixed with '+', increment every changelog user's record index
10707 # by INDEX. Otherwise, clear the changelog up to INDEX for every changelog
10708 # users.
10709 changelog_clear() {
10710         local rc
10711         local idx=$1
10712         shift
10713         local cl_facets="$@"
10714         # bash assoc arrays do not guarantee to list keys in created order
10715         # so reorder to get same order than in changelog_register()
10716         [[ -n "$cl_facets" ]] ||
10717                 cl_facets=$(echo "${!CL_USERS[@]}" | tr " " "\n" | sort |
10718                         tr "\n" " ")
10719         local cl_user
10720
10721         for facet in $cl_facets; do
10722                 for cl_user in ${CL_USERS[$facet]}; do
10723                         __changelog_clear $facet $cl_user $idx || rc=${rc:-$?}
10724                 done
10725         done
10726
10727         return ${rc:-0}
10728 }
10729
10730 changelog_dump() {
10731         local rc
10732
10733         for M in $(seq $MDSCOUNT); do
10734                 local facet=mds$M
10735                 local mdt="$(facet_svc $facet)"
10736                 local output
10737                 local ret
10738
10739                 output=$($LFS changelog $mdt)
10740                 ret=$?
10741                 if [ $ret -ne 0 ]; then
10742                         rc=${rc:-$ret}
10743                 elif [ -n "$output" ]; then
10744                         echo "$output" | sed -e 's/^/'$mdt'./'
10745                 fi
10746         done
10747
10748         return ${rc:-0}
10749 }
10750
10751 changelog_extract_field() {
10752         local cltype=$1
10753         local file=$2
10754         local identifier=$3
10755
10756         changelog_dump | gawk "/$cltype.*$file$/ {
10757                 print gensub(/^.* "$identifier'(\[[^\]]*\]).*$/,"\\1",1)}' |
10758                 tail -1
10759 }
10760
10761 # Prints a changelog record produced by "lfs changelog" as an associative array
10762 #
10763 # Example:
10764 # $> changelog2array 16 01CREAT 10:28:46.968438800 2018.03.09 0x0 \
10765 #                    t=[0x200000401:0x10:0x0] j=touch.501 ef=0xf u=501:501 \
10766 #                    nid=0@lo p=[0x200000007:0x1:0x0] blob
10767 # ([index]='16' [type]='CREAT' [time]='10:28:46.968438800'
10768 #  [date]='2018.03.09' [flags]=0x0 ['target-fid']='[0x200000401:0x10:0x0]'
10769 #  ['jobid']='touch.501' ['extra-flags']='0x0f' [uid]='0' ['gid']='0'
10770 #  ['nid']='0@lo' ['parent-fid']='[0x200000007:0x1:0x0]')
10771 #
10772 # Note that the changelog record is not quoted
10773 # Also note that the line breaks in the output were only added for readability
10774 #
10775 # Typically, you want to eval the output of the command to fill an actual
10776 # associative array, like this:
10777 # $> eval declare -A changelog=$(changelog2array $entry)
10778 #
10779 # It can then be accessed like any bash associative array:
10780 # $> echo "${changelog[index]}" "${changelog[type]}" "${changelog[flags]}"
10781 # 16 CREAT 0x0
10782 # $> echo "${changelog[uid]}":"${changelog[gid]}"
10783 # 501:501
10784 #
10785 changelog2array()
10786 {
10787         # Start the array
10788         printf '('
10789
10790         # A changelog, as printed by "lfs changelog" typically looks like this:
10791         # <index> <type> <time> <date> <flags> <key1=value1> <key2=value2> ...
10792
10793         # Parse the positional part of the changelog
10794
10795         # changelog_dump() prefixes records with their mdt's name
10796         local index="${1##*.}"
10797
10798         printf "[index]='%s' [type]='%s' [time]='%s' [date]='%s' [flags]='%s'" \
10799                "$index" "${2:2}" "$3" "$4" "$5"
10800
10801         # Parse the key/value part of the changelog
10802         for arg in "${@:5}"; do
10803                 # Check it matches a key=value syntax
10804                 [[ "$arg" =~ ^[[:alpha:]]+= ]] || continue
10805
10806                 local key="${arg%%=*}"
10807                 local value="${arg#*=}"
10808
10809                 case "$key" in
10810                 u)
10811                         # u is actually for uid AND gid: u=UID:GID
10812                         printf " [uid]='%s'" "${value%:*}"
10813                         key=gid
10814                         value="${value#*:}"
10815                         ;;
10816                 t)
10817                         key=target-fid
10818                         value="${value#[}"
10819                         value="${value%]}"
10820                         ;;
10821                 j)
10822                         key=jobid
10823                         ;;
10824                 p)
10825                         key=parent-fid
10826                         value="${value#[}"
10827                         value="${value%]}"
10828                         ;;
10829                 ef)
10830                         key=extra-flags
10831                         ;;
10832                 m)
10833                         key=mode
10834                         ;;
10835                 x)
10836                         key=xattr
10837                         ;;
10838                 *)
10839                         ;;
10840                 esac
10841
10842                 printf " ['%s']='%s'" "$key" "$value"
10843         done
10844
10845         # end the array
10846         printf ')'
10847 }
10848
10849 # Format and print a changelog record
10850 #
10851 # Interpreted sequences are:
10852 #       %%      a single %
10853 #       %f      the "flags" attribute of a changelog record
10854 __changelog_printf()
10855 {
10856         local format="$1"
10857
10858         local -i i
10859         for ((i = 0; i < ${#format}; i++)); do
10860                 local char="${format:$i:1}"
10861                 if [ "$char" != % ]; then
10862                         printf '%c' "$char"
10863                         continue
10864                 fi
10865
10866                 i+=1
10867                 char="${format:$i:1}"
10868                 case "$char" in
10869                 f)
10870                         printf '%s' "${changelog[flags]}"
10871                         ;;
10872                 %)
10873                         printf '%'
10874                         ;;
10875                 esac
10876         done
10877         printf '\n'
10878 }
10879
10880 # Filter changelog records
10881 changelog_find()
10882 {
10883         local -A filter
10884         local action='print'
10885         local format
10886
10887         while [ $# -gt 0 ]; do
10888                 case "$1" in
10889                 -print)
10890                         action='print'
10891                         ;;
10892                 -printf)
10893                         action='printf'
10894                         format="$2"
10895                         shift
10896                         ;;
10897                 -*)
10898                         filter[${1#-}]="$2"
10899                         shift
10900                         ;;
10901                 esac
10902                 shift
10903         done
10904
10905         local found=false
10906         local record
10907         changelog_dump | { while read -r record; do
10908                 eval local -A changelog=$(changelog2array $record)
10909                 for key in "${!filter[@]}"; do
10910                         case "$key" in
10911                         *)
10912                                 [ "${changelog[$key]}" == "${filter[$key]}" ]
10913                                 ;;
10914                         esac || continue 2
10915                 done
10916
10917                 found=true
10918
10919                 case "${action:-print}" in
10920                 print)
10921                         printf '%s\n' "$record"
10922                         ;;
10923                 printf)
10924                         __changelog_printf "$format"
10925                         ;;
10926                 esac
10927         done; $found; }
10928 }
10929
10930 restore_layout() {
10931         local dir=$1
10932         local layout=$2
10933
10934         [ ! -d "$dir" ] && return
10935
10936         [ -z "$layout" ] && {
10937                 $LFS setstripe -d $dir || error "error deleting stripe '$dir'"
10938                 return
10939         }
10940
10941         setfattr -n trusted.lov -v $layout $dir ||
10942                 error "error restoring layout '$layout' to '$dir'"
10943 }
10944
10945 # save the layout of a directory, the returned string will be used by
10946 # restore_layout() to restore the layout
10947 save_layout() {
10948         local dir=$1
10949         local str=$(getfattr -n trusted.lov --absolute-names -e hex $dir \
10950                     2> /dev/null | awk -F'=' '/trusted.lov/{ print $2 }')
10951         echo "$str"
10952 }
10953
10954 # save layout of a directory and restore it at exit
10955 save_layout_restore_at_exit() {
10956         local dir=$1
10957         local layout=$(save_layout $dir)
10958
10959         stack_trap "restore_layout $dir $layout" EXIT
10960 }
10961
10962 verify_yaml_layout() {
10963         local src=$1
10964         local dst=$2
10965         local temp=$3
10966         local msg_prefix=$4
10967
10968         echo "getstripe --yaml $src"
10969         $LFS getstripe --yaml $src > $temp || error "getstripe $src failed"
10970         echo "setstripe --yaml=$temp $dst"
10971         $LFS setstripe --yaml=$temp $dst|| error "setstripe $dst failed"
10972
10973         echo "compare"
10974         local layout1=$(get_layout_param $src)
10975         local layout2=$(get_layout_param $dst)
10976         # compare their layout info
10977         [ "$layout1" == "$layout2" ] ||
10978                 error "$msg_prefix $src/$dst layouts are not equal"
10979 }
10980
10981 is_project_quota_supported() {
10982         $ENABLE_PROJECT_QUOTAS || return 1
10983         [[ -z "$SAVE_PROJECT_SUPPORTED" ]] || return $SAVE_PROJECT_SUPPORTED
10984         local save_project_supported=1
10985
10986         [[ "$(facet_fstype $SINGLEMDS)" == "ldiskfs" &&
10987            $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.9.55) ]] &&
10988                 do_facet mds1 lfs --list-commands |& grep -q project &&
10989                         save_project_supported=0
10990
10991         [[ "$(facet_fstype $SINGLEMDS)" == "zfs" &&
10992            $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.10.53) ]] &&
10993                 do_facet mds1 $ZPOOL get all | grep -q project_quota &&
10994                         save_project_supported=0
10995
10996         # cache state of project quotas once instead of re-checking each time
10997         export SAVE_PROJECT_SUPPORTED=$save_project_supported
10998         echo "using SAVE_PROJECT_SUPPORTED=$SAVE_PROJECT_SUPPORTED"
10999
11000         return $save_project_supported
11001 }
11002
11003 # ZFS project quota enable/disable:
11004 #   This  feature  will  become  active as soon as it is enabled and will never
11005 #   return to being disabled. Each filesystem will be upgraded automatically
11006 #   when remounted or when [a] new file is created under that filesystem. The
11007 #   upgrade can also be triggered on filesystems via `zfs set version=current
11008 #   <pool/fs>`. The upgrade process runs in the background and may take a
11009 #   while to complete for the filesystems containing a large number of files.
11010 enable_project_quota() {
11011         is_project_quota_supported || return 0
11012         local zkeeper=${KEEP_ZPOOL}
11013         stack_trap "KEEP_ZPOOL=$zkeeper" EXIT
11014         KEEP_ZPOOL="true"
11015         stopall || error "failed to stopall (1)"
11016
11017         local zfeat_en="feature@project_quota=enabled"
11018         for facet in $(seq -f mds%g $MDSCOUNT) $(seq -f ost%g $OSTCOUNT); do
11019                 local facet_fstype=${facet:0:3}1_FSTYPE
11020                 local devname
11021
11022                 if [ "${!facet_fstype}" = "zfs" ]; then
11023                         devname=$(zpool_name ${facet})
11024                         do_facet ${facet} $ZPOOL set "$zfeat_en" $devname ||
11025                                 error "$ZPOOL set $zfeat_en $devname"
11026                 else
11027                         [ ${facet:0:3} == "mds" ] &&
11028                                 devname=$(mdsdevname ${facet:3}) ||
11029                                 devname=$(ostdevname ${facet:3})
11030                         do_facet ${facet} $TUNE2FS -O project $devname ||
11031                                 error "tune2fs $devname failed"
11032                 fi
11033         done
11034
11035         KEEP_ZPOOL="${zkeeper}"
11036         mount
11037         setupall
11038 }
11039
11040 disable_project_quota() {
11041         is_project_quota_supported || return 0
11042         [ "$mds1_FSTYPE" != "ldiskfs" ] && return 0
11043         stopall || error "failed to stopall (1)"
11044
11045         for num in $(seq $MDSCOUNT); do
11046                 do_facet mds$num $TUNE2FS -Q ^prj $(mdsdevname $num) ||
11047                         error "tune2fs $(mdsdevname $num) failed"
11048         done
11049
11050         for num in $(seq $OSTCOUNT); do
11051                 do_facet ost$num $TUNE2FS -Q ^prj $(ostdevname $num) ||
11052                         error "tune2fs $(ostdevname $num) failed"
11053         done
11054
11055         mount
11056         setupall
11057 }
11058
11059 #
11060 # In order to test multiple remote HSM agents, a new facet type named "AGT" and
11061 # the following associated variables are added:
11062 #
11063 # AGTCOUNT: number of agents
11064 # AGTDEV{N}: target HSM mount point (root path of the backend)
11065 # agt{N}_HOST: hostname of the agent agt{N}
11066 # SINGLEAGT: facet of the single agent
11067 #
11068 # The number of agents is initialized as the number of remote client nodes.
11069 # By default, only single copytool is started on a remote client/agent. If there
11070 # was no remote client, then the copytool will be started on the local client.
11071 #
11072 init_agt_vars() {
11073         local n
11074         local agent
11075
11076         export AGTCOUNT=${AGTCOUNT:-$((CLIENTCOUNT - 1))}
11077         [[ $AGTCOUNT -gt 0 ]] || AGTCOUNT=1
11078
11079         export SHARED_DIRECTORY=${SHARED_DIRECTORY:-$TMP}
11080         if [[ $CLIENTCOUNT -gt 1 ]] &&
11081                 ! check_shared_dir $SHARED_DIRECTORY $CLIENTS; then
11082                 skip_env "SHARED_DIRECTORY should be accessible"\
11083                          "on all client nodes"
11084                 exit 0
11085         fi
11086
11087         # We used to put the HSM archive in $SHARED_DIRECTORY but that
11088         # meant NFS issues could hose sanity-hsm sessions. So now we
11089         # use $TMP instead.
11090         for n in $(seq $AGTCOUNT); do
11091                 eval export AGTDEV$n=\$\{AGTDEV$n:-"$TMP/arc$n"\}
11092                 agent=CLIENT$((n + 1))
11093                 if [[ -z "${!agent}" ]]; then
11094                         [[ $CLIENTCOUNT -eq 1 ]] && agent=CLIENT1 ||
11095                                 agent=CLIENT2
11096                 fi
11097                 eval export agt${n}_HOST=\$\{agt${n}_HOST:-${!agent}\}
11098                 local var=agt${n}_HOST
11099                 [[ ! -z "${!var}" ]] || error "agt${n}_HOST is empty!"
11100         done
11101
11102         export SINGLEAGT=${SINGLEAGT:-agt1}
11103
11104         export HSMTOOL=${HSMTOOL:-"lhsmtool_posix"}
11105         export HSMTOOL_PID_FILE=${HSMTOOL_PID_FILE:-"/var/run/lhsmtool_posix.pid"}
11106         export HSMTOOL_VERBOSE=${HSMTOOL_VERBOSE:-""}
11107         export HSMTOOL_UPDATE_INTERVAL=${HSMTOOL_UPDATE_INTERVAL:=""}
11108         export HSMTOOL_EVENT_FIFO=${HSMTOOL_EVENT_FIFO:=""}
11109         export HSMTOOL_TESTDIR
11110         export HSMTOOL_ARCHIVE_FORMAT=${HSMTOOL_ARCHIVE_FORMAT:-v2}
11111
11112         if ! [[ $HSMTOOL =~ hsmtool ]]; then
11113                 echo "HSMTOOL = '$HSMTOOL' does not contain 'hsmtool', GLWT" >&2
11114         fi
11115
11116         HSM_ARCHIVE_NUMBER=2
11117
11118         # The test only support up to 10 MDTs
11119         MDT_PREFIX="mdt.$FSNAME-MDT000"
11120         HSM_PARAM="${MDT_PREFIX}0.hsm"
11121
11122         # archive is purged at copytool setup
11123         HSM_ARCHIVE_PURGE=true
11124
11125         # Don't allow copytool error upon start/setup
11126         HSMTOOL_NOERROR=false
11127 }
11128
11129 # Get the backend root path for the given agent facet.
11130 copytool_device() {
11131         local facet=$1
11132         local dev=AGTDEV$(facet_number $facet)
11133
11134         echo -n ${!dev}
11135 }
11136
11137 get_mdt_devices() {
11138         local mdtno
11139         # get MDT device for each mdc
11140         for mdtno in $(seq 1 $MDSCOUNT); do
11141                 local idx=$(($mdtno - 1))
11142                 MDT[$idx]=$($LCTL get_param -n \
11143                         mdc.$FSNAME-MDT000${idx}-mdc-*.mds_server_uuid |
11144                         awk '{gsub(/_UUID/,""); print $1}' | head -n1)
11145         done
11146 }
11147
11148 pkill_copytools() {
11149         local hosts="$1"
11150         local signal="$2"
11151
11152         do_nodes "$hosts" \
11153                 "pkill --pidfile=$HSMTOOL_PID_FILE --signal=$signal hsmtool"
11154 }
11155
11156 copytool_continue() {
11157         local agents=${1:-$(facet_active_host $SINGLEAGT)}
11158
11159         pkill_copytools "$agents" CONT || return 0
11160         echo "Copytool is continued on $agents"
11161 }
11162
11163 kill_copytools() {
11164         local hosts=${1:-$(facet_active_host $SINGLEAGT)}
11165
11166         echo "Killing existing copytools on $hosts"
11167         pkill_copytools "$hosts" TERM || return 0
11168         copytool_continue "$hosts"
11169 }
11170
11171 copytool_monitor_cleanup() {
11172         local facet=${1:-$SINGLEAGT}
11173         local agent=$(facet_active_host $facet)
11174
11175         if [ -n "$HSMTOOL_MONITOR_DIR" ]; then
11176                 # Should die when the copytool dies, but just in case.
11177                 local cmd="kill \\\$(cat $HSMTOOL_MONITOR_DIR/monitor_pid)"
11178                 cmd+=" 2>/dev/null || true"
11179                 do_node $agent "$cmd"
11180                 do_node $agent "rm -fr $HSMTOOL_MONITOR_DIR"
11181                 export HSMTOOL_MONITOR_DIR=
11182         fi
11183
11184         # The pdsh should die on its own when the monitor dies. Just
11185         # in case, though, try to clean up to avoid any cruft.
11186         if [ -n "$HSMTOOL_MONITOR_PDSH" ]; then
11187                 kill $HSMTOOL_MONITOR_PDSH 2>/dev/null || true
11188                 export HSMTOOL_MONITOR_PDSH=
11189         fi
11190 }
11191
11192 copytool_logfile()
11193 {
11194         local host="$(facet_host "$1")"
11195         local prefix=$TESTLOG_PREFIX
11196         [ -n "$TESTNAME" ] && prefix+=.$TESTNAME
11197
11198         printf "${prefix}.copytool${archive_id}_log.${host}.log"
11199 }
11200
11201 __lhsmtool_rebind()
11202 {
11203         do_facet $facet $HSMTOOL \
11204                 "${hsmtool_options[@]}" --rebind "$@" "$mountpoint"
11205 }
11206
11207 __lhsmtool_import()
11208 {
11209         mkdir -p "$(dirname "$2")" ||
11210                 error "cannot create directory '$(dirname "$2")'"
11211         do_facet $facet $HSMTOOL \
11212                 "${hsmtool_options[@]}" --import "$@" "$mountpoint"
11213 }
11214
11215 __lhsmtool_setup()
11216 {
11217         local host="$(facet_host "$facet")"
11218         local cmd="$HSMTOOL ${hsmtool_options[@]} --daemon --pid-file=$HSMTOOL_PID_FILE"
11219
11220         [ -n "$bandwidth" ] && cmd+=" --bandwidth $bandwidth"
11221         [ -n "$archive_id" ] && cmd+=" --archive $archive_id"
11222         #       [ ${#misc_options[@]} -gt 0 ] &&
11223 #               cmd+=" $(IFS=" " echo "$@")"
11224         cmd+=" $@ \"$mountpoint\""
11225
11226         echo "Starting copytool '$facet' on '$host' with cmdline '$cmd'"
11227         stack_trap "pkill_copytools $host TERM || true" EXIT
11228         do_node "$host" "$cmd < /dev/null > \"$(copytool_logfile $facet)\" 2>&1"
11229 }
11230
11231 hsm_root() {
11232         local facet="${1:-$SINGLEAGT}"
11233
11234         printf "$(copytool_device "$facet")/${TESTSUITE}.${TESTNAME}/"
11235 }
11236
11237 # Main entry point to perform copytool related operations
11238 #
11239 # Sub-commands:
11240 #
11241 #       setup   setup a copytool to run in the background, that copytool will be
11242 #               killed on EXIT
11243 #       import  import a file from an HSM backend
11244 #       rebind  rebind an archived file to a new fid
11245 #
11246 # Although the semantics might suggest otherwise, one does not need to 'setup'
11247 # a copytool before a call to 'copytool import' or 'copytool rebind'.
11248 #
11249 copytool()
11250 {
11251         local action=$1
11252         shift
11253
11254         # Use default values
11255         local facet=$SINGLEAGT
11256         local mountpoint="${MOUNT2:-$MOUNT}"
11257
11258         # Parse arguments
11259         local fail_on_error=true
11260         local -a hsmtool_options=()
11261         local -a action_options=()
11262
11263         if [[ -n "$HSMTOOL_ARCHIVE_FORMAT" ]]; then
11264                 hsmtool_options+=("--archive-format=$HSMTOOL_ARCHIVE_FORMAT")
11265         fi
11266
11267         if [[ -n "$HSMTOOL_VERBOSE" ]]; then
11268                 hsmtool_options+=("$HSMTOOL_VERBOSE")
11269         fi
11270
11271         while [ $# -gt 0 ]; do
11272                 case "$1" in
11273                 -f|--facet)
11274                         shift
11275                         facet="$1"
11276                         ;;
11277                 -m|--mountpoint)
11278                         shift
11279                         mountpoint="$1"
11280                         ;;
11281                 -a|--archive-id)
11282                         shift
11283                         local archive_id="$1"
11284                         ;;
11285                 -h|--hsm-root)
11286                         shift
11287                         local hsm_root="$1"
11288                         ;;
11289                 -b|--bwlimit)
11290                         shift
11291                         local bandwidth="$1" # in MB/s
11292                         ;;
11293                 -n|--no-fail)
11294                         local fail_on_error=false
11295                         ;;
11296                 *)
11297                         # Uncommon(/copytool dependent) option
11298                         action_options+=("$1")
11299                         ;;
11300                 esac
11301                 shift
11302         done
11303
11304         local hsm_root="${hsm_root:-$(hsm_root "$facet")}"
11305         hsmtool_options+=("--hsm-root=$hsm_root")
11306
11307         stack_trap "do_facet $facet rm -rf '$hsm_root'" EXIT
11308         do_facet $facet mkdir -p "$hsm_root" ||
11309                 error "mkdir '$hsm_root' failed"
11310
11311         case "$HSMTOOL" in
11312         lhsmtool_posix)
11313                 local copytool=lhsmtool
11314                 ;;
11315         esac
11316
11317         __${copytool}_${action} "${action_options[@]}"
11318         if [ $? -ne 0 ]; then
11319                 local error_msg
11320
11321                 case $action in
11322                 setup)
11323                         local host="$(facet_host $facet)"
11324                         error_msg="Failed to start copytool $facet on '$host'"
11325                         ;;
11326                 import)
11327                         local src="${action_options[0]}"
11328                         local dest="${action_options[1]}"
11329                         error_msg="Failed to import '$src' to '$dest'"
11330                         ;;
11331                 rebind)
11332                         error_msg="could not rebind file"
11333                         ;;
11334                 esac
11335
11336                 $fail_on_error && error "$error_msg" || echo "$error_msg"
11337         fi
11338 }
11339
11340 needclients() {
11341         local client_count=$1
11342         if [[ $CLIENTCOUNT -lt $client_count ]]; then
11343                 skip "Need $client_count or more clients, have $CLIENTCOUNT"
11344                 return 1
11345         fi
11346         return 0
11347 }
11348
11349 path2fid() {
11350         $LFS path2fid $1 | tr -d '[]'
11351         return ${PIPESTATUS[0]}
11352 }
11353
11354 get_hsm_flags() {
11355         local f=$1
11356         local u=$2
11357         local st
11358
11359         if [[ $u == "user" ]]; then
11360                 st=$($RUNAS $LFS hsm_state $f)
11361         else
11362                 u=root
11363                 st=$($LFS hsm_state $f)
11364         fi
11365
11366         [[ $? == 0 ]] || error "$LFS hsm_state $f failed (run as $u)"
11367
11368         st=$(echo $st | cut -f 2 -d" " | tr -d "()," )
11369         echo $st
11370 }
11371
11372 check_hsm_flags() {
11373         local f=$1
11374         local fl=$2
11375
11376         local st=$(get_hsm_flags $f)
11377         [[ $st == $fl ]] || error "hsm flags on $f are $st != $fl"
11378 }
11379
11380 mdts_set_param() {
11381         local arg=$1
11382         local key=$2
11383         local value=$3
11384         local mdtno
11385         local rc=0
11386         if [[ "$value" != "" ]]; then
11387                 value="='$value'"
11388         fi
11389         for mdtno in $(seq 1 $MDSCOUNT); do
11390                 local idx=$(($mdtno - 1))
11391                 local facet=mds${mdtno}
11392                 # if $arg include -P option, run 1 set_param per MDT on the MGS
11393                 # else, run set_param on each MDT
11394                 [[ $arg = *"-P"* ]] && facet=mgs
11395                 do_facet $facet $LCTL set_param $arg mdt.${MDT[$idx]}.$key$value
11396                 [[ $? != 0 ]] && rc=1
11397         done
11398         return $rc
11399 }
11400
11401 mdts_check_param() {
11402         local key="$1"
11403         local target="$2"
11404         local timeout="$3"
11405         local mdtno
11406
11407         for mdtno in $(seq 1 $MDSCOUNT); do
11408                 local idx=$(($mdtno - 1))
11409                 wait_update_facet --verbose mds${mdtno} \
11410                         "$LCTL get_param -n $MDT_PREFIX${idx}.$key" "$target" \
11411                         $timeout ||
11412                         error "$key state is not '$target' on mds${mdtno}"
11413         done
11414 }
11415
11416 cdt_set_mount_state() {
11417         mdts_set_param "-P" hsm_control "$1"
11418         # set_param -P is asynchronous operation and could race with set_param.
11419         # In such case configs could be retrieved and applied at mgc after
11420         # set_param -P completion. Sleep here to avoid race with set_param.
11421         # We need at least 20 seconds. 10 for mgc_requeue_thread to wake up
11422         # MGC_TIMEOUT_MIN_SECONDS + MGC_TIMEOUT_RAND_CENTISEC(5 + 5)
11423         # and 10 seconds to retrieve config from server.
11424         sleep 20
11425 }
11426
11427 cdt_check_state() {
11428         mdts_check_param hsm_control "$1" 20
11429 }
11430
11431 cdt_set_sanity_policy() {
11432         if [[ "$CDT_POLICY_HAD_CHANGED" ]]
11433         then
11434                 # clear all
11435                 mdts_set_param "" hsm.policy "+NRA"
11436                 mdts_set_param "" hsm.policy "-NBR"
11437                 CDT_POLICY_HAD_CHANGED=
11438         fi
11439 }
11440
11441 set_hsm_param() {
11442         local param=$1
11443         local value=$2
11444         local opt=$3
11445         mdts_set_param "$opt -n" "hsm.$param" "$value"
11446         return $?
11447 }
11448
11449 wait_request_state() {
11450         local fid=$1
11451         local request=$2
11452         local state=$3
11453         # 4th arg (mdt index) is optional
11454         local mdtidx=${4:-0}
11455         local mds=mds$(($mdtidx + 1))
11456
11457         local cmd="$LCTL get_param -n ${MDT_PREFIX}${mdtidx}.hsm.actions"
11458         cmd+=" | awk '/'$fid'.*action='$request'/ {print \\\$13}' | cut -f2 -d="
11459
11460         wait_update_facet --verbose $mds "$cmd" "$state" 200 ||
11461                 error "request on $fid is not $state on $mds"
11462 }
11463
11464
11465 rmultiop_start() {
11466         local client=$1
11467         local file=$2
11468         local cmds=$3
11469         local WAIT_MAX=${4:-60}
11470         local wait_time=0
11471
11472         # We need to run do_node in bg, because pdsh does not exit
11473         # if child process of run script exists.
11474         # I.e. pdsh does not exit when runmultiop_bg_pause exited,
11475         # because of multiop_bg_pause -> $MULTIOP_PROG &
11476         # By the same reason we need sleep a bit after do_nodes starts
11477         # to let runmultiop_bg_pause start muliop and
11478         # update /tmp/multiop_bg.pid ;
11479         # The rm /tmp/multiop_bg.pid guarantees here that
11480         # we have the updated by runmultiop_bg_pause
11481         # /tmp/multiop_bg.pid file
11482
11483         local pid_file=$TMP/multiop_bg.pid.$$
11484
11485         do_node $client "MULTIOP_PID_FILE=$pid_file LUSTRE= \
11486                         runmultiop_bg_pause $file $cmds" &
11487         local pid=$!
11488         local multiop_pid
11489
11490         while [[ $wait_time -lt $WAIT_MAX ]]; do
11491                 sleep 3
11492                 wait_time=$((wait_time + 3))
11493                 multiop_pid=$(do_node $client cat $pid_file)
11494                 if [ -n "$multiop_pid" ]; then
11495                         break
11496                 fi
11497         done
11498
11499         [ -n "$multiop_pid" ] ||
11500                 error "$client : Can not get multiop_pid from $pid_file "
11501
11502         eval export $(node_var_name $client)_multiop_pid=$multiop_pid
11503         eval export $(node_var_name $client)_do_node_pid=$pid
11504         local var=$(node_var_name $client)_multiop_pid
11505         echo client $client multiop_bg started multiop_pid=${!var}
11506         return $?
11507 }
11508
11509 rmultiop_stop() {
11510         local client=$1
11511         local multiop_pid=$(node_var_name $client)_multiop_pid
11512         local do_node_pid=$(node_var_name $client)_do_node_pid
11513
11514         echo "Stopping multiop_pid=${!multiop_pid} (kill ${!multiop_pid} on $client)"
11515         do_node $client kill -USR1 ${!multiop_pid}
11516
11517         wait ${!do_node_pid}
11518 }
11519
11520 sleep_maxage() {
11521         local delay=$(do_facet mds1 lctl get_param -n lod.*.qos_maxage |
11522                       awk '{ print $1 + 5; exit; }')
11523         sleep $delay
11524 }
11525
11526 sleep_maxage_lmv() {
11527         local delay=$(lctl get_param -n lmv.*.qos_maxage |
11528                       awk '{ print $1 + 5; exit; }')
11529         sleep $delay
11530 }
11531
11532 check_component_count() {
11533         local comp_cnt=$($LFS getstripe --component-count $1)
11534         [ $comp_cnt -eq $2 ] || error "$1, component count $comp_cnt != $2"
11535 }
11536
11537 # Verify there are no init components with "extension" flag
11538 verify_no_init_extension() {
11539         local flg_opts="--component-flags init,extension"
11540         local found=$($LFS find $flg_opts $1 | wc -l)
11541         [ $found -eq 0 ] || error "$1 has component with initialized extension"
11542 }
11543
11544 # Verify there is at least one component starting at 0
11545 verify_comp_at_zero() {
11546         flg_opts="--component-flags init"
11547         found=$($LFS find --component-start 0M $flg_opts $1 | wc -l)
11548         [ $found -eq 1 ] ||
11549                 error "No component starting at zero(!)"
11550 }
11551
11552 # version after which Self-Extending Layouts are available
11553 SEL_VER="2.12.55"
11554
11555 sel_layout_sanity() {
11556         local file=$1
11557         local comp_cnt=$2
11558
11559         verify_no_init_extension $file
11560         verify_comp_at_zero $file
11561         check_component_count $file $comp_cnt
11562 }
11563
11564 statx_supported() {
11565         $STATX --quiet --version
11566         return $?
11567 }
11568
11569 # lfs rm_entry is disabled on native client
11570 is_rmentry_supported() {
11571         $LFS rm_entry $DIR/dir/not/exists > /dev/null
11572         # is return code ENOENT?
11573         (( $? == 2 ))
11574 }
11575
11576 #
11577 # wrappers for createmany and unlinkmany
11578 # to set debug=0 if number of creates is high enough
11579 # this is to speedup testing
11580 #
11581 function createmany() {
11582         local count=${!#}
11583         local rc
11584
11585         if (( count > 100 )); then
11586                 debugsave
11587                 do_nodes $(comma_list $(all_nodes)) $LCTL set_param -n debug=0
11588         fi
11589         $LUSTRE/tests/createmany $*
11590         rc=$?
11591         debugrestore > /dev/null
11592
11593         return $rc
11594 }
11595
11596 function unlinkmany() {
11597         local count=${!#}
11598         local rc
11599
11600         if (( count > 100 )); then
11601                 debugsave
11602                 do_nodes $(comma_list $(all_nodes)) $LCTL set_param -n debug=0
11603         fi
11604         $LUSTRE/tests/unlinkmany $*
11605         rc=$?
11606         debugrestore > /dev/null
11607
11608         return $rc
11609 }
11610
11611 # Check if fallocate on facet is working. Returns fallocate mode if enabled.
11612 # Takes optional facet name as argument, to allow separate MDS/OSS checks.
11613 function check_fallocate_supported()
11614 {
11615         local facet=${1:-ost1}
11616         local supported="FALLOCATE_SUPPORTED_$facet"
11617         local fstype="${facet}_FSTYPE"
11618
11619         if [[ -n "${!supported}" ]]; then
11620                 echo "${!supported}"
11621                 return 0
11622         fi
11623         if [[ -z "${!fstype}" ]]; then
11624                 eval export $fstype=$(facet_fstype $facet)
11625         fi
11626         if [[ "${!fstype}" != "ldiskfs" ]]; then
11627                 echo "fallocate on ${!fstype} doesn't consume space" 1>&2
11628                 return 1
11629         fi
11630
11631         local fa_mode="osd-ldiskfs.$(facet_svc $facet).fallocate_zero_blocks"
11632         local mode=$(do_facet $facet $LCTL get_param -n $fa_mode 2>/dev/null |
11633                      head -n 1)
11634
11635         if [[ -z "$mode" ]]; then
11636                 echo "fallocate not supported on $facet" 1>&2
11637                 return 1
11638         fi
11639         eval export $supported="$mode"
11640
11641         echo ${!supported}
11642         return 0
11643 }
11644
11645 # Check if fallocate supported on OSTs, enable if unset, skip if unavailable.
11646 # Takes optional facet name as argument.
11647 function check_fallocate_or_skip()
11648 {
11649         local facet=$1
11650
11651         check_fallocate_supported $1 || skip "fallocate not supported"
11652 }
11653
11654 # Check if fallocate supported on OSTs, enable if unset, default mode=0
11655 # Optionally pass the OST fallocate mode (0=unwritten extents, 1=zero extents)
11656 function check_set_fallocate()
11657 {
11658         local new_mode="$1"
11659         local fa_mode="osd-ldiskfs.*.fallocate_zero_blocks"
11660         local old_mode="$(check_fallocate_supported)"
11661
11662         [[ -n "$old_mode" ]] || { echo "fallocate not supported"; return 1; }
11663         [[ -z "$new_mode" && "$old_mode" != "-1" ]] &&
11664                 { echo "keep default fallocate mode: $old_mode"; return 0; }
11665         [[ "$new_mode" && "$old_mode" == "$new_mode" ]] &&
11666                 { echo "keep current fallocate mode: $old_mode"; return 0; }
11667         local osts=$(comma_list $(osts_nodes))
11668
11669         stack_trap "do_nodes $osts $LCTL set_param $fa_mode=$old_mode"
11670         do_nodes $osts $LCTL set_param $fa_mode=${new_mode:-0} ||
11671                 error "set $fa_mode=$new_mode"
11672 }
11673
11674 # Check if fallocate supported on OSTs, enable if unset, skip if unavailable
11675 function check_set_fallocate_or_skip()
11676 {
11677         check_set_fallocate || skip "need >= 2.13.57 and ldiskfs for fallocate"
11678 }
11679
11680 function disable_opencache()
11681 {
11682         local state=$($LCTL get_param -n "llite.*.opencache_threshold_count" |
11683                         head -1)
11684
11685         test -z "${saved_OPENCACHE_value}" &&
11686                                         export saved_OPENCACHE_value="$state"
11687
11688         [[ "$state" = "off" ]] && return
11689
11690         $LCTL set_param -n "llite.*.opencache_threshold_count"=off
11691 }
11692
11693 function set_opencache()
11694 {
11695         local newvalue="$1"
11696         local state=$($LCTL get_param -n "llite.*.opencache_threshold_count")
11697
11698         [[ -n "$newvalue" ]] || return
11699
11700         [[ -n "${saved_OPENCACHE_value}" ]] ||
11701                                         export saved_OPENCACHE_value="$state"
11702
11703         $LCTL set_param -n "llite.*.opencache_threshold_count"=$newvalue
11704 }
11705
11706
11707
11708 function restore_opencache()
11709 {
11710         [[ -z "${saved_OPENCACHE_value}" ]] ||
11711                 $LCTL set_param -n "llite.*.opencache_threshold_count"=${saved_OPENCACHE_value}
11712 }
11713
11714 # LU-13417: XXX lots of tests assume the directory to be created under MDT0,
11715 # created on MDT0, use this function to create directory on specific MDT
11716 # explicitly, and set default LMV to create subdirs on the same MDT too.
11717 mkdir_on_mdt() {
11718         local mdt
11719         local OPTIND=1
11720
11721         while getopts "i:" opt $*; do
11722                 case $opt in
11723                         i) mdt=$OPTARG;;
11724                 esac
11725         done
11726
11727         shift $((OPTIND - 1))
11728
11729         $LFS mkdir -i $mdt -c 1 $*
11730 }
11731
11732 mkdir_on_mdt0() {
11733         mkdir_on_mdt -i0 $*
11734 }
11735
11736 # Wait for nodemap synchronization
11737 wait_nm_sync() {
11738         local nodemap_name=$1
11739         local key=$2
11740         local value=$3
11741         local opt=$4
11742         local proc_param
11743         local is_active=$(do_facet mgs $LCTL get_param -n nodemap.active)
11744         local max_retries=20
11745         local is_sync
11746         local out1=""
11747         local out2
11748         local mgs_ip=$(host_nids_address $mgs_HOST $NETTYPE | cut -d' ' -f1)
11749         local i
11750
11751         if [ "$nodemap_name" == "active" ]; then
11752                 proc_param="active"
11753         elif [ -z "$key" ]; then
11754                 proc_param=${nodemap_name}
11755         else
11756                 proc_param="${nodemap_name}.${key}"
11757         fi
11758         if [ "$opt" == "inactive" ]; then
11759                 # check nm sync even if nodemap is not activated
11760                 is_active=1
11761                 opt=""
11762         fi
11763         (( is_active == 0 )) && [ "$proc_param" != "active" ] && return
11764
11765         if [ -z "$value" ]; then
11766                 out1=$(do_facet mgs $LCTL get_param $opt \
11767                         nodemap.${proc_param} 2>/dev/null)
11768                 echo "On MGS ${mgs_ip}, ${proc_param} = $out1"
11769         else
11770                 out1=$value;
11771         fi
11772
11773         # if servers run on the same node, it is impossible to tell if they get
11774         # synced with the mgs, so just wait an arbitrary 10 seconds
11775         if [ $(facet_active_host mgs) == $(facet_active_host mds) ] &&
11776            [ $(facet_active_host mgs) == $(facet_active_host ost1) ]; then
11777                 echo "waiting 10 secs for sync"
11778                 sleep 10
11779                 return
11780         fi
11781
11782         # wait up to 10 seconds for other servers to sync with mgs
11783         for i in $(seq 1 10); do
11784                 for node in $(all_server_nodes); do
11785                         local node_ip=$(host_nids_address $node $NETTYPE |
11786                                         cut -d' ' -f1)
11787
11788                         is_sync=true
11789                         if [ -z "$value" ]; then
11790                                 [ $node_ip == $mgs_ip ] && continue
11791                         fi
11792
11793                         out2=$(do_node $node $LCTL get_param $opt \
11794                                nodemap.$proc_param 2>/dev/null)
11795                         echo "On $node ${node_ip}, ${proc_param} = $out2"
11796                         [ "$out1" != "$out2" ] && is_sync=false && break
11797                 done
11798                 $is_sync && break
11799                 sleep 1
11800         done
11801         if ! $is_sync; then
11802                 echo MGS
11803                 echo $out1
11804                 echo OTHER - IP: $node_ip
11805                 echo $out2
11806                 error "mgs and $nodemap_name ${key} mismatch, $i attempts"
11807         fi
11808         echo "waited $((i - 1)) seconds for sync"
11809 }
11810
11811 consume_precreations() {
11812         local dir=$1
11813         local mfacet=$2
11814         local OSTIDX=$3
11815         local extra=${4:-2}
11816         local OST=$(ostname_from_index $OSTIDX $dir)
11817
11818         mkdir_on_mdt -i $(facet_index $mfacet) $dir/${OST}
11819         $LFS setstripe -i $OSTIDX -c 1 ${dir}/${OST}
11820
11821         # on the mdt's osc
11822         local mdtosc_proc=$(get_mdtosc_proc_path $mfacet $OST)
11823         local last_id=$(do_facet $mfacet $LCTL get_param -n \
11824                         osp.$mdtosc_proc.prealloc_last_id)
11825         local next_id=$(do_facet $mfacet $LCTL get_param -n \
11826                         osp.$mdtosc_proc.prealloc_next_id)
11827         echo "Creating to objid $last_id on ost $OST..."
11828         createmany -o $dir/${OST}/f $next_id $((last_id - next_id + extra))
11829 }
11830
11831 __exhaust_precreations() {
11832         local OSTIDX=$1
11833         local FAILLOC=$2
11834         local FAILIDX=${3:-$OSTIDX}
11835         local ofacet=ost$((OSTIDX + 1))
11836
11837         mkdir_on_mdt0 $DIR/$tdir
11838         local mdtidx=$($LFS getstripe -m $DIR/$tdir)
11839         local mfacet=mds$((mdtidx + 1))
11840         echo OSTIDX=$OSTIDX MDTIDX=$mdtidx
11841
11842         local mdtosc_proc=$(get_mdtosc_proc_path $mfacet)
11843         do_facet $mfacet $LCTL get_param osp.$mdtosc_proc.prealloc*
11844
11845 #define OBD_FAIL_OST_ENOSPC              0x215
11846         do_facet $ofacet $LCTL set_param fail_val=$FAILIDX fail_loc=0x215
11847
11848         consume_precreations $DIR/$tdir $mfacet $OSTIDX
11849
11850         do_facet $mfacet $LCTL get_param osp.$mdtosc_proc.prealloc*
11851         do_facet $ofacet $LCTL set_param fail_loc=$FAILLOC
11852 }
11853
11854 exhaust_precreations() {
11855         __exhaust_precreations $1 $2 $3
11856         sleep_maxage
11857 }
11858
11859 exhaust_all_precreations() {
11860         local i
11861         for (( i=0; i < OSTCOUNT; i++ )) ; do
11862                 __exhaust_precreations $i $1 -1
11863         done
11864         sleep_maxage
11865 }
11866
11867 force_new_seq_ost() {
11868         local dir=$1
11869         local mfacet=$2
11870         local OSTIDX=$3
11871         local OST=$(ostname_from_index $OSTIDX)
11872         local mdtosc_proc=$(get_mdtosc_proc_path $mfacet $OST)
11873
11874         do_facet $mfacet $LCTL set_param \
11875                 osp.$mdtosc_proc.prealloc_force_new_seq=1
11876         # consume preallocated objects, to wake up precreate thread
11877         consume_precreations $dir $mfacet $OSTIDX
11878         do_facet $mfacet $LCTL set_param \
11879                 osp.$mdtosc_proc.prealloc_force_new_seq=0
11880 }
11881
11882 force_new_seq() {
11883         local mfacet=$1
11884         local MDTIDX=$(facet_index $mfacet)
11885         local MDT=$(mdtname_from_index $MDTIDX $DIR)
11886         local i
11887
11888         mkdir_on_mdt -i $MDTIDX $DIR/${MDT}
11889         for (( i=0; i < OSTCOUNT; i++ )) ; do
11890                 force_new_seq_ost $DIR/${MDT} $mfacet $i &
11891         done
11892         wait
11893         rm -rf $DIR/${MDT}
11894 }
11895
11896 force_new_seq_all() {
11897         local i
11898
11899         for (( i=0; i < MDSCOUNT; i++ )) ; do
11900                 force_new_seq mds$((i + 1)) &
11901         done
11902         wait
11903         sleep_maxage
11904 }
11905
11906 ost_set_temp_seq_width_all() {
11907         local osts=$(comma_list $(osts_nodes))
11908         local width=$(do_facet ost1 $LCTL get_param -n seq.*OST0000-super.width)
11909
11910         do_nodes $osts $LCTL set_param seq.*OST*-super.width=$1
11911         stack_trap "do_nodes $osts $LCTL set_param seq.*OST*-super.width=$width"
11912 }
11913
11914 verify_yaml_available() {
11915         python3 -c "import yaml; yaml.safe_load('''a: b''')"
11916 }
11917
11918 verify_yaml() {
11919         python3 -c "import sys, yaml; obj = yaml.safe_load(sys.stdin)"
11920 }
11921
11922 verify_compare_yaml() {
11923         python3 -c "import sys, yaml; f=open(\"$1\", \"r\"); obj1 = yaml.safe_load(f); f=open(\"$2\", \"r\"); obj2 = yaml.safe_load(f); sys.exit(obj1 != obj2)"
11924 }
11925
11926 zfs_or_rotational() {
11927         local ost_idx=0
11928         local ost_name=$(ostname_from_index $ost_idx $MOUNT)
11929         local param="get_param -n osd-*.${ost_name}.nonrotational"
11930         local nonrotat=$(do_facet ost1 $LCTL $param)
11931
11932         if [[ -z "$nonrotat" ]]; then
11933                 # At this point there is no point moving ahead.
11934                 # Will stop here and dump all the info
11935                 set -x
11936                 local ost_name=$(ostname_from_index $ost_idx)
11937                 set +x
11938                 error "$LCTL $input_str"
11939         fi
11940
11941         if [[ "$ost1_FSTYPE" == "zfs" ]] || (( "$nonrotat" == 0 )); then
11942                 return 0
11943         else
11944                 return 1
11945         fi
11946 }