gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package process
  5. import (
  6. "context"
  7. "runtime/pprof"
  8. "strconv"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "code.gitea.io/gitea/modules/gtprof"
  13. )
  14. // TODO: This packages still uses a singleton for the Manager.
  15. // Once there's a decent web framework and dependencies are passed around like they should,
  16. // then we delete the singleton.
  17. var (
  18. manager *Manager
  19. managerInit sync.Once
  20. // DefaultContext is the default context to run processing commands in
  21. DefaultContext = context.Background()
  22. )
  23. // IDType is a pid type
  24. type IDType string
  25. // FinishedFunc is a function that marks that the process is finished and can be removed from the process table
  26. // - it is simply an alias for context.CancelFunc and is only for documentary purposes
  27. type FinishedFunc = context.CancelFunc
  28. var (
  29. traceDisabled atomic.Int64
  30. TraceCallback = defaultTraceCallback // this global can be overridden by particular logging packages - thus avoiding import cycles
  31. )
  32. // defaultTraceCallback is a no-op. Without a proper TraceCallback (provided by the logger system), this "Trace" level messages shouldn't be outputted.
  33. func defaultTraceCallback(skip int, start bool, pid IDType, description string, parentPID IDType, typ string) {
  34. }
  35. // TraceLogDisable disables (or revert the disabling) the trace log for the process lifecycle.
  36. // eg: the logger system shouldn't print the trace log for themselves, that's cycle dependency (Logger -> ProcessManager -> TraceCallback -> Logger ...)
  37. // Theoretically, such trace log should only be enabled when the logger system is ready with a proper level, so the default TraceCallback is a no-op.
  38. func TraceLogDisable(v bool) {
  39. if v {
  40. traceDisabled.Add(1)
  41. } else {
  42. traceDisabled.Add(-1)
  43. }
  44. }
  45. func Trace(start bool, pid IDType, description string, parentPID IDType, typ string) {
  46. if traceDisabled.Load() != 0 {
  47. // the traceDisabled counter is mainly for recursive calls, so no concurrency problem.
  48. // because the counter can't be 0 since the caller function hasn't returned (decreased the counter) yet.
  49. return
  50. }
  51. TraceCallback(1, start, pid, description, parentPID, typ)
  52. }
  53. // Manager manages all processes and counts PIDs.
  54. type Manager struct {
  55. mutex sync.Mutex
  56. next int64
  57. lastTime int64
  58. processMap map[IDType]*process
  59. }
  60. // GetManager returns a Manager and initializes one as singleton if there's none yet
  61. func GetManager() *Manager {
  62. managerInit.Do(func() {
  63. manager = &Manager{
  64. processMap: make(map[IDType]*process),
  65. next: 1,
  66. }
  67. })
  68. return manager
  69. }
  70. // AddContext creates a new context and adds it as a process. Once the process is finished, finished must be called
  71. // to remove the process from the process table. It should not be called until the process is finished but must always be called.
  72. //
  73. // cancel should be used to cancel the returned context, however it will not remove the process from the process table.
  74. // finished will cancel the returned context and remove it from the process table.
  75. //
  76. // Most processes will not need to use the cancel function but there will be cases whereby you want to cancel the process but not immediately remove it from the
  77. // process table.
  78. func (pm *Manager) AddContext(parent context.Context, description string) (ctx context.Context, cancel context.CancelFunc, finished FinishedFunc) {
  79. ctx, cancel = context.WithCancel(parent)
  80. ctx, _, finished = pm.Add(ctx, description, cancel, NormalProcessType, true)
  81. return ctx, cancel, finished
  82. }
  83. // AddTypedContext creates a new context and adds it as a process. Once the process is finished, finished must be called
  84. // to remove the process from the process table. It should not be called until the process is finished but must always be called.
  85. //
  86. // cancel should be used to cancel the returned context, however it will not remove the process from the process table.
  87. // finished will cancel the returned context and remove it from the process table.
  88. //
  89. // Most processes will not need to use the cancel function but there will be cases whereby you want to cancel the process but not immediately remove it from the
  90. // process table.
  91. func (pm *Manager) AddTypedContext(parent context.Context, description, processType string, currentlyRunning bool) (ctx context.Context, cancel context.CancelFunc, finished FinishedFunc) {
  92. ctx, cancel = context.WithCancel(parent)
  93. ctx, _, finished = pm.Add(ctx, description, cancel, processType, currentlyRunning)
  94. return ctx, cancel, finished
  95. }
  96. // AddContextTimeout creates a new context and add it as a process. Once the process is finished, finished must be called
  97. // to remove the process from the process table. It should not be called until the process is finished but must always be called.
  98. //
  99. // cancel should be used to cancel the returned context, however it will not remove the process from the process table.
  100. // finished will cancel the returned context and remove it from the process table.
  101. //
  102. // Most processes will not need to use the cancel function but there will be cases whereby you want to cancel the process but not immediately remove it from the
  103. // process table.
  104. func (pm *Manager) AddContextTimeout(parent context.Context, timeout time.Duration, description string) (ctx context.Context, cancel context.CancelFunc, finished FinishedFunc) {
  105. if timeout <= 0 {
  106. // it's meaningless to use timeout <= 0, and it must be a bug! so we must panic here to tell developers to make the timeout correct
  107. panic("the timeout must be greater than zero, otherwise the context will be cancelled immediately")
  108. }
  109. ctx, cancel = context.WithTimeout(parent, timeout)
  110. ctx, _, finished = pm.Add(ctx, description, cancel, NormalProcessType, true)
  111. return ctx, cancel, finished
  112. }
  113. // Add create a new process
  114. func (pm *Manager) Add(ctx context.Context, description string, cancel context.CancelFunc, processType string, currentlyRunning bool) (context.Context, IDType, FinishedFunc) {
  115. parentPID := GetParentPID(ctx)
  116. pm.mutex.Lock()
  117. start, pid := pm.nextPID()
  118. parent := pm.processMap[parentPID]
  119. if parent == nil {
  120. parentPID = ""
  121. }
  122. process := &process{
  123. PID: pid,
  124. ParentPID: parentPID,
  125. Description: description,
  126. Start: start,
  127. Cancel: cancel,
  128. Type: processType,
  129. }
  130. var finished FinishedFunc
  131. if currentlyRunning {
  132. finished = func() {
  133. cancel()
  134. pm.remove(process)
  135. pprof.SetGoroutineLabels(ctx)
  136. }
  137. } else {
  138. finished = func() {
  139. cancel()
  140. pm.remove(process)
  141. }
  142. }
  143. pm.processMap[pid] = process
  144. pm.mutex.Unlock()
  145. Trace(true, pid, description, parentPID, processType)
  146. pprofCtx := pprof.WithLabels(ctx, pprof.Labels(
  147. gtprof.LabelProcessDescription, description,
  148. gtprof.LabelPpid, string(parentPID),
  149. gtprof.LabelPid, string(pid),
  150. gtprof.LabelProcessType, processType,
  151. ))
  152. if currentlyRunning {
  153. pprof.SetGoroutineLabels(pprofCtx)
  154. }
  155. return &Context{
  156. Context: pprofCtx,
  157. pid: pid,
  158. }, pid, finished
  159. }
  160. // nextPID will return the next available PID. pm.mutex should already be locked.
  161. func (pm *Manager) nextPID() (start time.Time, pid IDType) {
  162. start = time.Now()
  163. startUnix := start.Unix()
  164. if pm.lastTime == startUnix {
  165. pm.next++
  166. } else {
  167. pm.next = 1
  168. }
  169. pm.lastTime = startUnix
  170. pid = IDType(strconv.FormatInt(start.Unix(), 16))
  171. if pm.next == 1 {
  172. return start, pid
  173. }
  174. pid = IDType(string(pid) + "-" + strconv.FormatInt(pm.next, 10))
  175. return start, pid
  176. }
  177. func (pm *Manager) remove(process *process) {
  178. deleted := false
  179. pm.mutex.Lock()
  180. if pm.processMap[process.PID] == process {
  181. delete(pm.processMap, process.PID)
  182. deleted = true
  183. }
  184. pm.mutex.Unlock()
  185. if deleted {
  186. Trace(false, process.PID, process.Description, process.ParentPID, process.Type)
  187. }
  188. }
  189. // Cancel a process in the ProcessManager.
  190. func (pm *Manager) Cancel(pid IDType) {
  191. pm.mutex.Lock()
  192. process, ok := pm.processMap[pid]
  193. pm.mutex.Unlock()
  194. if ok && process.Type != SystemProcessType {
  195. process.Cancel()
  196. }
  197. }