config_info.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. }
  13. // GetNginxWorkerConfigInfo Get Nginx config info of worker_processes and worker_connections
  14. func GetNginxWorkerConfigInfo() (*NginxConfigInfo, error) {
  15. result := &NginxConfigInfo{
  16. WorkerProcesses: 1,
  17. WorkerConnections: 1024,
  18. }
  19. // Get worker_processes config
  20. cmd := exec.Command("nginx", "-T")
  21. output, err := cmd.CombinedOutput()
  22. if err != nil {
  23. return result, errors.Wrap(err, "failed to get nginx config")
  24. }
  25. // Parse worker_processes
  26. wpRe := regexp.MustCompile(`worker_processes\s+(\d+|auto);`)
  27. if matches := wpRe.FindStringSubmatch(string(output)); len(matches) > 1 {
  28. if matches[1] == "auto" {
  29. result.WorkerProcesses = runtime.NumCPU()
  30. } else {
  31. result.WorkerProcesses, _ = strconv.Atoi(matches[1])
  32. }
  33. }
  34. // Parse worker_connections
  35. wcRe := regexp.MustCompile(`worker_connections\s+(\d+);`)
  36. if matches := wcRe.FindStringSubmatch(string(output)); len(matches) > 1 {
  37. result.WorkerConnections, _ = strconv.Atoi(matches[1])
  38. }
  39. return result, nil
  40. }