btrfs-progs: introduce TEST_TOP and INTERNAL_BIN for tests
[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 # The first parameter is error message to print if it fails, just like
240 # run_must_fail().
241 # NOTE: we don't use pipefail to avoid disturbing other script, so here we
242 # use a temporary output file.
243 # So it doesn't support pipeline in the @cmd
244 run_mustfail_stdout()
245 {
246         local spec
247         local ins
248         local cmd
249         local msg
250         local ret
251         local tmp_output
252
253         tmp_output=$(mktemp --tmpdir btrfs-progs-test--mustfail-stdtout.XXXXXX)
254
255         msg="$1"
256         shift
257
258         if _is_file_or_command "$msg"; then
259                 echo "ASSERTION FAIL: 1st argument of run_mustfail_stdout must be a message"
260                 exit 1
261         fi
262
263         ins=$(_get_spec_ins "$@")
264         spec=$(($ins-1))
265         cmd=$(eval echo "\${$spec}")
266         spec=$(_cmd_spec "${@:$spec}")
267         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
268         echo "############### $@" >> "$RESULTS" 2>&1
269         if [[ $TEST_LOG =~ tty ]]; then echo "CMD(mustfail): $@" > /dev/tty; fi
270         if [ "$1" = 'root_helper' ]; then
271                 "$@" 2>&1 > "$tmp_output"
272         else
273                 $INSTRUMENT "$@" 2>&1 > "$tmp_output"
274         fi
275         ret=$?
276
277         cat "$tmp_output" >> "$RESULTS"
278         cat "$tmp_output"
279         rm "$tmp_output"
280
281         if [ "$ret" != 0 ]; then
282                 echo "failed (expected): $@" >> "$RESULTS"
283                 return 0
284         else
285                 echo "succeeded (unexpected!): $@" >> "$RESULTS"
286                 _fail "unexpected success: $msg"
287                 return 1
288         fi
289 }
290
291 check_prereq()
292 {
293         if [ "$1" = "btrfs-corrupt-block" -o "$1" = "fssum" ]; then
294                 if ! [ -f "$INTERNAL_BIN/$1" ]; then
295                         _fail "Failed prerequisites: $INTERNAL_BIN/$1";
296                 fi
297         elif ! [ -f "$TOP/$1" ]; then
298                 _fail "Failed prerequisites: $TOP/$1";
299         fi
300 }
301
302 check_global_prereq()
303 {
304         which $1 &> /dev/null
305         if [ $? -ne 0 ]; then
306                 _fail "Failed system wide prerequisities: $1";
307         fi
308 }
309
310 check_image()
311 {
312         local image
313
314         image=$1
315         echo "testing image $(basename $image)" >> "$RESULTS"
316         "$TOP/btrfs" check "$image" >> "$RESULTS" 2>&1
317         [ $? -eq 0 ] && _fail "btrfs check should have detected corruption"
318
319         run_check "$TOP/btrfs" check --repair "$image"
320         run_check "$TOP/btrfs" check "$image"
321 }
322
323 # Extract a usable image from packed formats
324 # - raw btrfs filesystem images, suffix .raw
325 # - dtto compressed by XZ, suffix .raw.xz
326 # - meta-dump images with suffix .img
327 # - dtto compressed by XZ, suffix .img.xz
328 # - compressed send stream, .stream.xz
329 extract_image()
330 {
331         local image
332         local cleanme
333
334         image="$1"
335         case "$image" in
336         *.img)
337                 rm -f "$image.restored"
338                 ;;
339         *.img.xz)
340                 xz --decompress --keep "$image" || \
341                         _fail "failed to decompress image $image" >&2
342                 image=${image%%.xz}
343                 rm -f "$image.restored"
344                 cleanme=$image
345                 ;;
346         *.raw)
347                 cp --sparse=auto "$image" "$image.restored"
348                 ;;
349         *.raw.xz)
350                 xz --decompress --keep "$image" || \
351                         _fail "failed to decompress image $image" >&2
352                 image=${image%%.xz}
353                 mv "$image" "$image.restored"
354                 ;;
355         *.stream.xz)
356                 xz --decompress --keep "$image" || \
357                         _fail "failed to decompress file $image" >&2
358                 image=${image%%.xz}
359                 mv "$image" "$image.restored"
360                 ;;
361         esac
362
363         if ! [ -f "$image.restored" ]; then
364                 echo "restoring image $(basename $image)" >> "$RESULTS"
365                 "$TOP/btrfs-image" -r "$image" "$image.restored" \
366                         &>> "$RESULTS" \
367                         || _fail "failed to restore image $image" >&2
368         fi
369
370         [ -f "$cleanme" ] && rm -f "$cleanme"
371
372         echo "$image.restored"
373 }
374
375 # Process all image dumps in a given directory
376 check_all_images()
377 {
378         local dir
379         local extracted
380
381         dir="$1"
382         if [ -z "$dir" ]; then
383                 dir=.
384         fi
385         _assert_path "$dir"
386         for image in $(find "$dir" \( -iname '*.img' -o \
387                                 -iname '*.img.xz' -o    \
388                                 -iname '*.raw' -o       \
389                                 -iname '*.raw.xz' \) | sort)
390         do
391                 extracted=$(extract_image "$image")
392                 check_image "$extracted"
393                 rm -f "$extracted"
394         done
395 }
396
397 # some tests need to mount the recovered image and do verifications call
398 # 'setup_root_helper' and then check for have_root_helper == 1 if the test
399 # needs to fail otherwise; using sudo by default for now
400 SUDO_HELPER=
401 NEED_SUDO_VALIDATE=unknown
402 export SUDO_HELPER
403 export NEED_SUDO_VALIDATE
404 root_helper()
405 {
406         if [ $UID -eq 0 ]; then
407                 "$@"
408         else
409                 if [ "$NEED_SUDO_VALIDATE" = 'yes' ]; then
410                         sudo -v -n &>/dev/null || \
411                                 _not_run "Need to validate sudo credentials"
412                         sudo -n "$@"
413                 elif [ "$NEED_SUDO_VALIDATE" = 'no' ]; then
414                         sudo -n /bin/true &> /dev/null || \
415                                 _not_run "Need to validate sudo user settings"
416                         sudo -n "$@"
417                 else
418                         # should not happen
419                         _not_run "Need to validate root privileges"
420                 fi
421         fi
422 }
423
424 setup_root_helper()
425 {
426         if [ $UID -eq 0 -o -n "$SUDO_HELPER" ]; then
427                 return
428         fi
429
430         # Test for old sudo or special settings, which make sudo -v fail even
431         # if user setting is NOPASSWD
432         sudo -n /bin/true &>/dev/null && NEED_SUDO_VALIDATE=no
433
434         # Newer sudo or default sudo setting
435         sudo -v -n &>/dev/null && NEED_SUDO_VALIDATE=yes
436
437         if [ "$NEED_SUDO_VALIDATE" = 'unknown' ]; then
438                 _not_run "Need to validate root privileges"
439         fi
440         SUDO_HELPER=root_helper
441 }
442
443 prepare_test_dev()
444 {
445         # num[K/M/G/T...]
446         local size="$1"
447
448         [[ "$size" ]] || size='2G'
449         # Still truncate it to new size
450         if [ -n "$TEST_DEV" ]; then
451                 truncate -s 0 "$TEST_DEV"
452                 truncate -s "$size" "$TEST_DEV"
453                 return;
454         fi
455
456         echo "\$TEST_DEV not given, using $TEST_TOP/test.img as fallback" >> \
457                 "$RESULTS"
458         TEST_DEV="$TEST_TOP/test.img"
459
460         truncate -s 0 "$TEST_DEV"
461         truncate -s "$size" "$TEST_DEV" || _not_run "create file for loop device failed"
462 }
463
464 run_check_mount_test_dev()
465 {
466         setup_root_helper
467
468         local loop_opt
469         if [[ -b "$TEST_DEV" ]]; then
470                 loop_opt=""
471         elif [[ -f "$TEST_DEV" ]]; then
472                 loop_opt="-o loop"
473         else
474                 _fail "Invalid \$TEST_DEV: $TEST_DEV"
475         fi
476
477         [[ -d "$TEST_MNT" ]] || {
478                 _fail "Invalid \$TEST_MNT: $TEST_MNT"
479         }
480
481         run_check $SUDO_HELPER mount -t btrfs $loop_opt "$@" "$TEST_DEV" "$TEST_MNT"
482 }
483
484 # $1-$n: optional paths to unmount, otherwise fallback to TEST_DEV
485 run_check_umount_test_dev()
486 {
487         setup_root_helper
488         if [ "$#" = 0 ]; then
489                 set -- "$TEST_DEV"
490         fi
491         run_check $SUDO_HELPER umount "$@"
492 }
493
494 check_kernel_support()
495 {
496         if ! grep -iq 'btrfs' /proc/filesystems; then
497                 run_check $SUDO_HELPER modprobe btrfs
498                         if ! grep -iq 'btrfs' /proc/filesystems; then
499                                 echo \
500 "WARNING: btrfs filesystem not found in /proc/filesystems, some tests might fail"
501                                 return 1
502                         fi
503         fi
504         return 0
505 }
506
507 # how many files to create.
508 DATASET_SIZE=50
509
510 generate_dataset() {
511
512         dataset_type="$1"
513         dirpath=$TEST_MNT/$dataset_type
514         run_check $SUDO_HELPER mkdir -p "$dirpath"
515
516         case "$dataset_type" in
517                 small)
518                         for num in $(seq 1 "$DATASET_SIZE"); do
519                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
520                                 count=1 >/dev/null 2>&1
521                         done
522                         ;;
523
524                 hardlink)
525                         for num in $(seq 1 "$DATASET_SIZE"); do
526                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
527                                 run_check $SUDO_HELPER ln "$dirpath/$dataset_type.$num" "$dirpath/hlink.$num"
528                         done
529                         ;;
530
531                 fast_symlink)
532                         for num in $(seq 1 "$DATASET_SIZE"); do
533                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
534                                 run_check cd "$dirpath" && \
535                                         $SUDO_HELPER ln -s "$dataset_type.$num" "$dirpath/slink.$num" && \
536                                         cd /
537                         done
538                         ;;
539
540                 brokenlink)
541                         for num in $(seq 1 "$DATASET_SIZE"); do
542                                 run_check $SUDO_HELPER ln -s "$dirpath/$dataset_type.$num" "$dirpath/blink.$num"
543                         done
544                         ;;
545
546                 perm)
547                         for modes in 777 775 755 750 700 666 664 644 640 600 444 440 400 000            \
548                                 1777 1775 1755 1750 1700 1666 1664 1644 1640 1600 1444 1440 1400 1000   \
549                                 2777 2775 2755 2750 2700 2666 2664 2644 2640 2600 2444 2440 2400 2000   \
550                                 4777 4775 4755 4750 4700 4666 4664 4644 4640 4600 4444 4440 4400 4000; do
551                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$modes"
552                                 run_check $SUDO_HELPER chmod "$modes" "$dirpath/$dataset_type.$modes"
553                         done
554                         ;;
555
556                 sparse)
557                         for num in $(seq 1 "$DATASET_SIZE"); do
558                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
559                                 count=1 >/dev/null 2>&1
560                                 run_check $SUDO_HELPER truncate -s 500K "$dirpath/$dataset_type.$num"
561                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
562                                 oflag=append conv=notrunc count=1 >/dev/null 2>&1
563                                 run_check $SUDO_HELPER truncate -s 800K "$dirpath/$dataset_type.$num"
564                         done
565                         ;;
566
567                 acls)
568                         for num in $(seq 1 "$DATASET_SIZE"); do
569                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
570                                 run_check $SUDO_HELPER setfacl -m "u:root:x" "$dirpath/$dataset_type.$num"
571                                 run_check $SUDO_HELPER setfattr -n user.foo -v "bar$num" "$dirpath/$dataset_type.$num"
572                         done
573                         ;;
574
575                 fifo)
576                         for num in $(seq 1 "$DATASET_SIZE"); do
577                                 run_check $SUDO_HELPER mkfifo "$dirpath/$dataset_type.$num"
578                         done
579                         ;;
580
581                 slow_symlink)
582                         long_filename=`date +%s | sha256sum | cut -f1 -d ' '`
583                         run_check $SUDO_HELPER touch "$dirpath/$long_filename"
584                         for num in $(seq 1 "$DATASET_SIZE"); do
585                                 run_check $SUDO_HELPER ln -s "$dirpath/$long_filename" "$dirpath/slow_slink.$num"
586                         done
587                         ;;
588                 large)
589                         run_check $SUDO_HELPER dd if=/dev/urandom bs=32M count=1 \
590                                 of="$dirpath/$dataset_type" >/dev/null 2>&1
591                         ;;
592         esac
593 }
594
595 # prepare environment for loop devices, set up the following variables
596 # - nloopdevs -- number of desired devices
597 # - loopdevs  -- array containing paths to all devices (after prepare is called)
598 # - loopdev_prefix -- file backed images starting with this string, 'img' by default
599 #
600 # $1: number of loop devices to be set up
601 setup_loopdevs()
602 {
603         if [ -z "$1" ]; then
604                 _fail "setup_loopdevs needs a number"
605         fi
606         nloopdevs="$1"
607         loopdev_prefix=img
608         declare -a loopdevs
609
610 }
611
612 # create all loop devices from a given loopdev environment
613 prepare_loopdevs()
614 {
615         for i in `seq $nloopdevs`; do
616                 touch $loopdev_prefix$i
617                 chmod a+rw $loopdev_prefix$i
618                 truncate -s0 $loopdev_prefix$i
619                 truncate -s2g $loopdev_prefix$i
620                 loopdevs[$i]=`run_check_stdout $SUDO_HELPER losetup --find --show $loopdev_prefix$i`
621         done
622 }
623
624 # detach loop devices and reset their size to 0, delete the files afterwards
625 cleanup_loopdevs()
626 {
627         for dev in ${loopdevs[@]}; do
628                 run_check $SUDO_HELPER losetup -d $dev
629         done
630         for i in `seq $nloopdevs`; do
631                 truncate -s0 $loopdev_prefix$i
632                 rm -- "$loopdev_prefix$i"
633         done
634         run_check $SUDO_HELPER losetup --all
635 }
636
637 init_env()
638 {
639         TEST_MNT="${TEST_MNT:-$TEST_TOP/mnt}"
640         export TEST_MNT
641         mkdir -p "$TEST_MNT" || { echo "Failed mkdir -p $TEST_MNT"; exit 1; }
642
643         source $TEST_TOP/common.local
644
645         if [ "$TEST_ENABLE_OVERRIDE" = 'true' -a -n "$RESULTS" ]; then
646                 echo "INCLUDE common.local" >> "$RESULTS"
647                 echo "  check: $TEST_ARGS_CHECK" >> "$RESULTS"
648         fi
649 }
650 init_env