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 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. run(func(ctx context.Context, atShutdown func()) {
  64. go func() {
  65. select {
  66. case <-g.IsShutdown():
  67. atShutdown()
  68. case <-ctx.Done():
  69. return
  70. }
  71. }()
  72. }, func(ctx context.Context, atTerminate func()) {
  73. g.RunAtTerminate(ctx, atTerminate)
  74. })
  75. }
  76. // RunnableWithShutdownChan is a runnable with functions to run at shutdown and terminate.
  77. // After the atShutdown channel is closed, the main function must return once shutdown is complete.
  78. // (Optionally IsHammer may be waited for instead however, this should be avoided if possible.)
  79. // The callback function provided to atTerminate must return once termination is complete.
  80. // 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.
  81. type RunnableWithShutdownChan func(atShutdown <-chan struct{}, atTerminate CallbackWithContext)
  82. // RunWithShutdownChan takes a function that has channel to watch for shutdown and atTerminate callbacks
  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. func (g *Manager) RunWithShutdownChan(run RunnableWithShutdownChan) {
  88. g.runningServerWaitGroup.Add(1)
  89. defer g.runningServerWaitGroup.Done()
  90. run(g.IsShutdown(), func(ctx context.Context, atTerminate func()) {
  91. g.RunAtTerminate(ctx, atTerminate)
  92. })
  93. }
  94. // RunWithShutdownContext takes a function that has a context to watch for shutdown.
  95. // After the provided context is Done(), the main function must return once shutdown is complete.
  96. // (Optionally the HammerContext may be obtained and waited for however, this should be avoided if possible.)
  97. func (g *Manager) RunWithShutdownContext(run func(context.Context)) {
  98. g.runningServerWaitGroup.Add(1)
  99. defer g.runningServerWaitGroup.Done()
  100. run(g.ShutdownContext())
  101. }
  102. // RunAtTerminate adds to the terminate wait group and creates a go-routine to run the provided function at termination
  103. func (g *Manager) RunAtTerminate(ctx context.Context, terminate func()) {
  104. g.terminateWaitGroup.Add(1)
  105. go func() {
  106. select {
  107. case <-g.IsTerminate():
  108. terminate()
  109. case <-ctx.Done():
  110. }
  111. g.terminateWaitGroup.Done()
  112. }()
  113. }
  114. // RunAtShutdown creates a go-routine to run the provided function at shutdown
  115. func (g *Manager) RunAtShutdown(ctx context.Context, shutdown func()) {
  116. go func() {
  117. select {
  118. case <-g.IsShutdown():
  119. shutdown()
  120. case <-ctx.Done():
  121. }
  122. }()
  123. }
  124. // RunAtHammer creates a go-routine to run the provided function at shutdown
  125. func (g *Manager) RunAtHammer(ctx context.Context, hammer func()) {
  126. go func() {
  127. select {
  128. case <-g.IsHammer():
  129. hammer()
  130. case <-ctx.Done():
  131. }
  132. }()
  133. }
  134. func (g *Manager) doShutdown() {
  135. if !g.setStateTransition(stateRunning, stateShuttingDown) {
  136. return
  137. }
  138. g.lock.Lock()
  139. close(g.shutdown)
  140. g.lock.Unlock()
  141. if setting.GracefulHammerTime >= 0 {
  142. go g.doHammerTime(setting.GracefulHammerTime)
  143. }
  144. go func() {
  145. g.WaitForServers()
  146. // Mop up any remaining unclosed events.
  147. g.doHammerTime(0)
  148. <-time.After(1 * time.Second)
  149. g.doTerminate()
  150. g.WaitForTerminate()
  151. g.lock.Lock()
  152. close(g.done)
  153. g.lock.Unlock()
  154. }()
  155. }
  156. func (g *Manager) doHammerTime(d time.Duration) {
  157. time.Sleep(d)
  158. g.lock.Lock()
  159. select {
  160. case <-g.hammer:
  161. default:
  162. log.Warn("Setting Hammer condition")
  163. close(g.hammer)
  164. }
  165. g.lock.Unlock()
  166. }
  167. func (g *Manager) doTerminate() {
  168. if !g.setStateTransition(stateShuttingDown, stateTerminate) {
  169. return
  170. }
  171. g.lock.Lock()
  172. select {
  173. case <-g.terminate:
  174. default:
  175. log.Warn("Terminating")
  176. close(g.terminate)
  177. }
  178. g.lock.Unlock()
  179. }
  180. // IsChild returns if the current process is a child of previous Gitea process
  181. func (g *Manager) IsChild() bool {
  182. return g.isChild
  183. }
  184. // IsShutdown returns a channel which will be closed at shutdown.
  185. // The order of closure is IsShutdown, IsHammer (potentially), IsTerminate
  186. func (g *Manager) IsShutdown() <-chan struct{} {
  187. return g.shutdown
  188. }
  189. // IsHammer returns a channel which will be closed at hammer
  190. // The order of closure is IsShutdown, IsHammer (potentially), IsTerminate
  191. // Servers running within the running server wait group should respond to IsHammer
  192. // if not shutdown already
  193. func (g *Manager) IsHammer() <-chan struct{} {
  194. return g.hammer
  195. }
  196. // IsTerminate returns a channel which will be closed at terminate
  197. // The order of closure is IsShutdown, IsHammer (potentially), IsTerminate
  198. // IsTerminate will only close once all running servers have stopped
  199. func (g *Manager) IsTerminate() <-chan struct{} {
  200. return g.terminate
  201. }
  202. // ServerDone declares a running server done and subtracts one from the
  203. // running server wait group. Users probably do not want to call this
  204. // and should use one of the RunWithShutdown* functions
  205. func (g *Manager) ServerDone() {
  206. g.runningServerWaitGroup.Done()
  207. }
  208. // WaitForServers waits for all running servers to finish. Users should probably
  209. // instead use AtTerminate or IsTerminate
  210. func (g *Manager) WaitForServers() {
  211. g.runningServerWaitGroup.Wait()
  212. }
  213. // WaitForTerminate waits for all terminating actions to finish.
  214. // Only the main go-routine should use this
  215. func (g *Manager) WaitForTerminate() {
  216. g.terminateWaitGroup.Wait()
  217. }
  218. func (g *Manager) getState() state {
  219. g.lock.RLock()
  220. defer g.lock.RUnlock()
  221. return g.state
  222. }
  223. func (g *Manager) setStateTransition(old, new state) bool {
  224. if old != g.getState() {
  225. return false
  226. }
  227. g.lock.Lock()
  228. if g.state != old {
  229. g.lock.Unlock()
  230. return false
  231. }
  232. g.state = new
  233. g.lock.Unlock()
  234. return true
  235. }
  236. func (g *Manager) setState(st state) {
  237. g.lock.Lock()
  238. defer g.lock.Unlock()
  239. g.state = st
  240. }
  241. // InformCleanup tells the cleanup wait group that we have either taken a listener
  242. // or will not be taking a listener
  243. func (g *Manager) InformCleanup() {
  244. g.createServerWaitGroup.Done()
  245. }
  246. // Done allows the manager to be viewed as a context.Context, it returns a channel that is closed when the server is finished terminating
  247. func (g *Manager) Done() <-chan struct{} {
  248. return g.done
  249. }
  250. // Err allows the manager to be viewed as a context.Context done at Terminate, it returns ErrTerminate
  251. func (g *Manager) Err() error {
  252. select {
  253. case <-g.Done():
  254. return ErrTerminate
  255. default:
  256. return nil
  257. }
  258. }
  259. // Value allows the manager to be viewed as a context.Context done at Terminate, it has no values
  260. func (g *Manager) Value(key interface{}) interface{} {
  261. return nil
  262. }
  263. // Deadline returns nil as there is no fixed Deadline for the manager, it allows the manager to be viewed as a context.Context
  264. func (g *Manager) Deadline() (deadline time.Time, ok bool) {
  265. return
  266. }