-
Notifications
You must be signed in to change notification settings - Fork 53
/
clientset.go
277 lines (255 loc) · 6.94 KB
/
clientset.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
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
package storage
import (
"context"
"crypto/sha256"
"encoding/hex"
"io"
"strings"
"time"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/rancher/opni/pkg/alerting/drivers/backend"
"github.com/rancher/opni/pkg/alerting/shared"
"github.com/rancher/opni/pkg/alerting/storage/opts"
storage_opts "github.com/rancher/opni/pkg/alerting/storage/opts"
alertingv1 "github.com/rancher/opni/pkg/apis/alerting/v1"
"github.com/rancher/opni/pkg/util"
"github.com/samber/lo"
"go.uber.org/zap"
)
const defaultTrackerTTL = 24 * time.Hour
type CompositeAlertingClientSet struct {
conds ConditionStorage
endps EndpointStorage
routers RouterStorage
states StateStorage
incidents IncidentStorage
hashes map[string]string
Logger *zap.SugaredLogger
}
var _ AlertingClientSet = (*CompositeAlertingClientSet)(nil)
func (c CompositeAlertingClientSet) Conditions() ConditionStorage {
return c.conds
}
func (c CompositeAlertingClientSet) Endpoints() EndpointStorage {
return c.endps
}
func (c CompositeAlertingClientSet) Routers() RouterStorage {
return c.routers
}
func (c CompositeAlertingClientSet) States() StateStorage {
return c.states
}
func (c CompositeAlertingClientSet) Incidents() IncidentStorage {
return c.incidents
}
func (c *CompositeAlertingClientSet) GetHash(_ context.Context, key string) string {
if _, ok := c.hashes[key]; !ok {
return ""
}
return c.hashes[key]
}
func (c *CompositeAlertingClientSet) CalculateHash(ctx context.Context, key string) error {
aggregate := ""
if key == shared.SingleConfigId {
conds, err := c.Conditions().List(ctx)
if err != nil {
return err
}
aggregate += strings.Join(
lo.Map(conds, func(a *alertingv1.AlertCondition, _ int) string {
return a.Id + a.LastUpdated.String()
}), "-")
endps, err := c.Endpoints().List(ctx)
if err != nil {
return err
}
aggregate += strings.Join(
lo.Map(endps, func(a *alertingv1.AlertEndpoint, _ int) string {
return a.Id + a.LastUpdated.String()
}), "_")
} else {
panic("not implemented")
}
encode := strings.NewReader(aggregate)
hash := sha256.New()
if _, err := io.Copy(hash, encode); err != nil {
return err
}
c.hashes[key] = hex.EncodeToString(hash.Sum(nil))
return nil
}
func (c *CompositeAlertingClientSet) calculateRouters(ctx context.Context, incomingOpts ...storage_opts.SyncOption) ([]string, error) {
syncOpts := storage_opts.NewSyncOptions()
syncOpts.Apply(incomingOpts...)
key := shared.SingleConfigId
// List all conditions & map their endpoints
conds, err := c.Conditions().List(ctx)
if err != nil {
return nil, err
}
endps, err := c.Endpoints().List(ctx, opts.WithUnredacted())
if err != nil {
return nil, err
}
endpMap := lo.Associate(endps, func(a *alertingv1.AlertEndpoint) (string, *alertingv1.AlertEndpoint) {
return a.Id, a
})
// create router specs for conditions
for _, cond := range conds {
if cond.Id == "" {
cond.Id = cond.GetClusterId().GetId()
}
ns := cond.Namespace()
endpoints := cond.GetAttachedEndpoints()
if endpoints == nil || len(endpoints.Items) == 0 {
// this registers it with the virtual router, but doesn't ever build it into the physical router
err = syncOpts.Router.SetNamespaceSpec(ns, cond.Id, &alertingv1.FullAttachedEndpoints{
Items: []*alertingv1.FullAttachedEndpoint{},
})
if err != nil {
return nil, err
}
continue
}
endpointConfigs := make([]*alertingv1.AlertEndpoint, len(endpoints.GetItems()))
for i, endpoint := range endpoints.GetItems() {
i := i
endpoint := endpoint
if endp, ok := endpMap[endpoint.EndpointId]; ok {
endpointConfigs[i] = endp
} else {
return nil, status.Error(codes.NotFound, "endpoint not found")
}
}
routingNode, err := backend.ConvertEndpointIdsToRoutingNode(
endpointConfigs,
endpoints,
cond.Id,
)
if err != nil {
return nil, err
}
err = syncOpts.Router.SetNamespaceSpec(ns, cond.Id, routingNode.GetFullAttachedEndpoints())
if err != nil {
return nil, err
}
if util.StatusCode(err) == codes.InvalidArgument { // sync & build logic are mismatched
panic(err)
}
}
// set expected defaults based on endpoint configuration
defaults := lo.Filter(endps, func(a *alertingv1.AlertEndpoint, _ int) bool {
if len(a.GetProperties()) == 0 {
return false
}
_, ok := a.GetProperties()[alertingv1.EndpointTagNotifications]
return ok
})
if err := syncOpts.Router.SetDefaultNamespaceConfig(defaults); err != nil {
return nil, err
}
if util.StatusCode(err) == codes.InvalidArgument { // sync & build logic are mismatched
panic(err)
}
// when we implement attaching endpoints to the default namespace. do this here
if err := c.Routers().Put(ctx, key, syncOpts.Router); err != nil {
return nil, err
}
return []string{key}, nil
}
// Based on the other storage, calculate what the virtual config should be,
// then overwrite the virtual config storage
func (c *CompositeAlertingClientSet) ForceSync(ctx context.Context, opts ...storage_opts.SyncOption) error {
if err := c.CalculateHash(ctx, shared.SingleConfigId); err != nil {
return err
}
c.Logger.With("hash", c.GetHash(ctx, shared.SingleConfigId)).Debug("starting force sync")
_, err := c.calculateRouters(ctx, opts...)
c.Logger.Debug("finished force sync")
return err
}
func (c *CompositeAlertingClientSet) Sync(ctx context.Context, opts ...storage_opts.SyncOption) ([]string, error) {
key := shared.SingleConfigId
curHash := strings.Clone(c.GetHash(ctx, key))
c.CalculateHash(ctx, key)
newHash := c.GetHash(ctx, key)
if curHash == newHash {
return []string{}, nil
}
keys, err := c.calculateRouters(ctx, opts...)
if err != nil {
return nil, err
}
return keys, nil
}
func (c *CompositeAlertingClientSet) Purge(ctx context.Context) error {
errG, ctxCa := errgroup.WithContext(ctx)
errG.Go(func() error {
keys, err := c.Conditions().ListKeys(ctxCa)
if err != nil {
return err
}
for _, key := range keys {
err := c.Conditions().Delete(ctxCa, key)
if err != nil {
return err
}
}
return nil
})
errG.Go(func() error {
keys, err := c.Endpoints().ListKeys(ctxCa)
if err != nil {
return err
}
for _, key := range keys {
err := c.Endpoints().Delete(ctxCa, key)
if err != nil {
return err
}
}
return nil
})
errG.Go(func() error {
keys, err := c.Routers().ListKeys(ctxCa)
if err != nil {
return err
}
for _, key := range keys {
err := c.Routers().Delete(ctxCa, key)
if err != nil {
return err
}
}
return nil
})
errG.Go(func() error {
keys, err := c.States().ListKeys(ctxCa)
if err != nil {
return err
}
for _, key := range keys {
err := c.States().Delete(ctxCa, key)
if err != nil {
return err
}
}
return nil
})
errG.Go(func() error {
keys, err := c.Incidents().ListKeys(ctxCa)
if err != nil {
return err
}
for _, key := range keys {
err := c.Incidents().Delete(ctxCa, key)
if err != nil {
return err
}
}
return nil
})
return errG.Wait()
}