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