Показ дописів із міткою systemd. Показати всі дописи
Показ дописів із міткою systemd. Показати всі дописи

19.08.13

Fedora 17 Boot Optimization (from 15 to 2.5 seconds)

This article shows how to reduce boot time for Fedora 17.
The target is to get a fast booting system with NetworkManager running and gdm displaying the login screen as fast as possible.
The system I use here is a Lenovo T420s (2x2x Intel(R) Core(TM) i5-2540M CPU @ 2.60GHz) with an INTEL SSDSA2BW160G3L harddrive.
First we choose a manual disk layout and use primary partitions and format them with ext4. In my case this results in:
sda1 ext4 /boot
sda2 swap
sda3 ext4 /
After the first boot, setup of the user, etc. and 2 reboots (always reboot 2 times, before taking the measurement, because readahead needs to adapt to the changed boot process).
First we update everything, prelink for speed and install systemd-analyze.
$ sudo yum update
$ sudo /etc/cron.daily/prelink
$ sudo yum install systemd-analyze
After the reboots, I get:
# systemd-analyze
Startup finished in 1413ms (kernel) + 2911ms (initramfs) + 10593ms (userspace) = 14918ms
The next step is to disable the initramfs, because the kernel can boot from an ext4 partition without it. Because I know how to rescue my system, I can set the root device directly to sda3 and tell the kernel which filesystem type to use. My /etc/grub2.cfg looks like this:
 linux /vmlinuz-3.3.7-1.fc17.x86_64 root=/dev/sda3 rootfstype=ext4 quiet libahci.ignore_sss=1 raid=noautodetect
#       initrd /initramfs-3.3.7-1.fc17.x86_64.img
"raid=noautodetect" and "libahci.ignore_sss=1" saves some time for the kernel initialization.
Startup finished in 1640ms (kernel) + 13043ms (userspace) = 14684ms
Because I don't use any LVM, RAID or encrypted devices, I can safely turn off all nearly all fedora-*storage* services. Additionally I turn off the plymouth boot splash, because I want speed and not eye candy. To turn off these services, we use the "systemctl mask" command. A bonus with that mechanism is, that no rpm %post script turns them on automatically.
$ cd /lib/systemd/system
$ for i in fedora*storage* plymouth-*.* lvm2-monitor.* mdmonitor*.*; do sudo systemctl mask $i;done
It seems there are still some SysV initscripts left, so we turn them off:
$ for i in livesys livesys-late spice-vdagentd ; do sudo chkconfig $i off;done
Seems like we saved half of the time in userspace:
Startup finished in 1640ms (kernel) + 6556ms (userspace) = 8197ms
From now on, you really have to know what you are doing and how to revert your actions. To compare Fedora 17 with e.g. Ubuntu, I will now turn off all services except NetworkManager. The result will be a Linux system without mail, firewall, printing, the abrt tools, avahi, some mountpoints, rsyslog, irqbalance, and selinux security.
$ cd /lib/systemd/system
$ for i in abrt*.service auditd.service avahi-daemon.* bluetooth.* dev-hugepages.mount dev-mqueue.mount \
      fedora-configure.service fedora-loadmodules.service fedora-readonly.service ip6tables.service \
      iptables.service irqbalance.service mcelog.service rsyslog.service sendmail.service sm-client.service \
      sys-kernel-config.mount sys-kernel-debug.mount; do \
    sudo systemctl mask $i; \
  done
To disable selinux, edit /etc/selinux/config and add "selinux=0" to the kernel command line. My /etc/grub2.cfg now looks like this:
 linux /vmlinuz-3.3.7-1.fc17.x86_64 root=/dev/sda3 rootfstype=ext4 libahci.ignore_sss=1 raid=noautodetect selinux=0
