forked from wso2/api-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttproute_mapper.go
More file actions
369 lines (334 loc) · 10.4 KB
/
httproute_mapper.go
File metadata and controls
369 lines (334 loc) · 10.4 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
367
368
369
/*
* Copyright (c) 2026, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package controller
import (
"context"
"fmt"
"strings"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
apiv1 "github.com/wso2/api-platform/kubernetes/gateway-operator/api/v1alpha1"
)
const defaultKubernetesClusterDNS = "cluster.local"
func effectiveClusterDNSBase(domain string) string {
d := strings.Trim(strings.TrimSpace(domain), ".")
if d == "" {
return defaultKubernetesClusterDNS
}
return d
}
type httpRouteConfigErrorKind string
const (
httpRouteConfigErrorInvalid httpRouteConfigErrorKind = "invalid"
httpRouteConfigErrorTransient httpRouteConfigErrorKind = "transient"
)
type HTTPRouteConfigError struct {
Kind httpRouteConfigErrorKind
Err error
}
func (e *HTTPRouteConfigError) Error() string {
if e == nil || e.Err == nil {
return "httproute config error"
}
return e.Err.Error()
}
func (e *HTTPRouteConfigError) Unwrap() error {
if e == nil {
return nil
}
return e.Err
}
func newInvalidHTTPRouteConfigError(format string, args ...any) error {
return &HTTPRouteConfigError{
Kind: httpRouteConfigErrorInvalid,
Err: fmt.Errorf(format, args...),
}
}
func newTransientHTTPRouteConfigError(format string, args ...any) error {
return &HTTPRouteConfigError{
Kind: httpRouteConfigErrorTransient,
Err: fmt.Errorf(format, args...),
}
}
func IsInvalidHTTPRouteConfigError(err error) bool {
if err == nil {
return false
}
e, ok := err.(*HTTPRouteConfigError)
return ok && e.Kind == httpRouteConfigErrorInvalid
}
// IsTransientHTTPRouteConfigError reports errors that should be retried (e.g. missing ReferenceGrant, API lookup).
func IsTransientHTTPRouteConfigError(err error) bool {
if err == nil {
return false
}
e, ok := err.(*HTTPRouteConfigError)
return ok && e.Kind == httpRouteConfigErrorTransient
}
// allRESTAPIOperationMethods returns every HTTP verb modeled by APIConfigData / RestApi operations
// (used when an HTTPRoute match omits method, which is valid in Gateway API).
func allRESTAPIOperationMethods() []apiv1.OperationMethod {
return []apiv1.OperationMethod{
apiv1.OperationMethodGET,
apiv1.OperationMethodPOST,
apiv1.OperationMethodPUT,
apiv1.OperationMethodPATCH,
apiv1.OperationMethodDELETE,
apiv1.OperationMethodHEAD,
apiv1.OperationMethodOPTIONS,
}
}
// restAPIOperationMethodsForHTTPRouteMatch returns a single explicit method or all supported methods
// when the Gateway API match leaves method unset.
func restAPIOperationMethodsForHTTPRouteMatch(m gatewayv1.HTTPRouteMatch) []apiv1.OperationMethod {
if m.Method != nil {
return []apiv1.OperationMethod{apiv1.OperationMethod(*m.Method)}
}
return allRESTAPIOperationMethods()
}
// BuildAPIConfigFromHTTPRoute maps HTTPRoute rules to APIConfigData (MVP: single Service backend across rules).
// clusterDomain is the cluster DNS suffix (e.g. cluster.local or from CLUSTER_DOMAIN / gateway_api.cluster_domain).
// log may be nil (tests); when set, emits structured diagnostics for policy loading and mapping.
func BuildAPIConfigFromHTTPRoute(ctx context.Context, c client.Client, route *gatewayv1.HTTPRoute, clusterDomain string, log *zap.Logger) (*apiv1.APIConfigData, error) {
if len(route.Spec.Rules) == 0 {
return nil, newInvalidHTTPRouteConfigError("HTTPRoute has no rules")
}
if log != nil {
log.Info("build API config from HTTPRoute",
zap.Int64("generation", route.Generation),
zap.String("resourceVersion", route.ResourceVersion),
zap.Int("ruleCount", len(route.Spec.Rules)))
}
displayName := route.Name
if v := route.Annotations[AnnHTTPRouteDisplayName]; v != "" {
displayName = v
}
version := route.Annotations[AnnHTTPRouteAPIVersion]
if version == "" {
version = "v1.0"
}
// Resolve backend URL (same Service required for all rules in MVP).
backendURL, err := firstBackendURL(ctx, c, route, clusterDomain)
if err != nil {
return nil, err
}
var ops []apiv1.Operation
for ruleIdx, rule := range route.Spec.Rules {
rulePolicies, err := policiesFromHTTPRouteRuleExtensionRefs(ctx, c, route, rule, ruleIdx, log)
if err != nil {
return nil, err
}
if len(rule.Matches) == 0 {
return nil, newInvalidHTTPRouteConfigError(
"rule[%d] has no matches; add at least one rule.matches entry (optional match.method; if omitted, all API verbs GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS are emitted)",
ruleIdx,
)
}
for _, m := range rule.Matches {
pathVal := "/"
if m.Path != nil && m.Path.Value != nil {
p := strings.TrimSpace(*m.Path.Value)
if p != "" {
pathVal = p
if !strings.HasPrefix(pathVal, "/") {
pathVal = "/" + pathVal
}
}
}
methods := restAPIOperationMethodsForHTTPRouteMatch(m)
for _, method := range methods {
ops = append(ops, apiv1.Operation{
Method: method,
Path: pathVal,
Policies: copyPolicies(rulePolicies),
})
}
}
}
if len(ops) == 0 {
return nil, newInvalidHTTPRouteConfigError("no operations derived from HTTPRoute")
}
contextPath := strings.TrimSpace(route.Annotations[AnnHTTPRouteContext])
if contextPath == "" {
contextPath = "/"
} else if !strings.HasPrefix(contextPath, "/") {
contextPath = "/" + contextPath
}
apiPolicies, err := loadHTTPRouteAPIPolicies(ctx, c, route, log)
if err != nil {
return nil, err
}
spec := &apiv1.APIConfigData{
Context: contextPath,
DisplayName: displayName,
Operations: ops,
Upstream: apiv1.UpstreamConfig{
Main: apiv1.Upstream{Url: backendURL},
},
Version: version,
Policies: apiPolicies,
}
if err := resolveAPIConfigPolicyParamsValueFrom(ctx, c, route.Namespace, spec, log); err != nil {
return nil, err
}
opsWithPol := 0
for i := range spec.Operations {
if len(spec.Operations[i].Policies) > 0 {
opsWithPol++
}
}
if log != nil {
log.Info("built API config from HTTPRoute",
zap.Int("operations", len(spec.Operations)),
zap.Int("apiLevelPolicies", len(spec.Policies)),
zap.Int("operationsWithAttachedPolicies", opsWithPol),
zap.Int("operationPolicyAnnotationEntries", 0))
}
return spec, nil
}
func firstBackendURL(ctx context.Context, c client.Client, route *gatewayv1.HTTPRoute, clusterDomain string) (string, error) {
dnsBase := effectiveClusterDNSBase(clusterDomain)
ns := route.Namespace
var (
baselineSet bool
baselineSvcNS string
baselineSvc string
baselinePort int32
)
for _, rule := range route.Spec.Rules {
for _, b := range rule.BackendRefs {
if b.Kind != nil && string(*b.Kind) != "" && string(*b.Kind) != "Service" {
continue
}
if b.Group != nil && string(*b.Group) != "" {
return "", newTransientHTTPRouteConfigError(
"unsupported backendRef: core Service backends require group to be omitted or empty (got group %q)",
string(*b.Group),
)
}
svcNS := ns
if b.Namespace != nil && *b.Namespace != "" {
svcNS = string(*b.Namespace)
}
svcName := string(b.Name)
if svcName == "" {
continue
}
if err := ensureCrossNamespaceServiceReferenceGrant(ctx, c, ns, svcNS, svcName); err != nil {
return "", err
}
svc := &corev1.Service{}
key := types.NamespacedName{Namespace: svcNS, Name: svcName}
if err := c.Get(ctx, key, svc); err != nil {
return "", newTransientHTTPRouteConfigError("get backend Service %s: %w", key.String(), err)
}
portNum, err := resolveServicePort(svc, b.Port)
if err != nil {
return "", err
}
if !baselineSet {
baselineSet = true
baselineSvcNS = svcNS
baselineSvc = svcName
baselinePort = portNum
continue
}
if svcNS != baselineSvcNS || svcName != baselineSvc || portNum != baselinePort {
return "", newInvalidHTTPRouteConfigError(
"HTTPRoute backendRefs must resolve to a single Service backend (first %s/%s:%d, found %s/%s:%d)",
baselineSvcNS, baselineSvc, baselinePort, svcNS, svcName, portNum,
)
}
}
}
if baselineSet {
return fmt.Sprintf("http://%s.%s.svc.%s:%d", baselineSvc, baselineSvcNS, dnsBase, baselinePort), nil
}
return "", newInvalidHTTPRouteConfigError("no Service backendRef found on HTTPRoute")
}
func resolveServicePort(svc *corev1.Service, refPort *gatewayv1.PortNumber) (int32, error) {
ports := svc.Spec.Ports
if len(ports) == 0 {
return 0, newInvalidHTTPRouteConfigError("service %s/%s has no ports", svc.Namespace, svc.Name)
}
var want int32
if refPort != nil && *refPort > 0 {
want = int32(*refPort)
}
if want > 0 {
for _, p := range ports {
if p.Port == want {
return p.Port, nil
}
}
return 0, newInvalidHTTPRouteConfigError(
"service %s/%s has no port %d in spec.ports (backendRefs[].port must match a Service spec.ports.port)",
svc.Namespace, svc.Name, want,
)
}
if len(ports) > 1 {
return 0, newInvalidHTTPRouteConfigError(
"service %s/%s has %d ports; set backendRefs[].port to a spec.ports.port value to disambiguate",
svc.Namespace, svc.Name, len(ports),
)
}
return ports[0].Port, nil
}
func sharedPrefix(a, b string) string {
if !strings.HasPrefix(a, "/") {
a = "/" + a
}
if !strings.HasPrefix(b, "/") {
b = "/" + b
}
aSeg := splitPathSegments(a)
bSeg := splitPathSegments(b)
n := len(aSeg)
if len(bSeg) < n {
n = len(bSeg)
}
matched := 0
for i := 0; i < n; i++ {
if aSeg[i] != bSeg[i] {
break
}
matched++
}
if matched == 0 {
return "/"
}
return "/" + strings.Join(aSeg[:matched], "/")
}
func splitPathSegments(p string) []string {
p = strings.TrimSpace(p)
p = strings.TrimPrefix(p, "/")
p = strings.TrimSuffix(p, "/")
if p == "" {
return nil
}
return strings.Split(p, "/")
}
// DefaultHTTPRouteAPIHandle returns a stable handle for rest-apis when no annotation is set.
func DefaultHTTPRouteAPIHandle(route *gatewayv1.HTTPRoute) string {
if h := route.Annotations[AnnHTTPRouteAPIHandle]; h != "" {
return h
}
return strings.ReplaceAll(route.Namespace+"-"+route.Name, "/", "-")
}