nginx.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package nginx
  2. import (
  3. "os"
  4. "sync"
  5. "time"
  6. "github.com/0xJacky/Nginx-UI/internal/docker"
  7. "github.com/0xJacky/Nginx-UI/settings"
  8. )
  9. var (
  10. mutex sync.Mutex
  11. lastStdOut string
  12. lastStdErr error
  13. )
  14. // TestConfig tests the nginx config
  15. func TestConfig() (stdOut string, stdErr error) {
  16. mutex.Lock()
  17. defer mutex.Unlock()
  18. if settings.NginxSettings.TestConfigCmd != "" {
  19. return execShell(settings.NginxSettings.TestConfigCmd)
  20. }
  21. return execCommand("nginx", "-t")
  22. }
  23. // Reload reloads the nginx
  24. func Reload() (stdOut string, stdErr error) {
  25. mutex.Lock()
  26. defer mutex.Unlock()
  27. // Clear the modules cache when reloading Nginx
  28. clearModulesCache()
  29. if settings.NginxSettings.ReloadCmd != "" {
  30. return execShell(settings.NginxSettings.ReloadCmd)
  31. }
  32. return execCommand("nginx", "-s", "reload")
  33. }
  34. // Restart restarts the nginx
  35. func Restart() {
  36. mutex.Lock()
  37. defer mutex.Unlock()
  38. // Clear the modules cache when restarting Nginx
  39. clearModulesCache()
  40. // fix(docker): nginx restart always output network error
  41. time.Sleep(500 * time.Millisecond)
  42. if settings.NginxSettings.RestartCmd != "" {
  43. lastStdOut, lastStdErr = execShell(settings.NginxSettings.RestartCmd)
  44. return
  45. }
  46. pidPath := GetPIDPath()
  47. daemon := GetSbinPath()
  48. lastStdOut, lastStdErr = execCommand("start-stop-daemon", "--stop", "--quiet", "--oknodo", "--retry=TERM/30/KILL/5", "--pidfile", pidPath)
  49. if lastStdErr != nil {
  50. return
  51. }
  52. if daemon == "" {
  53. lastStdOut, lastStdErr = execCommand("nginx")
  54. return
  55. }
  56. lastStdOut, lastStdErr = execCommand("start-stop-daemon", "--start", "--quiet", "--pidfile", pidPath, "--exec", daemon)
  57. }
  58. // GetLastOutput returns the last output of the nginx command
  59. func GetLastResult() *ControlResult {
  60. mutex.Lock()
  61. defer mutex.Unlock()
  62. return &ControlResult{
  63. stdOut: lastStdOut,
  64. stdErr: lastStdErr,
  65. }
  66. }
  67. func IsRunning() bool {
  68. pidPath := GetPIDPath()
  69. switch settings.NginxSettings.RunningInAnotherContainer() {
  70. case true:
  71. return docker.StatPath(pidPath)
  72. case false:
  73. if fileInfo, err := os.Stat(pidPath); err != nil || fileInfo.Size() == 0 {
  74. return false
  75. }
  76. return true
  77. }
  78. return false
  79. }