-
Notifications
You must be signed in to change notification settings - Fork 53
/
task.go
73 lines (65 loc) · 1.45 KB
/
task.go
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
package slo
import (
"context"
"io"
"github.com/kralicky/gpkg/sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/rancher/opni/plugins/slo/pkg/apis/slo"
"google.golang.org/protobuf/proto"
)
type task interface {
Run(ctx context.Context, state io.ReadWriter)
InitMetrics() []prometheus.Collector
}
type runningTask struct {
task task
cancel context.CancelFunc
}
type newTaskFunc func(*slo.SLOData) task
func (m *module) manageTasks(ctx context.Context, newTask newTaskFunc) {
tasks := sync.Map[string, *runningTask]{}
start := func(slo *slo.SLOData) {
_, tca := context.WithCancel(ctx)
running := &runningTask{
task: newTask(slo),
cancel: tca,
}
tasks.Store(slo.GetId(), running)
metrics := running.task.InitMetrics()
go func() {
for _, metric := range metrics {
m.mc.Reg.Register(metric)
}
// running.task.Run(tctx, &stateReadWriter{
// ctx: tctx,
// id: slo.GetId(),
// sloClient: m.sloClient,
// })
for _, metric := range metrics {
m.mc.Reg.Unregister(metric)
}
}()
}
stop := func(slo *slo.SLOData) {
if value, ok := tasks.LoadAndDelete(slo.GetId()); ok {
value.cancel()
}
}
for {
select {
case <-ctx.Done():
return
case event := <-m.events:
clone := proto.Clone(event.slo).(*slo.SLOData)
switch event.typ {
case sloAdded:
start(clone)
case sloRemoved:
stop(clone)
case sloUpdated:
stop(clone)
start(clone)
}
}
}
}