stub_status.go 6.2 KB

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