-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathkas-fleetshard-sync.go
375 lines (325 loc) · 12.7 KB
/
kas-fleetshard-sync.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
package kasfleetshardsync
import (
"context"
"fmt"
"testing"
"time"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/internal/kafka/internal/api/private"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/internal/kafka/internal/config"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/internal/kafka/internal/kafkas/types"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/internal/kafka/internal/services"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/internal/kafka/test"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/pkg/client/keycloak"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/pkg/client/ocm"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/pkg/api"
coreTest "github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/test"
"github.com/golang-jwt/jwt/v4"
clustersmgmtv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
)
const AdminServerURI = "http://test-admin-server-uri.com"
var StandardCapacityInfo private.DataPlaneClusterUpdateStatusRequestCapacity = private.DataPlaneClusterUpdateStatusRequestCapacity{
MaxUnits: 5,
RemainingUnits: 3,
}
var DeveloperCapacityInfo private.DataPlaneClusterUpdateStatusRequestCapacity = private.DataPlaneClusterUpdateStatusRequestCapacity{
MaxUnits: 50,
RemainingUnits: 8,
}
// defaultUpdateDataplaneClusterStatusFunc - The default behaviour for updating data plane cluster status in each Kas Fleetshard Sync reconcile.
// Retrieves all clusters in the database in a 'waiting_for_kas_fleetshard_operator' state and updates it to 'ready' once all of the addons are installed.
var defaultUpdateDataplaneClusterStatusFunc mockKasFleetshardSyncUpdateDataPlaneClusterStatusFunc = func(helper *coreTest.Helper, privateClient *private.APIClient, ocmClient ocm.Client) error {
var clusterService services.ClusterService
var ocmConfig *ocm.OCMConfig
var kasFleetshardConfig *config.KasFleetshardConfig
helper.Env.MustResolveAll(&clusterService, &ocmConfig, &kasFleetshardConfig)
clusters, err := clusterService.FindAllClusters(services.FindClusterCriteria{
Status: api.ClusterWaitingForKasFleetShardOperator,
})
if err != nil {
return fmt.Errorf("unable to retrieve a list of clusters in a '%s' state: %s", api.ClusterWaitingForKasFleetShardOperator, err)
}
for _, cluster := range clusters {
if cluster.ProviderType == api.ClusterProviderOCM {
managedKafkaAddon, err := ocmClient.GetAddon(cluster.ClusterID, ocmConfig.StrimziOperatorAddonID)
if err != nil {
return err
}
kasFleetShardOperatorAddon, err := ocmClient.GetAddon(cluster.ClusterID, ocmConfig.KasFleetshardAddonID)
if err != nil {
return err
}
if !(managedKafkaAddon.State() == clustersmgmtv1.AddOnInstallationStateReady && (kasFleetShardOperatorAddon.State() == clustersmgmtv1.AddOnInstallationStateReady || kasFleetShardOperatorAddon.State() == clustersmgmtv1.AddOnInstallationStateInstalling)) {
continue
}
}
ctx, err := NewAuthenticatedContextForDataPlaneCluster(helper, cluster.ClusterID)
if err != nil {
return err
}
clusterStatusUpdateRequest := SampleDataPlaneclusterStatusRequestWithAvailableCapacity()
if _, err := privateClient.AgentClustersApi.UpdateAgentClusterStatus(ctx, cluster.ClusterID, *clusterStatusUpdateRequest); err != nil {
return fmt.Errorf("failed to update cluster status via agent endpoint: %v", err)
}
}
return nil
}
// defaultUpdateKafkaStatusFunc - The default behaviour for updating kafka status in each Kas Fleetshard Sync reconcile.
// This function retrieves and updates Kafkas in all ready and full data plane clusters.
// Any Kafkas marked for deletion are updated to 'deleting'
// Kafkas with any other status are updated to 'ready'
var defaultUpdateKafkaStatusFunc mockKasFleetshardSyncupdateKafkaClusterStatusFunc = func(helper *coreTest.Helper, privateClient *private.APIClient) error {
var clusterService services.ClusterService
helper.Env.MustResolveAll(&clusterService)
var dataplaneClusters []*api.Cluster
readyDataplaneClusters, err := clusterService.FindAllClusters(services.FindClusterCriteria{
Status: api.ClusterReady,
})
if err != nil {
return fmt.Errorf("unable to retrieve a list of clusters in a '%s' state: %s", api.ClusterReady, err)
}
dataplaneClusters = append(dataplaneClusters, readyDataplaneClusters...)
for _, dataplaneCluster := range dataplaneClusters {
ctx, err := NewAuthenticatedContextForDataPlaneCluster(helper, dataplaneCluster.ClusterID)
if err != nil {
return err
}
kafkaList, _, err := privateClient.AgentClustersApi.GetKafkas(ctx, dataplaneCluster.ClusterID)
if err != nil {
return err
}
kafkaStatusList := make(map[string]private.DataPlaneKafkaStatus)
for _, kafka := range kafkaList.Items {
id := kafka.Metadata.Annotations.Bf2OrgId
if kafka.Spec.Deleted {
kafkaStatusList[id] = GetDeletedKafkaStatusResponse()
} else if kafka.Metadata.Labels.Bf2OrgSuspended == "true" {
// Update any 'suspending' kafkas to 'suspended'
kafkaStatusList[id] = GetSuspendedKafkaStatusResponse()
} else {
// Update any other clusters not in a 'deprovisioning' state to 'ready'
kafkaStatusList[id] = GetReadyKafkaStatusResponse(dataplaneCluster.ClusterDNS)
}
}
if _, err = privateClient.AgentClustersApi.UpdateKafkaClusterStatus(ctx, dataplaneCluster.ClusterID, kafkaStatusList); err != nil {
return err
}
}
return nil
}
type MockKasFleetshardSyncBuilder interface {
// SetUpdateDataplaneClusterStatusFunc - Sets behaviour for updating dataplane clusters in each KAS Fleetshard sync reconcile
SetUpdateDataplaneClusterStatusFunc(mockKasFleetshardSyncUpdateDataPlaneClusterStatusFunc)
// SetUpdateKafkaStatusFunc - Sets behaviour for updating kafka clusters in each KAS Fleetshard sync reconcile
SetUpdateKafkaStatusFunc(mockKasFleetshardSyncupdateKafkaClusterStatusFunc)
// SetInterval - Sets the repeat interval for the mock KAS Fleetshard sync
SetInterval(interval time.Duration)
// Build - Builds a mock KAS Fleetshard sync
Build() MockKasFleetshardSync
}
// Mock KAS Fleetshard Sync Builder
type mockKasFleetshardSyncBuilder struct {
kfsync mockKasFleetshardSync
}
var _ MockKasFleetshardSyncBuilder = &mockKasFleetshardSyncBuilder{}
func NewMockKasFleetshardSyncBuilder(helper *coreTest.Helper, t *testing.T) MockKasFleetshardSyncBuilder {
var ocmClient ocm.ClusterManagementClient
helper.Env.MustResolveAll(&ocmClient)
return &mockKasFleetshardSyncBuilder{
kfsync: mockKasFleetshardSync{
helper: helper,
t: t,
ocmClient: ocmClient,
privateClient: test.NewPrivateAPIClient(helper),
updateDataplaneClusterStatus: defaultUpdateDataplaneClusterStatusFunc,
updateKafkaClusterStatus: defaultUpdateKafkaStatusFunc,
interval: 1 * time.Second,
},
}
}
func (m *mockKasFleetshardSyncBuilder) SetUpdateDataplaneClusterStatusFunc(updateDataplaneClusterStatusFunc mockKasFleetshardSyncUpdateDataPlaneClusterStatusFunc) {
m.kfsync.updateDataplaneClusterStatus = updateDataplaneClusterStatusFunc
}
func (m *mockKasFleetshardSyncBuilder) SetUpdateKafkaStatusFunc(updateKafkaStatusFunc mockKasFleetshardSyncupdateKafkaClusterStatusFunc) {
m.kfsync.updateKafkaClusterStatus = updateKafkaStatusFunc
}
func (m *mockKasFleetshardSyncBuilder) SetInterval(interval time.Duration) {
m.kfsync.interval = interval
}
func (m *mockKasFleetshardSyncBuilder) Build() MockKasFleetshardSync {
return &m.kfsync
}
type MockKasFleetshardSync interface {
// Start - Starts the KAS Fleetshard sync reconciler
Start()
// Stop - Stops the KAS Fleetshard sync reconciler
Stop()
}
type mockKasFleetshardSyncUpdateDataPlaneClusterStatusFunc func(helper *coreTest.Helper, privateClient *private.APIClient, ocmClient ocm.Client) error
type mockKasFleetshardSyncupdateKafkaClusterStatusFunc func(helper *coreTest.Helper, privateClient *private.APIClient) error
type mockKasFleetshardSync struct {
helper *coreTest.Helper
t *testing.T
ocmClient ocm.Client
ticker *time.Ticker
privateClient *private.APIClient
interval time.Duration
updateDataplaneClusterStatus mockKasFleetshardSyncUpdateDataPlaneClusterStatusFunc
updateKafkaClusterStatus mockKasFleetshardSyncupdateKafkaClusterStatusFunc
}
var _ MockKasFleetshardSync = &mockKasFleetshardSync{}
func (m *mockKasFleetshardSync) Start() {
// starts reconcile immediately and then on every repeat interval
// run reconcile
m.t.Log("Starting mock fleetshard sync")
m.ticker = time.NewTicker(m.interval)
go func() {
for range m.ticker.C {
m.reconcileDataplaneClusters()
m.reconcileKafkaClusters()
}
}()
}
func (m *mockKasFleetshardSync) Stop() {
m.ticker.Stop()
}
func (m *mockKasFleetshardSync) reconcileDataplaneClusters() {
if err := m.updateDataplaneClusterStatus(m.helper, m.privateClient, m.ocmClient); err != nil {
m.t.Logf("Unable to update dataplane cluster status: %s", err)
}
}
func (m *mockKasFleetshardSync) reconcileKafkaClusters() {
if err := m.updateKafkaClusterStatus(m.helper, m.privateClient); err != nil {
m.t.Logf("Failed to update Kafka cluster status: %s", err)
}
}
// Returns an authenticated context to be used for calling the data plane endpoints
func NewAuthenticatedContextForDataPlaneCluster(h *coreTest.Helper, clusterID string) (context.Context, error) {
var keycloakConfig *keycloak.KeycloakConfig
var clusterService services.ClusterService
h.Env.MustResolveAll(&keycloakConfig, &clusterService)
account := h.NewAllowedServiceAccount()
claims := jwt.MapClaims{
"iss": keycloakConfig.SSOProviderRealm().ValidIssuerURI,
}
clientId, err := clusterService.GetClientID(clusterID)
if err != nil {
return nil, err
}
claims["clientId"] = clientId
token := h.CreateJWTStringWithClaim(account, claims)
ctx := context.WithValue(context.Background(), private.ContextAccessToken, token)
return ctx, err
}
// Returns a sample data plane cluster status request with available capacity
func SampleDataPlaneclusterStatusRequestWithAvailableCapacity() *private.DataPlaneClusterUpdateStatusRequest {
return &private.DataPlaneClusterUpdateStatusRequest{
Conditions: []private.DataPlaneClusterUpdateStatusRequestConditions{
{
Type: "Ready",
Status: "True",
},
},
Capacity: map[string]private.DataPlaneClusterUpdateStatusRequestCapacity{
types.STANDARD.String(): StandardCapacityInfo,
types.DEVELOPER.String(): DeveloperCapacityInfo,
},
Strimzi: []private.DataPlaneClusterUpdateStatusRequestStrimzi{
{
Ready: true,
Version: "strimzi-cluster-operator.v0.23.0-0",
KafkaVersions: []string{
"2.7.0",
"2.5.3",
"2.6.2",
},
KafkaIbpVersions: []string{
"2.7",
"2.5",
"2.6",
},
},
{
Ready: true,
Version: "strimzi-cluster-operator.v0.21.0-0",
KafkaVersions: []string{
"2.7.0",
"2.3.1",
"2.1.2",
},
KafkaIbpVersions: []string{
"2.7",
"2.1",
"2.3",
},
},
},
}
}
// Return a Kafka status for a deleted cluster
func GetDeletedKafkaStatusResponse() private.DataPlaneKafkaStatus {
return private.DataPlaneKafkaStatus{
Conditions: []private.DataPlaneClusterUpdateStatusRequestConditions{
{
Type: "Ready",
Reason: "Deleted",
},
},
}
}
func GetDefaultReportedKafkaVersion() string {
return "2.7.0"
}
func GetDefaultReportedStrimziVersion() string {
return "strimzi-cluster-operator.v0.23.0-0"
}
// Return a kafka status for a ready cluster
func GetReadyKafkaStatusResponse(clusterDNS string) private.DataPlaneKafkaStatus {
return private.DataPlaneKafkaStatus{
Conditions: []private.DataPlaneClusterUpdateStatusRequestConditions{
{
Type: "Ready",
Status: "True",
},
},
Versions: private.DataPlaneKafkaStatusVersions{
Kafka: GetDefaultReportedKafkaVersion(),
Strimzi: GetDefaultReportedStrimziVersion(),
},
Routes: &[]private.DataPlaneKafkaStatusRoutes{
{
Name: "test-route",
Prefix: "",
Router: clusterDNS,
},
},
AdminServerURI: AdminServerURI,
}
}
func GetErrorKafkaStatusResponse() private.DataPlaneKafkaStatus {
return private.DataPlaneKafkaStatus{
Conditions: []private.DataPlaneClusterUpdateStatusRequestConditions{
{
Type: "Ready",
Reason: "Error",
Status: "False",
},
},
}
}
func GetErrorWithCustomMessageKafkaStatusResponse(message string) private.DataPlaneKafkaStatus {
res := GetErrorKafkaStatusResponse()
res.Conditions[0].Message = message
return res
}
// Return a Kafka status for a suspended instance
func GetSuspendedKafkaStatusResponse() private.DataPlaneKafkaStatus {
return private.DataPlaneKafkaStatus{
Conditions: []private.DataPlaneClusterUpdateStatusRequestConditions{
{
Type: "Ready",
Reason: "Suspended",
Status: "False",
},
},
}
}