GithubHelp home page GithubHelp logo

osboot / make-initrd Goto Github PK

View Code? Open in Web Editor NEW
25.0 6.0 12.0 3.38 MB

Creates an initramfs image

License: GNU General Public License v3.0

Makefile 7.49% Shell 52.71% C 35.79% M4 1.19% Yacc 2.55% Lex 0.29%
initramfs-image creating-initramfs initrd dracut zfs

make-initrd's Introduction

make-initrd

make-initrd is a new, uevent-driven initramfs infrastructure based around udev.

The make-initrd is intended for creating initramfs images. The project consists of two main parts:

  • Utilities for initramfs image creation (this includes determining the kernel modules required for the current hardware, adding required utilities, etc).
  • Utilities that run inside the initramfs image at boot time.

The project has a modular structure. Its main idea is that to create the image you need (in the simplest case) to specify a list of characteristics (features) of the future image. The order of features does not matter. The user is not required to know how and in what order will apply stage.

Documentation

Documentation about the project is located in the Documentation directory or on the wiki where the information is collected in one place.

Build Requires

To build a initramfs, you have to install the following software packages:

  • gnu make is used to generate an initramfs image. This is a small but very powerful utility.
  • bash is needed for all scripts in the project. This allows for increased portability from one distribution to another.
  • busybox is used in the initramfs as runtime (submodule). This allows for increased portability from one distribution to another.
  • libshell is used both when generating the image and in the initramfs (submodule).
  • Utilities from coreutils are used in the initramfs image generation scripts.
  • kmod is needed to calculate dependencies and load kernel modules in the initramfs.
  • elfutils is optional but highly desirable for proper operation. This library is used to calculate the dependencies of binary utilities that are copied into the initramfs image.
  • json-c is needed to get dependencies from ELF DLOPEN Medatata. The systemd-256 switched to dynamic loading of libraries that the authors consider optional.
  • Compression libraries are required for the initramfs image parsing utilities: zlib, bzip2, xz, zstd.
  • scdoc is used to generate man-pages.

Build

$ ./autogen.sh
$ ./configure
$ make
$ make install DESTDIR=/path/to/somewhere

If you want to use it in-tree:

$ ./configure --enable-local-build
$ make

License

Make-initrd is licensed under the GNU General Public License (GPL), version 3.

make-initrd's People

Contributors

antohami avatar beefdeadbeef avatar blarse avatar boyarsh avatar glebfm avatar kiryl avatar klark973 avatar lakostis avatar laszlogombos avatar legionus avatar lo1ol avatar mc-pain avatar obirvalger avatar ptrnine avatar raorn avatar realnickel avatar shaba avatar wladmis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

make-initrd's Issues

Add zfs support

The zfs filesystem is very flexible and feature rich.

  • Add zfs support into kickstart feature to be able to partition with zfs.
  • Add guess feature to detect the zfs filesystem.
  • Add zfs initialization at runtime.
  • Add tests for zfs.
  • Add documentation.

Support for live environments

Hey there,

This project looks promising, and I was wondering if it actually supported booting in live environments (e.g. ISOs on CDs or USBs)?

I was also wondering if there is support for overlayfs and squashfs for compressed rootfs.

/sbin/init -- ссылка на файл внутри оригинального корня

Не учтен случай, когда /sbin/init -- ссылка.

[ -e "$rootmnt/$INIT" ] ||

Столкнулся с проблемой загрузки на Ubuntu 20.04: [ -e /sbin/init ] возвращает ошибку, что файл не существует. Проблема была в том, что /sbin/init является ссылкой на элемент внутри оригинального корня (/lib/systemd/systemd). Флаг -e для команды test проверяет наличие файла по разыменованной ссылке, но такого файла до монтирования корня не существует.

Проблему можно решить путем изменения строчки на

[ -e /sbin/init ] || [ -h /sbin/init ]

Ну Ubuntu 20.04 после таких изменений загрузиться удалось) Не тестировал работоспособность различных фич, но запуск системы в целом -- это кул!

Не могу добавить модули в alt linux вне /kernel/

make-initrd не находит модули nvidia, которые находятся в /lib/modules//nVidia/

Если я помещу эти модули в /lib/modules/<kernel>/kernel/
они обнаруживаются.

