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