stub_status.go 6.1 KB

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