You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

manager_unix.go 5.0KB

Rewrite logger system (#24726) ## ⚠️ Breaking The `log.<mode>.<logger>` style config has been dropped. If you used it, please check the new config manual & app.example.ini to make your instance output logs as expected. Although many legacy options still work, it's encouraged to upgrade to the new options. The SMTP logger is deleted because SMTP is not suitable to collect logs. If you have manually configured Gitea log options, please confirm the logger system works as expected after upgrading. ## Description Close #12082 and maybe more log-related issues, resolve some related FIXMEs in old code (which seems unfixable before) Just like rewriting queue #24505 : make code maintainable, clear legacy bugs, and add the ability to support more writers (eg: JSON, structured log) There is a new document (with examples): `logging-config.en-us.md` This PR is safer than the queue rewriting, because it's just for logging, it won't break other logic. ## The old problems The logging system is quite old and difficult to maintain: * Unclear concepts: Logger, NamedLogger, MultiChannelledLogger, SubLogger, EventLogger, WriterLogger etc * Some code is diffuclt to konw whether it is right: `log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs `log.DelLogger("console")` * The old system heavily depends on ini config system, it's difficult to create new logger for different purpose, and it's very fragile. * The "color" trick is difficult to use and read, many colors are unnecessary, and in the future structured log could help * It's difficult to add other log formats, eg: JSON format * The log outputer doesn't have full control of its goroutine, it's difficult to make outputer have advanced behaviors * The logs could be lost in some cases: eg: no Fatal error when using CLI. * Config options are passed by JSON, which is quite fragile. * INI package makes the KEY in `[log]` section visible in `[log.sub1]` and `[log.sub1.subA]`, this behavior is quite fragile and would cause more unclear problems, and there is no strong requirement to support `log.<mode>.<logger>` syntax. ## The new design See `logger.go` for documents. ## Screenshot <details> ![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff) ![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9) ![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee) </details> ## TODO * [x] add some new tests * [x] fix some tests * [x] test some sub-commands (manually ....) --------- Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: Giteabot <teabot@gitea.io>
1 year ago
Rewrite logger system (#24726) ## ⚠️ Breaking The `log.<mode>.<logger>` style config has been dropped. If you used it, please check the new config manual & app.example.ini to make your instance output logs as expected. Although many legacy options still work, it's encouraged to upgrade to the new options. The SMTP logger is deleted because SMTP is not suitable to collect logs. If you have manually configured Gitea log options, please confirm the logger system works as expected after upgrading. ## Description Close #12082 and maybe more log-related issues, resolve some related FIXMEs in old code (which seems unfixable before) Just like rewriting queue #24505 : make code maintainable, clear legacy bugs, and add the ability to support more writers (eg: JSON, structured log) There is a new document (with examples): `logging-config.en-us.md` This PR is safer than the queue rewriting, because it's just for logging, it won't break other logic. ## The old problems The logging system is quite old and difficult to maintain: * Unclear concepts: Logger, NamedLogger, MultiChannelledLogger, SubLogger, EventLogger, WriterLogger etc * Some code is diffuclt to konw whether it is right: `log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs `log.DelLogger("console")` * The old system heavily depends on ini config system, it's difficult to create new logger for different purpose, and it's very fragile. * The "color" trick is difficult to use and read, many colors are unnecessary, and in the future structured log could help * It's difficult to add other log formats, eg: JSON format * The log outputer doesn't have full control of its goroutine, it's difficult to make outputer have advanced behaviors * The logs could be lost in some cases: eg: no Fatal error when using CLI. * Config options are passed by JSON, which is quite fragile. * INI package makes the KEY in `[log]` section visible in `[log.sub1]` and `[log.sub1.subA]`, this behavior is quite fragile and would cause more unclear problems, and there is no strong requirement to support `log.<mode>.<logger>` syntax. ## The new design See `logger.go` for documents. ## Screenshot <details> ![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff) ![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9) ![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee) </details> ## TODO * [x] add some new tests * [x] fix some tests * [x] test some sub-commands (manually ....) --------- Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: Giteabot <teabot@gitea.io>
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. //go:build !windows
  4. package graceful
  5. import (
  6. "context"
  7. "errors"
  8. "os"
  9. "os/signal"
  10. "runtime/pprof"
  11. "strconv"
  12. "syscall"
  13. "time"
  14. "code.gitea.io/gitea/modules/graceful/releasereopen"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/process"
  17. "code.gitea.io/gitea/modules/setting"
  18. )
  19. func pidMsg() systemdNotifyMsg {
  20. return systemdNotifyMsg("MAINPID=" + strconv.Itoa(os.Getpid()))
  21. }
  22. // Notify systemd of status via the notify protocol
  23. func (g *Manager) notify(msg systemdNotifyMsg) {
  24. conn, err := getNotifySocket()
  25. if err != nil {
  26. // the err is logged in getNotifySocket
  27. return
  28. }
  29. if conn == nil {
  30. return
  31. }
  32. defer conn.Close()
  33. if _, err = conn.Write([]byte(msg)); err != nil {
  34. log.Warn("Failed to notify NOTIFY_SOCKET: %v", err)
  35. return
  36. }
  37. }
  38. func (g *Manager) start() {
  39. // Now label this and all goroutines created by this goroutine with the graceful-lifecycle manager
  40. pprof.SetGoroutineLabels(g.managerCtx)
  41. defer pprof.SetGoroutineLabels(g.ctx)
  42. g.isChild = len(os.Getenv(listenFDsEnv)) > 0 && os.Getppid() > 1
  43. g.notify(statusMsg("Starting Gitea"))
  44. g.notify(pidMsg())
  45. go g.handleSignals(g.managerCtx)
  46. // Handle clean up of unused provided listeners and delayed start-up
  47. startupDone := make(chan struct{})
  48. go func() {
  49. defer func() {
  50. close(startupDone)
  51. // Close the unused listeners
  52. closeProvidedListeners()
  53. }()
  54. // Wait for all servers to be created
  55. g.createServerCond.L.Lock()
  56. for {
  57. if g.createdServer >= numberOfServersToCreate {
  58. g.createServerCond.L.Unlock()
  59. g.notify(readyMsg)
  60. return
  61. }
  62. select {
  63. case <-g.IsShutdown():
  64. g.createServerCond.L.Unlock()
  65. return
  66. default:
  67. }
  68. g.createServerCond.Wait()
  69. }
  70. }()
  71. if setting.StartupTimeout > 0 {
  72. go func() {
  73. select {
  74. case <-startupDone:
  75. return
  76. case <-g.IsShutdown():
  77. g.createServerCond.Signal()
  78. return
  79. case <-time.After(setting.StartupTimeout):
  80. log.Error("Startup took too long! Shutting down")
  81. g.notify(statusMsg("Startup took too long! Shutting down"))
  82. g.notify(stoppingMsg)
  83. g.doShutdown()
  84. }
  85. }()
  86. }
  87. }
  88. func (g *Manager) handleSignals(ctx context.Context) {
  89. ctx, _, finished := process.GetManager().AddTypedContext(ctx, "Graceful: HandleSignals", process.SystemProcessType, true)
  90. defer finished()
  91. signalChannel := make(chan os.Signal, 1)
  92. signal.Notify(
  93. signalChannel,
  94. syscall.SIGHUP,
  95. syscall.SIGUSR1,
  96. syscall.SIGUSR2,
  97. syscall.SIGINT,
  98. syscall.SIGTERM,
  99. syscall.SIGTSTP,
  100. )
  101. watchdogTimeout := getWatchdogTimeout()
  102. t := &time.Ticker{}
  103. if watchdogTimeout != 0 {
  104. g.notify(watchdogMsg)
  105. t = time.NewTicker(watchdogTimeout / 2)
  106. }
  107. pid := syscall.Getpid()
  108. for {
  109. select {
  110. case sig := <-signalChannel:
  111. switch sig {
  112. case syscall.SIGHUP:
  113. log.Info("PID: %d. Received SIGHUP. Attempting GracefulRestart...", pid)
  114. g.DoGracefulRestart()
  115. case syscall.SIGUSR1:
  116. log.Warn("PID %d. Received SIGUSR1. Releasing and reopening logs", pid)
  117. g.notify(statusMsg("Releasing and reopening logs"))
  118. if err := releasereopen.GetManager().ReleaseReopen(); err != nil {
  119. log.Error("Error whilst releasing and reopening logs: %v", err)
  120. }
  121. case syscall.SIGUSR2:
  122. log.Warn("PID %d. Received SIGUSR2. Hammering...", pid)
  123. g.DoImmediateHammer()
  124. case syscall.SIGINT:
  125. log.Warn("PID %d. Received SIGINT. Shutting down...", pid)
  126. g.DoGracefulShutdown()
  127. case syscall.SIGTERM:
  128. log.Warn("PID %d. Received SIGTERM. Shutting down...", pid)
  129. g.DoGracefulShutdown()
  130. case syscall.SIGTSTP:
  131. log.Info("PID %d. Received SIGTSTP.", pid)
  132. default:
  133. log.Info("PID %d. Received %v.", pid, sig)
  134. }
  135. case <-t.C:
  136. g.notify(watchdogMsg)
  137. case <-ctx.Done():
  138. log.Warn("PID: %d. Background context for manager closed - %v - Shutting down...", pid, ctx.Err())
  139. g.DoGracefulShutdown()
  140. return
  141. }
  142. }
  143. }
  144. func (g *Manager) doFork() error {
  145. g.lock.Lock()
  146. if g.forked {
  147. g.lock.Unlock()
  148. return errors.New("another process already forked. Ignoring this one")
  149. }
  150. g.forked = true
  151. g.lock.Unlock()
  152. g.notify(reloadingMsg)
  153. // We need to move the file logs to append pids
  154. setting.RestartLogsWithPIDSuffix()
  155. _, err := RestartProcess()
  156. return err
  157. }
  158. // DoGracefulRestart causes a graceful restart
  159. func (g *Manager) DoGracefulRestart() {
  160. if setting.GracefulRestartable {
  161. log.Info("PID: %d. Forking...", os.Getpid())
  162. err := g.doFork()
  163. if err != nil {
  164. if err.Error() == "another process already forked. Ignoring this one" {
  165. g.DoImmediateHammer()
  166. } else {
  167. log.Error("Error whilst forking from PID: %d : %v", os.Getpid(), err)
  168. }
  169. }
  170. // doFork calls RestartProcess which starts a new Gitea process, so this parent process needs to exit
  171. // Otherwise some resources (eg: leveldb lock) will be held by this parent process and the new process will fail to start
  172. log.Info("PID: %d. Shutting down after forking ...", os.Getpid())
  173. g.doShutdown()
  174. } else {
  175. log.Info("PID: %d. Not set restartable. Shutting down...", os.Getpid())
  176. g.notify(stoppingMsg)
  177. g.doShutdown()
  178. }
  179. }