Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. "time"
  11. )
  12. // TODO: This packages still uses a singleton for the Manager.
  13. // Once there's a decent web framework and dependencies are passed around like they should,
  14. // then we delete the singleton.
  15. var (
  16. manager *Manager
  17. managerInit sync.Once
  18. // DefaultContext is the default context to run processing commands in
  19. DefaultContext = context.Background()
  20. )
  21. // DescriptionPProfLabel is a label set on goroutines that have a process attached
  22. const DescriptionPProfLabel = "process-description"
  23. // PIDPProfLabel is a label set on goroutines that have a process attached
  24. const PIDPProfLabel = "pid"
  25. // PPIDPProfLabel is a label set on goroutines that have a process attached
  26. const PPIDPProfLabel = "ppid"
  27. // ProcessTypePProfLabel is a label set on goroutines that have a process attached
  28. const ProcessTypePProfLabel = "process-type"
  29. // IDType is a pid type
  30. type IDType string
  31. // FinishedFunc is a function that marks that the process is finished and can be removed from the process table
  32. // - it is simply an alias for context.CancelFunc and is only for documentary purposes
  33. type FinishedFunc = context.CancelFunc
  34. // Manager manages all processes and counts PIDs.
  35. type Manager struct {
  36. mutex sync.Mutex
  37. next int64
  38. lastTime int64
  39. processMap map[IDType]*process
  40. }
  41. // GetManager returns a Manager and initializes one as singleton if there's none yet
  42. func GetManager() *Manager {
  43. managerInit.Do(func() {
  44. manager = &Manager{
  45. processMap: make(map[IDType]*process),
  46. next: 1,
  47. }
  48. })
  49. return manager
  50. }
  51. // AddContext creates a new context and adds it as a process. Once the process is finished, finished must be called
  52. // to remove the process from the process table. It should not be called until the process is finished but must always be called.
  53. //
  54. // cancel should be used to cancel the returned context, however it will not remove the process from the process table.
  55. // finished will cancel the returned context and remove it from the process table.
  56. //
  57. // 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
  58. // process table.
  59. func (pm *Manager) AddContext(parent context.Context, description string) (ctx context.Context, cancel context.CancelFunc, finished FinishedFunc) {
  60. ctx, cancel = context.WithCancel(parent)
  61. ctx, _, finished = pm.Add(ctx, description, cancel, NormalProcessType, true)
  62. return ctx, cancel, finished
  63. }
  64. // AddTypedContext creates a new context and adds it as a process. Once the process is finished, finished must be called
  65. // to remove the process from the process table. It should not be called until the process is finished but must always be called.
  66. //
  67. // cancel should be used to cancel the returned context, however it will not remove the process from the process table.
  68. // finished will cancel the returned context and remove it from the process table.
  69. //
  70. // 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
  71. // process table.
  72. func (pm *Manager) AddTypedContext(parent context.Context, description, processType string, currentlyRunning bool) (ctx context.Context, cancel context.CancelFunc, finished FinishedFunc) {
  73. ctx, cancel = context.WithCancel(parent)
  74. ctx, _, finished = pm.Add(ctx, description, cancel, processType, currentlyRunning)
  75. return ctx, cancel, finished
  76. }
  77. // AddContextTimeout creates a new context and add it as a process. Once the process is finished, finished must be called
  78. // to remove the process from the process table. It should not be called until the process is finished but must always be called.
  79. //
  80. // cancel should be used to cancel the returned context, however it will not remove the process from the process table.
  81. // finished will cancel the returned context and remove it from the process table.
  82. //
  83. // 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
  84. // process table.
  85. func (pm *Manager) AddContextTimeout(parent context.Context, timeout time.Duration, description string) (ctx context.Context, cancel context.CancelFunc, finshed FinishedFunc) {
  86. if timeout <= 0 {
  87. // 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
  88. panic("the timeout must be greater than zero, otherwise the context will be cancelled immediately")
  89. }
  90. ctx, cancel = context.WithTimeout(parent, timeout)
  91. ctx, _, finshed = pm.Add(ctx, description, cancel, NormalProcessType, true)
  92. return ctx, cancel, finshed
  93. }
  94. // Add create a new process
  95. func (pm *Manager) Add(ctx context.Context, description string, cancel context.CancelFunc, processType string, currentlyRunning bool) (context.Context, IDType, FinishedFunc) {
  96. parentPID := GetParentPID(ctx)
  97. pm.mutex.Lock()
  98. start, pid := pm.nextPID()
  99. parent := pm.processMap[parentPID]
  100. if parent == nil {
  101. parentPID = ""
  102. }
  103. process := &process{
  104. PID: pid,
  105. ParentPID: parentPID,
  106. Description: description,
  107. Start: start,
  108. Cancel: cancel,
  109. Type: processType,
  110. }
  111. var finished FinishedFunc
  112. if currentlyRunning {
  113. finished = func() {
  114. cancel()
  115. pm.remove(process)
  116. pprof.SetGoroutineLabels(ctx)
  117. }
  118. } else {
  119. finished = func() {
  120. cancel()
  121. pm.remove(process)
  122. }
  123. }
  124. pm.processMap[pid] = process
  125. pm.mutex.Unlock()
  126. pprofCtx := pprof.WithLabels(ctx, pprof.Labels(DescriptionPProfLabel, description, PPIDPProfLabel, string(parentPID), PIDPProfLabel, string(pid), ProcessTypePProfLabel, processType))
  127. if currentlyRunning {
  128. pprof.SetGoroutineLabels(pprofCtx)
  129. }
  130. return &Context{
  131. Context: pprofCtx,
  132. pid: pid,
  133. }, pid, finished
  134. }
  135. // nextPID will return the next available PID. pm.mutex should already be locked.
  136. func (pm *Manager) nextPID() (start time.Time, pid IDType) {
  137. start = time.Now()
  138. startUnix := start.Unix()
  139. if pm.lastTime == startUnix {
  140. pm.next++
  141. } else {
  142. pm.next = 1
  143. }
  144. pm.lastTime = startUnix
  145. pid = IDType(strconv.FormatInt(start.Unix(), 16))
  146. if pm.next == 1 {
  147. return
  148. }
  149. pid = IDType(string(pid) + "-" + strconv.FormatInt(pm.next, 10))
  150. return start, pid
  151. }
  152. // Remove a process from the ProcessManager.
  153. func (pm *Manager) Remove(pid IDType) {
  154. pm.mutex.Lock()
  155. delete(pm.processMap, pid)
  156. pm.mutex.Unlock()
  157. }
  158. func (pm *Manager) remove(process *process) {
  159. pm.mutex.Lock()
  160. defer pm.mutex.Unlock()
  161. if p := pm.processMap[process.PID]; p == process {
  162. delete(pm.processMap, process.PID)
  163. }
  164. }
  165. // Cancel a process in the ProcessManager.
  166. func (pm *Manager) Cancel(pid IDType) {
  167. pm.mutex.Lock()
  168. process, ok := pm.processMap[pid]
  169. pm.mutex.Unlock()
  170. if ok && process.Type != SystemProcessType {
  171. process.Cancel()
  172. }
  173. }