Сборка пакетов/Соглашение по стилю RPM-пакетов/Sysconfig

Перейти к: навигация, поиск
5. Sysconfig

Назад

Далее



5. Sysconfig


Данный раздел описывает специальные настройки SUSE, которые хранятся в /etc/sysconfig. После введения и раздела описывающего базовый формат файлов в этой директории, идет раздел с описанием специфичных для SUSE метаданных. И в завершении - раздел описывающий, как пакет может установить свои собственные настройки.

/etc/sysconfig/ - это центральное место для хранения системных настроек SUSE Linux. Generally, it includes setting that should be configurable but cannot be modified by native config files below /etc. It does not supply the native config files or duplicate information from such files.

It is typically used to configure SuSEconfig modules, init scripts, and various launchers. For example, /etc/sysconfig/security defines the security level for the system and also defines if permissions of critical files are checked by SuSEconfig. /etc/sysconfig/xntp defines options to start the xntpd daemon and also defines whether it must be started in a chroot environment.


Преимущества /etc/sysconfig:

  • Простой и унифицированный формат данных.
  • Всё находится в одном месте.
  • Настройки могут быть легко прочитаны как скриптами, так и пользователем.
  • Настройки легко изменить с помощью YaST Sysconfig или соответствующим модулем YaST.


Базовый формат файлов


Файлы в директории /etc/sysconfig - это обычные текстовые файлы. Настройки представлены в виде пар: {переменная,значение}, так же как и переменные оболочки(shell):

VARIABLE=”value”

Перед каждой переменной желательно добавить специальный комментарий, предоставляющий развернутую информацию о ней: описание, тип (какие значения может принимать) и значение по умолчанию. Подобные метаданные впоследствии использует YaST Sysconfig Editor. Комментарии, как и в оболочке (shell), начинаются с символа '#', но в дополнение к этому, должны следовать специальному синтаксису, чтобы можно было различать/разделять метаданные. Подробнее см. формат метаданных .

Пример из файла /etc/sysconfig/boot. Здесь определяется переменная PROMPT_FOR_CONFIRM:

## Path:        System/Boot
 ## Description: Boot configuration
 ## Type:        yesno
 ## Default:     no
 #
 # For interactive debugging of the startup process. If set
 # to "yes" the system will ask whether to confirm every
 # step of the boot process.
 #
 PROMPT_FOR_CONFIRM="no"


Формат метаданных


Информация в данном разделе взята из файла /usr/share/doc/packages/yast2-sysconfig/metadata.txt (т.е. подробности см. в этом файле), который входит в состав пакета yast2-sysconfig.

Метаданные очень важны, именно они позволяют пользователю легко менять настройки в /etc/sysconfig с помощью модуля YaST sysconfig. Этому модулю требуется дополнительная информация(метаданные), для корректного отображения и редактирования настроек. Изначально метаданные хранились в файле meta_sys.config пакета yast2-sysconfig, и это было не идеальным решением, так как файл поддерживался/разрабатывался одним разработчиком, а переменные, для которых он был предназначен, разработчиками других пакетов. Поэтому, начиная со SL 8.2 метаданные являются частью файлов в директории /etc/sysconfig.


Метаданные является частью комментария описывающего переменную. Строка с метаданными начинается с двойного символа хеш "##", а сами метаданные определены в виде пар {тег,значение}, следующим способом:

## tag:     value

Multiple values can be specified in a comma-separated list. Values that contain commas or spaces must be quoted. Long values can be split onto more lines using backslash '\' as the last character on the line.

