-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
deployment.go
639 lines (562 loc) · 16.2 KB
/
deployment.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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/*
Copyright 2017 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 framework
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// EchoService name of the deployment for the echo app
const EchoService = "echo"
// SlowEchoService name of the deployment for the echo app
const SlowEchoService = "slow-echo"
// HTTPBunService name of the deployment for the httpbun app
const HTTPBunService = "httpbun"
// NipService name of external service using nip.io
const NIPService = "external-nip"
// HTTPBunImage is the default image that is used to deploy HTTPBun with the framework
var HTTPBunImage = os.Getenv("HTTPBUN_IMAGE")
// EchoImage is the default image to be used by the echo service
const EchoImage = "registry.k8s.io/ingress-nginx/e2e-test-echo:v1.0.1@sha256:1cec65aa768720290d05d65ab1c297ca46b39930e56bc9488259f9114fcd30e2" //#nosec G101
// TODO: change all Deployment functions to use these options
// in order to reduce complexity and have a unified API across the
// framework
type deploymentOptions struct {
name string
namespace string
image string
replicas int
svcAnnotations map[string]string
}
// WithDeploymentNamespace allows configuring the deployment's namespace
func WithDeploymentNamespace(n string) func(*deploymentOptions) {
return func(o *deploymentOptions) {
o.namespace = n
}
}
// WithSvcTopologyAnnotations create svc with topology mode sets to auto
func WithSvcTopologyAnnotations() func(*deploymentOptions) {
return func(o *deploymentOptions) {
o.svcAnnotations = map[string]string{
corev1.AnnotationTopologyMode: "auto",
}
}
}
// WithDeploymentName allows configuring the deployment's names
func WithDeploymentName(n string) func(*deploymentOptions) {
return func(o *deploymentOptions) {
o.name = n
}
}
// WithDeploymentReplicas allows configuring the deployment's replicas count
func WithDeploymentReplicas(r int) func(*deploymentOptions) {
return func(o *deploymentOptions) {
o.replicas = r
}
}
func WithName(n string) func(*deploymentOptions) {
return func(o *deploymentOptions) {
o.name = n
}
}
// WithImage allows configuring the image for the deployments
func WithImage(i string) func(*deploymentOptions) {
return func(o *deploymentOptions) {
o.image = i
}
}
// NewEchoDeployment creates a new single replica deployment of the echo server image in a particular namespace
func (f *Framework) NewEchoDeployment(opts ...func(*deploymentOptions)) {
options := &deploymentOptions{
namespace: f.Namespace,
name: EchoService,
replicas: 1,
image: EchoImage,
}
for _, o := range opts {
o(options)
}
f.EnsureDeployment(newDeployment(
options.name,
options.namespace,
options.image,
80,
int32(options.replicas),
nil, nil, nil,
[]corev1.VolumeMount{},
[]corev1.Volume{},
true,
))
f.EnsureService(&corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: options.name,
Namespace: options.namespace,
Annotations: options.svcAnnotations,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "http",
Port: 80,
TargetPort: intstr.FromInt(80),
Protocol: corev1.ProtocolTCP,
},
},
Selector: map[string]string{
"app": options.name,
},
},
})
err := WaitForEndpoints(
f.KubeClientSet,
DefaultTimeout,
options.name,
options.namespace,
options.replicas,
)
assert.Nil(ginkgo.GinkgoT(), err, "waiting for endpoints to become ready")
}
// BuildNipHost used to generate a nip host for DNS resolving
func BuildNIPHost(ip string) string {
return fmt.Sprintf("%s.nip.io", ip)
}
// GetNipHost used to generate a nip host for external DNS resolving
// for the instance deployed by the framework
func (f *Framework) GetNIPHost() string {
return BuildNIPHost(f.HTTPBunIP)
}
// BuildNIPExternalNameService used to generate a service pointing to nip.io to
// help resolve to an IP address
func BuildNIPExternalNameService(f *Framework, ip, portName string) *corev1.Service {
return &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: NIPService,
Namespace: f.Namespace,
},
Spec: corev1.ServiceSpec{
ExternalName: BuildNIPHost(ip),
Type: corev1.ServiceTypeExternalName,
Ports: []corev1.ServicePort{
{
Name: portName,
Port: 80,
TargetPort: intstr.FromInt(80),
Protocol: "TCP",
},
},
},
}
}
// NewHttpbunDeployment creates a new single replica deployment of the httpbun
// server image in a particular namespace we return the ip for testing purposes
func (f *Framework) NewHttpbunDeployment(opts ...func(*deploymentOptions)) string {
options := &deploymentOptions{
namespace: f.Namespace,
name: HTTPBunService,
replicas: 1,
image: HTTPBunImage,
}
for _, o := range opts {
o(options)
}
// Create the HTTPBun Deployment
f.EnsureDeployment(newDeployment(
options.name,
options.namespace,
options.image,
80,
int32(options.replicas),
nil, nil,
// Required to get hostname information
[]corev1.EnvVar{
{
Name: "HTTPBUN_INFO_ENABLED",
Value: "1",
},
},
[]corev1.VolumeMount{},
[]corev1.Volume{},
true,
))
// Create a service pointing to deployment
f.EnsureService(&corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: options.name,
Namespace: options.namespace,
Annotations: options.svcAnnotations,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "http",
Port: 80,
TargetPort: intstr.FromInt(80),
Protocol: corev1.ProtocolTCP,
},
},
Selector: map[string]string{
"app": options.name,
},
},
})
// Wait for deployment to become available
err := WaitForEndpoints(
f.KubeClientSet,
DefaultTimeout,
options.name,
options.namespace,
options.replicas,
)
assert.Nil(ginkgo.GinkgoT(), err, "waiting for endpoints to become ready")
// Get cluster ip for HTTPBun to be used in tests
e, err := f.KubeClientSet.
CoreV1().
Endpoints(f.Namespace).
Get(context.TODO(), HTTPBunService, metav1.GetOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "failed to get httpbun endpoint")
return e.Subsets[0].Addresses[0].IP
}
// NewSlowEchoDeployment creates a new deployment of the slow echo server image in a particular namespace.
func (f *Framework) NewSlowEchoDeployment() {
cfg := `#
events {
worker_connections 1024;
multi_accept on;
}
http {
default_type 'text/plain';
client_max_body_size 0;
server {
access_log on;
access_log /dev/stdout;
listen 80;
location / {
content_by_lua_block {
ngx.print("ok")
}
}
location ~ ^/sleep/(?<sleepTime>[0-9]+)$ {
content_by_lua_block {
ngx.sleep(ngx.var.sleepTime)
ngx.print("ok after " .. ngx.var.sleepTime .. " seconds")
}
}
}
}
`
f.NGINXWithConfigDeployment(SlowEchoService, cfg)
}
func (f *Framework) GetNginxBaseImage() string {
nginxBaseImage := os.Getenv("NGINX_BASE_IMAGE")
if nginxBaseImage == "" {
assert.NotEmpty(ginkgo.GinkgoT(), errors.New("NGINX_BASE_IMAGE not defined"), "NGINX_BASE_IMAGE not defined")
}
return nginxBaseImage
}
// NGINXDeployment creates a new simple NGINX Deployment using NGINX base image
// and passing the desired configuration
func (f *Framework) NGINXDeployment(name, cfg string, waitendpoint bool) {
cfgMap := map[string]string{
"nginx.conf": cfg,
}
_, err := f.KubeClientSet.
CoreV1().
ConfigMaps(f.Namespace).
Create(context.TODO(), &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: f.Namespace,
},
Data: cfgMap,
}, metav1.CreateOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "creating configmap")
deployment := newDeployment(name, f.Namespace, f.GetNginxBaseImage(), 80, 1,
nil, nil, nil,
[]corev1.VolumeMount{
{
Name: name,
MountPath: "/etc/nginx/nginx.conf",
SubPath: "nginx.conf",
ReadOnly: true,
},
},
[]corev1.Volume{
{
Name: name,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: name,
},
},
},
},
}, true,
)
f.EnsureDeployment(deployment)
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: f.Namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "http",
Port: 80,
TargetPort: intstr.FromInt(80),
Protocol: corev1.ProtocolTCP,
},
},
Selector: map[string]string{
"app": name,
},
},
}
f.EnsureService(service)
if waitendpoint {
err = WaitForEndpoints(f.KubeClientSet, DefaultTimeout, name, f.Namespace, 1)
assert.Nil(ginkgo.GinkgoT(), err, "waiting for endpoints to become ready")
}
}
// NGINXWithConfigDeployment creates an NGINX deployment using a configmap containing the nginx.conf configuration
func (f *Framework) NGINXWithConfigDeployment(name, cfg string) {
f.NGINXDeployment(name, cfg, true)
}
// NewGRPCBinDeployment creates a new deployment of the
// moul/grpcbin image for GRPC tests
func (f *Framework) NewGRPCBinDeployment() {
name := "grpcbin"
probe := &corev1.Probe{
InitialDelaySeconds: 1,
PeriodSeconds: 1,
SuccessThreshold: 1,
TimeoutSeconds: 1,
ProbeHandler: corev1.ProbeHandler{
TCPSocket: &corev1.TCPSocketAction{
Port: intstr.FromInt(9000),
},
},
}
sel := map[string]string{
"app": name,
}
f.EnsureDeployment(&appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: f.Namespace,
},
Spec: appsv1.DeploymentSpec{
Replicas: NewInt32(1),
Selector: &metav1.LabelSelector{
MatchLabels: sel,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: sel,
},
Spec: corev1.PodSpec{
TerminationGracePeriodSeconds: NewInt64(0),
Containers: []corev1.Container{
{
Name: name,
Image: "moul/grpcbin",
Env: []corev1.EnvVar{},
Ports: []corev1.ContainerPort{
{
Name: "insecure",
ContainerPort: 9000,
Protocol: corev1.ProtocolTCP,
},
{
Name: "secure",
ContainerPort: 9001,
Protocol: corev1.ProtocolTCP,
},
},
ReadinessProbe: probe,
LivenessProbe: probe,
},
},
},
},
},
})
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: f.Namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "insecure",
Port: 9000,
TargetPort: intstr.FromInt(9000),
Protocol: corev1.ProtocolTCP,
},
{
Name: "secure",
Port: 9001,
TargetPort: intstr.FromInt(9001),
Protocol: corev1.ProtocolTCP,
},
},
Selector: sel,
},
}
f.EnsureService(service)
err := WaitForEndpoints(f.KubeClientSet, DefaultTimeout, name, f.Namespace, 1)
assert.Nil(ginkgo.GinkgoT(), err, "waiting for endpoints to become ready")
}
func newDeployment(name, namespace, image string, port int32, replicas int32, command []string, args []string, env []corev1.EnvVar,
volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool,
) *appsv1.Deployment {
probe := &corev1.Probe{
InitialDelaySeconds: 2,
PeriodSeconds: 1,
SuccessThreshold: 1,
TimeoutSeconds: 2,
FailureThreshold: 6,
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Port: intstr.FromString("http"),
Path: "/",
},
},
}
d := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: appsv1.DeploymentSpec{
Replicas: NewInt32(replicas),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": name,
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": name,
},
},
Spec: corev1.PodSpec{
TerminationGracePeriodSeconds: NewInt64(0),
Containers: []corev1.Container{
{
Name: name,
Image: image,
Env: []corev1.EnvVar{},
Ports: []corev1.ContainerPort{
{
Name: "http",
ContainerPort: port,
},
},
VolumeMounts: volumeMounts,
},
},
Volumes: volumes,
},
},
},
}
if setProbe {
d.Spec.Template.Spec.Containers[0].ReadinessProbe = probe
d.Spec.Template.Spec.Containers[0].LivenessProbe = probe
}
if len(command) > 0 {
d.Spec.Template.Spec.Containers[0].Command = command
}
if len(args) > 0 {
d.Spec.Template.Spec.Containers[0].Args = args
}
if len(env) > 0 {
d.Spec.Template.Spec.Containers[0].Env = env
}
return d
}
func (f *Framework) NewDeployment(name, image string, port, replicas int32) {
f.NewDeploymentWithOpts(name, image, port, replicas, nil, nil, nil, nil, nil, true)
}
// NewDeployment creates a new deployment in a particular namespace.
func (f *Framework) NewDeploymentWithOpts(name, image string, port, replicas int32, command, args []string, env []corev1.EnvVar, volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) {
deployment := newDeployment(name, f.Namespace, image, port, replicas, command, args, env, volumeMounts, volumes, setProbe)
f.EnsureDeployment(deployment)
service := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: f.Namespace,
},
Spec: corev1.ServiceSpec{
Ports: []corev1.ServicePort{
{
Name: "http",
Port: 80,
TargetPort: intstr.FromInt(int(port)),
Protocol: corev1.ProtocolTCP,
},
},
Selector: map[string]string{
"app": name,
},
},
}
f.EnsureService(service)
err := WaitForEndpoints(f.KubeClientSet, DefaultTimeout, name, f.Namespace, int(replicas))
assert.Nil(ginkgo.GinkgoT(), err, "waiting for endpoints to become ready")
}
// DeleteDeployment deletes a deployment with a particular name and waits for the pods to be deleted
func (f *Framework) DeleteDeployment(name string) error {
d, err := f.KubeClientSet.AppsV1().Deployments(f.Namespace).Get(context.TODO(), name, metav1.GetOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "getting deployment")
grace := int64(0)
err = f.KubeClientSet.AppsV1().Deployments(f.Namespace).Delete(context.TODO(), name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
assert.Nil(ginkgo.GinkgoT(), err, "deleting deployment")
return waitForPodsDeleted(f.KubeClientSet, 2*time.Minute, f.Namespace, &metav1.ListOptions{
LabelSelector: labelSelectorToString(d.Spec.Selector.MatchLabels),
})
}
// ScaleDeploymentToZero scales a deployment with a particular name and waits for the pods to be deleted
func (f *Framework) ScaleDeploymentToZero(name string) {
d, err := f.KubeClientSet.AppsV1().Deployments(f.Namespace).Get(context.TODO(), name, metav1.GetOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "getting deployment")
assert.NotNil(ginkgo.GinkgoT(), d, "expected a deployment but none returned")
d.Spec.Replicas = NewInt32(0)
d, err = f.KubeClientSet.AppsV1().Deployments(f.Namespace).Update(context.TODO(), d, metav1.UpdateOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "getting deployment")
assert.NotNil(ginkgo.GinkgoT(), d, "expected a deployment but none returned")
err = WaitForEndpoints(f.KubeClientSet, DefaultTimeout, name, f.Namespace, 0)
assert.Nil(ginkgo.GinkgoT(), err, "waiting for no endpoints")
}
// UpdateIngressControllerDeployment updates the ingress-nginx deployment
func (f *Framework) UpdateIngressControllerDeployment(fn func(deployment *appsv1.Deployment) error) error {
err := UpdateDeployment(f.KubeClientSet, f.Namespace, "nginx-ingress-controller", 1, fn)
if err != nil {
return err
}
return f.updateIngressNGINXPod()
}