systemd_linux.go 2.0 KB

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