config_info.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package nginx
  2. import (
  3. "os/exec"
  4. "regexp"
  5. "runtime"
  6. "strconv"
  7. "github.com/pkg/errors"
  8. )
  9. type NginxConfigInfo struct {
  10. WorkerProcesses int `json:"worker_processes"`
  11. WorkerConnections int `json:"worker_connections"`
  12. ProcessMode string `json:"process_mode"`
  13. }
  14. // GetNginxWorkerConfigInfo Get Nginx config info of worker_processes and worker_connections
  15. func GetNginxWorkerConfigInfo() (*NginxConfigInfo, error) {
  16. result := &NginxConfigInfo{
  17. WorkerProcesses: 1,
  18. WorkerConnections: 1024,
  19. ProcessMode: "manual",
  20. }
  21. // Get worker_processes config
  22. cmd := exec.Command("nginx", "-T")
  23. output, err := cmd.CombinedOutput()
  24. if err != nil {
  25. return result, errors.Wrap(err, "failed to get nginx config")
  26. }
  27. // Parse worker_processes
  28. wpRe := regexp.MustCompile(`worker_processes\s+(\d+|auto);`)
  29. if matches := wpRe.FindStringSubmatch(string(output)); len(matches) > 1 {
  30. if matches[1] == "auto" {
  31. result.WorkerProcesses = runtime.NumCPU()
  32. result.ProcessMode = "auto"
  33. } else {
  34. result.WorkerProcesses, _ = strconv.Atoi(matches[1])
  35. result.ProcessMode = "manual"
  36. }
  37. }
  38. // Parse worker_connections
  39. wcRe := regexp.MustCompile(`worker_connections\s+(\d+);`)
  40. if matches := wcRe.FindStringSubmatch(string(output)); len(matches) > 1 {
  41. result.WorkerConnections, _ = strconv.Atoi(matches[1])
  42. }
  43. return result, nil
  44. }