1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
|
package roadrunner
import (
"context"
"os/exec"
"github.com/spiral/errors"
"github.com/spiral/roadrunner/v2/util"
)
// StopRequest can be sent by worker to indicate that restart is required.
const StopRequest = "{\"stop\":true}"
var bCtx = context.Background()
// Allocator is responsible for worker allocation in the pool
type Allocator func() (WorkerBase, error)
// ErrorEncoder encode error or make a decision based on the error type
type ErrorEncoder func(err error, w WorkerBase) (Payload, error)
// PoolBefore is set of functions that executes BEFORE Exec
type Before func(req Payload) Payload
// PoolAfter is set of functions that executes AFTER Exec
type After func(req Payload, resp Payload) Payload
type PoolOptions func(p *StaticPool)
// StaticPool controls worker creation, destruction and task routing. Pool uses fixed amount of stack.
type StaticPool struct {
cfg PoolConfig
// worker command creator
cmd func() *exec.Cmd
// creates and connects to stack
factory Factory
// distributes the events
events util.EventsHandler
// manages worker states and TTLs
ww WorkerWatcher
// allocate new worker
allocator Allocator
errEncoder ErrorEncoder
before []Before
after []After
}
// NewPool creates new worker pool and task multiplexer. StaticPool will initiate with one worker.
func NewPool(ctx context.Context, cmd func() *exec.Cmd, factory Factory, cfg PoolConfig, options ...PoolOptions) (Pool, error) {
const op = errors.Op("NewPool")
cfg.InitDefaults()
if cfg.Debug {
cfg.NumWorkers = 0
cfg.MaxJobs = 1
}
p := &StaticPool{
cfg: cfg,
cmd: cmd,
factory: factory,
events: util.NewEventsHandler(),
after: make([]After, 0, 0),
before: make([]Before, 0, 0),
}
p.allocator = newPoolAllocator(factory, cmd)
p.ww = newWorkerWatcher(p.allocator, p.cfg.NumWorkers, p.events)
workers, err := p.allocateWorkers(ctx, p.cfg.NumWorkers)
if err != nil {
return nil, err
}
// put stack in the pool
err = p.ww.AddToWatch(ctx, workers)
if err != nil {
return nil, err
}
p.errEncoder = defaultErrEncoder(p)
// add pool options
for i := 0; i < len(options); i++ {
options[i](p)
}
// if supervised config not nil, guess, that pool wanted to be supervised
if cfg.Supervisor != nil {
sp := newPoolWatcher(p, p.events, p.cfg.Supervisor)
// start watcher timer
sp.Start()
return sp, nil
}
return p, nil
}
func PoolBefore(before ...Before) PoolOptions {
return func(p *StaticPool) {
p.before = append(p.before, before...)
}
}
func PoolAfter(after ...After) PoolOptions {
return func(p *StaticPool) {
p.after = append(p.after, after...)
}
}
// AddListener connects event listener to the pool.
func (sp *StaticPool) AddListener(listener util.EventListener) {
sp.events.AddListener(listener)
}
// PoolConfig returns associated pool configuration. Immutable.
func (sp *StaticPool) GetConfig() PoolConfig {
return sp.cfg
}
// Workers returns worker list associated with the pool.
func (sp *StaticPool) Workers() (workers []WorkerBase) {
return sp.ww.WorkersList()
}
func (sp *StaticPool) RemoveWorker(ctx context.Context, wb WorkerBase) error {
return sp.ww.RemoveWorker(ctx, wb)
}
func (sp *StaticPool) Exec(p Payload) (Payload, error) {
const op = errors.Op("Exec")
if sp.cfg.Debug {
return sp.execDebug(p)
}
w, err := sp.ww.GetFreeWorker(context.Background())
if err != nil {
return EmptyPayload, errors.E(op, err)
}
sw := w.(SyncWorker)
if len(sp.before) > 0 {
for i := 0; i < len(sp.before); i++ {
p = sp.before[i](p)
}
}
rsp, err := sw.Exec(p)
if err != nil {
return sp.errEncoder(err, sw)
}
// worker want's to be terminated
if rsp.Body == nil && rsp.Context != nil && string(rsp.Context) == StopRequest {
sw.State().Set(StateInvalid)
err = sw.Stop(bCtx)
if err != nil {
sp.events.Push(WorkerEvent{Event: EventWorkerError, Worker: sw, Payload: errors.E(op, err)})
}
return sp.Exec(p)
}
if sp.cfg.MaxJobs != 0 && sw.State().NumExecs() >= sp.cfg.MaxJobs {
err = sp.ww.AllocateNew(bCtx)
if err != nil {
return EmptyPayload, errors.E(op, err)
}
} else {
sp.ww.PushWorker(sw)
}
if len(sp.after) > 0 {
for i := 0; i < len(sp.after); i++ {
rsp = sp.after[i](p, rsp)
}
}
return rsp, nil
}
func (sp *StaticPool) ExecWithContext(ctx context.Context, rqs Payload) (Payload, error) {
const op = errors.Op("Exec with context")
w, err := sp.ww.GetFreeWorker(context.Background())
if err != nil {
return EmptyPayload, errors.E(op, err)
}
sw := w.(SyncWorker)
if len(sp.before) > 0 {
for i := 0; i < len(sp.before); i++ {
rqs = sp.before[i](rqs)
}
}
rsp, err := sw.ExecWithContext(ctx, rqs)
if err != nil {
return sp.errEncoder(err, sw)
}
// worker want's to be terminated
if rsp.Body == nil && rsp.Context != nil && string(rsp.Context) == StopRequest {
sw.State().Set(StateInvalid)
err = sw.Stop(bCtx)
if err != nil {
sp.events.Push(WorkerEvent{Event: EventWorkerError, Worker: sw, Payload: errors.E(op, err)})
}
return sp.Exec(rqs)
}
if sp.cfg.MaxJobs != 0 && sw.State().NumExecs() >= sp.cfg.MaxJobs {
err = sp.ww.AllocateNew(bCtx)
if err != nil {
return EmptyPayload, errors.E(op, err)
}
} else {
sp.ww.PushWorker(sw)
}
if len(sp.after) > 0 {
for i := 0; i < len(sp.after); i++ {
rsp = sp.after[i](rqs, rsp)
}
}
return rsp, nil
}
// Destroy all underlying stack (but let them to complete the task).
func (sp *StaticPool) Destroy(ctx context.Context) {
sp.ww.Destroy(ctx)
}
func defaultErrEncoder(sp *StaticPool) ErrorEncoder {
return func(err error, w WorkerBase) (Payload, error) {
const op = errors.Op("error encoder")
// soft job errors are allowed
if errors.Is(errors.Exec, err) {
if sp.cfg.MaxJobs != 0 && w.State().NumExecs() >= sp.cfg.MaxJobs {
err = sp.ww.AllocateNew(bCtx)
if err != nil {
sp.events.Push(PoolEvent{Event: EventPoolError, Payload: errors.E(op, err)})
}
w.State().Set(StateInvalid)
err = w.Stop(bCtx)
if err != nil {
sp.events.Push(WorkerEvent{Event: EventWorkerError, Worker: w, Payload: errors.E(op, err)})
}
} else {
sp.ww.PushWorker(w)
}
return EmptyPayload, errors.E(op, err)
}
w.State().Set(StateInvalid)
sp.events.Push(PoolEvent{Event: EventWorkerDestruct, Payload: w})
errS := w.Stop(bCtx)
if errS != nil {
return EmptyPayload, errors.E(op, errors.Errorf("%v, %v", err, errS))
}
return EmptyPayload, errors.E(op, err)
}
}
func newPoolAllocator(factory Factory, cmd func() *exec.Cmd) Allocator {
return func() (WorkerBase, error) {
w, err := factory.SpawnWorkerWithContext(bCtx, cmd())
if err != nil {
return nil, err
}
sw, err := NewSyncWorker(w)
if err != nil {
return nil, err
}
return sw, nil
}
}
func (sp *StaticPool) execDebug(p Payload) (Payload, error) {
sw, err := sp.allocator()
if err != nil {
return EmptyPayload, err
}
r, err := sw.(SyncWorker).Exec(p)
if stopErr := sw.Stop(context.Background()); stopErr != nil {
sp.events.Push(WorkerEvent{Event: EventWorkerError, Worker: sw, Payload: err})
}
return r, err
}
// allocate required number of stack
func (sp *StaticPool) allocateWorkers(ctx context.Context, numWorkers int64) ([]WorkerBase, error) {
const op = errors.Op("allocate workers")
var workers []WorkerBase
// constant number of stack simplify logic
for i := int64(0); i < numWorkers; i++ {
ctx, cancel := context.WithTimeout(ctx, sp.cfg.AllocateTimeout)
w, err := sp.factory.SpawnWorkerWithContext(ctx, sp.cmd())
if err != nil {
cancel()
return nil, errors.E(op, err)
}
workers = append(workers, w)
cancel()
}
return workers, nil
}
func (sp *StaticPool) checkMaxJobs(ctx context.Context, w WorkerBase) error {
const op = errors.Op("check max jobs")
if sp.cfg.MaxJobs != 0 && w.State().NumExecs() >= sp.cfg.MaxJobs {
err := sp.ww.AllocateNew(ctx)
if err != nil {
sp.events.Push(PoolEvent{Event: EventPoolError, Payload: err})
return errors.E(op, err)
}
}
return nil
}
|