nginx.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package nginx
  2. import (
  3. "os/exec"
  4. "strings"
  5. "sync"
  6. "time"
  7. "github.com/0xJacky/Nginx-UI/settings"
  8. )
  9. var (
  10. mutex sync.Mutex
  11. lastOutput string
  12. )
  13. func TestConf() (out string) {
  14. mutex.Lock()
  15. defer mutex.Unlock()
  16. if settings.NginxSettings.TestConfigCmd != "" {
  17. out = execShell(settings.NginxSettings.TestConfigCmd)
  18. return
  19. }
  20. out = execCommand("nginx", "-t")
  21. return
  22. }
  23. func Reload() (out string) {
  24. mutex.Lock()
  25. defer mutex.Unlock()
  26. if settings.NginxSettings.ReloadCmd != "" {
  27. out = execShell(settings.NginxSettings.ReloadCmd)
  28. return
  29. }
  30. out = execCommand("nginx", "-s", "reload")
  31. return
  32. }
  33. func Restart() {
  34. mutex.Lock()
  35. defer mutex.Unlock()
  36. // fix(docker): nginx restart always output network error
  37. time.Sleep(500 * time.Millisecond)
  38. if settings.NginxSettings.RestartCmd != "" {
  39. lastOutput = execShell(settings.NginxSettings.RestartCmd)
  40. return
  41. }
  42. pidPath := GetPIDPath()
  43. daemon := GetSbinPath()
  44. lastOutput = execCommand("start-stop-daemon", "--stop", "--quiet", "--oknodo", "--retry=TERM/30/KILL/5", "--pidfile", pidPath)
  45. if daemon == "" {
  46. lastOutput += execCommand("nginx")
  47. return
  48. }
  49. lastOutput += execCommand("start-stop-daemon", "--start", "--quiet", "--pidfile", pidPath, "--exec", daemon)
  50. return
  51. }
  52. func GetLastOutput() string {
  53. mutex.Lock()
  54. defer mutex.Unlock()
  55. return lastOutput
  56. }
  57. // GetModulesPath returns the nginx modules path
  58. func GetModulesPath() string {
  59. // First try to get from nginx -V output
  60. output := execCommand("nginx", "-V")
  61. if output != "" {
  62. // Look for --modules-path in the output
  63. if strings.Contains(output, "--modules-path=") {
  64. parts := strings.Split(output, "--modules-path=")
  65. if len(parts) > 1 {
  66. // Extract the path
  67. path := strings.Split(parts[1], " ")[0]
  68. // Remove quotes if present
  69. path = strings.Trim(path, "\"")
  70. return path
  71. }
  72. }
  73. }
  74. // Default path if not found
  75. return "/usr/lib/nginx/modules"
  76. }
  77. func execShell(cmd string) (out string) {
  78. bytes, err := exec.Command("/bin/sh", "-c", cmd).CombinedOutput()
  79. out = string(bytes)
  80. if err != nil {
  81. out += " " + err.Error()
  82. }
  83. return
  84. }
  85. func execCommand(name string, cmd ...string) (out string) {
  86. bytes, err := exec.Command(name, cmd...).CombinedOutput()
  87. out = string(bytes)
  88. if err != nil {
  89. out += " " + err.Error()
  90. }
  91. return
  92. }