-
Notifications
You must be signed in to change notification settings - Fork 52
/
test_cluster_driver.go
600 lines (526 loc) · 17.9 KB
/
test_cluster_driver.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
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package test
import (
"context"
"fmt"
"net/http"
"os"
"os/exec"
"path"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"emperror.dev/errors"
"github.com/rancher/opni/pkg/alerting/drivers/backend"
"github.com/rancher/opni/pkg/alerting/drivers/routing"
"github.com/rancher/opni/pkg/alerting/shared"
corev1 "github.com/rancher/opni/pkg/apis/core/v1"
"github.com/rancher/opni/pkg/logger"
"github.com/rancher/opni/pkg/plugins"
"github.com/rancher/opni/pkg/test/freeport"
"github.com/rancher/opni/pkg/test/testutil"
"github.com/rancher/opni/pkg/util/waitctx"
alerting_drivers "github.com/rancher/opni/plugins/alerting/pkg/alerting/drivers"
"github.com/rancher/opni/plugins/alerting/pkg/apis/alertops"
metrics_agent_drivers "github.com/rancher/opni/plugins/metrics/pkg/agent/drivers"
"github.com/rancher/opni/plugins/metrics/pkg/apis/cortexops"
"github.com/rancher/opni/plugins/metrics/pkg/apis/node"
"github.com/rancher/opni/plugins/metrics/pkg/apis/remoteread"
"golang.org/x/exp/slices"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"gopkg.in/yaml.v2"
)
var (
cortexVersion string
)
func init() {
buildInfo, ok := debug.ReadBuildInfo()
if !ok {
panic("could not read build info")
}
// https://github.com/golang/go/issues/33976
if buildInfo.Main.Path == "" {
cortexVersion = "(unknown)"
return
}
for _, depInfo := range buildInfo.Deps {
if depInfo.Path == "github.com/cortexproject/cortex" {
if depInfo.Replace != nil {
cortexVersion = depInfo.Replace.Version
} else {
cortexVersion = depInfo.Version
}
return
}
}
panic("could not find cortex dependency in build info")
}
type MetricsCortexClusterDriver struct {
cortexops.UnsafeCortexOpsServer
lock sync.Mutex
state cortexops.InstallState
cortexCtx context.Context
cortexCancel context.CancelFunc
Env *Environment
Configuration *cortexops.ClusterConfiguration
}
func NewMetricsCortexClusterDriver(env *Environment) *MetricsCortexClusterDriver {
return &MetricsCortexClusterDriver{
Env: env,
Configuration: &cortexops.ClusterConfiguration{},
state: cortexops.InstallState_NotInstalled,
}
}
func (d *MetricsCortexClusterDriver) Name() string {
return "test-environment"
}
func (d *MetricsCortexClusterDriver) ShouldDisableNode(*corev1.Reference) error {
d.lock.Lock()
defer d.lock.Unlock()
switch d.state {
case cortexops.InstallState_NotInstalled, cortexops.InstallState_Uninstalling:
return status.Error(codes.Unavailable, fmt.Sprintf("Cortex cluster is not installed"))
case cortexops.InstallState_Updating, cortexops.InstallState_Installed:
return nil
case cortexops.InstallState_Unknown:
fallthrough
default:
// can't determine cluster status, so don't disable the node
return nil
}
}
func (d *MetricsCortexClusterDriver) GetClusterConfiguration(context.Context, *emptypb.Empty) (*cortexops.ClusterConfiguration, error) {
d.lock.Lock()
defer d.lock.Unlock()
return d.Configuration, nil
}
func (d *MetricsCortexClusterDriver) ConfigureCluster(_ context.Context, conf *cortexops.ClusterConfiguration) (*emptypb.Empty, error) {
d.lock.Lock()
switch d.state {
case cortexops.InstallState_NotInstalled, cortexops.InstallState_Installed:
d.state = cortexops.InstallState_Updating
case cortexops.InstallState_Updating:
return nil, status.Error(codes.FailedPrecondition, "cluster is already being updated")
case cortexops.InstallState_Uninstalling:
return nil, status.Error(codes.FailedPrecondition, "cluster is currently being uninstalled")
default:
panic("bug: unknown state")
}
oldCtx, oldCancel := d.cortexCtx, d.cortexCancel
ctx, ca := context.WithCancel(waitctx.FromContext(d.Env.Context()))
d.cortexCtx = ctx
d.cortexCancel = ca
d.Configuration = conf
d.lock.Unlock()
go func() {
if oldCancel != nil {
oldCancel()
waitctx.Wait(oldCtx)
}
d.Env.StartCortex(ctx)
d.lock.Lock()
defer d.lock.Unlock()
d.state = cortexops.InstallState_Installed
}()
return &emptypb.Empty{}, nil
}
func (d *MetricsCortexClusterDriver) GetClusterStatus(context.Context, *emptypb.Empty) (*cortexops.InstallStatus, error) {
d.lock.Lock()
defer d.lock.Unlock()
return &cortexops.InstallStatus{
State: d.state,
Version: cortexVersion,
Metadata: map[string]string{"test-environment": "true"},
}, nil
}
func (d *MetricsCortexClusterDriver) UninstallCluster(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
d.lock.Lock()
switch d.state {
case cortexops.InstallState_NotInstalled:
return nil, status.Error(codes.FailedPrecondition, "cluster is not installed")
case cortexops.InstallState_Installed, cortexops.InstallState_Updating:
d.state = cortexops.InstallState_Uninstalling
case cortexops.InstallState_Uninstalling:
return nil, status.Error(codes.FailedPrecondition, "cluster is already being uninstalled")
default:
panic("bug: unknown state")
}
oldCtx, oldCancel := d.cortexCtx, d.cortexCancel
d.lock.Unlock()
go func() {
oldCancel()
waitctx.Wait(oldCtx)
d.lock.Lock()
defer d.lock.Unlock()
d.cortexCtx = nil
d.cortexCancel = nil
d.state = cortexops.InstallState_NotInstalled
}()
return &emptypb.Empty{}, nil
}
type MetricsOTELNodeDriver struct {
env *Environment
overridesMu sync.Mutex
overridesForNode map[string]*overridePrometheusConfig
otelCtx context.Context
otelCancel context.CancelFunc
}
func (m *MetricsOTELNodeDriver) ConfigureNode(nodeId string, conf *node.MetricsCapabilityConfig) {
lg := m.env.Logger.With("node", nodeId, "conf", "OTEL")
lg.Debug("configuring node")
exists := m.otelCtx != nil && m.otelCancel != nil
shouldExist := conf.Enabled &&
conf.GetSpec().GetOtel() != nil
if exists && !shouldExist {
lg.Info("stopping OTEL agent")
m.otelCancel()
m.otelCancel = nil
m.otelCtx = nil
} else if !exists && shouldExist {
lg.Info("starting OTEL agent")
ctx, ca := context.WithCancel(m.env.Context())
m.env.StartOTELCollectorContext(ctx, nodeId, conf.GetSpec())
m.otelCtx = ctx
m.otelCancel = ca
} else if exists && shouldExist {
lg.Debug("nothing to do (already running)")
} else {
lg.Debug("nothing to do (already stopped)")
}
}
func (m *MetricsOTELNodeDriver) DiscoverPrometheuses(ctx context.Context, s string) ([]*remoteread.DiscoveryEntry, error) {
return nil, nil
}
func (m *MetricsOTELNodeDriver) SetOverridesForNode(nodeName string, overrides *overridePrometheusConfig) {
m.overridesMu.Lock()
defer m.overridesMu.Unlock()
m.overridesForNode[nodeName] = overrides
}
var _ metrics_agent_drivers.MetricsNodeDriver = (*MetricsOTELNodeDriver)(nil)
type MetricsPrometheusNodeDriver struct {
env *Environment
overridesMu sync.Mutex
overridesForNode map[string]*overridePrometheusConfig
prometheusMu sync.Mutex
prometheusCtx context.Context
prometheusCancel context.CancelFunc
}
func (d *MetricsPrometheusNodeDriver) SetOverridesForNode(nodeName string, overrides *overridePrometheusConfig) {
d.overridesMu.Lock()
defer d.overridesMu.Unlock()
d.overridesForNode[nodeName] = overrides
}
var _ metrics_agent_drivers.MetricsNodeDriver = (*MetricsPrometheusNodeDriver)(nil)
// ConfigureNode implements drivers.MetricsNodeDriver
func (d *MetricsPrometheusNodeDriver) ConfigureNode(nodeId string, conf *node.MetricsCapabilityConfig) {
lg := d.env.Logger.With("node", nodeId, "conf", "prometheus")
lg.Debug("configuring node")
d.prometheusMu.Lock()
defer d.prometheusMu.Unlock()
exists := d.prometheusCtx != nil && d.prometheusCancel != nil
shouldExist := conf.Enabled &&
conf.GetSpec().GetPrometheus() != nil &&
conf.GetSpec().GetPrometheus().GetDeploymentStrategy() == "test-environment"
if exists && !shouldExist {
lg.Info("stopping prometheus")
d.prometheusCancel()
d.prometheusCancel = nil
d.prometheusCtx = nil
} else if !exists && shouldExist {
lg.Info("starting prometheus")
ctx, ca := context.WithCancel(d.env.Context())
d.env.StartPrometheusContext(ctx, nodeId, d.overridesForNode[nodeId])
d.prometheusCtx = ctx
d.prometheusCancel = ca
} else if exists && shouldExist {
lg.Debug("nothing to do (already running)")
} else {
lg.Debug("nothing to do (already stopped)")
}
}
// DiscoverPrometheuses implements drivers.MetricsNodeDriver
func (*MetricsPrometheusNodeDriver) DiscoverPrometheuses(context.Context, string) ([]*remoteread.DiscoveryEntry, error) {
return nil, nil
}
type AlertingAlertManagerClusterDriver struct {
env *Environment
managedInstances []AlertingServerUnit
enabled *atomic.Bool
ConfigFile string
stateMu *sync.RWMutex
*shared.AlertingClusterOptions
*alerting_drivers.AlertingManagerDriverOptions
*alertops.ClusterConfiguration
alertops.UnsafeAlertingAdminServer
}
var _ alerting_drivers.ClusterDriver = (*AlertingAlertManagerClusterDriver)(nil)
var _ alertops.AlertingAdminServer = (*AlertingAlertManagerClusterDriver)(nil)
func NewAlertingAlertManagerClusterDriver(env *Environment, opts ...alerting_drivers.AlertingManagerDriverOption) *AlertingAlertManagerClusterDriver {
dir := env.GenerateNewTempDirectory("alertmanager-config")
err := os.MkdirAll(dir, 0755)
if err != nil {
panic(err)
}
configFile := path.Join(dir, "alertmanager.yaml")
lg := logger.NewPluginLogger().Named("alerting-test-cluster-driver")
lg = lg.With("config-file", configFile)
options := &alerting_drivers.AlertingManagerDriverOptions{
Logger: lg,
}
options.Apply(opts...)
rTree := routing.NewRoutingTree("http://localhost:6000")
rTreeBytes, err := yaml.Marshal(rTree)
if err != nil {
panic(err)
}
err = os.WriteFile(configFile, rTreeBytes, 0644)
if err != nil {
panic(err)
}
initial := &atomic.Bool{}
initial.Store(false)
return &AlertingAlertManagerClusterDriver{
env: env,
managedInstances: []AlertingServerUnit{},
enabled: initial,
ConfigFile: configFile,
AlertingClusterOptions: &shared.AlertingClusterOptions{},
ClusterConfiguration: &alertops.ClusterConfiguration{
ResourceLimits: &alertops.ResourceLimitSpec{},
},
AlertingManagerDriverOptions: options,
stateMu: &sync.RWMutex{},
}
}
func (l *AlertingAlertManagerClusterDriver) GetClusterConfiguration(ctx context.Context, empty *emptypb.Empty) (*alertops.ClusterConfiguration, error) {
return l.ClusterConfiguration, nil
}
func (l *AlertingAlertManagerClusterDriver) ConfigureCluster(ctx context.Context, configuration *alertops.ClusterConfiguration) (*emptypb.Empty, error) {
l.stateMu.Lock()
defer l.stateMu.Unlock()
if err := configuration.Validate(); err != nil {
return nil, err
}
cur := l.ClusterConfiguration
if int(cur.NumReplicas) != len(l.managedInstances) {
panic(fmt.Sprintf("current cluster config indicates %d replicas but we have %d replicas running",
cur.NumReplicas, len(l.managedInstances)))
}
if cur.NumReplicas > configuration.NumReplicas { // shrink replicas
for i := cur.NumReplicas - 1; i > configuration.NumReplicas-1; i-- {
l.managedInstances[i].CancelFunc()
}
l.managedInstances = slices.Delete(l.managedInstances, int(configuration.NumReplicas-1), int(cur.NumReplicas-1))
} else if cur.NumReplicas < configuration.NumReplicas { // grow replicas
for i := cur.NumReplicas; i < configuration.NumReplicas; i++ {
l.managedInstances = append(
l.managedInstances,
l.StartAlertingBackendServer(l.env.Context(), l.ConfigFile),
)
}
}
if len(l.managedInstances) > 1 {
l.AlertingClusterOptions.WorkerNodesService = "localhost"
l.AlertingClusterOptions.WorkerNodePort = l.managedInstances[1].AlertManagerPort
l.AlertingClusterOptions.OpniPort = l.managedInstances[1].OpniPort
}
l.ClusterConfiguration = configuration
for _, subscriber := range l.Subscribers {
subscriber <- shared.AlertingClusterNotification{
A: true,
B: l.AlertingClusterOptions,
}
}
return &emptypb.Empty{}, nil
}
func (l *AlertingAlertManagerClusterDriver) GetClusterStatus(ctx context.Context, empty *emptypb.Empty) (*alertops.InstallStatus, error) {
if !l.enabled.Load() {
return &alertops.InstallStatus{
State: alertops.InstallState_NotInstalled,
}, nil
}
l.stateMu.RLock()
defer l.stateMu.RUnlock()
for _, replica := range l.managedInstances {
apiNode := backend.NewAlertManagerReadyClient(ctx, fmt.Sprintf("127.0.0.1:%d", replica.AlertManagerPort))
if err := apiNode.DoRequest(); err != nil {
return &alertops.InstallStatus{
State: alertops.InstallState_InstallUpdating,
}, nil
}
}
return &alertops.InstallStatus{
State: alertops.InstallState_Installed,
}, nil
}
func (l *AlertingAlertManagerClusterDriver) InstallCluster(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
if l.enabled.Load() {
return &emptypb.Empty{}, nil
}
if len(l.managedInstances) > 0 {
panic("should not have existing replicas")
}
l.stateMu.Lock()
defer l.stateMu.Unlock()
l.NumReplicas = 1
for i := 0; i < int(l.NumReplicas); i++ {
l.managedInstances = append(
l.managedInstances,
l.StartAlertingBackendServer(l.env.Context(), l.ConfigFile),
)
}
l.enabled.Store(true)
l.ClusterSettleTimeout = "1m0s"
l.ClusterGossipInterval = "200ms"
l.ClusterPushPullInterval = "1m0s"
l.ResourceLimits.Cpu = "500m"
l.ResourceLimits.Memory = "200Mi"
l.ResourceLimits.Storage = "500Mi"
l.AlertingClusterOptions.ControllerNodeService = "localhost"
l.AlertingClusterOptions.ControllerClusterPort = l.managedInstances[0].ClusterPort
l.AlertingClusterOptions.ControllerNodePort = l.managedInstances[0].AlertManagerPort
l.AlertingClusterOptions.OpniPort = l.managedInstances[0].OpniPort
rTree := routing.NewRoutingTree(fmt.Sprintf("http://localhost:%d", l.managedInstances[0].OpniPort))
rTreeBytes, err := yaml.Marshal(rTree)
if err != nil {
panic(err)
}
err = os.WriteFile(l.ConfigFile, rTreeBytes, 0644)
if err != nil {
panic(err)
}
for _, subscriber := range l.Subscribers {
subscriber <- shared.AlertingClusterNotification{
A: true,
B: l.AlertingClusterOptions,
}
}
return &emptypb.Empty{}, nil
}
func (l *AlertingAlertManagerClusterDriver) UninstallCluster(ctx context.Context, req *alertops.UninstallRequest) (*emptypb.Empty, error) {
l.stateMu.Lock()
defer l.stateMu.Unlock()
for _, replica := range l.managedInstances {
replica.CancelFunc()
}
l.managedInstances = []AlertingServerUnit{}
l.enabled.Store(false)
for _, subscriber := range l.Subscribers {
subscriber <- shared.AlertingClusterNotification{
A: false,
B: nil,
}
}
return &emptypb.Empty{}, nil
}
func (l *AlertingAlertManagerClusterDriver) GetRuntimeOptions() shared.AlertingClusterOptions {
return *l.AlertingClusterOptions
}
func (l *AlertingAlertManagerClusterDriver) Name() string {
return "local-alerting"
}
func (l *AlertingAlertManagerClusterDriver) ShouldDisableNode(reference *corev1.Reference) error {
return nil
}
type AlertingServerUnit struct {
AlertManagerPort int
ClusterPort int
OpniPort int
Ctx context.Context
CancelFunc context.CancelFunc
}
func (l *AlertingAlertManagerClusterDriver) StartAlertingBackendServer(
ctx context.Context,
configFilePath string,
) AlertingServerUnit {
opniBin := path.Join(l.env.TestBin, "../../bin/opni")
webPort := freeport.GetFreePort()
opniPort := freeport.GetFreePort()
syncerPort := freeport.GetFreePort()
syncerArgs := []string{
"alerting-server",
fmt.Sprintf("--syncer.alertmanager.config.file=%s", configFilePath),
fmt.Sprintf("--syncer.listen.address=:%d", syncerPort),
fmt.Sprintf("--syncer.alertmanager.address=%s", "http://localhost:"+strconv.Itoa(webPort)),
fmt.Sprintf("--syncer.gateway.join.address=%s", ":"+strings.Split(l.env.GatewayConfig().Spec.Management.GRPCListenAddress, ":")[2]),
"syncer",
}
l.Logger.Debug("Syncer start : " + strings.Join(syncerArgs, " "))
clusterPort := freeport.GetFreePort()
alertmanagerArgs := []string{
"alerting-server",
"alertmanager",
fmt.Sprintf("--config.file=%s", configFilePath),
fmt.Sprintf("--web.listen-address=:%d", webPort),
fmt.Sprintf("--opni.listen-address=:%d", opniPort),
fmt.Sprintf("--cluster.listen-address=:%d", clusterPort),
"--storage.path=/tmp/data",
// "--log.level=debug",
}
if len(l.managedInstances) > 0 {
for _, replica := range l.managedInstances {
alertmanagerArgs = append(alertmanagerArgs,
fmt.Sprintf("--cluster.peer=localhost:%d", replica.ClusterPort))
}
l.AlertingClusterOptions.WorkerNodesService = "localhost"
l.AlertingClusterOptions.WorkerNodePort = webPort
}
ctxCa, cancelFunc := context.WithCancel(ctx)
alertmanagerCmd := exec.CommandContext(ctxCa, opniBin, alertmanagerArgs...)
plugins.ConfigureSysProcAttr(alertmanagerCmd)
l.Logger.With("alertmanager-port", webPort, "opni-port", opniPort).Info("Starting AlertManager")
session, err := testutil.StartCmd(alertmanagerCmd)
if err != nil {
if !errors.Is(ctx.Err(), context.Canceled) {
panic(fmt.Sprintf("%s : opni bin path : %s", err, opniBin))
} else {
panic(err)
}
}
retries := 0
for ctx.Err() == nil {
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/-/ready", webPort))
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
break
}
}
time.Sleep(time.Second)
retries += 1
if retries > 90 {
panic("AlertManager failed to start")
}
}
syncerCmd := exec.CommandContext(ctxCa, opniBin, syncerArgs...)
plugins.ConfigureSysProcAttr(syncerCmd)
l.Logger.With("port", syncerPort).Info("Starting AlertManager Syncer")
_, err = testutil.StartCmd(syncerCmd)
if err != nil {
if !errors.Is(ctx.Err(), context.Canceled) {
panic(fmt.Sprintf("%s : opni bin path : %s", err, opniBin))
} else {
panic(err)
}
}
l.Logger.With("address", fmt.Sprintf("http://localhost:%d", webPort)).Info("AlertManager started")
waitctx.Permissive.Go(ctx, func() {
<-ctx.Done()
cmd, _ := session.G()
if cmd != nil {
cmd.Signal(os.Signal(syscall.SIGTERM))
}
})
return AlertingServerUnit{
AlertManagerPort: webPort,
ClusterPort: clusterPort,
OpniPort: opniPort,
Ctx: ctxCa,
CancelFunc: cancelFunc,
}
}