Compare commits

..
20 Commits
Author SHA1 Message Date
Joachim Wiberg c94fd9c495 initctl: add the settings of a service to the JSON status
initctl -j status had the state of a service but little of how it is
set up.  A program reading it could not tell how the service is
stopped, what scripts it runs, or how it signals readiness.

Add the settings: stop, reload, notify, remain, scripts, directories,
cgroup-config, rlimits, log or tty, provides, conflicts, if, groups,
capabilities, pam, name, id, protected, and nowarn.  The restart
object also gets sec, respawn, and oncrash, and the state Finit keeps
for its own use goes in internal:

    "stop": {
      "signal": "SIGTERM",
      "timeout": 3,
      "scope": "pgroup"
    },
    "scripts": {
      "exec-stop-post": { "command": "/bin/true", "timeout": 7 }
    },

initctl reads the status over D-Bus first, so each setting is also a
property of org.finit.Service1.  The new test checks that the JSON is
the same over D-Bus as over the initctl socket.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 21:51:23 +01:00
Joachim Wiberg 9fa50746a7 initctl: add what was missing from the JSON status
initctl -j status is for other programs and should have all there is,
the plain view is the one kept short.  It was the other way around:
the restart counter and restart-max were only in the plain view, and
the restart delay of restart-max-sec was not in the JSON either.

Add a restart object:

    "restarts": 7,
    "restart": {
      "count": 4,
      "max": -1,
      "delay": 160,
      "limit": 300
    },

Also add manual and started, and give starts for all services, not
only those with manual-start.  The restarts total stays where it is.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:43 +01:00
Joachim Wiberg 308287923d initctl: show the restart delay of a service with restart-max-sec
With restart-max-sec the delay before the next restart varies, and
nothing showed what it was or how far it could grow.

Show both in initctl status, for a service that has the setting:

       Restarts : 7 (4/-1)
     Restart in : 160 sec (max 300)

Add the D-Bus properties RestartDelay and RestartDelayMax for it, so
the status is the same when initctl goes over D-Bus.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:43 +01:00
Joachim Wiberg 7f652770e3 test: list what to install to run the test suite
A new machine lacks more than the build dependencies.  Without the
uidmap package every test fails:

    unshare: failed to execute newuidmap: No such file or directory

List the packages for Debian, Ubuntu, and Linux Mint, and what each is
used for.  The build instructions asked for libite and libuEv v2.2.0,
configure wants v2.6.1 and v2.4.1.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:42 +01:00
Joachim Wiberg aae640b8f3 service: spell the restart_sec: option restart-sec:
restart_sec: was the only setting in snake_case.  Every other option
of the line-based format is in kebab-case, and so is the block format,
restart-sec = SEC.

Take restart-sec: and keep restart_sec: as an alias, so a .conf from
an older Finit loads as before:

    service restart-sec:10 foo -- Foo daemon

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:42 +01:00
Joachim Wiberg 62bd5f4892 service: add restart-max-sec, a limit for the restart back-off
The delay between restarts of a crashing service is fixed: two
seconds, then five, or restart-sec if that is longer.  A service that
should be retried quickly at first and then less and less often, e.g.
a modem dialer, cannot be set up.

Add restart-max-sec, in the block format and as the restart-max-sec:
token:

    service dialer {
        restart         = "always"
        restart-sec     = 10
        restart-max-sec = 300
        command         = "dialer"
    }

When set, the delay doubles for each restart, from restart-sec up to
the limit: 10, 20, 40, 80, 160, 300.  Without restart-sec the first
restart is at once, then after 2, 4, 8 seconds.  The delay follows the
restart counter, so it comes down again as the counter ages.  With
restart always the counter stops where the delay peaks.

Fixes #306

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:42 +01:00
Joachim Wiberg bba286036e service: save the configured restart delay when registering
The configured restart delay was saved at the first restart, when the
restart counter went from zero to one, and restored when a restart
succeeded.  The counter ages back to zero while the service runs.  If
it did so right after a restart and the service crashed again, the
back-off delay was saved over the configured one.  From then on the
first restart after a crash waited two or five seconds, until the next
reload.

Save it once, when the service is registered.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:41 +01:00
Joachim Wiberg 644279cd72 service: stop the restart counter of restart always from overflowing
The restart counter is a char, and with restart always nothing stops
it.  A service restarted more often than the counter ages wrapped it
after 127 restarts, 255 on Arm.  initctl status then showed a negative
count and the back-off fell back to two seconds.

Make the counter an int that stops at INT_MAX.  With restart always it
stops at 10, the default restart-max.  The back-off peaks at half of
that, and from 10 the counter ages back within the hour.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:41 +01:00
Joachim Wiberg 4e1b0d4fbe service: start restart always at two seconds between restarts
A crashing service with restart always waited five seconds before
every restart.  It should wait two seconds for the first five, like a
service with the default restart-max:

    service foo {
        restart = "always"
        command = "foo"
    }

The back-off starts after half of restart-max attempts.  For restart
always restart-max is -1, so half of it was zero and the back-off
began with the first restart.  Use the default restart-max instead.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-19 20:39:40 +01:00
Joachim Wiberg 631baab756 api: acknowledge reboot, halt, and poweroff
Finit carried out a reboot, halt, or poweroff requested over the
initctl socket, but replied with a NACK.  The command printed an
empty line and fell back to signalling PID 1.

The result was never set from the action taken.  Return what
shutdown_now() returns.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 11:00:49 +01:00
Joachim Wiberg 20c422af69 shutdown: add time argument, wall message, and cancel
shutdown ignored everything after its options, so a delayed shutdown
went down right away:

    shutdown -r +10 "Upgrading, back in five"

Take a time, now, +MIN, or the next HH:MM, and an optional message.
Finit keeps the countdown, so it survives logging out:

  - warns logged-in users at 60, 30, 15 and 10 minutes left, then
    every minute from five, and on the console
  - writes the message to /etc/nologin from five minutes before,
    leaving one already in place alone
  - shutdown -c cancels, and a new shutdown TIME replaces it

Without a time, or with now and no message, shutdown acts right away
as before.  An immediate reboot, halt, or power-off, also over D-Bus,
cancels a scheduled one.  The warnings are written by a child, reading
utmp and closing a serial tty can block.

Fixes #149

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 11:00:49 +01:00
Joachim Wiberg d51f521bf8 service: add stop-scope, which processes a stop applies to
When the main process of a service exits, Finit sends SIGKILL to its
process group.  That killed the action script of avahi-autoipd, which
it runs on SIGTERM to deconfigure the interface, before it was done.

Add stop-scope, in the block format and as the stop-scope: token:

    service avahi-autoipd {
        stop-scope = "process"
        command    = "avahi-autoipd eth0"
    }

  - pgroup: the stop signal to the main process, SIGKILL to its
    process group when it exits, as before and the default
  - process: only the main process
  - cgroup: the stop signal to all of the cgroup, SIGKILL to the rest
  - mixed: the stop signal to the main process, SIGKILL to the rest of
    the cgroup, like systemd's KillMode=mixed

SIGKILL to a cgroup uses cgroup.kill when the kernel has it.  Without
a cgroup, cgroup and mixed fall back to the process group.  Services
in the same .conf file share a cgroup, Finit warns when one of them
uses a cgroup scope.

Fixes #413

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 11:00:48 +01:00
Joachim Wiberg 35c313c2fa service: keep a stop of a forking service waiting for its PID file
Stopping a forking service after its start script had exited, but
before the daemon had written its PID file, did not hold.  When the
PID file showed up, the service was reported running again and the
daemon was left alone:

    initctl stop ext

service_forked() cleared any block on the service, the user's stop
included.

Keep a user stop, and let the state machine stop the late daemon of
a service no longer enabled.  The service is briefly RUNNING on its
way to STOPPING, so service/NAME/running blinks on and off.

Follow-up to #452

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 07:49:50 +01:00
Joachim Wiberg a1706e8ebd pidfile: don't let a stopped service claim a PID file
A stopped service with a daemon-owned PID file came back as running
when another process wrote that file, e.g., a container started by
hand:

    sudo podman start dash

turned container:dash from stopped to running in initctl, with the
podman PID adopted, moved to the service's cgroup, and its conditions
set.  The same happened to a service waiting for its conditions.

The plugin acted on any new or changed PID file, only skipping
services stopping or running scripts, and service_forked() then
cleared the stop.

Only let a service that is starting or running claim its PID file.

Fixes #452

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:44:45 +01:00
Joachim Wiberg a162551896 service: bind the systemd notify socket before fork
A notify:systemd service that calls sd_notify() early could lose its
READY=1 and never become ready.  Seen with udevd in an initramfs.

The socket address contained the PID of the service, so it was bound
in the parent after fork(), racing the service.

Let the kernel pick a unique abstract address instead, bound before
fork(), and pass it in NOTIFY_SOCKET.

Fixes #505

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:26 +01:00
Joachim Wiberg 14fd315f38 keventd: touch the PID file after SIGHUP
After a SIGHUP, from initctl reload or a changed service, Finit waits
for a pid-notify daemon to recreate or touch its PID file to reassert
readiness.  keventd only reloaded its rules, so with a daemon-owned
PID file it never did.

Touch it with pidfile() after reloading the rules, once keventd has
created it.  With -c that is after the coldplug queue has drained.

Fixes #503

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:26 +01:00
Joachim Wiberg bf42811a13 service: drop a service's group when the configuration drops it
Changing a service from @alice:wheel to @alice, or removing group from
a block, and reloading kept the service running as group wheel, also
after a restart.

The group is only set when the configuration has one, and on reload
the service is updated in place, so the old one stayed.

Clear it before parsing, like a new service gets it.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:25 +01:00
Joachim Wiberg de73b06415 service: lift the limit of four supplementary groups
A service listing more than four supplementary groups, in extra-groups
or as @user:group,sup1,sup2,..., got only the first four:

    too many supplementary groups, max 4

The names were stored in a fixed array of four.  It was also only
reset when the new configuration listed groups, so groups dropped from
a service lingered until reboot.

Store the list as one string, split when the service starts, and set
it on every (re)registration.  A list longer than 511 characters drops
the name it cuts off, which may otherwise match another group.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-17 06:21:24 +01:00
Joachim Wiberg 8451c4087a Merge pull request #522 from firasuke/master
doc: list libcap as a dependency
2026-11-14 12:14:04 +01:00
Firas Khana e280569941 doc: list libcap as a dependency 2026-11-14 13:44:58 +03:00
36 changed files with 2318 additions and 157 deletions

No files matched your search

