Next: , Previous: , Up: Конфигурирование системы   [Contents][Index]


11.16 Invoking guix system

Однажды объявленное описание операционной системы, описанное в предыдущих разделах, может быть применено с помощью команды guix system. Синопсис:

guix system optionsaction file

file должно быть именем файла, содержащего определение operating-system. action указывает, как воспроизводится операционная система. В настоящее время поддерживаются следующие значения:

search

Показывает доступные определения типов служб, в соответствии с указанным регулярным выражениям, отсортированные по релевантности:

$ guix system search console
name: console-fonts
location: gnu/services/base.scm:806:2
extends: shepherd-root
description: Install the given fonts on the specified ttys (fonts are per
+ virtual console on GNU/Linux).  The value of this service is a list of
+ tty/font pairs.  The font can be the name of a font provided by the `kbd'
+ package or any valid argument to `setfont', as in this example:
+
+      '(("tty1" . "LatGrkCyr-8x16")
+        ("tty2" . (file-append
+                      font-tamzen
+                      "/share/kbd/consolefonts/TamzenForPowerline10x20.psf"))
+        ("tty3" . (file-append
+                      font-terminus
+                      "/share/consolefonts/ter-132n"))) ; for HDPI
relevance: 9

name: mingetty
location: gnu/services/base.scm:1190:2
extends: shepherd-root
description: Provide console login using the `mingetty' program.
relevance: 2

name: login
location: gnu/services/base.scm:860:2
extends: pam
description: Provide a console log-in service as specified by its
+ configuration value, a `login-configuration' object.
relevance: 2

…

Так же как для guix package --search, результат будет выведен в recutils формате, что делает его простым для фильтрации и вывода (see (GNU recutils manual)recutils).

edit

Edit or view the definition of the given service types.

For example, the command below opens your editor, as specified by the EDITOR environment variable, on the definition of the openssh service type:

guix system edit openssh
reconfigure

Собирает операционную систему описанную в file, активирует её и переключается на неё37.

Примечание: Настоятельно рекомендуется запустить команду guix pull перед первым запуском guix system reconfigure (see Вызов guix pull). В противном случае вы можете получить старую версию Guix после завершения reconfigure

Это действие повлияет на всю конфигурацию, указанную в file: учетные записи пользователей, системные службы, глобальный список пакетов, программы setuid и т.д. Команда запустит системные службы, указанные в file, которые в данный момент не запущены; если служба в данный момент запущена, изменения вступят в силу при следующем перезапуске (например по herd stop X или herd restart X).

Эта команда создает новое поколение, число которого на единицу больше, чем у текущего поколения (как описано guix system list-generations). Если это поколение уже существует, оно будет перезаписано. Это поведение описано в guix package (see Вызов guix package).

Она также добавляет пункты меню загрузчика для новой конфигурации ОС, если не передана опция --no-bootloader. Для GRUB она перемещает записи для более старых конфигураций вподменю, позволяя вам выбрать более старое поколение системы во время загрузки, если вам это понадобится.

По завершении новая система развертывается в /run/current-system. Этот каталог содержит метаданные о происхождении: список используемых каналов (see Каналы) и сам file, если он доступен. Вы можете просмотреть его, запустив:

guix system describe

Эта информация пригодится, если позже вы захотите проверить, как было собрано это конкретное поколение. Фактически, предполагая, что file содержит всё необходимое, вы можете позже пересобрать поколение n в вашей операционной системы с помощью:

guix time-machine \
  -C /var/guix/profiles/system-n-link/channels.scm -- \
  system reconfigure \
  /var/guix/profiles/system-n-link/configuration.scm

Вы можете думать об этом как о чем-то вроде встроенного контроля версий! Ваша система теперь не просто набор двоичных файлов: она содержит свой собственный источник. See provenance-service-type, для получения дополнительной информации об отслеживании происхождения.

По умолчанию reconfigure препятствует откату вашей системы, что может (пере)внести уязвимости безопасности, а также вызвать проблемы со службами "отслеживающими состояние", такими как системы управления базами данных. Вы можете переопределить это поведение, передав --allow-downgrades.

switch-generation

Переключает на существующее поколение системы. Эта команда атомарной операцией переключает системный профиль на указанное поколение системы. Она также изменяет порядок существующих элементов меню загрузчика системы. Она устанавливает в загрузчике запуск по умолчанию указанного поколения и перемещает другие поколения в подменю, если это поддерживается используемым загрузчиком. При следующей загрузке системы она будет использовать указанное поколение системы.

