notify.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package systemd
  2. import (
  3. "fmt"
  4. "sync"
  5. "github.com/coreos/go-systemd/v22/daemon"
  6. "github.com/rclone/rclone/fs"
  7. "github.com/rclone/rclone/lib/atexit"
  8. )
  9. // Notify systemd that the service is ready. This returns a
  10. // function which should be called to notify that the service is
  11. // stopping. This function will be called on exit if the service exits
  12. // on a signal.
  13. // NOTE: this function should only be called once, and so it
  14. // should generally only be used directly in a command's Run handler.
  15. // It should not be called as a result of rc commands. See #7540.
  16. func Notify() func() {
  17. if _, err := daemon.SdNotify(false, daemon.SdNotifyReady); err != nil {
  18. fs.Logf(nil, "failed to notify ready to systemd: %v", err)
  19. }
  20. var finaliseOnce sync.Once
  21. finalise := func() {
  22. finaliseOnce.Do(func() {
  23. if _, err := daemon.SdNotify(false, daemon.SdNotifyStopping); err != nil {
  24. fs.Logf(nil, "failed to notify stopping to systemd: %v", err)
  25. }
  26. })
  27. }
  28. finaliseHandle := atexit.Register(finalise)
  29. return func() {
  30. atexit.Unregister(finaliseHandle)
  31. finalise()
  32. }
  33. }
  34. // UpdateStatus updates the systemd status
  35. func UpdateStatus(status string) error {
  36. systemdStatus := fmt.Sprintf("STATUS=%s", status)
  37. _, err := daemon.SdNotify(false, systemdStatus)
  38. return err
  39. }