nginx_log.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package nginx
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/0xJacky/Nginx-UI/api"
  6. "github.com/0xJacky/Nginx-UI/internal/cache"
  7. "github.com/0xJacky/Nginx-UI/internal/helper"
  8. "github.com/0xJacky/Nginx-UI/internal/nginx"
  9. "github.com/0xJacky/Nginx-UI/settings"
  10. "github.com/gin-gonic/gin"
  11. "github.com/gorilla/websocket"
  12. "github.com/hpcloud/tail"
  13. "github.com/pkg/errors"
  14. "github.com/spf13/cast"
  15. "github.com/uozi-tech/cosy/logger"
  16. "io"
  17. "net/http"
  18. "os"
  19. "strings"
  20. )
  21. const (
  22. PageSize = 128 * 1024
  23. )
  24. type controlStruct struct {
  25. Type string `json:"type"`
  26. ConfName string `json:"conf_name"`
  27. ServerIdx int `json:"server_idx"`
  28. DirectiveIdx int `json:"directive_idx"`
  29. }
  30. type nginxLogPageResp struct {
  31. Content string `json:"content"`
  32. Page int64 `json:"page"`
  33. Error string `json:"error,omitempty"`
  34. }
  35. func GetNginxLogPage(c *gin.Context) {
  36. page := cast.ToInt64(c.Query("page"))
  37. if page < 0 {
  38. page = 0
  39. }
  40. var control controlStruct
  41. if !api.BindAndValid(c, &control) {
  42. return
  43. }
  44. logPath, err := getLogPath(&control)
  45. if err != nil {
  46. c.JSON(http.StatusInternalServerError, nginxLogPageResp{
  47. Error: err.Error(),
  48. })
  49. logger.Error(err)
  50. return
  51. }
  52. logFileStat, err := os.Stat(logPath)
  53. if err != nil {
  54. c.JSON(http.StatusInternalServerError, nginxLogPageResp{
  55. Error: err.Error(),
  56. })
  57. logger.Error(err)
  58. return
  59. }
  60. if !logFileStat.Mode().IsRegular() {
  61. c.JSON(http.StatusInternalServerError, nginxLogPageResp{
  62. Error: "log file is not regular file",
  63. })
  64. logger.Error("log file is not regular file:", logPath)
  65. return
  66. }
  67. // to fix: seek invalid argument #674
  68. if logFileStat.Size() == 0 {
  69. c.JSON(http.StatusOK, nginxLogPageResp{
  70. Page: 1,
  71. Content: "",
  72. })
  73. return
  74. }
  75. f, err := os.Open(logPath)
  76. if err != nil {
  77. c.JSON(http.StatusInternalServerError, nginxLogPageResp{
  78. Error: err.Error(),
  79. })
  80. logger.Error(err)
  81. return
  82. }
  83. totalPage := logFileStat.Size() / PageSize
  84. if logFileStat.Size()%PageSize > 0 {
  85. totalPage++
  86. }
  87. var buf []byte
  88. var offset int64
  89. if page == 0 {
  90. page = totalPage
  91. }
  92. buf = make([]byte, PageSize)
  93. offset = (page - 1) * PageSize
  94. // seek
  95. _, err = f.Seek(offset, io.SeekStart)
  96. if err != nil && err != io.EOF {
  97. c.JSON(http.StatusInternalServerError, nginxLogPageResp{
  98. Error: err.Error(),
  99. })
  100. logger.Error(err)
  101. return
  102. }
  103. n, err := f.Read(buf)
  104. if err != nil && !errors.Is(err, io.EOF) {
  105. c.JSON(http.StatusInternalServerError, nginxLogPageResp{
  106. Error: err.Error(),
  107. })
  108. logger.Error(err)
  109. return
  110. }
  111. c.JSON(http.StatusOK, nginxLogPageResp{
  112. Page: page,
  113. Content: string(buf[:n]),
  114. })
  115. }
  116. // isLogPathUnderWhiteList checks if the log path is under one of the paths in LogDirWhiteList
  117. func isLogPathUnderWhiteList(path string) bool {
  118. cacheKey := fmt.Sprintf("isLogPathUnderWhiteList:%s", path)
  119. res, ok := cache.Get(cacheKey)
  120. // no cache, check it
  121. if !ok {
  122. for _, whitePath := range settings.NginxSettings.LogDirWhiteList {
  123. if helper.IsUnderDirectory(path, whitePath) {
  124. cache.Set(cacheKey, true, 0)
  125. return true
  126. }
  127. }
  128. return false
  129. }
  130. return res.(bool)
  131. }
  132. func getLogPath(control *controlStruct) (logPath string, err error) {
  133. if len(settings.NginxSettings.LogDirWhiteList) == 0 {
  134. err = errors.New("The settings.NginxSettings.LogDirWhiteList has not been configured. " +
  135. "For security reasons, please configure a whitelist of log directories. " +
  136. "Please visit https://nginxui.com/guide/config-nginx.html for more information.")
  137. return
  138. }
  139. switch control.Type {
  140. case "site":
  141. var config *nginx.NgxConfig
  142. path := nginx.GetConfPath("sites-available", control.ConfName)
  143. config, err = nginx.ParseNgxConfig(path)
  144. if err != nil {
  145. err = errors.Wrap(err, "error parsing ngx config")
  146. return
  147. }
  148. if control.ServerIdx >= len(config.Servers) {
  149. err = errors.New("serverIdx out of range")
  150. return
  151. }
  152. if control.DirectiveIdx >= len(config.Servers[control.ServerIdx].Directives) {
  153. err = errors.New("DirectiveIdx out of range")
  154. return
  155. }
  156. directive := config.Servers[control.ServerIdx].Directives[control.DirectiveIdx]
  157. switch directive.Directive {
  158. case "access_log", "error_log":
  159. // ok
  160. default:
  161. err = errors.New("directive.Params neither access_log nor error_log")
  162. return
  163. }
  164. if directive.Params == "" {
  165. err = errors.New("directive.Params is empty")
  166. return
  167. }
  168. // fix: access_log /var/log/test.log main;
  169. p := strings.Split(directive.Params, " ")
  170. if len(p) > 0 {
  171. logPath = p[0]
  172. }
  173. case "error":
  174. path := nginx.GetErrorLogPath()
  175. if path == "" {
  176. err = errors.New("settings.NginxLogSettings.ErrorLogPath is empty," +
  177. " refer to https://nginxui.com/guide/config-nginx.html for more information")
  178. return
  179. }
  180. logPath = path
  181. default:
  182. path := nginx.GetAccessLogPath()
  183. if path == "" {
  184. err = errors.New("settings.NginxLogSettings.AccessLogPath is empty," +
  185. " refer to https://nginxui.com/guide/config-nginx.html for more information")
  186. return
  187. }
  188. logPath = path
  189. }
  190. // check if logPath is under one of the paths in LogDirWhiteList
  191. if !isLogPathUnderWhiteList(logPath) {
  192. err = errors.New("The log path is not under the paths in LogDirWhiteList.")
  193. return "", err
  194. }
  195. return
  196. }
  197. func tailNginxLog(ws *websocket.Conn, controlChan chan controlStruct, errChan chan error) {
  198. defer func() {
  199. if err := recover(); err != nil {
  200. logger.Error(err)
  201. return
  202. }
  203. }()
  204. control := <-controlChan
  205. for {
  206. logPath, err := getLogPath(&control)
  207. if err != nil {
  208. errChan <- err
  209. return
  210. }
  211. seek := tail.SeekInfo{
  212. Offset: 0,
  213. Whence: io.SeekEnd,
  214. }
  215. stat, err := os.Stat(logPath)
  216. if os.IsNotExist(err) {
  217. errChan <- errors.New("[error] log path not exists " + logPath)
  218. return
  219. }
  220. if !stat.Mode().IsRegular() {
  221. errChan <- errors.New("[error] " + logPath + " is not a regular file. " +
  222. "If you are using nginx-ui in docker container, please refer to " +
  223. "https://nginxui.com/zh_CN/guide/config-nginx-log.html for more information.")
  224. return
  225. }
  226. // Create a tail
  227. t, err := tail.TailFile(logPath, tail.Config{Follow: true,
  228. ReOpen: true, Location: &seek})
  229. if err != nil {
  230. errChan <- errors.Wrap(err, "error tailing log")
  231. return
  232. }
  233. for {
  234. var next = false
  235. select {
  236. case line := <-t.Lines:
  237. // Print the text of each received line
  238. if line == nil {
  239. continue
  240. }
  241. err = ws.WriteMessage(websocket.TextMessage, []byte(line.Text))
  242. if err != nil && websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  243. errChan <- errors.Wrap(err, "error tailNginxLog write message")
  244. return
  245. }
  246. case control = <-controlChan:
  247. next = true
  248. break
  249. }
  250. if next {
  251. break
  252. }
  253. }
  254. }
  255. }
  256. func handleLogControl(ws *websocket.Conn, controlChan chan controlStruct, errChan chan error) {
  257. defer func() {
  258. if err := recover(); err != nil {
  259. logger.Error(err)
  260. return
  261. }
  262. }()
  263. for {
  264. msgType, payload, err := ws.ReadMessage()
  265. if err != nil && websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  266. errChan <- errors.Wrap(err, "error handleLogControl read message")
  267. return
  268. }
  269. if msgType != websocket.TextMessage {
  270. errChan <- errors.New("error handleLogControl message type")
  271. return
  272. }
  273. var msg controlStruct
  274. err = json.Unmarshal(payload, &msg)
  275. if err != nil {
  276. errChan <- errors.Wrap(err, "error ReadWsAndWritePty json.Unmarshal")
  277. return
  278. }
  279. controlChan <- msg
  280. }
  281. }
  282. func Log(c *gin.Context) {
  283. var upGrader = websocket.Upgrader{
  284. CheckOrigin: func(r *http.Request) bool {
  285. return true
  286. },
  287. }
  288. // upgrade http to websocket
  289. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  290. if err != nil {
  291. logger.Error(err)
  292. return
  293. }
  294. defer ws.Close()
  295. errChan := make(chan error, 1)
  296. controlChan := make(chan controlStruct, 1)
  297. go tailNginxLog(ws, controlChan, errChan)
  298. go handleLogControl(ws, controlChan, errChan)
  299. if err = <-errChan; err != nil {
  300. logger.Error(err)
  301. _ = ws.WriteMessage(websocket.TextMessage, []byte(err.Error()))
  302. return
  303. }
  304. }