Как написать автоматически исходящий скрипт оболочки в /etc/profile

Вычислить InactiveEnterTimestamp - InactiveExitTimestamp

Время активации (в секундах) является результатом:

(ActiveEnterTimestampMonotonic - InactiveExitTimestampMonotonic) / 1e6

См. Функцию analysis_plot в файле analysis.c для подробностей.

Но у вас должно быть RemainAfterExit = yes в вашем отряде, чтобы получить ActiveEnterTimestampMonotonic .

Вы можете вычислить ExecMainExitTimestampMonotonic - ExecMainStartTimestampMonotonic в PostStartExec без RemainAfterExit .

например. читая их через интерфейс D-Bus в Python.

Вы можете использовать systemctl для извлечения этих значений:

$ systemctl show -p InactiveExitTimestampMonotonic -p ActiveEnterTimestampMonotonic unit
InactiveExitTimestampMonotonic=44364325621
ActiveEnterTimestampMonotonic=44369331083

Согласно Обещанию стабильности интерфейса :

The stable interfaces are:

...

The command line interface of systemctl, loginctl, journalctl.
We will make sure that scripts invoking these commands will continue
to work with future versions of systemd. Note however that the output
generated by these commands is generally not included in the promise,
unless it is documented in the man page. Example: the output of
"systemctl status" is not stable, but the one of "systemctl show" is,
because the former is intended to be human readable and the latter
computer readable, and this is documented in the man page.

Моя конечная цель - иметь возможность отслеживать, сколько времени каждый активация службы занимает, и вы получите предупреждение, если это займет слишком много времени

Вы можете установить TimeoutStartSec и OnFailure :

TimeoutStartSec= 

Configures the time to wait for start-up. If a daemon service does
not signal start-up completion within the configured time, the
service will be considered failed and will be shut down again.

OnFailure=

A space-separated list of one or more units that are activated when
this unit enters the "failed" state.

или не запускались в течение длительного времени

Вы может извлечь время последнего успеха из журнала:

 journalctl -u your-service MESSAGE='Started your-service.service.'

Но вы должны включить постоянное хранение сообщений журнала.

4
24.06.2018, 00:31
1 ответ

/etc/profile — это файл. Отсюда и ошибка при попытке создать /etc/profile/foo.sh.

/etc/profile.d— это каталог, о котором вы думаете. Скрипты, размещенные там, загружаются при входе в систему. В вашем примере вы хотите создать /etc/profile.d/foo.sh.

Логика скрипта, лежащая в основе этого, и то, как это реализовано, можно увидеть ниже. Аналогичный код есть в /etc/profile, /etc/bashrc, /etc/csh.cshrcи /etc/csh.login.

$ grep -A 8 ^for.*profile.d /etc/profile
for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
           . "$i"
        else
           . "$i" >/dev/null
        fi
    fi
done
$

Пример создания и вызова такого скрипта:

# echo id >/etc/profile.d/foo.sh
# su - steve
Last login: Sat Jun 23 21:44:41 UTC 2018 on pts/0
uid=1000(steve) gid=1001(steve) groups=1001(steve),4(adm),39(video),1000(google-sudoers) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$

Дополнительная информация на Что делают сценарии в /etc/profile.d?

10
27.01.2020, 20:47

Теги

Похожие вопросы