Make-initrd development discussion
 help / color / mirror / Atom feed
From: Leonid Krivoshein <klark.devel@gmail.com>
To: make-initrd@lists.altlinux.org
Subject: Re: [make-initrd] [PATCH v1 00/41] fork pipeline
Date: Wed, 13 Oct 2021 20:06:02 +0300
Message-ID: <933e0f96-35e5-afb5-80f1-6353d6973ca7@gmail.com> (raw)
In-Reply-To: <20210927135518.gnskejf4ga2izljb@example.org>

[-- Attachment #1: Type: text/plain, Size: 1162 bytes --]

Алексей, привет!


27.09.2021 16:55, Alexey Gladkov пишет:
> On Mon, Sep 27, 2021 at 04:17:38PM +0300, Leonid Krivoshein wrote:
>> [...] Чтобы не тратить зря твоё время,
>> Антон предложил пропустить сначала через него, поскольку опыт с ним сам
>> говоришь, положительный.
> Если он не против, то я за )))

Извини за задержку. Долго болел, решали вопросы с логическим разделением 
на коммиты и занимались README с переводами. Перевод на английский 
сделал Максим Князев, его можно взять за основу, чтобы тебе меньше 
работы было, но я не уверен в корректности перевода и пока не знаю, как 
учесть его участие. Прилагаю финальные варианты README, а коммиты зашлю 
следующими письмами.



-- 
Best regards,
Leonid Krivoshein.


[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: README.ru.utf8.md --]
[-- Type: text/markdown; name="README.ru.utf8.md", Size: 24595 bytes --]

# Фича: bootchain-core

`bootchain-core` - форк и дальнейшее развитие оригинальной фичи `pipeline`.
Производная фича, равно как и `pipeline`, последовательно запускает шаги-скрипты
один за другим. Подробности про `pipeline` см. в ../features/pipeline/README.md.

В процессе форка фича `pipeline` была разделена на три части:

- `bootchain-core` - основной функционал фичи `pipeline`, общий код и демон.
- `bootchain-getimage` - метод загрузки ISO-образов по сети утилитой wget.
- `bootchain-waitdev` - метод загрузки с указанных локальных носителей.

Дальнейшая работа над `bootchain` привела к созданию ещё нескольких модулей.
Их перенос в апстрим ожидается в ближайшее время. Такое разделение на модули
позволяет оптимизировать наполнение образа initramfs только необходимым.

## Основные компоненты bootchain-core

- `/bin/bootchain-sh-functions` - общий код, развитие `pipeline-sh-functions`.
- `/sbin/bootchained` - демон, развитие `pipelined`, перезапускаемый процесс.
- `/sbin/bootchain-logvt` - скрипт управления вспомогательным терминалом.
- `/etc/rc.d/init.d/bootchain` - стартовый скрипт sysvinit.

## Причины создания форка и переименования pipeline

- Набор модулей `bootchain` разрабатывался с целью создать в stage1 замену
  программы `propagator`, полностью интегрированную в run-time `make-initrd`.
  В исходном варианте фича `pipeline` не удовлетворяла названной потребности.
  На раннем этапе разработки ещё не было известно, какой функционал окажется
  в конечном итоге у `bootchain`, насколько далеко он уйдёт от форка и сможет
  ли быть с ним полностью совместимым.
- Некоторое время разработка `bootchain` велась независимо от основного проекта
  `make-initrd`. Чтобы собирать и тестировать загрузочные диски с `make-initrd`
  и `bootchain`, чтобы `bootchain` не зависел от версий `make-initrd`, чтобы не
  пересекаться со встроенной в `make-initrd` фичей `pipeline` и чтобы не мешать
  автору `make-initrd`, фичу `pipeline` пришлось скопировать под другим именем,
  дав ей заодно более подходящее название.
- Не всегда результат пройденного шага используется следующим. Шаги-скрипты
  могут использовать результаты не только предыдущего, но и любого ранее
  пройденного шага. Так что это не конвейер в чистом виде, а скорее цепочка
  шагов загрузки, последовательность выполняемых действий.