Я использовал MODULES_LOAD, MODULES_ADD и MODULES_TRY_ADD

Я не совсем уверен проблема это или нет.
Так и задумано, что модули берутся только в папке /lib/modules/<kernel>/kernel/ (либо, по крайней мере не во всех каталогах)?

Сохранение ссылок на дирректории

Теперь перешел на Red Os 7.3. При тестировании make-initd там обнаружил, что утилита не всегда сохраняет символические ссылки на директории. Например, вместо того, чтобы создавать ссылки lib -> /usr/lib, создается директория /lib.

Это не совсем корректное поведение т.к. пути до некоторых файлов в скриптах могут содержать через такие символические ссылки.

Вот как я решил проблему, чтобы образ initrd собирался корректно:

  1. перенес создание основных директорий (bin, lib, usr) в скрипте make-initrd ближе к концу. Они создадутся, только если не были созданы до этого. Будем считать, что до этого они создавались с правильной структурой. Вышло так:
mkdir $verbose -p -- \
	./{,usr/}{,s}bin \
	./.initrd/{killall,uevent/events,uevent/queues/udev/.tmp} \
	./etc/{{initrd,modprobe.d,sysconfig},udev/rules.d} \
	./lib/{udev,initrd/{all,kmodules,post,pre}} \
	./var/{lock/subsys,log,run} \
	./{home/root,dev,mnt,root,run,proc,sys,tmp,bin,sbin} \
	./"$KERNEL_MODULES_DIR" \
	#

for d in lib etc; do
	if [ -d "/$d/modprobe.d" ]; then
		verbose "Copying files from $d/modprobe.d ..."
		find -L "/$d/modprobe.d" \
				-name '*.conf' \
			-exec cp -aLt ./etc/modprobe.d -- '{}' '+'
	fi

	if [ -d "/$d/udev/initramfs-rules.d" ]; then
		verbose "Copying files from /$d/udev/initramfs-rules.d ..."
		find -L "/$d/udev/initramfs-rules.d" \
				-name '*.rules' \
			-exec cp -aLt ./etc/udev/rules.d -- '{}' '+'
	fi
done
  1. Поменял местами запуск put-files и put-tree. Это конечно скорее костыль, чем решение: put-tree должен сохранять структуру директорий, но почему-то этого не происходит. Вышло вот так:
printf '%s\n' "${FILES[@]}"      |xargs -r put-file .
printf '%s\n' "${LOCALFILES[@]}" |xargs -r put-file -r "$LOCALBUILDDIR" .
printf '%s\n' "${DIRS[@]}"       |xargs -r put-tree .
  1. Дальше по мелочи:
mkdir /.initrd
mkfifo ./.initrd/telinit
mkfifo ./.initrd/rdshell

...

[ ".$BASH"    = ./bin/bash     ] || ln $verbose -s -- "$BASH"    ./bin/bash || :
[ ".$UDEVD"   = ./sbin/udevd   ] || ln $verbose -s -- "$UDEVD"   ./sbin/udevd || :
[ ".$UDEVADM" = ./sbin/udevadm ] || ln $verbose -s -- "$UDEVADM" ./sbin/udevadm || :

После этих изменений на red os все запустилось без проблем и структура директорий сохранилась:
image

Errors are ignored when copying files to initramfs

The put-file in rules.mk ignores errors: some files were missing and did not end up in the initrd, which is why the system did not work correctly.

$ initrd-put /tmp/root /something/missing
initrd-put: unable to process component of path: /something: No such file or directory

$ echo $?
0

опции монтирования ro,loop срабатывают наоборот для фичи pipeline

Сейчас тестирую свою фичу pipeline на Red OS. Обнаружил, что здесь установка опций перепутана:

opts=
[ ! -c "$target" ] && [ ! -b "$target" ] ||
opts='ro,loop'

Опции устанавливаются для реальных устройств, но не устанавливаются для файлов. Чтобы корректно работало, кажется должно быть так:

opts=
[ -c "$target" ] || [ -b "$target" ] ||
	opts='ro,loop'

Также еще столкнулся с такой проблемой, что при погрузки зависимостей фичи plymoyth выгружается конкретный шрифт из конкретной директории:

