-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpool.go
More file actions
474 lines (379 loc) · 10.5 KB
/
pool.go
File metadata and controls
474 lines (379 loc) · 10.5 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package task
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
)
var (
ErrPoolClosed = errors.New("pool is closed")
)
// TaskOption represents a generic option that can be passed when starting a new task.
type TaskOption interface{}
// Pool manages a collection of concurrent tasks, providing thread-safe operations on them.
type Pool struct {
mu sync.Mutex
table map[string]Task
reporter Reporter
classifier *rootClassifier
wg sync.WaitGroup
isClosed bool
unread map[string]*TaskStat
}
// NewPool returns a new instance of a task pool.
func NewPool() *Pool {
return &Pool{
table: make(map[string]Task),
classifier: newRootClassifier(),
unread: make(map[string]*TaskStat),
}
}
// SetReporter sets the given [Reporter] instance as the main reporter.
// This reporter will receive task status and progress updates.
func (p *Pool) SetReporter(r Reporter) {
p.mu.Lock()
defer p.mu.Unlock()
p.reporter = r
}
// sendReport sends the current status of the given task to the main reporter (if it set).
func (p *Pool) sendReport(ctx context.Context, t Task) {
if p.reporter == nil {
return
}
p.reporter.Send(ctx, t.Stat())
}
// RegisterClassifier registers a new [TaskClassifier] under one or more names.
// If multiple names are specified, the first one will be the primary one,
// and the rest will be aliases.
// If no names are provided, a default name is generated based on the classifier's type.
//
// Returns the registered names or an error if registration fails.
func (p *Pool) RegisterClassifier(c TaskClassifier, names ...string) ([]string, error) {
p.mu.Lock()
defer p.mu.Unlock()
return p.classifier.Register(c, names...)
}
// StartTask starts the provided task asynchronously with optional configuration options.
//
// Before start:
// - if the task contains target locks, it will be checked for conflicts with
// currently running tasks.
// - if classifiers are specified in options, they will be attached to the task and
// may affect whether the task can start immediately, for example by limiting the number
// of concurrent tasks in a group.
//
// The optional parameter resp can be used to return data from the BeforeStart function.
//
// Returns the task ID or an error if starting fails.
//
// Example:
//
// pool := task.NewPool()
//
// requisites := Requisites{}
//
// t := IncomingMigrationTask{
// GenericTask: new(task.GenericTask),
// vmname: vmname,
// }
//
// taskOpts := []task.TaskOption{
// &task.TaskClassifierDefinition{
// Name: "unique-labels",
// Opts: &classifiers.UniqueLabelOptions{Label: vmname+"/migration"},
// },
// &task.TaskClassifierDefinition{
// Name: "group-migrations",
// Opts: &classifiers.LimitedGroupOptions{},
// },
// }
//
// ctx = context.WithoutCancel(ctx)
//
// md := reporter.Metadata{
// DisplayName: fmt.Sprintf("%T", t),
// }
//
// ctx = task_metadata.AppendToContext(ctx, &md)
//
// _, err := s.TaskStart(ctx, &t, &requisites)
// if err != nil {
// panic("cannot start incoming instance: " + err.Error())
// }
func (p *Pool) StartTask(ctx context.Context, t Task, resp interface{}, opts ...TaskOption) (string, error) {
err := func() error {
if p.isClosed {
return ErrPoolClosed
}
var success bool
p.wg.Add(1)
defer func() {
if !success {
p.wg.Done()
}
}()
// The low level embedded task interface
eti, ok := t.(interface {
init(context.Context, string, chan<- int)
release(error)
})
if !ok {
return fmt.Errorf("invalid embedded interface")
}
// New task ID
tid := uuid.New().String()
// Parse task options
for _, opt := range opts {
switch o := opt.(type) {
case *TaskClassifierDefinition:
if err := p.classifier.Assign(ctx, o, tid); err != nil {
return err
}
}
}
defer func() {
if !success {
p.classifier.Unassign(tid)
}
}()
// Verify if the context was closed in the previous step
if err := ctx.Err(); err != nil {
return err
}
p.mu.Lock()
delete(p.unread, tid)
// Get all running tasks and check if a new task conflicts with them
for tid := range p.table {
if targets := p.table[tid].Targets(); p.table[tid].IsRunning() && len(targets) > 0 {
for object, newActions := range t.Targets() {
if _, ok := targets[object]; ok && targets[object]&newActions != 0 {
p.mu.Unlock()
return &ConcurrentRunningError{fmt.Sprintf("%T", t), targets}
}
}
}
}
// Will be closed in the task release() function
progressCh := make(chan int, 8)
// Initialize ...
eti.init(ctx, tid, progressCh)
p.table[t.ID()] = t
logger := log.WithFields(log.Fields{"task-id": t.ShortID()})
p.mu.Unlock()
p.sendReport(ctx, t)
// Progress reporter
if p.reporter != nil {
go p.reporter.SendProgress(ctx, t.ID(), progressCh)
}
// ... and run the pre-start hook
if err := t.BeforeStart(resp); err != nil {
logger.Errorf("Pre-start function failed: %s", err)
eti.release(err)
p.mu.Lock()
delete(p.table, t.ID())
p.mu.Unlock()
return err
}
success = true
// Main background process
go func() {
var err error
defer func() {
eti.release(err)
p.classifier.Unassign(t.ID())
p.wg.Done()
p.sendReport(ctx, t)
go func() {
time.Sleep(30 * time.Second)
p.mu.Lock()
defer p.mu.Unlock()
if t, found := p.table[t.ID()]; found && !t.IsRunning() {
p.unread[t.ID()] = t.Stat()
delete(p.table, t.ID())
}
}()
}()
err = t.Main()
if err == nil {
logger.Info("Successfully completed")
err = t.OnSuccess()
} else {
logger.Errorf("Fatal error: %s", err)
t.OnFailure(err)
}
}()
return nil
}()
if err != nil {
return "", err
}
return t.ID(), nil
}
// Stat returns a slice of [TaskStat] structs representing the statistics
// (ID, progress, state, any error information) of tasks identified by the given keys.
// The keys can be specific task IDs or sets of labels that may correspond to multiple task IDs
// (e.g., group classifiers).
// If no keys are provided, it returns statistics for all tasks currently in the pool.
func (p *Pool) Stat(keys ...string) []*TaskStat {
p.mu.Lock()
defer p.mu.Unlock()
m := make(map[string]*TaskStat)
// Run through the summary list of task IDs satisfying the given keys
for _, tid := range p.ids(keys...) {
if t, found := p.table[tid]; found {
m[tid] = t.Stat()
} else {
if st, found := p.unread[tid]; found {
delete(p.unread, tid)
m[tid] = st
}
}
}
stats := make([]*TaskStat, 0, len(m))
for _, st := range m {
if st != nil {
stats = append(stats, st)
}
}
return stats
}
// Metadata returns a slice of user-defined metadata for the tasks identified by the given keys.
// The keys can be specific task IDs or sets of labels that may correspond to multiple task IDs
// (e.g., group classifiers).
// If no keys are provided, the function returns an empty slice.
func (p *Pool) Metadata(keys ...string) []interface{} {
p.mu.Lock()
defer p.mu.Unlock()
if len(keys) == 0 {
return make([]interface{}, 0)
}
m := make(map[string]interface{})
// Run through the summary list of task IDs satisfying the given keys
for _, tid := range p.ids(keys...) {
if t, found := p.table[tid]; found {
m[tid] = t.Metadata()
}
}
data := make([]interface{}, 0, len(m))
for _, md := range m {
if md != nil {
data = append(data, md)
}
}
return data
}
// Err returns the error associated with the task identified by tid, if any.
// Returns nil if the task is not found or has no error.
func (p *Pool) Err(tid string) error {
p.mu.Lock()
defer p.mu.Unlock()
if t, found := p.table[tid]; found {
return t.Err()
}
return nil
}
// Cancel cancels the tasks identified by the given keys.
// The keys can be specific task IDs or sets of labels that may correspond to multiple task IDs
// (e.g., group classifiers).
// If no keys are provided, no tasks are cancelled.
func (p *Pool) Cancel(keys ...string) {
p.mu.Lock()
defer p.mu.Unlock()
if len(keys) > 0 {
// Run through the summary list of task IDs satisfying the given keys
for _, tid := range p.ids(keys...) {
if t, found := p.table[tid]; found {
t.Cancel()
}
}
}
}
// Wait blocks until the task identified by tid is released (completed or cancelled or failed),
// if it exists in the pool.
func (p *Pool) Wait(tid string) {
t := func() Task {
p.mu.Lock()
defer p.mu.Unlock()
if t, found := p.table[tid]; found {
return t
}
return nil
}()
if t != nil {
t.Wait()
}
}
// List returns a slice of task IDs from the pool, that match the provided keys.
// The keys can be specific task IDs or sets of labels that may correspond to multiple task IDs
// (e.g., group classifiers).
// If no keys are given, the function returns IDs of all tasks currently in the pool.
func (p *Pool) List(keys ...string) []string {
p.mu.Lock()
defer p.mu.Unlock()
return p.ids(keys...)
}
// WaitAndClosePool waits for all running tasks to complete and marks the pool as closed,
// preventing new tasks from being started.
func (p *Pool) WaitAndClosePool() {
p.wg.Wait()
p.isClosed = true
}
// RunFunc creates and starts a function-based task with the specified target and options.
// If wait is true, it blocks until the task completes.
//
// Returns the task ID and any error encountered during execution.
//
// Example:
//
// pool := task.NewPool()
//
// taskOpts := []task.TaskOption{
// // ...
// }
//
// blockUntilCompleted := true
//
// err := pool.TaskRunFunc(ctx, tgt, blockUntilCompleted, taskOpts, func(l *log.Entry) error {
// return doSomething()
// })
func (p *Pool) RunFunc(ctx context.Context, tgt map[string]OperationMode, wait bool, opts []TaskOption, fn func(*log.Entry) error) (string, error) {
task := FuncTask{new(GenericTask), tgt, fn}
tid, err := p.StartTask(ctx, &task, nil, opts...)
if err != nil {
return "", err
}
if wait {
task.Wait()
}
return tid, task.Err()
}
func (p *Pool) ids(keys ...string) []string {
if len(keys) == 0 {
result := make([]string, 0, len(p.table))
for tid := range p.table {
result = append(result, tid)
}
return result
}
m := make(map[string]struct{})
// Get task IDs from classifiers using the given keys as labels
for _, tid := range p.classifier.Get(keys...) {
if _, found := p.table[tid]; found {
m[tid] = struct{}{}
}
}
// Сheck if there are task IDs in the given keys
for _, tid := range keys {
if _, found := p.table[tid]; found {
m[tid] = struct{}{}
}
}
result := make([]string, 0, len(m))
for tid := range m {
result = append(result, tid)
}
return result
}