## Отличия от оригинального pipeline

- Модульность: методы загрузки изначально отделены от общего кода и демона.
- Обеспечена возможность переводить демон на передний план в любое время.
  При этом происходит перезапуск процесса `bootchained` на конкретном
  терминале, хотя изначально демон запускается в фоновом режиме.
- Некоторые шаги (действия) встроены непосредственно в код главного цикла
  демона `bootchained`, внешние скрипты для их выполнения не вызываются.
  Такие псевдо-шаги позволяют управлять, в основном, внутренним состоянием
  демона и не должны учитываться в загрузочной цепочке, как будто они скрыты.
- Опционально демон может работать совместно с фичей `bootchain-interactive`,
  может перейти на передний план и продолжить работать на конкретном терминале,
  по умолчанию tty2. Совместно фичи `bootchain-core` и `bootchain-interactive`
  закладывают основу для построения простых текстовых инсталляторов в stage1.
- Демон `bootchianed` позволяет перегружать цепочку новым набором шагов,
  благодаря чему можно менять логику работы "на лету", поддерживать циклы и
  условные переходы, в текстовых диалогах это возможность возвращаться назад.
- Ведёт учёт хотя бы один раз пройденных шагов и позволяет предотвращать их
  повторный запуск.
- `bootchain-sh-functions` расширяет API оригинального `pipeline-sh-functions`,
  см. детали в соответствующем разделе.
- Через resolve_target() поддерживает не только прямую, но и обратную адресацию,
  относительно текущего шага. Например, запись вида `step-3/dir1/dev` обработает
  результат `dir1/dev`, сделанный на третьем шаге от текущего. Совместно с
  перегрузкой цепочки шагов прямая адресация безопасна только при сохранении
  номеров пройденных шагов в файлы, тогда как обратная относительная адресация
  безопасна в любом случае и зачастую может оказаться удобней.
- Позволяет работать с более короткими и привычными путями к специальным файлам
  устройств благодаря использованию `DEVNAME` наряду с `dev`.
- Предоставляет возможность связывать <ВХОД> шага с <ВЫХОДОМ> предыдущего шага
  через символические ссылки на точки монтирования внутри initramfs, вне дерева
  результатов шагов, что обеспечивает, при необходимости, механизм монтирования
  внахлёст, свойственный программе `propagator`.
- Наряду с РОДНЫМ режимом работы, демон `bootchianed` может работать в режиме
  СОВМЕСТИМОСТИ с `pipeline`. В РОДНОМ режиме работы демон навязывает другой
  подход к обработке кода состояния завершённого шага и способу преждевременного
  завершения загрузочной цепочки, см. детали в соответствующем разделе.
- Демон может быть сконфигурирован при сборке initramfs через включаемый файл
  конфигурации `/etc/sysconfig/bootchain`, а не только через параметры загрузки,
  см. детали в соответствующем разделе.
- Демон `bootchianed` предлагает наглядную и расширенную отладку. По умолчанию
  журнал ведётся в `/var/log/bootchained.log` и доступен на tty3, а при включении
  расширенной отладки или функции самотестирования также копируется в stage2.
  Служебный шаг-скрипт `debug` в режиме расширенной отладки запускается перед
  запуском любого другого шага-скрипта и позволяет наглядно отследить получаемые
  значения на каждом <ВХОДЕ>.

Несмотря на отличия, `bootchained` обратно совместим с ранее написанными шагами
для демона `pipelined` и не требует изменений для конфигураций с `root=pipeline`.

## Особенности работы демона pipelined

Если скрипт шага завершится кодом состояния 2, оригинальный демон `pipelined`
воспримет это как необходимость прервать цепочку и прекратить работу, полагая,
что система готова к переходу в stage2. Если скрипт шага не обработает данный
код от внешней команды, а stage2 окажется ещё не готов к работе, возникнет
ситуация с преждевременным завершением демона.

