Class Systemd
Implements and exposes most of the sd_notify protocol, as well as some convenience methods.
Applications are expected to:
- get the instance with
instance(), as early as possible, optionally enabling the periodic tasks they need: status updates withenableStatusUpdate(Duration), watchdog heartbeats withenableWatchdog(), timeout extensions withenableExtendTimeout(Duration, Duration); each can be changed or disabled at any time; - optionally, register status providers with
addStatusProviders(StatusProvider...), and health providers withaddHealthProviders(HealthProvider...); - call
ready()once the application has started; - on shutdown, call
stopping()before stopping the application, which also stops the watchdog heartbeats; - call
close()last, once the application has stopped, to stop the periodic tasks; it also callsstopping(), if not called before.
There is a single instance per process, as systemd follows a service through a single process, which goes through a single startup and a single
shutdown: once closed, the instance has told systemd that the application is stopping, so there is nothing left to tell. When not running under systemd,
as told by isUnderSystemd(), the instance can still be used, but nothing reaches systemd.
All methods can be called from any thread.
The periodic tasks are scheduled with a resolution of a microsecond, the one systemd uses for its own intervals, such as WATCHDOG_USEC:
their periods are truncated to whole microseconds, and must be of at least a microsecond.
- Author:
- Joao Silva
-
Method Summary
Modifier and TypeMethodDescriptionvoidaddHealthProviders(int index, HealthProvider... providers) Adds the health providers to the list of health providers in the specified position.voidaddHealthProviders(int index, List<HealthProvider> providers) Adds the health providers to the list of health providers in the specified position.voidaddHealthProviders(HealthProvider... providers) Adds the health providers to the end of the list of health providers.voidaddHealthProviders(List<HealthProvider> providers) Adds the health providers to the end of the list of health providers.voidaddStatusProviders(int index, StatusProvider... providers) Adds the status providers to the list of providers in the specified position.voidaddStatusProviders(int index, List<StatusProvider> providers) Adds the status providers to the list of providers in the specified position.voidaddStatusProviders(StatusProvider... providers) Adds the status providers to the end of the list of providers.voidaddStatusProviders(List<StatusProvider> providers) Adds the status providers to the end of the list of providers.voidclose()Stops the periodic tasks of this instance: the status updates, the watchdog heartbeats and the periodic extension of the timeout.voidDisables the periodic extension of the timeout.voidDisables the periodic status updates.voidDisables the periodic watchdog heartbeats.voidenableExtendTimeout(Duration period, Duration amount) Enables the periodic extension of the timeout that systemd enforces while the application starts up or stops:TimeoutStartSecuntilready()is called, andTimeoutStopSeconcestopping()is called.voidenableStatusUpdate(Duration period) Enables the periodic status updates, which send the status to systemd withupdateStatus()at the given period.voidEnables the periodic watchdog heartbeats when systemd expects them, that is, when the service unit setsWatchdogSec.voidenableWatchdog(Duration period) Enables the periodic watchdog heartbeats, which are sent withwatchdog()at the given period, once the application is ready.voidForces the timeout to be extended.Returns a read only snapshot of the current health providers.Returns a read only snapshot of the current providers.static Systemdinstance()Returns the instance of this process, creating it on first use.booleanisReady()Returns if the startup of the application is over.static booleanReturns if the application runs under systemd, that is, if the notifications sent to systemd reach it: the operating system is Linux, systemd set theNOTIFY_SOCKETenvironment variable, and the notifications could be set up: on Java 22 and later, with the Foreign Function and Memory API, unless native access is denied, and otherwise, as on Java 17 to 21 or forvsock:addresses, the native libsystemd library could be loaded.voidLogs information regarding the status of the integration with systemd.voidready()Notifies systemd that the application is ready.voidremoveHealthProviders(HealthProvider... providers) Removes the health providers from the list of health providers.voidremoveHealthProviders(List<HealthProvider> providers) Removes the health providers from the list of health providers.voidremoveStatusProviders(StatusProvider... providers) Removes the status providers from the list of providers.voidremoveStatusProviders(List<StatusProvider> providers) Removes the status providers from the list of providers.voidstopping()Signals that the application is stopping.voidForces the current status to be calculated and sent to systemd.voidwatchdog()Forces the watchdog timestamp to be updated.Returns the watchdog timeout of the service unit, that is, theWatchdogSecit sets, which systemd passes to the application in theWATCHDOG_USECenvironment variable.
-
Method Details
-
instance
Returns the instance of this process, creating it on first use. Creating it does not notify systemd, nor start any periodic task.- Returns:
- the instance of this process, which is the same on every call, even once closed
-
addStatusProviders
Adds the status providers to the end of the list of providers.- Parameters:
providers- the providers to add
-
addStatusProviders
Adds the status providers to the end of the list of providers.- Parameters:
providers- the providers to add
-
addStatusProviders
Adds the status providers to the list of providers in the specified position.- Parameters:
index- position to add the providersproviders- the providers to add
-
addStatusProviders
Adds the status providers to the list of providers in the specified position.- Parameters:
index- position to add the providersproviders- the providers to add
-
removeStatusProviders
Removes the status providers from the list of providers. Providers that are not registered are ignored.- Parameters:
providers- the providers to remove
-
removeStatusProviders
Removes the status providers from the list of providers. Providers that are not registered are ignored.- Parameters:
providers- the providers to remove
-
getStatusProviders
Returns a read only snapshot of the current providers. Later changes to the providers are not reflected in the returned list.- Returns:
- the current list of providers
-
addHealthProviders
Adds the health providers to the end of the list of health providers. The watchdog heartbeat is only sent while all of them report the application as healthy.- Parameters:
providers- the providers to add
-
addHealthProviders
Adds the health providers to the end of the list of health providers. The watchdog heartbeat is only sent while all of them report the application as healthy.- Parameters:
providers- the providers to add
-
addHealthProviders
Adds the health providers to the list of health providers in the specified position. The watchdog heartbeat is only sent while all of them report the application as healthy.- Parameters:
index- position to add the providersproviders- the providers to add
-
addHealthProviders
Adds the health providers to the list of health providers in the specified position. The watchdog heartbeat is only sent while all of them report the application as healthy.- Parameters:
index- position to add the providersproviders- the providers to add
-
removeHealthProviders
Removes the health providers from the list of health providers. Providers that are not registered are ignored.- Parameters:
providers- the providers to remove
-
removeHealthProviders
Removes the health providers from the list of health providers. Providers that are not registered are ignored.- Parameters:
providers- the providers to remove
-
getHealthProviders
Returns a read only snapshot of the current health providers. Later changes to the providers are not reflected in the returned list.- Returns:
- the current list of health providers
-
enableStatusUpdate
Enables the periodic status updates, which send the status to systemd withupdateStatus()at the given period. If already enabled, they are rescheduled at the new period. Does nothing once this instance is closed.- Parameters:
period- the period to use, which must be of at least a microsecond- Throws:
IllegalArgumentException- if the period is shorter than a microsecond- See Also:
-
disableStatusUpdate
public void disableStatusUpdate()Disables the periodic status updates. Does nothing if they are not enabled.- See Also:
-
enableWatchdog
Enables the periodic watchdog heartbeats, which are sent withwatchdog()at the given period, once the application is ready. If already enabled, they are rescheduled at the new period. Does nothing once the application is stopping, as no heartbeat is sent from then on, nor once this instance is closed. The periodic heartbeats stop once the application is stopping.- Parameters:
period- the period to use, which must be of at least a microsecond- Throws:
IllegalArgumentException- if the period is shorter than a microsecond- See Also:
-
enableWatchdog
public void enableWatchdog()Enables the periodic watchdog heartbeats when systemd expects them, that is, when the service unit setsWatchdogSec. The heartbeats are sent at half the interval systemd sets in theWATCHDOG_USECenvironment variable, as systemd recommends. When the variable is not set, this method does nothing.- Throws:
IllegalStateException- ifWATCHDOG_USECis 1, as half of it is shorter than a microsecond, the resolution of the periodic tasks- See Also:
-
disableWatchdog
public void disableWatchdog()Disables the periodic watchdog heartbeats. Does nothing if they are not enabled. Once the heartbeats stop, systemd considers the application hung afterWatchdogSec, and kills it, unless the application is stopping.- See Also:
-
enableExtendTimeout
Enables the periodic extension of the timeout that systemd enforces while the application starts up or stops:TimeoutStartSecuntilready()is called, andTimeoutStopSeconcestopping()is called. If already enabled, it is rescheduled at the new period.Enabled while the application starts up, it extends the startup, and stops once the application is ready, or once it starts stopping, so that the extension of the startup never carries over to the shutdown, where it would keep a hung shutdown from ever timing out. Enabled once the application is ready, or stopping, it extends the shutdown, until this instance is closed: enabled while the application runs, it only starts extending the timeout once
stopping()is called, as systemd would extendRuntimeMaxSecinstead until then, so that the shutdown can be prepared for in advance. Does nothing once this instance is closed.- Parameters:
period- the period to use, which must be of at least a microsecondamount- the amount of time to extend the timeout by, each time, which must be of at least a microsecond; also used byextendTimeout()from then on- Throws:
IllegalArgumentException- if the period or the amount is shorter than a microsecond- See Also:
-
disableExtendTimeout
public void disableExtendTimeout()Disables the periodic extension of the timeout. Does nothing if it is not enabled. -
updateStatus
public void updateStatus()Forces the current status to be calculated and sent to systemd. The methodenableStatusUpdate(Duration)can be used to enable periodic status updates.If there are no status providers, nothing is sent to systemd. A status provider that throws, or returns
null, is left out of the status, as it would otherwise fail the caller, such asready(); the first of its consecutive failures is logged as a warning.A status longer than systemd accepts, of 4089 bytes in UTF-8, is cut to fit, between two of its characters, and ends with an ellipsis: what is cut is what the last status providers show.
Concurrent updates do not wait for each other. The status is not sent if an update that started later was sent first, so that systemd is never left with an older status than the latest one sent.
-
extendTimeout
public void extendTimeout()Forces the timeout to be extended. The amount of time to extend by is the one of the periodic extension of the timeout, if enabled withenableExtendTimeout(Duration, Duration), or 29 seconds otherwise.The timeout is only extended while the application starts up or stops, that is, before
ready()is called, extendingTimeoutStartSec, or oncestopping()is called, extendingTimeoutStopSec. Nothing is sent while the application runs, as systemd would then extendRuntimeMaxSecinstead.- See Also:
-
watchdog
public void watchdog()Forces the watchdog timestamp to be updated. The methodsenableWatchdog()andenableWatchdog(Duration)can be used to enable periodic watchdog updates.The watchdog timestamp is only updated once
ready()is called, and untilstopping()is called: systemd only enforces the watchdog once the startup is complete, and enforcesTimeoutStartSecuntil then. If any health provider reports the application as unhealthy, the watchdog timestamp is not updated either. -
ready
public void ready()Notifies systemd that the application is ready. Also disables the periodic extension of the startup timeout, as the startup timeout no longer applies, and systemd would extendRuntimeMaxSecinstead. A periodic extension of the shutdown, enabled once ready, is left enabled.Only the first call notifies systemd, later calls have no effect. Does nothing once the application is stopping.
- See Also:
-
isReady
public boolean isReady()Returns if the startup of the application is over.- Returns:
trueif and only ifready()orstopping()have been called, as an application can stop before it is ready
-
stopping
public void stopping()Signals that the application is stopping. From then on, no more watchdog heartbeats are sent, and the periodic watchdog heartbeats are disabled, as is the periodic extension of the startup timeout, if the application stops before it is ready. The timeout can still be extended while the application stops, withextendTimeout()or by a periodic extension of the shutdown, enabled once ready or once stopping, which is left enabled.Only the first call notifies systemd, later calls have no effect.
close()calls this method, if not called before. -
isUnderSystemd
public static boolean isUnderSystemd()Returns if the application runs under systemd, that is, if the notifications sent to systemd reach it: the operating system is Linux, systemd set theNOTIFY_SOCKETenvironment variable, and the notifications could be set up: on Java 22 and later, with the Foreign Function and Memory API, unless native access is denied, and otherwise, as on Java 17 to 21 or forvsock:addresses, the native libsystemd library could be loaded. When it does not, the notifications do nothing.- Returns:
trueif the application runs under systemd
-
watchdogTimeout
Returns the watchdog timeout of the service unit, that is, theWatchdogSecit sets, which systemd passes to the application in theWATCHDOG_USECenvironment variable.- Returns:
- the watchdog timeout, or empty if the variable is not set, as when the service unit does not enable the watchdog, or not running under systemd
-
logStatus
public void logStatus()Logs information regarding the status of the integration with systemd. Meant to be used once the application has done sufficient work to initialize logging.When running under systemd, logs the notify socket and the periodic tasks that are enabled. Otherwise, logs why not: a warning with the cause when systemd expects notifications, but they could not be set up, as when the native libsystemd library cannot be loaded on Java 17 to 21, since systemd then receives no notifications, or a debug message otherwise.
-
close
Stops the periodic tasks of this instance: the status updates, the watchdog heartbeats and the periodic extension of the timeout. Waits for running tasks to finish, for up to 10 seconds each, before interrupting them. Status and health providers must therefore not call this method, as they run within those tasks.As the watchdog heartbeats stop, this method first calls
stopping(), if not called before, so that systemd stops enforcing theWatchdogSecof the service unit, and does not consider the application hung, and kill it, if the rest of its shutdown takes longer than that. Callingstopping()as soon as the application starts shutting down is still recommended, as systemd keeps enforcing the watchdog until then.As systemd is told that the application is stopping, only close the instance when the application shuts down. A closed instance cannot be reopened:
instance()keeps returning it, and enabling periodic tasks has no effect.Notifications sent directly to systemd, such as
updateStatus(), keep working once closed, as they do not depend on the periodic tasks. This allows the application to keep notifying systemd while shutting down.watchdog()no longer sends heartbeats, as the application is stopping.Calling this method more than once only waits, as the first call does, for the running tasks to finish: every call returns once the periodic tasks have stopped, even when it races with another call.
- Throws:
InterruptedException- if interrupted while waiting for the running tasks to finish
-