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