forked from kubernetes-sigs/gateway-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apply.go
280 lines (231 loc) · 9.54 KB
/
apply.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
/*
Copyright 2022 The Kubernetes Authors.
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 kubernetes
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/require"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/gateway-api/apis/v1beta1"
"sigs.k8s.io/gateway-api/conformance"
"sigs.k8s.io/gateway-api/conformance/utils/config"
)
// Applier prepares manifests depending on the available options and applies
// them to the Kubernetes cluster.
type Applier struct {
NamespaceLabels map[string]string
// ValidUniqueListenerPorts maps each listener port of each Gateway in the
// manifests to a valid, unique port. There must be as many
// ValidUniqueListenerPorts as there are listeners in the set of manifests.
// For example, given two Gateways, each with 2 listeners, there should be
// four ValidUniqueListenerPorts.
// If empty or nil, ports are not modified.
ValidUniqueListenerPorts []v1beta1.PortNumber
// GatewayClass will be used as the spec.gatewayClassName when applying Gateway resources
GatewayClass string
// ControllerName will be used as the spec.controllerName when applying GatewayClass resources
ControllerName string
}
// prepareGateway adjusts both listener ports and the gatewayClassName. It
// returns an index pointing to the next valid listener port.
func (a Applier) prepareGateway(t *testing.T, uObj *unstructured.Unstructured, portIndex int) int {
err := unstructured.SetNestedField(uObj.Object, a.GatewayClass, "spec", "gatewayClassName")
require.NoErrorf(t, err, "error setting `spec.gatewayClassName` on %s Gateway resource", uObj.GetName())
if len(a.ValidUniqueListenerPorts) > 0 {
listeners, _, err := unstructured.NestedSlice(uObj.Object, "spec", "listeners")
require.NoErrorf(t, err, "error getting `spec.listeners` on %s Gateway resource", uObj.GetName())
for i, uListener := range listeners {
require.Less(t, portIndex, len(a.ValidUniqueListenerPorts), "not enough unassigned valid ports for `spec.listeners[%d]` on %s Gateway resource", i, uObj.GetName())
listener, ok := uListener.(map[string]interface{})
require.Truef(t, ok, "unexpected type at `spec.listeners[%d]` on %s Gateway resource", i, uObj.GetName())
nextPort := a.ValidUniqueListenerPorts[portIndex]
err = unstructured.SetNestedField(listener, int64(nextPort), "port")
require.NoErrorf(t, err, "error setting `spec.listeners[%d].port` on %s Gateway resource", i, uObj.GetName())
portIndex++
listeners[i] = listener
}
err = unstructured.SetNestedSlice(uObj.Object, listeners, "spec", "listeners")
require.NoErrorf(t, err, "error setting `spec.listeners` on %s Gateway resource", uObj.GetName())
}
return portIndex
}
// prepareGatewayClass adjust the spec.controllerName on the resource
func (a Applier) prepareGatewayClass(t *testing.T, uObj *unstructured.Unstructured) {
err := unstructured.SetNestedField(uObj.Object, a.ControllerName, "spec", "controllerName")
require.NoErrorf(t, err, "error setting `spec.controllerName` on %s GatewayClass resource", uObj.GetName())
}
// prepareNamespace adjusts the Namespace labels.
func prepareNamespace(t *testing.T, uObj *unstructured.Unstructured, namespaceLabels map[string]string) {
labels, _, err := unstructured.NestedStringMap(uObj.Object, "metadata", "labels")
require.NoErrorf(t, err, "error getting labels on Namespace %s", uObj.GetName())
for k, v := range namespaceLabels {
if labels == nil {
labels = map[string]string{}
}
labels[k] = v
}
// SetNestedStringMap converts nil to an empty map
if labels != nil {
err = unstructured.SetNestedStringMap(uObj.Object, labels, "metadata", "labels")
}
require.NoErrorf(t, err, "error setting labels on Namespace %s", uObj.GetName())
}
// prepareResources uses the options from an Applier to tweak resources given by
// a set of manifests.
func (a Applier) prepareResources(t *testing.T, decoder *yaml.YAMLOrJSONDecoder) ([]unstructured.Unstructured, error) {
var resources []unstructured.Unstructured
// portIndex is incremented for each listener we see. For a manifest file
// with 2 gateways, each with 2 listeners, it will be incremented 4 times.
portIndex := 0
for {
uObj := unstructured.Unstructured{}
if err := decoder.Decode(&uObj); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, err
}
if len(uObj.Object) == 0 {
continue
}
if uObj.GetKind() == "GatewayClass" {
a.prepareGatewayClass(t, &uObj)
}
if uObj.GetKind() == "Gateway" {
portIndex = a.prepareGateway(t, &uObj, portIndex)
}
if uObj.GetKind() == "Namespace" && uObj.GetObjectKind().GroupVersionKind().Group == "" {
prepareNamespace(t, &uObj, a.NamespaceLabels)
}
resources = append(resources, uObj)
}
return resources, nil
}
func (a Applier) MustApplyObjectsWithCleanup(t *testing.T, c client.Client, timeoutConfig config.TimeoutConfig, resources []client.Object, cleanup bool) {
for _, resource := range resources {
resource := resource
ctx, cancel := context.WithTimeout(context.Background(), timeoutConfig.CreateTimeout)
defer cancel()
t.Logf("Creating %s %s", resource.GetName(), resource.GetObjectKind().GroupVersionKind().Kind)
err := c.Create(ctx, resource)
if err != nil {
if !apierrors.IsAlreadyExists(err) {
require.NoError(t, err, "error creating resource")
}
}
if cleanup {
t.Cleanup(func() {
ctx, cancel = context.WithTimeout(context.Background(), timeoutConfig.DeleteTimeout)
defer cancel()
t.Logf("Deleting %s %s", resource.GetName(), resource.GetObjectKind().GroupVersionKind().Kind)
err = c.Delete(ctx, resource)
require.NoErrorf(t, err, "error deleting resource")
})
}
}
}
// MustApplyWithCleanup creates or updates Kubernetes resources defined with the
// provided YAML file and registers a cleanup function for resources it created.
// Note that this does not remove resources that already existed in the cluster.
func (a Applier) MustApplyWithCleanup(t *testing.T, c client.Client, timeoutConfig config.TimeoutConfig, location string, cleanup bool) {
data, err := getContentsFromPathOrURL(location, timeoutConfig)
require.NoError(t, err)
decoder := yaml.NewYAMLOrJSONDecoder(data, 4096)
resources, err := a.prepareResources(t, decoder)
if err != nil {
t.Logf("manifest: %s", data.String())
require.NoErrorf(t, err, "error parsing manifest")
}
for i := range resources {
uObj := &resources[i]
ctx, cancel := context.WithTimeout(context.Background(), timeoutConfig.CreateTimeout)
defer cancel()
namespacedName := types.NamespacedName{Namespace: uObj.GetNamespace(), Name: uObj.GetName()}
fetchedObj := uObj.DeepCopy()
err := c.Get(ctx, namespacedName, fetchedObj)
if err != nil {
if !apierrors.IsNotFound(err) {
require.NoErrorf(t, err, "error getting resource")
}
t.Logf("Creating %s %s", uObj.GetName(), uObj.GetKind())
err = c.Create(ctx, uObj)
require.NoErrorf(t, err, "error creating resource")
if cleanup {
t.Cleanup(func() {
ctx, cancel = context.WithTimeout(context.Background(), timeoutConfig.DeleteTimeout)
defer cancel()
t.Logf("Deleting %s %s", uObj.GetName(), uObj.GetKind())
err = c.Delete(ctx, uObj)
require.NoErrorf(t, err, "error deleting resource")
})
}
continue
}
uObj.SetResourceVersion(fetchedObj.GetResourceVersion())
t.Logf("Updating %s %s", uObj.GetName(), uObj.GetKind())
err = c.Update(ctx, uObj)
if cleanup {
t.Cleanup(func() {
ctx, cancel = context.WithTimeout(context.Background(), timeoutConfig.DeleteTimeout)
defer cancel()
t.Logf("Deleting %s %s", uObj.GetName(), uObj.GetKind())
err = c.Delete(ctx, uObj)
require.NoErrorf(t, err, "error deleting resource")
})
}
require.NoErrorf(t, err, "error updating resource")
}
}
// getContentsFromPathOrURL takes a string that can either be a local file
// path or an https:// URL to YAML manifests and provides the contents.
func getContentsFromPathOrURL(location string, timeoutConfig config.TimeoutConfig) (*bytes.Buffer, error) {
if strings.HasPrefix(location, "http://") {
return nil, fmt.Errorf("data can't be retrieved from %s: http is not supported, use https", location)
} else if strings.HasPrefix(location, "https://") {
ctx, cancel := context.WithTimeout(context.Background(), timeoutConfig.ManifestFetchTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, location, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
manifests := new(bytes.Buffer)
count, err := manifests.ReadFrom(resp.Body)
if err != nil {
return nil, err
}
if resp.ContentLength != -1 && count != resp.ContentLength {
return nil, fmt.Errorf("received %d bytes from %s, expected %d", count, location, resp.ContentLength)
}
return manifests, nil
}
b, err := conformance.Manifests.ReadFile(location)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}