-
Notifications
You must be signed in to change notification settings - Fork 53
/
events.go
80 lines (73 loc) · 1.52 KB
/
events.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
74
75
76
77
78
79
80
package slo
import (
"context"
"time"
"github.com/rancher/opni/plugins/slo/pkg/apis/slo"
"github.com/samber/lo"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/emptypb"
)
type sloEventType int
const (
sloAdded sloEventType = iota
sloRemoved
sloUpdated
)
type sloEvent struct {
slo *slo.SLOData
typ sloEventType
}
func (m *module) watchEvents(ctx context.Context) {
interval := time.Second * 1
ticker := time.NewTicker(interval)
defer ticker.Stop()
current := map[string]*slo.SLOData{}
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
c, ca := context.WithTimeout(ctx, interval/2)
list, err := m.sloClient.ListSLOs(c, &emptypb.Empty{})
ca()
if err != nil {
continue
}
latest := lo.KeyBy(list.Items, (*slo.SLOData).GetId)
added := lo.PickBy(latest, func(k string, _ *slo.SLOData) bool {
_, ok := current[k]
return !ok
})
removed := lo.PickBy(current, func(k string, _ *slo.SLOData) bool {
_, ok := latest[k]
return !ok
})
updated := lo.PickBy(latest, func(k string, v *slo.SLOData) bool {
slo, ok := current[k]
if !ok {
return false
}
return !proto.Equal(slo, v)
})
current = latest
for _, slo := range added {
m.events <- &sloEvent{
slo: slo,
typ: sloAdded,
}
}
for _, slo := range removed {
m.events <- &sloEvent{
slo: slo,
typ: sloRemoved,
}
}
for _, slo := range updated {
m.events <- &sloEvent{
slo: slo,
typ: sloUpdated,
}
}
}
}
}