$(DATADIR)/fonts/ttf/dejavu/DejaVuSans.ttf \

в дистрибутиве Red OS этот шрифт располагается здесь $(DATADIR)/fonts/dejavu/DejaVuSans.ttf . Почему именно такой шрифт выгружается? Можно ли как-то определить какой точно шрифт используется и путь до него?

Извините, что я создаю обращения через issue, а не MR. Если вам будет удобнее, могу MR создавать. Просто мне кажется, что раз вы так хорошо знаете тонкости make-initrd вам будет проще самому правки сделать, чем объяснять мне, как надо)

Некорректное определение абсолютных символических ссылок

В этом месте не учитывается то, что ссылка может быть абсолютным путем:

static void canonicalize_symlink(char *file, char *target, char *d)
{
char pathbuf[PATH_MAX + 1];
char *p;
if (verbose > 2)
warnx("canonicalize_symlink: %s", file);
strncpy(pathbuf, file, sizeof(pathbuf) - 1);
if ((p = strrchr(pathbuf, '/'))) {
p++;
*p = 0;
}
strncat(pathbuf, target, sizeof(pathbuf) - 1 - strlen(pathbuf));
canonicalize_path(pathbuf, d);
}

Проблему можно решить так:

static void canonicalize_symlink(char *file, char *target, char *d)
{
	char pathbuf[PATH_MAX + 1];
	char *p;

	if (verbose > 2)
		warnx("canonicalize_symlink: %s", file);
        
        if (target && target[0] == '/') {
                strcpy(d, target);
                return;
        }
        
	strncpy(pathbuf, file, sizeof(pathbuf) - 1);
	if ((p = strrchr(pathbuf, '/'))) {
		p++;
		*p = 0;
	}
	strncat(pathbuf, target, sizeof(pathbuf) - 1 - strlen(pathbuf));

	canonicalize_path(pathbuf, d);
}

Словил проблему при запуске make-initrd на Ubuntu 20.04 вызванную этой багой

Фича pipeline содержит ошибки при работе с параметром waitdev

Добрый день,

Мы недавно реализовывали загрузку системы с ro устройств и обнаружили небольшие недочеты при работе с параметром waitdev.

  1. В этом месте функция get_dev иногда возвращает пустую строку в dev, но при этом возвращенное значение функции 0:
    [ -z "$spec" ] ||
    get_dev dev "$spec" ||:
    eval "export WAITDEV_FILE$WAITDEV_FILE=\"\$dev\""

    Таким образом я бы добавил дополнительную проверку на наличие непустой dev строки:
	[ -z "$spec" ] ||
		get_dev dev "$spec" ||: [ -z "$dev" ] ||
	eval "export WAITDEV_FILE$WAITDEV_FILE=\"\$dev\""
  1. Файл /.initrd/pipeline/waitdev постоянно перезаписывается:
    environ -q -i 'WAITDEV_FILE*' >waitdev.env
    mv -f -- waitdev.env waitdev

    Таким образом построение оверлея над несколькими устройствами не возможно. Я бы переписал эту часть вот так:
environ -q -i 'WAITDEV_FILE*' >> waitdev

При таком подходе хоть в файл и записывается несколько раз значение WAITDEV_FILE , оно остается всегда постоянным и при выполнении команды source над этим файлом это не помешает его прочитать. Также стоит учесть возможный момент одновременного записывания в файл, но он возможен и при текущей реализации (в файл waitdev.env). Также у меня есть ощущение, что при перенаправлении потоков с помощью >> будут перемешиваться только строки, что тоже нас устраивает

После этих изменений загрузка с ro раздела происходила успешно.

  1. Также у меня была небольшая проблема при работе с устройствами, на которых изначально скрыты разделы. udevadm не возвращал для таких устройств переменные ID_FS_UUID, ID_FS_LABEL, ID_PART_ENTRY_UUID и ID_PART_ENTRY_NAME, но зато для них была установлена переменная ID_SERIAL, можно ли добавить в существующую реализацию функции get_dev получения устройства по переменной SERIAL?

Universal initrd

Hello.
I want to make an universal initrd for ALT Linux on a USB SSD drive which would be able to boot on any hardware. That is what dracut is able to make. I could not find anything like that in make-initrd. Does such a mode exist?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.