Если шаг-скрипт завершится ненулевым кодом состояния, отличным от 2, демон
`pipelined` воспримет это как сбой и будет повторять зафейлившийся шаг с паузой
в одну секунду в бесконечном цикле (до истечения общего таймаута rootdelay=180).
Но зачастую повторять шаги бесполезно, поскольку ситуация неисправима, повтор
приводит лишь к ненужному ожиданию и разрастанию записей в журнале. Однако
демон `pipelined` не знает, как обрабатывать такие ситуации.

## Новый подход в демоне bootchained

Шагам-скриптам предлагается перед завершением с кодом состояния 0 вызвать
break_bc_loop(), чтобы сообщить демону о готовности stage2 и необходимости
завершить работу демона сразу после текущего шага. В случае сбоя в скрипте шага
демон может его повторять, но не более четырёх раз с паузой в две секунды. Чтобы
сбой в скрипте шага приводил к немедленному завершению работы демона, необходимо
использовать внутренний шаг `noretry`.

## Режимы работы демона

### РОДНОЙ режим работы

РОДНОЙ режим активируется параметром `root=bootchain`. В этом режиме демон будет
воспринимать код состояния 2 от скрипта шага так же, как и любой другой ненулевой
код и далее действовать согласно внутреннему состоянию: если повторы разрешены,
скрипт шага будет вызван повторно с паузой в 2 секунды, но не более четырёх раз.
Если же повторы запрещены, демон сам немедленно завершится.

### Режим СОВМЕСТИМОСТИ с pipeline

Режим СОВМЕСТИМОСТИ активируется параметром `root=pipeline`. В этом режиме демон
ведёт себя так же, как и оригинальный `pipelined`, разве что ограничивает число
повторных запусков зафейлившегося шага. Он воспринимает код состояния 2 не как
сбой, а как команду завершить главный цикл демона.

## Конфигурация

Конфигурация определяется в файле `/etc/sysconfig/bootchain` при сборке образа
initramfs, необязательна и может содержать следующие параметры:

- `BC_LOG_VT` - номер виртуального терминала, на который в фоновом режиме должен
  выводиться отладочный журнал. По умолчанию значение равно 3, соответственно
  журнал выводится на tty3. Пустое значение позволяет отключить вывод журнала
  на какой-либо терминал.
- `BC_FGVT_ACTIVATE` - задержка в секуднах перед активацией интерактивного
  терминала, по умолчанию tty2 активируется через 2 секунды в режиме отладки
  или через 8 секунд в обычном режиме. Пустое значение предписывает активировать
  интерактивный терминал немедленно. Данная опция конфигурации работает только
  вместе с включенной в initramfs фичей `bootchain-interactive`.
- `BC_LOGFILE` - полный путь к файлу журнала либо имя специального устройства,
  на который будут выводиться отладочные сообщения. В РОДНОМ режиме значение по
  умолчанию равно `/var/log/bootchained.log`, в режиме СОВМЕСТИМОСТИ с `pipeline`
  значение по умолчанию равно `/var/log/pipelined.log`.
- `mntdir` - где создавать подкаталоги шагов загрузочной цепочки. В РОДНОМ
  режиме значение по умолчанию равно `/dev/bootchain`, в режиме СОВМЕСТИМОСТИ
  с `pipeline` значение по умолчанию равно `/dev/pipeline`.

Другие модули `bootchain-*` также могут использовать этот файл конфигурации для
собственных потребностей.

## Встроенные псевдо-шаги

Все ниже перечисленные шаги являются расширением `pipeline`. Они встроены в код
главного цикла демона `bootchained`, не нуждаются в дополнительных параметрах и
не должны учитываться при адресации, как будто они скрыты.

- `fg` - обеспечивает перевод демона в интерактивный режим при сборке initramfs
  с фичей `bootchain-interactive`. Самому `bootchain-core` интерактивность не
  требуется, но в ней могут нуждаться некоторые другие шаги, такие как `altboot`.
- `noop` - не выполняет никаких действий и предназначен для отрыва результатов на
  <ВЫХОДЕ> предыдущего шага от <ВХОДА> следующего шага, что может быть полезно,
  например, когда мы не хотим, чтобы результаты шага `waitdev` были использованы
  в следующем шаге `localdev`, который в первую очередь смотрит именно на них.