Сам загрузчик не переустанавливается при использовании этой команды. Таким образом, установленный загрузчик используется с обновленным файлом конфигурации.

Нужное поколение может быть явно указано по его номеру. Например, следующий вызов переключится на поколение 7:

guix system switch-generation 7

Нужное поколение также может быть указано относительно текущего поколения +N или -N, где +3 означает "на 3 поколения старше текущего", а -1 означает "на 1 поколение младше текущего". При задании отрицательного значения -1, перед ним нужно поставить -- чтобы не воспринимать его в качестве опции. Например:

guix system switch-generation -- -1

В настоящее время результатом вызова этого действия является только переключение профиля на существующее поколение и изменение элементов меню загрузчика. Чтобы начать использовать указанное поколение, вы должны перезагрузиться. В будущем поведение будет аналогично reconfigure, например, запуск и остановка служб.

Это действие завершится ошибкой, если указанное поколение не существует.

откат

Переключает на предыдущее поколение системы. При следующей загрузке система будет использовать предыдущее. Команда отменяет reconfigure, и делает то же самое, что switch-generation с аргументом -1.

В настоящее время, как и в случае с switch-generation, вы должны перезагрузиться после выполнения этого действия, чтобы фактически начать использовать предыдущее поколение системы.

delete-generations

Удаляет поколение, делая их кандидатами на для сборщика мусора (see Вызов guix gc, для получения информации о том, как запустить "сборщик мусора").

Работает так же, как и ‘guix package --delete-generations’ (see --delete-generations). Без аргументов удаляются все системные поколения, кроме текущего:

guix system delete-generations

You can also select the generations you want to delete. The example below deletes all the system generations that are more than two months old:

guix system delete-generations 2m

Выполнение этой команды автоматически переустановит загрузчик с обновлением меню—например, подменю "old generations" в GRUB не будет содержать удаленные поколения.

build

Собирает деривацию операционной системы, которая включает в себя все файлы конфигурации и программы, необходимые для загрузки и запуска системы. Это действие на самом деле ничего не устанавливает.

init

Наполняет указанную директорию всем необходимым для запуска операционной системы, указанным в файле. Это полезно при первой установке системы Guix. В качестве примера:

guix system init my-os-config.scm /mnt

копирует в /mnt все элементы хранилища, необходимые для конфигурации, указанной в my-os-config.scm. Включая файлы конфигурации, пакеты и так далее. Он также создает другие важные файлы, необходимые для правильной работы системы, такие как каталоги /etc, /var и /run и файл /bin/sh.

This command also installs bootloader on the targets specified in my-os-config, unless the --no-bootloader option was passed.

vm

Build a virtual machine (VM) that contains the operating system declared in file, and return a script to run that VM.

Примечание: Параметры vm и другие, приведенные ниже, могут использовать поддержку KVM ядра Linux-libre. В частности, если машина поддерживает аппаратную виртуализацию,следует загрузить соответствующий модуль ядра KVM а файл устройства /dev/kvm должен существовать и быть доступен для чтения и записи пользователю и процессамсборки демона (see Установка окружения сборки).

Аргументы, переданные скрипту, передаются в QEMU, как в приведенном ниже примере,который включает сеть и запрашивает 1 GiB оперативной памяти для эмулируемоймашины:

$ /gnu/store/…-run-vm.sh -m 1024 -smp 2 -nic user,model=virtio-net-pci

It’s possible to combine the two steps into one:

$ $(guix system vm my-config.scm) -m 1024 -smp 2 -nic user,model=virtio-net-pci

Виртуальная машина использует свое хранилище совместно с хост-системой.

By default, the root file system of the VM is mounted volatile; the --persistent option can be provided to make it persistent instead. In that case, the VM disk-image file will be copied from the store to the TMPDIR directory to make it writable.

Дополнительные файловые системы могут быть разделены между хостом и виртуальной машиной с помощью параметров --share и --expose: первый указывает директорию, к которой должен быть предоставлен общий доступ с правом на запись, последний обеспечивает доступ только на чтение.

Пример ниже создает виртуальную машину, которой доступна домашняя директория пользователя с правами на чтение, а директория $HOME/tmp хоста размещена в /exchange с правами на чтение и запись:

guix system vm my-config.scm \
   --expose=$HOME --share=$HOME/tmp=/exchange

В GNU / Linux по умолчанию загрузка выполняется непосредственно в ядро; это имеет преимущество в том, что требуется только очень крошечный образ корневого диска, так как затем можно смонтировать хранилище хоста.

