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