d450c2c87a6fe054773ca24f1b832a1242233093
[platform/upstream/btrfs-progs.git] / tests / common
1 #!/bin/bash
2 #
3 # Common routines for all tests
4 #
5
6 # assert that argument is not empty and is an existing path (file or directory)
7 _assert_path()
8 {
9         local path
10
11         path="$1"
12         if [ -z "$path" ]; then
13                 echo "ASSERTION FAIL: $path is not valid"
14                 exit 1
15         fi
16
17         if [ -f "$path" -o -d "$path" -o -b "$path" ]; then
18                 return 0
19         fi
20         echo "ASSERTION FAIL: $path is not valid"
21         exit 1
22 }
23
24 # $1: this string gets matched to files, absolute or relative path, or a
25 # systemwide command available via $PATH
26 _is_file_or_command()
27 {
28         local msg
29
30         msg="$1"
31         if [ -z "$msg" ]; then
32                 return 1
33         fi
34
35         if [ -f "$msg" -o -d "$msg" -o -b "$msg" ]; then
36                 return 0
37         fi
38         msg=$(type -p "$msg")
39         if [ -f "$msg" ]; then
40                 return 0
41         fi
42         return 1
43 }
44
45 _fail()
46 {
47         echo "$*" | tee -a "$RESULTS"
48         exit 1
49 }
50
51 # log a message to the results file
52 _log()
53 {
54         echo "$*" | tee -a "$RESULTS"
55 }
56
57 _not_run()
58 {
59         echo "    [NOTRUN] $*"
60         exit 0
61 }
62
63 # debugging helper
64 _dump_args()
65 {
66         local i
67
68         i=1
69         echo "DUMP args for ${FUNCNAME[1]}:"
70         while [ $# -gt 0 ]; do
71                 echo "ARG[$i]: $1"
72                 i=$(($i+1))
73                 shift
74         done
75 }
76
77 # read arguments, look if we're calling btrfs and if there's a known
78 # subcommand, return argument index to insert, taking root helper into
79 # consideration, returns 2 for unknown subcommand
80 _get_spec_ins()
81 {
82         if [ "$1" = 'root_helper' ]; then
83                 if [[ $2 =~ /btrfs$ ]]; then
84                         echo -n 4
85                         return
86                 fi
87         else
88                 if [[ $1 =~ /btrfs$ ]]; then
89                         echo -n 3
90                         return
91                 fi
92         fi
93         echo -n 2
94 }
95
96 # return command-specific arguments if enabled
97 _cmd_spec()
98 {
99         if [ "$TEST_ENABLE_OVERRIDE" = 'true' ]; then
100                 # if defined via common.local, use it, otherwise pass make
101                 # arguments
102                 if [ "$(type -t _skip_spec)" = 'function' ]; then
103                         if _skip_spec "$@"; then
104                                 return
105                         fi
106                 fi
107                 case "$1" in
108                         check) echo -n "$TEST_ARGS_CHECK" ;;
109                 esac
110         fi
111 }
112
113 # Argument passing magic:
114 # the command passed to run_* helpers is inspected, if there's 'btrfs command'
115 # found and there are defined additional arguments, they're inserted just after
116 # the command name, ie. any arguments in the test could override them.
117 #
118 # The root helper is recognized.  Unrecognized subcommands or external tools
119 # are not affected.
120
121 run_check()
122 {
123         local spec
124         local ins
125         local cmd
126
127         ins=$(_get_spec_ins "$@")
128         spec=$(($ins-1))
129         cmd=$(eval echo "\${$spec}")
130         spec=$(_cmd_spec "${@:$spec}")
131         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
132         echo "############### $@" >> "$RESULTS" 2>&1
133         if [[ $TEST_LOG =~ tty ]]; then echo "CMD: $@" > /dev/tty; fi
134         if [ "$1" = 'root_helper' ]; then
135                 "$@" >> "$RESULTS" 2>&1 || _fail "failed: $@"
136         else
137                 $INSTRUMENT "$@" >> "$RESULTS" 2>&1 || _fail "failed: $@"
138         fi
139 }
140
141 # same as run_check but the stderr+stdout output is duplicated on stdout and
142 # can be processed further
143 run_check_stdout()
144 {
145         local spec
146         local ins
147         local cmd
148
149         ins=$(_get_spec_ins "$@")
150         spec=$(($ins-1))
151         cmd=$(eval echo "\${$spec}")
152         spec=$(_cmd_spec "${@:$spec}")
153         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
154         echo "############### $@" >> "$RESULTS" 2>&1
155         if [[ $TEST_LOG =~ tty ]]; then echo "CMD(stdout): $@" > /dev/tty; fi
156         if [ "$1" = 'root_helper' ]; then
157                 "$@" 2>&1 | tee -a "$RESULTS"
158         else
159                 $INSTRUMENT "$@" 2>&1 | tee -a "$RESULTS"
160         fi
161         if [ ${PIPESTATUS[0]} -ne 0 ]; then
162                 _fail "failed: $@"
163         fi
164 }
165
166 # same as run_check but does not fail the test if it's handled gracefully by
167 # the tool, unexpected failure like segfault or abor will exit forcibly
168 # output is logged
169 run_mayfail()
170 {
171         local spec
172         local ins
173         local cmd
174         local ret
175
176         ins=$(_get_spec_ins "$@")
177         spec=$(($ins-1))
178         cmd=$(eval echo "\${$spec}")
179         spec=$(_cmd_spec "${@:$spec}")
180         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
181         echo "############### $@" >> "$RESULTS" 2>&1
182         if [[ $TEST_LOG =~ tty ]]; then echo "CMD(mayfail): $@" > /dev/tty; fi
183         if [ "$1" = 'root_helper' ]; then
184                 "$@" >> "$RESULTS" 2>&1
185         else
186                 $INSTRUMENT "$@" >> "$RESULTS" 2>&1
187         fi
188         ret=$?
189         if [ $ret != 0 ]; then
190                 echo "failed (ignored, ret=$ret): $@" >> "$RESULTS"
191                 if [ $ret == 139 ]; then
192                         _fail "mayfail: returned code 139 (SEGFAULT), not ignored"
193                 elif [ $ret == 134 ]; then
194                         _fail "mayfail: returned code 134 (SIGABRT), not ignored"
195                 fi
196                 return $ret
197         fi
198 }
199
200 # first argument is error message to print if it fails, otherwise
201 # same as run_check but expects the command to fail, output is logged
202 run_mustfail()
203 {
204         local spec
205         local ins
206         local cmd
207         local msg
208
209         msg="$1"
210         shift
211
212         if _is_file_or_command "$msg"; then
213                 echo "ASSERTION FAIL: 1st argument of run_mustfail must be a message"
214                 exit 1
215         fi
216
217         ins=$(_get_spec_ins "$@")
218         spec=$(($ins-1))
219         cmd=$(eval echo "\${$spec}")
220         spec=$(_cmd_spec "${@:$spec}")
221         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
222         echo "############### $@" >> "$RESULTS" 2>&1
223         if [[ $TEST_LOG =~ tty ]]; then echo "CMD(mustfail): $@" > /dev/tty; fi
224         if [ "$1" = 'root_helper' ]; then
225                 "$@" >> "$RESULTS" 2>&1
226         else
227                 $INSTRUMENT "$@" >> "$RESULTS" 2>&1
228         fi
229         if [ $? != 0 ]; then
230                 echo "failed (expected): $@" >> "$RESULTS"
231                 return 0
232         else
233                 echo "succeeded (unexpected!): $@" >> "$RESULTS"
234                 _fail "unexpected success: $msg"
235                 return 1
236         fi
237 }
238
239 check_prereq()
240 {
241         if ! [ -f "$TOP/$1" ]; then
242                 _fail "Failed prerequisites: $1";
243         fi
244 }
245
246 check_global_prereq()
247 {
248         which $1 &> /dev/null
249         if [ $? -ne 0 ]; then
250                 _fail "Failed system wide prerequisities: $1";
251         fi
252 }
253
254 check_image()
255 {
256         local image
257
258         image=$1
259         echo "testing image $(basename $image)" >> "$RESULTS"
260         "$TOP/btrfs" check "$image" >> "$RESULTS" 2>&1
261         [ $? -eq 0 ] && _fail "btrfs check should have detected corruption"
262
263         run_check "$TOP/btrfs" check --repair "$image"
264         run_check "$TOP/btrfs" check "$image"
265 }
266
267 # Extract a usable image from packed formats
268 # - raw btrfs filesystem images, suffix .raw
269 # - dtto compressed by XZ, suffix .raw.xz
270 # - meta-dump images with suffix .img
271 # - dtto compressed by XZ, suffix .img.xz
272 # - compressed send stream, .stream.xz
273 extract_image()
274 {
275         local image
276         local cleanme
277
278         image="$1"
279         case "$image" in
280         *.img)
281                 rm -f "$image.restored"
282                 : ;;
283         *.img.xz)
284                 xz --decompress --keep "$image" || \
285                         _fail "failed to decompress image $image" >&2
286                 image=${image%%.xz}
287                 rm -f "$image.restored"
288                 cleanme=$image
289                 ;;
290         *.raw)
291                 cp --sparse=auto "$image" "$image.restored"
292                 ;;
293         *.raw.xz)
294                 xz --decompress --keep "$image" || \
295                         _fail "failed to decompress image $image" >&2
296                 image=${image%%.xz}
297                 mv "$image" "$image.restored"
298                 ;;
299         *.stream.xz)
300                 xz --decompress --keep "$image" || \
301                         _fail "failed to decompress file $image" >&2
302                 image=${image%%.xz}
303                 mv "$image" "$image.restored"
304                 ;;
305         esac
306
307         if ! [ -f "$image.restored" ]; then
308                 echo "restoring image $(basename $image)" >> "$RESULTS"
309                 "$TOP/btrfs-image" -r "$image" "$image.restored" \
310                         &>> "$RESULTS" \
311                         || _fail "failed to restore image $image" >&2
312         fi
313
314         [ -f "$cleanme" ] && rm -f "$cleanme"
315
316         echo "$image.restored"
317 }
318
319 # Process all image dumps in a given directory
320 check_all_images()
321 {
322         local dir
323         local extracted
324
325         dir="$1"
326         if [ -z "$dir" ]; then
327                 dir=.
328         fi
329         _assert_path "$dir"
330         for image in $(find "$dir" \( -iname '*.img' -o \
331                                 -iname '*.img.xz' -o    \
332                                 -iname '*.raw' -o       \
333                                 -iname '*.raw.xz' \) | sort)
334         do
335                 extracted=$(extract_image "$image")
336                 check_image "$extracted"
337                 rm -f "$extracted"
338         done
339 }
340
341 # some tests need to mount the recovered image and do verifications call
342 # 'setup_root_helper' and then check for have_root_helper == 1 if the test
343 # needs to fail otherwise; using sudo by default for now
344 SUDO_HELPER=
345 NEED_SUDO_VALIDATE=unknown
346 export SUDO_HELPER
347 export NEED_SUDO_VALIDATE
348 root_helper()
349 {
350         if [ $UID -eq 0 ]; then
351                 "$@"
352         else
353                 if [ "$NEED_SUDO_VALIDATE" = 'yes' ]; then
354                         sudo -v -n &>/dev/null || \
355                                 _not_run "Need to validate sudo credentials"
356                         sudo -n "$@"
357                 elif [ "$NEED_SUDO_VALIDATE" = 'no' ]; then
358                         sudo -n /bin/true &> /dev/null || \
359                                 _not_run "Need to validate sudo user settings"
360                         sudo -n "$@"
361                 else
362                         # should not happen
363                         _not_run "Need to validate root privileges"
364                 fi
365         fi
366 }
367
368 setup_root_helper()
369 {
370         if [ $UID -eq 0 -o -n "$SUDO_HELPER" ]; then
371                 return
372         fi
373
374         # Test for old sudo or special settings, which make sudo -v fail even
375         # if user setting is NOPASSWD
376         sudo -n /bin/true &>/dev/null && NEED_SUDO_VALIDATE=no
377
378         # Newer sudo or default sudo setting
379         sudo -v -n &>/dev/null && NEED_SUDO_VALIDATE=yes
380
381         if [ "$NEED_SUDO_VALIDATE" = 'unknown' ]; then
382                 _not_run "Need to validate root privileges"
383         fi
384         SUDO_HELPER=root_helper
385 }
386
387 prepare_test_dev()
388 {
389         # num[K/M/G/T...]
390         local size="$1"
391
392         [[ "$TEST_DEV" ]] && return
393         [[ "$size" ]] || size='2G'
394
395         echo "\$TEST_DEV not given, use $TOP/test/test.img as fallback" >> \
396                 "$RESULTS"
397         TEST_DEV="$TOP/tests/test.img"
398
399         truncate -s "$size" "$TEST_DEV" || _not_run "create file for loop device failed"
400 }
401
402 run_check_mount_test_dev()
403 {
404         setup_root_helper
405
406         local loop_opt
407         if [[ -b "$TEST_DEV" ]]; then
408                 loop_opt=""
409         elif [[ -f "$TEST_DEV" ]]; then
410                 loop_opt="-o loop"
411         else
412                 _fail "Invalid \$TEST_DEV: $TEST_DEV"
413         fi
414
415         [[ -d "$TEST_MNT" ]] || {
416                 _fail "Invalid \$TEST_MNT: $TEST_MNT"
417         }
418
419         run_check $SUDO_HELPER mount -t btrfs $loop_opt "$@" "$TEST_DEV" "$TEST_MNT"
420 }
421
422 run_check_umount_test_dev()
423 {
424         setup_root_helper
425         run_check $SUDO_HELPER umount "$@" "$TEST_DEV"
426 }
427
428 check_kernel_support()
429 {
430         if ! grep -iq 'btrfs' /proc/filesystems; then
431                 echo "WARNING: btrfs filesystem not listed in /proc/filesystems, some tests might fail"
432                 return 1
433         fi
434         return 0
435 }
436
437 # how many files to create.
438 DATASET_SIZE=50
439
440 generate_dataset() {
441
442         dataset_type="$1"
443         dirpath=$TEST_MNT/$dataset_type
444         run_check $SUDO_HELPER mkdir -p "$dirpath"
445
446         case "$dataset_type" in
447                 small)
448                         for num in $(seq 1 "$DATASET_SIZE"); do
449                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
450                                 count=1 >/dev/null 2>&1
451                         done
452                         ;;
453
454                 hardlink)
455                         for num in $(seq 1 "$DATASET_SIZE"); do
456                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
457                                 run_check $SUDO_HELPER ln "$dirpath/$dataset_type.$num" "$dirpath/hlink.$num"
458                         done
459                         ;;
460
461                 fast_symlink)
462                         for num in $(seq 1 "$DATASET_SIZE"); do
463                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
464                                 run_check cd "$dirpath" && \
465                                         $SUDO_HELPER ln -s "$dataset_type.$num" "$dirpath/slink.$num" && \
466                                         cd /
467                         done
468                         ;;
469
470                 brokenlink)
471                         for num in $(seq 1 "$DATASET_SIZE"); do
472                                 run_check $SUDO_HELPER ln -s "$dirpath/$dataset_type.$num" "$dirpath/blink.$num"
473                         done
474                         ;;
475
476                 perm)
477                         for modes in 777 775 755 750 700 666 664 644 640 600 444 440 400 000            \
478                                 1777 1775 1755 1750 1700 1666 1664 1644 1640 1600 1444 1440 1400 1000   \
479                                 2777 2775 2755 2750 2700 2666 2664 2644 2640 2600 2444 2440 2400 2000   \
480                                 4777 4775 4755 4750 4700 4666 4664 4644 4640 4600 4444 4440 4400 4000; do
481                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$modes"
482                                 run_check $SUDO_HELPER chmod "$modes" "$dirpath/$dataset_type.$modes"
483                         done
484                         ;;
485
486                 sparse)
487                         for num in $(seq 1 "$DATASET_SIZE"); do
488                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
489                                 count=1 >/dev/null 2>&1
490                                 run_check $SUDO_HELPER truncate -s 500K "$dirpath/$dataset_type.$num"
491                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
492                                 oflag=append conv=notrunc count=1 >/dev/null 2>&1
493                                 run_check $SUDO_HELPER truncate -s 800K "$dirpath/$dataset_type.$num"
494                         done
495                         ;;
496
497                 acls)
498                         for num in $(seq 1 "$DATASET_SIZE"); do
499                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
500                                 run_check $SUDO_HELPER setfacl -m "u:root:x" "$dirpath/$dataset_type.$num"
501                                 run_check $SUDO_HELPER setfattr -n user.foo -v "bar$num" "$dirpath/$dataset_type.$num"
502                         done
503                         ;;
504
505                 fifo)
506                         for num in $(seq 1 "$DATASET_SIZE"); do
507                                 run_check $SUDO_HELPER mkfifo "$dirpath/$dataset_type.$num"
508                         done
509                         ;;
510
511                 slow_symlink)
512                         long_filename=`date +%s | sha256sum | cut -f1 -d'-'`
513                         run_check $SUDO_HELPER touch "$dirpath/$long_filename"
514                         for num in $(seq 1 "$DATASET_SIZE"); do
515                                 run_check $SUDO_HELPER ln -s "$dirpath/$long_filename" "$dirpath/slow_slink.$num"
516                         done
517                         ;;
518                 large)
519                         run_check $SUDO_HELPER dd if=/dev/urandom bs=32M count=1 \
520                                 of="$dirpath/$dataset_type" >/dev/null 2>&1
521                         ;;
522         esac
523 }
524
525 # prepare environment for loop devices, set up the following variables
526 # - nloopdevs -- number of desired devices
527 # - loopdevs  -- array containing paths to all devices (after prepare is called)
528 # - loopdev_prefix -- file backed images starting with this string, 'img' by default
529 #
530 # $1: number of loop devices to be set up
531 setup_loopdevs()
532 {
533         if [ -z "$1" ]; then
534                 _fail "setup_loopdevs needs a number"
535         fi
536         nloopdevs="$1"
537         loopdev_prefix=img
538         declare -a loopdevs
539
540 }
541
542 # create all loop devices from a given loopdev environment
543 prepare_loopdevs()
544 {
545         for i in `seq $nloopdevs`; do
546                 touch $loopdev_prefix$i
547                 chmod a+rw $loopdev_prefix$i
548                 truncate -s0 $loopdev_prefix$i
549                 truncate -s2g $loopdev_prefix$i
550                 loopdevs[$i]=`run_check_stdout $SUDO_HELPER losetup --find --show $loopdev_prefix$i`
551         done
552 }
553
554 # detach loop devices and reset their size to 0, does not delete the files
555 cleanup_loopdevs()
556 {
557         for dev in ${loopdevs[@]}; do
558                 run_check $SUDO_HELPER losetup -d $dev
559         done
560         for i in `seq $nloopdevs`; do
561                 truncate -s0 $loopdev_prefix$i
562         done
563         run_check $SUDO_HELPER losetup --all
564 }
565
566 init_env()
567 {
568         TEST_MNT="${TEST_MNT:-$TOP/tests/mnt}"
569         export TEST_MNT
570         mkdir -p "$TEST_MNT" || { echo "Failed mkdir -p $TEST_MNT"; exit 1; }
571
572         source $TOP/tests/common.local
573
574         if [ "$TEST_ENABLE_OVERRIDE" = 'true' -a -n "$RESULTS" ]; then
575                 echo "INCLUDE common.local" >> "$RESULTS"
576                 echo "  check: $TEST_ARGS_CHECK" >> "$RESULTS"
577         fi
578 }
579 init_env