systemd_linux.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build linux
  4. package systemd
  5. import (
  6. "errors"
  7. "log"
  8. "os"
  9. "sync"
  10. "github.com/mdlayher/sdnotify"
  11. )
  12. var getNotifyOnce struct {
  13. sync.Once
  14. v *sdnotify.Notifier
  15. }
  16. type logOnce struct {
  17. sync.Once
  18. }
  19. func (l *logOnce) logf(format string, args ...any) {
  20. l.Once.Do(func() {
  21. log.Printf(format, args...)
  22. })
  23. }
  24. var (
  25. readyOnce = &logOnce{}
  26. statusOnce = &logOnce{}
  27. )
  28. func notifier() *sdnotify.Notifier {
  29. getNotifyOnce.Do(func() {
  30. var err error
  31. getNotifyOnce.v, err = sdnotify.New()
  32. // Not exist means probably not running under systemd, so don't log.
  33. if err != nil && !errors.Is(err, os.ErrNotExist) {
  34. log.Printf("systemd: systemd-notifier error: %v", err)
  35. }
  36. })
  37. return getNotifyOnce.v
  38. }
  39. // Ready signals readiness to systemd. This will unblock service dependents from starting.
  40. func Ready() {
  41. err := notifier().Notify(sdnotify.Ready)
  42. if err != nil {
  43. readyOnce.logf("systemd: error notifying: %v", err)
  44. }
  45. }
  46. // Status sends a single line status update to systemd so that information shows up
  47. // in systemctl output. For example:
  48. //
  49. // $ systemctl status tailscale
  50. // ● tailscale.service - Tailscale client daemon
  51. // Loaded: loaded (/nix/store/qc312qcy907wz80fqrgbbm8a9djafmlg-unit-tailscale.service/tailscale.service; enabled; vendor preset: enabled)
  52. // Active: active (running) since Tue 2020-11-24 17:54:07 EST; 13h ago
  53. // Main PID: 26741 (.tailscaled-wra)
  54. // Status: "Connected; [email protected]; 100.101.102.103"
  55. // IP: 0B in, 0B out
  56. // Tasks: 22 (limit: 4915)
  57. // Memory: 30.9M
  58. // CPU: 2min 38.469s
  59. // CGroup: /system.slice/tailscale.service
  60. // └─26741 /nix/store/sv6cj4mw2jajm9xkbwj07k29dj30lh0n-tailscale-date.20200727/bin/tailscaled --port 41641
  61. func Status(format string, args ...any) {
  62. err := notifier().Notify(sdnotify.Statusf(format, args...))
  63. if err != nil {
  64. statusOnce.logf("systemd: error notifying: %v", err)
  65. }
  66. }