systemd_linux.go 2.0 KB

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