From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.1 (2015-04-28) on sa.local.altlinux.org X-Spam-Level: X-Spam-Status: No, score=-2.0 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,FREEMAIL_FROM,PP_MIME_FAKE_ASCII_TEXT autolearn=ham autolearn_force=no version=3.4.1 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=subject:to:references:from:message-id:date:user-agent:mime-version :in-reply-to:content-language; bh=zZeP3nwRM4cHLjemqish0xBHajzXdNlYx8H5YH8dGUI=; b=acvD1Dokgt0NucOC9xv3ydX5ElHJmiwEfepTzog79Ao5BwzuIMLEPe7j0b11XjopKN jM0aYiI768/MAS8sELXe+qALMbAWnA2GB794TjNMokCB877AeNRyfz2O6y7nn5k2j7VK 9UqbBNM3bVSq3TzWcv76ycioRhms5fxsFk8rKx/28P57gfWb2RPD5jIvlBtSyGTJSgvo HcaHMjENunRcINM1U5pNIQIMsTa/LxfqUjs8C+lplDcPWGCD2O5Tpbi+j75NNE5Hv8J2 hdI2v9tP3Ax96j/rsAC1AtpK73Y/+y1/xp4B/zqsPrFKclhUUI/nQALoyzZGnAt2mvIB iKsQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:subject:to:references:from:message-id:date :user-agent:mime-version:in-reply-to:content-language; bh=zZeP3nwRM4cHLjemqish0xBHajzXdNlYx8H5YH8dGUI=; b=LFfqT78qDoyza6JYPFxrlQp/SBN+hV5H83G9ALOW76SJ7RayO95AhIWpGA6mPjtnCv w6+P9PKpBLefYrQOOKBDA0ndakIqdFBGUSj5wSQ0SK7tLUrx7TLTV0qPITO/JH5h3Fvx 0ZcGWbWZoHcyveqXXA8un1zXXRB5RcXEb5l5873M6QAXI/xE5HJU0pefUo2EWwDpk8kj oJPk+Iw0L4bic/Lc2FUdohy4EdAgNVULGEvzo1upeVIRFS6yH5q0IcYNa9g9O3LwVNuM uAwY5HKAHLxdUb0HD5Qp10bvinV0QRNvMGioo96M0EgLixB4ie/yAM5r9U3joLJURKOF LpKw== X-Gm-Message-State: AOAM531gbQYIHRUNmiUDKcJVo5C/yP7D/LnEUkLtGsnW8PhanWUfVi5Y v92X5crQzhgWEvsW+1n+yUWe/S2R59w= X-Google-Smtp-Source: ABdhPJxjMMTpEPD6sA3/b9mQyZxxjzUjBMu+A5DnkuUmJaxT7UKyHyeBTXaqB4G5vQLR0I+5lqaI7w== X-Received: by 2002:a05:6512:2393:: with SMTP id c19mr217888lfv.518.1634144764515; Wed, 13 Oct 2021 10:06:04 -0700 (PDT) To: make-initrd@lists.altlinux.org References: <20210924165640.snmbn7vjsusa7rjo@example.org> <1c88a28c-1155-7b51-33ce-52bf7fcfb6a3@gmail.com> <20210924190638.ysy3ukxckv77kptf@example.org> <74f9543c-ca73-75b2-6e77-1984f379365e@gmail.com> <20210927091542.zidthho7tyxa737w@example.org> <138916a4-bd1d-367e-2aa2-8bb1fd5901b7@gmail.com> <20210927135518.gnskejf4ga2izljb@example.org> From: Leonid Krivoshein Message-ID: <933e0f96-35e5-afb5-80f1-6353d6973ca7@gmail.com> Date: Wed, 13 Oct 2021 20:06:02 +0300 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.8.0 MIME-Version: 1.0 In-Reply-To: <20210927135518.gnskejf4ga2izljb@example.org> Content-Type: multipart/mixed; boundary="------------67D38F569FE16F682653BD9B" Content-Language: ru X-Mailman-Approved-At: Wed, 13 Oct 2021 20:29:23 +0300 Subject: Re: [make-initrd] [PATCH v1 00/41] fork pipeline X-BeenThere: make-initrd@lists.altlinux.org X-Mailman-Version: 2.1.12 Precedence: list Reply-To: make-initrd@lists.altlinux.org List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 13 Oct 2021 17:06:08 -0000 Archived-At: List-Archive: This is a multi-part message in MIME format. --------------67D38F569FE16F682653BD9B Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit Алексей, привет! 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. --------------67D38F569FE16F682653BD9B Content-Type: text/markdown; name="README.ru.utf8.md" Content-Transfer-Encoding: 8bit Content-Disposition: attachment; filename="README.ru.utf8.md" # Фича: 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 и пытается загрузиться с него. --------------67D38F569FE16F682653BD9B Content-Type: text/markdown; name="README.md" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="README.md" # 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 of a step with the 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 . 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 of the previous step from the 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 of the previous step with the 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. --------------67D38F569FE16F682653BD9B--