Skip to content

Commit

Permalink
Merge pull request #2 from orobio/get-watchdog-configuration-from-sys…
Browse files Browse the repository at this point in the history
…temd

Get watchdog configuration from systemd
  • Loading branch information
xtremekforever authored Sep 4, 2024
2 parents 708c66f + b9854af commit e94f67d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 10 deletions.
23 changes: 23 additions & 0 deletions Sources/Systemd/SystemdHelpers.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@

#if os(Linux)
import Glibc
import CSystemd
#endif

import Foundation

public struct SystemdHelpers {
public static let isSystemdService: Bool = getIsSystemdService()
public static let watchdogTimeout: Duration? = getWatchdogTimeout()

public static var watchdogEnabled: Bool { watchdogTimeout != nil }
public static var watchdogRecommendedNotifyInterval: Duration? { watchdogTimeout.map { $0 / 2 } }

private static func getIsSystemdService() -> Bool {
#if os(Linux)
Expand All @@ -22,4 +27,22 @@ public struct SystemdHelpers {

return false
}

private static func getWatchdogTimeout() -> Duration? {
#if os(Linux)
var usec: UInt64 = 0
let ret = sd_watchdog_enabled(0, &usec)
if ret > 0 {
return .microseconds(usec)
} else if ret == 0 {
return nil // Watchdog disabled
} else {
let error = String(cString: strerror(-ret))
print("Unable to get watchdog configuration: \(error)")
return nil
}
#else
return nil
#endif
}
}
16 changes: 6 additions & 10 deletions Sources/SystemdLifecycle/SystemdService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,20 @@ import ServiceLifecycle
import Systemd

public struct SystemdService: Service {
private let _watchdogEnabled: Bool
private let _watchdogInterval: Duration

public init(watchdogEnabled: Bool = false,
watchdogInterval: Duration = .seconds(5)) {
_watchdogEnabled = watchdogEnabled
_watchdogInterval = watchdogInterval
}
public init() {}

public func run() async throws {
let notifier = SystemdNotifier()

// Send ready signal at startup
notifier.notify(ServiceState.Ready)


// Run the task until cancelled
for await _ in AsyncTimerSequence(interval: _watchdogInterval, clock: .continuous).cancelOnGracefulShutdown() {
if _watchdogEnabled {
let watchdogEnabled = SystemdHelpers.watchdogEnabled
let interval = SystemdHelpers.watchdogRecommendedNotifyInterval ?? .seconds(3600)
for await _ in AsyncTimerSequence(interval: interval, clock: .continuous).cancelOnGracefulShutdown() {
if watchdogEnabled {
notifier.notify(ServiceState.Watchdog)
}
}
Expand Down

0 comments on commit e94f67d

Please sign in to comment.