| 52 | } |
| 53 | |
| 54 | func (jm *jobManager) worker() { |
| 55 | defer func() { |
| 56 | if err := recover(); err != nil { |
| 57 | buf := make([]byte, stackTraceBufferSize) |
| 58 | buf = buf[:runtime.Stack(buf, false)] |
| 59 | log.Printf("panic: certificate worker: %v\n%s", err, buf) |
| 60 | } |
| 61 | // Decrement activeWorkers here (rather than inline at the |
| 62 | // queue-empty branch) so that the counter is correctly released |
| 63 | // even when the worker exits via a recovered panic. Otherwise the |
| 64 | // counter drifts upward and eventually no new workers ever spawn. |
| 65 | jm.mu.Lock() |
| 66 | jm.activeWorkers-- |
| 67 | jm.mu.Unlock() |
| 68 | }() |
| 69 | |
| 70 | for { |
| 71 | jm.mu.Lock() |
| 72 | if len(jm.queue) == 0 { |
| 73 | jm.mu.Unlock() |
| 74 | return |
| 75 | } |
| 76 | next := jm.queue[0] |
| 77 | jm.queue = jm.queue[1:] |
| 78 | jm.mu.Unlock() |
| 79 | // Run the job inside a closure so that the name is always removed |
| 80 | // from jm.names, even if the job panics. Otherwise the name would |
| 81 | // stay in the in-flight set and future Submit() calls for the same |
| 82 | // name would be silently dropped until process restart. |
| 83 | func() { |
| 84 | defer func() { |
| 85 | if next.name != "" { |
| 86 | jm.mu.Lock() |
| 87 | delete(jm.names, next.name) |
| 88 | jm.mu.Unlock() |
| 89 | } |
| 90 | }() |
| 91 | if err := next.job(); err != nil { |
| 92 | next.logger.Error("job failed", zap.Error(err)) |
| 93 | } |
| 94 | }() |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | func doWithRetry(ctx context.Context, log *zap.Logger, f func(context.Context) error) error { |
| 99 | var attempts int |