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