The --full-boot option forces a complete boot sequence, starting with the bootloader. This requires more disk space since a root image containing at least the kernel, initrd, and bootloader data files must be created.

The --image-size option can be used to specify the size of the image.

The --no-graphic option will instruct guix system to spawn a headless VM that will use the invoking tty for IO. Among other things, this enables copy-pasting, and scrollback. Use the ctrl-a prefix to issue QEMU commands; e.g. ctrl-a h prints a help, ctrl-a x quits the VM, and ctrl-a c switches between the QEMU monitor and the VM.

образ

The image command can produce various image types. The image type can be selected using the --image-type option. It defaults to mbr-hybrid-raw. When its value is iso9660, the --label option can be used to specify a volume ID with image. By default, the root file system of a disk image is mounted non-volatile; the --volatile option can be provided to make it volatile instead. When using image, the bootloader installed on the generated image is taken from the provided operating-system definition. The following example demonstrates how to generate an image that uses the grub-efi-bootloader bootloader and boot it with QEMU:

image=$(guix system image --image-type=qcow2 \
        gnu/system/examples/lightweight-desktop.tmpl)
cp $image /tmp/my-image.qcow2
chmod +w /tmp/my-image.qcow2
qemu-system-x86_64 -enable-kvm -hda /tmp/my-image.qcow2 -m 1000 \
                   -bios $(guix build ovmf)/share/firmware/ovmf_x64.bin

When using the mbr-hybrid-raw image type, a raw disk image is produced; it can be copied as is to a USB stick, for instance. Assuming /dev/sdc is the device corresponding to a USB stick, one can copy the image to it using the following command:

# dd if=$(guix system image my-os.scm) of=/dev/sdc status=progress

The --list-image-types command lists all the available image types.

When using the qcow2 image type, the returned image is in qcow2 format, which the QEMU emulator can efficiently use. See Running Guix in a Virtual Machine, for more information on how to run the image in a virtual machine. The grub-bootloader bootloader is always used independently of what is declared in the operating-system file passed as argument. This is to make it easier to work with QEMU, which uses the SeaBIOS BIOS by default, expecting a bootloader to be installed in the Master Boot Record (MBR).

When using the docker image type, a Docker image is produced. Guix builds the image from scratch, not from a pre-existing Docker base image. As a result, it contains exactly what you define in the operating system configuration file. You can then load the image and launch a Docker container using commands like the following:

image_id="$(docker load < guix-system-docker-image.tar.gz)"
container_id="$(docker create $image_id)"
docker start $container_id

This command starts a new Docker container from the specified image. It will boot the Guix system in the usual manner, which means it will start any services you have defined in the operating system configuration. You can get an interactive shell running in the container using docker exec:

docker exec -ti $container_id /run/current-system/profile/bin/bash --login

Depending on what you run in the Docker container, it may be necessary to give the container additional permissions. For example, if you intend to build software using Guix inside of the Docker container, you may need to pass the --privileged option to docker create.

Last, the --network option applies to guix system docker-image: it produces an image where network is supposedly shared with the host, and thus without services like nscd or NetworkManager.

контейнер

Return a script to run the operating system declared in file within a container. Containers are a set of lightweight isolation mechanisms provided by the kernel Linux-libre. Containers are substantially less resource-demanding than full virtual machines since the kernel, shared objects, and other resources can be shared with the host system; this also means they provide thinner isolation.

Currently, the script must be run as root in order to support more than a single user and group. The container shares its store with the host system.

As with the vm action (see guix system vm), additional file systems to be shared between the host and container can be specified using the --share and --expose options:

guix system container my-config.scm \
   --expose=$HOME --share=$HOME/tmp=/exchange

The --share and --expose options can also be passed to the generated script to bind-mount additional directories into the container.

Примечание: This option requires Linux-libre 3.19 or newer.

options can contain any of the common build options (see Стандартные параметры сборки). In addition, options can contain one of the following:

--expression=expr
-e expr

Consider the operating-system expr evaluates to. This is an alternative to specifying a file which evaluates to an operating system. This is used to generate the Guix system installer see Сборка установочного образа).

--system=system
-s system

Attempt to build for system instead of the host system type. This works as per guix build (see Запуск guix build).

--target=triplet

Cross-сборка для triplet, который должен быть допустимым GNU triplet, например \ "aarch64-linux-gnu\" (see GNU configuration triplets in Autoconf).

--derivation
-d

Return the derivation file name of the given operating system without building anything.

--save-provenance

As discussed above, guix system init and guix system reconfigure always save provenance information via a dedicated service (see provenance-service-type). However, other commands don’t do that by default. If you wish to, say, create a virtual machine image that contains provenance information, you can run:

