websocket.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package nginx_log
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. "os"
  7. "github.com/0xJacky/Nginx-UI/internal/helper"
  8. "github.com/0xJacky/Nginx-UI/internal/nginx"
  9. "github.com/0xJacky/Nginx-UI/internal/nginx_log"
  10. "github.com/gin-gonic/gin"
  11. "github.com/gorilla/websocket"
  12. "github.com/nxadm/tail"
  13. "github.com/pkg/errors"
  14. "github.com/uozi-tech/cosy/logger"
  15. )
  16. // getLogPath resolves the log file path based on the provided control parameters
  17. // It checks if the path is under the whitelist directories
  18. func getLogPath(control *controlStruct) (logPath string, err error) {
  19. // If direct log path is provided, use it
  20. if control.LogPath != "" {
  21. logPath = control.LogPath
  22. // Check if logPath is under one of the paths in LogDirWhiteList
  23. if !nginx_log.IsLogPathUnderWhiteList(logPath) {
  24. return "", nginx_log.ErrLogPathIsNotUnderTheLogDirWhiteList
  25. }
  26. return
  27. }
  28. // Otherwise, use default log path based on type
  29. switch control.Type {
  30. case "error":
  31. path := nginx.GetErrorLogPath()
  32. if path == "" {
  33. err = nginx_log.ErrErrorLogPathIsEmpty
  34. return
  35. }
  36. logPath = path
  37. case "access":
  38. fallthrough
  39. default:
  40. path := nginx.GetAccessLogPath()
  41. if path == "" {
  42. err = nginx_log.ErrAccessLogPathIsEmpty
  43. return
  44. }
  45. logPath = path
  46. }
  47. // check if logPath is under one of the paths in LogDirWhiteList
  48. if !nginx_log.IsLogPathUnderWhiteList(logPath) {
  49. return "", nginx_log.ErrLogPathIsNotUnderTheLogDirWhiteList
  50. }
  51. return
  52. }
  53. // tailNginxLog tails the specified log file and sends each line to the websocket
  54. func tailNginxLog(ws *websocket.Conn, controlChan chan controlStruct, errChan chan error) {
  55. defer func() {
  56. if err := recover(); err != nil {
  57. logger.Error(err)
  58. return
  59. }
  60. }()
  61. control := <-controlChan
  62. for {
  63. logPath, err := getLogPath(&control)
  64. if err != nil {
  65. errChan <- err
  66. return
  67. }
  68. seek := tail.SeekInfo{
  69. Offset: 0,
  70. Whence: io.SeekEnd,
  71. }
  72. stat, err := os.Stat(logPath)
  73. if os.IsNotExist(err) {
  74. errChan <- errors.New("[error] Log path does not exist: " + logPath)
  75. return
  76. }
  77. if !stat.Mode().IsRegular() {
  78. errChan <- errors.New("[error] " + logPath + " is not a regular file. " +
  79. "If you are using nginx-ui in docker container, please refer to " +
  80. "https://nginxui.com/zh_CN/guide/config-nginx-log.html for more information.")
  81. return
  82. }
  83. // Create a tail
  84. t, err := tail.TailFile(logPath, tail.Config{Follow: true,
  85. ReOpen: true, Location: &seek})
  86. if err != nil {
  87. errChan <- errors.Wrap(err, "error tailing log")
  88. return
  89. }
  90. for {
  91. var next = false
  92. select {
  93. case line := <-t.Lines:
  94. // Print the text of each received line
  95. if line == nil {
  96. continue
  97. }
  98. err = ws.WriteMessage(websocket.TextMessage, []byte(line.Text))
  99. if err != nil {
  100. if helper.IsUnexpectedWebsocketError(err) {
  101. errChan <- errors.Wrap(err, "error tailNginxLog write message")
  102. }
  103. return
  104. }
  105. case control = <-controlChan:
  106. next = true
  107. break
  108. }
  109. if next {
  110. break
  111. }
  112. }
  113. }
  114. }
  115. // handleLogControl processes websocket control messages
  116. func handleLogControl(ws *websocket.Conn, controlChan chan controlStruct, errChan chan error) {
  117. defer func() {
  118. if err := recover(); err != nil {
  119. logger.Error(err)
  120. return
  121. }
  122. }()
  123. for {
  124. msgType, payload, err := ws.ReadMessage()
  125. if err != nil && websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  126. errChan <- errors.Wrap(err, "error handleLogControl read message")
  127. return
  128. }
  129. if msgType != websocket.TextMessage {
  130. errChan <- errors.New("error handleLogControl message type")
  131. return
  132. }
  133. var msg controlStruct
  134. err = json.Unmarshal(payload, &msg)
  135. if err != nil {
  136. errChan <- errors.Wrap(err, "error ReadWsAndWritePty json.Unmarshal")
  137. return
  138. }
  139. controlChan <- msg
  140. }
  141. }
  142. // Log handles websocket connection for real-time log viewing
  143. func Log(c *gin.Context) {
  144. var upGrader = websocket.Upgrader{
  145. CheckOrigin: func(r *http.Request) bool {
  146. return true
  147. },
  148. }
  149. // upgrade http to websocket
  150. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  151. if err != nil {
  152. logger.Error(err)
  153. return
  154. }
  155. defer ws.Close()
  156. errChan := make(chan error, 1)
  157. controlChan := make(chan controlStruct, 1)
  158. go tailNginxLog(ws, controlChan, errChan)
  159. go handleLogControl(ws, controlChan, errChan)
  160. if err = <-errChan; err != nil {
  161. logger.Error(err)
  162. _ = ws.WriteMessage(websocket.TextMessage, []byte(err.Error()))
  163. return
  164. }
  165. }