restart.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Package sysutil provides system-level utilities for process management.
  2. package sysutil
  3. import (
  4. "log"
  5. "os"
  6. "runtime"
  7. "time"
  8. )
  9. // RestartService triggers a service restart by gracefully exiting.
  10. //
  11. // This relies on systemd's Restart=always configuration to automatically
  12. // restart the service after it exits. This is the industry-standard approach:
  13. // - Simple and reliable
  14. // - No sudo permissions needed
  15. // - No complex process management
  16. // - Leverages systemd's native restart capability
  17. //
  18. // Prerequisites:
  19. // - Linux OS with systemd
  20. // - Service configured with Restart=always in systemd unit file
  21. func RestartService() error {
  22. if runtime.GOOS != "linux" {
  23. log.Println("Service restart via exit only works on Linux with systemd")
  24. return nil
  25. }
  26. log.Println("Initiating service restart by graceful exit...")
  27. log.Println("systemd will automatically restart the service (Restart=always)")
  28. // Give a moment for logs to flush and response to be sent
  29. go func() {
  30. time.Sleep(100 * time.Millisecond)
  31. os.Exit(0)
  32. }()
  33. return nil
  34. }
  35. // RestartServiceAsync is a fire-and-forget version of RestartService.
  36. // It logs errors instead of returning them, suitable for goroutine usage.
  37. func RestartServiceAsync() {
  38. if err := RestartService(); err != nil {
  39. log.Printf("Service restart failed: %v", err)
  40. log.Println("Please restart the service manually: sudo systemctl restart sub2api")
  41. }
  42. }