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