- `noretry` - запрещает следующим шагам завершаться с ненулевым кодом возврата,
  что приведёт к немедленному завершению работы демона в случае сбоя в скрипте
  любого следующего шага. По умолчанию шагам разрешено фейлиться, демон будет
  пытаться перезапускать их повторно четыре раза с паузой в две секунды.
- `retry` - разрешает всем последующим шагам завершаться с ненулевым кодом
  возврата, что приведёт к их пятикратному запуску, в общей сложности. Такой
  режим работы демона действует по умолчанию.

## Внешние элементы загрузочной цепочки (шаги-скрипты)

- `mountfs` - монтирует файл или устройство из результата предыдущего либо
  другого указанного шага.
- `overlayfs` - объединяет один или несколько элементов загрузочной цепочки
  с помощью overlayfs.
- `rootfs` - заставляет демон использовать результат предыдущего элемента как
  найденный корень stage2.

## Параметры загрузки

- `bootchain=name1[,name2][,name3]` - определяет начальное состояние загрузочной
  цепочки, т.е. шаги, которые должен пройти демон один за другим. Это могут быть
  как встроенные псевдо-шаги, так и реальные скрипты выполняемых действий. Имена
  этих шагов перечисляются через запятую.
- `pipeline=name1[,name2][,name3]` - синоним для `bootchain=...`.
- `mountfs=target` - определяет монтируемый файл или устройство.
- `overlayfs=list` - определяет список элементов для объединения.
- `bc_debug` - булевый параметр, включающий расширенную отладку и заставляющий
  в случае успешного завершения демона скопировать журнал загрузки в stage2.
- `bc_test=name` - определяет название текущего тест-кейса в процессе полностью
  автоматизированного самотестирования, заставляющий в случае успешного
  завершения демона скопировать журнал загрузки в stage2 и рядом с ним
  создать файл BC-TEST.passed с указанным названием тест-кейса.

## Расширенное API bootchain-sh-functions

- check_parameter() - проверяет, чтобы обязательный параметр был не пуст,
  иначе завершает работу через fatal().
- get_parameter() - вывод значения параметра текущего шага по индексу $callnum.
- resolve_target() - вывод пути к файлу, каталогу или устройству, в зависимости
  от параметра.
- resolve_devname() - вывод пути к специальному файлу устройства по указанному
  каталогу. Обычно каталог шага содержит файл DEVNAME или dev, если устройство
  было результатом шага, тогда функция вернёт читаемый `/dev/узел`.
- debug() - вывод текстового сообщения при расширенной отладке.
- enter() - трассировка при расширенной отладке: вход в указанную функцию.
- leave() - трассировка при расширенной отладке: выход из указанной функции.
- run() - запуск внешней команды. При расширенной отладке выполняемая команда
  попадёт в журнал.
- fdump() - вывод содержимого указанного файла при расширенной отладке.
- assign() - присвоение переменной указанного значения, попадающее в журнал
  при расширенной отладке. Левостороннее выражение также является вычисляемым.
- next_bootchain() - команда демону на смену последовательности следующих шагов.
- is_step_passed() - возвращает 0, если текущий шаг был пройден хотя бы один раз.
- launch_step_once() - если текущий шаг уже был пройден, завершает работу через
  вызов fatal().
- break_bc_loop() - сообщает демону о том, что текущий шаг последний и после
  его успешного завершения можно переходить в stage2. Скрипт этого шага, тем
  не менее, должен отработать до конца и завершиться с нулевым кодом состояния,
  чтобы демон обработал полученный сигнал.
- bc_reboot() - выполняет журналируемый перезапуск компьютера.
- bypass_results() - просит демон связать <ВЫХОД> предыдущего шага со <ВХОДОМ>
  следующего шага. Также используется для сообщения демону о результате
  (смонтированном каталоге) внутри текущего корня initramfs, вне дерева $mntdir.
- initrd_version() - вывод текущей версии make-initrd. Предлагается перенести
  в make-initrd/data/bin/initrd-sh-functions вслед за has_module().