guix system image -t qcow2 --save-provenance config.scm

That way, the resulting image will effectively “embed its own source” in the form of meta-data in /run/current-system. With that information, one can rebuild the image to make sure it really contains what it pretends to contain; or they could use that to derive a variant of the image.

--target=triplet
-t type

For the image action, create an image with given type.

When this option is omitted, guix system uses the mbr-hybrid-raw image type.

--image-type=iso9660 produces an ISO-9660 image, suitable for burning on CDs and DVDs.

--image-size=size

Если задана min, остановиться, когда min байт собрано. min может быть числом байт или может содержать единицу измерения в суффиксе, как например, MiB для мебибайт и GB гигабайт (see size specifications in GNU Coreutils).

When this option is omitted, guix system computes an estimate of the image size as a function of the size of the system declared in file.

--network
-N

For the container action, allow containers to access the host network, that is, do not create a network namespace.

--root=file
-r file

Make file a symlink to the result, and register it as a garbage collector root.

--skip-checks

Skip pre-installation safety checks.

By default, guix system init and guix system reconfigure perform safety checks: they make sure the file systems that appear in the operating-system declaration actually exist (see Файловые системы), and that any Linux kernel modules that may be needed at boot time are listed in initrd-modules (see Начальный RAM-диск). Passing this option skips these tests altogether.

--allow-downgrades

Instruct guix system reconfigure to allow system downgrades.

By default, reconfigure prevents you from downgrading your system. It achieves that by comparing the provenance info of your system (shown by guix system describe) with that of your guix command (shown by guix describe). If the commits for guix are not descendants of those used for your system, guix system reconfigure errors out. Passing --allow-downgrades allows you to bypass these checks.

Примечание: Прежде чем использовать --allow-downgrades, убедитесь, что вы понимаете его последствия для безопасности.

--on-error=strategy

Apply strategy when an error occurs when reading file. strategy may be one of the following:

nothing-special

Report the error concisely and exit. This is the default strategy.

backtrace

Likewise, but also display a backtrace.

debug

Report the error and enter Guile’s debugger. From there, you can run commands such as ,bt to get a backtrace, ,locals to display local variable values, and more generally inspect the state of the program. See Debug Commands in GNU Guile Reference Manual, for a list of available debugging commands.

Once you have built, configured, re-configured, and re-re-configured your Guix installation, you may find it useful to list the operating system generations available on disk—and that you can choose from the bootloader boot menu:

describe

Describe the running system generation: its file name, the kernel and bootloader used, etc., as well as provenance information when available.

The --list-installed flag is available, with the same syntax that is used in guix package --list-installed (see Вызов guix package). When the flag is used, the description will include a list of packages that are currently installed in the system profile, with optional filtering based on a regular expression.

Примечание: The running system generation—referred to by /run/current-system—is not necessarily the current system generation—referred to by /var/guix/profiles/system: it differs when, for instance, you chose from the bootloader menu to boot an older generation.

It can also differ from the booted system generation—referred to by /run/booted-system—for instance because you reconfigured the system in the meantime.

list-generations

List a summary of each generation of the operating system available on disk, in a human-readable way. This is similar to the --list-generations option of guix package (see Вызов guix package).

Optionally, one can specify a pattern, with the same syntax that is used in guix package --list-generations, to restrict the list of generations displayed. For instance, the following command displays generations that are up to 10 days old:

$ guix system list-generations 10d

The --list-installed flag may also be specified, with the same syntax that is used in guix package --list-installed. This may be helpful if trying to determine when a package was added to the system.

The guix system command has even more to offer! The following sub-commands allow you to visualize how your system services relate to each other:

extension-graph

Emit to standard output the service extension graph of the operating system defined in file (see Структура сервисов, for more information on service extensions). By default the output is in Dot/Graphviz format, but you can choose a different format with --graph-backend, as with guix graph (see --backend):

The command:

$ guix system extension-graph file | xdot -

shows the extension relations among services.

Примечание: The dot program is provided by the graphviz package.

shepherd-graph

Emit to standard output the dependency graph of shepherd services of the operating system defined in file. See Сервисы Shepherd, for more information and for an example graph.

Again, the default output format is Dot/Graphviz, but you can pass --graph-backend to select a different one.


Footnotes

(37)

Это действие (и связанные с ним switch-generation и roll-back) можно использовать только в системах, в которых уже работает Guix System.


Next: Invoking guix deploy, Previous: Настройка загрузчика, Up: Конфигурирование системы   [Contents][Index]