Difference between revisions of "Systemd (Português)"
(→Automontagem) |
(→Montagens de sistemas de arquivos) |
||
Line 230: | Line 230: | ||
=== Montagens de sistemas de arquivos === | === Montagens de sistemas de arquivos === | ||
− | {{Merge|File Systems|Esta seção foi adicionada | + | {{Merge|File Systems|Esta seção foi adicionada antes do systemd tornar-se o sistema de inicialização padrão. Removida após a fusão.|section=Duplication of content in Native configuration section}} |
A configuração padrão será automaticamente fsck e montará sistemas de arquivos antes de iniciar os serviços que eles precisam para serem montados. Por exemplo, systemd automaticamente garante que monta sistemas de arquivos remotos como [[NFS]] ou [[Samba]] são somente iniciados depois que a rede for configurada. Portanto, montagens de sistema de arquivos local e remoto especificados em {{ic|/etc/fstab}}} devem funcionar. | A configuração padrão será automaticamente fsck e montará sistemas de arquivos antes de iniciar os serviços que eles precisam para serem montados. Por exemplo, systemd automaticamente garante que monta sistemas de arquivos remotos como [[NFS]] ou [[Samba]] são somente iniciados depois que a rede for configurada. Portanto, montagens de sistema de arquivos local e remoto especificados em {{ic|/etc/fstab}}} devem funcionar. |
Revision as of 18:46, 8 August 2013
zh-CN:Systemd zh-TW:Systemd Template:Article summary start Template:Article summary text Template:Article summary heading Template:Article summary wiki Template:Article summary wiki Template:Article summary wiki Template:Article summary wiki Template:Article summary wiki Template:Article summary wiki Template:Article summary wiki Template:Article summary end De project web page:
- Systemd é um sistema e gerenciador de serviços para Linux, compatível com os scripts de inicializações SysV e LS. Systemd fornece recursos de paralelização agressivos, usa socket e ativação D-Bus para iniciar seviços, oferece o incicio de daemons on-demand, mantém o registro de processos usando Linux control groups, suporte snapshotting e restauração do estado do sistema, preserva pontos de montagens e automontagens e implementa uma lógica de controle elaborado transacional baseada em dependência de serviço.
Contents
Migração de SysVinit/initscripts
- systemd e systemd-sysvcompat estão instalados por padrão na mídia de instalação mais recente 2012-10-13. Esta seção é destinada a instalações do Arch Linux, que ainda dependem de sysvinit e initscripts.
- Se você estiver executando Arch Linux dentro de um VPS, consulte Virtual Private Server#Moving your VPS from initscripts to systemd.
Considerações antes de mudar
- Faça algumas leituras sobre systemd.
- Note que systemd tem um systema journal que substitue syslog, embora os dois podem co-existir. Consulte #Journal.
- Embora systemd possa subtituir algumas das funcionabilidades do cron, acpid, ou xinetd, não há necessidade de deixar de usar os daemons traditionais, a menos que você queira.
- Interativo initscripts não está trabalhando com systemd. Em particular, netcfg-menu não pode ser usado no sistema de inicialização (FS#31377).
Procedimento de instalação
- Instalar systemd do official repositories.
- Acrescente o seguinte ao seu kernel parameters:
init=/usr/lib/systemd/systemd
. - Uma vez concluído, você pode permitir que todos os serviços desejados, através do uso
systemctl enable service_name
(isso equivale o que você inclue na arrayDAEMONS
. Novos nomes podem ser encontrados em Daemons List). - Reinicie seu sistema e verifique se systemd está atualmente ativo emitindo o seguinte comando:
cat /proc/1/comm
. Isso deve retornar a stringsystemd
. - Verifique se o seu hostname está configurado corretamente com systemd:
hostnamectl set-hostname myhostname
ou/etc/hostname
. - Proceda para remover initscripts e sysvinit de seu sistema e instale systemd-sysvcompat.
- Opcionalmente, remova o parâmetro
init=/usr/lib/systemd/systemd
. Não é mais necessário desde que systemd-sysvcompat fornece um symlink para systemd's.
Informações complementares
- Se você tem
quiet
em seu parâmetro kernel, você talvez queira removê-lo em seus primeiros boots com systemd, para auxiliar na identificação de eventuais problemas durante a inicialização.
- Não é necessário adicionar o usuário ao grupos (
sys
,disk
,lp
,network
,video
,audio
,optical
,storage
,scanner
,power
, etc.) para a maioria dos casos de uso com systemd. Os grupos podem até causar algumas quebras de funcionalidades. Por exemplo, o grupoaudio
vai quebrar a troca rápida de usuário e permite que os aplicativos bloqueiem programas. Cada registro PAM fornece uma sessão de logind, no qual para uma sessão local lhe dará permissões via POSIX ACLs em dispositivos audio/video, e permite certas operações como montagem de armazenamento removível via udisks.
- Veja o artigo Network Configuration para saber como configurar targets de rede.
Uso básico systemctl
O principal comando usado para introspecção e controle systemd é systemctl. Alguns de seus usos são examinando o estado do sistema e gerenciando do sistema e serviços. Consulte man 1 systemctl
para mais detalhes.
-H user@host
altera para controlar uma instância systemd em uma máqiona remota. Isto irá usar SSH para conectar-se uma instância remota systemd.Analisando o estado do sistema
Lista units executadas:
$ systemctl
ou:
$ systemctl list-units
Lista units que falharam::
$ systemctl --failed
Os arquivos units disponíveis podem ser vistos em /usr/lib/systemd/system/
e /etc/systemd/system/
(este último tem precedência). Você pode ver uma lista dos arquivos units instalados com:
$ systemctl list-unit-files
Usando units
As units podem ser, por exemplo, serviços (.service), pontos de montagem (.mount), dispositivos (.device) ou sockets (.socket).
Quando usa systemctl, você geralmente tem que especificar o nome completo do arquivo unit, incluindo o sufixo, por exemplo sshd.socket. No entanto, existem algumas formas curtas de especificar a unit nos seguintes comandos systemctl:
- Se você não especificar o sufixo, systemctl irá assumir .service. Por exemplo,
netcfg
enetcfg.service
são equivalentes. - Os pontos de montagem serão automaticamente convertidos para a unit .mount adequada. Por exemplo, especificando
/home
equivale ahome.mount
. - Similar aos pontos de montagem, dispositivos são automaticamente convertido para a unit .device adequada, portanto, especificando
/dev/sda2
equivale adev-sda2.device
.
Consulte man systemd.unit
para detalhes.
Ativa uma unit imediatamente:
# systemctl start unit
Desativa uma unit imediatamente:
# systemctl stop unit
Reinicia uma unit:
# systemctl restart unit
Peça uma unit para recarregar sua configuração:
# systemctl reload unit
Mostra o estado de uma unit, inclusive se estiver em execução ou não:
$ systemctl status unit
Verifica se a unit já está habilitada ou não:
$ systemctl is-enabled unit
Habilita uma unit para ser iniciada na inicialização:
# systemctl enable unit
[Install]
são geralmente chamados por outros serviços automaticamente. Se você precisa instalá-los manualmente, use o seguinte comando, substituindo foo com o nome do serviço.
# ln -s /usr/lib/systemd/system/foo.service /etc/systemd/system/graphical.target.wants/
Desativa uma unit para não iniciar durante a inicialização:
# systemctl disable unit
Mostra a página de manual associado a uma unit (tem que ser suportado pelo arquivo da unit):
$ systemctl help unit
Recarrega o systemd, scaneando por units novas e modificadas:
# systemctl daemon-reload
O gerenciamento de energia
polkit é necessário para o gerenciamento de energia. Se você está numa sessão de usuário local systemd-logind e nenhuma outra sessão está ativa, os seguintes comandos funcionarão sem privilégios root. Se não (por exemplo, porque outro usuário está conectado em um tty), systemd irá automaticamente pedir a senha de root.
Desliga e reinicia o sistema:
$ systemctl reboot
Desliga e desliga o sistema:
$ systemctl poweroff
Suspende o sistema:
$ systemctl suspend
Coloca o sistema em modo de hibernação:
$ systemctl hibernate
Coloca o sistema no modo de suspensão :
$ systemctl hybrid-sleep
Executando Gerenciadores de Display no systemd
Para habilitar a autenticação gráfica, execute o seu daemon de Display Manager preferido (ex. KDM). No momento, existem arquivos de serviço para GDM, KDM, SLiM, XDM, LXDM, LightDM, e SDDMAUR.
# systemctl enable kdm
Isso deve funcionar. Se não, você pode ter que definir o default.target manualmente ou de uma velha instalação:
# ls -l /etc/systemd/system/default.target
/etc/systemd/system/default.target -> /usr/lib/systemd/system/graphical.target
Basta apagar o link simbólico e systemd usará seu default.target (ex. graphical.target).
# rm /etc/systemd/system/default.target
Usando systemd-logind
A fim de verificar o estado de sua sessão de usuário, você pode usar loginctl
. Todas ações PolicyKit como suspender o sistema ou montar unidades externas irão funcionar.
$ loginctl show-session $XDG_SESSION_ID
Configuração nativa
644
e propriedade root:root
.Console virtual
O console virtual (mapeamento de teclado, fonte do console e mapa do console) é configurado em /etc/vconsole.conf
ou utilizando a ferramenta localectl.
Para mais informação, consulte fontes do console e keymaps.
Relógio do hardware
systemd usará UTC para o relógio do hardware por padrão.
Relógio do hardware em localtime
Se quiser alterar o relógio de hardware para usar horário local (não recomendado) fazer:
# timedatectl set-local-rtc true
Se quiser reverter para o relógio do hardware estando em UTC, faça:
# timedatectl set-local-rtc false
Esteja avisado que, se o relógio do hardware está definido para localtime, lidar com o horário de verão é uma confusão(there is a lot more to it).
Uma razão para permitir que o RTC esteja em hora local é permitir dual boot com o Windowss (which uses localtime). No entanto, o Windows é capaz de lidar com a RTC inicando em UTC, com um simples registry fix.
Para mais informação, consulte Time.
Módulos do kernel
Consulte Kernel modules#Configuration.
Montagens de sistemas de arquivos
A configuração padrão será automaticamente fsck e montará sistemas de arquivos antes de iniciar os serviços que eles precisam para serem montados. Por exemplo, systemd automaticamente garante que monta sistemas de arquivos remotos como NFS ou Samba são somente iniciados depois que a rede for configurada. Portanto, montagens de sistema de arquivos local e remoto especificados em /etc/fstab
} devem funcionar.
Consulte man 5 systemd.mount
por detalhes.
Automontagem
Se você tem uma partição /home
grande, talvez seja melhor permitir que os serviços que não dependem da /home
para iniciar enquanto /home
é verificada pelo fsck. Isto pode ser feito adicionando as seguintes opções em /etc/fstab
na entrada de ssua partição /home
:
noauto,x-systemd.automount
Isso irá fsck e montar /home
quando for acessada pela primeira vez, e o kernel irá buffer todos os acessos de arquivo para /home
até que esteja pronto.
/home
filesystem type autofs
, which is ignored by mlocate by default. The speedup of automounting /home
may not be more than a second or two, depending on your system, so this trick may not be worth it.The same applies to remote filesystem mounts. If you want them to be mounted only upon access, you will need to use the noauto,x-systemd.automount
parameters. In addition, you can use the x-systemd.device-timeout=#
option to specify a timeout in case the network resource is not available.
If you have encrypted filesystems with keyfiles, you can also add the noauto
parameter to the corresponding entries in /etc/crypttab
. systemd will then not open the encrypted device on boot, but instead wait until it is actually accessed and then automatically open it with the specified keyfile before mounting it. This might save a few seconds on boot if you are using an encrypted RAID device for example, because systemd does not have to wait for the device to become available. For example:
/etc/crypttab
data /dev/md0 /root/key noauto
LVM
Se você não tiver volumes LVM ativados via o initramfs, enable o serviço lvm-monitoring, que é fornecido pelo pacote lvm2.
Gerenciamento de energia ACPI
Consulte Power Management.
Arquivos temporários
systemd-tmpfiles usa arquivos de configuração em /usr/lib/tmpfiles.d/
e /etc/tmpfiles.d/
para descrever a criação, limpeza e remoção de arquivos e diretórios voláteis e temporários que normalmente residem em diretórios como /run
ou /tmp
.
Cada arquivo de configuração é chamado no estilo /etc/tmpfiles.d/program.conf
. Isso também irá substituir todos os arquivos em /usr/lib/tmpfiles.d/
com o mesmo nome.
tmpfiles normalmente são fornecidos em conjunto com arquivos de serviços para criar diretórios que deverão existir por certas daemons. Por exemplo o daemon Samba espera que o diretório /run/samba
exista e tenha as permissões corretas. Assim, o pacote samba vem com esta configuração:
/usr/lib/tmpfiles.d/samba.conf
D /run/samba 0755 root root
tmpfiles também pode ser usado para escrever os valores em determinados arquivos na inicialização. Por exemplo, se você usa /etc/rc.local
para desativar ativação de dispositivos USB com echo USBE > /proc/acpi/wakeup
, você pode usar o seguinte tmpfile:
/etc/tmpfiles.d/disable-usb-wake.conf
w /proc/acpi/wakeup - - - - USBE
Consulte man 5 tmpfiles.d
para detalhes.
/sys
uma vez que o serviço systemd-tmpfiles-setup pode ser executado antes dos módulos de dispositivo apropriado for carregado. Neste caso, você pode verificar se o módulo tem um parâmetro para a opção que pretende definir com modinfo module
e setar essa opção com um arquivo de configuração em /etc/modprobe.d. Caso contrário, você terá que escrever uma regra udev para setar o atributo adequado logo que o dispositivo aparecer.Escrevendo arquivos .service personalizados
A sintaxe do systemd arquivos unit é inpirado pela Especificações de Entrada de arquivos .desktop XDG Desktop, que são, por sua vez inspirado pelo .ini Microsoft Windows.
Consulte systemd/Services para mais exemplos.
Manuseando dependências
With systemd, dependencies can be resolved by designing the unit files correctly. The most typical case is that the unit A requires the unit B to be running before A is started. In that case add Requires=B
and After=B
to the [Unit]
section of A. If the dependency is optional, add Wants=B
and After=B
instead. Note that Wants=
and Requires=
do not imply After=
, meaning that if After=
is not specified, the two units will be started in parallel.
Dependencies are typically placed on services and not on targets. For example, network.target is pulled in by whatever service configures your network interfaces, therefore ordering your custom unit after it is sufficient since network.target is started anyway.
Type
There are several different start-up types to consider when writing a custom service file. This is set with the Type=
parameter in the [Service]
section. See man systemd.service
for a more detailed explanation.
-
Type=simple
(default): systemd considers the service to be started up immediately. The process must not fork. Do not use this type if other services need to be ordered on this service, unless it is socket activated. -
Type=forking
: systemd considers the service started up once the process forks and the parent has exited. For classic daemons use this type unless you know that it is not necessary. You should specifyPIDFile=
as well so systemd can keep track of the main process. -
Type=oneshot
: this is useful for scripts that do a single job and then exit. You may want to setRemainAfterExit=yes
as well so that systemd still considers the service as active after the process has exited. -
Type=notify
: identical toType=simple
, but with the stipulation that the daemon will send a signal to systemd when it is ready. The reference implementation for this notification is provided by libsystemd-daemon.so. -
Type=dbus
: the service is considered ready when the specifiedBusName
appears on DBus's system bus.
Editing provided unit files
To edit a unit file provided by a package, you can create a directory called /etc/systemd/system/unit.d/
for example /etc/systemd/system/httpd.service.d/
and place *.conf files in there to override or add new options. systemd will parse these *.conf files and apply them on top of the original unit. For example, if you simply want to add an additional dependency to a unit, you may create the following file:
/etc/systemd/system/unit.d/customdependency.conf
[Unit] Requires=new dependency After=new dependency
Then run the following for your changes to take effect:
# systemctl daemon-reload # systemctl restart unit
Alternatively you can copy the old unit file from /usr/lib/systemd/system/
to /etc/systemd/system/
and make your changes there. A unit file in /etc/systemd/system/
always overrides the same unit in /usr/lib/systemd/system/
. Note that when the original unit in /usr/lib/
is changed due to a package upgrade, these changes will not automatically apply to your custom unit file in /etc/
. Additionally you will have to manually reenable the unit with systemctl reenable unit
. It is therefore recommended to use the *.conf method described before instead.
As the provided unit files will be updated from time to time, use systemd-delta for system maintenance.
Syntax highlighting for units within Vim
Syntax highlighting for systemd unit files within Vim can be enabled by installing vim-systemd from the official repositories.
Targets
systemd uses targets which serve a similar purpose as runlevels but act a little different. Each target is named instead of numbered and is intended to serve a specific purpose with the possibility of having multiple ones active at the same time. Some targets are implemented by inheriting all of the services of another target and adding additional services to it. There are systemd targets that mimic the common SystemVinit runlevels so you can still switch targets using the familiar telinit RUNLEVEL
command.
Get current targets
The following should be used under systemd instead of running runlevel
:
$ systemctl list-units --type=target
Create custom target
The runlevels that are assigned a specific purpose on vanilla Fedora installs; 0, 1, 3, 5, and 6; have a 1:1 mapping with a specific systemd target. Unfortunately, there is no good way to do the same for the user-defined runlevels like 2 and 4. If you make use of those it is suggested that you make a new named systemd target as /etc/systemd/system/your target
that takes one of the existing runlevels as a base (you can look at /usr/lib/systemd/system/graphical.target
as an example), make a directory /etc/systemd/system/your target.wants
, and then symlink the additional services from /usr/lib/systemd/system/
that you wish to enable.
Targets table
SysV Runlevel | systemd Target | Notes |
---|---|---|
0 | runlevel0.target, poweroff.target | Halt the system. |
1, s, single | runlevel1.target, rescue.target | Single user mode. |
2, 4 | runlevel2.target, runlevel4.target, multi-user.target | User-defined/Site-specific runlevels. By default, identical to 3. |
3 | runlevel3.target, multi-user.target | Multi-user, non-graphical. Users can usually login via multiple consoles or via the network. |
5 | runlevel5.target, graphical.target | Multi-user, graphical. Usually has all the services of runlevel 3 plus a graphical login. |
6 | runlevel6.target, reboot.target | Reboot |
emergency | emergency.target | Emergency shell |
Change current target
In systemd targets are exposed via target units. You can change them like this:
# systemctl isolate graphical.target
This will only change the current target, and has no effect on the next boot. This is equivalent to commands such as telinit 3
or telinit 5
in Sysvinit.
Change default target to boot into
The standard target is default.target, which is aliased by default to graphical.target (which roughly corresponds to the old runlevel 5). To change the default target at boot-time, append one of the following kernel parameters to your bootloader:
-
systemd.unit=multi-user.target
(which roughly corresponds to the old runlevel 3), -
systemd.unit=rescue.target
(which roughly corresponds to the old runlevel 1).
Alternatively, you may leave the bootloader alone and change default.target. This can be done using systemctl:
# systemctl enable multi-user.target
The effect of this command is output by systemctl; a symlink to the new default target is made at /etc/systemd/system/default.target
. This works if, and only if:
[Install] Alias=default.target
is in the target's configuration file. Currently, multi-user.target and graphical.target both have it.
Journal
systemd has its own logging system called the journal; therefore, running a syslog daemon is no longer required. To read the log, use:
# journalctl
By default (when Storage=
is set to auto
in /etc/systemd/journald.conf
), the journal writes to /var/log/journal/
. The directory /var/log/journal/
is a part of the systemd package. If you or some program delete that directory, systemd will not recreate it automatically; however, it will be recreated during the next update of the systemd package. Until then, logs will be written to /run/systemd/journal
, and logs will be lost on reboot.
/var/log/journal/
resides in a btrfs filesystem you should consider disabling Copy-on-Write for the directory:
# chattr +C /var/log/journal
Filtering output
journalctl allows you to filter the output by specific fields.
Examples:
Show all messages from this boot:
# journalctl -b
However, often one is interested in messages not from the current, but from the previous boot (e.g. if an unrecoverable system crash happened). Currently, this feature is not implemented, though there was a discussion at systemd-devel@lists.freedesktop.org (September/October 2012).
As a workaround you can use at the moment:
# journalctl --since=today | tac | sed -n '/-- Reboot --/{n;:r;/-- Reboot --/q;p;n;b r}' | tac
provided, that the previous boot happened today. Be aware that, if there are many messages for the current day, the output of this command can be delayed for quite some time.
journalctl -b
now takes arguments such as -0
for the last boot or a boot id. E.g. journalctl -b -3
will show all messages from the fourth to last boot.Follow new messages:
# journalctl -f
Show all messages by a specific executable:
# journalctl /usr/lib/systemd/systemd
Show all messages by a specific process:
# journalctl _PID=1
Show all messages by a specific unit:
# journalctl -u netcfg
See man 1 journalctl
, man 7 systemd.journal-fields
, or Lennert's blog post for details.
Journal size limit
If the journal is persistent (non-volatile), its size limit is set to a default value of 10% of the size of the respective file system. For example, with /var/log/journal
located on a 50 GiB root partition this would lead to 5 GiB of journal data. The maximum size of the persistent journal can be controlled by SystemMaxUse
in /etc/systemd/journald.conf
, so to limit it for example to 50 MiB uncomment and edit the corresponding line to:
SystemMaxUse=50M
Refer to man journald.conf
for more info.
Journald in conjunction with syslog
Compatibility with classic syslog implementations is provided via a socket /run/systemd/journal/syslog
, to which all messages are forwarded. To make the syslog daemon work with the journal, it has to bind to this socket instead of /dev/log
(official announcement). The syslog-ng package in the repositories automatically provides the necessary configuration.
# systemctl enable syslog-ng
A good journalctl tutorial is here.
Troubleshooting
Shutdown/reboot takes terribly long
If the shutdown process takes a very long time (or seems to freeze) most likely a service not exiting is to blame. systemd waits some time for each service to exit before trying to kill it. To find out if you are affected, see this article.
Short lived processes do not seem to log any output
If journalctl -u foounit
does not show any output for a short lived service, look at the PID instead. For example, if systemd-modules-load.service
fails, and systemctl status systemd-modules-load
shows that it ran as PID 123, then you might be able to see output in the journal for that PID, i.e. journalctl -b _PID=123
. Metadata fields for the journal such as _SYSTEMD_UNIT and _COMM are collected asynchronously and rely on the /proc
directory for the process existing. Fixing this requires fixing the kernel to provide this data via a socket connection, similar to SCM_CREDENTIALS.
Diagnosing boot problems
Boot with these parameters on the kernel command line:
systemd.log_level=debug systemd.log_target=kmsg log_buf_len=1M
Disabling application crash dumps journaling
To get back normal core dump files, edit the following file in order to overwrite the settings from /lib/sysctl.d/
:
/etc/sysctl.d/49-coredump.conf
kernel.core_pattern = core kernel.core_uses_pid = 0
Then run:
# /usr/lib/systemd/systemd-sysctl
As before, you also need to "unlimit" the core files size in the shell:
$ ulimit -c unlimited
See sysctl.d and the documentation for /proc/sys/kernel for more information.
See also
- Official web site
- Wikipedia article
- Manual pages
- systemd optimizations
- FAQ
- Tips and tricks
- systemd for Administrators (PDF)
- About systemd on Fedora Project
- How to debug systemd problems
- Two part introductory article in The H Open magazine.
- Lennart's blog story
- Status update
- Status update2
- Status update3
- Most recent summary
- Fedora's SysVinit to systemd cheatsheet