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