-
Notifications
You must be signed in to change notification settings - Fork 207
/
cluster.go
382 lines (334 loc) · 13.5 KB
/
cluster.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
package e2e
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/Azure/agentbaker/pkg/agent/datamodel"
nbcontractv1 "github.com/Azure/agentbaker/pkg/proto/nbcontract/v1"
"github.com/Azure/agentbakere2e/config"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v6"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
)
var (
clusterKubenet *Cluster
clusterKubenetAirgap *Cluster
clusterAzureNetwork *Cluster
clusterKubenetError error
clusterKubenetAirgapError error
clusterAzureNetworkError error
clusterKubenetOnce sync.Once
clusterKubenetAirgapOnce sync.Once
clusterAzureNetworkOnce sync.Once
)
type Cluster struct {
Model *armcontainerservice.ManagedCluster
Kube *Kubeclient
SubnetID string
NodeBootstrappingConfiguration *datamodel.NodeBootstrappingConfiguration
AKSNodeConfig *nbcontractv1.Configuration
Maintenance *armcontainerservice.MaintenanceConfiguration
}
// Returns true if the cluster is configured with Azure CNI
func (c *Cluster) IsAzureCNI() (bool, error) {
if c.Model.Properties.NetworkProfile != nil {
return *c.Model.Properties.NetworkProfile.NetworkPlugin == armcontainerservice.NetworkPluginAzure, nil
}
return false, fmt.Errorf("cluster network profile was nil: %+v", c.Model)
}
// Returns the maximum number of pods per node of the cluster's agentpool
func (c *Cluster) MaxPodsPerNode() (int, error) {
if len(c.Model.Properties.AgentPoolProfiles) > 0 {
return int(*c.Model.Properties.AgentPoolProfiles[0].MaxPods), nil
}
return 0, fmt.Errorf("cluster agentpool profiles were nil or empty: %+v", c.Model)
}
// Same cluster can be attempted to be created concurrently by different tests
// sync.Once is used to ensure that only one cluster for the set of tests is created
func ClusterKubenet(ctx context.Context, t *testing.T) (*Cluster, error) {
clusterKubenetOnce.Do(func() {
clusterKubenet, clusterKubenetError = prepareCluster(ctx, t, getKubenetClusterModel("abe2e-kubenet"), false)
})
return clusterKubenet, clusterKubenetError
}
func ClusterKubenetAirgap(ctx context.Context, t *testing.T) (*Cluster, error) {
clusterKubenetAirgapOnce.Do(func() {
cluster, err := prepareCluster(ctx, t, getKubenetClusterModel("abe2e-kubenet-airgap"), true)
if err == nil {
err = addAirgapNetworkSettings(ctx, t, cluster.Model)
}
clusterKubenetAirgap, clusterKubenetAirgapError = cluster, err
})
return clusterKubenetAirgap, clusterKubenetAirgapError
}
func ClusterAzureNetwork(ctx context.Context, t *testing.T) (*Cluster, error) {
clusterAzureNetworkOnce.Do(func() {
clusterAzureNetwork, clusterAzureNetworkError = prepareCluster(ctx, t, getAzureNetworkClusterModel("abe2e-azure-network"), false)
})
return clusterAzureNetwork, clusterAzureNetworkError
}
func prepareCluster(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster, isAirgap bool) (*Cluster, error) {
cluster.Name = to.Ptr(fmt.Sprintf("%s-%s", *cluster.Name, hash(cluster)))
// private acr must be created before we add the debug daemonsets
if isAirgap {
if err := createPrivateAzureContainerRegistry(ctx, t, config.ResourceGroupName, config.PrivateACRName); err != nil {
return nil, fmt.Errorf("failed to create private acr: %w", err)
}
}
cluster, err := getOrCreateCluster(ctx, t, cluster)
if err != nil {
return nil, err
}
maintenance, err := getOrCreateMaintenanceConfiguration(ctx, t, cluster)
if err != nil {
return nil, fmt.Errorf("get or create maintenance configuration: %w", err)
}
// sometimes tests can be interrupted and vmss are left behind
// don't waste resource and delete them
if err := collectGarbageVMSS(ctx, t, cluster); err != nil {
return nil, fmt.Errorf("collect garbage vmss: %w", err)
}
kube, err := getClusterKubeClient(ctx, config.ResourceGroupName, *cluster.Name)
if err != nil {
return nil, fmt.Errorf("get kube client using cluster %q: %w", *cluster.Name, err)
}
t.Logf("node resource group: %s", *cluster.Properties.NodeResourceGroup)
subnetID, err := getClusterSubnetID(ctx, *cluster.Properties.NodeResourceGroup, t)
if err != nil {
return nil, fmt.Errorf("get cluster subnet: %w", err)
}
t.Logf("ensuring debug daemonsets")
if err := ensureDebugDaemonsets(ctx, t, kube, isAirgap); err != nil {
return nil, fmt.Errorf("ensure debug daemonsets for %q: %w", *cluster.Name, err)
}
nbc := getBaseNodeBootstrappingConfiguration(ctx, t, kube)
return &Cluster{
Model: cluster,
Kube: kube,
SubnetID: subnetID,
NodeBootstrappingConfiguration: nbc,
Maintenance: maintenance,
AKSNodeConfig: nbcToNbcContractV1(nbc), // TODO: replace with base template
}, nil
}
func hash(cluster *armcontainerservice.ManagedCluster) string {
jsonData, err := json.Marshal(cluster)
if err != nil {
panic(err)
}
hasher := sha256.New()
_, err = hasher.Write(jsonData)
if err != nil {
panic(err)
}
hexHash := hex.EncodeToString(hasher.Sum(nil))
return hexHash[:5]
}
func getOrCreateCluster(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster) (*armcontainerservice.ManagedCluster, error) {
existingCluster, err := config.Azure.AKS.Get(ctx, config.ResourceGroupName, *cluster.Name, nil)
var azErr *azcore.ResponseError
if errors.As(err, &azErr) && azErr.StatusCode == 404 {
return createNewAKSClusterWithRetry(ctx, t, cluster, config.ResourceGroupName)
}
if err != nil {
return nil, fmt.Errorf("failed to get cluster %q: %w", *cluster.Name, err)
}
t.Logf("cluster %s already exists in rg %s\n", *cluster.Name, config.ResourceGroupName)
switch *existingCluster.Properties.ProvisioningState {
case "Succeeded":
return &existingCluster.ManagedCluster, nil
case "Creating", "Updating":
return waitUntilClusterReady(ctx, config.ResourceGroupName, *cluster.Name)
default:
// this operation will try to update the cluster if it's in a failed state
return createNewAKSClusterWithRetry(ctx, t, cluster, config.ResourceGroupName)
}
}
func createNewAKSCluster(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster) (*armcontainerservice.ManagedCluster, error) {
t.Logf("creating or updating cluster %s in rg %s\n", *cluster.Name, *cluster.Location)
// Note, it seems like the operation still can start a trigger a new operation even if nothing has changes
pollerResp, err := config.Azure.AKS.BeginCreateOrUpdate(
ctx,
config.ResourceGroupName,
*cluster.Name,
*cluster,
nil,
)
if err != nil {
return nil, fmt.Errorf("failed to begin aks cluster creation: %w", err)
}
clusterResp, err := pollerResp.PollUntilDone(ctx, config.DefaultPollUntilDoneOptions)
if err != nil {
return nil, fmt.Errorf("failed to wait for aks cluster creation %w", err)
}
return &clusterResp.ManagedCluster, nil
}
// createNewAKSClusterWithRetry is a wrapper around createNewAKSCluster
// that retries creating a cluster if it fails with a 409 Conflict error
// clusters are reused, and sometimes a cluster can be in UPDATING or DELETING state
// simple retry should be sufficient to avoid such conflicts
func createNewAKSClusterWithRetry(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster, resourceGroup string) (*armcontainerservice.ManagedCluster, error) {
maxRetries := 10
retryInterval := 30 * time.Second
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
t.Logf("Attempt %d: creating or updating cluster %s in region %s and rg %s\n", attempt+1, *cluster.Name, *cluster.Location, resourceGroup)
createdCluster, err := createNewAKSCluster(ctx, t, cluster)
if err == nil {
return createdCluster, nil
}
// Check if the error is a 409 Conflict
var respErr *azcore.ResponseError
if errors.As(err, &respErr) && respErr.StatusCode == 409 {
lastErr = err
t.Logf("Attempt %d failed with 409 Conflict: %v. Retrying in %v...\n", attempt+1, err, retryInterval)
select {
case <-time.After(retryInterval):
// Continue to next iteration
case <-ctx.Done():
return nil, fmt.Errorf("context canceled while retrying cluster creation: %w", ctx.Err())
}
} else {
// If it's not a 409 error, return immediately
return nil, fmt.Errorf("failed to create cluster: %w", err)
}
}
return nil, fmt.Errorf("failed to create cluster after %d attempts due to persistent 409 Conflict: %w", maxRetries, lastErr)
}
func getOrCreateMaintenanceConfiguration(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster) (*armcontainerservice.MaintenanceConfiguration, error) {
existingMaintenance, err := config.Azure.Maintenance.Get(ctx, config.ResourceGroupName, *cluster.Name, "default", nil)
var azErr *azcore.ResponseError
if errors.As(err, &azErr) && azErr.StatusCode == 404 {
return createNewMaintenanceConfiguration(ctx, t, cluster)
}
if err != nil {
return nil, fmt.Errorf("failed to get maintenance configuration 'default' for cluster %q: %w", *cluster.Name, err)
}
return &existingMaintenance.MaintenanceConfiguration, nil
}
func createNewMaintenanceConfiguration(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster) (*armcontainerservice.MaintenanceConfiguration, error) {
t.Logf("creating maintenance configuration for cluster %s in rg %s\n", *cluster.Name, config.ResourceGroupName)
maintenance := armcontainerservice.MaintenanceConfiguration{
Properties: &armcontainerservice.MaintenanceConfigurationProperties{
MaintenanceWindow: &armcontainerservice.MaintenanceWindow{
NotAllowedDates: []*armcontainerservice.DateSpan{ // no maintenance till 2100
{
End: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2100-01-01"); return t }()),
Start: to.Ptr(func() time.Time { t, _ := time.Parse("2006-01-02", "2000-01-01"); return t }()),
}},
DurationHours: to.Ptr[int32](4),
StartTime: to.Ptr("00:00"), //PST
UTCOffset: to.Ptr("+08:00"), //PST
Schedule: &armcontainerservice.Schedule{
RelativeMonthly: &armcontainerservice.RelativeMonthlySchedule{
DayOfWeek: to.Ptr(armcontainerservice.WeekDayMonday),
IntervalMonths: to.Ptr[int32](3),
WeekIndex: to.Ptr(armcontainerservice.TypeFirst),
},
},
},
},
}
_, err := config.Azure.Maintenance.CreateOrUpdate(ctx, config.ResourceGroupName, *cluster.Name, "default", maintenance, nil)
if err != nil {
return nil, fmt.Errorf("failed to create maintenance configuration: %w", err)
}
return &maintenance, nil
}
type VNet struct {
name string
subnetId string
}
func getClusterVNet(ctx context.Context, mcResourceGroupName string) (VNet, error) {
pager := config.Azure.VNet.NewListPager(mcResourceGroupName, nil)
for pager.More() {
nextResult, err := pager.NextPage(ctx)
if err != nil {
return VNet{}, fmt.Errorf("failed to advance page: %w", err)
}
for _, v := range nextResult.Value {
if v == nil {
return VNet{}, fmt.Errorf("aks vnet was empty")
}
return VNet{name: *v.Name, subnetId: fmt.Sprintf("%s/subnets/%s", *v.ID, "aks-subnet")}, nil
}
}
return VNet{}, fmt.Errorf("failed to find aks vnet")
}
func collectGarbageVMSS(ctx context.Context, t *testing.T, cluster *armcontainerservice.ManagedCluster) error {
rg := *cluster.Properties.NodeResourceGroup
pager := config.Azure.VMSS.NewListPager(rg, nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
return fmt.Errorf("failed to get next page of VMSS: %w", err)
}
for _, vmss := range page.Value {
if _, ok := vmss.Tags["KEEP_VMSS"]; ok {
continue
}
// don't delete managed pools
if _, ok := vmss.Tags["aks-managed-poolName"]; ok {
continue
}
// don't delete VMSS created in the last hour. They might be currently used in tests
// extra 10 minutes is a buffer for test cleanup, clock drift and timeout adjustments
if config.Config.TestTimeout == 0 || time.Since(*vmss.Properties.TimeCreated) < config.Config.TestTimeout+10*time.Minute {
continue
}
_, err := config.Azure.VMSS.BeginDelete(ctx, rg, *vmss.Name, &armcompute.VirtualMachineScaleSetsClientBeginDeleteOptions{
ForceDeletion: to.Ptr(true),
})
if err != nil {
t.Logf("failed to delete vmss %q: %s", *vmss.Name, err)
continue
}
t.Logf("deleted garbage vmss %q", *vmss.ID)
}
}
return nil
}
func isExistingResourceGroup(ctx context.Context, resourceGroupName string) (bool, error) {
rgExistence, err := config.Azure.ResourceGroup.CheckExistence(ctx, resourceGroupName, nil)
if err != nil {
return false, fmt.Errorf("failed to get RG %q: %w", resourceGroupName, err)
}
return rgExistence.Success, nil
}
var rgOnce sync.Once
func ensureResourceGroupOnce(ctx context.Context) {
rgOnce.Do(func() {
err := ensureResourceGroup(ctx)
if err != nil {
panic(err)
}
})
}
func ensureResourceGroup(ctx context.Context) error {
rgExists, err := isExistingResourceGroup(ctx, config.ResourceGroupName)
if err != nil {
return err
}
if !rgExists {
_, err = config.Azure.ResourceGroup.CreateOrUpdate(
ctx,
config.ResourceGroupName,
armresources.ResourceGroup{
Location: to.Ptr(config.Config.Location),
Name: to.Ptr(config.ResourceGroupName),
},
nil)
if err != nil {
return fmt.Errorf("failed to create RG %q: %w", config.ResourceGroupName, err)
}
}
return nil
}