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