-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathservice_network_manager.go
More file actions
366 lines (321 loc) · 13.5 KB
/
service_network_manager.go
File metadata and controls
366 lines (321 loc) · 13.5 KB
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
package lattice
import (
"context"
"fmt"
"golang.org/x/exp/slices"
"github.com/aws/aws-application-networking-k8s/pkg/aws/services"
lattice_runtime "github.com/aws/aws-application-networking-k8s/pkg/runtime"
"github.com/aws/aws-application-networking-k8s/pkg/utils/gwlog"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/vpclattice"
pkg_aws "github.com/aws/aws-application-networking-k8s/pkg/aws"
"github.com/aws/aws-application-networking-k8s/pkg/config"
model "github.com/aws/aws-application-networking-k8s/pkg/model/lattice"
"github.com/aws/aws-application-networking-k8s/pkg/utils"
)
//go:generate mockgen -destination service_network_manager_mock.go -package lattice github.com/aws/aws-application-networking-k8s/pkg/deploy/lattice ServiceNetworkManager
type ServiceNetworkManager interface {
UpsertVpcAssociation(ctx context.Context, snName string, sgIds []*string, additionalTags services.Tags) (string, error)
DeleteVpcAssociation(ctx context.Context, snName string) error
CreateOrUpdate(ctx context.Context, serviceNetwork *model.ServiceNetwork) (model.ServiceNetworkStatus, error)
Delete(ctx context.Context, snName string) error
}
func NewDefaultServiceNetworkManager(log gwlog.Logger, cloud pkg_aws.Cloud) *defaultServiceNetworkManager {
return &defaultServiceNetworkManager{
log: log,
cloud: cloud,
}
}
type defaultServiceNetworkManager struct {
log gwlog.Logger
cloud pkg_aws.Cloud
}
func (m *defaultServiceNetworkManager) UpsertVpcAssociation(ctx context.Context, snName string, sgIds []*string, additionalTags services.Tags) (string, error) {
sn, err := m.cloud.Lattice().FindServiceNetwork(ctx, snName)
if err != nil {
return "", err
}
snva, err := m.getActiveVpcAssociation(ctx, *sn.SvcNetwork.Id)
if err != nil {
return "", err
}
if snva != nil {
// association is active
// Check if this is a RAM-shared network by examining the service network ARN
isLocal, err := m.isLocalServiceNetwork(sn.SvcNetwork.Arn)
if err != nil {
return "", err
}
if isLocal {
// For local networks, check ownership as before
owned, err := m.cloud.TryOwn(ctx, *snva.Arn)
if err != nil {
return "", err
}
if !owned {
return "", services.NewConflictError("snva", snName,
fmt.Sprintf("Found existing vpc association not owned by controller: %s", *snva.Arn))
}
// Update if needed
_, err = m.updateServiceNetworkVpcAssociation(ctx, &sn.SvcNetwork, sgIds, snva.Id, additionalTags)
if err != nil {
return "", err
}
} else {
// For RAM-shared networks, we can't modify the association
// Just return the existing ARN and log
m.log.Infof(ctx, "Using existing VPC association for RAM-shared service network %s: %s",
snName, *snva.Arn)
}
return *snva.Arn, nil
} else {
tags := m.cloud.MergeTags(m.cloud.DefaultTags(), additionalTags)
req := vpclattice.CreateServiceNetworkVpcAssociationInput{
ServiceNetworkIdentifier: sn.SvcNetwork.Id,
VpcIdentifier: &config.VpcID,
SecurityGroupIds: sgIds,
Tags: tags,
}
resp, err := m.cloud.Lattice().CreateServiceNetworkVpcAssociationWithContext(ctx, &req)
if err != nil {
return "", err
}
switch status := aws.StringValue(resp.Status); status {
case vpclattice.ServiceNetworkVpcAssociationStatusActive:
return *resp.Arn, nil
default:
return *resp.Arn, fmt.Errorf("%w, vpc association status in %s", lattice_runtime.NewRetryError(), status)
}
}
}
// isLocalServiceNetwork determines if a service network belongs to the current AWS account
func (m *defaultServiceNetworkManager) isLocalServiceNetwork(arnStr *string) (bool, error) {
if arnStr == nil {
return false, fmt.Errorf("service network ARN is nil")
}
parsedArn, err := arn.Parse(*arnStr)
if err != nil {
return false, fmt.Errorf("failed to parse service network ARN %s: %w", *arnStr, err)
}
// Compare with controller's account
controllerAccount := m.cloud.Config().AccountId
if controllerAccount == "" {
// If controller account is not set, assume it's local (backward compatibility)
m.log.Debugf(context.Background(), "Controller account ID not set, assuming service network %s is local", *arnStr)
return true, nil
}
return parsedArn.AccountID == controllerAccount, nil
}
func (m *defaultServiceNetworkManager) DeleteVpcAssociation(ctx context.Context, snName string) error {
sn, err := m.cloud.Lattice().FindServiceNetwork(ctx, snName)
if err != nil {
return err
}
snva, err := m.getActiveVpcAssociation(ctx, *sn.SvcNetwork.Id)
if err != nil {
return err
}
if snva != nil {
// association is active
m.log.Debugf(ctx, "Disassociating ServiceNetwork %s from VPC", snName)
owned, err := m.cloud.IsArnManaged(ctx, *snva.Arn)
if err != nil {
// TODO check for vpclattice.ErrCodeAccessDeniedException or a new error type ErrorCodeNotFoundException
// when the api no longer responds with a 404 NotFoundException instead of either of the above.
// ErrorCodeNotFoundException currently not part of the golang sdk for the lattice api. This a is a distinct
// error from vpclattice.ErrCodeResourceNotFoundException.
// In a scenario that the vpc association is created by a foreign account,
// the owner account's controller cannot read the tags of this ServiceNetworkVpcAssociation,
// and AccessDeniedException is expected.
m.log.Warnf(ctx, "skipping delete vpc association, association: %s, error: %s", *snva.Arn, err)
return nil
}
if !owned {
m.log.Infof(ctx, "Association %s for %s not owned by controller, skipping deletion", *snva.Arn, snName)
return nil
}
deleteServiceNetworkVpcAssociationInput := vpclattice.DeleteServiceNetworkVpcAssociationInput{
ServiceNetworkVpcAssociationIdentifier: snva.Id,
}
resp, err := m.cloud.Lattice().DeleteServiceNetworkVpcAssociationWithContext(ctx, &deleteServiceNetworkVpcAssociationInput)
if err != nil {
m.log.Infof(ctx, "Failed to delete association %s for %s, with response %s and err %s", *snva.Arn, snName, resp, err.Error())
}
return lattice_runtime.NewRetryError()
}
return nil
}
func (m *defaultServiceNetworkManager) Delete(ctx context.Context, snName string) error {
sn, err := m.cloud.Lattice().FindServiceNetwork(ctx, snName)
if err != nil {
if services.IsNotFoundError(err) {
return nil
}
return err
}
snArn := aws.StringValue(sn.SvcNetwork.Arn)
owned, err := m.cloud.IsArnManaged(ctx, snArn)
if err != nil {
m.log.Warnf(ctx, "cannot check ownership of ServiceNetwork %s: %s, skipping deletion", snName, err)
return nil
}
if !owned {
m.log.Infof(ctx, "ServiceNetwork %s not owned by controller, skipping deletion", snName)
return nil
}
assocs, err := m.cloud.Lattice().ListServiceNetworkServiceAssociationsAsList(ctx,
&vpclattice.ListServiceNetworkServiceAssociationsInput{
ServiceNetworkIdentifier: sn.SvcNetwork.Id,
})
if err != nil {
return fmt.Errorf("failed to list service associations for ServiceNetwork %s: %w", snName, err)
}
if len(assocs) > 0 {
return fmt.Errorf("cannot delete ServiceNetwork %s: %d service association(s) still active, "+
"detach all services before deleting the Gateway", snName, len(assocs))
}
if err := m.DeleteVpcAssociation(ctx, snName); err != nil {
return err
}
_, err = m.cloud.Lattice().DeleteServiceNetworkWithContext(ctx, &vpclattice.DeleteServiceNetworkInput{
ServiceNetworkIdentifier: sn.SvcNetwork.Id,
})
if err != nil {
return err
}
m.log.Infof(ctx, "Deleted ServiceNetwork %s", snName)
return nil
}
func (m *defaultServiceNetworkManager) getActiveVpcAssociation(ctx context.Context, serviceNetworkId string) (*vpclattice.ServiceNetworkVpcAssociationSummary, error) {
vpcLatticeSess := m.cloud.Lattice()
associationStatusInput := vpclattice.ListServiceNetworkVpcAssociationsInput{
ServiceNetworkIdentifier: &serviceNetworkId,
VpcIdentifier: &config.VpcID,
}
resp, err := vpcLatticeSess.ListServiceNetworkVpcAssociationsAsList(ctx, &associationStatusInput)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, nil
}
// There can be at most one response for this
snva := resp[0]
if aws.StringValue(snva.Status) == vpclattice.ServiceNetworkVpcAssociationStatusActive {
return snva, nil
}
m.log.Debugf(ctx, "snva %s status: %s",
aws.StringValue(snva.Arn), aws.StringValue(snva.Status))
switch aws.StringValue(snva.Status) {
case vpclattice.ServiceNetworkVpcAssociationStatusActive,
vpclattice.ServiceNetworkVpcAssociationStatusDeleteFailed,
vpclattice.ServiceNetworkVpcAssociationStatusUpdateFailed:
// the resource exists
return snva, nil
case vpclattice.ServiceNetworkVpcAssociationStatusCreateFailed:
// consider it does not exist
return nil, nil
default:
// a mutation is in progress, try later
return nil, lattice_runtime.NewRetryError()
}
}
// The controller does not manage service network anymore, just having to upsert SN and SNVA for default SN setup.
// This function does not care about the association status, the caller is not supposed to wait for it.
func (m *defaultServiceNetworkManager) CreateOrUpdate(ctx context.Context, serviceNetwork *model.ServiceNetwork) (model.ServiceNetworkStatus, error) {
// check if exists
foundSnSummary, err := m.cloud.Lattice().FindServiceNetwork(ctx, serviceNetwork.Spec.Name)
if err != nil && !services.IsNotFoundError(err) {
return model.ServiceNetworkStatus{ServiceNetworkARN: "", ServiceNetworkID: ""}, err
}
var serviceNetworkId string
var serviceNetworkArn string
vpcLatticeSess := m.cloud.Lattice()
if foundSnSummary == nil {
m.log.Debugf(ctx, "Creating ServiceNetwork %s and tagging it with vpcId %s",
serviceNetwork.Spec.Name, config.VpcID)
serviceNetworkInput := vpclattice.CreateServiceNetworkInput{
Name: &serviceNetwork.Spec.Name,
Tags: m.cloud.DefaultTags(),
}
resp, err := vpcLatticeSess.CreateServiceNetworkWithContext(ctx, &serviceNetworkInput)
if err != nil {
return model.ServiceNetworkStatus{}, err
}
serviceNetworkId = aws.StringValue(resp.Id)
serviceNetworkArn = aws.StringValue(resp.Arn)
} else {
m.log.Debugf(ctx, "ServiceNetwork %s exists, checking its VPC association", serviceNetwork.Spec.Name)
serviceNetworkId = aws.StringValue(foundSnSummary.SvcNetwork.Id)
serviceNetworkArn = aws.StringValue(foundSnSummary.SvcNetwork.Arn)
snva, err := m.getActiveVpcAssociation(ctx, serviceNetworkId)
if err != nil {
return model.ServiceNetworkStatus{}, err
}
if snva != nil {
m.log.Debugf(ctx, "ServiceNetwork %s already has VPC association %s",
serviceNetwork.Spec.Name, aws.StringValue(snva.Arn))
return model.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil
}
}
if !serviceNetwork.Spec.AssociateToVPC {
m.log.Debugf(ctx, "Skipping VPC association for ServiceNetwork %s (AssociateToVPC=false)", serviceNetwork.Spec.Name)
return model.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil
}
m.log.Debugf(ctx, "Creating association between ServiceNetwork %s and VPC %s", serviceNetworkId, config.VpcID)
createServiceNetworkVpcAssociationInput := vpclattice.CreateServiceNetworkVpcAssociationInput{
ServiceNetworkIdentifier: &serviceNetworkId,
VpcIdentifier: &config.VpcID,
Tags: m.cloud.DefaultTags(),
}
_, err = vpcLatticeSess.CreateServiceNetworkVpcAssociationWithContext(ctx, &createServiceNetworkVpcAssociationInput)
if err != nil {
return model.ServiceNetworkStatus{}, err
}
return model.ServiceNetworkStatus{ServiceNetworkARN: serviceNetworkArn, ServiceNetworkID: serviceNetworkId}, nil
}
func (m *defaultServiceNetworkManager) updateServiceNetworkVpcAssociation(ctx context.Context, existingSN *vpclattice.ServiceNetworkSummary, sgIds []*string, existingSnvaId *string, additionalTags services.Tags) (model.ServiceNetworkStatus, error) {
snva, err := m.cloud.Lattice().GetServiceNetworkVpcAssociationWithContext(ctx, &vpclattice.GetServiceNetworkVpcAssociationInput{
ServiceNetworkVpcAssociationIdentifier: existingSnvaId,
})
if err != nil {
return model.ServiceNetworkStatus{}, err
}
err = m.cloud.Tagging().UpdateTags(ctx, aws.StringValue(snva.Arn), additionalTags, nil)
if err != nil {
return model.ServiceNetworkStatus{}, fmt.Errorf("failed to update tags for service network vpc association %s: %w", aws.StringValue(snva.Id), err)
}
sgIdsEqual := securityGroupIdsEqual(sgIds, snva.SecurityGroupIds)
if sgIdsEqual {
// desiredSN's security group ids are same with snva's security group ids, don't need to update
return model.ServiceNetworkStatus{
ServiceNetworkID: *existingSN.Id,
ServiceNetworkARN: *existingSN.Arn,
SnvaSecurityGroupIds: snva.SecurityGroupIds,
}, nil
}
updateSnvaResp, err := m.cloud.Lattice().UpdateServiceNetworkVpcAssociationWithContext(ctx, &vpclattice.UpdateServiceNetworkVpcAssociationInput{
ServiceNetworkVpcAssociationIdentifier: existingSnvaId,
SecurityGroupIds: sgIds,
})
if err != nil {
return model.ServiceNetworkStatus{}, err
}
if *updateSnvaResp.Status == vpclattice.ServiceNetworkVpcAssociationStatusActive {
return model.ServiceNetworkStatus{
ServiceNetworkID: *existingSN.Id,
ServiceNetworkARN: *existingSN.Arn,
SnvaSecurityGroupIds: updateSnvaResp.SecurityGroupIds,
}, nil
} else {
return model.ServiceNetworkStatus{}, fmt.Errorf("%w, update snva status: %s", lattice_runtime.NewRetryError(), *updateSnvaResp.Status)
}
}
func securityGroupIdsEqual(arr1, arr2 []*string) bool {
ids1 := utils.SliceMap(arr1, aws.StringValue)
slices.Sort(ids1)
ids2 := utils.SliceMap(arr2, aws.StringValue)
slices.Sort(ids2)
return slices.Equal(ids1, ids2)
}