Debian Codegraph @

e2e/main_test.go

raw symbols SCIP
1 /*
2 Copyright 2024 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16 package e2e
17
18 import (
19 "bytes"
20 "context"
21 "flag"
22 "fmt"
23 "io"
24 "log"
25 "os"
26 "path"
27 "testing"
28 "text/template"
29 "time"
30
31 appsv1api "k8s.io/api/apps/v1"
32 corev1 "k8s.io/api/core/v1"
33 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
34 "k8s.io/apimachinery/pkg/labels"
35 "k8s.io/apimachinery/pkg/runtime/schema"
36 "k8s.io/client-go/kubernetes"
37 "k8s.io/client-go/kubernetes/scheme"
38 "sigs.k8s.io/controller-runtime/pkg/client"
39 "sigs.k8s.io/e2e-framework/klient/k8s"
40 "sigs.k8s.io/e2e-framework/klient/wait"
41 "sigs.k8s.io/e2e-framework/klient/wait/conditions"
42 "sigs.k8s.io/e2e-framework/pkg/env"
43 "sigs.k8s.io/e2e-framework/pkg/envconf"
44 "sigs.k8s.io/e2e-framework/pkg/envfuncs"
45 "sigs.k8s.io/e2e-framework/support/kind"
46 )
47
48 var (
49 testenv env.Environment
50 agentImage = flag.String("agent-image", "", "The proxy agent's docker image.")
51 serverImage = flag.String("server-image", "", "The proxy server's docker image.")
52 kindImage = flag.String("kind-image", "kindest/node", "Image to use for kind nodes.")
53 connectionMode = flag.String("mode", "grpc", "Connection mode to use during e2e tests.")
54 )
55
56 func TestMain(m *testing.M) {
57 flag.Parse()
58 if *agentImage == "" {
59 log.Fatalf("must provide agent image with -agent-image")
60 }
61 if *serverImage == "" {
62 log.Fatalf("must provide server image with -server-image")
63 }
64
65 scheme.AddToScheme(scheme.Scheme)
66
67 testenv = env.New()
68 kindClusterName := "kind-test"
69 kindCluster := kind.NewCluster(kindClusterName).WithOpts(kind.WithImage(*kindImage))
70
71 testenv.Setup(
72 envfuncs.CreateClusterWithConfig(kindCluster, kindClusterName, "templates/kind.config"),
73 envfuncs.LoadImageToCluster(kindClusterName, *agentImage),
74 envfuncs.LoadImageToCluster(kindClusterName, *serverImage),
75 renderAndApplyManifests,
76 )
77
78 testenv.Finish(envfuncs.DestroyCluster(kindClusterName))
79
80 os.Exit(testenv.Run(m))
81 }
82
83 // renderTemplate renders a template from e2e/templates into a kubernetes object.
84 // Template paths are relative to e2e/templates.
85 func renderTemplate(file string, params any) (client.Object, *schema.GroupVersionKind, error) {
86 b := &bytes.Buffer{}
87
88 tmp, err := template.ParseFiles(path.Join("templates/", file))
89 if err != nil {
90 return nil, nil, fmt.Errorf("could not parse template %v: %w", file, err)
91 }
92
93 err = tmp.Execute(b, params)
94 if err != nil {
95 return nil, nil, fmt.Errorf("could not execute template %v: %w", file, err)
96 }
97
98 decoder := scheme.Codecs.UniversalDeserializer()
99
100 obj, gvk, err := decoder.Decode(b.Bytes(), nil, nil)
101 if err != nil {
102 return nil, nil, fmt.Errorf("could not decode rendered yaml into kubernetes object: %w", err)
103 }
104
105 return obj.(client.Object), gvk, nil
106 }
107
108 type CLIFlag struct {
109 Flag string
110 Value string
111 EmptyValue bool
112 }
113
114 type DeploymentConfig struct {
115 Replicas int
116 Image string
117 Args []CLIFlag
118 }
119
120 func renderAndApplyManifests(ctx context.Context, cfg *envconf.Config) (context.Context, error) {
121 client := cfg.Client()
122
123 // Render agent RBAC and Service templates.
124 agentServiceAccount, _, err := renderTemplate("agent/serviceaccount.yaml", struct{}{})
125 if err != nil {
126 return nil, err
127 }
128 agentClusterRole, _, err := renderTemplate("agent/clusterrole.yaml", struct{}{})
129 if err != nil {
130 return nil, err
131 }
132 agentClusterRoleBinding, _, err := renderTemplate("agent/clusterrolebinding.yaml", struct{}{})
133 if err != nil {
134 return ctx, err
135 }
136
137 // Submit agent RBAC templates to k8s.
138 err = client.Resources().Create(ctx, agentServiceAccount)
139 if err != nil {
140 return ctx, err
141 }
142 err = client.Resources().Create(ctx, agentClusterRole)
143 if err != nil {
144 return ctx, err
145 }
146 err = client.Resources().Create(ctx, agentClusterRoleBinding)
147 if err != nil {
148 return ctx, err
149 }
150
151 // Render server RBAC and Service templates.
152 serverClusterRoleBinding, _, err := renderTemplate("server/clusterrolebinding.yaml", struct{}{})
153 if err != nil {
154 return ctx, err
155 }
156 serverService, _, err := renderTemplate("server/service.yaml", struct{}{})
157 if err != nil {
158 return ctx, err
159 }
160
161 // Submit server templates to k8s.
162 err = client.Resources().Create(ctx, serverClusterRoleBinding)
163 if err != nil {
164 return ctx, err
165 }
166 err = client.Resources().Create(ctx, serverService)
167 if err != nil {
168 return ctx, err
169 }
170
171 return ctx, nil
172 }
173
174 func createDeployment(obj client.Object) func(context.Context, *testing.T, *envconf.Config) context.Context {
175 return func(ctx context.Context, t *testing.T, cfg *envconf.Config) context.Context {
176 deployment, ok := obj.(*appsv1api.Deployment)
177 if !ok {
178 t.Fatalf("object %q is not a deployment", obj.GetName())
179 }
180
181 err := cfg.Client().Resources(deployment.Namespace).Create(ctx, deployment)
182 if err != nil {
183 t.Fatalf("could not create deployment %q: %v", deployment.Name, err)
184 }
185
186 newDeployment := &appsv1api.Deployment{}
187 err = cfg.Client().Resources(deployment.Namespace).Get(ctx, deployment.Name, deployment.Namespace, newDeployment)
188 if err != nil {
189 t.Fatalf("could not get deployment %q after creation: %v", deployment.Name, err)
190 }
191
192 return ctx
193 }
194 }
195
196 func deleteDeployment(obj client.Object) func(context.Context, *testing.T, *envconf.Config) context.Context {
197 return func(ctx context.Context, t *testing.T, cfg *envconf.Config) context.Context {
198 deployment, ok := obj.(*appsv1api.Deployment)
199 if !ok {
200 t.Fatalf("object %q is not a deployment", obj.GetName())
201 }
202
203 k8sClient := kubernetes.NewForConfigOrDie(cfg.Client().RESTConfig())
204 pods, err := k8sClient.CoreV1().Pods(deployment.Namespace).List(ctx, metav1.ListOptions{LabelSelector: labels.FormatLabels(deployment.Spec.Selector.MatchLabels)})
205 if err != nil {
206 t.Fatalf("could not get pods for deployment %q: %v", deployment.Name, err)
207 }
208
209 cfg.Client().Resources(deployment.Namespace).Delete(ctx, deployment)
210
211 err = wait.For(
212 conditions.New(cfg.Client().Resources(deployment.Namespace)).ResourcesDeleted(pods),
213 wait.WithTimeout(60*time.Second),
214 wait.WithInterval(5*time.Second),
215 )
216 if err != nil {
217 pods, err := k8sClient.CoreV1().Pods(deployment.Namespace).List(ctx, metav1.ListOptions{LabelSelector: labels.FormatLabels(deployment.Spec.Selector.MatchLabels)})
218 if err != nil {
219 t.Fatalf("could not get pods for deployment %q: %v", deployment.Name, err)
220 }
221
222 for _, pod := range pods.Items {
223 logs, err := dumpPodLogs(ctx, k8sClient, pod.Namespace, pod.Name)
224 if err != nil {
225 t.Fatalf("could not dump logs for pod %q: %v", pod.Name, err)
226 }
227 t.Errorf("logs for pod %q: %v", pod.Name, logs)
228 }
229 t.Fatalf("waiting for deletion of pods for deployment %q failed, dumped pod logs", deployment.Name)
230 }
231
232 return ctx
233 }
234 }
235
236 func waitForDeployment(obj client.Object) func(context.Context, *testing.T, *envconf.Config) context.Context {
237 return func(ctx context.Context, t *testing.T, cfg *envconf.Config) context.Context {
238 deployment, ok := obj.(*appsv1api.Deployment)
239 if !ok {
240 t.Fatalf("object %q is not a deployment", obj.GetName())
241 }
242
243 k8sClient := kubernetes.NewForConfigOrDie(cfg.Client().RESTConfig())
244 err := wait.For(
245 conditions.New(cfg.Client().Resources(deployment.Namespace)).DeploymentAvailable(deployment.Name, deployment.Namespace),
246 wait.WithTimeout(120*time.Second),
247 wait.WithInterval(5*time.Second),
248 )
249 if err != nil {
250 pods, err := k8sClient.CoreV1().Pods(deployment.Namespace).List(ctx, metav1.ListOptions{LabelSelector: labels.FormatLabels(deployment.Spec.Selector.MatchLabels)})
251 if err != nil {
252 t.Fatalf("could not get pods for deployment %q: %v", deployment.Name, err)
253 }
254
255 for _, pod := range pods.Items {
256 if isPodReady(&pod) {
257 continue
258 }
259
260 logs, err := dumpPodLogs(ctx, k8sClient, pod.Namespace, pod.Name)
261 if err != nil {
262 t.Fatalf("could not dump logs for pod %q: %v", pod.Name, err)
263 }
264 t.Errorf("logs for pod %q: %v", pod.Name, logs)
265 }
266 t.Fatalf("waiting for deployment %q failed, dumped pod logs", deployment.Name)
267 }
268
269 return ctx
270 }
271 }
272
273 func isPodReady(pod *corev1.Pod) bool {
274 for _, condition := range pod.Status.Conditions {
275 if condition.Type == corev1.PodReady {
276 return condition.Status == corev1.ConditionTrue
277 }
278 }
279 return false
280 }
281
282 func dumpPodLogs(ctx context.Context, k8sClient kubernetes.Interface, namespace, name string) (string, error) {
283 req := k8sClient.CoreV1().Pods(namespace).GetLogs(name, &corev1.PodLogOptions{})
284 podLogs, err := req.Stream(ctx)
285 if err != nil {
286 return "", fmt.Errorf("could not stream logs for pod %q in namespace %q: %w", name, namespace, err)
287 }
288 defer podLogs.Close()
289
290 b, err := io.ReadAll(podLogs)
291 if err != nil {
292 return "", fmt.Errorf("could not read logs for pod %q in namespace %q from stream: %w", name, namespace, err)
293 }
294
295 return string(b), nil
296 }
297
298 func scaleDeployment(obj client.Object, replicas int) func(context.Context, *testing.T, *envconf.Config) context.Context {
299 return func(ctx context.Context, t *testing.T, cfg *envconf.Config) context.Context {
300 deployment, ok := obj.(*appsv1api.Deployment)
301 if !ok {
302 t.Fatalf("provided object is not a deployment")
303 }
304
305 err := cfg.Client().Resources().Get(ctx, deployment.Name, deployment.Namespace, deployment)
306 if err != nil {
307 t.Fatalf("could not get Deployment to update (name: %q, namespace: %q): %v", deployment.Name, deployment.Namespace, err)
308 }
309
310 newReplicas := int32(replicas)
311 deployment.Spec.Replicas = &newReplicas
312
313 client := cfg.Client()
314 err = client.Resources().Update(ctx, deployment)
315 if err != nil {
316 t.Fatalf("could not update Deployment replicas: %v", err)
317 }
318
319 err = wait.For(
320 conditions.New(cfg.Client().Resources(deployment.Namespace)).ResourceScaled(deployment, func(obj k8s.Object) int32 {
321 deployment, ok := obj.(*appsv1api.Deployment)
322 if !ok {
323 t.Fatalf("provided object is not a deployment")
324 }
325
326 return deployment.Status.AvailableReplicas
327 }, int32(replicas)),
328 wait.WithTimeout(60*time.Second),
329 wait.WithInterval(5*time.Second),
330 )
331 if err != nil {
332 t.Fatalf("waiting for deployment %q to scale failed", deployment.Name)
333 }
334
335 return ctx
336 }
337 }