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.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package graceful
  5. import (
  6. "context"
  7. "sync"
  8. "time"
  9. "code.gitea.io/gitea/modules/log"
  10. "code.gitea.io/gitea/modules/process"
  11. "code.gitea.io/gitea/modules/setting"
  12. )
  13. type state uint8
  14. const (
  15. stateInit state = iota
  16. stateRunning
  17. stateShuttingDown
  18. stateTerminate
  19. )
  20. // There are three places that could inherit sockets:
  21. //
  22. // * HTTP or HTTPS main listener
  23. // * HTTP redirection fallback
  24. // * SSH
  25. //
  26. // If you add an additional place you must increment this number
  27. // and add a function to call manager.InformCleanup if it's not going to be used
  28. const numberOfServersToCreate = 3
  29. // Manager represents the graceful server manager interface
  30. var manager *Manager
  31. var initOnce = sync.Once{}
  32. // GetManager returns the Manager
  33. func GetManager() *Manager {
  34. InitManager(context.Background())
  35. return manager
  36. }
  37. // InitManager creates the graceful manager in the provided context
  38. func InitManager(ctx context.Context) {
  39. initOnce.Do(func() {
  40. manager = newGracefulManager(ctx)
  41. // Set the process default context to the HammerContext
  42. process.DefaultContext = manager.HammerContext()
  43. })
  44. }
  45. // CallbackWithContext is combined runnable and context to watch to see if the caller has finished
  46. type CallbackWithContext func(ctx context.Context, callback func())
  47. // RunnableWithShutdownFns is a runnable with functions to run at shutdown and terminate
  48. // After the callback to atShutdown is called and is complete, the main function must return.
  49. // Similarly the callback function provided to atTerminate must return once termination is complete.
  50. // Please note that use of the atShutdown and atTerminate callbacks will create go-routines that will wait till their respective signals
  51. // - users must therefore be careful to only call these as necessary.
  52. // If run is not expected to run indefinitely RunWithShutdownChan is likely to be more appropriate.
  53. type RunnableWithShutdownFns func(atShutdown, atTerminate func(context.Context, func()))
  54. // RunWithShutdownFns takes a function that has both atShutdown and atTerminate callbacks
  55. // After the callback to atShutdown is called and is complete, the main function must return.
  56. // Similarly the callback function provided to atTerminate must return once termination is complete.
  57. // Please note that use of the atShutdown and atTerminate callbacks will create go-routines that will wait till their respective signals
  58. // - users must therefore be careful to only call these as necessary.
  59. // If run is not expected to run indefinitely RunWithShutdownChan is likely to be more appropriate.
  60. func (g *Manager) RunWithShutdownFns(run RunnableWithShutdownFns) {
  61. g.runningServerWaitGroup.Add(1)
  62. defer g.runningServerWaitGroup.Done()
  63. defer func() {
  64. if err := recover(); err != nil {
  65. log.Critical("PANIC during RunWithShutdownFns: %v\nStacktrace: %s", err, log.Stack(2))
  66. g.doShutdown()
  67. }
  68. }()
  69. run(func(ctx context.Context, atShutdown func()) {
  70. go func() {
  71. select {
  72. case <-g.IsShutdown():
  73. atShutdown()
  74. case <-ctx.Done():
  75. return
  76. }
  77. }()
  78. }, func(ctx context.Context, atTerminate func()) {
  79. g.RunAtTerminate(ctx, atTerminate)
  80. })
  81. }
  82. // RunnableWithShutdownChan is a runnable with functions to run at shutdown and terminate.
  83. // After the atShutdown channel is closed, the main function must return once shutdown is complete.
  84. // (Optionally IsHammer may be waited for instead however, this should be avoided if possible.)
  85. // The callback function provided to atTerminate must return once termination is complete.
  86. // Please note that use of the atTerminate function will create a go-routine that will wait till terminate - users must therefore be careful to only call this as necessary.
  87. type RunnableWithShutdownChan func(atShutdown <-chan struct{}, atTerminate CallbackWithContext)
  88. // RunWithShutdownChan takes a function that has channel to watch for shutdown and atTerminate callbacks
  89. // After the atShutdown channel is closed, the main function must return once shutdown is complete.
  90. // (Optionally IsHammer may be waited for instead however, this should be avoided if possible.)
  91. // The callback function provided to atTerminate must return once termination is complete.
  92. // Please note that use of the atTerminate function will create a go-routine that will wait till terminate - users must therefore be careful to only call this as necessary.
  93. func (g *Manager) RunWithShutdownChan(run RunnableWithShutdownChan) {
  94. g.runningServerWaitGroup.Add(1)
  95. defer g.runningServerWaitGroup.Done()
  96. defer func() {
  97. if err := recover(); err != nil {
  98. log.Critical("PANIC during RunWithShutdownChan: %v\nStacktrace: %s", err, log.Stack(2))
  99. g.doShutdown()
  100. }
  101. }()
  102. run(g.IsShutdown(), func(ctx context.Context, atTerminate func()) {
  103. g.RunAtTerminate(ctx, atTerminate)
  104. })
  105. }
  106. // RunWithShutdownContext takes a function that has a context to watch for shutdown.
  107. // After the provided context is Done(), the main function must return once shutdown is complete.
  108. // (Optionally the HammerContext may be obtained and waited for however, this should be avoided if possible.)
  109. func (g *Manager) RunWithShutdownContext(run func(context.Context)) {
  110. g.runningServerWaitGroup.Add(1)
  111. defer g.runningServerWaitGroup.Done()
  112. defer func() {
  113. if err := recover(); err != nil {
  114. log.Critical("PANIC during RunWithShutdownContext: %v\nStacktrace: %s", err, log.Stack(2))
  115. g.doShutdown()
  116. }
  117. }()
  118. run(g.ShutdownContext())
  119. }
  120. // RunAtTerminate adds to the terminate wait group and creates a go-routine to run the provided function at termination
  121. func (g *Manager) RunAtTerminate(ctx context.Context, terminate func()) {
  122. g.terminateWaitGroup.Add(1)
  123. go func() {
  124. defer g.terminateWaitGroup.Done()
  125. defer func() {
  126. if err := recover(); err != nil {
  127. log.Critical("PANIC during RunAtTerminate: %v\nStacktrace: %s", err, log.Stack(2))
  128. }
  129. }()
  130. select {
  131. case <-g.IsTerminate():
  132. terminate()
  133. case <-ctx.Done():
  134. }
  135. }()
  136. }
  137. // RunAtShutdown creates a go-routine to run the provided function at shutdown
  138. func (g *Manager) RunAtShutdown(ctx context.Context, shutdown func()) {
  139. go func() {
  140. defer func() {
  141. if err := recover(); err != nil {
  142. log.Critical("PANIC during RunAtShutdown: %v\nStacktrace: %s", err, log.Stack(2))
  143. }
  144. }()
  145. select {
  146. case <-g.IsShutdown():
  147. shutdown()
  148. case <-ctx.Done():
  149. }
  150. }()
  151. }
  152. // RunAtHammer creates a go-routine to run the provided function at shutdown
  153. func (g *Manager) RunAtHammer(ctx context.Context, hammer func()) {
  154. go func() {
  155. defer func() {
  156. if err := recover(); err != nil {
  157. log.Critical("PANIC during RunAtHammer: %v\nStacktrace: %s", err, log.Stack(2))
  158. }
  159. }()
  160. select {
  161. case <-g.IsHammer():
  162. hammer()
  163. case <-ctx.Done():
  164. }
  165. }()
  166. }
  167. func (g *Manager) doShutdown() {
  168. if !g.setStateTransition(stateRunning, stateShuttingDown) {
  169. return
  170. }
  171. g.lock.Lock()
  172. close(g.shutdown)
  173. g.lock.Unlock()
  174. if setting.GracefulHammerTime >= 0 {
  175. go g.doHammerTime(setting.GracefulHammerTime)
  176. }
  177. go func() {
  178. g.WaitForServers()
  179. // Mop up any remaining unclosed events.
  180. g.doHammerTime(0)
  181. <-time.After(1 * time.Second)
  182. g.doTerminate()
  183. g.WaitForTerminate()
  184. g.lock.Lock()
  185. close(g.done)
  186. g.lock.Unlock()
  187. }()
  188. }
  189. func (g *Manager) doHammerTime(d time.Duration) {
  190. time.Sleep(d)
  191. g.lock.Lock()
  192. select {
  193. case <-g.hammer:
  194. default:
  195. log.Warn("Setting Hammer condition")
  196. close(g.hammer)
  197. }
  198. g.lock.Unlock()
  199. }
  200. func (g *Manager) doTerminate() {
  201. if !g.setStateTransition(stateShuttingDown, stateTerminate) {
  202. return
  203. }
  204. g.lock.Lock()
  205. select {
  206. case <-g.terminate:
  207. default:
  208. log.Warn("Terminating")
  209. close(g.terminate)
  210. }
  211. g.lock.Unlock()
  212. }
  213. // IsChild returns if the current process is a child of previous Gitea process
  214. func (g *Manager) IsChild() bool {
  215. return g.isChild
  216. }
  217. // IsShutdown returns a channel which will be closed at shutdown.
  218. // The order of closure is IsShutdown, IsHammer (potentially), IsTerminate
  219. func (g *Manager) IsShutdown() <-chan struct{} {
  220. return g.shutdown
  221. }
  222. // IsHammer returns a channel which will be closed at hammer
  223. // The order of closure is IsShutdown, IsHammer (potentially), IsTerminate
  224. // Servers running within the running server wait group should respond to IsHammer
  225. // if not shutdown already
  226. func (g *Manager) IsHammer() <-chan struct{} {
  227. return g.hammer
  228. }
  229. // IsTerminate returns a channel which will be closed at terminate
  230. // The order of closure is IsShutdown, IsHammer (potentially), IsTerminate
  231. // IsTerminate will only close once all running servers have stopped
  232. func (g *Manager) IsTerminate() <-chan struct{} {
  233. return g.terminate
  234. }
  235. // ServerDone declares a running server done and subtracts one from the
  236. // running server wait group. Users probably do not want to call this
  237. // and should use one of the RunWithShutdown* functions
  238. func (g *Manager) ServerDone() {
  239. g.runningServerWaitGroup.Done()
  240. }
  241. // WaitForServers waits for all running servers to finish. Users should probably
  242. // instead use AtTerminate or IsTerminate
  243. func (g *Manager) WaitForServers() {
  244. g.runningServerWaitGroup.Wait()
  245. }
  246. // WaitForTerminate waits for all terminating actions to finish.
  247. // Only the main go-routine should use this
  248. func (g *Manager) WaitForTerminate() {
  249. g.terminateWaitGroup.Wait()
  250. }
  251. func (g *Manager) getState() state {
  252. g.lock.RLock()
  253. defer g.lock.RUnlock()
  254. return g.state
  255. }
  256. func (g *Manager) setStateTransition(old, new state) bool {
  257. if old != g.getState() {
  258. return false
  259. }
  260. g.lock.Lock()
  261. if g.state != old {
  262. g.lock.Unlock()
  263. return false
  264. }
  265. g.state = new
  266. g.lock.Unlock()
  267. return true
  268. }
  269. func (g *Manager) setState(st state) {
  270. g.lock.Lock()
  271. defer g.lock.Unlock()
  272. g.state = st
  273. }
  274. // InformCleanup tells the cleanup wait group that we have either taken a listener
  275. // or will not be taking a listener
  276. func (g *Manager) InformCleanup() {
  277. g.createServerWaitGroup.Done()
  278. }
  279. // Done allows the manager to be viewed as a context.Context, it returns a channel that is closed when the server is finished terminating
  280. func (g *Manager) Done() <-chan struct{} {
  281. return g.done
  282. }
  283. // Err allows the manager to be viewed as a context.Context done at Terminate, it returns ErrTerminate
  284. func (g *Manager) Err() error {
  285. select {
  286. case <-g.Done():
  287. return ErrTerminate
  288. default:
  289. return nil
  290. }
  291. }
  292. // Value allows the manager to be viewed as a context.Context done at Terminate, it has no values
  293. func (g *Manager) Value(key interface{}) interface{} {
  294. return nil
  295. }
  296. // Deadline returns nil as there is no fixed Deadline for the manager, it allows the manager to be viewed as a context.Context
  297. func (g *Manager) Deadline() (deadline time.Time, ok bool) {
  298. return
  299. }