btrfs-progs: tests: fix _is_file_or_command detection
[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" || _fail "failed: $@"
158         else
159                 $INSTRUMENT "$@" 2>&1 | tee -a "$RESULTS" || _fail "failed: $@"
160         fi
161 }
162
163 # same as run_check but does not fail the test if it's handled gracefully by
164 # the tool, unexpected failure like segfault or abor will exit forcibly
165 # output is logged
166 run_mayfail()
167 {
168         local spec
169         local ins
170         local cmd
171         local ret
172
173         ins=$(_get_spec_ins "$@")
174         spec=$(($ins-1))
175         cmd=$(eval echo "\${$spec}")
176         spec=$(_cmd_spec "${@:$spec}")
177         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
178         echo "############### $@" >> "$RESULTS" 2>&1
179         if [[ $TEST_LOG =~ tty ]]; then echo "CMD(mayfail): $@" > /dev/tty; fi
180         if [ "$1" = 'root_helper' ]; then
181                 "$@" >> "$RESULTS" 2>&1
182         else
183                 $INSTRUMENT "$@" >> "$RESULTS" 2>&1
184         fi
185         ret=$?
186         if [ $ret != 0 ]; then
187                 echo "failed (ignored, ret=$ret): $@" >> "$RESULTS"
188                 if [ $ret == 139 ]; then
189                         _fail "mayfail: returned code 139 (SEGFAULT), not ignored"
190                 elif [ $ret == 134 ]; then
191                         _fail "mayfail: returned code 134 (SIGABRT), not ignored"
192                 fi
193                 return $ret
194         fi
195 }
196
197 # first argument is error message to print if it fails, otherwise
198 # same as run_check but expects the command to fail, output is logged
199 run_mustfail()
200 {
201         local spec
202         local ins
203         local cmd
204         local msg
205
206         msg="$1"
207         shift
208
209         if _is_file_or_command "$msg"; then
210                 echo "ASSERTION FAIL: 1st argument of run_mustfail must be a message"
211                 exit 1
212         fi
213
214         ins=$(_get_spec_ins "$@")
215         spec=$(($ins-1))
216         cmd=$(eval echo "\${$spec}")
217         spec=$(_cmd_spec "${@:$spec}")
218         set -- "${@:1:$(($ins-1))}" $spec "${@: $ins}"
219         echo "############### $@" >> "$RESULTS" 2>&1
220         if [[ $TEST_LOG =~ tty ]]; then echo "CMD(mustfail): $@" > /dev/tty; fi
221         if [ "$1" = 'root_helper' ]; then
222                 "$@" >> "$RESULTS" 2>&1
223         else
224                 $INSTRUMENT "$@" >> "$RESULTS" 2>&1
225         fi
226         if [ $? != 0 ]; then
227                 echo "failed (expected): $@" >> "$RESULTS"
228                 return 0
229         else
230                 echo "succeeded (unexpected!): $@" >> "$RESULTS"
231                 _fail "unexpected success: $msg"
232                 return 1
233         fi
234 }
235
236 check_prereq()
237 {
238         if ! [ -f "$TOP/$1" ]; then
239                 _fail "Failed prerequisites: $1";
240         fi
241 }
242
243 check_global_prereq()
244 {
245         which $1 &> /dev/null
246         if [ $? -ne 0 ]; then
247                 _fail "Failed system wide prerequisities: $1";
248         fi
249 }
250
251 check_image()
252 {
253         local image
254
255         image=$1
256         echo "testing image $(basename $image)" >> "$RESULTS"
257         "$TOP/btrfs" check "$image" >> "$RESULTS" 2>&1
258         [ $? -eq 0 ] && _fail "btrfs check should have detected corruption"
259
260         run_check "$TOP/btrfs" check --repair "$image"
261         run_check "$TOP/btrfs" check "$image"
262 }
263
264 # Extract a usable image from packed formats
265 # - raw btrfs filesystem images, suffix .raw
266 # - dtto compressed by XZ, suffix .raw.xz
267 # - meta-dump images with suffix .img
268 # - dtto compressed by XZ, suffix .img.xz
269 # - compressed send stream, .stream.xz
270 extract_image()
271 {
272         local image
273         local cleanme
274
275         image="$1"
276         case "$image" in
277         *.img)
278                 rm -f "$image.restored"
279                 : ;;
280         *.img.xz)
281                 xz --decompress --keep "$image" || \
282                         _fail "failed to decompress image $image" >&2
283                 image=${image%%.xz}
284                 rm -f "$image.restored"
285                 cleanme=$image
286                 ;;
287         *.raw)
288                 cp --sparse=auto "$image" "$image.restored"
289                 ;;
290         *.raw.xz)
291                 xz --decompress --keep "$image" || \
292                         _fail "failed to decompress image $image" >&2
293                 image=${image%%.xz}
294                 mv "$image" "$image.restored"
295                 ;;
296         *.stream.xz)
297                 xz --decompress --keep "$image" || \
298                         _fail "failed to decompress file $image" >&2
299                 image=${image%%.xz}
300                 mv "$image" "$image.restored"
301                 ;;
302         esac
303
304         if ! [ -f "$image.restored" ]; then
305                 echo "restoring image $(basename $image)" >> "$RESULTS"
306                 "$TOP/btrfs-image" -r "$image" "$image.restored" \
307                         &>> "$RESULTS" \
308                         || _fail "failed to restore image $image" >&2
309         fi
310
311         [ -f "$cleanme" ] && rm -f "$cleanme"
312
313         echo "$image.restored"
314 }
315
316 # Process all image dumps in a given directory
317 check_all_images()
318 {
319         local dir
320         local extracted
321
322         dir="$1"
323         if [ -z "$dir" ]; then
324                 dir=.
325         fi
326         _assert_path "$dir"
327         for image in $(find "$dir" \( -iname '*.img' -o \
328                                 -iname '*.img.xz' -o    \
329                                 -iname '*.raw' -o       \
330                                 -iname '*.raw.xz' \) | sort)
331         do
332                 extracted=$(extract_image "$image")
333                 check_image "$extracted"
334                 rm -f "$extracted"
335         done
336 }
337
338 # some tests need to mount the recovered image and do verifications call
339 # 'setup_root_helper' and then check for have_root_helper == 1 if the test
340 # needs to fail otherwise; using sudo by default for now
341 SUDO_HELPER=
342 NEED_SUDO_VALIDATE=unknown
343 export SUDO_HELPER
344 export NEED_SUDO_VALIDATE
345 root_helper()
346 {
347         if [ $UID -eq 0 ]; then
348                 "$@"
349         else
350                 if [ "$NEED_SUDO_VALIDATE" = 'yes' ]; then
351                         sudo -v -n &>/dev/null || \
352                                 _not_run "Need to validate sudo credentials"
353                         sudo -n "$@"
354                 elif [ "$NEED_SUDO_VALIDATE" = 'no' ]; then
355                         sudo -n /bin/true &> /dev/null || \
356                                 _not_run "Need to validate sudo user settings"
357                         sudo -n "$@"
358                 else
359                         # should not happen
360                         _not_run "Need to validate root privileges"
361                 fi
362         fi
363 }
364
365 setup_root_helper()
366 {
367         if [ $UID -eq 0 -o -n "$SUDO_HELPER" ]; then
368                 return
369         fi
370
371         # Test for old sudo or special settings, which make sudo -v fail even
372         # if user setting is NOPASSWD
373         sudo -n /bin/true &>/dev/null && NEED_SUDO_VALIDATE=no
374
375         # Newer sudo or default sudo setting
376         sudo -v -n &>/dev/null && NEED_SUDO_VALIDATE=yes
377
378         if [ "$NEED_SUDO_VALIDATE" = 'unknown' ]; then
379                 _not_run "Need to validate root privileges"
380         fi
381         SUDO_HELPER=root_helper
382 }
383
384 prepare_test_dev()
385 {
386         # num[K/M/G/T...]
387         local size="$1"
388
389         [[ "$TEST_DEV" ]] && return
390         [[ "$size" ]] || size='2G'
391
392         echo "\$TEST_DEV not given, use $TOP/test/test.img as fallback" >> \
393                 "$RESULTS"
394         TEST_DEV="$TOP/tests/test.img"
395
396         truncate -s "$size" "$TEST_DEV" || _not_run "create file for loop device failed"
397 }
398
399 run_check_mount_test_dev()
400 {
401         setup_root_helper
402
403         local loop_opt
404         if [[ -b "$TEST_DEV" ]]; then
405                 loop_opt=""
406         elif [[ -f "$TEST_DEV" ]]; then
407                 loop_opt="-o loop"
408         else
409                 _fail "Invalid \$TEST_DEV: $TEST_DEV"
410         fi
411
412         [[ -d "$TEST_MNT" ]] || {
413                 _fail "Invalid \$TEST_MNT: $TEST_MNT"
414         }
415
416         run_check $SUDO_HELPER mount -t btrfs $loop_opt "$@" "$TEST_DEV" "$TEST_MNT"
417 }
418
419 run_check_umount_test_dev()
420 {
421         setup_root_helper
422         run_check $SUDO_HELPER umount "$@" "$TEST_DEV"
423 }
424
425 check_kernel_support()
426 {
427         if ! grep -iq 'btrfs' /proc/filesystems; then
428                 echo "WARNING: btrfs filesystem not listed in /proc/filesystems, some tests might fail"
429                 return 1
430         fi
431         return 0
432 }
433
434 # how many files to create.
435 DATASET_SIZE=50
436
437 generate_dataset() {
438
439         dataset_type="$1"
440         dirpath=$TEST_MNT/$dataset_type
441         run_check $SUDO_HELPER mkdir -p "$dirpath"
442
443         case "$dataset_type" in
444                 small)
445                         for num in $(seq 1 "$DATASET_SIZE"); do
446                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
447                                 count=1 >/dev/null 2>&1
448                         done
449                         ;;
450
451                 hardlink)
452                         for num in $(seq 1 "$DATASET_SIZE"); do
453                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
454                                 run_check $SUDO_HELPER ln "$dirpath/$dataset_type.$num" "$dirpath/hlink.$num"
455                         done
456                         ;;
457
458                 fast_symlink)
459                         for num in $(seq 1 "$DATASET_SIZE"); do
460                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
461                                 run_check cd "$dirpath" && \
462                                         $SUDO_HELPER ln -s "$dataset_type.$num" "$dirpath/slink.$num" && \
463                                         cd /
464                         done
465                         ;;
466
467                 brokenlink)
468                         for num in $(seq 1 "$DATASET_SIZE"); do
469                                 run_check $SUDO_HELPER ln -s "$dirpath/$dataset_type.$num" "$dirpath/blink.$num"
470                         done
471                         ;;
472
473                 perm)
474                         for modes in 777 775 755 750 700 666 664 644 640 600 444 440 400 000            \
475                                 1777 1775 1755 1750 1700 1666 1664 1644 1640 1600 1444 1440 1400 1000   \
476                                 2777 2775 2755 2750 2700 2666 2664 2644 2640 2600 2444 2440 2400 2000   \
477                                 4777 4775 4755 4750 4700 4666 4664 4644 4640 4600 4444 4440 4400 4000; do
478                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$modes"
479                                 run_check $SUDO_HELPER chmod "$modes" "$dirpath/$dataset_type.$modes"
480                         done
481                         ;;
482
483                 sparse)
484                         for num in $(seq 1 "$DATASET_SIZE"); do
485                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
486                                 count=1 >/dev/null 2>&1
487                                 run_check $SUDO_HELPER truncate -s 500K "$dirpath/$dataset_type.$num"
488                                 run_check $SUDO_HELPER dd if=/dev/urandom of="$dirpath/$dataset_type.$num" bs=10K \
489                                 oflag=append conv=notrunc count=1 >/dev/null 2>&1
490                                 run_check $SUDO_HELPER truncate -s 800K "$dirpath/$dataset_type.$num"
491                         done
492                         ;;
493
494                 acls)
495                         for num in $(seq 1 "$DATASET_SIZE"); do
496                                 run_check $SUDO_HELPER touch "$dirpath/$dataset_type.$num"
497                                 run_check $SUDO_HELPER setfacl -m "u:root:x" "$dirpath/$dataset_type.$num"
498                                 run_check $SUDO_HELPER setfattr -n user.foo -v "bar$num" "$dirpath/$dataset_type.$num"
499                         done
500                         ;;
501
502                 fifo)
503                         for num in $(seq 1 "$DATASET_SIZE"); do
504                                 run_check $SUDO_HELPER mkfifo "$dirpath/$dataset_type.$num"
505                         done
506                         ;;
507
508                 slow_symlink)
509                         long_filename=`date +%s | sha256sum | cut -f1 -d'-'`
510                         run_check $SUDO_HELPER touch "$dirpath/$long_filename"
511                         for num in $(seq 1 "$DATASET_SIZE"); do
512                                 run_check $SUDO_HELPER ln -s "$dirpath/$long_filename" "$dirpath/slow_slink.$num"
513                         done
514                         ;;
515                 large)
516                         run_check $SUDO_HELPER dd if=/dev/urandom bs=32M count=1 \
517                                 of="$dirpath/$dataset_type" >/dev/null 2>&1
518                         ;;
519         esac
520 }
521
522 init_env()
523 {
524         TEST_MNT="${TEST_MNT:-$TOP/tests/mnt}"
525         export TEST_MNT
526         mkdir -p "$TEST_MNT" || { echo "Failed mkdir -p $TEST_MNT"; exit 1; }
527
528         source $TOP/tests/common.local
529
530         if [ "$TEST_ENABLE_OVERRIDE" = 'true' -a -n "$RESULTS" ]; then
531                 echo "INCLUDE common.local" >> "$RESULTS"
532                 echo "  check: $TEST_ARGS_CHECK" >> "$RESULTS"
533         fi
534 }
535 init_env