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