## Примеры

Cmdline: root=bootchain bootchain=waitdev,mountfs,mountfs,overlayfs,rootfs waitdev=CDROM:LABEL=ALT_regular-rescue/x86_64 mountfs=DEVNANE mountfs=rescue

Следуя этим параметрам, демон дожидается локального устройства с файловой
системой ISO-9660 и меткой тома "ALT_regular-rescue/x86_64", монтирует этот
носитель, монтирует с него файл "rescue" как squashfs корневой системы, делает
его доступным для записи с помощью overlayfs и пытается загрузиться с него.

Cmdline: root=pipeline pipeline=getimage,mountfs,overlayfs,rootfs getimage=http://ftp.altlinux.org/pub/people/mike/iso/misc/vi-20140918-i586.iso mountfs=rescue

Следуя этим параметрам, демон загружает образ "vi-20140918-i586.iso", монтирует
его через устройство loop, монтирует с него файл "rescue" как squashfs корневой
системы, делает его доступным для записи с помощью overlayfs и пытается
загрузиться с него.

[-- Attachment #3: README.md --]
[-- Type: text/markdown, Size: 15340 bytes --]

# Feature: bootchain-core

`bootchain-core` - it's a fork and further development the original
feature of `pipeline`. This feature allow us to consistently setup
steps-scripts one by one. For details about `pipeline` you can see
in ../features/pipeline/README.md.

In fork process `pipeline` was divided by three parts:

- `bootchain-core` - the main functional of feature `pipeline`, common
  API and daemon.
- `bootchain-getimage` - method to networking boot from ISO-image with
  the wget utility.
- `bootchain-waitdev` - method to boot from specified local media.

The future work with `bootchain` allowed us to create a few modules.
They are expected to be upstream soon. This divide on modules allow
us to optimize fill in `initramfs` only which we are need.

## Main components of bootchain-core

- `/bin/bootchain-sh-functions` - common API and evolution
  of `pipeline-sh-functions`.
- `/sbin/bootchained` - daemon, evolution of `pipelined`.
- `/sbin/bootchain-logvt` - script which allow to control sub terminal.
- `/etc/rc.d/init.d/bootchain` - sysvinit start script.

## Reasons of making fork and rename pipeline

- A set of `bootchain` modules was developed in order to create a
  replacement in stage1 programs `propagator`, fully integrated into
  the run-time `make-initrd`. In the original version, the `pipeline`
  feature did not satisfy this need. At an early stage of development,
  it was not yet known what functionality `bootchain` would eventually
  have, how far it would go from the fork and be able to whether to be
  fully compatible with it.
- For some time, the development of `bootchain` was carried out independently
  of the main project `make-initrd`. To build and test bootable disks with
  `make-initrd` and `bootchain` so that `bootchain` does not depend on
  `make-initrd` versions, so that not intersect with the `pipeline` features
  built into the `make-initrd` and so as not to interfere the author of
  `make-initrd`, the `pipeline` feature had to be copied under a different
  name, giving it a more appropriate name at the same time.
- The result of the completed step is not always used next. Steps-scripts
  they can use the results not only of the previous one, but also of any
  earlier one the completed step. So it's not a pipeline in its purest
  form, but rather a chain loading steps, the sequence of actions performed.

## Defference from the original pipeline

- Modularity: loading methods are initially separated from the common
  code and daemon.
- The main loop of the `bootchain-loop` daemon is separated from the
  `bootchained` daemon code, which provides the ability to bring the daemon
  to the foreground at any time. In fact, this restarts the `bootchain-loop`
  process on a specific terminal, although initially the daemon runs this
  process in the background.
- Some steps (actions) are built directly into the code of the main loop
  of the `bootchain-loop` daemon, external scripts are not called to execute
  them. Such pseudo-steps allow you to control, basically, the internal state
  of the daemon and should not be taken into account in the boot chain, as if
  they are hidden.
- Optionally, the daemon can work in conjunction with the `bootchain-interactive`
  feature, can move to the foreground and continue working on a specific terminal,
  by default, tty2. Jointly features `bootchain-core` and `bootchain-interactive`
  they lay the foundation for building simple text installers in stage1.
- The `bootchianed` daemon allows you to overload the chain with a new set of
  steps, thanks to this, you can change the logic of work "on the fly", support
  loops and conditional jumps, in text dialogs it is an opportunity to go back.
- Keeps records of the steps taken at least once and allows you to prevent their
  re-launch.
- `bootchain-sh-functions` extends the API of the original `pipeline-sh-functions`,
  see the details in the corresponding section.
- Via resolve_target() supports not only forward, but also reverse addressing,
  relative to the current step. For example, a record like `step-3/dir1/dev`
  will process the result of `dir1/dev`, made in the third step from the current
  one. Together with the overload of the chain of steps, direct addressing is safe
  only when storing the numbers of the completed steps in files, whereas reverse
  relative addressing it is safe in any case and can often be more convenient.
- Allows you to work with shorter and more familiar paths to special files
  devices thanks to the use of `DEVNAME` along with `dev`.
- Provides the ability to associate the <IN> of a step with the <OUT>
  of the previous step through symbolic links to mount points inside initramfs,
  outside the tree the results of the steps, which provides, if necessary, the
  overlap mounting mechanism inherent in the program `propagator`.
- Along with the NATIVE mode of operation, the `bootchianed` daemon can work
  in COMPATIBILITY WITH `pipeline`. In the NATIVE mode of operation, the daemon
  imposes another an approach to processing the status code of the completed
  step and the method of premature completion of the boot chain, see the details
  in the corresponding section.
- The daemon can be configured when building initramfs via the included file
  configurations of `/etc/sysconfig/bootchain`, and not only through boot
  parameters, see the details in the corresponding section.
- The `bootchianed` daemon offers visual and advanced debugging. By default,
  the log is kept in `/var/log/bootchained.log` and is available on tty3,
  and when enabled advanced debugging or self-testing functions are also copied
  to stage2. Service step-the `debug` script in advanced debugging mode is run
  before by launching any other step-script and allows you to visually track
  the received values at each <IN>.

Despite the differences, `bootchained` is backward compatible with previously
written steps for the `pipelined` daemon and does not require changes for
configurations with `root=pipeline`.

## Features of the pipelined work

If the step-script will be finished with code of status 2, the original daemon
`pipelined` will understand it like a must to stop chains and finish work.
(meaning that system is ready to go stage2). If the step-script does not
process this code from an external command, and stage2 is not ready to work
yet, a situation with premature termination of the daemon will arise.

If the step-script will be finished with non-null code of status (different
from 2), daemon `pipelined` will understand it like a fail and will repeat this
failure-step with pause in one second in infinity cycle (until common timeout
rootdelay=180). But, sometimes repeat steps are unnecessary because the
situation is incorrigible and repeating will just waste of time and make a
system log is filling up. But the daemon `pipelined` don't know how to work
with this situations.

## New approach in bootchained daemon

For steps-scripts are suggested before finish work with code of status 0 call
break_bc_loop() for tell to the daemon about ready stage2 and needed finish
work this daemon after the current step.In case of a failure in the step-by-step
scenario, the daemon can repeat it, but no more than four times with a pause of
two seconds. In order for a failure in the step-by-step scenario to lead to an
immediate shutdown of the daemon, it is necessary to use the internal step
`noretry`.

## Daemon operation mode

### NATIVE mode of operation

NATIVE mode is activated by the `root=bootchain` parameter. In this mode, the
daemon will perceive the status code 2 from the step script in the same way as
any other non-zero code and then act according to the internal state: if
repetitions are allowed, the step script will be called again with a pause
of 2 seconds, but no more than four times. If repetitions are prohibited,
the daemon itself will immediately terminate.

### Pipeline COMPATIBILITY mode

Compatibility mode is activated by the `root=pipeline` parameter. In this mode,
the daemon behaves the same as the original `pipelined`, except that it limits
the number of re-runs of the failed step. He perceives the status code 2 not as
a failure, but as a command to end the main daemon cycle.

## Configuration

The configuration is defined in the file `/etc/sysconfig/bootchain` when
building the image initramfs, optional and may contain the following parameters:

- `BC_LOG_VT` is the number of the virtual terminal to which the debug log
  should be output in the background. By default, the value is 3, respectively,
  the log is output to tty3. An empty value allows you to disable log output
  to any terminal.
- `BC_FGVT_ACTIVATE` - delay in seconds before activating the interactive
  terminal, by default tty2 is activated after 2 seconds in debug mode
  or after 8 seconds in normal mode. An empty value instructs to activate
  the interactive terminal immediately. This configuration option only works
  together with the `bootchain-interactive` features included in initramfs.
- `BC_LOGFILE` - the full path to the log file or the name of a special device,
  to which debugging messages will be output. In NATIVE mode, the default value
  is the default value is `/var/log/bootchained.log`, in compatibility mode with
  `pipeline` the default value is `/var/log/pipelined.log`.
- `mntdir` - where to create subdirectories of the boot chain steps. In NATIVE
  mode the default value is `/dev/bootchain`, in COMPATIBILITY mode with
  `pipeline`, the default value is `/dev/pipeline`.

Other `bootchain-*` modules can also use this configuration file for their
own needs.

## In-app pseudo-steps

All the steps listed below are an extension of the `pipeline`. They are
embedded in the code of the main loop of the `boot chain-loop` daemon, do
not need additional parameters and should not be taken into account when
addressing, as if they are hidden.

- `fg` - provides the transfer of the daemon to interactive mode when building
  initramfs with `bootchain-interactive` features. The `bootchain-core` itself
  is not interactivity required, but some other steps may need it, such as
  `altboot`.
- `noop` - does not perform any actions and is designed to pull off the results
  on the <OUT> of the previous step from the <IN> of the next step, which can
  be useful, for example, when we don`t want the results of the `waitdev` step
  to be used in the next step, `localdev`, which primarily looks at them.
- `noretry` - prohibits the following steps from ending with a non-zero return
  code, what will lead to the immediate shutdown of the daemon in case of a
  script failure any next step. By default, the steps are allowed to fail,
  the daemon will try to restart them again four times with a pause of two
  seconds.
- `retry` - allows all subsequent steps to be completed with a non-zero return
  code, which will lead to their starting five times, in total. This mode of
  operation of the daemon operates by default.

## External elements of the bootchain (steps-scripts)

- `mountfs` - mounts a file or device from the result of the previous or other
  specified step.
- `overlayfs` - combines one or more elements of the boot chain using overlayfs.
- `rootfs` - forces the daemon to use the result of the previous element as the
  found root of stage 2.

## Boot parameters

- `bootchain=name1[,name2][,name3]` - defines the initial state of the boot
  chains, i.e. the steps that the daemon must go through one by one. These can
  be both built-in pseudo-steps and real scripts of the actions performed. The
  names these steps are listed separated by commas.
- `pipeline=name1[,name2][,name3]` - alias for `bootchain=...`.
- `mountfs=target` - specifies the file or device to be mounted.
- `overlayfs=list` - defines the list of elements to combine.
- `bc_debug` - a boolean parameter that enables advanced debugging and forces
  if the daemon completes successfully, copy the download log to stage2.
- `bc_test=name` - defines the name of the current test case in the process of
  fully automated self-testing, forcing in case of successful after completing
  the daemon, copy the download log to stage2 and next to it create a
  `BC-TEST.passed` file with the specified name of the test case.

## bootchain-sh-functions extended API

- check_parameter() - checks that the required parameter is not empty, otherwise
  it exits via fatal().
- get_parameter() - outputs the value of the parameter of the current step by
  the index $callnum.
- resolve_target() - output the path to a file, directory or device, depending
  on from the parameter.
- resolve_devname() - output the path to a special device file at the specified
  directory. Usually the step directory contains a DEVNAME or dev file if the
  device was the result of a step, then the function will return a readable
  `/dev/node`.
- debug() - text message output during extended debugging.
- enter() - tracing during extended debugging: entering the specified function.
- leave() - tracing during extended debugging: exit from the specified function.
- run() - run an external command. With extended debugging, the executed command
  will be logged.
- fdump() - output of the contents of the specified file during extended
  debugging.
- assign() - assignment of the specified value to a variable that gets into
  the log with advanced debugging. The left-hand expression is also computable.
- next_bootchain() - command to the daemon to change the sequence of the
  following steps.
- is_step_passed() - returns 0 if the current step has been passed at
  least once.
- launch_step_once() - if the current step has already been completed,
  it completes the work through the fatal() call.
- break_bc_loop() - informs the daemon that the current step is the last and
  after after its successful completion, you can switch to stage2. The script
  of this step, however, must work to the end and end with a zero status code
  in order for the daemon to process the received signal.
- bc_reboot() - performs a logged restart of the computer.
- bypass_results() - asks the daemon to associate the <OUT> of the previous
  step with the <IN> the next step. It is also used to inform the daemon about
  the result (mounted directory) inside the current initramfs root, outside the
  $mntdir tree.
- initrd_version() - output of the current version of make-initrd. It is proposed
  to move to make-initrd/data/bin/initrd-sh-functions after has_module().

## Examples

Cmdline: root=bootchain bootchain=waitdev,mountfs,mountfs,overlayfs,rootfs waitdev=CDROM:LABEL=ALT_regular-rescue/x86_64 mountfs=DEVNANE mountfs=rescue

Following these parameters, the daemon waits for a local device with the
ISO-9660 file system and the volume label "ALT_regular-rescue/x86_64", mounts
this media, mounts the "rescue" file from it as squashfs of the root system,
makes it writable using overlayfs and tries to boot from it.

Cmdline: root=pipeline pipeline=getimage,mountfs,overlayfs,rootfs getimage=http://ftp.altlinux.org/pub/people/mike/iso/misc/vi-20140918-i586.iso mountfs=rescue

Following these parameters, the daemon loads the image "vi-20140918-i586.iso",
mounts it via the loop device, mounts the "rescue" file from it as squashfs of
the root system, makes it writable using overlayfs and tries to boot from it.

  reply	other threads:[~2021-10-13 17:06 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2021-09-24 15:52 Leonid Krivoshein
2021-09-24 16:56 ` Alexey Gladkov
2021-09-24 18:42   ` Leonid Krivoshein
2021-09-24 19:06     ` Alexey Gladkov
2021-09-26 18:56       ` Leonid Krivoshein
2021-09-27  9:15         ` Alexey Gladkov
2021-09-27 13:17           ` Leonid Krivoshein
2021-09-27 13:55             ` Alexey Gladkov
2021-10-13 17:06               ` Leonid Krivoshein [this message]
2021-10-13 18:38                 ` Alexey Gladkov
2021-10-13 18:48                   ` Leonid Krivoshein
2021-09-24 19:08 ` Alexey Gladkov
2021-09-24 21:59   ` Leonid Krivoshein
2021-09-26 14:29     ` Alexey Gladkov
2021-09-26 20:09       ` Leonid Krivoshein
2021-09-27  9:23         ` Alexey Gladkov

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=933e0f96-35e5-afb5-80f1-6353d6973ca7@gmail.com \
    --to=klark.devel@gmail.com \
    --cc=make-initrd@lists.altlinux.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link

Make-initrd development discussion

This inbox may be cloned and mirrored by anyone:

	git clone --mirror http://lore.altlinux.org/make-initrd/0 make-initrd/git/0.git

	# If you have public-inbox 1.1+ installed, you may
	# initialize and index your mirror using the following commands:
	public-inbox-init -V2 make-initrd make-initrd/ http://lore.altlinux.org/make-initrd \
		make-initrd@lists.altlinux.org make-initrd@lists.altlinux.ru make-initrd@lists.altlinux.com
	public-inbox-index make-initrd

Example config snippet for mirrors.
Newsgroup available over NNTP:
	nntp://lore.altlinux.org/org.altlinux.lists.make-initrd


AGPL code for this site: git clone https://public-inbox.org/public-inbox.git