Class Systemd

java.lang.Object
com.github.jpmsilva.jsystemd.Systemd

public class Systemd extends Object
The main systemd integration class.

Implements and exposes most of the sd_notify protocol, as well as some convenience methods.

Applications are expected to:

  1. get the instance with instance(), as early as possible, optionally enabling the periodic tasks they need: status updates with enableStatusUpdate(Duration), watchdog heartbeats with enableWatchdog(), timeout extensions with enableExtendTimeout(Duration, Duration); each can be changed or disabled at any time;
  2. optionally, register status providers with addStatusProviders(StatusProvider...), and health providers with addHealthProviders(HealthProvider...);
  3. call ready() once the application has started;
  4. on shutdown, call stopping() before stopping the application, which also stops the watchdog heartbeats;
  5. call close() last, once the application has stopped, to stop the periodic tasks; it also calls stopping(), 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 Details

    • instance

      public static Systemd 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

      public void addStatusProviders(StatusProvider... providers)
      Adds the status providers to the end of the list of providers.
      Parameters:
      providers - the providers to add
    • addStatusProviders

      public void addStatusProviders(List<StatusProvider> providers)
      Adds the status providers to the end of the list of providers.
      Parameters:
      providers - the providers to add
    • addStatusProviders

      public void addStatusProviders(int index, StatusProvider... providers)
      Adds the status providers to the list of providers in the specified position.
      Parameters:
      index - position to add the providers
      providers - the providers to add
    • addStatusProviders

      public void addStatusProviders(int index, List<StatusProvider> providers)
      Adds the status providers to the list of providers in the specified position.
      Parameters:
      index - position to add the providers
      providers - the providers to add
    • removeStatusProviders

      public void removeStatusProviders(StatusProvider... providers)
      Removes the status providers from the list of providers. Providers that are not registered are ignored.
      Parameters:
      providers - the providers to remove
    • removeStatusProviders

      public void removeStatusProviders(List<StatusProvider> providers)
      Removes the status providers from the list of providers. Providers that are not registered are ignored.
      Parameters:
      providers - the providers to remove
    • getStatusProviders

      public List<StatusProvider> 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

      public void addHealthProviders(HealthProvider... providers)
      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

      public void addHealthProviders(List<HealthProvider> providers)
      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

      public void addHealthProviders(int index, HealthProvider... providers)
      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 providers
      providers - the providers to add
    • addHealthProviders

      public void addHealthProviders(int index, List<HealthProvider> providers)
      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 providers
      providers - the providers to add
    • removeHealthProviders

      public void removeHealthProviders(HealthProvider... providers)
      Removes the health providers from the list of health providers. Providers that are not registered are ignored.
      Parameters:
      providers - the providers to remove
    • removeHealthProviders

      public void removeHealthProviders(List<HealthProvider> providers)
      Removes the health providers from the list of health providers. Providers that are not registered are ignored.
      Parameters:
      providers - the providers to remove
    • getHealthProviders

      public List<HealthProvider> 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

      public void enableStatusUpdate(Duration period)
      Enables the periodic status updates, which send the status to systemd with updateStatus() 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

      public void enableWatchdog(Duration period)
      Enables the periodic watchdog heartbeats, which are sent with watchdog() 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 sets WatchdogSec. The heartbeats are sent at half the interval systemd sets in the WATCHDOG_USEC environment variable, as systemd recommends. When the variable is not set, this method does nothing.
      Throws:
      IllegalStateException - if WATCHDOG_USEC is 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 after WatchdogSec, and kills it, unless the application is stopping.
      See Also:
    • enableExtendTimeout

      public void enableExtendTimeout(Duration period, Duration amount)
      Enables the periodic extension of the timeout that systemd enforces while the application starts up or stops: TimeoutStartSec until ready() is called, and TimeoutStopSec once stopping() 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 extend RuntimeMaxSec instead 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 microsecond
      amount - the amount of time to extend the timeout by, each time, which must be of at least a microsecond; also used by extendTimeout() 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.
      See Also:
    • updateStatus

      public void updateStatus()
      Forces the current status to be calculated and sent to systemd. The method enableStatusUpdate(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 as ready(); 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 with enableExtendTimeout(Duration, Duration), or 29 seconds otherwise.

      The timeout is only extended while the application starts up or stops, that is, before ready() is called, extending TimeoutStartSec, or once stopping() is called, extending TimeoutStopSec. Nothing is sent while the application runs, as systemd would then extend RuntimeMaxSec instead.

      See Also:
    • watchdog

      public void watchdog()
      Forces the watchdog timestamp to be updated. The methods enableWatchdog() and enableWatchdog(Duration) can be used to enable periodic watchdog updates.

      The watchdog timestamp is only updated once ready() is called, and until stopping() is called: systemd only enforces the watchdog once the startup is complete, and enforces TimeoutStartSec until 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 extend RuntimeMaxSec instead. 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:
      true if and only if ready() or stopping() 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, with extendTimeout() 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 the NOTIFY_SOCKET environment 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 for vsock: addresses, the native libsystemd library could be loaded. When it does not, the notifications do nothing.
      Returns:
      true if the application runs under systemd
    • watchdogTimeout

      public static Optional<Duration> watchdogTimeout()
      Returns the watchdog timeout of the service unit, that is, the WatchdogSec it sets, which systemd passes to the application in the WATCHDOG_USEC environment 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

      public void close() throws InterruptedException
      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 the WatchdogSec of the service unit, and does not consider the application hung, and kill it, if the rest of its shutdown takes longer than that. Calling stopping() 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