+56
View File
@@ -8,6 +8,31 @@ All relevant changes are documented in this file.
### Changes ### Changes
- `shutdown` now takes a time, `now`, `+MIN`, or `HH:MM`, and a message.
Finit warns logged-in users as the time approaches, refuses new logins
from five minutes before, and `shutdown -c` cancels. Issue #149
- The `restart_sec:` option of the line-based format is now spelled
`restart-sec:`, kebab-case like every other setting. The old spelling
is still accepted
- `initctl -j status` now has all `initctl` gets from Finit about a
service. New is a `restart` object with the restart counter,
`restart-max`, the current restart delay and its limit, and `manual`
and `started`. `starts` is now there for all services, not only those
with `manual-start`. Also new are the settings of the service: `stop`,
`reload`, `notify`, `remain`, `scripts`, `directories`, `log` or `tty`,
`cgroup-config`, `rlimits`, `provides`, `conflicts`, `if`, `groups`,
`capabilities`, `pam`, `name`, `id`, `protected`, `nowarn`, and the
state Finit keeps for its own use in `internal`, see
[Commands & Status](initctl.md), with a D-Bus property for each
- Add `restart-max-sec`, a limit for the delay between restarts of a
crashing service. When set, the delay doubles for each restart, from
`restart-sec` up to the limit, and comes down again as the service keeps
running. `initctl status` shows the current delay and the limit, also
available as the D-Bus properties `RestartDelay` and `RestartDelayMax`.
Issue #306
- Add `stop-scope`, which processes a stop applies to: `pgroup`, the process
group of the main process (default), `process`, only the main process,
`cgroup`, the cgroup of the service, or `mixed` like systemd. Issue #413
- keventd is now a full device manager, promoted from the power supply - keventd is now a full device manager, promoted from the power supply
monitor it was in v4, and the device management defaults have swapped: monitor it was in v4, and the device management defaults have swapped:
keventd is enabled by default (`--without-keventd` opts out, libblkid is keventd is enabled by default (`--without-keventd` opts out, libblkid is
@@ -143,6 +168,13 @@ All relevant changes are documented in this file.
- Service `user:` and `group:` names, including supplementary groups, can - Service `user:` and `group:` names, including supplementary groups, can
now be up to 63 characters, up from 15. Longer names were silently now be up to 63 characters, up from 15. Longer names were silently
truncated before the lookup, so the service never started. By Anees Rehman truncated before the lookup, so the service never started. By Anees Rehman
- A service can have more than four supplementary groups, `extra-groups` or
`@user:group,sup1,sup2,...`. The list may now be up to 511 characters.
Groups dropped from a service's configuration are now also dropped the
next time it starts, before they lingered until reboot
- Fix a service's group lingering after it was dropped from the
configuration, e.g. `@alice:wheel` changed to `@alice` kept running as
`wheel` until reboot
- `stop:` and `reload:` scripts take a timeout of their own, `stop:5,/path`, - `stop:` and `reload:` scripts take a timeout of their own, `stop:5,/path`,
defaulting to the kill delay as before. Such a line used to crash Finit at defaulting to the kill delay as before. Such a line used to crash Finit at
config load config load
@@ -156,9 +188,33 @@ All relevant changes are documented in this file.
- Fix #512: `--` in the `command` of a block-format .conf, it was taken as the - Fix #512: `--` in the `command` of a block-format .conf, it was taken as the
start of the description, so `command = "cmd -- arg"` ran `cmd` with start of the description, so `command = "cmd -- arg"` ran `cmd` with
description `arg`. Found by Alexandru Paniș description `arg`. Found by Alexandru Paniș
- Fix #503: keventd did not touch its PID file after SIGHUP, so with a
daemon-owned PID file Finit never saw it reassert readiness after a
reload. Reported by Aaron Andersen
- Fix #505: a `notify:systemd` service could send `READY=1` before Finit
had bound the notify socket, losing it, so the service never became
ready. Seen with udevd in an initramfs. Reported by Aaron Andersen
- Fix #452: a stopped or waiting service with a daemon-owned PID file was
reported as running, with its conditions set, when another process wrote
that PID file, e.g., a container started by hand with podman. Found by
Mattias Walström
- Fix `initctl stop` of a forking service before it had written its PID
file. The PID file showing up later undid the stop and the service was
reported running. Now the late daemon is stopped instead
- Fix `reboot`, `halt`, and `poweroff` being refused by Finit over the
initctl socket, although carried out. The commands then also fell
back to signalling PID 1
- Fix a command whose name starts like a service option, e.g. `logger` or - Fix a command whose name starts like a service option, e.g. `logger` or
`pidof`. It was taken as the `log` or `pid` option and the next argument `pidof`. It was taken as the `log` or `pid` option and the next argument
ran as the command, which also broke the `logger` example in finit.conf(5) ran as the command, which also broke the `logger` example in finit.conf(5)
- Fix the delay before the first restart of a crashing service, it could
grow to the back-off delay and stay there until the next reload
- Fix the restart counter of a service with `restart = "always"`, nothing
stopped it and it overflowed after 127 restarts, 255 on Arm. It now
stops at 10, where the back-off has long since peaked, and ages from
there
- Fix `restart = "always"` skipping the initial two second delay between
restarts, every restart waited five seconds
- Reject a .conf file that declares the same block title twice. The title is - Reject a .conf file that declares the same block title twice. The title is
the service identity and libConfuse merges two sections sharing one, so the the service identity and libConfuse merges two sections sharing one, so the
file loaded as a single service holding a mix of both declarations, file loaded as a single service holding a mix of both declarations,
+12 -2
View File
@@ -15,6 +15,10 @@ and `/dev/disk/by-label/` symlinks after. keventd is enabled by
default, so this is a hard requirement unless you build with default, so this is a hard requirement unless you build with
`--without-keventd`. `--without-keventd`.
Linux capabilities support for services is also built by default. It needs
[libcap][] (-lcap); the build falls back to no capabilities support when that
library is missing, or with `--disable-libcap`.
PAM session support for services is built by default. It needs PAM session support for services is built by default. It needs
[Linux-PAM][] (-lpam); the build falls back to no PAM support when that [Linux-PAM][] (-lpam); the build falls back to no PAM support when that
library is missing. A static build, `--enable-static`, disables PAM library is missing. A static build, `--enable-static`, disables PAM
@@ -33,10 +37,11 @@ too, since libpam loads its modules with `dlopen()`.
The configure script checks for all dependencies, including the correct The configure script checks for all dependencies, including the correct
version of the above mentioned libraries. Currently required versions: version of the above mentioned libraries. Currently required versions:
- libite v2.2.0, or later - libite v2.6.1, or later
- libuEv v2.2.0, or later - libuEv v2.4.1, or later
- libConfuse v3.3, or later - libConfuse v3.3, or later
- libblkid, any version, when keventd is enabled - libblkid, any version, when keventd is enabled
- libcap, any version, unless `--disable-libcap` is given
Configure Configure
@@ -59,6 +64,10 @@ Below are a few of the main switches to configure:
built-ins (.o files) and all external libraries, except the C library built-ins (.o files) and all external libraries, except the C library
will be linked statically. will be linked statically.
* `--disable-libcap`: Opt out of Finit's built-in Linux capabilities support,
enabled by default. Needs libcap, and falls back to disabled when it is
missing. See [Linux Capabilities](config/capabilities.md)
* `--disable-pam`: Opt out of Finit's built-in PAM session support, * `--disable-pam`: Opt out of Finit's built-in PAM session support,
enabled by default, which lets a service declare `pam = "name"` and enabled by default, which lets a service declare `pam = "name"` and
run inside a session set up from `/etc/pam.d/name`. Needs libpam, run inside a session set up from `/etc/pam.d/name`. Needs libpam,
@@ -298,4 +307,5 @@ it only for debugging start up issues when Finit crashes.
[libite]: https://github.com/troglobit/libite [libite]: https://github.com/troglobit/libite
[libConfuse]: https://github.com/libconfuse/libconfuse [libConfuse]: https://github.com/libconfuse/libconfuse
[util-linux]: https://github.com/util-linux/util-linux [util-linux]: https://github.com/util-linux/util-linux
[libcap]: https://sites.google.com/site/fullycapable/
[Linux-PAM]: https://github.com/linux-pam/linux-pam [Linux-PAM]: https://github.com/linux-pam/linux-pam
+22
View File
@@ -11,3 +11,25 @@ For compatibility reasons Finit listens to the same set of signals as
BusyBox init. This is not 100% compatible with SysV init, but clearly BusyBox init. This is not 100% compatible with SysV init, but clearly
the more common combination for Finit. For more details, see the the more common combination for Finit. For more details, see the
[Signal](signals.md) section. [Signal](signals.md) section.
Scheduled Shutdown
------------------
The `shutdown` command takes a time, and an optional message to warn
logged-in users with:
shutdown -r +10 "Upgrading to v5.0, back in five"
shutdown -h 23:30
shutdown -c
The time is `now`, `+MIN` minutes from now, at most a year, or the next
`HH:MM`. Finit keeps track of it, so it survives logging out. It counts
down the time left, changing the system clock does not move it. At 60, 30, 15 and 10
minutes left, and then every minute from five, Finit writes the warning
to the terminal of every logged-in user. From five minutes before, it
also creates `/etc/nologin`, with the message, to refuse new logins. A
`/etc/nologin` already in place is left alone.
A new `shutdown TIME` replaces the scheduled one, and `shutdown -c`
cancels it. Without a time, or with `now` and no message, `shutdown`
acts right away, as before.
+3 -2
View File
@@ -169,8 +169,9 @@ ps -o user,pid,cmd -p $(pidof nginx)
- Linux kernel 4.3+ (for ambient capabilities support) - Linux kernel 4.3+ (for ambient capabilities support)
- libcap library installed - libcap library installed
- Finit built with `--enable-libcap`, otherwise a `capabilities` list is - Finit built with libcap support (enabled by default unless `--disable-libcap`
ignored, with a warning is given or libcap was missing at build time), otherwise a `capabilities` list
is ignored, with a warning
## Limitations ## Limitations
+5 -2
View File
@@ -63,12 +63,14 @@ Service options
| `manual:yes` | `manual-start = true` | | `manual:yes` | `manual-start = true` |
| `remain:yes` | `remain-after-exit = true` | | `remain:yes` | `remain-after-exit = true` |
| `restart:always` / `restart:NUM` | `restart = "always"` / `restart-max = NUM` | | `restart:always` / `restart:NUM` | `restart = "always"` / `restart-max = NUM` |
| `restart_sec:SEC` | `restart-sec = SEC` | | `restart-sec:SEC` | `restart-sec = SEC` |
| `restart-max-sec:SEC` | `restart-max-sec = SEC` |
| `norestart` | `restart = "never"` | | `norestart` | `restart = "never"` |
| `respawn` | `respawn = true` | | `respawn` | `respawn = true` |
| `oncrash:reboot` | `oncrash = "reboot"` | | `oncrash:reboot` | `oncrash = "reboot"` |
| `halt:SIG` | `stop-signal = "SIG"` | | `halt:SIG` | `stop-signal = "SIG"` |
| `kill:SEC` | `stop-timeout = SEC` | | `kill:SEC` | `stop-timeout = SEC` |
| `stop-scope:SCOPE` | `stop-scope = "SCOPE"` |
| `pre:[TMO,]/script` | `exec-start-pre`, `exec-start-pre-timeout` | | `pre:[TMO,]/script` | `exec-start-pre`, `exec-start-pre-timeout` |
| `ready:[TMO,]/script` | `exec-start-ready`, and its `-timeout` | | `ready:[TMO,]/script` | `exec-start-ready`, and its `-timeout` |
| `stop:[TMO,]/script` | `exec-stop`, and its `-timeout` | | `stop:[TMO,]/script` | `exec-stop`, and its `-timeout` |
@@ -80,7 +82,8 @@ Service options
| `if:svc` / `if:<cond>` | `if = "svc"` / `if = "cond"`, no angle brackets | | `if:svc` / `if:<cond>` | `if = "svc"` / `if = "cond"`, no angle brackets |
| `tty:/dev/x` | `tty = "/dev/x"` | | `tty:/dev/x` | `tty = "/dev/x"` |
| `nowarn` | leading `-` on `command` or `envfile` | | `nowarn` | leading `-` on `command` or `envfile` |
| `restarttmo:` | dropped, was already an alias for `restart_sec:` | | `restart_sec:` | old spelling of `restart-sec:`, still accepted |
| `restarttmo:` | dropped, was already an alias for `restart-sec:` |
Repeated stanzas Repeated stanzas
---------------- ----------------
+44 -2
View File
@@ -176,8 +176,20 @@ following settings are available:
* `restart-sec = SEC` -- number of seconds before Finit tries to * `restart-sec = SEC` -- number of seconds before Finit tries to
restart a crashing service. The default is 2 seconds for the first restart a crashing service. The default is 2 seconds for the first
half of `restart-max` attempts, then a back-off to 5 seconds -- with half of `restart-max` attempts, then a back-off to 5 seconds -- with
the default `restart-max` that is the first five retries. The the default `restart-max`, and with `restart = "always"`, that is the
greater of this configured value and the back-off is used first five retries. The greater of this configured value and the
back-off is used
* `restart-max-sec = SEC` -- replaces that back-off with a delay that
doubles for each restart, from `restart-sec` up to this limit. With
`restart-sec = 10` and `restart-max-sec = 300` Finit waits 10, 20,
40, 80, 160, and then 300 seconds. Without `restart-sec` the first
restart is at once, then after 2, 4, 8 seconds, and so on. A service
that stays up longer than the current delay is restarted after
`restart-sec` the next time it crashes, and the delay comes down
again the longer the service keeps running. `initctl status NAME`
shows the current delay and the limit, see below. Useful with
`restart = "always"`, for a service that should be retried forever,
only less and less often
* `restart = "always"` -- no upper limit on the number of times Finit * `restart = "always"` -- no upper limit on the number of times Finit
tries to restart a crashing service tries to restart a crashing service
* `restart = "never"` -- do not restart on failures. `false` is * `restart = "never"` -- do not restart on failures. `false` is
@@ -197,6 +209,15 @@ following settings are available:
* `oncrash = "script"` -- similarly, but instead of rebooting, call * `oncrash = "script"` -- similarly, but instead of rebooting, call
the `exec-stop-post` script with exit code `crashed`, see below the `exec-stop-post` script with exit code `crashed`, see below
With `restart-max-sec` set, `initctl status` shows the delay before the
next restart and its limit, here for a service that has crashed four
times in a row:
$ initctl status dialer
...
Restarts : 7 (4/-1)
Restart in : 160 sec (max 300)
Service directories Service directories
------------------- -------------------
@@ -259,6 +280,27 @@ down gracefully. If it has not been collected within 3 seconds,
* `stop-signal = "SIGPWR"` -- send this instead of `SIGTERM` * `stop-signal = "SIGPWR"` -- send this instead of `SIGTERM`
* `stop-timeout = 10` -- seconds to wait before `SIGKILL`, 1-300 * `stop-timeout = 10` -- seconds to wait before `SIGKILL`, 1-300
* `stop-scope = "process"` -- which processes are stopped, see below
The stop signal goes to the main process of the service. When that
exits, Finit sends `SIGKILL` to any processes it left behind in its
process group. This is the default, `stop-scope = "pgroup"`. Other
scopes:
* `process` -- only the main process, anything it leaves behind is
left alone, e.g. a script it started on its way down
* `cgroup` -- the stop signal goes to all processes in the cgroup of
the service, and `SIGKILL` to those still there when the main
process exits
* `mixed` -- the stop signal goes to the main process, and `SIGKILL`
to the rest of the cgroup when it exits
All services declared in the same .conf file share a cgroup, unless
given a [name of their own](cgroups.md#overriding-cgroup-leaf-names),
so `cgroup` and `mixed` reach them all, Finit warns about this. Without
cgroups, these two fall back to the process group. A forking daemon
usually leaves the process group of its start command, so only `cgroup`
and `mixed` reach what it leaves behind.
Some services need more than a signal: Some services need more than a signal:
+67
View File
@@ -187,10 +187,77 @@ All read-only; observable via `Properties.Get` and `Properties.GetAll`.
| `ExitStatus` | `u` | Raw `waitpid(2)` status from the last exit | | `ExitStatus` | `u` | Raw `waitpid(2)` status from the last exit |
| `RestartsTotal` | `u` | Restarts over the service's lifetime | | `RestartsTotal` | `u` | Restarts over the service's lifetime |
| `RestartMax` | `u` | Restart limit before the service is blocked | | `RestartMax` | `u` | Restart limit before the service is blocked |
| `RestartDelay` | `u` | Seconds before the next restart, should the service crash |
| `RestartDelayMax` | `u` | The `restart-max-sec` setting, 0 when not set |
| `Starts` | `u` | Times started, for `manual-start` units | | `Starts` | `u` | Times started, for `manual-start` units |
| `ManualStart` | `b` | `manual-start` set in the `.conf` | | `ManualStart` | `b` | `manual-start` set in the `.conf` |
| `Forking` | `b` | Daemon forks to background | | `Forking` | `b` | Daemon forks to background |
| `Started` | `b` | Run/task completed successfully | | `Started` | `b` | Run/task completed successfully |
| `Notify` | `s` | Readiness protocol: `none`, `pid`, `systemd`, or `s6` |
| `Remain` | `b` | `remain-after-exit` set in the `.conf` |
| `If` | `s` | The `if` setting, raw |
| `Provides` | `s` | Conditions from `provides`, comma separated |
| `Conflicts` | `s` | Services from `conflicts`, comma separated |
| `ExtraGroups` | `s` | Supplementary groups, comma separated |
| `Capabilities` | `s` | The `capabilities` setting, comma separated |
| `Pam` | `s` | PAM service name, empty when not set |
| `StopSignal` | `s` | Signal that stops the service, e.g. `SIGTERM` |
| `StopTimeout` | `u` | Seconds to wait for it to stop, before `SIGKILL` |
| `StopScope` | `s` | `pgroup`, `process`, `cgroup`, or `mixed` |
| `ReloadSignal` | `s` | `SIGHUP`, or `none` when a reload restarts the service |
| `RestartSec` | `u` | The `restart-sec` setting, 0 when not set |
| `Respawn` | `b` | `respawn` set in the `.conf` |
| `OnCrash` | `s` | `ignore`, `reboot`, or `script` |
| `RuntimeDir` | `s` | The `runtime-dir` setting, likewise for the four below |
| `StateDir` | `s` | |
| `CacheDir` | `s` | |
| `LogsDir` | `s` | |
| `ConfigDir` | `s` | |
| `RuntimeDirPreserve` | `s` | `no`, `restart`, or `yes` |
| `RuntimeDirMode` | `u` | Mode of the runtime directory, likewise for the four below |
| `StateDirMode` | `u` | |
| `CacheDirMode` | `u` | |
| `LogsDirMode` | `u` | |
| `ConfigDirMode` | `u` | |
| `Id` | `s` | The `:ID` part of the identity, empty when there is none |
| `Job` | `u` | Job number, internal |
| `OldPid` | `u` | PID of the previous run, internal |
| `Dirty` | `b` | Changed in the `.conf`, pending the next reload, internal |
| `Removed` | `b` | Gone from the `.conf`, pending removal, internal |
| `Starting` | `b` | Started, waiting for its PID file or readiness, internal |
| `Protected` | `b` | Built-in service, kept when the configuration is reloaded |
| `NoWarn` | `b` | No warning when the command is missing |
| `ReloadPropagate` | `b` | A reload of a dependency reloads this service too, `~` in its conditions |
| `CgroupName` | `s` | Control group the service joins, empty for the default |
| `CgroupConfig` | `s` | Its cgroup settings, `key:value` comma separated |
| `CgroupDelegate` | `b` | The service manages its own cgroup subtree |
| `Rlimits` | `s` | Resource limits as `name=soft:hard`, comma separated, a number or `unlimited` |
| `ExecStartPre` | `s` | Script, empty when not set, likewise for the five below |
| `ExecStartPreTimeout` | `u` | Seconds the script may run, one for each script |
| `ExecStartReady` | `s` | |
| `ExecStartReadyTimeout` | `u` | |
| `ExecStop` | `s` | |
| `ExecStopTimeout` | `u` | |
| `ExecStopPost` | `s` | |
| `ExecStopPostTimeout` | `u` | |
| `ExecReload` | `s` | |
| `ExecReloadTimeout` | `u` | |
| `ExecCleanup` | `s` | |
| `ExecCleanupTimeout` | `u` | |
| `Log` | `b` | Output is logged, not for a `tty` |
| `LogNull` | `b` | Output is discarded |
| `LogConsole` | `b` | Output goes to the console |
| `LogFile` | `s` | Log file, empty for syslog |
| `LogPriority` | `s` | Syslog facility and level, empty for the default |
| `LogIdentity` | `s` | Syslog identity, empty for the default |
| `TtyDevice` | `s` | Device of a `tty`, this and the below are empty or false for other types |
| `TtyBaud` | `s` | Baud rate, empty for the default |
| `TtyTerm` | `s` | The `TERM` to set |
| `TtyNoClear` | `b` | `noclear` set in the `.conf` |
| `TtyNoWait` | `b` | `nowait` set in the `.conf` |
| `TtyNoLogin` | `b` | `nologin` set in the `.conf` |
| `TtyNoTty` | `b` | `notty` set in the `.conf` |
| `TtyRescue` | `b` | `rescue` set in the `.conf` |
On every state transition the object also emits the standard On every state transition the object also emits the standard
`org.freedesktop.DBus.Properties.PropertiesChanged` signal: `State` `org.freedesktop.DBus.Properties.PropertiesChanged` signal: `State`
+111
View File
@@ -146,6 +146,117 @@ Apr 8 15:02:11 alpine authpriv.info dropbear[2634]: Child connection from 192.1
Apr 8 15:02:12 alpine authpriv.notice dropbear[2634]: Password auth succeeded for 'root' from 192.168.121.1:48576 Apr 8 15:02:12 alpine authpriv.notice dropbear[2634]: Password auth succeeded for 'root' from 192.168.121.1:48576
``` ```
With `-j` the same command gives JSON, for scripts and other programs.
The view above is kept short for reading, the JSON also has the
settings of the service:
```
alpine:~# initctl -j status dialer
{
"identity": "dialer",
"description": "Modem dialer",
"type": "service",
"forking": false,
"status": "restart",
"exit": { "code": 1 },
"origin": "/etc/finit.d/enabled/dialer.conf",
"command": "dialer",
"manual": false,
"started": false,
"starts": 0,
"restarts": 7,
"restart": {
"count": 4,
"max": -1,
"sec": 10,
"delay": 160,
"limit": 300,
"respawn": false,
"oncrash": "ignore"
},
"name": "dialer",
"id": "",
"internal": {
"job": 12,
"oldpid": 1234,
"starting": false,
"dirty": false,
"removed": false
},
"protected": false,
"nowarn": false,
"notify": "none",
"remain": false,
"stop": {
"signal": "SIGTERM",
"timeout": 3,
"scope": "pgroup"
},
"reload": {
"signal": "SIGHUP",
"propagate": false
},
"scripts": {
"exec-stop-post": { "command": "/usr/libexec/dialer-down", "timeout": 3 }
},
"directories": {
"runtime": { "name": "dialer", "mode": "0755" },
"preserve": "no"
},
"cgroup-config": {
"group": "",
"config": "",
"delegate": false
},
"rlimits": {
"core": { "soft": 0, "hard": "unlimited" },
"nofile": { "soft": 1024, "hard": 4096 },
...
},
"log": {
"enabled": true,
"null": false,
"console": false,
"file": "",
"priority": "",
"identity": "dialer"
},
"pidfile": "none",
"pid": 0,
"user": "root",
"group": "root",
"uptime": 0,
"runlevels": [ 2, 3, 4, 5 ]
}
```
In `restart`, `count` is the restart counter that `restart-max`, here
`max`, is compared to, -1 for `restart = "always"`. The total since
boot is in `restarts`. `delay` is the number of seconds before the
next restart, should the service crash, `sec` is `restart-sec`, and
`limit` is `restart-max-sec`, both 0 when not set. All times are in
seconds.
The settings use the names from the [configuration](config/service-opts.md):
`scripts` has the `exec-*` scripts that are set, each with its timeout,
`directories` the `runtime`, `state`, `cache`, `logs`, and `config`
directories that are set, and `preserve`. `cgroup-config` is the
`cgroup` setting of the service, where `cgroup` is the control group
it runs in right now. `rlimits` has every resource limit, the ones
from `rlimit` and the ones the service inherits. A `tty` has a `tty`
object with its device and flags where other types have `log`.
`internal` is state Finit keeps for its own use, it may change between
releases.
Left out when they do not apply are `environment`, `condition`, `exit`,
`if`, `provides`, `conflicts`, `groups`, `capabilities`, `pam`, and the
cgroup members `cgroup`, `memory`, `cpu`, and `limits`.
```
alpine:~# initctl -j status dialer | jq .restart.delay
160
```
Switch Root Switch Root
----------- -----------
+6
View File
@@ -143,6 +143,7 @@ static int num_ac;
static int level; static int level;
static int logon; static int logon;
static int passive; /* power-supply only, no device management */ static int passive; /* power-supply only, no device management */
static int ready; /* pidfile created, see issue #503 */
static struct rule_list rules = TAILQ_HEAD_INITIALIZER(rules); static struct rule_list rules = TAILQ_HEAD_INITIALIZER(rules);
static char *rules_dir; /* extra rules dir from -r option */ static char *rules_dir; /* extra rules dir from -r option */
@@ -507,10 +508,13 @@ static void sigterm_cb(uev_t *w, void *arg, int events)
uev_exit(w->ctx); uev_exit(w->ctx);
} }
/* Finit expects the pidfile touched to reassert readiness after SIGHUP */
static void sighup_cb(uev_t *w, void *arg, int events) static void sighup_cb(uev_t *w, void *arg, int events)
{ {
(void)w; (void)arg; (void)events; (void)w; (void)arg; (void)events;
kev_rules_reload(); kev_rules_reload();
if (ready)
pidfile(NULL);
} }
static void sigchld_cb(uev_t *w, void *arg, int events) static void sigchld_cb(uev_t *w, void *arg, int events)
@@ -613,6 +617,7 @@ static void coldplug_pidfile_cb(uev_t *w, void *arg, int events)
return; return;
pidfile(NULL); pidfile(NULL);
ready = 1;
logit(LOG_NOTICE, "keventd ready, coldplug queue drained"); logit(LOG_NOTICE, "keventd ready, coldplug queue drained");
uev_timer_stop(w); uev_timer_stop(w);
} }
@@ -826,6 +831,7 @@ int main(int argc, char *argv[])
logit(LOG_NOTICE, "keventd v%s started, draining coldplug queue...", KEVENTD_VERSION); logit(LOG_NOTICE, "keventd v%s started, draining coldplug queue...", KEVENTD_VERSION);
} else { } else {
pidfile(NULL); pidfile(NULL);
ready = 1;
logit(LOG_NOTICE, "keventd v%s started, waiting for events...", KEVENTD_VERSION); logit(LOG_NOTICE, "keventd v%s started, waiting for events...", KEVENTD_VERSION);
} }
+25 -2
View File
@@ -379,11 +379,22 @@ marked
.Em crashed .Em crashed
and must be restarted manually with and must be restarted manually with
.Xr initctl 8 . .Xr initctl 8 .
.It Cm restart_sec:SEC .It Cm restart-sec:SEC
number of seconds before Finit tries to restart number of seconds before Finit tries to restart
a crashing service, default: 2 seconds for the first five retries, a crashing service, default: 2 seconds for the first five retries,
then back-off to 5 seconds. The maximum of this configured value then back-off to 5 seconds. The maximum of this configured value
and the above (2 and 5) will be used and the above (2 and 5) will be used. The old spelling,
.Cm restart_sec:SEC ,
is still accepted
.It Cm restart-max-sec:SEC
replaces that back-off with a delay that doubles for each restart, from
.Cm restart-sec
up to this limit, e.g. 10, 20, 40, and so on up to 300 seconds with
.Cm restart-sec:10 restart-max-sec:300 .
Without
.Cm restart-sec
the first restart is at once, then after 2, 4, 8 seconds. The delay
comes down again as the service keeps running
.It Cm restart:always .It Cm restart:always
no upper limit on the number of times Finit tries to restart a crashing no upper limit on the number of times Finit tries to restart a crashing
service. Same as service. Same as
@@ -470,6 +481,18 @@ modifier
e.g., e.g.,
.Cm kill:10 .Cm kill:10
to wait 10 seconds before sending SIGKILL. to wait 10 seconds before sending SIGKILL.
When the process exits, Finit sends SIGKILL to any processes left in
its process group. The command modifier
.Cm stop-scope:SCOPE
changes this:
.Cm process
leaves them alone,
.Cm cgroup
sends the halt signal to all processes in the cgroup of the service and
SIGKILL to the rest when the process exits, and
.Cm mixed
sends only SIGKILL to the rest of the cgroup. The default is
.Cm pgroup .
.Pp .Pp
Services, including the Services, including the
.Cm sysv .Cm sysv
+10 -3
View File
@@ -109,6 +109,12 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
} }
if (mask & (IN_CLOSE_WRITE | IN_ATTRIB | IN_MODIFY | IN_MOVED_TO)) { if (mask & (IN_CLOSE_WRITE | IN_ATTRIB | IN_MODIFY | IN_MOVED_TO)) {
/* Only a starting or running service may claim a PID file, issue #452 */
if (!svc_is_starting(svc) && !svc_is_running(svc)) {
dbg("%s is %s, ignoring %s", nm, svc_status(svc), fn);
return;
}
/* /*
* only mark native services as started, the s6 and * only mark native services as started, the s6 and
* systemd style services rely on their respective * systemd style services rely on their respective
@@ -133,9 +139,6 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
return; return;
} }
/* Service is not crashing, let's tell state machine! */
service_forked(svc);
if (pid != svc->pid) { if (pid != svc->pid) {
dbg("Forking service %s (cmd %s) changed PID from %d to %d", dbg("Forking service %s (cmd %s) changed PID from %d to %d",
svc_ident(svc, NULL, 0), svc->cmd, svc->pid, pid); svc_ident(svc, NULL, 0), svc->cmd, svc->pid, pid);
@@ -145,6 +148,10 @@ static void pidfile_update_conds(char *dir, char *name, uint32_t mask)
logit(LOG_CONSOLE | LOG_NOTICE, "Started %s[%d]", svc_ident(svc, NULL, 0), pid); logit(LOG_CONSOLE | LOG_NOTICE, "Started %s[%d]", svc_ident(svc, NULL, 0), pid);
cgroup_move_svc(svc); cgroup_move_svc(svc);
} }
/* Service is not crashing, let's tell state machine! */
if (!service_forked(svc))
return;
} }
if (svc->notify == SVC_NOTIFY_PID) if (svc->notify == SVC_NOTIFY_PID)
+1
View File
@@ -54,6 +54,7 @@ finit_SOURCES = api.c cgroup.c cgroup.h \
legacy.c legacy.h \ legacy.c legacy.h \
devmon.c devmon.h \ devmon.c devmon.h \
exec.c finit.c finit.h \ exec.c finit.c finit.h \
shutdown.c shutdown.h \
stty.c \ stty.c \
helpers.c helpers.h \ helpers.c helpers.h \
initramfs.c \ initramfs.c \
+15 -37
View File
@@ -48,6 +48,7 @@
#include "schedule.h" #include "schedule.h"
#include "service.h" #include "service.h"
#include "sm.h" #include "sm.h"
#include "shutdown.h"
#include "sig.h" #include "sig.h"
#include "util.h" #include "util.h"
@@ -241,43 +242,9 @@ static int do_reboot(int cmd, int timeout, char *buf, size_t len)
switch (cmd) { switch (cmd) {
case INIT_CMD_REBOOT: case INIT_CMD_REBOOT:
halt = SHUT_REBOOT;
break;
case INIT_CMD_HALT: case INIT_CMD_HALT:
halt = SHUT_HALT;
break;
case INIT_CMD_POWEROFF: case INIT_CMD_POWEROFF:
halt = SHUT_OFF; rc = shutdown_now(cmd, timeout);
break;
case INIT_CMD_SUSPEND:
break;
default:
return 255;
}
shutdown_bypass(timeout);
switch (cmd) {
case INIT_CMD_REBOOT:
dbg("reboot");
halt = SHUT_REBOOT;
sm_runlevel(6);
break;
case INIT_CMD_HALT:
dbg("halt");
halt = SHUT_HALT;
sm_runlevel(0);
break;
case INIT_CMD_POWEROFF:
dbg("poweroff");
halt = SHUT_OFF;
sm_runlevel(0);
break; break;
case INIT_CMD_SUSPEND: case INIT_CMD_SUSPEND:
@@ -293,8 +260,7 @@ static int do_reboot(int cmd, int timeout, char *buf, size_t len)
break; break;
default: default:
/* Handled previously */ return 255;
break;
} }
return rc; return rc;
@@ -384,6 +350,7 @@ static void api_cb(uev_t *w, void *arg, int events)
case INIT_CMD_HALT: case INIT_CMD_HALT:
case INIT_CMD_POWEROFF: case INIT_CMD_POWEROFF:
case INIT_CMD_SUSPEND: case INIT_CMD_SUSPEND:
case INIT_CMD_SHUTDOWN:
if (IS_RESERVED_RUNLEVEL(runlevel)) { if (IS_RESERVED_RUNLEVEL(runlevel)) {
strterm(rq.data, sizeof(rq.data)); strterm(rq.data, sizeof(rq.data));
warnx("Unsupported command (cmd: %d, data: %s) in runlevel S and 6/0.", warnx("Unsupported command (cmd: %d, data: %s) in runlevel S and 6/0.",
@@ -484,6 +451,17 @@ static void api_cb(uev_t *w, void *arg, int events)
result = do_reboot(rq.cmd, rq.sleeptime, rq.data, sizeof(rq.data)); result = do_reboot(rq.cmd, rq.sleeptime, rq.data, sizeof(rq.data));
break; break;
case INIT_CMD_SHUTDOWN:
strterm(rq.data, sizeof(rq.data));
result = shutdown_schedule(rq.runlevel, rq.sleeptime, rq.data);
break;
case INIT_CMD_SHUTDOWN_CANCEL:
result = shutdown_cancel();
if (result)
strlcpy(rq.data, "No scheduled shutdown to cancel.", sizeof(rq.data));
break;
case INIT_CMD_SWITCH_ROOT: case INIT_CMD_SWITCH_ROOT:
result = do_switch_root_api(sd, &rq); result = do_switch_root_api(sd, &rq);
if (result) if (result)
+82 -10
View File
@@ -222,6 +222,86 @@ int cgroup_move_svc(svc_t *svc)
svc->pid, svc->cgroup.delegate); svc->pid, svc->cgroup.delegate);
} }
/*
* The cgroup @svc runs in, as set up by cgroup_prepare(). NULL for
* the root cgroup, which is not the service's own.
*/
static char *cgroup_svc_path(svc_t *svc, const char *name, char *buf, size_t len)
{
const char *group;
if (svc_is_tty(svc))
group = "user";
else if (!strcmp(svc->cgroup.name, "root"))
return NULL;
else
group = svc->cgroup.name[0] ? svc->cgroup.name : "system";
snprintf(buf, len, FINIT_CGPATH "/%s/%s", group, name);
return buf;
}
static void cgroup_signal_path(const char *path, int sig)
{
char fn[PATH_MAX];
struct dirent *d;
DIR *dir;
FILE *fp;
int pid;
fp = fopenf("r", "%s/cgroup.procs", path);
if (fp) {
/* A PID outside our PID namespace reads as 0, our own group */
while (fscanf(fp, "%d", &pid) == 1) {
if (pid > 1)
kill(pid, sig);
}
fclose(fp);
}
/* Delegated cgroups have their processes in sub-cgroups */
dir = opendir(path);
if (!dir)
return;
while ((d = readdir(dir))) {
if (d->d_type != DT_DIR || !strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
continue;
snprintf(fn, sizeof(fn), "%s/%s", path, d->d_name);
cgroup_signal_path(fn, sig);
}
closedir(dir);
}
/* True if @svc runs in a cgroup of its own, not the root cgroup */
int cgroup_svc_has(svc_t *svc)
{
return avail && svc && strcmp(svc->cgroup.name, "root");
}
/*
* Send @sig to every process in the cgroup of @svc. Returns -1 if
* it has no cgroup of its own, e.g. cgroups are not available.
*/
int cgroup_signal_svc(svc_t *svc, int sig)
{
char name[MAX_ARG_LEN];
char path[PATH_MAX];
if (!cgroup_svc_has(svc))
return -1;
if (!cgroup_svc_path(svc, cgroup_svc_name(svc, name, sizeof(name)), path, sizeof(path)) ||
!fisdir(path))
return -1;
/* Atomic and recursive, Linux 5.14 and later */
if (sig == SIGKILL && !fnwrite("1", "%s/cgroup.kill", path))
return 0;
cgroup_signal_path(path, sig);
return 0;
}
static void cgset(const char *path, char *ctrl, char *prop) static void cgset(const char *path, char *ctrl, char *prop)
{ {
char *val; char *val;
@@ -798,23 +878,15 @@ int cgroup_del(char *dir)
*/ */
int cgroup_del_svc(svc_t *svc, const char *name) int cgroup_del_svc(svc_t *svc, const char *name)
{ {
const char *group; char path[PATH_MAX];
char path[256];
if (!avail) if (!avail)
return 0; return 0;
/* Determine group from service */
if (svc_is_tty(svc)) {
group = "user";
} else if (svc->cgroup.name[0] && !strcmp(svc->cgroup.name, "root")) {
/* Root cgroup - nothing to delete */ /* Root cgroup - nothing to delete */
if (!cgroup_svc_path(svc, name, path, sizeof(path)))
return 0; return 0;
} else {
group = svc->cgroup.name[0] ? svc->cgroup.name : "system";
}
snprintf(path, sizeof(path), "/sys/fs/cgroup/%s/%s", group, name);
return cgroup_del(path); return cgroup_del(path);
} }
+2
View File
@@ -58,6 +58,8 @@ int cgroup_watch (const char *group, const char *name);
int cgroup_move_pid(const char *group, const char *name, int pid, int delegate); int cgroup_move_pid(const char *group, const char *name, int pid, int delegate);
int cgroup_move_svc(svc_t *svc); int cgroup_move_svc(svc_t *svc);
int cgroup_svc_has (svc_t *svc);
int cgroup_signal_svc(svc_t *svc, int sig);
void cgroup_prune (void); void cgroup_prune (void);
+7 -1
View File
@@ -261,6 +261,7 @@ static cfg_opt_t svc_opts[] = {
CFG_STR ("restart", NULL, CFGF_NODEFAULT), CFG_STR ("restart", NULL, CFGF_NODEFAULT),
CFG_INT ("restart-max", 0, CFGF_NODEFAULT), CFG_INT ("restart-max", 0, CFGF_NODEFAULT),
CFG_INT ("restart-sec", 0, CFGF_NODEFAULT), CFG_INT ("restart-sec", 0, CFGF_NODEFAULT),
CFG_INT ("restart-max-sec", 0, CFGF_NODEFAULT),
CFG_STR ("oncrash", NULL, CFGF_NODEFAULT), CFG_STR ("oncrash", NULL, CFGF_NODEFAULT),
CFG_STR ("reload-signal", NULL, CFGF_NODEFAULT), CFG_STR ("reload-signal", NULL, CFGF_NODEFAULT),
CFG_BOOL ("required", cfg_true, CFGF_NODEFAULT), CFG_BOOL ("required", cfg_true, CFGF_NODEFAULT),
@@ -268,6 +269,7 @@ static cfg_opt_t svc_opts[] = {
CFG_STR ("halt", NULL, CFGF_NODEFAULT), /* alias */ CFG_STR ("halt", NULL, CFGF_NODEFAULT), /* alias */
CFG_INT ("stop-timeout", 0, CFGF_NODEFAULT), CFG_INT ("stop-timeout", 0, CFGF_NODEFAULT),
CFG_INT ("kill", 0, CFGF_NODEFAULT), /* alias */ CFG_INT ("kill", 0, CFGF_NODEFAULT), /* alias */
CFG_STR ("stop-scope", NULL, CFGF_NODEFAULT),
/* lifecycle scripts, each with its own bound */ /* lifecycle scripts, each with its own bound */
EXEC_OPTS("exec-start-pre"), EXEC_OPTS("exec-start-pre"),
@@ -1666,7 +1668,9 @@ static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *fi
} }
if (sec_getint(sec, "restart-sec", NULL, &num)) if (sec_getint(sec, "restart-sec", NULL, &num))
addtok(line, sizeof(line), "restart_sec:%ld", num); addtok(line, sizeof(line), "restart-sec:%ld", num);
if (sec_getint(sec, "restart-max-sec", NULL, &num))
addtok(line, sizeof(line), "restart-max-sec:%ld", num);
if ((str = sec_getstr(sec, "oncrash", NULL))) if ((str = sec_getstr(sec, "oncrash", NULL)))
addtok(line, sizeof(line), "oncrash:%s", str); addtok(line, sizeof(line), "oncrash:%s", str);
@@ -1674,6 +1678,8 @@ static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *fi
addtok(line, sizeof(line), "halt:%s", str); addtok(line, sizeof(line), "halt:%s", str);
if (sec_getint(sec, "stop-timeout", "kill", &num)) if (sec_getint(sec, "stop-timeout", "kill", &num))
addtok(line, sizeof(line), "kill:%ld", num); addtok(line, sizeof(line), "kill:%ld", num);
if ((str = sec_getstr(sec, "stop-scope", NULL)))
addtok(line, sizeof(line), "stop-scope:%s", str);
addscript(line, sizeof(line), sec, "exec-start-pre", "pre:"); addscript(line, sizeof(line), sec, "exec-start-pre", "pre:");
addscript(line, sizeof(line), sec, "exec-start-ready", "ready:"); addscript(line, sizeof(line), sec, "exec-start-ready", "ready:");
+176 -7
View File
@@ -50,6 +50,7 @@
#include "schedule.h" #include "schedule.h"
#include "service.h" #include "service.h"
#include "sig.h" #include "sig.h"
#include "shutdown.h"
#include "sm.h" #include "sm.h"
#include "svc.h" #include "svc.h"
#include "util.h" #include "util.h"
@@ -438,7 +439,7 @@ static int manager_set_runlevel(link_call_t *call, void *userdata)
return 0; return 0;
} }
static int dbus_shutdown(link_call_t *call, shutop_t target, int level) static int dbus_shutdown(link_call_t *call, int cmd)
{ {
uint32_t timeout; uint32_t timeout;
@@ -450,16 +451,14 @@ static int dbus_shutdown(link_call_t *call, shutop_t target, int level)
return link_call_reply_error(call, return link_call_reply_error(call,
"org.finit.Error.WrongRunlevel", "org.finit.Error.WrongRunlevel",
"Already in shutdown"); "Already in shutdown");
halt = target; shutdown_now(cmd, (int)timeout);
shutdown_bypass((int)timeout);
sm_runlevel(level);
(void)link_call_reply(call); (void)link_call_reply(call);
return 0; return 0;
} }
static int manager_reboot (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, SHUT_REBOOT, 6); } static int manager_reboot (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, INIT_CMD_REBOOT); }
static int manager_poweroff(link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, SHUT_OFF, 0); } static int manager_poweroff(link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, INIT_CMD_POWEROFF); }
static int manager_halt (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, SHUT_HALT, 0); } static int manager_halt (link_call_t *c, void *u) { (void)u; return dbus_shutdown(c, INIT_CMD_HALT); }
static int manager_set_debug(link_call_t *call, void *u) static int manager_set_debug(link_call_t *call, void *u)
{ {
@@ -798,11 +797,114 @@ SVC_PROP_U32 (svc_prop_runlevels, runlevels)
SVC_PROP_U32 (svc_prop_exitstatus, status) SVC_PROP_U32 (svc_prop_exitstatus, status)
SVC_PROP_U32 (svc_prop_restarts_tot, restart_tot) SVC_PROP_U32 (svc_prop_restarts_tot, restart_tot)
SVC_PROP_U32 (svc_prop_restart_max, restart_max) SVC_PROP_U32 (svc_prop_restart_max, restart_max)
SVC_PROP_U32 (svc_prop_restart_delay, restart_tmo / 1000) /* msec */
SVC_PROP_U32 (svc_prop_restart_delay_max, restart_tmo_max / 1000)
SVC_PROP_U32 (svc_prop_starts, once) SVC_PROP_U32 (svc_prop_starts, once)
SVC_PROP_BOOL(svc_prop_manual, manual) SVC_PROP_BOOL(svc_prop_manual, manual)
SVC_PROP_BOOL(svc_prop_forking, forking) SVC_PROP_BOOL(svc_prop_forking, forking)
SVC_PROP_BOOL(svc_prop_started, started) SVC_PROP_BOOL(svc_prop_started, started)
/* The settings of the service, for initctl -j status */
#define SVC_PROP_EXPR(fn, writer, expr) \
static int fn(link_writer_t *w, void *arg) \
{ \
svc_t *svc = arg; \
\
writer(w, expr); \
return 0; \
}
static int svc_prop_provides(link_writer_t *w, void *arg)
{
char buf[MAX_NUM_PROVIDES * MAX_COND_LEN];
link_w_string(w, svc_provides_str(arg, buf, sizeof(buf)));
return 0;
}
static int svc_prop_rlimits(link_writer_t *w, void *arg)
{
svc_t *svc = arg;
char buf[1024];
link_w_string(w, rlimits2str(svc->rlimit, buf, sizeof(buf)));
return 0;
}
static int svc_prop_stop_signal(link_writer_t *w, void *arg)
{
svc_t *svc = arg;
char buf[16];
/* Not sig_name(), initctl has only sig2str() for its own transport */
snprintf(buf, sizeof(buf), "SIG%s", sig2str(svc->sighalt));
link_w_string(w, buf);
return 0;
}
SVC_PROP_BOOL(svc_prop_remain, remain)
SVC_PROP_STR (svc_prop_if, ifstmt)
SVC_PROP_STR (svc_prop_conflicts, conflict)
SVC_PROP_STR (svc_prop_extra_groups, supgroups)
SVC_PROP_STR (svc_prop_capabilities, capabilities)
SVC_PROP_STR (svc_prop_pam, pam)
SVC_PROP_U32 (svc_prop_stop_timeout, killdelay / 1000)
SVC_PROP_U32 (svc_prop_restart_sec, restart_saved / 1000)
SVC_PROP_BOOL(svc_prop_respawn, respawn)
SVC_PROP_BOOL(svc_prop_protected, protect)
SVC_PROP_STR (svc_prop_id, id)
SVC_PROP_U32 (svc_prop_job, job)
SVC_PROP_U32 (svc_prop_old_pid, oldpid)
SVC_PROP_BOOL(svc_prop_dirty, dirty)
SVC_PROP_BOOL(svc_prop_removed, removed)
SVC_PROP_BOOL(svc_prop_starting, starting)
SVC_PROP_BOOL(svc_prop_no_warn, nowarn)
SVC_PROP_BOOL(svc_prop_reload_propagate, flux_reload)
SVC_PROP_STR (svc_prop_cgroup_name, cgroup.name)
SVC_PROP_STR (svc_prop_cgroup_config, cgroup.cfg)
SVC_PROP_BOOL(svc_prop_cgroup_delegate, cgroup.delegate)
SVC_PROP_U32 (svc_prop_runtime_dir_mode, dir_mode[0])
SVC_PROP_U32 (svc_prop_state_dir_mode, dir_mode[1])
SVC_PROP_U32 (svc_prop_cache_dir_mode, dir_mode[2])
SVC_PROP_U32 (svc_prop_logs_dir_mode, dir_mode[3])
SVC_PROP_U32 (svc_prop_config_dir_mode, dir_mode[4])
SVC_PROP_STR (svc_prop_runtime_dir, runtime_dir)
SVC_PROP_STR (svc_prop_state_dir, state_dir)
SVC_PROP_STR (svc_prop_cache_dir, cache_dir)
SVC_PROP_STR (svc_prop_logs_dir, logs_dir)
SVC_PROP_STR (svc_prop_config_dir, config_dir)
SVC_PROP_STR (svc_prop_exec_start_pre, pre_script)
SVC_PROP_U32 (svc_prop_exec_start_pre_timeout, pre_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_start_ready, ready_script)
SVC_PROP_U32 (svc_prop_exec_start_ready_timeout, ready_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_stop, stop_script)
SVC_PROP_U32 (svc_prop_exec_stop_timeout, stop_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_stop_post, post_script)
SVC_PROP_U32 (svc_prop_exec_stop_post_timeout, post_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_reload, reload_script)
SVC_PROP_U32 (svc_prop_exec_reload_timeout, reload_tmo / 1000)
SVC_PROP_STR (svc_prop_exec_cleanup, cleanup_script)
SVC_PROP_U32 (svc_prop_exec_cleanup_timeout, cleanup_tmo / 1000)
SVC_PROP_EXPR(svc_prop_notify, link_w_string, svc_notify_str(svc))
SVC_PROP_EXPR(svc_prop_stop_scope, link_w_string, svc_scope_str(svc->stop_scope))
SVC_PROP_EXPR(svc_prop_reload_signal, link_w_string, svc->sighup ? "SIGHUP" : "none")
SVC_PROP_EXPR(svc_prop_on_crash, link_w_string, svc_oncrash_str(svc))
SVC_PROP_EXPR(svc_prop_runtime_dir_preserve, link_w_string, svc_preserve_str(svc))
SVC_PROP_EXPR(svc_prop_log, link_w_bool, !svc_is_tty(svc) ? svc->log.enabled : 0)
SVC_PROP_EXPR(svc_prop_log_null, link_w_bool, !svc_is_tty(svc) ? svc->log.null : 0)
SVC_PROP_EXPR(svc_prop_log_console, link_w_bool, !svc_is_tty(svc) ? svc->log.console : 0)
SVC_PROP_EXPR(svc_prop_log_file, link_w_string, !svc_is_tty(svc) ? svc->log.file : "")
SVC_PROP_EXPR(svc_prop_log_priority, link_w_string, !svc_is_tty(svc) ? svc->log.prio : "")
SVC_PROP_EXPR(svc_prop_log_identity, link_w_string, !svc_is_tty(svc) ? svc->log.ident : "")
SVC_PROP_EXPR(svc_prop_tty_device, link_w_string, svc_is_tty(svc) ? svc->dev : "")
SVC_PROP_EXPR(svc_prop_tty_baud, link_w_string, svc_is_tty(svc) ? svc->baud : "")
SVC_PROP_EXPR(svc_prop_tty_term, link_w_string, svc_is_tty(svc) ? svc->term : "")
SVC_PROP_EXPR(svc_prop_tty_no_clear, link_w_bool, svc_is_tty(svc) ? svc->noclear : 0)
SVC_PROP_EXPR(svc_prop_tty_no_wait, link_w_bool, svc_is_tty(svc) ? svc->nowait : 0)
SVC_PROP_EXPR(svc_prop_tty_no_login, link_w_bool, svc_is_tty(svc) ? svc->nologin : 0)
SVC_PROP_EXPR(svc_prop_tty_no_tty, link_w_bool, svc_is_tty(svc) ? svc->notty : 0)
SVC_PROP_EXPR(svc_prop_tty_rescue, link_w_bool, svc_is_tty(svc) ? svc->rescue : 0)
static const link_property_t service_properties[] = { static const link_property_t service_properties[] = {
{ .name = "Identity", .sig = "s", .getter = svc_prop_identity }, { .name = "Identity", .sig = "s", .getter = svc_prop_identity },
{ .name = "Name", .sig = "s", .getter = svc_prop_name }, { .name = "Name", .sig = "s", .getter = svc_prop_name },
@@ -823,10 +925,77 @@ static const link_property_t service_properties[] = {
{ .name = "ExitStatus", .sig = "u", .getter = svc_prop_exitstatus }, { .name = "ExitStatus", .sig = "u", .getter = svc_prop_exitstatus },
{ .name = "RestartsTotal",.sig = "u", .getter = svc_prop_restarts_tot }, { .name = "RestartsTotal",.sig = "u", .getter = svc_prop_restarts_tot },
{ .name = "RestartMax", .sig = "u", .getter = svc_prop_restart_max }, { .name = "RestartMax", .sig = "u", .getter = svc_prop_restart_max },
{ .name = "RestartDelay", .sig = "u", .getter = svc_prop_restart_delay },
{ .name = "RestartDelayMax", .sig = "u", .getter = svc_prop_restart_delay_max },
{ .name = "Starts", .sig = "u", .getter = svc_prop_starts }, { .name = "Starts", .sig = "u", .getter = svc_prop_starts },
{ .name = "ManualStart", .sig = "b", .getter = svc_prop_manual }, { .name = "ManualStart", .sig = "b", .getter = svc_prop_manual },
{ .name = "Forking", .sig = "b", .getter = svc_prop_forking }, { .name = "Forking", .sig = "b", .getter = svc_prop_forking },
{ .name = "Started", .sig = "b", .getter = svc_prop_started }, { .name = "Started", .sig = "b", .getter = svc_prop_started },
{ .name = "Notify", .sig = "s", .getter = svc_prop_notify },
{ .name = "Remain", .sig = "b", .getter = svc_prop_remain },
{ .name = "If", .sig = "s", .getter = svc_prop_if },
{ .name = "Provides", .sig = "s", .getter = svc_prop_provides },
{ .name = "Conflicts", .sig = "s", .getter = svc_prop_conflicts },
{ .name = "ExtraGroups", .sig = "s", .getter = svc_prop_extra_groups },
{ .name = "Capabilities", .sig = "s", .getter = svc_prop_capabilities },
{ .name = "Pam", .sig = "s", .getter = svc_prop_pam },
{ .name = "StopSignal", .sig = "s", .getter = svc_prop_stop_signal },
{ .name = "StopTimeout", .sig = "u", .getter = svc_prop_stop_timeout },
{ .name = "StopScope", .sig = "s", .getter = svc_prop_stop_scope },
{ .name = "ReloadSignal", .sig = "s", .getter = svc_prop_reload_signal },
{ .name = "RestartSec", .sig = "u", .getter = svc_prop_restart_sec },
{ .name = "Respawn", .sig = "b", .getter = svc_prop_respawn },
{ .name = "OnCrash", .sig = "s", .getter = svc_prop_on_crash },
{ .name = "RuntimeDir", .sig = "s", .getter = svc_prop_runtime_dir },
{ .name = "StateDir", .sig = "s", .getter = svc_prop_state_dir },
{ .name = "CacheDir", .sig = "s", .getter = svc_prop_cache_dir },
{ .name = "LogsDir", .sig = "s", .getter = svc_prop_logs_dir },
{ .name = "ConfigDir", .sig = "s", .getter = svc_prop_config_dir },
{ .name = "RuntimeDirPreserve", .sig = "s", .getter = svc_prop_runtime_dir_preserve },
{ .name = "RuntimeDirMode", .sig = "u", .getter = svc_prop_runtime_dir_mode },
{ .name = "StateDirMode", .sig = "u", .getter = svc_prop_state_dir_mode },
{ .name = "CacheDirMode", .sig = "u", .getter = svc_prop_cache_dir_mode },
{ .name = "LogsDirMode", .sig = "u", .getter = svc_prop_logs_dir_mode },
{ .name = "ConfigDirMode", .sig = "u", .getter = svc_prop_config_dir_mode },
{ .name = "Protected", .sig = "b", .getter = svc_prop_protected },
{ .name = "Id", .sig = "s", .getter = svc_prop_id },
{ .name = "Job", .sig = "u", .getter = svc_prop_job },
{ .name = "OldPid", .sig = "u", .getter = svc_prop_old_pid },
{ .name = "Dirty", .sig = "b", .getter = svc_prop_dirty },
{ .name = "Removed", .sig = "b", .getter = svc_prop_removed },
{ .name = "Starting", .sig = "b", .getter = svc_prop_starting },
{ .name = "NoWarn", .sig = "b", .getter = svc_prop_no_warn },
{ .name = "ReloadPropagate", .sig = "b", .getter = svc_prop_reload_propagate },
{ .name = "CgroupName", .sig = "s", .getter = svc_prop_cgroup_name },
{ .name = "CgroupConfig", .sig = "s", .getter = svc_prop_cgroup_config },
{ .name = "CgroupDelegate", .sig = "b", .getter = svc_prop_cgroup_delegate },
{ .name = "Rlimits", .sig = "s", .getter = svc_prop_rlimits },
{ .name = "ExecStartPre", .sig = "s", .getter = svc_prop_exec_start_pre },
{ .name = "ExecStartPreTimeout", .sig = "u", .getter = svc_prop_exec_start_pre_timeout },
{ .name = "ExecStartReady", .sig = "s", .getter = svc_prop_exec_start_ready },
{ .name = "ExecStartReadyTimeout", .sig = "u", .getter = svc_prop_exec_start_ready_timeout },
{ .name = "ExecStop", .sig = "s", .getter = svc_prop_exec_stop },
{ .name = "ExecStopTimeout", .sig = "u", .getter = svc_prop_exec_stop_timeout },
{ .name = "ExecStopPost", .sig = "s", .getter = svc_prop_exec_stop_post },
{ .name = "ExecStopPostTimeout", .sig = "u", .getter = svc_prop_exec_stop_post_timeout },
{ .name = "ExecReload", .sig = "s", .getter = svc_prop_exec_reload },
{ .name = "ExecReloadTimeout", .sig = "u", .getter = svc_prop_exec_reload_timeout },
{ .name = "ExecCleanup", .sig = "s", .getter = svc_prop_exec_cleanup },
{ .name = "ExecCleanupTimeout", .sig = "u", .getter = svc_prop_exec_cleanup_timeout },
{ .name = "Log", .sig = "b", .getter = svc_prop_log },
{ .name = "LogNull", .sig = "b", .getter = svc_prop_log_null },
{ .name = "LogConsole", .sig = "b", .getter = svc_prop_log_console },
{ .name = "LogFile", .sig = "s", .getter = svc_prop_log_file },
{ .name = "LogPriority", .sig = "s", .getter = svc_prop_log_priority },
{ .name = "LogIdentity", .sig = "s", .getter = svc_prop_log_identity },
{ .name = "TtyDevice", .sig = "s", .getter = svc_prop_tty_device },
{ .name = "TtyBaud", .sig = "s", .getter = svc_prop_tty_baud },
{ .name = "TtyTerm", .sig = "s", .getter = svc_prop_tty_term },
{ .name = "TtyNoClear", .sig = "b", .getter = svc_prop_tty_no_clear },
{ .name = "TtyNoWait", .sig = "b", .getter = svc_prop_tty_no_wait },
{ .name = "TtyNoLogin", .sig = "b", .getter = svc_prop_tty_no_login },
{ .name = "TtyNoTty", .sig = "b", .getter = svc_prop_tty_no_tty },
{ .name = "TtyRescue", .sig = "b", .getter = svc_prop_tty_rescue },
{ NULL, NULL, NULL } { NULL, NULL, NULL }
}; };
+2
View File
@@ -100,6 +100,8 @@
#define INIT_CMD_POWEROFF 22 #define INIT_CMD_POWEROFF 22
#define INIT_CMD_SUSPEND 23 #define INIT_CMD_SUSPEND 23
#define INIT_CMD_SWITCH_ROOT 24 /* Switch to new root filesystem */ #define INIT_CMD_SWITCH_ROOT 24 /* Switch to new root filesystem */
#define INIT_CMD_SHUTDOWN 25 /* runlevel: REBOOT/HALT/POWEROFF, sleeptime: sec, data: msg */
#define INIT_CMD_SHUTDOWN_CANCEL 26
#define INIT_CMD_WDOG_HELLO 128 /* Watchdog register and hello */ #define INIT_CMD_WDOG_HELLO 128 /* Watchdog register and hello */
#define INIT_CMD_SVC_ITER 129 #define INIT_CMD_SVC_ITER 129
#define INIT_CMD_SVC_QUERY 130 #define INIT_CMD_SVC_QUERY 130
+439 -10
View File
@@ -1090,6 +1090,36 @@ static int do_reboot_dbus(const char *method)
} }
#endif #endif
/* Scheduled shutdown, see issue #149, @cmd is INIT_CMD_REBOOT, _HALT or _POWEROFF */
int do_shutdown_at(int cmd, int sec, const char *msg)
{
struct init_request rq = {
.magic = INIT_MAGIC,
.cmd = INIT_CMD_SHUTDOWN,
.runlevel = cmd,
.sleeptime = sec,
};
strlcpy(rq.data, msg ? msg : "", sizeof(rq.data));
return client_send(&rq, sizeof(rq));
}
int do_shutdown_cancel(void)
{
struct init_request rq = {
.magic = INIT_MAGIC,
.cmd = INIT_CMD_SHUTDOWN_CANCEL,
};
if (client_send(&rq, sizeof(rq))) {
if (rq.cmd == INIT_CMD_NACK)
warnx("%s", rq.data);
return 1;
}
return 0;
}
int do_reboot (char *arg) int do_reboot (char *arg)
{ {
#ifdef HAVE_DBUS #ifdef HAVE_DBUS
@@ -1445,6 +1475,16 @@ static int svc_compare(svc_t *svc, char *arg)
* from a raw svc_t on the legacy socket path or from Service1 * from a raw svc_t on the legacy socket path or from Service1
* properties on the D-Bus path, rendered by the same printers. * properties on the D-Bus path, rendered by the same printers.
*/ */
/* In the order of the script[] and dir[] members of svc_row */
#define NUM_SCRIPTS 6
static const char *script_names[NUM_SCRIPTS] = {
"exec-start-pre", "exec-start-ready", "exec-stop",
"exec-stop-post", "exec-reload", "exec-cleanup",
};
static const char *dir_names[NUM_SVCDIRS] = {
"runtime", "state", "cache", "logs", "config",
};
struct svc_row { struct svc_row {
char ident[MAX_IDENT_LEN]; char ident[MAX_IDENT_LEN];
char state[16]; char state[16];
@@ -1465,9 +1505,61 @@ struct svc_row {
int32_t restart_tot; int32_t restart_tot;
int32_t restart_cnt; int32_t restart_cnt;
int32_t restart_max; /* -1 = restart:always */ int32_t restart_max; /* -1 = restart:always */
uint32_t restart_delay; /* seconds, before the next restart */
uint32_t restart_delay_max; /* restart-max-sec, 0 = not set */
int manual; int manual;
int forking; int forking;
int started; int started;
/* Settings, only in the JSON output */
char name[MAX_ARG_LEN];
char id[MAX_ID_LEN];
uint32_t job;
uint32_t oldpid;
int dirty;
int removed;
int starting;
char rlimits[1024]; /* name=soft:hard,... */
char cgroup_name[16];
char cgroup_cfg[128];
uint32_t dir_mode[NUM_SVCDIRS];
int cgroup_delegate;
int protect;
int nowarn;
int flux_reload;
char notify[8];
char ifstmt[MAX_IDENT_LEN];
char provides[MAX_NUM_PROVIDES * MAX_COND_LEN];
char conflicts[MAX_ARG_LEN];
char supgroups[MAX_SUPGROUPS_LEN];
char caps[MAX_CMD_LEN];
char pam[MAX_ARG_LEN];
char stop_signal[16];
char stop_scope[8];
char reload_signal[8];
char oncrash[8];
char dir[NUM_SVCDIRS][MAX_ARG_LEN];
char preserve[8];
char script[NUM_SCRIPTS][MAX_CMD_LEN];
uint32_t script_tmo[NUM_SCRIPTS]; /* seconds */
char log_file[64];
char log_prio[20];
char log_ident[20];
char tty_dev[32];
char tty_baud[10];
char tty_term[10];
uint32_t stop_timeout; /* seconds */
uint32_t restart_sec; /* restart-sec, 0 = not set */
int remain;
int respawn;
int log;
int log_null;
int log_console;
int tty_noclear;
int tty_nowait;
int tty_nologin;
int tty_notty;
int tty_rescue;
}; };
static void fill_row_from_svc(struct svc_row *r, svc_t *svc) static void fill_row_from_svc(struct svc_row *r, svc_t *svc)
@@ -1495,9 +1587,78 @@ static void fill_row_from_svc(struct svc_row *r, svc_t *svc)
r->restart_tot = (int32_t)svc->restart_tot; r->restart_tot = (int32_t)svc->restart_tot;
r->restart_cnt = (int32_t)svc->restart_cnt; r->restart_cnt = (int32_t)svc->restart_cnt;
r->restart_max = (int32_t)svc->restart_max; r->restart_max = (int32_t)svc->restart_max;
r->restart_delay = (uint32_t)svc->restart_tmo / 1000;
r->restart_delay_max = (uint32_t)svc->restart_tmo_max / 1000;
r->manual = svc->manual; r->manual = svc->manual;
r->forking = svc->forking; r->forking = svc->forking;
r->started = svc->started; r->started = svc->started;
strlcpy(r->notify, svc_notify_str(svc), sizeof(r->notify));
r->remain = svc->remain;
strlcpy(r->ifstmt, svc->ifstmt, sizeof(r->ifstmt));
svc_provides_str(svc, r->provides, sizeof(r->provides));
strlcpy(r->conflicts, svc->conflict, sizeof(r->conflicts));
strlcpy(r->supgroups, svc->supgroups, sizeof(r->supgroups));
strlcpy(r->caps, svc->capabilities, sizeof(r->caps));
strlcpy(r->pam, svc->pam, sizeof(r->pam));
snprintf(r->stop_signal, sizeof(r->stop_signal), "SIG%s", sig2str(svc->sighalt));
r->stop_timeout = (uint32_t)(svc->killdelay / 1000);
strlcpy(r->stop_scope, svc_scope_str(svc->stop_scope), sizeof(r->stop_scope));
strlcpy(r->reload_signal, svc->sighup ? "SIGHUP" : "none", sizeof(r->reload_signal));
r->restart_sec = (uint32_t)(svc->restart_saved / 1000);
r->respawn = svc->respawn;
strlcpy(r->name, svc->name, sizeof(r->name));
strlcpy(r->id, svc->id, sizeof(r->id));
r->job = (uint32_t)svc->job;
r->oldpid = (uint32_t)svc->oldpid;
r->dirty = svc->dirty;
r->removed = svc->removed;
r->starting = svc->starting;
rlimits2str(svc->rlimit, r->rlimits, sizeof(r->rlimits));
strlcpy(r->cgroup_name, svc->cgroup.name, sizeof(r->cgroup_name));
strlcpy(r->cgroup_cfg, svc->cgroup.cfg, sizeof(r->cgroup_cfg));
r->cgroup_delegate = svc->cgroup.delegate;
for (int i = 0; i < NUM_SVCDIRS; i++)
r->dir_mode[i] = (uint32_t)svc->dir_mode[i];
r->protect = svc->protect;
r->nowarn = svc->nowarn;
r->flux_reload = svc->flux_reload;
strlcpy(r->oncrash, svc_oncrash_str(svc), sizeof(r->oncrash));
strlcpy(r->dir[0], svc->runtime_dir, sizeof(r->dir[0]));
strlcpy(r->dir[1], svc->state_dir, sizeof(r->dir[1]));
strlcpy(r->dir[2], svc->cache_dir, sizeof(r->dir[2]));
strlcpy(r->dir[3], svc->logs_dir, sizeof(r->dir[3]));
strlcpy(r->dir[4], svc->config_dir, sizeof(r->dir[4]));
strlcpy(r->preserve, svc_preserve_str(svc), sizeof(r->preserve));
strlcpy(r->script[0], svc->pre_script, sizeof(r->script[0]));
r->script_tmo[0] = (uint32_t)(svc->pre_tmo / 1000);
strlcpy(r->script[1], svc->ready_script, sizeof(r->script[1]));
r->script_tmo[1] = (uint32_t)(svc->ready_tmo / 1000);
strlcpy(r->script[2], svc->stop_script, sizeof(r->script[2]));
r->script_tmo[2] = (uint32_t)(svc->stop_tmo / 1000);
strlcpy(r->script[3], svc->post_script, sizeof(r->script[3]));
r->script_tmo[3] = (uint32_t)(svc->post_tmo / 1000);
strlcpy(r->script[4], svc->reload_script, sizeof(r->script[4]));
r->script_tmo[4] = (uint32_t)(svc->reload_tmo / 1000);
strlcpy(r->script[5], svc->cleanup_script, sizeof(r->script[5]));
r->script_tmo[5] = (uint32_t)(svc->cleanup_tmo / 1000);
if (svc_is_tty(svc)) {
strlcpy(r->tty_dev, svc->dev, sizeof(r->tty_dev));
strlcpy(r->tty_baud, svc->baud, sizeof(r->tty_baud));
strlcpy(r->tty_term, svc->term, sizeof(r->tty_term));
r->tty_noclear = svc->noclear;
r->tty_nowait = svc->nowait;
r->tty_nologin = svc->nologin;
r->tty_notty = svc->notty;
r->tty_rescue = svc->rescue;
} else {
r->log = svc->log.enabled;
r->log_null = svc->log.null;
r->log_console = svc->log.console;
strlcpy(r->log_file, svc->log.file, sizeof(r->log_file));
strlcpy(r->log_prio, svc->log.prio, sizeof(r->log_prio));
strlcpy(r->log_ident, svc->log.ident, sizeof(r->log_ident));
}
} }
static const char *pidfile_str(struct svc_row *r) static const char *pidfile_str(struct svc_row *r)
@@ -1666,6 +1827,176 @@ static char *json_escape(const char *str)
return buf; return buf;
} }
static const char *json_bool(int val)
{
return val ? "true" : "false";
}
/* "a,b" as [ "a", "b" ], nothing when the list is empty */
static void json_list(FILE *fp, const char *indent, const char *key, const char *list)
{
char *buf = strdupa(list), *tok, *ptr;
const char *sep = "";
if (!list[0])
return;
fprintf(fp, "%s \"%s\": [", indent, key);
for (tok = strtok_r(buf, ",", &ptr); tok; tok = strtok_r(NULL, ",", &ptr)) {
fprintf(fp, "%s \"%s\"", sep, json_escape(tok));
sep = ",";
}
fprintf(fp, " ],\n");
}
/* "nofile=1024:unlimited,..." from rlimits2str() as an object */
static void json_rlimits(FILE *fp, const char *indent, const char *rlimits)
{
char *buf = strdupa(rlimits), *tok, *ptr;
const char *sep = "";
fprintf(fp, "%s \"rlimits\": {", indent);
for (tok = strtok_r(buf, ",", &ptr); tok; tok = strtok_r(NULL, ",", &ptr)) {
char *soft = strchr(tok, '='), *hard;
const char *q[2];
if (!soft || !(hard = strchr(soft, ':')))
continue;
*soft++ = 0;
*hard++ = 0;
/* unlimited is the only value that is not a number */
q[0] = soft[0] == 'u' ? "\"" : "";
q[1] = hard[0] == 'u' ? "\"" : "";
fprintf(fp, "%s\n%s \"%s\": { \"soft\": %s%s%s, \"hard\": %s%s%s }",
sep, indent, tok, q[0], soft, q[0], q[1], hard, q[1]);
sep = ",";
}
if (sep[0])
fprintf(fp, "\n%s ", indent);
fprintf(fp, "},\n");
}
/* The settings of a service, what the plain view leaves out */
static void json_settings(FILE *fp, struct svc_row *r, const char *indent)
{
const char *sep = "";
int i;
fprintf(fp, "%s \"name\": \"%s\",\n", indent, json_escape(r->name));
fprintf(fp, "%s \"id\": \"%s\",\n", indent, json_escape(r->id));
fprintf(fp,
"%s \"internal\": {\n"
"%s \"job\": %u,\n"
"%s \"oldpid\": %u,\n"
"%s \"starting\": %s,\n"
"%s \"dirty\": %s,\n"
"%s \"removed\": %s\n"
"%s },\n",
indent,
indent, r->job,
indent, r->oldpid,
indent, json_bool(r->starting),
indent, json_bool(r->dirty),
indent, json_bool(r->removed),
indent);
fprintf(fp, "%s \"protected\": %s,\n", indent, json_bool(r->protect));
fprintf(fp, "%s \"nowarn\": %s,\n", indent, json_bool(r->nowarn));
fprintf(fp, "%s \"notify\": \"%s\",\n", indent, r->notify);
fprintf(fp, "%s \"remain\": %s,\n", indent, json_bool(r->remain));
if (r->ifstmt[0])
fprintf(fp, "%s \"if\": \"%s\",\n", indent, json_escape(r->ifstmt));
json_list(fp, indent, "provides", r->provides);
json_list(fp, indent, "conflicts", r->conflicts);
fprintf(fp,
"%s \"stop\": {\n"
"%s \"signal\": \"%s\",\n"
"%s \"timeout\": %u,\n"
"%s \"scope\": \"%s\"\n"
"%s },\n"
"%s \"reload\": {\n"
"%s \"signal\": \"%s\",\n"
"%s \"propagate\": %s\n"
"%s },\n",
indent,
indent, r->stop_signal,
indent, r->stop_timeout,
indent, r->stop_scope,
indent,
indent,
indent, r->reload_signal,
indent, json_bool(r->flux_reload),
indent);
fprintf(fp, "%s \"scripts\": {", indent);
for (i = 0; i < NUM_SCRIPTS; i++) {
if (!r->script[i][0])
continue;
fprintf(fp, "%s\n%s \"%s\": { \"command\": \"%s\", \"timeout\": %u }",
sep, indent, script_names[i], json_escape(r->script[i]), r->script_tmo[i]);
sep = ",";
}
if (sep[0])
fprintf(fp, "\n%s ", indent);
fprintf(fp, "},\n");
sep = "";
fprintf(fp, "%s \"directories\": {", indent);
for (i = 0; i < NUM_SVCDIRS; i++) {
if (!r->dir[i][0])
continue;
fprintf(fp, "%s\n%s \"%s\": { \"name\": \"%s\", \"mode\": \"%04o\" }",
sep, indent, dir_names[i], json_escape(r->dir[i]), r->dir_mode[i]);
sep = ",";
}
if (sep[0])
fprintf(fp, ",\n%s \"preserve\": \"%s\"\n%s ", indent, r->preserve, indent);
fprintf(fp, "},\n");
fprintf(fp, "%s \"cgroup-config\": {\n", indent);
fprintf(fp, "%s \"group\": \"%s\",\n", indent, json_escape(r->cgroup_name));
fprintf(fp, "%s \"config\": \"%s\",\n", indent, json_escape(r->cgroup_cfg));
fprintf(fp, "%s \"delegate\": %s\n%s },\n", indent, json_bool(r->cgroup_delegate), indent);
json_rlimits(fp, indent, r->rlimits);
if (!strcmp(r->type, "tty")) {
fprintf(fp, "%s \"tty\": {\n", indent);
fprintf(fp, "%s \"device\": \"%s\",\n", indent, json_escape(r->tty_dev));
fprintf(fp, "%s \"baud\": \"%s\",\n", indent, r->tty_baud);
fprintf(fp, "%s \"term\": \"%s\",\n", indent, json_escape(r->tty_term));
fprintf(fp,
"%s \"noclear\": %s,\n"
"%s \"nowait\": %s,\n"
"%s \"nologin\": %s,\n"
"%s \"notty\": %s,\n"
"%s \"rescue\": %s\n"
"%s },\n",
indent, json_bool(r->tty_noclear),
indent, json_bool(r->tty_nowait),
indent, json_bool(r->tty_nologin),
indent, json_bool(r->tty_notty),
indent, json_bool(r->tty_rescue),
indent);
} else {
fprintf(fp,
"%s \"log\": {\n"
"%s \"enabled\": %s,\n"
"%s \"null\": %s,\n"
"%s \"console\": %s,\n",
indent,
indent, json_bool(r->log),
indent, json_bool(r->log_null),
indent, json_bool(r->log_console));
fprintf(fp, "%s \"file\": \"%s\",\n", indent, json_escape(r->log_file));
fprintf(fp, "%s \"priority\": \"%s\",\n", indent, json_escape(r->log_prio));
fprintf(fp, "%s \"identity\": \"%s\"\n%s },\n", indent, json_escape(r->log_ident), indent);
}
}
static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev) static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev)
{ {
const char *pidfn = pidfile_str(r); const char *pidfn = pidfile_str(r);
@@ -1721,12 +2052,34 @@ static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev)
fprintf(fp, fprintf(fp,
"%s \"condition\": %s,\n", indent, buf); "%s \"condition\": %s,\n", indent, buf);
if (r->manual)
fprintf(fp, fprintf(fp,
"%s \"starts\": %u,\n", indent, r->starts); "%s \"manual\": %s,\n"
"%s \"started\": %s,\n"
fprintf(fp, "%s \"starts\": %u,\n"
"%s \"restarts\": %d,\n", indent, r->restart_tot); /* XXX: add restart_cnt and restart_max */ "%s \"restarts\": %d,\n"
"%s \"restart\": {\n"
"%s \"count\": %d,\n"
"%s \"max\": %d,\n"
"%s \"sec\": %u,\n"
"%s \"delay\": %u,\n"
"%s \"limit\": %u,\n"
"%s \"respawn\": %s,\n"
"%s \"oncrash\": \"%s\"\n"
"%s },\n",
indent, json_bool(r->manual),
indent, json_bool(r->started),
indent, r->starts,
indent, r->restart_tot,
indent,
indent, r->restart_cnt,
indent, r->restart_max,
indent, r->restart_sec,
indent, r->restart_delay,
indent, r->restart_delay_max,
indent, json_bool(r->respawn),
indent, r->oncrash,
indent);
json_settings(fp, r, indent);
/* Add memory and CPU information if cgroup support is available */ /* Add memory and CPU information if cgroup support is available */
if (cgrp && r->pid > 1) { if (cgrp && r->pid > 1) {
@@ -1836,14 +2189,19 @@ static int json_status_one(FILE *fp, struct svc_row *r, char *indent, int prev)
"%s \"pidfile\": \"%s\",\n" "%s \"pidfile\": \"%s\",\n"
"%s \"pid\": %u,\n" "%s \"pid\": %u,\n"
"%s \"user\": \"%s\",\n" "%s \"user\": \"%s\",\n"
"%s \"group\": \"%s\",\n" "%s \"group\": \"%s\",\n",
"%s \"uptime\": %ld,\n"
"%s \"runlevels\": %s\n"
"%s}",
indent, pidfn, indent, pidfn,
indent, r->pid, indent, r->pid,
indent, r->user, indent, r->user,
indent, r->grp, indent, r->grp);
json_list(fp, indent, "groups", r->supgroups);
json_list(fp, indent, "capabilities", r->caps);
if (r->pam[0])
fprintf(fp, "%s \"pam\": \"%s\",\n", indent, json_escape(r->pam));
fprintf(fp,
"%s \"uptime\": %ld,\n"
"%s \"runlevels\": %s\n"
"%s}",
indent, (long)r->uptime, indent, (long)r->uptime,
indent, runlevel_arr((int)r->runlevels), indent, runlevel_arr((int)r->runlevels),
indent); indent);
@@ -1910,6 +2268,9 @@ static int show_one_row(struct svc_row *r)
printf(" Starts : %u\n", r->starts); printf(" Starts : %u\n", r->starts);
printf(" Restarts : %d (%d/%d)\n", printf(" Restarts : %d (%d/%d)\n",
r->restart_tot, r->restart_cnt, r->restart_max); r->restart_tot, r->restart_cnt, r->restart_max);
if (r->restart_delay_max)
printf(" Restart in : %u sec (max %u)\n",
r->restart_delay, r->restart_delay_max);
printf(" Runlevels : %s\n", printf(" Runlevels : %s\n",
runlevel_string(runlevel, (int)r->runlevels)); runlevel_string(runlevel, (int)r->runlevels));
@@ -2025,9 +2386,77 @@ static const struct row_field {
ROW_U32 ("RestartsTotal", restart_tot), ROW_U32 ("RestartsTotal", restart_tot),
ROW_U32 ("RestartCount", restart_cnt), ROW_U32 ("RestartCount", restart_cnt),
ROW_U32 ("RestartMax", restart_max), ROW_U32 ("RestartMax", restart_max),
ROW_U32 ("RestartDelay", restart_delay),
ROW_U32 ("RestartDelayMax", restart_delay_max),
ROW_BOOL("ManualStart", manual), ROW_BOOL("ManualStart", manual),
ROW_BOOL("Forking", forking), ROW_BOOL("Forking", forking),
ROW_BOOL("Started", started), ROW_BOOL("Started", started),
ROW_STR ("Notify", notify),
ROW_BOOL("Remain", remain),
ROW_STR ("If", ifstmt),
ROW_STR ("Provides", provides),
ROW_STR ("Conflicts", conflicts),
ROW_STR ("ExtraGroups", supgroups),
ROW_STR ("Capabilities", caps),
ROW_STR ("Pam", pam),
ROW_STR ("StopSignal", stop_signal),
ROW_U32 ("StopTimeout", stop_timeout),
ROW_STR ("StopScope", stop_scope),
ROW_STR ("ReloadSignal", reload_signal),
ROW_U32 ("RestartSec", restart_sec),
ROW_BOOL("Respawn", respawn),
ROW_STR ("Name", name),
ROW_STR ("Id", id),
ROW_U32 ("Job", job),
ROW_U32 ("OldPid", oldpid),
ROW_BOOL("Dirty", dirty),
ROW_BOOL("Removed", removed),
ROW_BOOL("Starting", starting),
ROW_STR ("Rlimits", rlimits),
ROW_STR ("CgroupName", cgroup_name),
ROW_STR ("CgroupConfig", cgroup_cfg),
ROW_BOOL("CgroupDelegate", cgroup_delegate),
ROW_U32 ("RuntimeDirMode", dir_mode[0]),
ROW_U32 ("StateDirMode", dir_mode[1]),
ROW_U32 ("CacheDirMode", dir_mode[2]),
ROW_U32 ("LogsDirMode", dir_mode[3]),
ROW_U32 ("ConfigDirMode", dir_mode[4]),
ROW_BOOL("Protected", protect),
ROW_BOOL("NoWarn", nowarn),
ROW_BOOL("ReloadPropagate", flux_reload),
ROW_STR ("OnCrash", oncrash),
ROW_STR ("RuntimeDir", dir[0]),
ROW_STR ("StateDir", dir[1]),
ROW_STR ("CacheDir", dir[2]),
ROW_STR ("LogsDir", dir[3]),
ROW_STR ("ConfigDir", dir[4]),
ROW_STR ("RuntimeDirPreserve", preserve),
ROW_STR ("ExecStartPre", script[0]),
ROW_U32 ("ExecStartPreTimeout", script_tmo[0]),
ROW_STR ("ExecStartReady", script[1]),
ROW_U32 ("ExecStartReadyTimeout", script_tmo[1]),
ROW_STR ("ExecStop", script[2]),
ROW_U32 ("ExecStopTimeout", script_tmo[2]),
ROW_STR ("ExecStopPost", script[3]),
ROW_U32 ("ExecStopPostTimeout", script_tmo[3]),
ROW_STR ("ExecReload", script[4]),
ROW_U32 ("ExecReloadTimeout", script_tmo[4]),
ROW_STR ("ExecCleanup", script[5]),
ROW_U32 ("ExecCleanupTimeout", script_tmo[5]),
ROW_BOOL("Log", log),
ROW_BOOL("LogNull", log_null),
ROW_BOOL("LogConsole", log_console),
ROW_STR ("LogFile", log_file),
ROW_STR ("LogPriority", log_prio),
ROW_STR ("LogIdentity", log_ident),
ROW_STR ("TtyDevice", tty_dev),
ROW_STR ("TtyBaud", tty_baud),
ROW_STR ("TtyTerm", tty_term),
ROW_BOOL("TtyNoClear", tty_noclear),
ROW_BOOL("TtyNoWait", tty_nowait),
ROW_BOOL("TtyNoLogin", tty_nologin),
ROW_BOOL("TtyNoTty", tty_notty),
ROW_BOOL("TtyRescue", tty_rescue),
{ NULL, 0, 0, 0 } { NULL, 0, 0, 0 }
}; };
+106 -8
View File
@@ -28,15 +28,17 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <time.h>
#include <unistd.h> #include <unistd.h>
#include "finit.h"
#include "util.h" #include "util.h"
typedef enum { typedef enum {
CMD_UNKNOWN = -1, CMD_UNKNOWN = -1,
CMD_REBOOT = 0, CMD_REBOOT = INIT_CMD_REBOOT,
CMD_HALT, CMD_HALT = INIT_CMD_HALT,
CMD_POWEROFF, CMD_POWEROFF = INIT_CMD_POWEROFF,
CMD_SUSPEND, CMD_SUSPEND = INIT_CMD_SUSPEND,
} cmd_t; } cmd_t;
static cmd_t cmd = CMD_UNKNOWN; static cmd_t cmd = CMD_UNKNOWN;
@@ -49,6 +51,8 @@ extern int do_reboot (char *arg);
extern int do_halt (char *arg); extern int do_halt (char *arg);
extern int do_poweroff(char *arg); extern int do_poweroff(char *arg);
extern int do_suspend (char *arg); extern int do_suspend (char *arg);
extern int do_shutdown_at(int cmd, int sec, const char *msg);
extern int do_shutdown_cancel(void);
static void transform(char *nm) static void transform(char *nm)
@@ -101,18 +105,83 @@ static void do_kill(int signo, char *msg)
do_sleep(5); do_sleep(5);
} }
#define MAX_MIN (365 * 24 * 60) /* Finit takes no more than a year */
/* now, +MIN, or HH:MM, as seconds from now, or -1 */
static int parse_time(const char *arg)
{
struct tm tm;
time_t t, at;
int hh, mm;
char *end;
long min;
char c;
if (!strcmp(arg, "now"))
return 0;
if (arg[0] == '+') {
min = strtol(&arg[1], &end, 10);
if (end == &arg[1] || *end || min < 0 || min > MAX_MIN)
return -1;
return (int)min * 60;
}
if (sscanf(arg, "%d:%d%c", &hh, &mm, &c) != 2 || hh < 0 || hh > 23 || mm < 0 || mm > 59)
return -1;
/* Next time the clock shows HH:MM, today or tomorrow */
t = time(NULL);
localtime_r(&t, &tm);
tm.tm_hour = hh;
tm.tm_min = mm;
tm.tm_sec = 0;
tm.tm_isdst = -1;
at = mktime(&tm);
if (at <= t) {
tm.tm_mday++;
tm.tm_isdst = -1;
at = mktime(&tm);
}
return (int)(at - t);
}
static int schedule(int sec, const char *text)
{
char tm[32];
time_t at;
if (do_shutdown_at(cmd, sec, text))
errx(1, "Failed scheduling %s.", msg);
if (sec > 0) {
at = time(NULL) + sec;
strftime(tm, sizeof(tm), "%a %Y-%m-%d %H:%M", localtime(&at));
printf("Scheduled %s at %s, use 'shutdown -c' to cancel.\n", msg, tm);
}
return 0;
}
static int usage(int rc) static int usage(int rc)
{ {
fprintf(stderr, "Usage: %s [OPTIONS]\n\n" int sd = !strcmp(prognm, "shutdown");
fprintf(stderr, "Usage: %s [OPTIONS]%s\n\n"
"Options:\n" "Options:\n"
" -?, --help This help text\n" " -?, --help This help text\n"
" -c Cancel a scheduled shutdown\n"
" -f, --force Force unsafe %s now, do not contact the init system.\n" " -f, --force Force unsafe %s now, do not contact the init system.\n"
" --halt Halt system, regardless of how the command is called.\n" " --halt Halt system, regardless of how the command is called.\n"
" -h Halt or power off after shutdown.\n" " -h Halt or power off after shutdown.\n"
" -P, --poweroff Power-off system, regardless of how the command is called.\n" " -P, --poweroff Power-off system, regardless of how the command is called.\n"
" -r, --reboot Reboot system, regardless of how the command is called.\n" " -r, --reboot Reboot system, regardless of how the command is called.\n"
" -t, --timeout=SEC Force reboot/shutdown after a given timeout\n" " -t, --timeout=SEC Force reboot/shutdown after a given timeout\n"
"\n", prognm, msg); "\n", prognm, sd ? " [TIME [MESSAGE]]" : "", msg);
if (sd)
fprintf(stderr, "TIME is now, +MIN, or HH:MM. Logged-in users are sent MESSAGE as a\n"
"warning, and from five minutes before, new logins are refused.\n\n");
return rc; return rc;
} }
@@ -128,17 +197,21 @@ int reboot_main(int argc, char *argv[])
{"timeout", 1, NULL, 't'}, {"timeout", 1, NULL, 't'},
{NULL, 0, NULL, 0} {NULL, 0, NULL, 0}
}; };
int c, force = 0; int c, force = 0, cancel = 0;
int tmp; int tmp;
/* Initial command taken from program name */ /* Initial command taken from program name */
transform(prognm); transform(prognm);
while ((c = getopt_long(argc, argv, "h?fHPprt:", long_options, NULL)) != EOF) { while ((c = getopt_long(argc, argv, "h?cfHPprt:", long_options, NULL)) != EOF) {
switch(c) { switch(c) {
case '?': case '?':
return usage(0); return usage(0);
case 'c':
cancel = 1;
break;
case 'f': case 'f':
force = 1; force = 1;
break; break;
@@ -176,6 +249,31 @@ int reboot_main(int argc, char *argv[])
if (getenv("SULOGIN")) if (getenv("SULOGIN"))
force = 1; force = 1;
if (cancel)
return do_shutdown_cancel();
/* shutdown [opts] [TIME [MESSAGE]], see issue #149 */
if (!strcmp(prognm, "shutdown") && optind < argc) {
char text[256] = "";
int sec, i;
sec = parse_time(argv[optind]);
if (sec < 0)
errx(1, "Invalid time '%s', use now, +MIN, or HH:MM.", argv[optind]);
for (i = optind + 1; i < argc; i++) {
if (text[0])
strlcat(text, " ", sizeof(text));
strlcat(text, argv[i], sizeof(text));
}
if (sec > 0 || text[0]) {
if (force)
errx(1, "Cannot schedule a forced %s.", msg);
return schedule(sec, text);
}
}
if (force) { if (force) {
sync(); sync();
+202 -66
View File
@@ -65,8 +65,6 @@
#include "utmp-api.h" #include "utmp-api.h"
#include "schedule.h" #include "schedule.h"
#define NOTIFY_PATH "@run/finit/notify/%d"
int logfile_size_max = 200000; /* 200 kB */ int logfile_size_max = 200000; /* 200 kB */
int logfile_count_max = 5; int logfile_count_max = 5;
@@ -780,20 +778,22 @@ static pid_t service_fork(svc_t *svc)
{ {
gid_t supgids[NGROUPS_MAX]; gid_t supgids[NGROUPS_MAX];
int ngroups = NGROUPS_MAX; int ngroups = NGROUPS_MAX;
int i, j, n = 0; char *sup, *ptr;
int j, n = 0;
/* Get user's supplementary groups from /etc/group */ /* Get user's supplementary groups from /etc/group */
if (getgrouplist(svc->username, gid, supgids, &ngroups) >= 0) if (getgrouplist(svc->username, gid, supgids, &ngroups) >= 0)
n = ngroups; n = ngroups;
/* Add explicitly configured supplementary groups */ /* Add explicitly configured supplementary groups */
for (i = 0; i < svc->num_supgroups && n < NGROUPS_MAX; i++) { for (sup = strtok_r(strdupa(svc->supgroups), ",", &ptr);
int g = getgroup(svc->supgroups[i]); sup && n < NGROUPS_MAX; sup = strtok_r(NULL, ",", &ptr)) {
int g = getgroup(sup);
int found = 0; int found = 0;
if (g < 0) { if (g < 0) {
warn("%s: unknown supplementary group '%s'", warnx("%s: unknown supplementary group '%s'",
svc_ident(svc, NULL, 0), svc->supgroups[i]); svc_ident(svc, NULL, 0), sup);
continue; continue;
} }
/* Skip if already in list from /etc/group */ /* Skip if already in list from /etc/group */
@@ -893,6 +893,26 @@ static int pam_refused(svc_t *svc)
return 1; return 1;
} }
/*
* Bind the systemd notify socket before fork since the daemon may
* notify right away, see issue #505. The kernel picks a unique abstract
* address, which NOTIFY_SOCKET spells with a leading '@'.
*/
static int notify_bind(int sd, char *path, size_t len)
{
struct sockaddr_un sun = { .sun_family = AF_UNIX };
socklen_t slen = sizeof(sun);
if (bind(sd, (struct sockaddr *)&sun, sizeof(sa_family_t)) ||
getsockname(sd, (struct sockaddr *)&sun, &slen))
return -1;
slen -= offsetof(struct sockaddr_un, sun_path) + 1;
snprintf(path, len, "@%.*s", (int)slen, &sun.sun_path[1]);
return 0;
}
/** /**
* service_start - Start service * service_start - Start service
* @svc: Service to start * @svc: Service to start
@@ -902,6 +922,7 @@ static int pam_refused(svc_t *svc)
*/ */
static int service_start(svc_t *svc) static int service_start(svc_t *svc)
{ {
char notify[sizeof(struct sockaddr_un)];
int result = 0, do_progress = 1; int result = 0, do_progress = 1;
char cmdline[CMD_SIZE] = ""; char cmdline[CMD_SIZE] = "";
sigset_t nmask, omask; sigset_t nmask, omask;
@@ -985,6 +1006,12 @@ static int service_start(svc_t *svc)
svc_missing(svc); svc_missing(svc);
return 1; return 1;
} }
if (notify_bind(sd, notify, sizeof(notify))) {
err(1, "%s: failed binding to notify socket", svc_ident(svc, NULL, 0));
close(sd);
svc_missing(svc);
return 1;
}
break; break;
default: default:
break; break;
@@ -1023,31 +1050,16 @@ static int service_start(svc_t *svc)
result = -1; result = -1;
goto fail; goto fail;
} else if (pid > 0) { } else if (pid > 0) {
struct sockaddr_un sun;
size_t len;
dbg("Starting %s as PID %d", svc_ident(svc, NULL, 0), pid); dbg("Starting %s as PID %d", svc_ident(svc, NULL, 0), pid);
svc->pid = pid; svc->pid = pid;
svc->start_time = jiffies(); svc->start_time = jiffies();
switch (svc->notify) { if (fd != -1)
case SVC_NOTIFY_SYSTEMD:
memset(&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
snprintf(sun.sun_path, sizeof(sun.sun_path), NOTIFY_PATH, pid);
len = strlen(sun.sun_path);
sun.sun_path[0] = 0;
result = bind(sd, (struct sockaddr *)&sun, offsetof(struct sockaddr_un, sun_path) + len);
if (result == -1) {
err(1, "%s: failed binding to notify socket", svc_ident(svc, NULL, 0));
close(sd);
break;
}
/* fallthrough */
case SVC_NOTIFY_S6:
if (svc->notify == SVC_NOTIFY_S6)
close(fd); /* client-end of pipefd for s6 notify */ close(fd); /* client-end of pipefd for s6 notify */
switch (svc->notify) {
case SVC_NOTIFY_SYSTEMD:
case SVC_NOTIFY_S6:
result = uev_io_init(ctx, &svc->notify_watcher, service_notify_cb, svc, sd, UEV_READ); result = uev_io_init(ctx, &svc->notify_watcher, service_notify_cb, svc, sd, UEV_READ);
if (result < 0) { if (result < 0) {
err(1, "%s: failed setting up notify callback", svc_ident(svc, NULL, 0)); err(1, "%s: failed setting up notify callback", svc_ident(svc, NULL, 0));
@@ -1058,7 +1070,6 @@ static int service_start(svc_t *svc)
break; break;
} }
} else { /* pid == 0 */ } else { /* pid == 0 */
char str[strlen(NOTIFY_PATH) + 32];
char *args[MAX_NUM_SVC_ARGS + 3]; char *args[MAX_NUM_SVC_ARGS + 3];
int status; int status;
@@ -1067,8 +1078,7 @@ static int service_start(svc_t *svc)
switch (svc->notify) { switch (svc->notify) {
case SVC_NOTIFY_SYSTEMD: case SVC_NOTIFY_SYSTEMD:
snprintf(str, sizeof(str), NOTIFY_PATH, getpid()); setenv("NOTIFY_SOCKET", notify, 1);
setenv("NOTIFY_SOCKET", str, 1);
/* fallthrough */ /* fallthrough */
case SVC_NOTIFY_S6: case SVC_NOTIFY_S6:
close(sd); close(sd);
@@ -1242,6 +1252,15 @@ fail:
return result; return result;
} }
/* The cgroup of the service, or the process group of its main PID */
static int service_signal_all(svc_t *svc, int sig)
{
if (svc_is_cgroup_scope(svc) && !cgroup_signal_svc(svc, sig))
return 0;
return kill(-svc->pid, sig);
}
/** /**
* service_kill - Forcefully terminate a service * service_kill - Forcefully terminate a service
* @param svc Service to kill * @param svc Service to kill
@@ -1485,7 +1504,10 @@ int service_stop(svc_t *svc)
* entire group. This gives the process time to properly stop * entire group. This gives the process time to properly stop
* and/or forward TERM to its children. If it does not respond * and/or forward TERM to its children. If it does not respond
* in within a reasonable timeout we SIGKILL the entire group. * in within a reasonable timeout we SIGKILL the entire group.
* With stop-scope cgroup, all of the cgroup gets SIGTERM,
* if the service has one.
*/ */
if (svc->stop_scope != SVC_SCOPE_CGROUP || cgroup_signal_svc(svc, svc->sighalt))
rc = kill(svc->pid, svc->sighalt); rc = kill(svc->pid, svc->sighalt);
dbg("kill(%d, %d) => rc %d, errno %d", svc->pid, svc->sighalt, rc, errno); dbg("kill(%d, %d) => rc %d, errno %d", svc->pid, svc->sighalt, rc, errno);
/* PID lost or forking process never really started */ /* PID lost or forking process never really started */
@@ -1991,6 +2013,51 @@ static void parse_sighalt(svc_t *svc, char *arg)
svc->sighalt = signo; svc->sighalt = signo;
} }
static svc_scope_t parse_scope(svc_t *svc, const char *arg)
{
svc_scope_t i;
if (!arg)
return SVC_SCOPE_PGROUP;
for (i = SVC_SCOPE_PGROUP; i <= SVC_SCOPE_MIXED; i++) {
if (!strcmp(arg, svc_scope_str(i)))
return i;
}
warnx("%s: unknown stop-scope '%s', using pgroup", svc_ident(svc, NULL, 0), arg);
return SVC_SCOPE_PGROUP;
}
/*
* A cgroup scope also reaches other services sharing the cgroup.
* Only checked for a new or changed service, not on every reload.
*/
static void scope_check(svc_t *svc)
{
char a[MAX_ARG_LEN], b[MAX_ARG_LEN];
svc_t *s, *iter = NULL;
if (!svc_is_changed(svc) || !cgroup_svc_has(svc))
return;
cgroup_svc_name(svc, a, sizeof(a));
for (s = svc_iterator(&iter, 1); s; s = svc_iterator(&iter, 0)) {
svc_t *scoped = svc_is_cgroup_scope(svc) ? svc : s;
if (s == svc || !svc_is_cgroup_scope(scoped))
continue;
if (svc_is_tty(s) != svc_is_tty(svc) || strcmp(s->cgroup.name, svc->cgroup.name) ||
strcmp(cgroup_svc_name(s, b, sizeof(b)), a))
continue;
logit(LOG_WARNING, "%s: stop-scope %s also reaches %s, give it a cgroup name of its own",
svc_ident(scoped, a, sizeof(a)), svc_scope_str(scoped->stop_scope),
svc_ident(scoped == svc ? s : svc, b, sizeof(b)));
return;
}
}
static void parse_killdelay(svc_t *svc, char *delay) static void parse_killdelay(svc_t *svc, char *delay)
{ {
const char *errstr; const char *errstr;
@@ -2240,7 +2307,7 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
{ {
char *cmd, *runlevels = NULL, *cond = NULL; char *cmd, *runlevels = NULL, *cond = NULL;
char *username = NULL, *log = NULL, *pid = NULL; char *username = NULL, *log = NULL, *pid = NULL;
char *name = NULL, *halt = NULL, *delay = NULL; char *name = NULL, *halt = NULL, *delay = NULL, *scope = NULL;
char *id = NULL, *env = NULL, *cgroup = NULL; char *id = NULL, *env = NULL, *cgroup = NULL;
char *pre_script = NULL, *post_script = NULL; char *pre_script = NULL, *post_script = NULL;
char *ready_script = NULL, *conflict = NULL; char *ready_script = NULL, *conflict = NULL;
@@ -2258,6 +2325,7 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
int forking = 0, manual = 0, remain = 0, nowarn = 0; int forking = 0, manual = 0, remain = 0, nowarn = 0;
int restart_max = SVC_RESPAWN_MAX; int restart_max = SVC_RESPAWN_MAX;
int restart_tmo = 0; int restart_tmo = 0;
int restart_tmo_max = 0;
unsigned oncrash_action = SVC_ONCRASH_IGNORE; unsigned oncrash_action = SVC_ONCRASH_IGNORE;
char *line, *args; char *line, *args;
svc_t *svc; svc_t *svc;
@@ -2321,10 +2389,17 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
else else
restart_max = atoi(arg); restart_max = atoi(arg);
} }
else if (MATCH_CMD(cmd, "restarttmo:", arg)) /* compat alias */ else if (MATCH_CMD(cmd, "restart-sec:", arg) ||
restart_tmo = atoi(arg) * 1000; MATCH_CMD(cmd, "restart_sec:", arg) || /* compat alias */
else if (MATCH_CMD(cmd, "restart_sec:", arg)) MATCH_CMD(cmd, "restarttmo:", arg)) /* compat alias */
restart_tmo = atoi(arg) * 1000; restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "restart-max-sec:", arg)) {
const char *errstr;
restart_tmo_max = (int)strtonum(arg, 0, 86400, &errstr) * 1000;
if (errstr)
warnx("restart-max-sec %s is %s (0-86400), ignoring", arg, errstr);
}
else if (!strcasecmp(cmd, "norestart")) else if (!strcasecmp(cmd, "norestart"))
restart_max = 0; restart_max = 0;
else if (!strcasecmp(cmd, "nowarn")) else if (!strcasecmp(cmd, "nowarn"))
@@ -2341,6 +2416,8 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
halt = arg; halt = arg;
else if (MATCH_CMD(cmd, "kill:", arg)) else if (MATCH_CMD(cmd, "kill:", arg))
delay = arg; delay = arg;
else if (MATCH_CMD(cmd, "stop-scope:", arg))
scope = arg;
else if (MATCH_CMD(cmd, "pre:", arg)) else if (MATCH_CMD(cmd, "pre:", arg))
pre_script = arg; pre_script = arg;
else if (MATCH_CMD(cmd, "post:", arg)) else if (MATCH_CMD(cmd, "post:", arg))
@@ -2490,10 +2567,13 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
svc_unblock(svc); svc_unblock(svc);
} }
svc->group[0] = 0;
svc->supgroups[0] = 0;
if (username) { if (username) {
char *ptr = strchr(username, ':'); char *ptr = strchr(username, ':');
if (ptr) { if (ptr) {
size_t len = sizeof(svc->supgroups);
char *sup; char *sup;
*ptr++ = 0; *ptr++ = 0;
@@ -2501,20 +2581,15 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
sup = strchr(ptr, ','); sup = strchr(ptr, ',');
if (sup) { if (sup) {
*sup++ = 0; *sup++ = 0;
svc->num_supgroups = 0; if (strlcpy(svc->supgroups, sup, len) >= len) {
while (sup) { /* Drop the cut-off name, it may match another group */
char *next = strchr(sup, ','); sup = strrchr(svc->supgroups, ',');
if (next) if (sup)
*next++ = 0; *sup = 0;
if (svc->num_supgroups >= MAX_NUM_SUPGROUPS) { else
warn("%s: too many supplementary groups, max %d", svc->supgroups[0] = 0;
svc->cmd, MAX_NUM_SUPGROUPS); warnx("%s: supplementary group list too long, max %zu characters",
break; svc->cmd, len - 1);
}
strlcpy(svc->supgroups[svc->num_supgroups], sup,
sizeof(svc->supgroups[0]));
svc->num_supgroups++;
sup = next;
} }
} }
strlcpy(svc->group, ptr, sizeof(svc->group)); strlcpy(svc->group, ptr, sizeof(svc->group));
@@ -2563,6 +2638,7 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
parse_killdelay(svc, delay); parse_killdelay(svc, delay);
else else
svc->killdelay = SVC_TERM_TIMEOUT; svc->killdelay = SVC_TERM_TIMEOUT;
svc->stop_scope = parse_scope(svc, scope);
if (pre_script) if (pre_script)
parse_script(svc, "pre", pre_script, &svc->pre_tmo, svc->pre_script, sizeof(svc->pre_script)); parse_script(svc, "pre", pre_script, &svc->pre_tmo, svc->pre_script, sizeof(svc->pre_script));
else else
@@ -2669,6 +2745,7 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
svc->forking = forking; svc->forking = forking;
svc->restart_max = restart_max; svc->restart_max = restart_max;
svc->restart_tmo = restart_tmo; svc->restart_tmo = restart_tmo;
svc->restart_tmo_max = restart_tmo_max;
svc->oncrash_action = oncrash_action; svc->oncrash_action = oncrash_action;
/* Decode any (optional) pid:/optional/path/to/file.pid */ /* Decode any (optional) pid:/optional/path/to/file.pid */
@@ -2701,6 +2778,7 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
/* TTYs need a longer default to throttle errors (e.g., missing device) */ /* TTYs need a longer default to throttle errors (e.g., missing device) */
if (svc_is_tty(svc) && svc->restart_tmo == 0) if (svc_is_tty(svc) && svc->restart_tmo == 0)
svc->restart_tmo = 2000; svc->restart_tmo = 2000;
svc->restart_saved = svc->restart_tmo;
/* Set configured limits */ /* Set configured limits */
memcpy(svc->rlimit, rlimit, sizeof(svc->rlimit)); memcpy(svc->rlimit, rlimit, sizeof(svc->rlimit));
@@ -2728,6 +2806,7 @@ svc_t *service_register_desc(int type, char *cfg, const char *desc,
svc_mark_dirty(svc); svc_mark_dirty(svc);
svc_enable(svc); svc_enable(svc);
scope_check(svc);
/* for finit native services only, e.g. plugins/hotplug.c */ /* for finit native services only, e.g. plugins/hotplug.c */
if (!file) if (!file)
@@ -2870,9 +2949,11 @@ void service_monitor(pid_t lost, int status)
logit(LOG_CONSOLE | LOG_NOTICE, "Stopped %s[%d]", svc_ident(svc, NULL, 0), lost); logit(LOG_CONSOLE | LOG_NOTICE, "Stopped %s[%d]", svc_ident(svc, NULL, 0), lost);
} }
/* Terminate any children in the same proess group, e.g. logit */ /* Terminate lingering children, e.g. logit, unless stop-scope says not to */
dbg("Killing lingering children in same process group ..."); if (svc->stop_scope != SVC_SCOPE_PROCESS) {
kill(-svc->pid, SIGKILL); dbg("Killing lingering children ...");
service_signal_all(svc, SIGKILL);
}
/* Try removing PID file (in case service does not clean up after itself) */ /* Try removing PID file (in case service does not clean up after itself) */
if (svc_is_daemon(svc) || svc_is_tty(svc)) { if (svc_is_daemon(svc) || svc_is_tty(svc)) {
@@ -3186,10 +3267,61 @@ static void service_cleanup_script(svc_t *svc)
service_timeout_after(svc, svc->cleanup_tmo, service_kill_script); service_timeout_after(svc, svc->cleanup_tmo, service_kill_script);
} }
/* Doubles with the instability index, up to restart-max-sec, issue #306 */
static int restart_backoff(svc_t *svc, int cnt)
{
int tmo = svc->restart_saved;
/* No restart-sec, the first restart was immediate */
if (tmo < 1000) {
tmo = 2000;
cnt--;
}
while (cnt-- > 0 && tmo < svc->restart_tmo_max)
tmo = tmo > svc->restart_tmo_max / 2 ? svc->restart_tmo_max : tmo * 2;
return tmo;
}
/* Delay before the next restart of a crashing service */
static int restart_delay(svc_t *svc)
{
int half;
if (svc->restart_tmo_max)
return restart_backoff(svc, svc->restart_cnt);
/* Wait 2s for the first half of the attempts, then back off to 5s */
half = (svc->restart_max == -1 ? SVC_RESPAWN_MAX : svc->restart_max) / 2;
/* If a longer timeout was specified in the conf, use that instead. */
return max(svc->restart_tmo, svc->restart_cnt <= half ? 2000 : 5000);
}
/*
* Saturates, restart always has no restart_max to stop the count.
* It stops where the back-off peaks, so aging soon brings it down.
*/
static void restart_cnt_inc(svc_t *svc)
{
int *restart_cnt = (int *)&svc->restart_cnt;
int limit = INT_MAX;
if (svc->restart_max == -1) {
if (!svc->restart_tmo_max)
limit = SVC_RESPAWN_MAX;
else if (*restart_cnt && restart_backoff(svc, *restart_cnt) >= svc->restart_tmo_max)
return;
}
if (*restart_cnt < limit)
(*restart_cnt)++;
}
static void service_retry(svc_t *svc) static void service_retry(svc_t *svc)
{ {
char *restart_cnt = (char *)&svc->restart_cnt; int *restart_cnt = (int *)&svc->restart_cnt;
int timeout;
service_timeout_cancel(svc); service_timeout_cancel(svc);
@@ -3243,15 +3375,10 @@ static void service_retry(svc_t *svc)
return; return;
} }
(*restart_cnt)++; restart_cnt_inc(svc);
dbg("%s crashed, trying to start it again, attempt %d", svc_ident(svc, NULL, 0), *restart_cnt); dbg("%s crashed, trying to start it again, attempt %d", svc_ident(svc, NULL, 0), *restart_cnt);
if ((*restart_cnt) == 1) svc->restart_tmo = restart_delay(svc);
svc->restart_saved = svc->restart_tmo;
/* Wait 2s for the first 5 respawns, then back off to 5s */
timeout = ((*restart_cnt) <= (svc->restart_max / 2)) ? 2000 : 5000;
/* If a longer timeout was specified in the conf, use that instead. */
svc->restart_tmo = max(svc->restart_tmo, timeout);
if (WIFEXITED(svc->status)) if (WIFEXITED(svc->status))
logit(LOG_CONSOLE|LOG_WARNING, logit(LOG_CONSOLE|LOG_WARNING,
"Service %s[%d] died (exit status: %d), restarting (retry in %d msec) (attempt: %d/%d)", "Service %s[%d] died (exit status: %d), restarting (retry in %d msec) (attempt: %d/%d)",
@@ -3352,16 +3479,26 @@ static void svc_set_state(svc_t *svc, svc_state_t new_state)
/* /*
* Called by pidfile plugin for forking services that have successfully started. * Called by pidfile plugin for forking services that have successfully started.
* We get here when the service_monitor() collects the PID, sets svc->pid to 0, * We get here when the service_monitor() collects the PID, sets svc->pid to 0,
* and the state machine prepares for the worst bu setting state to HALTED. * and the state machine prepares for the worst by setting state to HALTED.
*
* Returns 1 if the service is now running, 0 if it was stopped or disabled
* while waiting for its PID file, then the late daemon is stopped.
*/ */
void service_forked(svc_t *svc) int service_forked(svc_t *svc)
{ {
/* Stop forking_retry() timer */ /* Stop forking_retry() timer */
service_timeout_cancel(svc); service_timeout_cancel(svc);
/* Not crashing, restore RUNNING state */ /* Not crashing, restore RUNNING state, but keep a user stop */
if (!svc_is_stopped(svc))
svc_unblock(svc); svc_unblock(svc);
svc_set_state(svc, SVC_RUNNING_STATE); svc_set_state(svc, SVC_RUNNING_STATE);
/* Follow-up to issue #452, RUNNING and not enabled -> service_stop() */
if (!svc_enabled(svc))
service_step(svc);
return svc_is_running(svc);
} }
/* Set or clear service/foo/ready condition for services and call optional ready:script */ /* Set or clear service/foo/ready condition for services and call optional ready:script */
@@ -3389,7 +3526,6 @@ void service_ready(svc_t *svc, int ready)
*/ */
int service_step(svc_t *svc) int service_step(svc_t *svc)
{ {
char *restart_cnt = (char *)&svc->restart_cnt;
int changed = 0, waiting = 0; int changed = 0, waiting = 0;
svc_state_t old_state; svc_state_t old_state;
cond_state_t cond; cond_state_t cond;
@@ -3580,7 +3716,7 @@ restart:
svc_set_state(svc, SVC_HALTED_STATE); svc_set_state(svc, SVC_HALTED_STATE);
break; break;
} }
(*restart_cnt)++; restart_cnt_inc(svc);
break; break;
} }
@@ -3684,7 +3820,7 @@ restart:
} }
if (!svc->pid) { if (!svc->pid) {
(*restart_cnt)++; restart_cnt_inc(svc);
svc_set_state(svc, SVC_WAITING_STATE); svc_set_state(svc, SVC_WAITING_STATE);
break; break;
} }
@@ -4008,7 +4144,7 @@ static void service_interval_cb(uev_t *w, void *arg, int events)
for (svc = svc_iterator(&iter, 1); svc; svc = svc_iterator(&iter, 0)) { for (svc = svc_iterator(&iter, 1); svc; svc = svc_iterator(&iter, 0)) {
if (svc_is_daemon(svc)) { if (svc_is_daemon(svc)) {
char *restart_cnt = (char *)&svc->restart_cnt; int *restart_cnt = (int *)&svc->restart_cnt;
if (!svc_is_running(svc)) if (!svc_is_running(svc))
continue; continue;
+1 -1
View File
@@ -58,7 +58,7 @@ int service_timeout_after (svc_t *svc, int timeout, void (*cb)(svc_t *svc
int service_timeout_cancel (svc_t *svc); int service_timeout_cancel (svc_t *svc);
void compose_cmdline (svc_t *svc, char *buf, size_t len); void compose_cmdline (svc_t *svc, char *buf, size_t len);
void service_forked (svc_t *svc); int service_forked (svc_t *svc);
void service_ready (svc_t *svc, int ready); void service_ready (svc_t *svc, int ready);
int service_stop (svc_t *svc); int service_stop (svc_t *svc);
+264
View File
@@ -0,0 +1,264 @@
/* Scheduled shutdown with wall messages and nologin, see issue #149
*
* Copyright (c) 2026 Joachim Wiberg <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "config.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <utmp.h>
#include "conf.h"
#include "finit.h"
#include "log.h"
#include "private.h"
#include "schedule.h"
#include "shutdown.h"
#include "sig.h"
#include "sm.h"
#include "util.h"
#include "utmp-api.h"
/* Minutes left at each warning, 0 is the deadline */
static const int warn_at[] = { 60, 30, 15, 10, 5, 4, 3, 2, 1, 0 };
#define NOLOGIN_MIN 5
#define MAX_WAIT 3600 /* sec, keeps the msec timer delay an int */
#define MAX_DELAY (365 * 24 * 3600)
static struct {
int cmd; /* INIT_CMD_REBOOT, _HALT, _POWEROFF, 0: none */
long when; /* Deadline, jiffies() */
int next; /* Minutes left at next warning */
int nologin; /* We created FINIT_NOLOGIN_PATH */
char msg[256];
struct wq work;
} sched;
static const char *action(int cmd)
{
switch (cmd) {
case INIT_CMD_REBOOT:
return "reboot";
case INIT_CMD_HALT:
return "halt";
default:
return "power-off";
}
}
/*
* Write @text to the terminal of every logged-in user. Done in a
* child, reading utmp may wait for its lock and closing a serial
* tty for its output to drain.
*/
static void wall(const char *text)
{
char host[64] = "", tm[32], hdr[160];
struct utmp *ut;
time_t t;
if (!has_utmp() || fork())
return;
t = time(NULL);
gethostname(host, sizeof(host) - 1);
strftime(tm, sizeof(tm), "%a %b %e %H:%M:%S %Y", localtime(&t));
snprintf(hdr, sizeof(hdr), "\r\nBroadcast message from root@%s (%s):\r\n\r\n", host, tm);
setutent();
while ((ut = getutent())) {
char tty[sizeof(ut->ut_line) + 6];
int fd;
if (ut->ut_type != USER_PROCESS || !ut->ut_line[0])
continue;
snprintf(tty, sizeof(tty), "/dev/%.*s", (int)sizeof(ut->ut_line), ut->ut_line);
if (strstr(tty, ".."))
continue;
/* utmp is not ours alone to write, make sure it is a tty */
fd = open(tty, O_WRONLY | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
continue;
if (isatty(fd) && write(fd, hdr, strlen(hdr)) > 0)
(void)!write(fd, text, strlen(text));
close(fd);
}
endutent();
_exit(0);
}
static void announce(int min)
{
char line[80], text[sizeof(sched.msg) + sizeof(line) + 8];
if (min > 0)
snprintf(line, sizeof(line), "The system is going DOWN for %s in %d minute%s!",
action(sched.cmd), min, min > 1 ? "s" : "");
else
snprintf(line, sizeof(line), "The system is going DOWN for %s NOW!", action(sched.cmd));
logit(LOG_CONSOLE | LOG_NOTICE, "%s", line);
snprintf(text, sizeof(text), "%s%s%s\r\n", sched.msg, sched.msg[0] ? "\r\n" : "", line);
wall(text);
}
/* Never touch an admin's nologin, only create and remove our own */
static void nologin(void)
{
FILE *fp;
if (fexist(FINIT_NOLOGIN_PATH))
return;
fp = fopen(FINIT_NOLOGIN_PATH, "w");
if (!fp) {
dbg("Failed creating %s: %s", FINIT_NOLOGIN_PATH, strerror(errno));
return;
}
fprintf(fp, "%s%sThe system is going down for %s.\n", sched.msg,
sched.msg[0] ? "\n" : "", action(sched.cmd));
fclose(fp);
sched.nologin = 1;
}
static void tick(void *arg)
{
long left, wait;
size_t i;
int min;
if (!sched.cmd || IS_RESERVED_RUNLEVEL(runlevel))
return;
left = sched.when - jiffies();
if (left <= 0) {
announce(0);
shutdown_now(sched.cmd, 0);
return;
}
min = (left + 59) / 60;
if (min <= NOLOGIN_MIN)
nologin();
if (min == sched.next)
announce(min);
for (i = 0; warn_at[i] >= min; i++)
;
sched.next = warn_at[i];
wait = left - sched.next * 60;
if (wait > MAX_WAIT)
wait = MAX_WAIT;
sched.work.delay = wait * 1000;
schedule_work(&sched.work);
}
/*
* Reboot, halt, or power off now, replacing any scheduled shutdown.
* A @timeout in seconds arms the emergency shutdown bypass, 0: none.
*/
int shutdown_now(int cmd, int timeout)
{
switch (cmd) {
case INIT_CMD_REBOOT:
halt = SHUT_REBOOT;
break;
case INIT_CMD_HALT:
halt = SHUT_HALT;
break;
case INIT_CMD_POWEROFF:
halt = SHUT_OFF;
break;
default:
return 1;
}
if (sched.cmd) {
sched.cmd = 0;
uev_timer_stop(&sched.work.watcher);
}
shutdown_bypass(timeout);
dbg("%s", action(cmd));
sm_runlevel(cmd == INIT_CMD_REBOOT ? 6 : 0);
return 0;
}
/* Replaces any already scheduled shutdown */
int shutdown_schedule(int cmd, int sec, const char *msg)
{
if (cmd != INIT_CMD_REBOOT && cmd != INIT_CMD_HALT && cmd != INIT_CMD_POWEROFF)
return 1;
if (sec < 0 || sec > MAX_DELAY)
return 1;
/* Our nologin belongs to the shutdown being replaced */
if (sched.nologin) {
erase(FINIT_NOLOGIN_PATH);
sched.nologin = 0;
}
sched.cmd = cmd;
sched.when = jiffies() + sec;
sched.next = (sec + 59) / 60; /* First tick warns */
strlcpy(sched.msg, msg ? msg : "", sizeof(sched.msg));
/* First tick right away, a zero delay would disarm the timer */
sched.work.cb = tick;
sched.work.delay = 1;
return schedule_work(&sched.work);
}
int shutdown_cancel(void)
{
if (!sched.cmd)
return 1;
sched.cmd = 0;
uev_timer_stop(&sched.work.watcher);
if (sched.nologin) {
erase(FINIT_NOLOGIN_PATH);
sched.nologin = 0;
}
logit(LOG_CONSOLE | LOG_NOTICE, "The system shutdown has been cancelled.");
wall("The system shutdown has been cancelled.\r\n");
return 0;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+31
View File
@@ -0,0 +1,31 @@
/* Scheduled shutdown, see issue #149
*
* Copyright (c) 2026 Joachim Wiberg <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef FINIT_SHUTDOWN_H_
#define FINIT_SHUTDOWN_H_
int shutdown_now (int cmd, int timeout);
int shutdown_schedule(int cmd, int sec, const char *msg);
int shutdown_cancel (void);
#endif /* FINIT_SHUTDOWN_H_ */
+85 -4
View File
@@ -101,7 +101,7 @@ typedef enum {
#define MAX_STR_LEN 64 #define MAX_STR_LEN 64
#define MAX_COND_LEN (MAX_ARG_LEN * 3) #define MAX_COND_LEN (MAX_ARG_LEN * 3)
#define MAX_USER_LEN MAX_ARG_LEN #define MAX_USER_LEN MAX_ARG_LEN
#define MAX_NUM_SUPGROUPS 4 #define MAX_SUPGROUPS_LEN (MAX_CMD_LEN * 2)
#define MAX_NUM_PROVIDES 4 #define MAX_NUM_PROVIDES 4
#define MAX_NUM_FDS 64 /* Max number of I/O plugins */ #define MAX_NUM_FDS 64 /* Max number of I/O plugins */
#define MAX_NUM_SVC_ARGS 64 #define MAX_NUM_SVC_ARGS 64
@@ -112,6 +112,14 @@ typedef enum {
/* Prevent endless respawn of faulty services. */ /* Prevent endless respawn of faulty services. */
#define SVC_RESPAWN_MAX 10 #define SVC_RESPAWN_MAX 10
/* stop-scope, issue #413 */
typedef enum {
SVC_SCOPE_PGROUP = 0, /* Signal main PID, SIGKILL its process group */
SVC_SCOPE_PROCESS, /* Main PID only */
SVC_SCOPE_CGROUP, /* Signal all in cgroup, SIGKILL the rest */
SVC_SCOPE_MIXED, /* Signal main PID, SIGKILL rest of cgroup */
} svc_scope_t;
/* /*
* Default enable for all services, can be stopped by means * Default enable for all services, can be stopped by means
* of issuing an initctl call. E.g. * of issuing an initctl call. E.g.
@@ -131,6 +139,7 @@ typedef struct svc {
/* Service details */ /* Service details */
int sighalt; /* Signal to stop process, default: SIGTERM */ int sighalt; /* Signal to stop process, default: SIGTERM */
int killdelay; /* Delay in msec before sending SIGKILL */ int killdelay; /* Delay in msec before sending SIGKILL */
svc_scope_t stop_scope; /* Which processes stop applies to */
pid_t oldpid, pid; pid_t oldpid, pid;
char pidfile[MAX_CMD_LEN]; char pidfile[MAX_CMD_LEN];
long start_time; /* Start time, as seconds since boot, from sysinfo() */ long start_time; /* Start time, as seconds since boot, from sysinfo() */
@@ -168,9 +177,10 @@ typedef struct svc {
int restart_max; /* Maximum number of restarts allowed */ int restart_max; /* Maximum number of restarts allowed */
int restart_saved; /* INTERNAL, saved copy of .conf value */ int restart_saved; /* INTERNAL, saved copy of .conf value */
int restart_tmo; /* Time before restarting a crashing service */ int restart_tmo; /* Time before restarting a crashing service */
int restart_tmo_max;/* restart-max-sec, 0: fixed back-off, issue #306 */
unsigned char oncrash_action; /* Action to perform in crashed state. */ unsigned char oncrash_action; /* Action to perform in crashed state. */
char respawn; /* ttys, or services with `respawn`, never increment restart_cnt */ char respawn; /* ttys, or services with `respawn`, never increment restart_cnt */
const char restart_cnt; /* Incremented for each restart by service monitor. */ const int restart_cnt; /* Incremented for each restart by service monitor. */
union { union {
/* services we redirect stdout/stderr to syslog (not TTYs!) */ /* services we redirect stdout/stderr to syslog (not TTYs!) */
@@ -200,8 +210,7 @@ typedef struct svc {
/* Identity */ /* Identity */
char username[MAX_USER_LEN]; char username[MAX_USER_LEN];
char group[MAX_USER_LEN]; char group[MAX_USER_LEN];
char supgroups[MAX_NUM_SUPGROUPS][MAX_USER_LEN]; char supgroups[MAX_SUPGROUPS_LEN]; /* sup1,sup2,... */
int num_supgroups;
char capabilities[MAX_CMD_LEN]; char capabilities[MAX_CMD_LEN];
char pam[MAX_ARG_LEN]; /* /etc/pam.d/NAME, block format only */ char pam[MAX_ARG_LEN]; /* /etc/pam.d/NAME, block format only */
@@ -325,6 +334,7 @@ static inline void svc_starting (svc_t *svc) { if (svc) svc->starting = 1;
static inline void svc_started (svc_t *svc) { if (svc) svc->starting = 0; } static inline void svc_started (svc_t *svc) { if (svc) svc->starting = 0; }
static inline int svc_is_starting (svc_t *svc) { return svc && 0 != svc->starting; } static inline int svc_is_starting (svc_t *svc) { return svc && 0 != svc->starting; }
static inline int svc_is_running (svc_t *svc) { return svc && svc->state == SVC_RUNNING_STATE; } static inline int svc_is_running (svc_t *svc) { return svc && svc->state == SVC_RUNNING_STATE; }
static inline int svc_is_cgroup_scope(svc_t *svc) { return svc->stop_scope == SVC_SCOPE_CGROUP || svc->stop_scope == SVC_SCOPE_MIXED; }
static inline int svc_is_stopping (svc_t *svc) { return svc && svc->state == SVC_STOPPING_STATE; } static inline int svc_is_stopping (svc_t *svc) { return svc && svc->state == SVC_STOPPING_STATE; }
static inline int svc_is_stopped (svc_t *svc) { return svc && svc->block == SVC_BLOCK_USER; } static inline int svc_is_stopped (svc_t *svc) { return svc && svc->block == SVC_BLOCK_USER; }
@@ -369,6 +379,77 @@ static inline int svc_has_cond(svc_t *svc)
return 0; return 0;
} }
static inline const char *svc_scope_str(svc_scope_t scope)
{
switch (scope) {
case SVC_SCOPE_PGROUP:
return "pgroup";
case SVC_SCOPE_PROCESS:
return "process";
case SVC_SCOPE_CGROUP:
return "cgroup";
case SVC_SCOPE_MIXED:
return "mixed";
}
return "unknown";
}
static inline const char *svc_notify_str(svc_t *svc)
{
switch (svc->notify) {
case SVC_NOTIFY_NONE:
return "none";
case SVC_NOTIFY_PID:
return "pid";
case SVC_NOTIFY_SYSTEMD:
return "systemd";
case SVC_NOTIFY_S6:
return "s6";
}
return "unknown";
}
static inline const char *svc_oncrash_str(svc_t *svc)
{
switch (svc->oncrash_action) {
case SVC_ONCRASH_REBOOT:
return "reboot";
case SVC_ONCRASH_SCRIPT:
return "script";
}
return "ignore";
}
static inline const char *svc_preserve_str(svc_t *svc)
{
switch (svc->dir_preserve) {
case SVC_DIR_PRESERVE_RESTART:
return "restart";
case SVC_DIR_PRESERVE_YES:
return "yes";
}
return "no";
}
/* The conditions in provides, comma separated */
static inline char *svc_provides_str(svc_t *svc, char *buf, size_t len)
{
int i;
buf[0] = 0;
for (i = 0; i < svc->num_provides; i++) {
if (i)
strlcat(buf, ",", len);
strlcat(buf, svc->provides[i], len);
}
return buf;
}
static inline const char *svc_typestr(svc_t *svc) static inline const char *svc_typestr(svc_t *svc)
{ {
switch (svc->type) { switch (svc->type) {
+24
View File
@@ -722,6 +722,30 @@ char *rlim2str(int rlim)
return "unknown"; return "unknown";
} }
/* All of @rlimit as "name=soft:hard,...", a value is a number or unlimited */
char *rlimits2str(struct rlimit *rlimit, char *buf, size_t len)
{
const struct rlimit_name *rn;
size_t pos = 0;
buf[0] = 0;
for (rn = rlimit_names; rn->name && pos < len; rn++) {
rlim_t lim[2] = { rlimit[rn->val].rlim_cur, rlimit[rn->val].rlim_max };
int i;
pos += snprintf(&buf[pos], len - pos, "%s%s", pos ? "," : "", rn->name);
for (i = 0; i < 2 && pos < len; i++) {
if (lim[i] == RLIM_INFINITY)
pos += snprintf(&buf[pos], len - pos, "%cunlimited", i ? ':' : '=');
else
pos += snprintf(&buf[pos], len - pos, "%c%llu", i ? ':' : '=',
(unsigned long long)lim[i]);
}
}
return buf;
}
char *lim2str(struct rlimit *rlim) char *lim2str(struct rlimit *rlim)
{ {
char tmp[25]; char tmp[25];
+1
View File
@@ -95,6 +95,7 @@ char *code2str (int code);
int str2rlim (char *str); int str2rlim (char *str);
char *rlim2str (int rlim); char *rlim2str (int rlim);
char *lim2str (struct rlimit *rlim); char *lim2str (struct rlimit *rlim);
char *rlimits2str (struct rlimit *rlimit, char *buf, size_t len);
void do_sleep (unsigned int sec); void do_sleep (unsigned int sec);
void do_usleep (unsigned int usec); void do_usleep (unsigned int usec);
+12
View File
@@ -38,6 +38,7 @@ EXTRA_DIST += conf-provides.sh
EXTRA_DIST += conf-tty.sh EXTRA_DIST += conf-tty.sh
EXTRA_DIST += conf-dup-title.sh EXTRA_DIST += conf-dup-title.sh
EXTRA_DIST += conf-dirs.sh EXTRA_DIST += conf-dirs.sh
EXTRA_DIST += conf-groups.sh
EXTRA_DIST += conf-if.sh EXTRA_DIST += conf-if.sh
EXTRA_DIST += conf-template.sh EXTRA_DIST += conf-template.sh
EXTRA_DIST += script-timeout.sh EXTRA_DIST += script-timeout.sh
@@ -54,13 +55,17 @@ EXTRA_DIST += keventd.sh
EXTRA_DIST += notify.sh EXTRA_DIST += notify.sh
EXTRA_DIST += pam-session.sh EXTRA_DIST += pam-session.sh
EXTRA_DIST += pidfile.sh EXTRA_DIST += pidfile.sh
EXTRA_DIST += pidfile-stopped.sh
EXTRA_DIST += stale-pidfile.sh EXTRA_DIST += stale-pidfile.sh
EXTRA_DIST += stop-scope.sh
EXTRA_DIST += shutdown-sched.sh
EXTRA_DIST += pre-post-serv.sh EXTRA_DIST += pre-post-serv.sh
EXTRA_DIST += pre-fail.sh EXTRA_DIST += pre-fail.sh
EXTRA_DIST += process-depends.sh EXTRA_DIST += process-depends.sh
EXTRA_DIST += rclocal.sh EXTRA_DIST += rclocal.sh
EXTRA_DIST += ready-serv.sh EXTRA_DIST += ready-serv.sh
EXTRA_DIST += remain-task-control.sh EXTRA_DIST += remain-task-control.sh
EXTRA_DIST += restart-backoff.sh
EXTRA_DIST += restart-self.sh EXTRA_DIST += restart-self.sh
EXTRA_DIST += runlevel.sh EXTRA_DIST += runlevel.sh
EXTRA_DIST += run-restart-forever.sh EXTRA_DIST += run-restart-forever.sh
@@ -68,6 +73,7 @@ EXTRA_DIST += run-task-tricks.sh
EXTRA_DIST += runparts.sh EXTRA_DIST += runparts.sh
EXTRA_DIST += sysvparts.sh EXTRA_DIST += sysvparts.sh
EXTRA_DIST += start-stop-service.sh EXTRA_DIST += start-stop-service.sh
EXTRA_DIST += status-json.sh
EXTRA_DIST += start-stop-service-sub-config.sh EXTRA_DIST += start-stop-service-sub-config.sh
EXTRA_DIST += start-kill-service.sh EXTRA_DIST += start-kill-service.sh
EXTRA_DIST += start-kill-stop.sh EXTRA_DIST += start-kill-stop.sh
@@ -106,6 +112,7 @@ TESTS += conf-provides.sh
TESTS += conf-tty.sh TESTS += conf-tty.sh
TESTS += conf-dup-title.sh TESTS += conf-dup-title.sh
TESTS += conf-dirs.sh TESTS += conf-dirs.sh
TESTS += conf-groups.sh
TESTS += conf-if.sh TESTS += conf-if.sh
TESTS += conf-template.sh TESTS += conf-template.sh
TESTS += script-timeout.sh TESTS += script-timeout.sh
@@ -124,13 +131,17 @@ endif
TESTS += notify.sh TESTS += notify.sh
TESTS += pam-session.sh TESTS += pam-session.sh
TESTS += pidfile.sh TESTS += pidfile.sh
TESTS += pidfile-stopped.sh
TESTS += stale-pidfile.sh TESTS += stale-pidfile.sh
TESTS += stop-scope.sh
TESTS += shutdown-sched.sh
TESTS += pre-post-serv.sh TESTS += pre-post-serv.sh
TESTS += pre-fail.sh TESTS += pre-fail.sh
TESTS += process-depends.sh TESTS += process-depends.sh
TESTS += rclocal.sh TESTS += rclocal.sh
TESTS += ready-serv.sh TESTS += ready-serv.sh
TESTS += remain-task-control.sh TESTS += remain-task-control.sh
TESTS += restart-backoff.sh
TESTS += restart-self.sh TESTS += restart-self.sh
TESTS += runlevel.sh TESTS += runlevel.sh
TESTS += sysvparts.sh TESTS += sysvparts.sh
@@ -138,6 +149,7 @@ TESTS += run-restart-forever.sh
TESTS += run-task-tricks.sh TESTS += run-task-tricks.sh
TESTS += runparts.sh TESTS += runparts.sh
TESTS += start-stop-service.sh TESTS += start-stop-service.sh
TESTS += status-json.sh
TESTS += start-stop-service-sub-config.sh TESTS += start-stop-service-sub-config.sh
TESTS += start-kill-service.sh TESTS += start-kill-service.sh
TESTS += start-kill-stop.sh TESTS += start-kill-stop.sh
+36
View File
@@ -11,6 +11,42 @@ directory it will be able to function properly without having any super user
privileges in the host environment. privileges in the host environment.
Requirements
------------
On Debian, Ubuntu, and Linux Mint, install the build dependencies and
the tools the tests use:
sudo apt install build-essential autoconf automake libtool pkg-config \
libconfuse-dev libblkid-dev libcap-dev libpam0g-dev \
uidmap jq wget dbus shellcheck
* `uidmap` has `newuidmap` and `newgidmap`, which `unshare` needs to
set up the namespace of each test. Without it every test fails with
`unshare: failed to execute newuidmap`. Your user also needs a range
in `/etc/subuid` and `/etc/subgid`, which `adduser` sets up
* `jq` is used by the tests that read `initctl -j`
* `wget` fetches the BusyBox binary for the test root, on the first run
* `dbus` has the `dbus-daemon` and `dbus-send` that the D-Bus broker
test stages in the test root, without them that test is skipped
* `shellcheck` is used by the `checkself.sh` test, which checks the
test scripts themselves
* `libcap-dev` and `libpam0g-dev` are optional for Finit. Without
the latter the PAM session test is skipped
Finit also needs [libuEv][] v2.4.1 and [libite][] v2.6.1, or later. The
`libuev-dev` and `libite-dev` packages may be older, check with:
apt-cache policy libuev-dev libite-dev
In Ubuntu 24.04, `libuev-dev` is new enough but `libite-dev` is not, so
libite has to be built and installed from source, see the [build
instructions](../doc/build.md).
[libuEv]: https://github.com/troglobit/libuev
[libite]: https://github.com/troglobit/libite
Running tests Running tests
------------- -------------
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
# Verify group and extra-groups are set on the service, and that
# dropping either setting drops the group(s) too.
set -eu
TEST_DIR=$(dirname "$0")
# Optional arguments are the extra-groups list and the group
write_conf()
{
run "echo 'service grp {' > $FINIT_CONF"
run "echo ' user = \"root\"' >> $FINIT_CONF"
if [ -n "${2:-}" ]; then
run "echo ' group = \"$2\"' >> $FINIT_CONF"
fi
if [ -n "${1:-}" ]; then
run "echo ' extra-groups = { $1 }' >> $FINIT_CONF"
fi
run "echo ' command = \"serv -np -i grp\"' >> $FINIT_CONF"
run "echo '}' >> $FINIT_CONF"
}
# Kernel sorts the list, so it compares as a plain string.
assert_groups()
{
pid=$(texec initctl -j status grp | jq .pid)
assert "Service groups == $1" \
"$(texec cat "/proc/$pid/status" | sed -n 's/^Groups:[[:space:]]*//p' | xargs)" = "$1"
}
assert_gid()
{
pid=$(texec initctl -j status grp | jq .pid)
assert "Service gid == $1" \
"$(texec cat "/proc/$pid/status" | awk '/^Gid:/ {print $2}')" = "$1"
}
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
say 'Seven extra groups'
write_conf '"daemon", "bin", "sys", "adm", "tty", "disk", "dialout"' root
run "initctl reload"
retry 'assert_num_children 1 serv'
retry 'assert_groups "0 1 2 3 4 5 6 20"'
# The running process keeps its groups, the next start drops them
say 'Dropping extra-groups drops the groups'
write_conf
run "initctl reload"
run "initctl restart grp"
retry 'assert_groups "0"'
say 'Dropping group drops the group'
write_conf "" adm
run "initctl reload"
run "initctl restart grp"
retry 'assert_gid 4'
write_conf
run "initctl reload"
run "initctl restart grp"
retry 'assert_gid 0'
+8
View File
@@ -39,6 +39,14 @@ run "ip link del probe0"
sep "keventd readiness" sep "keventd readiness"
retry 'assert_ready "keventd"' 50 0.2 retry 'assert_ready "keventd"' 50 0.2
# Finit does not touch a daemon-owned pidfile, so keventd must do it
# after SIGHUP to reassert readiness, see issue #503. Signalled with
# kill to keep Finit out of it.
sep "keventd touches its pidfile on SIGHUP"
run "touch -d '2000-01-01 00:00' /run/keventd.pid"
run "kill -HUP $(texec cat /run/keventd.pid)"
retry "test \$(texec stat -c %Y /run/keventd.pid) -gt 1000000000" 10 0.2
sep "interface add asserts <class/net/dummy0>" sep "interface add asserts <class/net/dummy0>"
cat >> "$SYSROOT$FINIT_CONF" <<EOF cat >> "$SYSROOT$FINIT_CONF" <<EOF
service serv { service serv {
+84
View File
@@ -0,0 +1,84 @@
#!/bin/sh
# Verify that a PID file written by someone else does not make a stopped
# or waiting service look started, see issue #452. E.g., a container
# started by hand with podman, outside of Finit.
set -eu
TEST_DIR=$(dirname "$0")
PIDFN=/run/ext.pid
# Stand-in for the process started outside of Finit
external()
{
say "Starting a process outside of Finit, it writes $PIDFN"
run "sh -c 'sleep 100 & echo \$! > $PIDFN'"
# Negative check, give the pidfile plugin time to (not) react
sleep 2
}
cleanup()
{
run "kill \$(cat $PIDFN 2>/dev/null) 2>/dev/null || true"
run "rm -f $PIDFN /bin/late.sh /tmp/late"
}
test_teardown()
{
say "Running test teardown."
cleanup
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'A stopped forking service stays stopped'
run "echo 'service name:ext pid:!$PIDFN serv -p -P $PIDFN -- External' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status ext running'
run "initctl stop ext"
retry 'assert_status ext stopped'
run "rm -f $PIDFN"
external
assert_status ext stopped
assert_nocond pid/ext
cleanup
sep
say 'A service waiting for its condition stays waiting'
run "echo 'service name:ext pid:!$PIDFN <usr/never> serv -p -P $PIDFN -- External' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status ext waiting'
external
assert_status ext waiting
assert_nocond pid/ext
cleanup
# A forking daemon whose launcher exits before the daemon has written
# its PID file. A stop in that window must hold, and the daemon that
# shows up late must be stopped, not adopted as running.
sep
say 'A forking service stopped before its PID file appears stays stopped'
# Unquoted END, $PIDFN expands here. /tmp/late marks the daemon start
cat > "$SYSROOT/bin/late.sh" <<END
#!/bin/sh
( sleep 1; touch /tmp/late; exec serv -n -p -P $PIDFN ) &
END
chmod +x "$SYSROOT/bin/late.sh"
run "echo 'service name:ext pid:!$PIDFN late.sh -- Late' > $FINIT_CONF"
run "initctl reload"
run "initctl stop ext"
retry 'assert_file_exists /tmp/late'
# Negative check, give the pidfile plugin time to (not) react
sleep 1
assert_status ext stopped
assert_nocond pid/ext
assert_num_children 0 serv
+89
View File
@@ -0,0 +1,89 @@
#!/bin/sh
# Verify the delay between restarts of a crashing service. It logs
# the uptime, in centiseconds, of each start and then exits.
set -eu
TEST_DIR=$(dirname "$0")
STARTS=/tmp/starts
# Wait for start $2, then check the delay since start $1, in sec
assert_delay()
{
retry "texec sh -c 'test \$(wc -l < $STARTS) -ge $2'" 150 0.1
# shellcheck disable=SC2016 # $1 is awk's field reference, not the shell's
delay=$(texec awk -v a="$1" -v b="$2" 'NR == a { t = $1 } NR == b { print $1 - t }' $STARTS)
assert "Delay between start $1 and $2 is $3-$4 sec" "$delay" -ge "$(($3 * 100))"
assert "Delay between start $1 and $2 is $3-$4 sec" "$delay" -le "$(($4 * 100))"
}
# Replace the service, settings in $1, and let it start crashing
crash()
{
run "rm -f $FINIT_CONF"
run "initctl reload"
run "rm -f $STARTS"
run "cat > $FINIT_CONF" <<CONF
service crash {
$1
command = "crash.sh"
}
CONF
run "initctl reload"
}
# Same, with the line-based format, options in $1
crash_line()
{
run "rm -f $FINIT_CONF"
run "initctl reload"
run "rm -f $STARTS"
run "echo 'service $1 crash.sh -- Crashing' > $FINIT_CONF"
run "initctl reload"
}
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF $STARTS /bin/crash.sh"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
cat > "$SYSROOT/bin/crash.sh" <<SCRIPT
#!/bin/sh
tr -d . < /proc/uptime | cut -d' ' -f1 >> $STARTS
exit 1
SCRIPT
chmod +x "$SYSROOT/bin/crash.sh"
sep
say 'restart always, at once the first time, then every other second'
crash 'restart = "always"'
assert_delay 1 2 0 1
assert_delay 2 3 2 3
assert_delay 3 4 2 3
sep
say 'restart-max-sec, the delay doubles from restart-sec up to the limit'
crash 'restart = "always"
restart-sec = 1
restart-max-sec = 4'
assert_delay 1 2 1 2
assert_delay 2 3 2 3
assert_delay 3 4 4 5
assert_delay 4 5 4 5
say 'The restart counter stops where the delay peaks'
assert "Delay and limit in status" "$(texec initctl status crash | sed -n 's/.*Restart in : //p')" = "4 sec (max 4)"
run "initctl -j status crash"
assert "Same in JSON" "$(texec initctl -j status crash | jq -c .restart)" = '{"count":2,"max":-1,"sec":1,"delay":4,"limit":4,"respawn":false,"oncrash":"ignore"}'
assert "Restart counter is 2" "$(texec initctl status crash | awk '/Restarts/{ print $4 }')" = "(2/-1)"
sep
say 'restart-sec in the line-based format, and its old spelling'
crash_line 'restart:always restart-sec:3'
assert_delay 1 2 3 4
crash_line 'restart:always restart_sec:3'
assert_delay 1 2 3 4
+59
View File
@@ -0,0 +1,59 @@
#!/bin/sh
# Verify scheduled shutdown, see issue #149: shutdown TIME [MESSAGE]
# blocks new logins from five minutes before, and shutdown -c cancels
# it. The countdown never runs out here, it is always cancelled.
set -eu
TEST_DIR=$(dirname "$0")
NOLOGIN=/etc/nologin
# Assert that the command, run in the test namespace, fails
fails()
{
assert "$1 fails" "$(texec sh -c "$1 >/dev/null 2>&1 || echo fail")" = fail
}
test_teardown()
{
say "Running test teardown."
run "shutdown -c 2>/dev/null || true"
run "rm -f $NOLOGIN"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep
say 'Schedule a reboot in two minutes, within the nologin window'
run "shutdown -r +2 Testing scheduled reboot"
retry "assert_file_contains $NOLOGIN 'Testing scheduled reboot'"
say 'Cancel it, nologin is removed and the system stays up'
run "shutdown -c"
retry "texec sh -c '! test -e $NOLOGIN'"
assert "Still in runlevel 2" "$(texec initctl runlevel | awk '{print $2}')" = 2
sep
say 'Nothing to cancel'
fails "shutdown -c"
say 'An invalid time is refused'
fails "shutdown -r 25:00"
fails "shutdown -r +999999999"
sep
say 'A later shutdown replaces it, and its nologin'
run "shutdown -r +2 First"
retry "assert_file_contains $NOLOGIN First"
run "shutdown -r +120 Second"
retry "texec sh -c '! test -e $NOLOGIN'"
run "shutdown -c"
sep
say 'A nologin file of the admin is left alone'
run "echo 'Down for maintenance' > $NOLOGIN"
run "shutdown -h +2"
sleep 1 # first tick, where nologin would be written
run "shutdown -c"
assert_file_contains $NOLOGIN 'Down for maintenance'
+98
View File
@@ -0,0 +1,98 @@
#!/bin/sh
# Verify initctl -j status: it has the settings of a service, and gives
# the same over D-Bus as over the initctl socket.
set -eu
TEST_DIR=$(dirname "$0")
BUS=/run/finit/bus
# Check member $1 of the JSON status in $json
assert_json()
{
assert "$1 is $2" "$(echo "$json" | jq -c "$1")" = "$2"
}
test_teardown()
{
say "Running test teardown."
run "test -e $BUS.hidden && mv $BUS.hidden $BUS || true"
run "rm -f $FINIT_CONF"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
run "cat > $FINIT_CONF" <<CONF
service json {
description = "JSON status"
notify = "pid"
stop-signal = "SIGINT"
stop-timeout = 5
stop-scope = "process"
restart-max = 3
restart-sec = 2
restart-max-sec = 8
oncrash = "script"
exec-stop-post = "/bin/true"
exec-stop-post-timeout = 7
runtime-dir = "json"
runtime-dir-mode = 0750
rlimit {
soft.nofile = 123
hard.nofile = 456
core = unlimited
}
cgroup maint { cpu.weight = 250 }
runtime-dir-preserve = "restart"
extra-groups = { "daemon", "bin" }
provides = { "usr/json-a", "usr/json-b" }
conflicts = { "nosuch" }
log {
identity = "jason"
}
command = "serv -np -i json"
}
CONF
run "initctl reload"
retry 'assert_status json running'
sep
say 'The settings of the service are in the JSON status'
run "initctl -j status json"
json=$(texec initctl -j status json)
assert_json .notify '"pid"'
assert_json .remain 'false'
assert_json .stop '{"signal":"SIGINT","timeout":5,"scope":"process"}'
assert_json .reload.signal '"SIGHUP"'
assert_json .restart.max '3'
assert_json .restart.sec '2'
assert_json .restart.limit '8'
assert_json .restart.respawn 'false'
assert_json .restart.oncrash '"script"'
assert_json .scripts '{"exec-stop-post":{"command":"/bin/true","timeout":7}}'
assert_json .directories '{"runtime":{"name":"json","mode":"0750"},"preserve":"restart"}'
assert_json .rlimits.nofile '{"soft":123,"hard":456}'
assert_json .rlimits.core '{"soft":"unlimited","hard":"unlimited"}'
assert_json '."cgroup-config"' '{"group":"maint","config":"cpu.weight:250","delegate":false}'
assert_json .name '"json"'
assert_json .protected 'false'
assert_json .id '""'
assert_json .internal.removed 'false'
assert_json .internal.oldpid '0'
assert_json .reload.propagate 'false'
assert_json .groups '["daemon","bin"]'
assert_json .provides '["usr/json-a","usr/json-b"]'
assert_json .conflicts '["nosuch"]'
assert_json .log.enabled 'true'
assert_json .log.identity '"jason"'
if texec test -e $BUS; then
sep
say 'Same over the initctl socket, with the bus hidden'
run "mv $BUS $BUS.hidden"
legacy=$(texec initctl -j status json)
run "mv $BUS.hidden $BUS"
assert "Same JSON from both" "$(echo "$json" | jq -cS 'del(.uptime)')" = "$(echo "$legacy" | jq -cS 'del(.uptime)')"
fi
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Verify stop-scope, which processes a stop applies to, see issue #413.
# The service leaves a child behind in its process group, like the
# action script of avahi-autoipd. Cgroups are not available in the
# test namespace, so cgroup and mixed fall back to the process group.
set -eu
TEST_DIR=$(dirname "$0")
CHILD=/tmp/scope-child
# Start the service, stop it, and check if its child is still there.
# Optional second argument is the stop-scope.
stop_one()
{
sep
say "stop-scope ${2:-default}, child is left $1"
run "rm -f $CHILD"
run "cat > $FINIT_CONF" <<EOF
service scope {
${2:+stop-scope = "$2"}
command = "scope.sh"
}
EOF
run "initctl reload"
run "initctl start scope"
retry 'assert_status scope running'
retry "texec test -s $CHILD"
run "initctl stop scope"
retry 'assert_status scope stopped'
if [ "$1" = alive ]; then
assert "Child is alive" "$(texec sh -c "kill -0 \$(cat $CHILD) && echo yes")" = yes
run "kill \$(cat $CHILD)"
else
retry "texec sh -c '! kill -0 \$(cat $CHILD) 2>/dev/null'"
fi
}
test_teardown()
{
say "Running test teardown."
run "kill \$(cat $CHILD 2>/dev/null) 2>/dev/null || true"
run "rm -f $FINIT_CONF $CHILD /bin/scope.sh"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
cat > "$SYSROOT/bin/scope.sh" <<EOF
#!/bin/sh
sleep 100 &
echo \$! > $CHILD
exec serv -np -i scope
EOF
chmod +x "$SYSROOT/bin/scope.sh"
stop_one dead
stop_one dead pgroup
stop_one alive process
stop_one dead cgroup
stop_one dead mixed