#       initrd /initramfs-3.3.7-1.fc17.x86_64.img
Now we are really fast!
$ systemd-analyze
Startup finished in 1329ms (kernel) + 1596ms (userspace) = 2926ms
I also like the idea of automounting (systemd's automount feature was an idea of mine :-). So I turn /boot in a "mount on demand" mountpoint. Also having /tmp as a tmpfs is one way to reduce disk activity (useful for e.g. a slow flash disk).
My resulting /etc/fstab looks like this:
/dev/sda3  /                       ext4    defaults        1 1
/dev/sda1  /boot                   ext4    noauto,comment=systemd.automount     1 2
/dev/sda2  swap                    swap    defaults        0 0
tmpfs      /tmp                    tmpfs   defaults        0 0
This only saved a little bit of time, but still:
$ systemd-analyze
Startup finished in 1342ms (kernel) + 1426ms (userspace) = 2769ms
Because NetworkManager is started also by the graphical login target, I can remove it from the multi-user target and it will be started in parallel to the gdm lo)gin screen.
$ sudo rm  /etc/systemd/system/multi-user.target.wants/NetworkManager.service
This will shave of a few milliseconds:
$ systemd-analyze 
Startup finished in 1323ms (kernel) + 1279ms (userspace) = 2603ms
To see the difference readahead makes for the system, I turn it off temporarily and reboot
$ cd /lib/systemd/system
$ for i in *readahead*; do sudo systemctl mask $i;done
Which will give us:
$ systemd-analyze 
Startup finished in 1336ms (kernel) + 1210ms (userspace) = 2547ms
This time is a little bit misleading. Although it seems faster, the real time until the login screen is displayed is taking longer. So a fair comparison would involve a stopwatch.
$ sudo dracut -f
Here is the time with readahead and the initramfs turned back on:
$ systemd-analyze 
Startup finished in 803ms (kernel) + 2217ms (initramfs) + 1018ms (userspace) = 4039ms
Of course, this can be optimzed also, when we build the initramfs without plymouth and in host-only mode.
$ sudo dracut -f -H -o plymouth
After a reboot we get the stunning result of:
$ systemd-analyze 
Startup finished in 612ms (kernel) + 499ms (initramfs) + 1330ms (userspace) = 2443ms
The nice thing about "systemctl mask" is, that you always unmask it via "systemctl unmask" and enable those default services, which you really need.
Have fun and happy rebooting!
And don't forget to reboot twice to let the readahead optimization kick in!

13.01.13

Запуск собственных скриптов systemd


Через rc.local

Как и ранее, чтобы запустить какой-то скрипт при загрузке системы, вы можете поместить его в файл /etc/rc.d/rc.local. Однако стоит учесть специфику запуска этого скрипта в systemd.
service-файл отвечающего за него юнита выглядит следующим образом:
$ cat /lib/systemd/system/rc-local.service
[Unit]
Description=/etc/rc.d/rc.local Compatibility
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
SysVStartPriority=99
Отсюда видно, во-первых, что файл /etc/rc.d/rc.local обязан быть исполняемым.
А во-вторых, видно, что сервис rc-local имеет зависимость только от цели network.target. Параметр SysVStartPriority=99 отвечает только за приоритет по сравнению с другими sysVinit-скриптами, которых в Fedora становится все меньше. С учетом параллельной загрузки это означает, что скрипт, который вы разместите в файле rc.local может быть запущен слишком рано, например, до старта нужных сервисов. Поэтому, если вы разместите в этом файле скрипты перезапуска апача, то, с большой вероятностью, они не сработают.
В версиях до Fedora 17, не было зависимости от network.target, так что, там этот скрипт запускался практически в самом начале.

С помощью systemd-юнита

Более естественный для systemd способ запускать скрипты - это создание своего собственного юнита.
Просто создайте файл /etc/systemd/system/my_stuff.service со следующим текстом:
[Unit]
Description=Run my stuff  
Requires=network.target   
After=network.target 
 
[Service]
Type=oneshot
RemainAfterExit=True
ExecStart=/some/script --with-some-parameters
ExecStart=/some/other/script
 
[Install]
WantedBy=multi-user.target
Здесь Requires - указывает цель, после которой необходимо запустить сервис, After означает, что сеть должна быть полностью запущена к моменту старта, WantedBy - цель, для которой запускается сервис. В ExecStart должен быть указан полный путь к скрипту или исполняемому файлу, поскольку переменная PATH не используется.
multi-user.target - это аналог init 3 в sysVinit. Подробнее о реализации runlevel-ов в systemd, можно прочесть по ссылке.
В такой конфигурации скрипты будут запускаться сразу после запуска сети и старта всех интерфейсов. Однако systemd позволяет гораздо более гибкую настройку. Например, для выполнения скриптов после запуска графического DM можно использовать After: systemd-user-sessions.service
Небольшой пример: После появления облачного хранилища Яндекс.Диск, захотелось автоматически монтировать его в файловую систему через davfs2 (с заранее положенными логином и паролем в /etc/davfs2/secrets). Прописывание в fstab не дало результатов, как и прописывание в rc.local, поскольку в Fedora 16 оба они обрабатывались ещё до поднятия сети. А вот создание модуля по вышеприведённому образцу решило проблему.

Дополнительно

Для диагностики сервиса используйте команду
systemctl status rc-local.service
или загляните в файл /var/log/boot.log (он появится если в параметрах загрузки убрать quiet, см. Grub2).

03.09.12

rtorrent.servise

pacman -S tmux
[Unit]
Description=rTorrent for dima

[Service]
ExecStart=/usr/bin/tmux new-session -d -s rtorrent rtorrent
Type=forking
User=dima

[Install]
WantedBy=multi-user.target