A normal comment (after single hash characer “#”) is displayed as help text.

This example is taken from the package acpid. It defines the variable ACPI_MODULES, which is entered to /etc/sysconfig/powermanagement from the template /var/adm/fillup-templates/sysconfig.powermanagement-acpid:

## Path:                System/Powermanagement/acpid/General
 ## Type:                string(ac,battery,button,fan,processor,\
 ##                             thermal,asus_acpi,toshiba_acpi)
 ## Default:             "ac battery button fan processor thermal"
 ## ServiceRestart:      acpid
 # The acipd startscript will load all necessary modules for acpi.
 # If some of these modules cause trouble, you may remove it
 # from this variable.  You may add the modules asus_acpi or
 # toshiba_acpi if your computer is an Asus or a Toshiba.
 # Seperate several modules by space.
 ACPI_MODULES="ac battery button fan processor thermal"

Comments after three hash characters “###” are ignored. They can be used to disable some unwanted parts or to create comments that should not be visible for YaST users. For example:

### I don't want thermal module in the default, Admin
 ### Default:             "ac battery button fan processor thermal"
 ## Default:             "ac battery button fan processor"

Metadata blocks must be located at the beginning of a comment block. Metadata can have any order in the metadata block.

The metadata should not include comments like:

#
 # This is /etc/sysconfig/foo
 #
#
 # Here ends /etc/sysconfig/foo
 #      

or:

#####
 # start of section xyz
 #
#
 # end of section xyz
 #####

After an update or when a second package adds a variable, those markers may do more harm then good. See below.


5.3. Metadata Tags

All tags are optional and can be sorted into two sets: descriptions and actions. The first tags describe the variable itself, like type, default value, and position in the tree widget in YaST. The second tags describe actions required to activate changes, like calling a SuSEconfig module or restarting a service.

Descriptive tags:


  • Path defines where the variable should be located in the tree widget in the YaST sysconfig editor. The character slash '/' is used as the separator. It can be escaped with backslash '\' if it is part of a subtree name. The variables are typically positioned at the second or third level. However, the depth is not limited.

The first character of subtree name should be an uppercase letter. The following basic categories are defined (used at the first level of the path):

    • Hardware is the subtree for all hardware-related settings. It is used, for example, in the sysconfig files sound and keyboard.
    • System is the subtree for basic system configuration. It is used, for example, in the sysconfig files boot, suseconfig, cron, console, and security.
    • Desktop is the subtree for desktop settings. It is used, for example, in the sysconfig files kde, gnome, and xdm.
    • Applications is the subtree for application-related settings. It is used, for example, in the sysconfig files java, ispell, and man.
    • Network is the subtree for network service settings. It is used, for example, in the sysconfig files apache, mail, and nfs.
    • Other is the subtree for settings that do not fit any category above. This subtree is also used as a fallback if no path is specified. The sysconfig filename is then used at the second level of the path name. For example, the variables from /etc/sysconfig/test appear in the path Other/test if no other path is specified.

All the variables should be located in a subtree of the basic categories, as in path:Hardware/Joystick or path:System/Console. The path depth can be greater than two, as in path:System/Filesystem/Fam.

  • Description is a very special tag because it is not related to the following variable, but is connected with the previous path. It defines a description of the path set by the previous Path tag. It should describe the entire subtree. It is displayed if a YaST user selects a path in the tree instead of a variable.

Each path specification can have a description. If a path has more than one description, the last found is used. If multiple packages require the same base package, the description should be located only in the base package. If packages are independent, the description should be located in an extra file that is part of yast2-sysconfig package.

  • Type defines the type of the variable and is used to check the entered value. The following types are supported:
    • string — Any value is allowed. It is the default type.
    • string(v1,v2,...) — The listed values are offered. Any value is allowed.
    • list(v1,v2,...) — The listed values are offered and no other value is allowed.
    • integer — Any integer value is allowed.
    • integer(min:max) — Any integer in the specified range is allowed. One limit can be missing, for example, integer(0:) allows values greater than 0.
    • boolean — The values "true" and "false" offered and no other value is allowed.
    • yesno — The values "yes" and "no" are offered and no other value is allowed.
    • ip — An IPv4 or IPv6 address is allowed as the value, for example, 10.20.0.1.
    • ip4 — Only an IPv4 address is allowed as the value.
    • ip6 — Only an IPv6 address is allowed as the value.
    • regexp(exp) — only strings that matches the regular expression exp are allowed. The expression must follow POSIX Extended Regular Expression syntax. For example: regexp(^0[0-7]*$) allows octal values only.
  • Default defines the default value of the variable. It is used if the user clicks the [Default] button in the YaST sysconfig editor.


Activation tags:


  • PreSaveCommand defines a Bash command that is processed before a new value is saved to the sysconfig file. It can be used, for example, to stop a daemon if it must be done before the value is modified.

The value is a string that is then executed with bash -c. All Bash features, like conditional execution (&&,||) or output redirection (<,>,>>), are allowed. The string is not parsed or changed by YaST2, except white spaces at the beginning and at the end of the string are removed and multiline strings are merged into single line.

  • Config defines a comma-separated list of SuSEconfig modules that should be started after the value is changed, for example, Config: profiles,kde,susewm.
  • ServiceReload defines a comma-separated list of init script names that should be called to reload the service after the value is changed. For example: ServiceReload: sendmail,postfix.
  • ServiceRestart defines a comma-separated list of init script names that should be called to restart the service after the value is changed. For example: ServiceRestart: tomcat,jonas.
  • Command defines a Bash command to process after the variable is changed. It can be used for any action that cannot be specified using above tags. The value type is defined and processed the same way as for PreSaveCommand (see above).


The commands should not do any dangerous actions because they will probably be started automatically by beginners. For example, the variable DISPLAYMANAGER requires xdm to be restarted, which kills the current X session. Therefore, the required action should only be described in the comment in this case. If the activation command would be too complex (too many dependences or checks). The needed steps should be only commented as well.

The YaST sysconfig editor does not run the same action for each modified variable. It starts the following process after the user clicks the [Finish] button:


  1. Start commands from the PreSaveCommmand tags for each changed variable. If it returns a nonzero exit status, it is assumed that it failed and other activation commands are ignored for this variable.
  2. Save all changed variables.
  3. Start all specified SuSEconfig modules for each changed variable.
  4. Restart and reload specified services for each changed variable. This is done only for running services. Therefore, the init scripts with the parameter status are called to check if the services are running first.
  5. Start the commands from the Command tags for each changed variable.


Each command is started only once to speed up the activation if more modified variables need the same activation command. The commands are compared without any parsing or semantic check when testing whether the command has already been executed. For this reason, the commands should be consistent at least in one file. The user usually changes only a few variables in one file.

If activation commands are missing in the entire sysconfig file, SuSEconfig is started for backward compatibility with old sysconfig files. Some variables need no activation, like those in /etc/sysconfig/boot, which are used only within boot. In this case, the empty Config tag could be used to avoid starting the SuSEconfig script after a variable is changed.


5.4. Metadata Inheritance

The metadata need not be defined for each value. All metadata, including help comments, are also used for subsequent variables until they are predefined. The only exception is the Decription tag, which is connected with the previous Path tag. See its specification for more details.

The inheritance is often used to keep sysconfig files simple and synoptical. However, it could also be dangerous. The variables are entered in sysconfig files by the utility fillup, described in [[SUSE_Package_Conventions/Sysconfig#spc_sc_installation Section�5.5, “Installation”]. fillup updates metadata of already included variables and adds new variables at the end of the sysconfig file. It adds metadata only immediately above the new variables and does not guarantee that they inherit other metadata correctly. Several packages can enter variables in the same sysconfig file, so the variables can be mixed after some updates. Therefore, it is a good practice to repeat all metadata before new variables added in a later version of a package. It is even a good idea to reset some potential unwanted actions by setting an empty value if they are not requested.

This example is taken from /etc/sysconfig/fam. The same Path and ServiceRestart values are defined once for both variables:

## Path:                System/File systems/Fam
 ## Description:         File Access Monitoring Daemon
 ## Type:                integer
 ## ServiceRestart:      fam
 ## Default:             4
 # Polling interval. check for local files each
 # $FAM_POLLING_INTERVAL second
 # (default is 4)
 FAM_POLLING_INTERVAL="4"
 
 ## Type:        integer
 ## Default:     0
 # Close connections after $FAM_INACTIVE_TIMEOUT seconds.
 # (default is 0 -> do not close connections)
 FAM_INACTIVE_TIMEOUT="0"
 [...]

This example is taken from /etc/sysconfig/joystick. All metadata, including description, is defined once for all four variables:

## Path:        Hardware/Joystick
 ## Description: Joystick cofigurations
 ## Type:        string
 ## Default:     ""
 ## ServiceRestart: joystick
 # Gameport module names
 # (typically "ns558" for legacy gameport support)GAMEPORT_MODULE_0=""
 GAMEPORT_MODULE_1=""
 GAMEPORT_MODULE_2=""
 GAMEPORT_MODULE_3=""


5.5. Installation

Any package can add its own variables into any existing sysconfig file or into its own one. As more packages can add variables into the same sysconfig files, they do not include the files directly. Instead, the packages install only templates into /var/adm/fillup-templates/ and call the utility fillup in their %post scripts to fill up the variables from the templates into real sysconfig files.

The variables should be prefixed like in the old /etc/rc.config to avoid name clashes and simplify searching. For example, the postfix package uses variables prefixed by POSTFIX_. Existing variables should not be renamed to avoid problems after update.

If a package comes with many variables, it is better to split the variables into multiple sysconfig files.

The templates are typically added to the package as extra files. They are installed in the %install section, mentioned in the file list, and filled up in the %post script. There are the macros %fillup_and_insserv and %fillup_only for this purpose. This example is taken from the package man:

PreReq:       %fillup_prereq
[...]
Source1:      sysconfig.cron-man
[...]

%install
[...]
mkdir -p ${RPM_BUILD_ROOT}/var/adm/fillup-templates
install -m 700 %{SOURCE1} ${RPM_BUILD_ROOT}/var/adm/fillup-templates
[...]

%post
%{fillup_only -an cron}

%files
[...]
/var/adm/fillup-templates/sysconfig.cron-man

It adds the following variables into /etc/sysconfig/cron from the template /var/adm/fillup-templates/sysconfig.cron-man. The variables are used to configure cron scripts installed by the same package into /etc/cron.daily/.

## Path:        System/Cron/Man
 ## Description: cron configuration for man utility
 ## Type:        yesno
 ## Default:     yes
 # Should mandb and whatis be recreated by cron.daily ("yes" or "no")
 REINIT_MANDB=yes
 
 ## Type:        yesno
 ## Default:     yes
 # Should old preformatted man pages (in /var/catman) be deleted? (yes/no)
 DELETE_OLD_CATMAN=yes
 
 ## Type:        integer
 ## Default:     7
 # How long should old preformatted man pages be kept before deletion? (days)
 CATMAN_ATIME=7

See Section�3.6, “%fillup_and_insserv” and Section�3.7, “%fillup_only” for more examples.

It is not possible to determine which config file or variable belongs to a package because the files below /etc/sysconfig/ are not owned by RPM packages. The templates in /var/adm/fillup-templates/ must be searched and queried instead.



Назад

Далее

4. Структура файловой системы

Вверх

6. SuSEconfig (deprecated)