stub_status.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package performance
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "text/template"
  12. "time"
  13. "github.com/0xJacky/Nginx-UI/internal/nginx"
  14. "github.com/0xJacky/Nginx-UI/settings"
  15. "github.com/pkg/errors"
  16. )
  17. // StubStatusInfo Store the stub_status module status
  18. type StubStatusInfo struct {
  19. Enabled bool `json:"stub_status_enabled"` // stub_status module is enabled
  20. URL string `json:"stub_status_url"` // stub_status access address
  21. }
  22. type StubStatusData struct {
  23. Active int `json:"active"`
  24. Accepts int `json:"accepts"`
  25. Handled int `json:"handled"`
  26. Requests int `json:"requests"`
  27. Reading int `json:"reading"`
  28. Writing int `json:"writing"`
  29. Waiting int `json:"waiting"`
  30. }
  31. const (
  32. StubStatusPath = "/stub_status"
  33. StubStatusHost = "127.0.0.1"
  34. StubStatusProtocol = "http"
  35. StubStatusAllow = "127.0.0.1"
  36. StubStatusDeny = "all"
  37. StubStatusConfigName = "stub_status_nginx-ui.conf"
  38. )
  39. // GetStubStatusData Get the stub_status module data
  40. func GetStubStatusData() (bool, *StubStatusData, error) {
  41. result := &StubStatusData{
  42. Active: 0,
  43. Accepts: 0,
  44. Handled: 0,
  45. Requests: 0,
  46. Reading: 0,
  47. Writing: 0,
  48. Waiting: 0,
  49. }
  50. // Get the stub_status status information
  51. enabled, statusURL := IsStubStatusEnabled()
  52. if !enabled {
  53. return false, result, fmt.Errorf("stub_status is not enabled")
  54. }
  55. // Create an HTTP client
  56. client := &http.Client{
  57. Timeout: 5 * time.Second,
  58. }
  59. // Send a request to get the stub_status data
  60. resp, err := client.Get(statusURL)
  61. if err != nil {
  62. return enabled, result, fmt.Errorf("failed to get stub status: %v", err)
  63. }
  64. defer resp.Body.Close()
  65. // Read the response content
  66. body, err := io.ReadAll(resp.Body)
  67. if err != nil {
  68. return enabled, result, fmt.Errorf("failed to read response body: %v", err)
  69. }
  70. // Parse the response content
  71. statusContent := string(body)
  72. // Match the active connection number
  73. activeRe := regexp.MustCompile(`Active connections:\s+(\d+)`)
  74. if matches := activeRe.FindStringSubmatch(statusContent); len(matches) > 1 {
  75. result.Active, _ = strconv.Atoi(matches[1])
  76. }
  77. // Match the request statistics information
  78. serverRe := regexp.MustCompile(`(\d+)\s+(\d+)\s+(\d+)`)
  79. if matches := serverRe.FindStringSubmatch(statusContent); len(matches) > 3 {
  80. result.Accepts, _ = strconv.Atoi(matches[1])
  81. result.Handled, _ = strconv.Atoi(matches[2])
  82. result.Requests, _ = strconv.Atoi(matches[3])
  83. }
  84. // Match the read and write waiting numbers
  85. connRe := regexp.MustCompile(`Reading:\s+(\d+)\s+Writing:\s+(\d+)\s+Waiting:\s+(\d+)`)
  86. if matches := connRe.FindStringSubmatch(statusContent); len(matches) > 3 {
  87. result.Reading, _ = strconv.Atoi(matches[1])
  88. result.Writing, _ = strconv.Atoi(matches[2])
  89. result.Waiting, _ = strconv.Atoi(matches[3])
  90. }
  91. return enabled, result, nil
  92. }
  93. // GetStubStatus Get the stub_status module status
  94. func GetStubStatus() *StubStatusInfo {
  95. enabled, statusURL := IsStubStatusEnabled()
  96. return &StubStatusInfo{
  97. Enabled: enabled,
  98. URL: statusURL,
  99. }
  100. }
  101. // IsStubStatusEnabled Check if the stub_status module is enabled and return the access address
  102. // Only check the stub_status_nginx-ui.conf configuration file
  103. func IsStubStatusEnabled() (bool, string) {
  104. stubStatusConfPath := nginx.GetConfPath("conf.d", StubStatusConfigName)
  105. if _, err := os.Stat(stubStatusConfPath); os.IsNotExist(err) {
  106. return false, ""
  107. }
  108. ngxConfig, err := nginx.ParseNgxConfig(stubStatusConfPath)
  109. if err != nil {
  110. return false, ""
  111. }
  112. // Find the stub_status configuration
  113. for _, server := range ngxConfig.Servers {
  114. protocol := StubStatusProtocol
  115. host := StubStatusHost
  116. port := settings.NginxSettings.GetStubStatusPort()
  117. for _, location := range server.Locations {
  118. // Check if the location content contains stub_status
  119. if strings.Contains(location.Content, "stub_status") {
  120. stubStatusURL := fmt.Sprintf("%s://%s:%d%s", protocol, host, port, StubStatusPath)
  121. return true, stubStatusURL
  122. }
  123. }
  124. }
  125. return false, ""
  126. }
  127. // EnableStubStatus Enable stub_status module
  128. func EnableStubStatus() error {
  129. enabled, _ := IsStubStatusEnabled()
  130. if enabled {
  131. return nil
  132. }
  133. return CreateStubStatusConfig()
  134. }
  135. // DisableStubStatus Disable stub_status module
  136. func DisableStubStatus() error {
  137. stubStatusConfPath := nginx.GetConfPath("conf.d", StubStatusConfigName)
  138. if _, err := os.Stat(stubStatusConfPath); os.IsNotExist(err) {
  139. return nil
  140. }
  141. return os.Remove(stubStatusConfPath)
  142. }
  143. // CreateStubStatusConfig Create a new stub_status configuration file
  144. func CreateStubStatusConfig() error {
  145. httpConfPath := nginx.GetConfPath("conf.d", StubStatusConfigName)
  146. const stubStatusTemplate = `
  147. # DO NOT EDIT THIS FILE, IT IS AUTO GENERATED BY NGINX-UI
  148. # Nginx stub_status configuration for Nginx-UI
  149. # Modified at {{.ModifiedTime}}
  150. server {
  151. listen {{.Port}}; # Use non-standard port to avoid conflicts
  152. server_name {{.ServerName}};
  153. # Status monitoring interface
  154. location {{.StatusPath}} {
  155. stub_status;
  156. allow {{.AllowIP}}; # Only allow local access
  157. deny {{.DenyAccess}};
  158. }
  159. }
  160. `
  161. type StubStatusTemplateData struct {
  162. ModifiedTime string
  163. Port uint
  164. ServerName string
  165. StatusPath string
  166. AllowIP string
  167. DenyAccess string
  168. }
  169. data := StubStatusTemplateData{
  170. ModifiedTime: time.Now().Format(time.DateTime),
  171. Port: settings.NginxSettings.GetStubStatusPort(),
  172. ServerName: "localhost",
  173. StatusPath: StubStatusPath,
  174. AllowIP: StubStatusAllow,
  175. DenyAccess: StubStatusDeny,
  176. }
  177. tmpl, err := template.New("stub_status").Parse(stubStatusTemplate)
  178. if err != nil {
  179. return errors.Wrap(err, "failed to parse template")
  180. }
  181. var buf bytes.Buffer
  182. if err := tmpl.Execute(&buf, data); err != nil {
  183. return errors.Wrap(err, "failed to execute template")
  184. }
  185. stubStatusConfig := buf.String()
  186. ngxConfig, err := nginx.ParseNgxConfigByContent(stubStatusConfig)
  187. if err != nil {
  188. return errors.Wrap(err, "failed to parse new nginx config")
  189. }
  190. ngxConfig.FileName = httpConfPath
  191. configText, err := ngxConfig.BuildConfig()
  192. if err != nil {
  193. return errors.Wrap(err, "failed to build nginx config")
  194. }
  195. return os.WriteFile(httpConfPath, []byte(configText), 0644)
  196. }