]> git.proxmox.com Git - mirror_zfs.git/blob - tests/zfs-tests/include/libtest.shlib
ZTS: Fix DEV_DSKDIR trim from disk
[mirror_zfs.git] / tests / zfs-tests / include / libtest.shlib
1 #
2 # CDDL HEADER START
3 #
4 # The contents of this file are subject to the terms of the
5 # Common Development and Distribution License (the "License").
6 # You may not use this file except in compliance with the License.
7 #
8 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 # or http://www.opensolaris.org/os/licensing.
10 # See the License for the specific language governing permissions
11 # and limitations under the License.
12 #
13 # When distributing Covered Code, include this CDDL HEADER in each
14 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 # If applicable, add the following below this CDDL HEADER, with the
16 # fields enclosed by brackets "[]" replaced with your own identifying
17 # information: Portions Copyright [yyyy] [name of copyright owner]
18 #
19 # CDDL HEADER END
20 #
21
22 #
23 # Copyright 2009 Sun Microsystems, Inc. All rights reserved.
24 # Use is subject to license terms.
25 # Copyright (c) 2012, 2017 by Delphix. All rights reserved.
26 # Copyright 2016 Nexenta Systems, Inc.
27 # Copyright (c) 2017 Lawrence Livermore National Security, LLC.
28 # Copyright (c) 2017 Datto Inc.
29 # Copyright (c) 2017 Open-E, Inc. All Rights Reserved.
30 #
31
32 . ${STF_TOOLS}/include/logapi.shlib
33 . ${STF_SUITE}/include/math.shlib
34 . ${STF_SUITE}/include/blkdev.shlib
35
36 #
37 # Apply constrained path when available. This is required since the
38 # PATH may have been modified by sudo's secure_path behavior.
39 #
40 if [ -n "$STF_PATH" ]; then
41 PATH="$STF_PATH"
42 fi
43
44 #
45 # Generic dot version comparison function
46 #
47 # Returns success when version $1 is greater than or equal to $2.
48 #
49 function compare_version_gte
50 {
51 if [[ "$(printf "$1\n$2" | sort -V | tail -n1)" == "$1" ]]; then
52 return 0
53 else
54 return 1
55 fi
56 }
57
58 # Linux kernel version comparison function
59 #
60 # $1 Linux version ("4.10", "2.6.32") or blank for installed Linux version
61 #
62 # Used for comparison: if [ $(linux_version) -ge $(linux_version "2.6.32") ]
63 #
64 function linux_version
65 {
66 typeset ver="$1"
67
68 [[ -z "$ver" ]] && ver=$(uname -r | grep -Eo "^[0-9]+\.[0-9]+\.[0-9]+")
69
70 typeset version=$(echo $ver | cut -d '.' -f 1)
71 typeset major=$(echo $ver | cut -d '.' -f 2)
72 typeset minor=$(echo $ver | cut -d '.' -f 3)
73
74 [[ -z "$version" ]] && version=0
75 [[ -z "$major" ]] && major=0
76 [[ -z "$minor" ]] && minor=0
77
78 echo $((version * 10000 + major * 100 + minor))
79 }
80
81 # Determine if this is a Linux test system
82 #
83 # Return 0 if platform Linux, 1 if otherwise
84
85 function is_linux
86 {
87 if [[ $(uname -o) == "GNU/Linux" ]]; then
88 return 0
89 else
90 return 1
91 fi
92 }
93
94 # Determine if this is a 32-bit system
95 #
96 # Return 0 if platform is 32-bit, 1 if otherwise
97
98 function is_32bit
99 {
100 if [[ $(getconf LONG_BIT) == "32" ]]; then
101 return 0
102 else
103 return 1
104 fi
105 }
106
107 # Determine if kmemleak is enabled
108 #
109 # Return 0 if kmemleak is enabled, 1 if otherwise
110
111 function is_kmemleak
112 {
113 if is_linux && [[ -e /sys/kernel/debug/kmemleak ]]; then
114 return 0
115 else
116 return 1
117 fi
118 }
119
120 # Determine whether a dataset is mounted
121 #
122 # $1 dataset name
123 # $2 filesystem type; optional - defaulted to zfs
124 #
125 # Return 0 if dataset is mounted; 1 if unmounted; 2 on error
126
127 function ismounted
128 {
129 typeset fstype=$2
130 [[ -z $fstype ]] && fstype=zfs
131 typeset out dir name ret
132
133 case $fstype in
134 zfs)
135 if [[ "$1" == "/"* ]] ; then
136 for out in $(zfs mount | awk '{print $2}'); do
137 [[ $1 == $out ]] && return 0
138 done
139 else
140 for out in $(zfs mount | awk '{print $1}'); do
141 [[ $1 == $out ]] && return 0
142 done
143 fi
144 ;;
145 ufs|nfs)
146 out=$(df -F $fstype $1 2>/dev/null)
147 ret=$?
148 (($ret != 0)) && return $ret
149
150 dir=${out%%\(*}
151 dir=${dir%% *}
152 name=${out##*\(}
153 name=${name%%\)*}
154 name=${name%% *}
155
156 [[ "$1" == "$dir" || "$1" == "$name" ]] && return 0
157 ;;
158 ext*)
159 out=$(df -t $fstype $1 2>/dev/null)
160 return $?
161 ;;
162 zvol)
163 if [[ -L "$ZVOL_DEVDIR/$1" ]]; then
164 link=$(readlink -f $ZVOL_DEVDIR/$1)
165 [[ -n "$link" ]] && \
166 mount | grep -q "^$link" && \
167 return 0
168 fi
169 ;;
170 esac
171
172 return 1
173 }
174
175 # Return 0 if a dataset is mounted; 1 otherwise
176 #
177 # $1 dataset name
178 # $2 filesystem type; optional - defaulted to zfs
179
180 function mounted
181 {
182 ismounted $1 $2
183 (($? == 0)) && return 0
184 return 1
185 }
186
187 # Return 0 if a dataset is unmounted; 1 otherwise
188 #
189 # $1 dataset name
190 # $2 filesystem type; optional - defaulted to zfs
191
192 function unmounted
193 {
194 ismounted $1 $2
195 (($? == 1)) && return 0
196 return 1
197 }
198
199 # split line on ","
200 #
201 # $1 - line to split
202
203 function splitline
204 {
205 echo $1 | sed "s/,/ /g"
206 }
207
208 function default_setup
209 {
210 default_setup_noexit "$@"
211
212 log_pass
213 }
214
215 #
216 # Given a list of disks, setup storage pools and datasets.
217 #
218 function default_setup_noexit
219 {
220 typeset disklist=$1
221 typeset container=$2
222 typeset volume=$3
223 log_note begin default_setup_noexit
224
225 if is_global_zone; then
226 if poolexists $TESTPOOL ; then
227 destroy_pool $TESTPOOL
228 fi
229 [[ -d /$TESTPOOL ]] && rm -rf /$TESTPOOL
230 log_must zpool create -f $TESTPOOL $disklist
231 else
232 reexport_pool
233 fi
234
235 rm -rf $TESTDIR || log_unresolved Could not remove $TESTDIR
236 mkdir -p $TESTDIR || log_unresolved Could not create $TESTDIR
237
238 log_must zfs create $TESTPOOL/$TESTFS
239 log_must zfs set mountpoint=$TESTDIR $TESTPOOL/$TESTFS
240
241 if [[ -n $container ]]; then
242 rm -rf $TESTDIR1 || \
243 log_unresolved Could not remove $TESTDIR1
244 mkdir -p $TESTDIR1 || \
245 log_unresolved Could not create $TESTDIR1
246
247 log_must zfs create $TESTPOOL/$TESTCTR
248 log_must zfs set canmount=off $TESTPOOL/$TESTCTR
249 log_must zfs create $TESTPOOL/$TESTCTR/$TESTFS1
250 log_must zfs set mountpoint=$TESTDIR1 \
251 $TESTPOOL/$TESTCTR/$TESTFS1
252 fi
253
254 if [[ -n $volume ]]; then
255 if is_global_zone ; then
256 log_must zfs create -V $VOLSIZE $TESTPOOL/$TESTVOL
257 block_device_wait
258 else
259 log_must zfs create $TESTPOOL/$TESTVOL
260 fi
261 fi
262 }
263
264 #
265 # Given a list of disks, setup a storage pool, file system and
266 # a container.
267 #
268 function default_container_setup
269 {
270 typeset disklist=$1
271
272 default_setup "$disklist" "true"
273 }
274
275 #
276 # Given a list of disks, setup a storage pool,file system
277 # and a volume.
278 #
279 function default_volume_setup
280 {
281 typeset disklist=$1
282
283 default_setup "$disklist" "" "true"
284 }
285
286 #
287 # Given a list of disks, setup a storage pool,file system,
288 # a container and a volume.
289 #
290 function default_container_volume_setup
291 {
292 typeset disklist=$1
293
294 default_setup "$disklist" "true" "true"
295 }
296
297 #
298 # Create a snapshot on a filesystem or volume. Defaultly create a snapshot on
299 # filesystem
300 #
301 # $1 Existing filesystem or volume name. Default, $TESTPOOL/$TESTFS
302 # $2 snapshot name. Default, $TESTSNAP
303 #
304 function create_snapshot
305 {
306 typeset fs_vol=${1:-$TESTPOOL/$TESTFS}
307 typeset snap=${2:-$TESTSNAP}
308
309 [[ -z $fs_vol ]] && log_fail "Filesystem or volume's name is undefined."
310 [[ -z $snap ]] && log_fail "Snapshot's name is undefined."
311
312 if snapexists $fs_vol@$snap; then
313 log_fail "$fs_vol@$snap already exists."
314 fi
315 datasetexists $fs_vol || \
316 log_fail "$fs_vol must exist."
317
318 log_must zfs snapshot $fs_vol@$snap
319 }
320
321 #
322 # Create a clone from a snapshot, default clone name is $TESTCLONE.
323 #
324 # $1 Existing snapshot, $TESTPOOL/$TESTFS@$TESTSNAP is default.
325 # $2 Clone name, $TESTPOOL/$TESTCLONE is default.
326 #
327 function create_clone # snapshot clone
328 {
329 typeset snap=${1:-$TESTPOOL/$TESTFS@$TESTSNAP}
330 typeset clone=${2:-$TESTPOOL/$TESTCLONE}
331
332 [[ -z $snap ]] && \
333 log_fail "Snapshot name is undefined."
334 [[ -z $clone ]] && \
335 log_fail "Clone name is undefined."
336
337 log_must zfs clone $snap $clone
338 }
339
340 #
341 # Create a bookmark of the given snapshot. Defaultly create a bookmark on
342 # filesystem.
343 #
344 # $1 Existing filesystem or volume name. Default, $TESTFS
345 # $2 Existing snapshot name. Default, $TESTSNAP
346 # $3 bookmark name. Default, $TESTBKMARK
347 #
348 function create_bookmark
349 {
350 typeset fs_vol=${1:-$TESTFS}
351 typeset snap=${2:-$TESTSNAP}
352 typeset bkmark=${3:-$TESTBKMARK}
353
354 [[ -z $fs_vol ]] && log_fail "Filesystem or volume's name is undefined."
355 [[ -z $snap ]] && log_fail "Snapshot's name is undefined."
356 [[ -z $bkmark ]] && log_fail "Bookmark's name is undefined."
357
358 if bkmarkexists $fs_vol#$bkmark; then
359 log_fail "$fs_vol#$bkmark already exists."
360 fi
361 datasetexists $fs_vol || \
362 log_fail "$fs_vol must exist."
363 snapexists $fs_vol@$snap || \
364 log_fail "$fs_vol@$snap must exist."
365
366 log_must zfs bookmark $fs_vol@$snap $fs_vol#$bkmark
367 }
368
369 #
370 # Create a temporary clone result of an interrupted resumable 'zfs receive'
371 # $1 Destination filesystem name. Must not exist, will be created as the result
372 # of this function along with its %recv temporary clone
373 # $2 Source filesystem name. Must not exist, will be created and destroyed
374 #
375 function create_recv_clone
376 {
377 typeset recvfs="$1"
378 typeset sendfs="${2:-$TESTPOOL/create_recv_clone}"
379 typeset snap="$sendfs@snap1"
380 typeset incr="$sendfs@snap2"
381 typeset mountpoint="$TESTDIR/create_recv_clone"
382 typeset sendfile="$TESTDIR/create_recv_clone.zsnap"
383
384 [[ -z $recvfs ]] && log_fail "Recv filesystem's name is undefined."
385
386 datasetexists $recvfs && log_fail "Recv filesystem must not exist."
387 datasetexists $sendfs && log_fail "Send filesystem must not exist."
388
389 log_must zfs create -o mountpoint="$mountpoint" $sendfs
390 log_must zfs snapshot $snap
391 log_must eval "zfs send $snap | zfs recv -u $recvfs"
392 log_must mkfile 1m "$mountpoint/data"
393 log_must zfs snapshot $incr
394 log_must eval "zfs send -i $snap $incr | dd bs=10K count=1 > $sendfile"
395 log_mustnot eval "zfs recv -su $recvfs < $sendfile"
396 destroy_dataset "$sendfs" "-r"
397 log_must rm -f "$sendfile"
398
399 if [[ $(get_prop 'inconsistent' "$recvfs/%recv") -ne 1 ]]; then
400 log_fail "Error creating temporary $recvfs/%recv clone"
401 fi
402 }
403
404 function default_mirror_setup
405 {
406 default_mirror_setup_noexit $1 $2 $3
407
408 log_pass
409 }
410
411 #
412 # Given a pair of disks, set up a storage pool and dataset for the mirror
413 # @parameters: $1 the primary side of the mirror
414 # $2 the secondary side of the mirror
415 # @uses: ZPOOL ZFS TESTPOOL TESTFS
416 function default_mirror_setup_noexit
417 {
418 readonly func="default_mirror_setup_noexit"
419 typeset primary=$1
420 typeset secondary=$2
421
422 [[ -z $primary ]] && \
423 log_fail "$func: No parameters passed"
424 [[ -z $secondary ]] && \
425 log_fail "$func: No secondary partition passed"
426 [[ -d /$TESTPOOL ]] && rm -rf /$TESTPOOL
427 log_must zpool create -f $TESTPOOL mirror $@
428 log_must zfs create $TESTPOOL/$TESTFS
429 log_must zfs set mountpoint=$TESTDIR $TESTPOOL/$TESTFS
430 }
431
432 #
433 # create a number of mirrors.
434 # We create a number($1) of 2 way mirrors using the pairs of disks named
435 # on the command line. These mirrors are *not* mounted
436 # @parameters: $1 the number of mirrors to create
437 # $... the devices to use to create the mirrors on
438 # @uses: ZPOOL ZFS TESTPOOL
439 function setup_mirrors
440 {
441 typeset -i nmirrors=$1
442
443 shift
444 while ((nmirrors > 0)); do
445 log_must test -n "$1" -a -n "$2"
446 [[ -d /$TESTPOOL$nmirrors ]] && rm -rf /$TESTPOOL$nmirrors
447 log_must zpool create -f $TESTPOOL$nmirrors mirror $1 $2
448 shift 2
449 ((nmirrors = nmirrors - 1))
450 done
451 }
452
453 #
454 # create a number of raidz pools.
455 # We create a number($1) of 2 raidz pools using the pairs of disks named
456 # on the command line. These pools are *not* mounted
457 # @parameters: $1 the number of pools to create
458 # $... the devices to use to create the pools on
459 # @uses: ZPOOL ZFS TESTPOOL
460 function setup_raidzs
461 {
462 typeset -i nraidzs=$1
463
464 shift
465 while ((nraidzs > 0)); do
466 log_must test -n "$1" -a -n "$2"
467 [[ -d /$TESTPOOL$nraidzs ]] && rm -rf /$TESTPOOL$nraidzs
468 log_must zpool create -f $TESTPOOL$nraidzs raidz $1 $2
469 shift 2
470 ((nraidzs = nraidzs - 1))
471 done
472 }
473
474 #
475 # Destroy the configured testpool mirrors.
476 # the mirrors are of the form ${TESTPOOL}{number}
477 # @uses: ZPOOL ZFS TESTPOOL
478 function destroy_mirrors
479 {
480 default_cleanup_noexit
481
482 log_pass
483 }
484
485 #
486 # Given a minimum of two disks, set up a storage pool and dataset for the raid-z
487 # $1 the list of disks
488 #
489 function default_raidz_setup
490 {
491 typeset disklist="$*"
492 disks=(${disklist[*]})
493
494 if [[ ${#disks[*]} -lt 2 ]]; then
495 log_fail "A raid-z requires a minimum of two disks."
496 fi
497
498 [[ -d /$TESTPOOL ]] && rm -rf /$TESTPOOL
499 log_must zpool create -f $TESTPOOL raidz $disklist
500 log_must zfs create $TESTPOOL/$TESTFS
501 log_must zfs set mountpoint=$TESTDIR $TESTPOOL/$TESTFS
502
503 log_pass
504 }
505
506 #
507 # Common function used to cleanup storage pools and datasets.
508 #
509 # Invoked at the start of the test suite to ensure the system
510 # is in a known state, and also at the end of each set of
511 # sub-tests to ensure errors from one set of tests doesn't
512 # impact the execution of the next set.
513
514 function default_cleanup
515 {
516 default_cleanup_noexit
517
518 log_pass
519 }
520
521 #
522 # Utility function used to list all available pool names.
523 #
524 # NOTE: $KEEP is a variable containing pool names, separated by a newline
525 # character, that must be excluded from the returned list.
526 #
527 function get_all_pools
528 {
529 zpool list -H -o name | grep -Fvx "$KEEP" | grep -v "$NO_POOLS"
530 }
531
532 function default_cleanup_noexit
533 {
534 typeset pool=""
535 #
536 # Destroying the pool will also destroy any
537 # filesystems it contains.
538 #
539 if is_global_zone; then
540 zfs unmount -a > /dev/null 2>&1
541 ALL_POOLS=$(get_all_pools)
542 # Here, we loop through the pools we're allowed to
543 # destroy, only destroying them if it's safe to do
544 # so.
545 while [ ! -z ${ALL_POOLS} ]
546 do
547 for pool in ${ALL_POOLS}
548 do
549 if safe_to_destroy_pool $pool ;
550 then
551 destroy_pool $pool
552 fi
553 ALL_POOLS=$(get_all_pools)
554 done
555 done
556
557 zfs mount -a
558 else
559 typeset fs=""
560 for fs in $(zfs list -H -o name \
561 | grep "^$ZONE_POOL/$ZONE_CTR[01234]/"); do
562 destroy_dataset "$fs" "-Rf"
563 done
564
565 # Need cleanup here to avoid garbage dir left.
566 for fs in $(zfs list -H -o name); do
567 [[ $fs == /$ZONE_POOL ]] && continue
568 [[ -d $fs ]] && log_must rm -rf $fs/*
569 done
570
571 #
572 # Reset the $ZONE_POOL/$ZONE_CTR[01234] file systems property to
573 # the default value
574 #
575 for fs in $(zfs list -H -o name); do
576 if [[ $fs == $ZONE_POOL/$ZONE_CTR[01234] ]]; then
577 log_must zfs set reservation=none $fs
578 log_must zfs set recordsize=128K $fs
579 log_must zfs set mountpoint=/$fs $fs
580 typeset enc=""
581 enc=$(get_prop encryption $fs)
582 if [[ $? -ne 0 ]] || [[ -z "$enc" ]] || \
583 [[ "$enc" == "off" ]]; then
584 log_must zfs set checksum=on $fs
585 fi
586 log_must zfs set compression=off $fs
587 log_must zfs set atime=on $fs
588 log_must zfs set devices=off $fs
589 log_must zfs set exec=on $fs
590 log_must zfs set setuid=on $fs
591 log_must zfs set readonly=off $fs
592 log_must zfs set snapdir=hidden $fs
593 log_must zfs set aclmode=groupmask $fs
594 log_must zfs set aclinherit=secure $fs
595 fi
596 done
597 fi
598
599 [[ -d $TESTDIR ]] && \
600 log_must rm -rf $TESTDIR
601
602 disk1=${DISKS%% *}
603 if is_mpath_device $disk1; then
604 delete_partitions
605 fi
606
607 rm -f $TEST_BASE_DIR/{err,out}
608 }
609
610
611 #
612 # Common function used to cleanup storage pools, file systems
613 # and containers.
614 #
615 function default_container_cleanup
616 {
617 if ! is_global_zone; then
618 reexport_pool
619 fi
620
621 ismounted $TESTPOOL/$TESTCTR/$TESTFS1
622 [[ $? -eq 0 ]] && \
623 log_must zfs unmount $TESTPOOL/$TESTCTR/$TESTFS1
624
625 destroy_dataset "$TESTPOOL/$TESTCTR/$TESTFS1" "-R"
626 destroy_dataset "$TESTPOOL/$TESTCTR" "-Rf"
627
628 [[ -e $TESTDIR1 ]] && \
629 log_must rm -rf $TESTDIR1 > /dev/null 2>&1
630
631 default_cleanup
632 }
633
634 #
635 # Common function used to cleanup snapshot of file system or volume. Default to
636 # delete the file system's snapshot
637 #
638 # $1 snapshot name
639 #
640 function destroy_snapshot
641 {
642 typeset snap=${1:-$TESTPOOL/$TESTFS@$TESTSNAP}
643
644 if ! snapexists $snap; then
645 log_fail "'$snap' does not existed."
646 fi
647
648 #
649 # For the sake of the value which come from 'get_prop' is not equal
650 # to the really mountpoint when the snapshot is unmounted. So, firstly
651 # check and make sure this snapshot's been mounted in current system.
652 #
653 typeset mtpt=""
654 if ismounted $snap; then
655 mtpt=$(get_prop mountpoint $snap)
656 (($? != 0)) && \
657 log_fail "get_prop mountpoint $snap failed."
658 fi
659
660 destroy_dataset "$snap"
661 [[ $mtpt != "" && -d $mtpt ]] && \
662 log_must rm -rf $mtpt
663 }
664
665 #
666 # Common function used to cleanup clone.
667 #
668 # $1 clone name
669 #
670 function destroy_clone
671 {
672 typeset clone=${1:-$TESTPOOL/$TESTCLONE}
673
674 if ! datasetexists $clone; then
675 log_fail "'$clone' does not existed."
676 fi
677
678 # With the same reason in destroy_snapshot
679 typeset mtpt=""
680 if ismounted $clone; then
681 mtpt=$(get_prop mountpoint $clone)
682 (($? != 0)) && \
683 log_fail "get_prop mountpoint $clone failed."
684 fi
685
686 destroy_dataset "$clone"
687 [[ $mtpt != "" && -d $mtpt ]] && \
688 log_must rm -rf $mtpt
689 }
690
691 #
692 # Common function used to cleanup bookmark of file system or volume. Default
693 # to delete the file system's bookmark.
694 #
695 # $1 bookmark name
696 #
697 function destroy_bookmark
698 {
699 typeset bkmark=${1:-$TESTPOOL/$TESTFS#$TESTBKMARK}
700
701 if ! bkmarkexists $bkmark; then
702 log_fail "'$bkmarkp' does not existed."
703 fi
704
705 destroy_dataset "$bkmark"
706 }
707
708 # Return 0 if a snapshot exists; $? otherwise
709 #
710 # $1 - snapshot name
711
712 function snapexists
713 {
714 zfs list -H -t snapshot "$1" > /dev/null 2>&1
715 return $?
716 }
717
718 #
719 # Return 0 if a bookmark exists; $? otherwise
720 #
721 # $1 - bookmark name
722 #
723 function bkmarkexists
724 {
725 zfs list -H -t bookmark "$1" > /dev/null 2>&1
726 return $?
727 }
728
729 #
730 # Set a property to a certain value on a dataset.
731 # Sets a property of the dataset to the value as passed in.
732 # @param:
733 # $1 dataset who's property is being set
734 # $2 property to set
735 # $3 value to set property to
736 # @return:
737 # 0 if the property could be set.
738 # non-zero otherwise.
739 # @use: ZFS
740 #
741 function dataset_setprop
742 {
743 typeset fn=dataset_setprop
744
745 if (($# < 3)); then
746 log_note "$fn: Insufficient parameters (need 3, had $#)"
747 return 1
748 fi
749 typeset output=
750 output=$(zfs set $2=$3 $1 2>&1)
751 typeset rv=$?
752 if ((rv != 0)); then
753 log_note "Setting property on $1 failed."
754 log_note "property $2=$3"
755 log_note "Return Code: $rv"
756 log_note "Output: $output"
757 return $rv
758 fi
759 return 0
760 }
761
762 #
763 # Assign suite defined dataset properties.
764 # This function is used to apply the suite's defined default set of
765 # properties to a dataset.
766 # @parameters: $1 dataset to use
767 # @uses: ZFS COMPRESSION_PROP CHECKSUM_PROP
768 # @returns:
769 # 0 if the dataset has been altered.
770 # 1 if no pool name was passed in.
771 # 2 if the dataset could not be found.
772 # 3 if the dataset could not have it's properties set.
773 #
774 function dataset_set_defaultproperties
775 {
776 typeset dataset="$1"
777
778 [[ -z $dataset ]] && return 1
779
780 typeset confset=
781 typeset -i found=0
782 for confset in $(zfs list); do
783 if [[ $dataset = $confset ]]; then
784 found=1
785 break
786 fi
787 done
788 [[ $found -eq 0 ]] && return 2
789 if [[ -n $COMPRESSION_PROP ]]; then
790 dataset_setprop $dataset compression $COMPRESSION_PROP || \
791 return 3
792 log_note "Compression set to '$COMPRESSION_PROP' on $dataset"
793 fi
794 if [[ -n $CHECKSUM_PROP ]]; then
795 dataset_setprop $dataset checksum $CHECKSUM_PROP || \
796 return 3
797 log_note "Checksum set to '$CHECKSUM_PROP' on $dataset"
798 fi
799 return 0
800 }
801
802 #
803 # Check a numeric assertion
804 # @parameter: $@ the assertion to check
805 # @output: big loud notice if assertion failed
806 # @use: log_fail
807 #
808 function assert
809 {
810 (($@)) || log_fail "$@"
811 }
812
813 #
814 # Function to format partition size of a disk
815 # Given a disk cxtxdx reduces all partitions
816 # to 0 size
817 #
818 function zero_partitions #<whole_disk_name>
819 {
820 typeset diskname=$1
821 typeset i
822
823 if is_linux; then
824 DSK=$DEV_DSKDIR/$diskname
825 DSK=$(echo $DSK | sed -e "s|//|/|g")
826 log_must parted $DSK -s -- mklabel gpt
827 blockdev --rereadpt $DSK 2>/dev/null
828 block_device_wait
829 else
830 for i in 0 1 3 4 5 6 7
831 do
832 log_must set_partition $i "" 0mb $diskname
833 done
834 fi
835
836 return 0
837 }
838
839 #
840 # Given a slice, size and disk, this function
841 # formats the slice to the specified size.
842 # Size should be specified with units as per
843 # the `format` command requirements eg. 100mb 3gb
844 #
845 # NOTE: This entire interface is problematic for the Linux parted utilty
846 # which requires the end of the partition to be specified. It would be
847 # best to retire this interface and replace it with something more flexible.
848 # At the moment a best effort is made.
849 #
850 function set_partition #<slice_num> <slice_start> <size_plus_units> <whole_disk_name>
851 {
852 typeset -i slicenum=$1
853 typeset start=$2
854 typeset size=$3
855 typeset disk=$4
856
857 if is_linux; then
858 if [[ -z $size || -z $disk ]]; then
859 log_fail "The size or disk name is unspecified."
860 fi
861 typeset size_mb=${size%%[mMgG]}
862
863 size_mb=${size_mb%%[mMgG][bB]}
864 if [[ ${size:1:1} == 'g' ]]; then
865 ((size_mb = size_mb * 1024))
866 fi
867
868 # Create GPT partition table when setting slice 0 or
869 # when the device doesn't already contain a GPT label.
870 parted $DEV_DSKDIR/$disk -s -- print 1 >/dev/null
871 typeset ret_val=$?
872 if [[ $slicenum -eq 0 || $ret_val -ne 0 ]]; then
873 parted $DEV_DSKDIR/$disk -s -- mklabel gpt
874 if [[ $? -ne 0 ]]; then
875 log_note "Failed to create GPT partition table on $disk"
876 return 1
877 fi
878 fi
879
880 # When no start is given align on the first cylinder.
881 if [[ -z "$start" ]]; then
882 start=1
883 fi
884
885 # Determine the cylinder size for the device and using
886 # that calculate the end offset in cylinders.
887 typeset -i cly_size_kb=0
888 cly_size_kb=$(parted -m $DEV_DSKDIR/$disk -s -- \
889 unit cyl print | head -3 | tail -1 | \
890 awk -F '[:k.]' '{print $4}')
891 ((end = (size_mb * 1024 / cly_size_kb) + start))
892
893 parted $DEV_DSKDIR/$disk -s -- \
894 mkpart part$slicenum ${start}cyl ${end}cyl
895 if [[ $? -ne 0 ]]; then
896 log_note "Failed to create partition $slicenum on $disk"
897 return 1
898 fi
899
900 blockdev --rereadpt $DEV_DSKDIR/$disk 2>/dev/null
901 block_device_wait
902 else
903 if [[ -z $slicenum || -z $size || -z $disk ]]; then
904 log_fail "The slice, size or disk name is unspecified."
905 fi
906
907 typeset format_file=/var/tmp/format_in.$$
908
909 echo "partition" >$format_file
910 echo "$slicenum" >> $format_file
911 echo "" >> $format_file
912 echo "" >> $format_file
913 echo "$start" >> $format_file
914 echo "$size" >> $format_file
915 echo "label" >> $format_file
916 echo "" >> $format_file
917 echo "q" >> $format_file
918 echo "q" >> $format_file
919
920 format -e -s -d $disk -f $format_file
921 fi
922
923 typeset ret_val=$?
924 rm -f $format_file
925 if [[ $ret_val -ne 0 ]]; then
926 log_note "Unable to format $disk slice $slicenum to $size"
927 return 1
928 fi
929 return 0
930 }
931
932 #
933 # Delete all partitions on all disks - this is specifically for the use of multipath
934 # devices which currently can only be used in the test suite as raw/un-partitioned
935 # devices (ie a zpool cannot be created on a whole mpath device that has partitions)
936 #
937 function delete_partitions
938 {
939 typeset -i j=1
940
941 if [[ -z $DISK_ARRAY_NUM ]]; then
942 DISK_ARRAY_NUM=$(echo ${DISKS} | nawk '{print NF}')
943 fi
944 if [[ -z $DISKSARRAY ]]; then
945 DISKSARRAY=$DISKS
946 fi
947
948 if is_linux; then
949 if (( $DISK_ARRAY_NUM == 1 )); then
950 while ((j < MAX_PARTITIONS)); do
951 parted $DEV_DSKDIR/$DISK -s rm $j \
952 > /dev/null 2>&1
953 if (( $? == 1 )); then
954 lsblk | egrep ${DISK}${SLICE_PREFIX}${j} > /dev/null
955 if (( $? == 1 )); then
956 log_note "Partitions for $DISK should be deleted"
957 else
958 log_fail "Partition for ${DISK}${SLICE_PREFIX}${j} not deleted"
959 fi
960 return 0
961 else
962 lsblk | egrep ${DISK}${SLICE_PREFIX}${j} > /dev/null
963 if (( $? == 0 )); then
964 log_fail "Partition for ${DISK}${SLICE_PREFIX}${j} not deleted"
965 fi
966 fi
967 ((j = j+1))
968 done
969 else
970 for disk in `echo $DISKSARRAY`; do
971 while ((j < MAX_PARTITIONS)); do
972 parted $DEV_DSKDIR/$disk -s rm $j > /dev/null 2>&1
973 if (( $? == 1 )); then
974 lsblk | egrep ${disk}${SLICE_PREFIX}${j} > /dev/null
975 if (( $? == 1 )); then
976 log_note "Partitions for $disk should be deleted"
977 else
978 log_fail "Partition for ${disk}${SLICE_PREFIX}${j} not deleted"
979 fi
980 j=7
981 else
982 lsblk | egrep ${disk}${SLICE_PREFIX}${j} > /dev/null
983 if (( $? == 0 )); then
984 log_fail "Partition for ${disk}${SLICE_PREFIX}${j} not deleted"
985 fi
986 fi
987 ((j = j+1))
988 done
989 j=1
990 done
991 fi
992 fi
993 return 0
994 }
995
996 #
997 # Get the end cyl of the given slice
998 #
999 function get_endslice #<disk> <slice>
1000 {
1001 typeset disk=$1
1002 typeset slice=$2
1003 if [[ -z $disk || -z $slice ]] ; then
1004 log_fail "The disk name or slice number is unspecified."
1005 fi
1006
1007 if is_linux; then
1008 endcyl=$(parted -s $DEV_DSKDIR/$disk -- unit cyl print | \
1009 grep "part${slice}" | \
1010 awk '{print $3}' | \
1011 sed 's,cyl,,')
1012 ((endcyl = (endcyl + 1)))
1013 else
1014 disk=${disk#/dev/dsk/}
1015 disk=${disk#/dev/rdsk/}
1016 disk=${disk%s*}
1017
1018 typeset -i ratio=0
1019 ratio=$(prtvtoc /dev/rdsk/${disk}s2 | \
1020 grep "sectors\/cylinder" | \
1021 awk '{print $2}')
1022
1023 if ((ratio == 0)); then
1024 return
1025 fi
1026
1027 typeset -i endcyl=$(prtvtoc -h /dev/rdsk/${disk}s2 |
1028 nawk -v token="$slice" '{if ($1==token) print $6}')
1029
1030 ((endcyl = (endcyl + 1) / ratio))
1031 fi
1032
1033 echo $endcyl
1034 }
1035
1036
1037 #
1038 # Given a size,disk and total slice number, this function formats the
1039 # disk slices from 0 to the total slice number with the same specified
1040 # size.
1041 #
1042 function partition_disk #<slice_size> <whole_disk_name> <total_slices>
1043 {
1044 typeset -i i=0
1045 typeset slice_size=$1
1046 typeset disk_name=$2
1047 typeset total_slices=$3
1048 typeset cyl
1049
1050 zero_partitions $disk_name
1051 while ((i < $total_slices)); do
1052 if ! is_linux; then
1053 if ((i == 2)); then
1054 ((i = i + 1))
1055 continue
1056 fi
1057 fi
1058 log_must set_partition $i "$cyl" $slice_size $disk_name
1059 cyl=$(get_endslice $disk_name $i)
1060 ((i = i+1))
1061 done
1062 }
1063
1064 #
1065 # This function continues to write to a filenum number of files into dirnum
1066 # number of directories until either file_write returns an error or the
1067 # maximum number of files per directory have been written.
1068 #
1069 # Usage:
1070 # fill_fs [destdir] [dirnum] [filenum] [bytes] [num_writes] [data]
1071 #
1072 # Return value: 0 on success
1073 # non 0 on error
1074 #
1075 # Where :
1076 # destdir: is the directory where everything is to be created under
1077 # dirnum: the maximum number of subdirectories to use, -1 no limit
1078 # filenum: the maximum number of files per subdirectory
1079 # bytes: number of bytes to write
1080 # num_writes: numer of types to write out bytes
1081 # data: the data that will be written
1082 #
1083 # E.g.
1084 # file_fs /testdir 20 25 1024 256 0
1085 #
1086 # Note: bytes * num_writes equals the size of the testfile
1087 #
1088 function fill_fs # destdir dirnum filenum bytes num_writes data
1089 {
1090 typeset destdir=${1:-$TESTDIR}
1091 typeset -i dirnum=${2:-50}
1092 typeset -i filenum=${3:-50}
1093 typeset -i bytes=${4:-8192}
1094 typeset -i num_writes=${5:-10240}
1095 typeset -i data=${6:-0}
1096
1097 typeset -i odirnum=1
1098 typeset -i idirnum=0
1099 typeset -i fn=0
1100 typeset -i retval=0
1101
1102 log_must mkdir -p $destdir/$idirnum
1103 while (($odirnum > 0)); do
1104 if ((dirnum >= 0 && idirnum >= dirnum)); then
1105 odirnum=0
1106 break
1107 fi
1108 file_write -o create -f $destdir/$idirnum/$TESTFILE.$fn \
1109 -b $bytes -c $num_writes -d $data
1110 retval=$?
1111 if (($retval != 0)); then
1112 odirnum=0
1113 break
1114 fi
1115 if (($fn >= $filenum)); then
1116 fn=0
1117 ((idirnum = idirnum + 1))
1118 log_must mkdir -p $destdir/$idirnum
1119 else
1120 ((fn = fn + 1))
1121 fi
1122 done
1123 return $retval
1124 }
1125
1126 #
1127 # Simple function to get the specified property. If unable to
1128 # get the property then exits.
1129 #
1130 # Note property is in 'parsable' format (-p)
1131 #
1132 function get_prop # property dataset
1133 {
1134 typeset prop_val
1135 typeset prop=$1
1136 typeset dataset=$2
1137
1138 prop_val=$(zfs get -pH -o value $prop $dataset 2>/dev/null)
1139 if [[ $? -ne 0 ]]; then
1140 log_note "Unable to get $prop property for dataset " \
1141 "$dataset"
1142 return 1
1143 fi
1144
1145 echo "$prop_val"
1146 return 0
1147 }
1148
1149 #
1150 # Simple function to get the specified property of pool. If unable to
1151 # get the property then exits.
1152 #
1153 # Note property is in 'parsable' format (-p)
1154 #
1155 function get_pool_prop # property pool
1156 {
1157 typeset prop_val
1158 typeset prop=$1
1159 typeset pool=$2
1160
1161 if poolexists $pool ; then
1162 prop_val=$(zpool get -pH $prop $pool 2>/dev/null | tail -1 | \
1163 awk '{print $3}')
1164 if [[ $? -ne 0 ]]; then
1165 log_note "Unable to get $prop property for pool " \
1166 "$pool"
1167 return 1
1168 fi
1169 else
1170 log_note "Pool $pool not exists."
1171 return 1
1172 fi
1173
1174 echo "$prop_val"
1175 return 0
1176 }
1177
1178 # Return 0 if a pool exists; $? otherwise
1179 #
1180 # $1 - pool name
1181
1182 function poolexists
1183 {
1184 typeset pool=$1
1185
1186 if [[ -z $pool ]]; then
1187 log_note "No pool name given."
1188 return 1
1189 fi
1190
1191 zpool get name "$pool" > /dev/null 2>&1
1192 return $?
1193 }
1194
1195 # Return 0 if all the specified datasets exist; $? otherwise
1196 #
1197 # $1-n dataset name
1198 function datasetexists
1199 {
1200 if (($# == 0)); then
1201 log_note "No dataset name given."
1202 return 1
1203 fi
1204
1205 while (($# > 0)); do
1206 zfs get name $1 > /dev/null 2>&1 || \
1207 return $?
1208 shift
1209 done
1210
1211 return 0
1212 }
1213
1214 # return 0 if none of the specified datasets exists, otherwise return 1.
1215 #
1216 # $1-n dataset name
1217 function datasetnonexists
1218 {
1219 if (($# == 0)); then
1220 log_note "No dataset name given."
1221 return 1
1222 fi
1223
1224 while (($# > 0)); do
1225 zfs list -H -t filesystem,snapshot,volume $1 > /dev/null 2>&1 \
1226 && return 1
1227 shift
1228 done
1229
1230 return 0
1231 }
1232
1233 #
1234 # Given a mountpoint, or a dataset name, determine if it is shared via NFS.
1235 #
1236 # Returns 0 if shared, 1 otherwise.
1237 #
1238 function is_shared
1239 {
1240 typeset fs=$1
1241 typeset mtpt
1242
1243 if [[ $fs != "/"* ]] ; then
1244 if datasetnonexists "$fs" ; then
1245 return 1
1246 else
1247 mtpt=$(get_prop mountpoint "$fs")
1248 case $mtpt in
1249 none|legacy|-) return 1
1250 ;;
1251 *) fs=$mtpt
1252 ;;
1253 esac
1254 fi
1255 fi
1256
1257 if is_linux; then
1258 for mtpt in `share | awk '{print $1}'` ; do
1259 if [[ $mtpt == $fs ]] ; then
1260 return 0
1261 fi
1262 done
1263 return 1
1264 fi
1265
1266 for mtpt in `share | awk '{print $2}'` ; do
1267 if [[ $mtpt == $fs ]] ; then
1268 return 0
1269 fi
1270 done
1271
1272 typeset stat=$(svcs -H -o STA nfs/server:default)
1273 if [[ $stat != "ON" ]]; then
1274 log_note "Current nfs/server status: $stat"
1275 fi
1276
1277 return 1
1278 }
1279
1280 #
1281 # Given a dataset name determine if it is shared via SMB.
1282 #
1283 # Returns 0 if shared, 1 otherwise.
1284 #
1285 function is_shared_smb
1286 {
1287 typeset fs=$1
1288 typeset mtpt
1289
1290 if datasetnonexists "$fs" ; then
1291 return 1
1292 else
1293 fs=$(echo $fs | sed 's@/@_@g')
1294 fi
1295
1296 if is_linux; then
1297 for mtpt in `net usershare list | awk '{print $1}'` ; do
1298 if [[ $mtpt == $fs ]] ; then
1299 return 0
1300 fi
1301 done
1302 return 1
1303 else
1304 log_unsupported "Currently unsupported by the test framework"
1305 return 1
1306 fi
1307 }
1308
1309 #
1310 # Given a mountpoint, determine if it is not shared via NFS.
1311 #
1312 # Returns 0 if not shared, 1 otherwise.
1313 #
1314 function not_shared
1315 {
1316 typeset fs=$1
1317
1318 is_shared $fs
1319 if (($? == 0)); then
1320 return 1
1321 fi
1322
1323 return 0
1324 }
1325
1326 #
1327 # Given a dataset determine if it is not shared via SMB.
1328 #
1329 # Returns 0 if not shared, 1 otherwise.
1330 #
1331 function not_shared_smb
1332 {
1333 typeset fs=$1
1334
1335 is_shared_smb $fs
1336 if (($? == 0)); then
1337 return 1
1338 fi
1339
1340 return 0
1341 }
1342
1343 #
1344 # Helper function to unshare a mountpoint.
1345 #
1346 function unshare_fs #fs
1347 {
1348 typeset fs=$1
1349
1350 is_shared $fs || is_shared_smb $fs
1351 if (($? == 0)); then
1352 log_must zfs unshare $fs
1353 fi
1354
1355 return 0
1356 }
1357
1358 #
1359 # Helper function to share a NFS mountpoint.
1360 #
1361 function share_nfs #fs
1362 {
1363 typeset fs=$1
1364
1365 if is_linux; then
1366 is_shared $fs
1367 if (($? != 0)); then
1368 log_must share "*:$fs"
1369 fi
1370 else
1371 is_shared $fs
1372 if (($? != 0)); then
1373 log_must share -F nfs $fs
1374 fi
1375 fi
1376
1377 return 0
1378 }
1379
1380 #
1381 # Helper function to unshare a NFS mountpoint.
1382 #
1383 function unshare_nfs #fs
1384 {
1385 typeset fs=$1
1386
1387 if is_linux; then
1388 is_shared $fs
1389 if (($? == 0)); then
1390 log_must unshare -u "*:$fs"
1391 fi
1392 else
1393 is_shared $fs
1394 if (($? == 0)); then
1395 log_must unshare -F nfs $fs
1396 fi
1397 fi
1398
1399 return 0
1400 }
1401
1402 #
1403 # Helper function to show NFS shares.
1404 #
1405 function showshares_nfs
1406 {
1407 if is_linux; then
1408 share -v
1409 else
1410 share -F nfs
1411 fi
1412
1413 return 0
1414 }
1415
1416 #
1417 # Helper function to show SMB shares.
1418 #
1419 function showshares_smb
1420 {
1421 if is_linux; then
1422 net usershare list
1423 else
1424 share -F smb
1425 fi
1426
1427 return 0
1428 }
1429
1430 #
1431 # Check NFS server status and trigger it online.
1432 #
1433 function setup_nfs_server
1434 {
1435 # Cannot share directory in non-global zone.
1436 #
1437 if ! is_global_zone; then
1438 log_note "Cannot trigger NFS server by sharing in LZ."
1439 return
1440 fi
1441
1442 if is_linux; then
1443 #
1444 # Re-synchronize /var/lib/nfs/etab with /etc/exports and
1445 # /etc/exports.d./* to provide a clean test environment.
1446 #
1447 log_must share -r
1448
1449 log_note "NFS server must be started prior to running ZTS."
1450 return
1451 fi
1452
1453 typeset nfs_fmri="svc:/network/nfs/server:default"
1454 if [[ $(svcs -Ho STA $nfs_fmri) != "ON" ]]; then
1455 #
1456 # Only really sharing operation can enable NFS server
1457 # to online permanently.
1458 #
1459 typeset dummy=/tmp/dummy
1460
1461 if [[ -d $dummy ]]; then
1462 log_must rm -rf $dummy
1463 fi
1464
1465 log_must mkdir $dummy
1466 log_must share $dummy
1467
1468 #
1469 # Waiting for fmri's status to be the final status.
1470 # Otherwise, in transition, an asterisk (*) is appended for
1471 # instances, unshare will reverse status to 'DIS' again.
1472 #
1473 # Waiting for 1's at least.
1474 #
1475 log_must sleep 1
1476 timeout=10
1477 while [[ timeout -ne 0 && $(svcs -Ho STA $nfs_fmri) == *'*' ]]
1478 do
1479 log_must sleep 1
1480
1481 ((timeout -= 1))
1482 done
1483
1484 log_must unshare $dummy
1485 log_must rm -rf $dummy
1486 fi
1487
1488 log_note "Current NFS status: '$(svcs -Ho STA,FMRI $nfs_fmri)'"
1489 }
1490
1491 #
1492 # To verify whether calling process is in global zone
1493 #
1494 # Return 0 if in global zone, 1 in non-global zone
1495 #
1496 function is_global_zone
1497 {
1498 if is_linux; then
1499 return 0
1500 else
1501 typeset cur_zone=$(zonename 2>/dev/null)
1502 if [[ $cur_zone != "global" ]]; then
1503 return 1
1504 fi
1505 return 0
1506 fi
1507 }
1508
1509 #
1510 # Verify whether test is permitted to run from
1511 # global zone, local zone, or both
1512 #
1513 # $1 zone limit, could be "global", "local", or "both"(no limit)
1514 #
1515 # Return 0 if permitted, otherwise exit with log_unsupported
1516 #
1517 function verify_runnable # zone limit
1518 {
1519 typeset limit=$1
1520
1521 [[ -z $limit ]] && return 0
1522
1523 if is_global_zone ; then
1524 case $limit in
1525 global|both)
1526 ;;
1527 local) log_unsupported "Test is unable to run from "\
1528 "global zone."
1529 ;;
1530 *) log_note "Warning: unknown limit $limit - " \
1531 "use both."
1532 ;;
1533 esac
1534 else
1535 case $limit in
1536 local|both)
1537 ;;
1538 global) log_unsupported "Test is unable to run from "\
1539 "local zone."
1540 ;;
1541 *) log_note "Warning: unknown limit $limit - " \
1542 "use both."
1543 ;;
1544 esac
1545
1546 reexport_pool
1547 fi
1548
1549 return 0
1550 }
1551
1552 # Return 0 if create successfully or the pool exists; $? otherwise
1553 # Note: In local zones, this function should return 0 silently.
1554 #
1555 # $1 - pool name
1556 # $2-n - [keyword] devs_list
1557
1558 function create_pool #pool devs_list
1559 {
1560 typeset pool=${1%%/*}
1561
1562 shift
1563
1564 if [[ -z $pool ]]; then
1565 log_note "Missing pool name."
1566 return 1
1567 fi
1568
1569 if poolexists $pool ; then
1570 destroy_pool $pool
1571 fi
1572
1573 if is_global_zone ; then
1574 [[ -d /$pool ]] && rm -rf /$pool
1575 log_must zpool create -f $pool $@
1576 fi
1577
1578 return 0
1579 }
1580
1581 # Return 0 if destroy successfully or the pool exists; $? otherwise
1582 # Note: In local zones, this function should return 0 silently.
1583 #
1584 # $1 - pool name
1585 # Destroy pool with the given parameters.
1586
1587 function destroy_pool #pool
1588 {
1589 typeset pool=${1%%/*}
1590 typeset mtpt
1591
1592 if [[ -z $pool ]]; then
1593 log_note "No pool name given."
1594 return 1
1595 fi
1596
1597 if is_global_zone ; then
1598 if poolexists "$pool" ; then
1599 mtpt=$(get_prop mountpoint "$pool")
1600
1601 # At times, syseventd/udev activity can cause attempts
1602 # to destroy a pool to fail with EBUSY. We retry a few
1603 # times allowing failures before requiring the destroy
1604 # to succeed.
1605 log_must_busy zpool destroy -f $pool
1606
1607 [[ -d $mtpt ]] && \
1608 log_must rm -rf $mtpt
1609 else
1610 log_note "Pool does not exist. ($pool)"
1611 return 1
1612 fi
1613 fi
1614
1615 return 0
1616 }
1617
1618 # Return 0 if created successfully; $? otherwise
1619 #
1620 # $1 - dataset name
1621 # $2-n - dataset options
1622
1623 function create_dataset #dataset dataset_options
1624 {
1625 typeset dataset=$1
1626
1627 shift
1628
1629 if [[ -z $dataset ]]; then
1630 log_note "Missing dataset name."
1631 return 1
1632 fi
1633
1634 if datasetexists $dataset ; then
1635 destroy_dataset $dataset
1636 fi
1637
1638 log_must zfs create $@ $dataset
1639
1640 return 0
1641 }
1642
1643 # Return 0 if destroy successfully or the dataset exists; $? otherwise
1644 # Note: In local zones, this function should return 0 silently.
1645 #
1646 # $1 - dataset name
1647 # $2 - custom arguments for zfs destroy
1648 # Destroy dataset with the given parameters.
1649
1650 function destroy_dataset #dataset #args
1651 {
1652 typeset dataset=$1
1653 typeset mtpt
1654 typeset args=${2:-""}
1655
1656 if [[ -z $dataset ]]; then
1657 log_note "No dataset name given."
1658 return 1
1659 fi
1660
1661 if is_global_zone ; then
1662 if datasetexists "$dataset" ; then
1663 mtpt=$(get_prop mountpoint "$dataset")
1664 log_must_busy zfs destroy $args $dataset
1665
1666 [[ -d $mtpt ]] && \
1667 log_must rm -rf $mtpt
1668 else
1669 log_note "Dataset does not exist. ($dataset)"
1670 return 1
1671 fi
1672 fi
1673
1674 return 0
1675 }
1676
1677 #
1678 # Firstly, create a pool with 5 datasets. Then, create a single zone and
1679 # export the 5 datasets to it. In addition, we also add a ZFS filesystem
1680 # and a zvol device to the zone.
1681 #
1682 # $1 zone name
1683 # $2 zone root directory prefix
1684 # $3 zone ip
1685 #
1686 function zfs_zones_setup #zone_name zone_root zone_ip
1687 {
1688 typeset zone_name=${1:-$(hostname)-z}
1689 typeset zone_root=${2:-"/zone_root"}
1690 typeset zone_ip=${3:-"10.1.1.10"}
1691 typeset prefix_ctr=$ZONE_CTR
1692 typeset pool_name=$ZONE_POOL
1693 typeset -i cntctr=5
1694 typeset -i i=0
1695
1696 # Create pool and 5 container within it
1697 #
1698 [[ -d /$pool_name ]] && rm -rf /$pool_name
1699 log_must zpool create -f $pool_name $DISKS
1700 while ((i < cntctr)); do
1701 log_must zfs create $pool_name/$prefix_ctr$i
1702 ((i += 1))
1703 done
1704
1705 # create a zvol
1706 log_must zfs create -V 1g $pool_name/zone_zvol
1707 block_device_wait
1708
1709 #
1710 # If current system support slog, add slog device for pool
1711 #
1712 if verify_slog_support ; then
1713 typeset sdevs="$TEST_BASE_DIR/sdev1 $TEST_BASE_DIR/sdev2"
1714 log_must mkfile $MINVDEVSIZE $sdevs
1715 log_must zpool add $pool_name log mirror $sdevs
1716 fi
1717
1718 # this isn't supported just yet.
1719 # Create a filesystem. In order to add this to
1720 # the zone, it must have it's mountpoint set to 'legacy'
1721 # log_must zfs create $pool_name/zfs_filesystem
1722 # log_must zfs set mountpoint=legacy $pool_name/zfs_filesystem
1723
1724 [[ -d $zone_root ]] && \
1725 log_must rm -rf $zone_root/$zone_name
1726 [[ ! -d $zone_root ]] && \
1727 log_must mkdir -p -m 0700 $zone_root/$zone_name
1728
1729 # Create zone configure file and configure the zone
1730 #
1731 typeset zone_conf=/tmp/zone_conf.$$
1732 echo "create" > $zone_conf
1733 echo "set zonepath=$zone_root/$zone_name" >> $zone_conf
1734 echo "set autoboot=true" >> $zone_conf
1735 i=0
1736 while ((i < cntctr)); do
1737 echo "add dataset" >> $zone_conf
1738 echo "set name=$pool_name/$prefix_ctr$i" >> \
1739 $zone_conf
1740 echo "end" >> $zone_conf
1741 ((i += 1))
1742 done
1743
1744 # add our zvol to the zone
1745 echo "add device" >> $zone_conf
1746 echo "set match=/dev/zvol/dsk/$pool_name/zone_zvol" >> $zone_conf
1747 echo "end" >> $zone_conf
1748
1749 # add a corresponding zvol rdsk to the zone
1750 echo "add device" >> $zone_conf
1751 echo "set match=$ZVOL_RDEVDIR/$pool_name/zone_zvol" >> $zone_conf
1752 echo "end" >> $zone_conf
1753
1754 # once it's supported, we'll add our filesystem to the zone
1755 # echo "add fs" >> $zone_conf
1756 # echo "set type=zfs" >> $zone_conf
1757 # echo "set special=$pool_name/zfs_filesystem" >> $zone_conf
1758 # echo "set dir=/export/zfs_filesystem" >> $zone_conf
1759 # echo "end" >> $zone_conf
1760
1761 echo "verify" >> $zone_conf
1762 echo "commit" >> $zone_conf
1763 log_must zonecfg -z $zone_name -f $zone_conf
1764 log_must rm -f $zone_conf
1765
1766 # Install the zone
1767 zoneadm -z $zone_name install
1768 if (($? == 0)); then
1769 log_note "SUCCESS: zoneadm -z $zone_name install"
1770 else
1771 log_fail "FAIL: zoneadm -z $zone_name install"
1772 fi
1773
1774 # Install sysidcfg file
1775 #
1776 typeset sysidcfg=$zone_root/$zone_name/root/etc/sysidcfg
1777 echo "system_locale=C" > $sysidcfg
1778 echo "terminal=dtterm" >> $sysidcfg
1779 echo "network_interface=primary {" >> $sysidcfg
1780 echo "hostname=$zone_name" >> $sysidcfg
1781 echo "}" >> $sysidcfg
1782 echo "name_service=NONE" >> $sysidcfg
1783 echo "root_password=mo791xfZ/SFiw" >> $sysidcfg
1784 echo "security_policy=NONE" >> $sysidcfg
1785 echo "timezone=US/Eastern" >> $sysidcfg
1786
1787 # Boot this zone
1788 log_must zoneadm -z $zone_name boot
1789 }
1790
1791 #
1792 # Reexport TESTPOOL & TESTPOOL(1-4)
1793 #
1794 function reexport_pool
1795 {
1796 typeset -i cntctr=5
1797 typeset -i i=0
1798
1799 while ((i < cntctr)); do
1800 if ((i == 0)); then
1801 TESTPOOL=$ZONE_POOL/$ZONE_CTR$i
1802 if ! ismounted $TESTPOOL; then
1803 log_must zfs mount $TESTPOOL
1804 fi
1805 else
1806 eval TESTPOOL$i=$ZONE_POOL/$ZONE_CTR$i
1807 if eval ! ismounted \$TESTPOOL$i; then
1808 log_must eval zfs mount \$TESTPOOL$i
1809 fi
1810 fi
1811 ((i += 1))
1812 done
1813 }
1814
1815 #
1816 # Verify a given disk or pool state
1817 #
1818 # Return 0 is pool/disk matches expected state, 1 otherwise
1819 #
1820 function check_state # pool disk state{online,offline,degraded}
1821 {
1822 typeset pool=$1
1823 typeset disk=${2#$DEV_DSKDIR/}
1824 typeset state=$3
1825
1826 [[ -z $pool ]] || [[ -z $state ]] \
1827 && log_fail "Arguments invalid or missing"
1828
1829 if [[ -z $disk ]]; then
1830 #check pool state only
1831 zpool get -H -o value health $pool \
1832 | grep -i "$state" > /dev/null 2>&1
1833 else
1834 zpool status -v $pool | grep "$disk" \
1835 | grep -i "$state" > /dev/null 2>&1
1836 fi
1837
1838 return $?
1839 }
1840
1841 #
1842 # Get the mountpoint of snapshot
1843 # For the snapshot use <mp_filesystem>/.zfs/snapshot/<snap>
1844 # as its mountpoint
1845 #
1846 function snapshot_mountpoint
1847 {
1848 typeset dataset=${1:-$TESTPOOL/$TESTFS@$TESTSNAP}
1849
1850 if [[ $dataset != *@* ]]; then
1851 log_fail "Error name of snapshot '$dataset'."
1852 fi
1853
1854 typeset fs=${dataset%@*}
1855 typeset snap=${dataset#*@}
1856
1857 if [[ -z $fs || -z $snap ]]; then
1858 log_fail "Error name of snapshot '$dataset'."
1859 fi
1860
1861 echo $(get_prop mountpoint $fs)/.zfs/snapshot/$snap
1862 }
1863
1864 #
1865 # Given a device and 'ashift' value verify it's correctly set on every label
1866 #
1867 function verify_ashift # device ashift
1868 {
1869 typeset device="$1"
1870 typeset ashift="$2"
1871
1872 zdb -e -lll $device | awk -v ashift=$ashift '/ashift: / {
1873 if (ashift != $2)
1874 exit 1;
1875 else
1876 count++;
1877 } END {
1878 if (count != 4)
1879 exit 1;
1880 else
1881 exit 0;
1882 }'
1883
1884 return $?
1885 }
1886
1887 #
1888 # Given a pool and file system, this function will verify the file system
1889 # using the zdb internal tool. Note that the pool is exported and imported
1890 # to ensure it has consistent state.
1891 #
1892 function verify_filesys # pool filesystem dir
1893 {
1894 typeset pool="$1"
1895 typeset filesys="$2"
1896 typeset zdbout="/tmp/zdbout.$$"
1897
1898 shift
1899 shift
1900 typeset dirs=$@
1901 typeset search_path=""
1902
1903 log_note "Calling zdb to verify filesystem '$filesys'"
1904 zfs unmount -a > /dev/null 2>&1
1905 log_must zpool export $pool
1906
1907 if [[ -n $dirs ]] ; then
1908 for dir in $dirs ; do
1909 search_path="$search_path -d $dir"
1910 done
1911 fi
1912
1913 log_must zpool import $search_path $pool
1914
1915 zdb -cudi $filesys > $zdbout 2>&1
1916 if [[ $? != 0 ]]; then
1917 log_note "Output: zdb -cudi $filesys"
1918 cat $zdbout
1919 log_fail "zdb detected errors with: '$filesys'"
1920 fi
1921
1922 log_must zfs mount -a
1923 log_must rm -rf $zdbout
1924 }
1925
1926 #
1927 # Given a pool, and this function list all disks in the pool
1928 #
1929 function get_disklist # pool
1930 {
1931 typeset disklist=""
1932
1933 disklist=$(zpool iostat -v $1 | nawk '(NR >4) {print $1}' | \
1934 grep -v "\-\-\-\-\-" | \
1935 egrep -v -e "^(mirror|raidz1|raidz2|spare|log|cache)$")
1936
1937 echo $disklist
1938 }
1939
1940 #
1941 # Given a pool, and this function list all disks in the pool with their full
1942 # path (like "/dev/sda" instead of "sda").
1943 #
1944 function get_disklist_fullpath # pool
1945 {
1946 args="-P $1"
1947 get_disklist $args
1948 }
1949
1950
1951
1952 # /**
1953 # This function kills a given list of processes after a time period. We use
1954 # this in the stress tests instead of STF_TIMEOUT so that we can have processes
1955 # run for a fixed amount of time, yet still pass. Tests that hit STF_TIMEOUT
1956 # would be listed as FAIL, which we don't want : we're happy with stress tests
1957 # running for a certain amount of time, then finishing.
1958 #
1959 # @param $1 the time in seconds after which we should terminate these processes
1960 # @param $2..$n the processes we wish to terminate.
1961 # */
1962 function stress_timeout
1963 {
1964 typeset -i TIMEOUT=$1
1965 shift
1966 typeset cpids="$@"
1967
1968 log_note "Waiting for child processes($cpids). " \
1969 "It could last dozens of minutes, please be patient ..."
1970 log_must sleep $TIMEOUT
1971
1972 log_note "Killing child processes after ${TIMEOUT} stress timeout."
1973 typeset pid
1974 for pid in $cpids; do
1975 ps -p $pid > /dev/null 2>&1
1976 if (($? == 0)); then
1977 log_must kill -USR1 $pid
1978 fi
1979 done
1980 }
1981
1982 #
1983 # Verify a given hotspare disk is inuse or avail
1984 #
1985 # Return 0 is pool/disk matches expected state, 1 otherwise
1986 #
1987 function check_hotspare_state # pool disk state{inuse,avail}
1988 {
1989 typeset pool=$1
1990 typeset disk=${2#$DEV_DSKDIR/}
1991 typeset state=$3
1992
1993 cur_state=$(get_device_state $pool $disk "spares")
1994
1995 if [[ $state != ${cur_state} ]]; then
1996 return 1
1997 fi
1998 return 0
1999 }
2000
2001 #
2002 # Wait until a hotspare transitions to a given state or times out.
2003 #
2004 # Return 0 when pool/disk matches expected state, 1 on timeout.
2005 #
2006 function wait_hotspare_state # pool disk state timeout
2007 {
2008 typeset pool=$1
2009 typeset disk=${2#*$DEV_DSKDIR/}
2010 typeset state=$3
2011 typeset timeout=${4:-60}
2012 typeset -i i=0
2013
2014 while [[ $i -lt $timeout ]]; do
2015 if check_hotspare_state $pool $disk $state; then
2016 return 0
2017 fi
2018
2019 i=$((i+1))
2020 sleep 1
2021 done
2022
2023 return 1
2024 }
2025
2026 #
2027 # Verify a given slog disk is inuse or avail
2028 #
2029 # Return 0 is pool/disk matches expected state, 1 otherwise
2030 #
2031 function check_slog_state # pool disk state{online,offline,unavail}
2032 {
2033 typeset pool=$1
2034 typeset disk=${2#$DEV_DSKDIR/}
2035 typeset state=$3
2036
2037 cur_state=$(get_device_state $pool $disk "logs")
2038
2039 if [[ $state != ${cur_state} ]]; then
2040 return 1
2041 fi
2042 return 0
2043 }
2044
2045 #
2046 # Verify a given vdev disk is inuse or avail
2047 #
2048 # Return 0 is pool/disk matches expected state, 1 otherwise
2049 #
2050 function check_vdev_state # pool disk state{online,offline,unavail}
2051 {
2052 typeset pool=$1
2053 typeset disk=${2#*$DEV_DSKDIR/}
2054 typeset state=$3
2055
2056 cur_state=$(get_device_state $pool $disk)
2057
2058 if [[ $state != ${cur_state} ]]; then
2059 return 1
2060 fi
2061 return 0
2062 }
2063
2064 #
2065 # Wait until a vdev transitions to a given state or times out.
2066 #
2067 # Return 0 when pool/disk matches expected state, 1 on timeout.
2068 #
2069 function wait_vdev_state # pool disk state timeout
2070 {
2071 typeset pool=$1
2072 typeset disk=${2#*$DEV_DSKDIR/}
2073 typeset state=$3
2074 typeset timeout=${4:-60}
2075 typeset -i i=0
2076
2077 while [[ $i -lt $timeout ]]; do
2078 if check_vdev_state $pool $disk $state; then
2079 return 0
2080 fi
2081
2082 i=$((i+1))
2083 sleep 1
2084 done
2085
2086 return 1
2087 }
2088
2089 #
2090 # Check the output of 'zpool status -v <pool>',
2091 # and to see if the content of <token> contain the <keyword> specified.
2092 #
2093 # Return 0 is contain, 1 otherwise
2094 #
2095 function check_pool_status # pool token keyword <verbose>
2096 {
2097 typeset pool=$1
2098 typeset token=$2
2099 typeset keyword=$3
2100 typeset verbose=${4:-false}
2101
2102 scan=$(zpool status -v "$pool" 2>/dev/null | nawk -v token="$token:" '
2103 ($1==token) {print $0}')
2104 if [[ $verbose == true ]]; then
2105 log_note $scan
2106 fi
2107 echo $scan | grep -i "$keyword" > /dev/null 2>&1
2108
2109 return $?
2110 }
2111
2112 #
2113 # These 6 following functions are instance of check_pool_status()
2114 # is_pool_resilvering - to check if the pool is resilver in progress
2115 # is_pool_resilvered - to check if the pool is resilver completed
2116 # is_pool_scrubbing - to check if the pool is scrub in progress
2117 # is_pool_scrubbed - to check if the pool is scrub completed
2118 # is_pool_scrub_stopped - to check if the pool is scrub stopped
2119 # is_pool_scrub_paused - to check if the pool has scrub paused
2120 # is_pool_removing - to check if the pool is removing a vdev
2121 # is_pool_removed - to check if the pool is remove completed
2122 #
2123 function is_pool_resilvering #pool <verbose>
2124 {
2125 check_pool_status "$1" "scan" "resilver in progress since " $2
2126 return $?
2127 }
2128
2129 function is_pool_resilvered #pool <verbose>
2130 {
2131 check_pool_status "$1" "scan" "resilvered " $2
2132 return $?
2133 }
2134
2135 function is_pool_scrubbing #pool <verbose>
2136 {
2137 check_pool_status "$1" "scan" "scrub in progress since " $2
2138 return $?
2139 }
2140
2141 function is_pool_scrubbed #pool <verbose>
2142 {
2143 check_pool_status "$1" "scan" "scrub repaired" $2
2144 return $?
2145 }
2146
2147 function is_pool_scrub_stopped #pool <verbose>
2148 {
2149 check_pool_status "$1" "scan" "scrub canceled" $2
2150 return $?
2151 }
2152
2153 function is_pool_scrub_paused #pool <verbose>
2154 {
2155 check_pool_status "$1" "scan" "scrub paused since " $2
2156 return $?
2157 }
2158
2159 function is_pool_removing #pool
2160 {
2161 check_pool_status "$1" "remove" "in progress since "
2162 return $?
2163 }
2164
2165 function is_pool_removed #pool
2166 {
2167 check_pool_status "$1" "remove" "completed on"
2168 return $?
2169 }
2170
2171 function wait_for_degraded
2172 {
2173 typeset pool=$1
2174 typeset timeout=${2:-30}
2175 typeset t0=$SECONDS
2176
2177 while :; do
2178 [[ $(get_pool_prop health $pool) == "DEGRADED" ]] && break
2179 log_note "$pool is not yet degraded."
2180 sleep 1
2181 if ((SECONDS - t0 > $timeout)); then
2182 log_note "$pool not degraded after $timeout seconds."
2183 return 1
2184 fi
2185 done
2186
2187 return 0
2188 }
2189
2190 #
2191 # Use create_pool()/destroy_pool() to clean up the information in
2192 # in the given disk to avoid slice overlapping.
2193 #
2194 function cleanup_devices #vdevs
2195 {
2196 typeset pool="foopool$$"
2197
2198 if poolexists $pool ; then
2199 destroy_pool $pool
2200 fi
2201
2202 create_pool $pool $@
2203 destroy_pool $pool
2204
2205 return 0
2206 }
2207
2208 #/**
2209 # A function to find and locate free disks on a system or from given
2210 # disks as the parameter. It works by locating disks that are in use
2211 # as swap devices and dump devices, and also disks listed in /etc/vfstab
2212 #
2213 # $@ given disks to find which are free, default is all disks in
2214 # the test system
2215 #
2216 # @return a string containing the list of available disks
2217 #*/
2218 function find_disks
2219 {
2220 # Trust provided list, no attempt is made to locate unused devices.
2221 if is_linux; then
2222 echo "$@"
2223 return
2224 fi
2225
2226
2227 sfi=/tmp/swaplist.$$
2228 dmpi=/tmp/dumpdev.$$
2229 max_finddisksnum=${MAX_FINDDISKSNUM:-6}
2230
2231 swap -l > $sfi
2232 dumpadm > $dmpi 2>/dev/null
2233
2234 # write an awk script that can process the output of format
2235 # to produce a list of disks we know about. Note that we have
2236 # to escape "$2" so that the shell doesn't interpret it while
2237 # we're creating the awk script.
2238 # -------------------
2239 cat > /tmp/find_disks.awk <<EOF
2240 #!/bin/nawk -f
2241 BEGIN { FS="."; }
2242
2243 /^Specify disk/{
2244 searchdisks=0;
2245 }
2246
2247 {
2248 if (searchdisks && \$2 !~ "^$"){
2249 split(\$2,arr," ");
2250 print arr[1];
2251 }
2252 }
2253
2254 /^AVAILABLE DISK SELECTIONS:/{
2255 searchdisks=1;
2256 }
2257 EOF
2258 #---------------------
2259
2260 chmod 755 /tmp/find_disks.awk
2261 disks=${@:-$(echo "" | format -e 2>/dev/null | /tmp/find_disks.awk)}
2262 rm /tmp/find_disks.awk
2263
2264 unused=""
2265 for disk in $disks; do
2266 # Check for mounted
2267 grep "${disk}[sp]" /etc/mnttab >/dev/null
2268 (($? == 0)) && continue
2269 # Check for swap
2270 grep "${disk}[sp]" $sfi >/dev/null
2271 (($? == 0)) && continue
2272 # check for dump device
2273 grep "${disk}[sp]" $dmpi >/dev/null
2274 (($? == 0)) && continue
2275 # check to see if this disk hasn't been explicitly excluded
2276 # by a user-set environment variable
2277 echo "${ZFS_HOST_DEVICES_IGNORE}" | grep "${disk}" > /dev/null
2278 (($? == 0)) && continue
2279 unused_candidates="$unused_candidates $disk"
2280 done
2281 rm $sfi
2282 rm $dmpi
2283
2284 # now just check to see if those disks do actually exist
2285 # by looking for a device pointing to the first slice in
2286 # each case. limit the number to max_finddisksnum
2287 count=0
2288 for disk in $unused_candidates; do
2289 if [ -b $DEV_DSKDIR/${disk}s0 ]; then
2290 if [ $count -lt $max_finddisksnum ]; then
2291 unused="$unused $disk"
2292 # do not impose limit if $@ is provided
2293 [[ -z $@ ]] && ((count = count + 1))
2294 fi
2295 fi
2296 done
2297
2298 # finally, return our disk list
2299 echo $unused
2300 }
2301
2302 #
2303 # Add specified user to specified group
2304 #
2305 # $1 group name
2306 # $2 user name
2307 # $3 base of the homedir (optional)
2308 #
2309 function add_user #<group_name> <user_name> <basedir>
2310 {
2311 typeset gname=$1
2312 typeset uname=$2
2313 typeset basedir=${3:-"/var/tmp"}
2314
2315 if ((${#gname} == 0 || ${#uname} == 0)); then
2316 log_fail "group name or user name are not defined."
2317 fi
2318
2319 log_must useradd -g $gname -d $basedir/$uname -m $uname
2320 echo "export PATH=\"$STF_PATH\"" >>$basedir/$uname/.profile
2321 echo "export PATH=\"$STF_PATH\"" >>$basedir/$uname/.bash_profile
2322 echo "export PATH=\"$STF_PATH\"" >>$basedir/$uname/.login
2323
2324 # Add new users to the same group and the command line utils.
2325 # This allows them to be run out of the original users home
2326 # directory as long as it permissioned to be group readable.
2327 if is_linux; then
2328 cmd_group=$(stat --format="%G" $(which zfs))
2329 log_must usermod -a -G $cmd_group $uname
2330 fi
2331
2332 return 0
2333 }
2334
2335 #
2336 # Delete the specified user.
2337 #
2338 # $1 login name
2339 # $2 base of the homedir (optional)
2340 #
2341 function del_user #<logname> <basedir>
2342 {
2343 typeset user=$1
2344 typeset basedir=${2:-"/var/tmp"}
2345
2346 if ((${#user} == 0)); then
2347 log_fail "login name is necessary."
2348 fi
2349
2350 if id $user > /dev/null 2>&1; then
2351 log_must_retry "currently used" 5 userdel $user
2352 fi
2353
2354 [[ -d $basedir/$user ]] && rm -fr $basedir/$user
2355
2356 return 0
2357 }
2358
2359 #
2360 # Select valid gid and create specified group.
2361 #
2362 # $1 group name
2363 #
2364 function add_group #<group_name>
2365 {
2366 typeset group=$1
2367
2368 if ((${#group} == 0)); then
2369 log_fail "group name is necessary."
2370 fi
2371
2372 # Assign 100 as the base gid, a larger value is selected for
2373 # Linux because for many distributions 1000 and under are reserved.
2374 if is_linux; then
2375 while true; do
2376 groupadd $group > /dev/null 2>&1
2377 typeset -i ret=$?
2378 case $ret in
2379 0) return 0 ;;
2380 *) return 1 ;;
2381 esac
2382 done
2383 else
2384 typeset -i gid=100
2385 while true; do
2386 groupadd -g $gid $group > /dev/null 2>&1
2387 typeset -i ret=$?
2388 case $ret in
2389 0) return 0 ;;
2390 # The gid is not unique
2391 4) ((gid += 1)) ;;
2392 *) return 1 ;;
2393 esac
2394 done
2395 fi
2396 }
2397
2398 #
2399 # Delete the specified group.
2400 #
2401 # $1 group name
2402 #
2403 function del_group #<group_name>
2404 {
2405 typeset grp=$1
2406 if ((${#grp} == 0)); then
2407 log_fail "group name is necessary."
2408 fi
2409
2410 if is_linux; then
2411 getent group $grp > /dev/null 2>&1
2412 typeset -i ret=$?
2413 case $ret in
2414 # Group does not exist.
2415 2) return 0 ;;
2416 # Name already exists as a group name
2417 0) log_must groupdel $grp ;;
2418 *) return 1 ;;
2419 esac
2420 else
2421 groupmod -n $grp $grp > /dev/null 2>&1
2422 typeset -i ret=$?
2423 case $ret in
2424 # Group does not exist.
2425 6) return 0 ;;
2426 # Name already exists as a group name
2427 9) log_must groupdel $grp ;;
2428 *) return 1 ;;
2429 esac
2430 fi
2431
2432 return 0
2433 }
2434
2435 #
2436 # This function will return true if it's safe to destroy the pool passed
2437 # as argument 1. It checks for pools based on zvols and files, and also
2438 # files contained in a pool that may have a different mountpoint.
2439 #
2440 function safe_to_destroy_pool { # $1 the pool name
2441
2442 typeset pool=""
2443 typeset DONT_DESTROY=""
2444
2445 # We check that by deleting the $1 pool, we're not
2446 # going to pull the rug out from other pools. Do this
2447 # by looking at all other pools, ensuring that they
2448 # aren't built from files or zvols contained in this pool.
2449
2450 for pool in $(zpool list -H -o name)
2451 do
2452 ALTMOUNTPOOL=""
2453
2454 # this is a list of the top-level directories in each of the
2455 # files that make up the path to the files the pool is based on
2456 FILEPOOL=$(zpool status -v $pool | grep /$1/ | \
2457 awk '{print $1}')
2458
2459 # this is a list of the zvols that make up the pool
2460 ZVOLPOOL=$(zpool status -v $pool | grep "$ZVOL_DEVDIR/$1$" \
2461 | awk '{print $1}')
2462
2463 # also want to determine if it's a file-based pool using an
2464 # alternate mountpoint...
2465 POOL_FILE_DIRS=$(zpool status -v $pool | \
2466 grep / | awk '{print $1}' | \
2467 awk -F/ '{print $2}' | grep -v "dev")
2468
2469 for pooldir in $POOL_FILE_DIRS
2470 do
2471 OUTPUT=$(zfs list -H -r -o mountpoint $1 | \
2472 grep "${pooldir}$" | awk '{print $1}')
2473
2474 ALTMOUNTPOOL="${ALTMOUNTPOOL}${OUTPUT}"
2475 done
2476
2477
2478 if [ ! -z "$ZVOLPOOL" ]
2479 then
2480 DONT_DESTROY="true"
2481 log_note "Pool $pool is built from $ZVOLPOOL on $1"
2482 fi
2483
2484 if [ ! -z "$FILEPOOL" ]
2485 then
2486 DONT_DESTROY="true"
2487 log_note "Pool $pool is built from $FILEPOOL on $1"
2488 fi
2489
2490 if [ ! -z "$ALTMOUNTPOOL" ]
2491 then
2492 DONT_DESTROY="true"
2493 log_note "Pool $pool is built from $ALTMOUNTPOOL on $1"
2494 fi
2495 done
2496
2497 if [ -z "${DONT_DESTROY}" ]
2498 then
2499 return 0
2500 else
2501 log_note "Warning: it is not safe to destroy $1!"
2502 return 1
2503 fi
2504 }
2505
2506 #
2507 # Get the available ZFS compression options
2508 # $1 option type zfs_set|zfs_compress
2509 #
2510 function get_compress_opts
2511 {
2512 typeset COMPRESS_OPTS
2513 typeset GZIP_OPTS="gzip gzip-1 gzip-2 gzip-3 gzip-4 gzip-5 \
2514 gzip-6 gzip-7 gzip-8 gzip-9"
2515
2516 if [[ $1 == "zfs_compress" ]] ; then
2517 COMPRESS_OPTS="on lzjb"
2518 elif [[ $1 == "zfs_set" ]] ; then
2519 COMPRESS_OPTS="on off lzjb"
2520 fi
2521 typeset valid_opts="$COMPRESS_OPTS"
2522 zfs get 2>&1 | grep gzip >/dev/null 2>&1
2523 if [[ $? -eq 0 ]]; then
2524 valid_opts="$valid_opts $GZIP_OPTS"
2525 fi
2526 echo "$valid_opts"
2527 }
2528
2529 #
2530 # Verify zfs operation with -p option work as expected
2531 # $1 operation, value could be create, clone or rename
2532 # $2 dataset type, value could be fs or vol
2533 # $3 dataset name
2534 # $4 new dataset name
2535 #
2536 function verify_opt_p_ops
2537 {
2538 typeset ops=$1
2539 typeset datatype=$2
2540 typeset dataset=$3
2541 typeset newdataset=$4
2542
2543 if [[ $datatype != "fs" && $datatype != "vol" ]]; then
2544 log_fail "$datatype is not supported."
2545 fi
2546
2547 # check parameters accordingly
2548 case $ops in
2549 create)
2550 newdataset=$dataset
2551 dataset=""
2552 if [[ $datatype == "vol" ]]; then
2553 ops="create -V $VOLSIZE"
2554 fi
2555 ;;
2556 clone)
2557 if [[ -z $newdataset ]]; then
2558 log_fail "newdataset should not be empty" \
2559 "when ops is $ops."
2560 fi
2561 log_must datasetexists $dataset
2562 log_must snapexists $dataset
2563 ;;
2564 rename)
2565 if [[ -z $newdataset ]]; then
2566 log_fail "newdataset should not be empty" \
2567 "when ops is $ops."
2568 fi
2569 log_must datasetexists $dataset
2570 log_mustnot snapexists $dataset
2571 ;;
2572 *)
2573 log_fail "$ops is not supported."
2574 ;;
2575 esac
2576
2577 # make sure the upper level filesystem does not exist
2578 destroy_dataset "${newdataset%/*}" "-rRf"
2579
2580 # without -p option, operation will fail
2581 log_mustnot zfs $ops $dataset $newdataset
2582 log_mustnot datasetexists $newdataset ${newdataset%/*}
2583
2584 # with -p option, operation should succeed
2585 log_must zfs $ops -p $dataset $newdataset
2586 block_device_wait
2587
2588 if ! datasetexists $newdataset ; then
2589 log_fail "-p option does not work for $ops"
2590 fi
2591
2592 # when $ops is create or clone, redo the operation still return zero
2593 if [[ $ops != "rename" ]]; then
2594 log_must zfs $ops -p $dataset $newdataset
2595 fi
2596
2597 return 0
2598 }
2599
2600 #
2601 # Get configuration of pool
2602 # $1 pool name
2603 # $2 config name
2604 #
2605 function get_config
2606 {
2607 typeset pool=$1
2608 typeset config=$2
2609 typeset alt_root
2610
2611 if ! poolexists "$pool" ; then
2612 return 1
2613 fi
2614 alt_root=$(zpool list -H $pool | awk '{print $NF}')
2615 if [[ $alt_root == "-" ]]; then
2616 value=$(zdb -C $pool | grep "$config:" | awk -F: \
2617 '{print $2}')
2618 else
2619 value=$(zdb -e $pool | grep "$config:" | awk -F: \
2620 '{print $2}')
2621 fi
2622 if [[ -n $value ]] ; then
2623 value=${value#'}
2624 value=${value%'}
2625 fi
2626 echo $value
2627
2628 return 0
2629 }
2630
2631 #
2632 # Privated function. Random select one of items from arguments.
2633 #
2634 # $1 count
2635 # $2-n string
2636 #
2637 function _random_get
2638 {
2639 typeset cnt=$1
2640 shift
2641
2642 typeset str="$@"
2643 typeset -i ind
2644 ((ind = RANDOM % cnt + 1))
2645
2646 typeset ret=$(echo "$str" | cut -f $ind -d ' ')
2647 echo $ret
2648 }
2649
2650 #
2651 # Random select one of item from arguments which include NONE string
2652 #
2653 function random_get_with_non
2654 {
2655 typeset -i cnt=$#
2656 ((cnt =+ 1))
2657
2658 _random_get "$cnt" "$@"
2659 }
2660
2661 #
2662 # Random select one of item from arguments which doesn't include NONE string
2663 #
2664 function random_get
2665 {
2666 _random_get "$#" "$@"
2667 }
2668
2669 #
2670 # Detect if the current system support slog
2671 #
2672 function verify_slog_support
2673 {
2674 typeset dir=$TEST_BASE_DIR/disk.$$
2675 typeset pool=foo.$$
2676 typeset vdev=$dir/a
2677 typeset sdev=$dir/b
2678
2679 mkdir -p $dir
2680 mkfile $MINVDEVSIZE $vdev $sdev
2681
2682 typeset -i ret=0
2683 if ! zpool create -n $pool $vdev log $sdev > /dev/null 2>&1; then
2684 ret=1
2685 fi
2686 rm -r $dir
2687
2688 return $ret
2689 }
2690
2691 #
2692 # The function will generate a dataset name with specific length
2693 # $1, the length of the name
2694 # $2, the base string to construct the name
2695 #
2696 function gen_dataset_name
2697 {
2698 typeset -i len=$1
2699 typeset basestr="$2"
2700 typeset -i baselen=${#basestr}
2701 typeset -i iter=0
2702 typeset l_name=""
2703
2704 if ((len % baselen == 0)); then
2705 ((iter = len / baselen))
2706 else
2707 ((iter = len / baselen + 1))
2708 fi
2709 while ((iter > 0)); do
2710 l_name="${l_name}$basestr"
2711
2712 ((iter -= 1))
2713 done
2714
2715 echo $l_name
2716 }
2717
2718 #
2719 # Get cksum tuple of dataset
2720 # $1 dataset name
2721 #
2722 # sample zdb output:
2723 # Dataset data/test [ZPL], ID 355, cr_txg 2413856, 31.0K, 7 objects, rootbp
2724 # DVA[0]=<0:803046400:200> DVA[1]=<0:81199000:200> [L0 DMU objset] fletcher4
2725 # lzjb LE contiguous unique double size=800L/200P birth=2413856L/2413856P
2726 # fill=7 cksum=11ce125712:643a9c18ee2:125e25238fca0:254a3f74b59744
2727 function datasetcksum
2728 {
2729 typeset cksum
2730 sync
2731 cksum=$(zdb -vvv $1 | grep "^Dataset $1 \[" | grep "cksum" \
2732 | awk -F= '{print $7}')
2733 echo $cksum
2734 }
2735
2736 #
2737 # Get cksum of file
2738 # #1 file path
2739 #
2740 function checksum
2741 {
2742 typeset cksum
2743 cksum=$(cksum $1 | awk '{print $1}')
2744 echo $cksum
2745 }
2746
2747 #
2748 # Get the given disk/slice state from the specific field of the pool
2749 #
2750 function get_device_state #pool disk field("", "spares","logs")
2751 {
2752 typeset pool=$1
2753 typeset disk=${2#$DEV_DSKDIR/}
2754 typeset field=${3:-$pool}
2755
2756 state=$(zpool status -v "$pool" 2>/dev/null | \
2757 nawk -v device=$disk -v pool=$pool -v field=$field \
2758 'BEGIN {startconfig=0; startfield=0; }
2759 /config:/ {startconfig=1}
2760 (startconfig==1) && ($1==field) {startfield=1; next;}
2761 (startfield==1) && ($1==device) {print $2; exit;}
2762 (startfield==1) &&
2763 ($1==field || $1 ~ "^spares$" || $1 ~ "^logs$") {startfield=0}')
2764 echo $state
2765 }
2766
2767
2768 #
2769 # print the given directory filesystem type
2770 #
2771 # $1 directory name
2772 #
2773 function get_fstype
2774 {
2775 typeset dir=$1
2776
2777 if [[ -z $dir ]]; then
2778 log_fail "Usage: get_fstype <directory>"
2779 fi
2780
2781 #
2782 # $ df -n /
2783 # / : ufs
2784 #
2785 df -n $dir | awk '{print $3}'
2786 }
2787
2788 #
2789 # Given a disk, label it to VTOC regardless what label was on the disk
2790 # $1 disk
2791 #
2792 function labelvtoc
2793 {
2794 typeset disk=$1
2795 if [[ -z $disk ]]; then
2796 log_fail "The disk name is unspecified."
2797 fi
2798 typeset label_file=/var/tmp/labelvtoc.$$
2799 typeset arch=$(uname -p)
2800
2801 if is_linux; then
2802 log_note "Currently unsupported by the test framework"
2803 return 1
2804 fi
2805
2806 if [[ $arch == "i386" ]]; then
2807 echo "label" > $label_file
2808 echo "0" >> $label_file
2809 echo "" >> $label_file
2810 echo "q" >> $label_file
2811 echo "q" >> $label_file
2812
2813 fdisk -B $disk >/dev/null 2>&1
2814 # wait a while for fdisk finishes
2815 sleep 60
2816 elif [[ $arch == "sparc" ]]; then
2817 echo "label" > $label_file
2818 echo "0" >> $label_file
2819 echo "" >> $label_file
2820 echo "" >> $label_file
2821 echo "" >> $label_file
2822 echo "q" >> $label_file
2823 else
2824 log_fail "unknown arch type"
2825 fi
2826
2827 format -e -s -d $disk -f $label_file
2828 typeset -i ret_val=$?
2829 rm -f $label_file
2830 #
2831 # wait the format to finish
2832 #
2833 sleep 60
2834 if ((ret_val != 0)); then
2835 log_fail "unable to label $disk as VTOC."
2836 fi
2837
2838 return 0
2839 }
2840
2841 #
2842 # check if the system was installed as zfsroot or not
2843 # return: 0 ture, otherwise false
2844 #
2845 function is_zfsroot
2846 {
2847 df -n / | grep zfs > /dev/null 2>&1
2848 return $?
2849 }
2850
2851 #
2852 # get the root filesystem name if it's zfsroot system.
2853 #
2854 # return: root filesystem name
2855 function get_rootfs
2856 {
2857 typeset rootfs=""
2858
2859 if ! is_linux; then
2860 rootfs=$(awk '{if ($2 == "/" && $3 == "zfs") print $1}' \
2861 /etc/mnttab)
2862 fi
2863 if [[ -z "$rootfs" ]]; then
2864 log_fail "Can not get rootfs"
2865 fi
2866 zfs list $rootfs > /dev/null 2>&1
2867 if (($? == 0)); then
2868 echo $rootfs
2869 else
2870 log_fail "This is not a zfsroot system."
2871 fi
2872 }
2873
2874 #
2875 # get the rootfs's pool name
2876 # return:
2877 # rootpool name
2878 #
2879 function get_rootpool
2880 {
2881 typeset rootfs=""
2882 typeset rootpool=""
2883
2884 if ! is_linux; then
2885 rootfs=$(awk '{if ($2 == "/" && $3 =="zfs") print $1}' \
2886 /etc/mnttab)
2887 fi
2888 if [[ -z "$rootfs" ]]; then
2889 log_fail "Can not get rootpool"
2890 fi
2891 zfs list $rootfs > /dev/null 2>&1
2892 if (($? == 0)); then
2893 rootpool=`echo $rootfs | awk -F\/ '{print $1}'`
2894 echo $rootpool
2895 else
2896 log_fail "This is not a zfsroot system."
2897 fi
2898 }
2899
2900 #
2901 # Get the package name
2902 #
2903 function get_package_name
2904 {
2905 typeset dirpath=${1:-$STC_NAME}
2906
2907 echo "SUNWstc-${dirpath}" | /usr/bin/sed -e "s/\//-/g"
2908 }
2909
2910 #
2911 # Get the word numbers from a string separated by white space
2912 #
2913 function get_word_count
2914 {
2915 echo $1 | wc -w
2916 }
2917
2918 #
2919 # To verify if the require numbers of disks is given
2920 #
2921 function verify_disk_count
2922 {
2923 typeset -i min=${2:-1}
2924
2925 typeset -i count=$(get_word_count "$1")
2926
2927 if ((count < min)); then
2928 log_untested "A minimum of $min disks is required to run." \
2929 " You specified $count disk(s)"
2930 fi
2931 }
2932
2933 function ds_is_volume
2934 {
2935 typeset type=$(get_prop type $1)
2936 [[ $type = "volume" ]] && return 0
2937 return 1
2938 }
2939
2940 function ds_is_filesystem
2941 {
2942 typeset type=$(get_prop type $1)
2943 [[ $type = "filesystem" ]] && return 0
2944 return 1
2945 }
2946
2947 function ds_is_snapshot
2948 {
2949 typeset type=$(get_prop type $1)
2950 [[ $type = "snapshot" ]] && return 0
2951 return 1
2952 }
2953
2954 #
2955 # Check if Trusted Extensions are installed and enabled
2956 #
2957 function is_te_enabled
2958 {
2959 svcs -H -o state labeld 2>/dev/null | grep "enabled"
2960 if (($? != 0)); then
2961 return 1
2962 else
2963 return 0
2964 fi
2965 }
2966
2967 # Utility function to determine if a system has multiple cpus.
2968 function is_mp
2969 {
2970 if is_linux; then
2971 (($(nproc) > 1))
2972 else
2973 (($(psrinfo | wc -l) > 1))
2974 fi
2975
2976 return $?
2977 }
2978
2979 function get_cpu_freq
2980 {
2981 if is_linux; then
2982 lscpu | awk '/CPU MHz/ { print $3 }'
2983 else
2984 psrinfo -v 0 | awk '/processor operates at/ {print $6}'
2985 fi
2986 }
2987
2988 # Run the given command as the user provided.
2989 function user_run
2990 {
2991 typeset user=$1
2992 shift
2993
2994 log_note "user:$user $@"
2995 eval su - \$user -c \"$@\" > $TEST_BASE_DIR/out 2>$TEST_BASE_DIR/err
2996 return $?
2997 }
2998
2999 #
3000 # Check if the pool contains the specified vdevs
3001 #
3002 # $1 pool
3003 # $2..n <vdev> ...
3004 #
3005 # Return 0 if the vdevs are contained in the pool, 1 if any of the specified
3006 # vdevs is not in the pool, and 2 if pool name is missing.
3007 #
3008 function vdevs_in_pool
3009 {
3010 typeset pool=$1
3011 typeset vdev
3012
3013 if [[ -z $pool ]]; then
3014 log_note "Missing pool name."
3015 return 2
3016 fi
3017
3018 shift
3019
3020 typeset tmpfile=$(mktemp)
3021 zpool list -Hv "$pool" >$tmpfile
3022 for vdev in $@; do
3023 grep -w ${vdev##*/} $tmpfile >/dev/null 2>&1
3024 [[ $? -ne 0 ]] && return 1
3025 done
3026
3027 rm -f $tmpfile
3028
3029 return 0;
3030 }
3031
3032 function get_max
3033 {
3034 typeset -l i max=$1
3035 shift
3036
3037 for i in "$@"; do
3038 max=$(echo $((max > i ? max : i)))
3039 done
3040
3041 echo $max
3042 }
3043
3044 function get_min
3045 {
3046 typeset -l i min=$1
3047 shift
3048
3049 for i in "$@"; do
3050 min=$(echo $((min < i ? min : i)))
3051 done
3052
3053 echo $min
3054 }
3055
3056 #
3057 # Generate a random number between 1 and the argument.
3058 #
3059 function random
3060 {
3061 typeset max=$1
3062 echo $(( ($RANDOM % $max) + 1 ))
3063 }
3064
3065 # Write data that can be compressed into a directory
3066 function write_compressible
3067 {
3068 typeset dir=$1
3069 typeset megs=$2
3070 typeset nfiles=${3:-1}
3071 typeset bs=${4:-1024k}
3072 typeset fname=${5:-file}
3073
3074 [[ -d $dir ]] || log_fail "No directory: $dir"
3075
3076 # Under Linux fio is not currently used since its behavior can
3077 # differ significantly across versions. This includes missing
3078 # command line options and cases where the --buffer_compress_*
3079 # options fail to behave as expected.
3080 if is_linux; then
3081 typeset file_bytes=$(to_bytes $megs)
3082 typeset bs_bytes=4096
3083 typeset blocks=$(($file_bytes / $bs_bytes))
3084
3085 for (( i = 0; i < $nfiles; i++ )); do
3086 truncate -s $file_bytes $dir/$fname.$i
3087
3088 # Write every third block to get 66% compression.
3089 for (( j = 0; j < $blocks; j += 3 )); do
3090 dd if=/dev/urandom of=$dir/$fname.$i \
3091 seek=$j bs=$bs_bytes count=1 \
3092 conv=notrunc >/dev/null 2>&1
3093 done
3094 done
3095 else
3096 log_must eval "fio \
3097 --name=job \
3098 --fallocate=0 \
3099 --minimal \
3100 --randrepeat=0 \
3101 --buffer_compress_percentage=66 \
3102 --buffer_compress_chunk=4096 \
3103 --directory=$dir \
3104 --numjobs=$nfiles \
3105 --nrfiles=$nfiles \
3106 --rw=write \
3107 --bs=$bs \
3108 --filesize=$megs \
3109 --filename_format='$fname.\$jobnum' >/dev/null"
3110 fi
3111 }
3112
3113 function get_objnum
3114 {
3115 typeset pathname=$1
3116 typeset objnum
3117
3118 [[ -e $pathname ]] || log_fail "No such file or directory: $pathname"
3119 objnum=$(stat -c %i $pathname)
3120 echo $objnum
3121 }
3122
3123 #
3124 # Sync data to the pool
3125 #
3126 # $1 pool name
3127 # $2 boolean to force uberblock (and config including zpool cache file) update
3128 #
3129 function sync_pool #pool <force>
3130 {
3131 typeset pool=${1:-$TESTPOOL}
3132 typeset force=${2:-false}
3133
3134 if [[ $force == true ]]; then
3135 log_must zpool sync -f $pool
3136 else
3137 log_must zpool sync $pool
3138 fi
3139
3140 return 0
3141 }
3142
3143 #
3144 # Wait for zpool 'freeing' property drops to zero.
3145 #
3146 # $1 pool name
3147 #
3148 function wait_freeing #pool
3149 {
3150 typeset pool=${1:-$TESTPOOL}
3151 while true; do
3152 [[ "0" == "$(zpool list -Ho freeing $pool)" ]] && break
3153 log_must sleep 1
3154 done
3155 }
3156
3157 #
3158 # Wait for every device replace operation to complete
3159 #
3160 # $1 pool name
3161 #
3162 function wait_replacing #pool
3163 {
3164 typeset pool=${1:-$TESTPOOL}
3165 while true; do
3166 [[ "" == "$(zpool status $pool |
3167 awk '/replacing-[0-9]+/ {print $1}')" ]] && break
3168 log_must sleep 1
3169 done
3170 }
3171
3172 #
3173 # Wait for a pool to be scrubbed
3174 #
3175 # $1 pool name
3176 # $2 number of seconds to wait (optional)
3177 #
3178 # Returns true when pool has been scrubbed, or false if there's a timeout or if
3179 # no scrub was done.
3180 #
3181 function wait_scrubbed
3182 {
3183 typeset pool=${1:-$TESTPOOL}
3184 typeset iter=${2:-10}
3185 for i in {1..$iter} ; do
3186 if is_pool_scrubbed $pool ; then
3187 return 0
3188 fi
3189 sleep 1
3190 done
3191 return 1
3192 }
3193
3194 # Backup the zed.rc in our test directory so that we can edit it for our test.
3195 #
3196 # Returns: Backup file name. You will need to pass this to zed_rc_restore().
3197 function zed_rc_backup
3198 {
3199 zedrc_backup="$(mktemp)"
3200 cp $ZEDLET_DIR/zed.rc $zedrc_backup
3201 echo $zedrc_backup
3202 }
3203
3204 function zed_rc_restore
3205 {
3206 mv $1 $ZEDLET_DIR/zed.rc
3207 }
3208
3209 #
3210 # Setup custom environment for the ZED.
3211 #
3212 # $@ Optional list of zedlets to run under zed.
3213 function zed_setup
3214 {
3215 if ! is_linux; then
3216 return
3217 fi
3218
3219 if [[ ! -d $ZEDLET_DIR ]]; then
3220 log_must mkdir $ZEDLET_DIR
3221 fi
3222
3223 if [[ ! -e $VDEVID_CONF ]]; then
3224 log_must touch $VDEVID_CONF
3225 fi
3226
3227 if [[ -e $VDEVID_CONF_ETC ]]; then
3228 log_fail "Must not have $VDEVID_CONF_ETC file present on system"
3229 fi
3230 EXTRA_ZEDLETS=$@
3231
3232 # Create a symlink for /etc/zfs/vdev_id.conf file.
3233 log_must ln -s $VDEVID_CONF $VDEVID_CONF_ETC
3234
3235 # Setup minimal ZED configuration. Individual test cases should
3236 # add additional ZEDLETs as needed for their specific test.
3237 log_must cp ${ZEDLET_ETC_DIR}/zed.rc $ZEDLET_DIR
3238 log_must cp ${ZEDLET_ETC_DIR}/zed-functions.sh $ZEDLET_DIR
3239
3240 # Scripts must only be user writable.
3241 if [[ -n "$EXTRA_ZEDLETS" ]] ; then
3242 saved_umask=$(umask)
3243 log_must umask 0022
3244 for i in $EXTRA_ZEDLETS ; do
3245 log_must cp ${ZEDLET_LIBEXEC_DIR}/$i $ZEDLET_DIR
3246 done
3247 log_must umask $saved_umask
3248 fi
3249
3250 # Customize the zed.rc file to enable the full debug log.
3251 log_must sed -i '/\#ZED_DEBUG_LOG=.*/d' $ZEDLET_DIR/zed.rc
3252 echo "ZED_DEBUG_LOG=$ZED_DEBUG_LOG" >>$ZEDLET_DIR/zed.rc
3253
3254 }
3255
3256 #
3257 # Cleanup custom ZED environment.
3258 #
3259 # $@ Optional list of zedlets to remove from our test zed.d directory.
3260 function zed_cleanup
3261 {
3262 if ! is_linux; then
3263 return
3264 fi
3265 EXTRA_ZEDLETS=$@
3266
3267 log_must rm -f ${ZEDLET_DIR}/zed.rc
3268 log_must rm -f ${ZEDLET_DIR}/zed-functions.sh
3269 log_must rm -f ${ZEDLET_DIR}/all-syslog.sh
3270 log_must rm -f ${ZEDLET_DIR}/all-debug.sh
3271 log_must rm -f ${ZEDLET_DIR}/state
3272
3273 if [[ -n "$EXTRA_ZEDLETS" ]] ; then
3274 for i in $EXTRA_ZEDLETS ; do
3275 log_must rm -f ${ZEDLET_DIR}/$i
3276 done
3277 fi
3278 log_must rm -f $ZED_LOG
3279 log_must rm -f $ZED_DEBUG_LOG
3280 log_must rm -f $VDEVID_CONF_ETC
3281 log_must rm -f $VDEVID_CONF
3282 rmdir $ZEDLET_DIR
3283 }
3284
3285 #
3286 # Check if ZED is currently running, if not start ZED.
3287 #
3288 function zed_start
3289 {
3290 if ! is_linux; then
3291 return
3292 fi
3293
3294 # ZEDLET_DIR=/var/tmp/zed
3295 if [[ ! -d $ZEDLET_DIR ]]; then
3296 log_must mkdir $ZEDLET_DIR
3297 fi
3298
3299 # Verify the ZED is not already running.
3300 pgrep -x zed > /dev/null
3301 if (($? == 0)); then
3302 log_fail "ZED already running"
3303 fi
3304
3305 log_note "Starting ZED"
3306 # run ZED in the background and redirect foreground logging
3307 # output to $ZED_LOG.
3308 log_must truncate -s 0 $ZED_DEBUG_LOG
3309 log_must eval "zed -vF -d $ZEDLET_DIR -p $ZEDLET_DIR/zed.pid -P $PATH" \
3310 "-s $ZEDLET_DIR/state 2>$ZED_LOG &"
3311
3312 return 0
3313 }
3314
3315 #
3316 # Kill ZED process
3317 #
3318 function zed_stop
3319 {
3320 if ! is_linux; then
3321 return
3322 fi
3323
3324 log_note "Stopping ZED"
3325 if [[ -f ${ZEDLET_DIR}/zed.pid ]]; then
3326 zedpid=$(cat ${ZEDLET_DIR}/zed.pid)
3327 kill $zedpid
3328 while ps -p $zedpid > /dev/null; do
3329 sleep 1
3330 done
3331 rm -f ${ZEDLET_DIR}/zed.pid
3332 fi
3333 return 0
3334 }
3335
3336 #
3337 # Drain all zevents
3338 #
3339 function zed_events_drain
3340 {
3341 while [ $(zpool events -H | wc -l) -ne 0 ]; do
3342 sleep 1
3343 zpool events -c >/dev/null
3344 done
3345 }
3346
3347 # Set a variable in zed.rc to something, un-commenting it in the process.
3348 #
3349 # $1 variable
3350 # $2 value
3351 function zed_rc_set
3352 {
3353 var="$1"
3354 val="$2"
3355 # Remove the line
3356 cmd="'/$var/d'"
3357 eval sed -i $cmd $ZEDLET_DIR/zed.rc
3358
3359 # Add it at the end
3360 echo "$var=$val" >> $ZEDLET_DIR/zed.rc
3361 }
3362
3363
3364 #
3365 # Check is provided device is being active used as a swap device.
3366 #
3367 function is_swap_inuse
3368 {
3369 typeset device=$1
3370
3371 if [[ -z $device ]] ; then
3372 log_note "No device specified."
3373 return 1
3374 fi
3375
3376 if is_linux; then
3377 swapon -s | grep -w $(readlink -f $device) > /dev/null 2>&1
3378 else
3379 swap -l | grep -w $device > /dev/null 2>&1
3380 fi
3381
3382 return $?
3383 }
3384
3385 #
3386 # Setup a swap device using the provided device.
3387 #
3388 function swap_setup
3389 {
3390 typeset swapdev=$1
3391
3392 if is_linux; then
3393 log_must eval "mkswap $swapdev > /dev/null 2>&1"
3394 log_must swapon $swapdev
3395 else
3396 log_must swap -a $swapdev
3397 fi
3398
3399 return 0
3400 }
3401
3402 #
3403 # Cleanup a swap device on the provided device.
3404 #
3405 function swap_cleanup
3406 {
3407 typeset swapdev=$1
3408
3409 if is_swap_inuse $swapdev; then
3410 if is_linux; then
3411 log_must swapoff $swapdev
3412 else
3413 log_must swap -d $swapdev
3414 fi
3415 fi
3416
3417 return 0
3418 }
3419
3420 #
3421 # Set a global system tunable (64-bit value)
3422 #
3423 # $1 tunable name
3424 # $2 tunable values
3425 #
3426 function set_tunable64
3427 {
3428 set_tunable_impl "$1" "$2" Z
3429 }
3430
3431 #
3432 # Set a global system tunable (32-bit value)
3433 #
3434 # $1 tunable name
3435 # $2 tunable values
3436 #
3437 function set_tunable32
3438 {
3439 set_tunable_impl "$1" "$2" W
3440 }
3441
3442 function set_tunable_impl
3443 {
3444 typeset tunable="$1"
3445 typeset value="$2"
3446 typeset mdb_cmd="$3"
3447 typeset module="${4:-zfs}"
3448
3449 [[ -z "$tunable" ]] && return 1
3450 [[ -z "$value" ]] && return 1
3451 [[ -z "$mdb_cmd" ]] && return 1
3452
3453 case "$(uname)" in
3454 Linux)
3455 typeset zfs_tunables="/sys/module/$module/parameters"
3456 [[ -w "$zfs_tunables/$tunable" ]] || return 1
3457 echo -n "$value" > "$zfs_tunables/$tunable"
3458 return "$?"
3459 ;;
3460 SunOS)
3461 [[ "$module" -eq "zfs" ]] || return 1
3462 echo "${tunable}/${mdb_cmd}0t${value}" | mdb -kw
3463 return "$?"
3464 ;;
3465 esac
3466 }
3467
3468 #
3469 # Get a global system tunable
3470 #
3471 # $1 tunable name
3472 #
3473 function get_tunable
3474 {
3475 get_tunable_impl "$1"
3476 }
3477
3478 function get_tunable_impl
3479 {
3480 typeset tunable="$1"
3481 typeset module="${2:-zfs}"
3482
3483 [[ -z "$tunable" ]] && return 1
3484
3485 case "$(uname)" in
3486 Linux)
3487 typeset zfs_tunables="/sys/module/$module/parameters"
3488 [[ -f "$zfs_tunables/$tunable" ]] || return 1
3489 cat $zfs_tunables/$tunable
3490 return "$?"
3491 ;;
3492 SunOS)
3493 [[ "$module" -eq "zfs" ]] || return 1
3494 ;;
3495 esac
3496
3497 return 1
3498 }
3499
3500 #
3501 # Prints the current time in seconds since UNIX Epoch.
3502 #
3503 function current_epoch
3504 {
3505 printf '%(%s)T'
3506 }
3507
3508 #
3509 # Get decimal value of global uint32_t variable using mdb.
3510 #
3511 function mdb_get_uint32
3512 {
3513 typeset variable=$1
3514 typeset value
3515
3516 value=$(mdb -k -e "$variable/X | ::eval .=U")
3517 if [[ $? -ne 0 ]]; then
3518 log_fail "Failed to get value of '$variable' from mdb."
3519 return 1
3520 fi
3521
3522 echo $value
3523 return 0
3524 }
3525
3526 #
3527 # Set global uint32_t variable to a decimal value using mdb.
3528 #
3529 function mdb_set_uint32
3530 {
3531 typeset variable=$1
3532 typeset value=$2
3533
3534 mdb -kw -e "$variable/W 0t$value" > /dev/null
3535 if [[ $? -ne 0 ]]; then
3536 echo "Failed to set '$variable' to '$value' in mdb."
3537 return 1
3538 fi
3539
3540 return 0
3541 }
3542
3543 #
3544 # Set global scalar integer variable to a hex value using mdb.
3545 # Note: Target should have CTF data loaded.
3546 #
3547 function mdb_ctf_set_int
3548 {
3549 typeset variable=$1
3550 typeset value=$2
3551
3552 mdb -kw -e "$variable/z $value" > /dev/null
3553 if [[ $? -ne 0 ]]; then
3554 echo "Failed to set '$variable' to '$value' in mdb."
3555 return 1
3556 fi
3557
3558 return 0
3559 }