-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathops_kongroute.go
More file actions
296 lines (261 loc) · 9.8 KB
/
ops_kongroute.go
File metadata and controls
296 lines (261 loc) · 9.8 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
package ops
import (
"context"
"fmt"
sdkkonnectgo "github.com/Kong/sdk-konnect-go"
sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
"github.com/samber/lo"
commonv1alpha1 "github.com/kong/kong-operator/v2/api/common/v1alpha1"
configurationv1alpha1 "github.com/kong/kong-operator/v2/api/configuration/v1alpha1"
)
func createRoute(
ctx context.Context,
sdk sdkkonnectgo.RoutesSDK,
route *configurationv1alpha1.KongRoute,
) error {
cpID := route.GetControlPlaneID()
if cpID == "" {
return CantPerformOperationWithoutControlPlaneIDError{Entity: route, Op: CreateOp}
}
if route.Spec.Name == nil || *route.Spec.Name == "" {
routeID := string(route.GetUID())
resp, err := sdk.UpsertRoute(ctx, sdkkonnectops.UpsertRouteRequest{
ControlPlaneID: cpID,
RouteID: routeID,
Route: kongRouteToSDKRouteInput(route),
})
if errWrap := wrapErrIfKonnectOpFailed(err, CreateOp, route); errWrap != nil {
return errWrap
}
if resp == nil || resp.Route == nil || resp.Route.RouteJSON == nil || resp.Route.RouteJSON.ID == nil {
return fmt.Errorf("failed creating %s: %w", route.GetTypeName(), ErrNilResponse)
}
route.SetKonnectID(*resp.Route.RouteJSON.ID)
return nil
}
resp, err := sdk.CreateRoute(ctx, cpID, kongRouteToSDKRouteInput(route))
if errWrap := wrapErrIfKonnectOpFailed(err, CreateOp, route); errWrap != nil {
return errWrap
}
if resp == nil || resp.Route == nil || resp.Route.RouteJSON.ID == nil {
return fmt.Errorf("failed creating %s: %w", route.GetTypeName(), ErrNilResponse)
}
route.SetKonnectID(*resp.Route.RouteJSON.ID)
return nil
}
// updateRoute updates the Konnect Route entity.
// It is assumed that provided KongRoute has Konnect ID set in status.
// It returns an error if the KongRoute does not have a ControlPlaneRef or
// if the operation fails.
func updateRoute(
ctx context.Context,
sdk sdkkonnectgo.RoutesSDK,
route *configurationv1alpha1.KongRoute,
) error {
cpID := route.GetControlPlaneID()
if cpID == "" {
return CantPerformOperationWithoutControlPlaneIDError{Entity: route, Op: UpdateOp}
}
id := route.GetKonnectStatus().GetKonnectID()
_, err := sdk.UpsertRoute(ctx, sdkkonnectops.UpsertRouteRequest{
ControlPlaneID: cpID,
RouteID: id,
Route: kongRouteToSDKRouteInput(route),
})
if errWrap := wrapErrIfKonnectOpFailed(err, UpdateOp, route); errWrap != nil {
return errWrap
}
return nil
}
// deleteRoute deletes a KongRoute in Konnect.
// It is assumed that provided KongRoute has Konnect ID set in status.
// It returns an error if the operation fails.
func deleteRoute(
ctx context.Context,
sdk sdkkonnectgo.RoutesSDK,
route *configurationv1alpha1.KongRoute,
) error {
id := route.GetKonnectStatus().GetKonnectID()
_, err := sdk.DeleteRoute(ctx, route.Status.Konnect.ControlPlaneID, id)
if errWrap := wrapErrIfKonnectOpFailed(err, DeleteOp, route); errWrap != nil {
return handleDeleteError(ctx, err, route)
}
return nil
}
// adoptRoute adopts an existing route with the ID
// given in the spec.adopt.konnect.id of the KongRoute.
// It returns an error if the operation fails.
func adoptRoute(
ctx context.Context,
sdk sdkkonnectgo.RoutesSDK,
route *configurationv1alpha1.KongRoute,
) error {
cpID := route.GetControlPlaneID()
if cpID == "" {
return KonnectEntityAdoptionMissingControlPlaneIDError{}
}
adoptOptions := route.Spec.Adopt
konnectID := adoptOptions.Konnect.ID
resp, err := sdk.GetRoute(ctx, konnectID, cpID)
if err != nil {
return KonnectEntityAdoptionFetchError{
KonnectID: konnectID,
Err: err,
}
}
// KO only supports routes with "RouteJSON" type now.
if resp.Route.Type != sdkkonnectcomp.RouteTypeRouteJSON {
return KonnectEntityAdoptionRouteTypeNotSupportedError{
RouteType: resp.Route.Type,
}
}
if resp.Route.RouteJSON == nil {
return fmt.Errorf("route content in RouteJSON is empty")
}
// Check if the service ID matches.
if route.Spec.ServiceRef != nil {
// if the KongRoute has a service reference, check if the referenced service matches.
if route.Status.Konnect.ServiceID == "" {
return fmt.Errorf("failed to adopt: service reference not resolved")
}
if resp.Route.RouteJSON.Service == nil ||
resp.Route.RouteJSON.Service.ID == nil {
return fmt.Errorf("failed to adopt: existing route does not have service reference")
}
if *resp.Route.RouteJSON.Service.ID != route.Status.Konnect.ServiceID {
return KonnectEntityAdoptionReferenceServiceIDMismatchError{}
}
} else if resp.Route.RouteJSON.Service != nil {
// if the KongRoute does not have a service reference, the existing route should not have a reference service.
return fmt.Errorf("failed to adopt: KongRoute has no service reference but existing route has service reference")
}
uidTag, hasUIDTag := findUIDTag(resp.Route.RouteJSON.Tags)
if hasUIDTag && extractUIDFromTag(uidTag) != string(route.UID) {
return KonnectEntityAdoptionUIDTagConflictError{
KonnectID: konnectID,
ActualUIDTag: extractUIDFromTag(uidTag),
}
}
adoptMode := adoptOptions.Mode
if adoptMode == "" {
adoptMode = commonv1alpha1.AdoptModeOverride
}
switch adoptMode {
case commonv1alpha1.AdoptModeOverride:
routeCopy := route.DeepCopy()
routeCopy.SetKonnectID(konnectID)
if err = updateRoute(ctx, sdk, routeCopy); err != nil {
return err
}
case commonv1alpha1.AdoptModeMatch:
if !routeJSONMatch(resp.Route.RouteJSON, route) {
return KonnectEntityAdoptionNotMatchError{
KonnectID: konnectID,
}
}
default:
return fmt.Errorf("failed to adopt: adopt mode %q not supported", adoptMode)
}
route.SetKonnectID(konnectID)
return nil
}
func kongRouteToSDKRouteInput(
route *configurationv1alpha1.KongRoute,
) sdkkonnectcomp.Route {
r := sdkkonnectcomp.Route{
RouteJSON: &sdkkonnectcomp.RouteJSON{
Destinations: route.Spec.Destinations,
Headers: route.Spec.Headers,
Hosts: route.Spec.Hosts,
HTTPSRedirectStatusCode: route.Spec.HTTPSRedirectStatusCode,
Methods: route.Spec.Methods,
Name: route.Spec.Name,
PathHandling: route.Spec.PathHandling,
Paths: route.Spec.Paths,
PreserveHost: route.Spec.PreserveHost,
Protocols: route.Spec.Protocols,
RegexPriority: route.Spec.RegexPriority,
RequestBuffering: route.Spec.RequestBuffering,
ResponseBuffering: route.Spec.ResponseBuffering,
Snis: route.Spec.Snis,
Sources: route.Spec.Sources,
StripPath: route.Spec.StripPath,
Tags: GenerateTagsForObject(route, route.Spec.Tags...),
},
}
if route.Status.Konnect != nil && route.Status.Konnect.ServiceID != "" {
r.RouteJSON.Service = &sdkkonnectcomp.RouteJSONService{
ID: new(route.Status.Konnect.ServiceID),
}
}
return r
}
// getKongRouteForUID returns the Konnect ID of the KongRoute
// that matches the UID of the provided KongRoute.
func getKongRouteForUID(
ctx context.Context,
sdk sdkkonnectgo.RoutesSDK,
r *configurationv1alpha1.KongRoute,
) (string, error) {
reqList := sdkkonnectops.ListRouteRequest{
// NOTE: only filter on object's UID.
// Other fields like name might have changed in the meantime but that's OK.
// Those will be enforced via subsequent updates.
Tags: new(UIDLabelForObject(r)),
ControlPlaneID: r.GetControlPlaneID(),
}
resp, err := sdk.ListRoute(ctx, reqList)
if err != nil {
return "", fmt.Errorf("failed listing %s: %w", r.GetTypeName(), err)
}
if resp == nil || resp.Object == nil {
return "", fmt.Errorf("failed listing %s: %w", r.GetTypeName(), ErrNilResponse)
}
_, id, err := getMatchingEntryFromListResponseData(
sliceToEntityWithIDPtrSlice(
lo.Map(resp.Object.Data, func(route sdkkonnectcomp.Route, _ int) sdkkonnectcomp.RouteJSON {
return *route.RouteJSON
}),
), r)
return id, err
}
// routeHeadersMatch compares two header matches in the two routes.
func routeHeadersMatch(headers1, headers2 map[string][]string) bool {
// If they are both `nil`, they are equal.
if headers1 == nil && headers2 == nil {
return true
}
// If one of them is nil but not both, or they have different number of elements, they are not equal.
if headers1 == nil || headers2 == nil || len(headers1) != len(headers2) {
return false
}
// Check each header name in one map inside another.
// If all the headers can be found, and the values are the same, they are equal
// (Given that they have the same number of headers).
// If any header is not found, or the matching values differ, they are not equal.
for k1, v1 := range headers1 {
v2, ok := headers2[k1]
if !ok || !lo.ElementsMatch(v1, v2) {
return false
}
}
return true
}
// routeJSONMatch compares a Konnect in RouteJSON type with the spec of a KongRoute.
func routeJSONMatch(routeJSON *sdkkonnectcomp.RouteJSON, route *configurationv1alpha1.KongRoute) bool {
routeJSONInput := kongRouteToSDKRouteInput(route).RouteJSON
return equalWithDefault(routeJSON.Name, routeJSONInput.Name, "") &&
lo.ElementsMatch(routeJSON.Hosts, routeJSONInput.Hosts) &&
lo.ElementsMatch(routeJSON.Paths, routeJSONInput.Paths) &&
lo.ElementsMatch(routeJSON.Methods, routeJSONInput.Methods) &&
routeHeadersMatch(routeJSON.Headers, routeJSONInput.Headers) &&
equalWithDefault(routeJSON.RegexPriority, routeJSONInput.RegexPriority, 0) &&
equalWithDefault(routeJSON.HTTPSRedirectStatusCode, routeJSONInput.HTTPSRedirectStatusCode,
sdkkonnectcomp.HTTPSRedirectStatusCodeFourHundredAndTwentySix) &&
lo.ElementsMatch(routeJSON.Snis, routeJSONInput.Snis) &&
equalWithDefault(routeJSON.PathHandling, routeJSONInput.PathHandling,
sdkkonnectcomp.PathHandlingV0) &&
lo.ElementsMatch(routeJSON.Sources, routeJSONInput.Sources) &&
lo.ElementsMatch(routeJSON.Destinations, routeJSONInput.Destinations)
}