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