chiark / gitweb /
test: make the image bigger
[elogind.git] / test / test-functions
1 #!/bin/bash
2 # -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
3 # ex: ts=8 sw=4 sts=4 et filetype=sh
4 PATH=/sbin:/bin:/usr/sbin:/usr/bin
5 export PATH
6
7 KERNEL_VER=${KERNEL_VER-$(uname -r)}
8 KERNEL_MODS="/lib/modules/$KERNEL_VER/"
9
10 BASICTOOLS="sh bash setsid loadkeys setfont login sushell sulogin gzip sleep echo mount umount cryptsetup date dmsetup modprobe"
11 DEBUGTOOLS="df free ls stty cat ps ln ip route dmesg dhclient mkdir cp ping dhclient strace less grep id tty touch du sort"
12
13 function find_qemu_bin() {
14     # SUSE and Red Hat call the binary qemu-kvm
15     # Debian and Gentoo call it kvm
16     [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a kvm qemu-kvm 2>/dev/null | grep '^/' -m1)
17
18     [ "$ARCH" ] || ARCH=$(uname -m)
19     case $ARCH in
20     x86_64)
21         # QEMU's own build system calls it qemu-system-x86_64
22         [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-x86_64 2>/dev/null | grep '^/' -m1)
23         ;;
24     i*86)
25         # new i386 version of QEMU
26         [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu-system-i386 2>/dev/null | grep '^/' -m1)
27
28         # i386 version of QEMU
29         [ "$QEMU_BIN" ] || QEMU_BIN=$(which -a qemu 2>/dev/null | grep '^/' -m1)
30         ;;
31     esac
32
33     if [ ! -e "$QEMU_BIN" ]; then
34         echo "Could not find a suitable QEMU binary" >&2
35         return 1
36     fi
37 }
38
39 run_qemu() {
40     [ "$KERNEL_BIN" ] || KERNEL_BIN=/boot/vmlinuz-$KERNEL_VER
41     [ "$INITRD" ]     || INITRD=/boot/initramfs-${KERNEL_VER}.img
42     [ "$QEMU_SMP" ]   || QEMU_SMP=1
43
44     find_qemu_bin || return 1
45
46     KERNEL_APPEND="root=/dev/sda1 \
47 systemd.log_level=debug \
48 raid=noautodetect \
49 loglevel=2 \
50 init=/usr/lib/systemd/systemd \
51 ro \
52 console=ttyS0 \
53 selinux=0 \
54 $KERNEL_APPEND \
55 "
56
57     QEMU_OPTIONS="-machine accel=kvm:tcg \
58 -smp $QEMU_SMP \
59 -net none \
60 -m 512M \
61 -nographic \
62 -kernel $KERNEL_BIN \
63 "
64
65     if [ "$INITRD" ]; then
66         QEMU_OPTIONS="$QEMU_OPTIONS -initrd $INITRD"
67     fi
68
69     $QEMU_BIN $QEMU_OPTIONS -append "$KERNEL_APPEND" $TESTDIR/rootdisk.img || return 1
70 }
71
72 run_nspawn() {
73     ../../systemd-nspawn --boot --directory=$TESTDIR/nspawn-root /usr/lib/systemd/systemd
74 }
75
76 setup_basic_environment() {
77     # create the basic filesystem layout
78     setup_basic_dirs
79
80     install_systemd
81     install_missing_libraries
82     install_config_files
83     create_rc_local
84     install_basic_tools
85     install_libnss
86     install_pam
87     install_dbus
88     install_fonts
89     install_keymaps
90     install_terminfo
91     install_execs
92     install_plymouth
93     install_debug_tools
94     install_ld_so_conf
95     strip_binaries
96     install_depmod_files
97     generate_module_dependencies
98     # softlink mtab
99     ln -fs /proc/self/mounts $initdir/etc/mtab
100 }
101
102 install_dmevent() {
103     instmods dm_crypt =crypto
104     type -P dmeventd >/dev/null && dracut_install dmeventd
105     inst_libdir_file "libdevmapper-event.so*"
106     inst_rules 10-dm.rules 13-dm-disk.rules 95-dm-notify.rules
107 }
108
109 install_systemd() {
110     # install compiled files
111     (cd $TEST_BASE_DIR/..; make DESTDIR=$initdir install)
112     # remove unneeded documentation
113     rm -fr $initdir/usr/share/{man,doc,gtk-doc}
114     # we strip binaries since debug symbols increase binaries size a lot
115     # and it could fill the available space
116     strip_binaries
117 }
118
119 install_missing_libraries() {
120     # install possible missing libraries
121     for i in $initdir/{sbin,bin}/* $initdir/lib/systemd/*; do
122         inst_libs $i
123     done
124 }
125
126 create_empty_image() {
127     rm -f "$TESTDIR/rootdisk.img"
128     # Create the blank file to use as a root filesystem
129     dd if=/dev/null of="$TESTDIR/rootdisk.img" bs=1M seek=300
130     LOOPDEV=$(losetup --show -P -f $TESTDIR/rootdisk.img)
131     [ -b "$LOOPDEV" ] || return 1
132     echo "LOOPDEV=$LOOPDEV" >> $STATEFILE
133     sfdisk -C 9600 -H 2 -S 32 -L "$LOOPDEV" <<EOF
134 ,4800
135 ,
136 EOF
137
138     mkfs.ext3 -L systemd "${LOOPDEV}p1"
139 }
140
141 check_result_nspawn() {
142     ret=1
143     [[ -e $TESTDIR/nspawn-root/testok ]] && ret=0
144     [[ -f $TESTDIR/nspawn-root/failed ]] && cp -a $TESTDIR/nspawn-root/failed $TESTDIR
145     cp -a $TESTDIR/nspawn-root/var/log/journal $TESTDIR
146     [[ -f $TESTDIR/failed ]] && cat $TESTDIR/failed
147     ls -l $TESTDIR/journal/*/*.journal
148     test -s $TESTDIR/failed && ret=$(($ret+1))
149     return $ret
150 }
151
152 strip_binaries() {
153     ddebug "Strip binaries"
154     find "$initdir" -executable -not -path '*/lib/modules/*.ko' -type f | xargs strip --strip-unneeded | ddebug
155 }
156
157 create_rc_local() {
158     mkdir -p $initdir/etc/rc.d
159     cat >$initdir/etc/rc.d/rc.local <<EOF
160 #!/bin/bash
161 exit 0
162 EOF
163     chmod 0755 $initdir/etc/rc.d/rc.local
164 }
165
166 install_execs() {
167     # install any Execs from the service files
168     egrep -ho '^Exec[^ ]*=[^ ]+' $initdir/lib/systemd/system/*.service \
169         | while read i; do
170         i=${i##Exec*=}; i=${i##-}
171         inst $i
172     done
173 }
174
175 generate_module_dependencies() {
176     if [[ -d $initdir/lib/modules/$KERNEL_VER ]] && \
177         ! depmod -a -b "$initdir" $KERNEL_VER; then
178             dfatal "\"depmod -a $KERNEL_VER\" failed."
179             exit 1
180     fi
181 }
182
183 install_depmod_files() {
184     inst /lib/modules/$KERNEL_VER/modules.order
185     inst /lib/modules/$KERNEL_VER/modules.builtin
186 }
187
188 install_plymouth() {
189     # install plymouth, if found... else remove plymouth service files
190     # if [ -x /usr/libexec/plymouth/plymouth-populate-initrd ]; then
191     #     PLYMOUTH_POPULATE_SOURCE_FUNCTIONS="$TEST_BASE_DIR/test-functions" \
192     #         /usr/libexec/plymouth/plymouth-populate-initrd -t $initdir
193     #         dracut_install plymouth plymouthd
194     # else
195         rm -f $initdir/{usr/lib,etc}/systemd/system/plymouth* $initdir/{usr/lib,etc}/systemd/system/*/plymouth*
196     # fi
197 }
198
199 install_ld_so_conf() {
200     cp -a /etc/ld.so.conf* $initdir/etc
201     ldconfig -r "$initdir"
202 }
203
204 install_config_files() {
205     inst /etc/sysconfig/init
206     inst /etc/passwd
207     inst /etc/shadow
208     inst /etc/group
209     inst /etc/shells
210     inst /etc/nsswitch.conf
211     inst /etc/pam.conf
212     inst /etc/securetty
213     inst /etc/os-release
214     inst /etc/localtime
215     # we want an empty environment
216     > $initdir/etc/environment
217     > $initdir/etc/machine-id
218     # set the hostname
219     echo systemd-testsuite > $initdir/etc/hostname
220     # fstab
221     cat >$initdir/etc/fstab <<EOF
222 LABEL=systemd           /       ext3    rw 0 1
223 EOF
224 }
225
226 install_basic_tools() {
227     [[ $BASICTOOLS ]] && dracut_install $BASICTOOLS
228 }
229
230 install_debug_tools() {
231     [[ $DEBUGTOOLS ]] && dracut_install $DEBUGTOOLS
232 }
233
234 install_libnss() {
235     # install libnss_files for login
236     inst_libdir_file "libnss_files*"
237 }
238
239 install_dbus() {
240     inst /usr/lib/systemd/system/dbus.socket
241     inst /usr/lib/systemd/system/dbus.service
242
243     find \
244         /etc/dbus-1 -xtype f \
245         | while read file; do
246         inst $file
247     done
248 }
249
250 install_pam() {
251     find \
252         /etc/pam.d \
253         /etc/security \
254         /lib64/security \
255         /lib/security -xtype f \
256         | while read file; do
257         inst $file
258     done
259 }
260
261 install_keymaps() {
262     for i in \
263         /usr/lib/kbd/keymaps/include/* \
264         /usr/lib/kbd/keymaps/i386/include/* \
265         /usr/lib/kbd/keymaps/i386/qwerty/us.*; do
266             [[ -f $i ]] || continue
267             inst $i
268     done
269 }
270
271 install_fonts() {
272     for i in \
273         /usr/lib/kbd/consolefonts/latarcyrheb-sun16*; do
274             [[ -f $i ]] || continue
275             inst $i
276     done
277 }
278
279 install_terminfo() {
280     for _terminfodir in /lib/terminfo /etc/terminfo /usr/share/terminfo; do
281         [ -f ${_terminfodir}/l/linux ] && break
282     done
283     dracut_install -o ${_terminfodir}/l/linux
284 }
285
286 setup_testsuite() {
287     cp $TEST_BASE_DIR/{testsuite.target,end.service} $initdir/etc/systemd/system/
288
289     mkdir -p $initdir/etc/systemd/system/testsuite.target.wants
290     ln -fs $TEST_BASE_DIR/testsuite.service $initdir/etc/systemd/system/testsuite.target.wants/testsuite.service
291     ln -fs $TEST_BASE_DIR/end.service $initdir/etc/systemd/system/testsuite.target.wants/end.service
292
293     # make the testsuite the default target
294     ln -fs testsuite.target $initdir/etc/systemd/system/default.target
295 }
296
297 setup_nspawn_root() {
298     rm -fr $TESTDIR/nspawn-root
299     ddebug "cp -ar $initdir $TESTDIR/nspawn-root"
300     cp -ar $initdir $TESTDIR/nspawn-root
301     # we don't mount in the nspawn root
302     rm -f $TESTDIR/nspawn-root/etc/fstab
303 }
304
305 setup_basic_dirs() {
306     mkdir -p $initdir/run
307     mkdir -p $initdir/etc/systemd/system
308     mkdir -p $initdir/var/log/journal
309
310     for d in usr/bin usr/sbin bin etc lib "$libdir" sbin tmp usr var var/log dev proc sys sysroot root run run/lock run/initramfs; do
311         if [ -L "/$d" ]; then
312             inst_symlink "/$d"
313         else
314             inst_dir "/$d"
315         fi
316     done
317
318     ln -sfn /run "$initdir/var/run"
319     ln -sfn /run/lock "$initdir/var/lock"
320 }
321
322 inst_libs() {
323     local _bin=$1
324     local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
325     local _file _line
326
327     LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
328         [[ $_line = 'not a dynamic executable' ]] && break
329
330         if [[ $_line =~ $_so_regex ]]; then
331             _file=${BASH_REMATCH[1]}
332             [[ -e ${initdir}/$_file ]] && continue
333             inst_library "$_file"
334             continue
335         fi
336
337         if [[ $_line =~ not\ found ]]; then
338             dfatal "Missing a shared library required by $_bin."
339             dfatal "Run \"ldd $_bin\" to find out what it is."
340             dfatal "$_line"
341             dfatal "dracut cannot create an initrd."
342             exit 1
343         fi
344     done
345 }
346
347 import_testdir() {
348     STATEFILE=".testdir"
349     [[ -e $STATEFILE ]] && . $STATEFILE
350     if [[ -z "$TESTDIR" ]] || [[ ! -d "$TESTDIR" ]]; then
351         TESTDIR=$(mktemp --tmpdir=/var/tmp -d -t systemd-test.XXXXXX)
352         echo "TESTDIR=\"$TESTDIR\"" > $STATEFILE
353         export TESTDIR
354     fi
355 }
356
357 import_initdir() {
358     initdir=$TESTDIR/root
359     export initdir
360 }
361
362 ## @brief Converts numeric logging level to the first letter of level name.
363 #
364 # @param lvl Numeric logging level in range from 1 to 6.
365 # @retval 1 if @a lvl is out of range.
366 # @retval 0 if @a lvl is correct.
367 # @result Echoes first letter of level name.
368 _lvl2char() {
369     case "$1" in
370         1) echo F;;
371         2) echo E;;
372         3) echo W;;
373         4) echo I;;
374         5) echo D;;
375         6) echo T;;
376         *) return 1;;
377     esac
378 }
379
380 ## @brief Internal helper function for _do_dlog()
381 #
382 # @param lvl Numeric logging level.
383 # @param msg Message.
384 # @retval 0 It's always returned, even if logging failed.
385 #
386 # @note This function is not supposed to be called manually. Please use
387 # dtrace(), ddebug(), or others instead which wrap this one.
388 #
389 # This function calls _do_dlog() either with parameter msg, or if
390 # none is given, it will read standard input and will use every line as
391 # a message.
392 #
393 # This enables:
394 # dwarn "This is a warning"
395 # echo "This is a warning" | dwarn
396 LOG_LEVEL=4
397
398 dlog() {
399     [ -z "$LOG_LEVEL" ] && return 0
400     [ $1 -le $LOG_LEVEL ] || return 0
401     local lvl="$1"; shift
402     local lvlc=$(_lvl2char "$lvl") || return 0
403
404     if [ $# -ge 1 ]; then
405         echo "$lvlc: $*"
406     else
407         while read line; do
408             echo "$lvlc: " "$line"
409         done
410     fi
411 }
412
413 ## @brief Logs message at TRACE level (6)
414 #
415 # @param msg Message.
416 # @retval 0 It's always returned, even if logging failed.
417 dtrace() {
418     set +x
419     dlog 6 "$@"
420     [ -n "$debug" ] && set -x || :
421 }
422
423 ## @brief Logs message at DEBUG level (5)
424 #
425 # @param msg Message.
426 # @retval 0 It's always returned, even if logging failed.
427 ddebug() {
428 #    set +x
429     dlog 5 "$@"
430 #    [ -n "$debug" ] && set -x || :
431 }
432
433 ## @brief Logs message at INFO level (4)
434 #
435 # @param msg Message.
436 # @retval 0 It's always returned, even if logging failed.
437 dinfo() {
438     set +x
439     dlog 4 "$@"
440     [ -n "$debug" ] && set -x || :
441 }
442
443 ## @brief Logs message at WARN level (3)
444 #
445 # @param msg Message.
446 # @retval 0 It's always returned, even if logging failed.
447 dwarn() {
448     set +x
449     dlog 3 "$@"
450     [ -n "$debug" ] && set -x || :
451 }
452
453 ## @brief Logs message at ERROR level (2)
454 #
455 # @param msg Message.
456 # @retval 0 It's always returned, even if logging failed.
457 derror() {
458 #    set +x
459     dlog 2 "$@"
460 #    [ -n "$debug" ] && set -x || :
461 }
462
463 ## @brief Logs message at FATAL level (1)
464 #
465 # @param msg Message.
466 # @retval 0 It's always returned, even if logging failed.
467 dfatal() {
468     set +x
469     dlog 1 "$@"
470     [ -n "$debug" ] && set -x || :
471 }
472
473
474 # Generic substring function.  If $2 is in $1, return 0.
475 strstr() { [ "${1#*$2*}" != "$1" ]; }
476
477 # normalize_path <path>
478 # Prints the normalized path, where it removes any duplicated
479 # and trailing slashes.
480 # Example:
481 # $ normalize_path ///test/test//
482 # /test/test
483 normalize_path() {
484     shopt -q -s extglob
485     set -- "${1//+(\/)//}"
486     shopt -q -u extglob
487     echo "${1%/}"
488 }
489
490 # convert_abs_rel <from> <to>
491 # Prints the relative path, when creating a symlink to <to> from <from>.
492 # Example:
493 # $ convert_abs_rel /usr/bin/test /bin/test-2
494 # ../../bin/test-2
495 # $ ln -s $(convert_abs_rel /usr/bin/test /bin/test-2) /usr/bin/test
496 convert_abs_rel() {
497     local __current __absolute __abssize __cursize __newpath
498     local -i __i __level
499
500     set -- "$(normalize_path "$1")" "$(normalize_path "$2")"
501
502     # corner case #1 - self looping link
503     [[ "$1" == "$2" ]] && { echo "${1##*/}"; return; }
504
505     # corner case #2 - own dir link
506     [[ "${1%/*}" == "$2" ]] && { echo "."; return; }
507
508     IFS="/" __current=($1)
509     IFS="/" __absolute=($2)
510
511     __abssize=${#__absolute[@]}
512     __cursize=${#__current[@]}
513
514     while [[ ${__absolute[__level]} == ${__current[__level]} ]]
515     do
516         (( __level++ ))
517         if (( __level > __abssize || __level > __cursize ))
518         then
519             break
520         fi
521     done
522
523     for ((__i = __level; __i < __cursize-1; __i++))
524     do
525         if ((__i > __level))
526         then
527             __newpath=$__newpath"/"
528         fi
529         __newpath=$__newpath".."
530     done
531
532     for ((__i = __level; __i < __abssize; __i++))
533     do
534         if [[ -n $__newpath ]]
535         then
536             __newpath=$__newpath"/"
537         fi
538         __newpath=$__newpath${__absolute[__i]}
539     done
540
541     echo "$__newpath"
542 }
543
544
545 # Install a directory, keeping symlinks as on the original system.
546 # Example: if /lib points to /lib64 on the host, "inst_dir /lib/file"
547 # will create ${initdir}/lib64, ${initdir}/lib64/file,
548 # and a symlink ${initdir}/lib -> lib64.
549 inst_dir() {
550     [[ -e ${initdir}/"$1" ]] && return 0  # already there
551
552     local _dir="$1" _part="${1%/*}" _file
553     while [[ "$_part" != "${_part%/*}" ]] && ! [[ -e "${initdir}/${_part}" ]]; do
554         _dir="$_part $_dir"
555         _part=${_part%/*}
556     done
557
558     # iterate over parent directories
559     for _file in $_dir; do
560         [[ -e "${initdir}/$_file" ]] && continue
561         if [[ -L $_file ]]; then
562             inst_symlink "$_file"
563         else
564             # create directory
565             mkdir -m 0755 -p "${initdir}/$_file" || return 1
566             [[ -e "$_file" ]] && chmod --reference="$_file" "${initdir}/$_file"
567             chmod u+w "${initdir}/$_file"
568         fi
569     done
570 }
571
572 # $1 = file to copy to ramdisk
573 # $2 (optional) Name for the file on the ramdisk
574 # Location of the image dir is assumed to be $initdir
575 # We never overwrite the target if it exists.
576 inst_simple() {
577     [[ -f "$1" ]] || return 1
578     strstr "$1" "/" || return 1
579
580     local _src=$1 target="${2:-$1}"
581     if ! [[ -d ${initdir}/$target ]]; then
582         [[ -e ${initdir}/$target ]] && return 0
583         [[ -L ${initdir}/$target ]] && return 0
584         [[ -d "${initdir}/${target%/*}" ]] || inst_dir "${target%/*}"
585     fi
586     # install checksum files also
587     if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
588         inst "${_src%/*}/.${_src##*/}.hmac" "${target%/*}/.${target##*/}.hmac"
589     fi
590     ddebug "Installing $_src"
591     cp --sparse=always -pfL "$_src" "${initdir}/$target"
592 }
593
594 # find symlinks linked to given library file
595 # $1 = library file
596 # Function searches for symlinks by stripping version numbers appended to
597 # library filename, checks if it points to the same target and finally
598 # prints the list of symlinks to stdout.
599 #
600 # Example:
601 # rev_lib_symlinks libfoo.so.8.1
602 # output: libfoo.so.8 libfoo.so
603 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
604 rev_lib_symlinks() {
605     [[ ! $1 ]] && return 0
606
607     local fn="$1" orig="$(readlink -f "$1")" links=''
608
609     [[ ${fn} =~ .*\.so\..* ]] || return 1
610
611     until [[ ${fn##*.} == so ]]; do
612         fn="${fn%.*}"
613         [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
614     done
615
616     echo "${links}"
617 }
618
619 # Same as above, but specialized to handle dynamic libraries.
620 # It handles making symlinks according to how the original library
621 # is referenced.
622 inst_library() {
623     local _src="$1" _dest=${2:-$1} _lib _reallib _symlink
624     strstr "$1" "/" || return 1
625     [[ -e $initdir/$_dest ]] && return 0
626     if [[ -L $_src ]]; then
627         # install checksum files also
628         if [[ -e "${_src%/*}/.${_src##*/}.hmac" ]]; then
629             inst "${_src%/*}/.${_src##*/}.hmac" "${_dest%/*}/.${_dest##*/}.hmac"
630         fi
631         _reallib=$(readlink -f "$_src")
632         inst_simple "$_reallib" "$_reallib"
633         inst_dir "${_dest%/*}"
634         [[ -d "${_dest%/*}" ]] && _dest=$(readlink -f "${_dest%/*}")/${_dest##*/}
635         ln -sfn $(convert_abs_rel "${_dest}" "${_reallib}") "${initdir}/${_dest}"
636     else
637         inst_simple "$_src" "$_dest"
638     fi
639
640     # Create additional symlinks.  See rev_symlinks description.
641     for _symlink in $(rev_lib_symlinks $_src) $(rev_lib_symlinks $_reallib); do
642         [[ ! -e $initdir/$_symlink ]] && {
643             ddebug "Creating extra symlink: $_symlink"
644             inst_symlink $_symlink
645         }
646     done
647 }
648
649 # find a binary.  If we were not passed the full path directly,
650 # search in the usual places to find the binary.
651 find_binary() {
652     if [[ -z ${1##/*} ]]; then
653         if [[ -x $1 ]] || { strstr "$1" ".so" && ldd $1 &>/dev/null; };  then
654             echo $1
655             return 0
656         fi
657     fi
658
659     type -P $1
660 }
661
662 # Same as above, but specialized to install binary executables.
663 # Install binary executable, and all shared library dependencies, if any.
664 inst_binary() {
665     local _bin _target
666     _bin=$(find_binary "$1") || return 1
667     _target=${2:-$_bin}
668     [[ -e $initdir/$_target ]] && return 0
669     [[ -L $_bin ]] && inst_symlink $_bin $_target && return 0
670     local _file _line
671     local _so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
672     # I love bash!
673     LC_ALL=C ldd "$_bin" 2>/dev/null | while read _line; do
674         [[ $_line = 'not a dynamic executable' ]] && break
675
676         if [[ $_line =~ $_so_regex ]]; then
677             _file=${BASH_REMATCH[1]}
678             [[ -e ${initdir}/$_file ]] && continue
679             inst_library "$_file"
680             continue
681         fi
682
683         if [[ $_line =~ not\ found ]]; then
684             dfatal "Missing a shared library required by $_bin."
685             dfatal "Run \"ldd $_bin\" to find out what it is."
686             dfatal "$_line"
687             dfatal "dracut cannot create an initrd."
688             exit 1
689         fi
690     done
691     inst_simple "$_bin" "$_target"
692 }
693
694 # same as above, except for shell scripts.
695 # If your shell script does not start with shebang, it is not a shell script.
696 inst_script() {
697     local _bin
698     _bin=$(find_binary "$1") || return 1
699     shift
700     local _line _shebang_regex
701     read -r -n 80 _line <"$_bin"
702     # If debug is set, clean unprintable chars to prevent messing up the term
703     [[ $debug ]] && _line=$(echo -n "$_line" | tr -c -d '[:print:][:space:]')
704     _shebang_regex='(#! *)(/[^ ]+).*'
705     [[ $_line =~ $_shebang_regex ]] || return 1
706     inst "${BASH_REMATCH[2]}" && inst_simple "$_bin" "$@"
707 }
708
709 # same as above, but specialized for symlinks
710 inst_symlink() {
711     local _src=$1 _target=${2:-$1} _realsrc
712     strstr "$1" "/" || return 1
713     [[ -L $1 ]] || return 1
714     [[ -L $initdir/$_target ]] && return 0
715     _realsrc=$(readlink -f "$_src")
716     if ! [[ -e $initdir/$_realsrc ]]; then
717         if [[ -d $_realsrc ]]; then
718             inst_dir "$_realsrc"
719         else
720             inst "$_realsrc"
721         fi
722     fi
723     [[ ! -e $initdir/${_target%/*} ]] && inst_dir "${_target%/*}"
724     [[ -d ${_target%/*} ]] && _target=$(readlink -f ${_target%/*})/${_target##*/}
725     ln -sfn $(convert_abs_rel "${_target}" "${_realsrc}") "$initdir/$_target"
726 }
727
728 # attempt to install any programs specified in a udev rule
729 inst_rule_programs() {
730     local _prog _bin
731
732     if grep -qE 'PROGRAM==?"[^ "]+' "$1"; then
733         for _prog in $(grep -E 'PROGRAM==?"[^ "]+' "$1" | sed -r 's/.*PROGRAM==?"([^ "]+).*/\1/'); do
734             if [ -x /lib/udev/$_prog ]; then
735                 _bin=/lib/udev/$_prog
736             else
737                 _bin=$(find_binary "$_prog") || {
738                     dinfo "Skipping program $_prog using in udev rule $(basename $1) as it cannot be found"
739                     continue;
740                 }
741             fi
742
743             #dinfo "Installing $_bin due to it's use in the udev rule $(basename $1)"
744             dracut_install "$_bin"
745         done
746     fi
747 }
748
749 # udev rules always get installed in the same place, so
750 # create a function to install them to make life simpler.
751 inst_rules() {
752     local _target=/etc/udev/rules.d _rule _found
753
754     inst_dir "/lib/udev/rules.d"
755     inst_dir "$_target"
756     for _rule in "$@"; do
757         if [ "${rule#/}" = "$rule" ]; then
758             for r in /lib/udev/rules.d /etc/udev/rules.d; do
759                 if [[ -f $r/$_rule ]]; then
760                     _found="$r/$_rule"
761                     inst_simple "$_found"
762                     inst_rule_programs "$_found"
763                 fi
764             done
765         fi
766         for r in '' ./ $dracutbasedir/rules.d/; do
767             if [[ -f ${r}$_rule ]]; then
768                 _found="${r}$_rule"
769                 inst_simple "$_found" "$_target/${_found##*/}"
770                 inst_rule_programs "$_found"
771             fi
772         done
773         [[ $_found ]] || dinfo "Skipping udev rule: $_rule"
774     done
775 }
776
777 # general purpose installation function
778 # Same args as above.
779 inst() {
780     local _x
781
782     case $# in
783         1) ;;
784         2) [[ ! $initdir && -d $2 ]] && export initdir=$2
785             [[ $initdir = $2 ]] && set $1;;
786         3) [[ -z $initdir ]] && export initdir=$2
787             set $1 $3;;
788         *) dfatal "inst only takes 1 or 2 or 3 arguments"
789             exit 1;;
790     esac
791     for _x in inst_symlink inst_script inst_binary inst_simple; do
792         $_x "$@" && return 0
793     done
794     return 1
795 }
796
797 # install any of listed files
798 #
799 # If first argument is '-d' and second some destination path, first accessible
800 # source is installed into this path, otherwise it will installed in the same
801 # path as source.  If none of listed files was installed, function return 1.
802 # On first successful installation it returns with 0 status.
803 #
804 # Example:
805 #
806 # inst_any -d /bin/foo /bin/bar /bin/baz
807 #
808 # Lets assume that /bin/baz exists, so it will be installed as /bin/foo in
809 # initramfs.
810 inst_any() {
811     local to f
812
813     [[ $1 = '-d' ]] && to="$2" && shift 2
814
815     for f in "$@"; do
816         if [[ -e $f ]]; then
817             [[ $to ]] && inst "$f" "$to" && return 0
818             inst "$f" && return 0
819         fi
820     done
821
822     return 1
823 }
824
825 # dracut_install [-o ] <file> [<file> ... ]
826 # Install <file> to the initramfs image
827 # -o optionally install the <file> and don't fail, if it is not there
828 dracut_install() {
829     local _optional=no
830     if [[ $1 = '-o' ]]; then
831         _optional=yes
832         shift
833     fi
834     while (($# > 0)); do
835         if ! inst "$1" ; then
836             if [[ $_optional = yes ]]; then
837                 dinfo "Skipping program $1 as it cannot be found and is" \
838                     "flagged to be optional"
839             else
840                 dfatal "Failed to install $1"
841                 exit 1
842             fi
843         fi
844         shift
845     done
846 }
847
848 # Install a single kernel module along with any firmware it may require.
849 # $1 = full path to kernel module to install
850 install_kmod_with_fw() {
851     # no need to go further if the module is already installed
852
853     [[ -e "${initdir}/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" ]] \
854         && return 0
855
856     [[ -e "$initdir/.kernelmodseen/${1##*/}" ]] && return 0
857
858     if [[ $omit_drivers ]]; then
859         local _kmod=${1##*/}
860         _kmod=${_kmod%.ko}
861         _kmod=${_kmod/-/_}
862         if [[ "$_kmod" =~ $omit_drivers ]]; then
863             dinfo "Omitting driver $_kmod"
864             return 1
865         fi
866         if [[ "${1##*/lib/modules/$KERNEL_VER/}" =~ $omit_drivers ]]; then
867             dinfo "Omitting driver $_kmod"
868             return 1
869         fi
870     fi
871
872     [ -d "$initdir/.kernelmodseen" ] && \
873         > "$initdir/.kernelmodseen/${1##*/}"
874
875     inst_simple "$1" "/lib/modules/$KERNEL_VER/${1##*/lib/modules/$KERNEL_VER/}" \
876         || return $?
877
878     local _modname=${1##*/} _fwdir _found _fw
879     _modname=${_modname%.ko*}
880     for _fw in $(modinfo -k $KERNEL_VER -F firmware $1 2>/dev/null); do
881         _found=''
882         for _fwdir in $fw_dir; do
883             if [[ -d $_fwdir && -f $_fwdir/$_fw ]]; then
884                 inst_simple "$_fwdir/$_fw" "/lib/firmware/$_fw"
885                 _found=yes
886             fi
887         done
888         if [[ $_found != yes ]]; then
889             if ! grep -qe "\<${_modname//-/_}\>" /proc/modules; then
890                 dinfo "Possible missing firmware \"${_fw}\" for kernel module" \
891                     "\"${_modname}.ko\""
892             else
893                 dwarn "Possible missing firmware \"${_fw}\" for kernel module" \
894                     "\"${_modname}.ko\""
895             fi
896         fi
897     done
898     return 0
899 }
900
901 # Do something with all the dependencies of a kernel module.
902 # Note that kernel modules depend on themselves using the technique we use
903 # $1 = function to call for each dependency we find
904 #      It will be passed the full path to the found kernel module
905 # $2 = module to get dependencies for
906 # rest of args = arguments to modprobe
907 # _fderr specifies FD passed from surrounding scope
908 for_each_kmod_dep() {
909     local _func=$1 _kmod=$2 _cmd _modpath _options _found=0
910     shift 2
911     modprobe "$@" --ignore-install --show-depends $_kmod 2>&${_fderr} | (
912         while read _cmd _modpath _options; do
913             [[ $_cmd = insmod ]] || continue
914             $_func ${_modpath} || exit $?
915             _found=1
916         done
917         [[ $_found -eq 0 ]] && exit 1
918         exit 0
919     )
920 }
921
922 # filter kernel modules to install certain modules that meet specific
923 # requirements.
924 # $1 = search only in subdirectory of /kernel/$1
925 # $2 = function to call with module name to filter.
926 #      This function will be passed the full path to the module to test.
927 # The behavior of this function can vary depending on whether $hostonly is set.
928 # If it is, we will only look at modules that are already in memory.
929 # If it is not, we will look at all kernel modules
930 # This function returns the full filenames of modules that match $1
931 filter_kernel_modules_by_path () (
932     local _modname _filtercmd
933     if ! [[ $hostonly ]]; then
934         _filtercmd='find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra"'
935         _filtercmd+=' "$KERNEL_MODS/weak-updates" -name "*.ko" -o -name "*.ko.gz"'
936         _filtercmd+=' -o -name "*.ko.xz"'
937         _filtercmd+=' 2>/dev/null'
938     else
939         _filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename '
940         _filtercmd+='-k $KERNEL_VER 2>/dev/null'
941     fi
942     for _modname in $(eval $_filtercmd); do
943         case $_modname in
944             *.ko) "$2" "$_modname" && echo "$_modname";;
945             *.ko.gz) gzip -dc "$_modname" > $initdir/$$.ko
946                 $2 $initdir/$$.ko && echo "$_modname"
947                 rm -f $initdir/$$.ko
948                 ;;
949             *.ko.xz) xz -dc "$_modname" > $initdir/$$.ko
950                 $2 $initdir/$$.ko && echo "$_modname"
951                 rm -f $initdir/$$.ko
952                 ;;
953         esac
954     done
955 )
956 find_kernel_modules_by_path () (
957     if ! [[ $hostonly ]]; then
958         find "$KERNEL_MODS/kernel/$1" "$KERNEL_MODS/extra" "$KERNEL_MODS/weak-updates" \
959           -name "*.ko" -o -name "*.ko.gz" -o -name "*.ko.xz" 2>/dev/null
960     else
961         cut -d " " -f 1 </proc/modules \
962         | xargs modinfo -F filename -k $KERNEL_VER 2>/dev/null
963     fi
964 )
965
966 filter_kernel_modules () {
967     filter_kernel_modules_by_path  drivers  "$1"
968 }
969
970 find_kernel_modules () {
971     find_kernel_modules_by_path  drivers
972 }
973
974 # instmods [-c] <kernel module> [<kernel module> ... ]
975 # instmods [-c] <kernel subsystem>
976 # install kernel modules along with all their dependencies.
977 # <kernel subsystem> can be e.g. "=block" or "=drivers/usb/storage"
978 instmods() {
979     [[ $no_kernel = yes ]] && return
980     # called [sub]functions inherit _fderr
981     local _fderr=9
982     local _check=no
983     if [[ $1 = '-c' ]]; then
984         _check=yes
985         shift
986     fi
987
988     function inst1mod() {
989         local _ret=0 _mod="$1"
990         case $_mod in
991             =*)
992                 if [ -f $KERNEL_MODS/modules.${_mod#=} ]; then
993                     ( [[ "$_mpargs" ]] && echo $_mpargs
994                       cat "${KERNEL_MODS}/modules.${_mod#=}" ) \
995                     | instmods
996                 else
997                     ( [[ "$_mpargs" ]] && echo $_mpargs
998                       find "$KERNEL_MODS" -path "*/${_mod#=}/*" -printf '%f\n' ) \
999                     | instmods
1000                 fi
1001                 ;;
1002             --*) _mpargs+=" $_mod" ;;
1003             i2o_scsi) return ;; # Do not load this diagnostic-only module
1004             *)
1005                 _mod=${_mod##*/}
1006                 # if we are already installed, skip this module and go on
1007                 # to the next one.
1008                 [[ -f "$initdir/.kernelmodseen/${_mod%.ko}.ko" ]] && return
1009
1010                 if [[ $omit_drivers ]] && [[ "$1" =~ $omit_drivers ]]; then
1011                     dinfo "Omitting driver ${_mod##$KERNEL_MODS}"
1012                     return
1013                 fi
1014                 # If we are building a host-specific initramfs and this
1015                 # module is not already loaded, move on to the next one.
1016                 [[ $hostonly ]] && ! grep -qe "\<${_mod//-/_}\>" /proc/modules \
1017                     && ! echo $add_drivers | grep -qe "\<${_mod}\>" \
1018                     && return
1019
1020                 # We use '-d' option in modprobe only if modules prefix path
1021                 # differs from default '/'.  This allows us to use Dracut with
1022                 # old version of modprobe which doesn't have '-d' option.
1023                 local _moddirname=${KERNEL_MODS%%/lib/modules/*}
1024                 [[ -n ${_moddirname} ]] && _moddirname="-d ${_moddirname}/"
1025
1026                 # ok, load the module, all its dependencies, and any firmware
1027                 # it may require
1028                 for_each_kmod_dep install_kmod_with_fw $_mod \
1029                     --set-version $KERNEL_VER ${_moddirname} $_mpargs
1030                 ((_ret+=$?))
1031                 ;;
1032         esac
1033         return $_ret
1034     }
1035
1036     function instmods_1() {
1037         local _mod _mpargs
1038         if (($# == 0)); then  # filenames from stdin
1039             while read _mod; do
1040                 inst1mod "${_mod%.ko*}" || {
1041                     if [ "$_check" = "yes" ]; then
1042                         dfatal "Failed to install $_mod"
1043                         return 1
1044                     fi
1045                 }
1046             done
1047         fi
1048         while (($# > 0)); do  # filenames as arguments
1049             inst1mod ${1%.ko*} || {
1050                 if [ "$_check" = "yes" ]; then
1051                     dfatal "Failed to install $1"
1052                     return 1
1053                 fi
1054             }
1055             shift
1056         done
1057         return 0
1058     }
1059
1060     local _ret _filter_not_found='FATAL: Module .* not found.'
1061     set -o pipefail
1062     # Capture all stderr from modprobe to _fderr. We could use {var}>...
1063     # redirections, but that would make dracut require bash4 at least.
1064     eval "( instmods_1 \"\$@\" ) ${_fderr}>&1" \
1065     | while read line; do [[ "$line" =~ $_filter_not_found ]] && echo $line || echo $line >&2 ;done | derror
1066     _ret=$?
1067     set +o pipefail
1068     return $_ret
1069 }
1070
1071 # inst_libdir_file [-n <pattern>] <file> [<file>...]
1072 # Install a <file> located on a lib directory to the initramfs image
1073 # -n <pattern> install non-matching files
1074 inst_libdir_file() {
1075     if [[ "$1" == "-n" ]]; then
1076         local _pattern=$1
1077         shift 2
1078         for _dir in $libdirs; do
1079             for _i in "$@"; do
1080                 for _f in "$_dir"/$_i; do
1081                     [[ "$_i" =~ $_pattern ]] || continue
1082                     [[ -e "$_i" ]] && dracut_install "$_i"
1083                 done
1084             done
1085         done
1086     else
1087         for _dir in $libdirs; do
1088             for _i in "$@"; do
1089                 for _f in "$_dir"/$_i; do
1090                     [[ -e "$_f" ]] && dracut_install "$_f"
1091                 done
1092             done
1093         done
1094     fi
1095 }
1096
1097 check_nspawn() {
1098     [[ -d /sys/fs/cgroup/systemd ]]
1099 }
1100
1101
1102 do_test() {
1103     if [[ $UID != "0" ]]; then
1104         echo "TEST: $TEST_DESCRIPTION [SKIPPED]: not root" >&2
1105         exit 0
1106     fi
1107
1108 # Detect lib paths
1109     [[ $libdir ]] || for libdir in /lib64 /lib; do
1110         [[ -d $libdir ]] && libdirs+=" $libdir" && break
1111     done
1112
1113     [[ $usrlibdir ]] || for usrlibdir in /usr/lib64 /usr/lib; do
1114         [[ -d $usrlibdir ]] && libdirs+=" $usrlibdir" && break
1115     done
1116
1117     import_testdir
1118     import_initdir
1119
1120     while (($# > 0)); do
1121         case $1 in
1122             --run)
1123                 echo "TEST RUN: $TEST_DESCRIPTION"
1124                 test_run
1125                 ret=$?
1126                 if [ $ret -eq 0 ]; then
1127                     echo "TEST RUN: $TEST_DESCRIPTION [OK]"
1128                 else
1129                     echo "TEST RUN: $TEST_DESCRIPTION [FAILED]"
1130                 fi
1131                 exit $ret;;
1132             --setup)
1133                 echo "TEST SETUP: $TEST_DESCRIPTION"
1134                 test_setup
1135                 exit $?;;
1136             --clean)
1137                 echo "TEST CLEANUP: $TEST_DESCRIPTION"
1138                 test_cleanup
1139                 rm -fr "$TESTDIR"
1140                 rm -f .testdir
1141                 exit $?;;
1142             --all)
1143                 echo -n "TEST: $TEST_DESCRIPTION ";
1144                 (
1145                     test_setup && test_run
1146                     ret=$?
1147                     test_cleanup
1148                     rm -fr "$TESTDIR"
1149                     rm -f .testdir
1150                     exit $ret
1151                 ) </dev/null >test.log 2>&1
1152                 ret=$?
1153                 if [ $ret -eq 0 ]; then
1154                     rm test.log
1155                     echo "[OK]"
1156                 else
1157                     echo "[FAILED]"
1158                     echo "see $(pwd)/test.log"
1159                 fi
1160                 exit $ret;;
1161             *) break ;;
1162         esac
1163         shift
1164     done
1165 }