-
Notifications
You must be signed in to change notification settings - Fork 197
/
check.go
1206 lines (1020 loc) · 34.5 KB
/
check.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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020-2021 Authors of Cilium
//
// 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 check
import (
"bytes"
"context"
"fmt"
"io"
"strings"
"time"
"github.com/cilium/cilium-cli/connectivity/filters"
"github.com/cilium/cilium-cli/defaults"
"github.com/cilium/cilium-cli/internal/k8s"
"github.com/cilium/cilium-cli/internal/utils"
"github.com/cilium/cilium/api/v1/flow"
"github.com/cilium/cilium/api/v1/observer"
ciliumv2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
hubprinter "github.com/cilium/hubble/pkg/printer"
"github.com/golang/protobuf/ptypes"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
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"
)
const (
ClientDeploymentName = "client"
echoSameNodeDeploymentName = "echo-same-node"
echoOtherNodeDeploymentName = "echo-other-node"
kindEchoName = "echo"
kindClientName = "client"
)
var serviceLabels = map[string]string{
"kind": kindEchoName,
}
func newService(name string, selector map[string]string, labels map[string]string, portName string, port int) *corev1.Service {
return &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: labels,
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeNodePort,
Ports: []corev1.ServicePort{
{Name: name, Port: int32(port)},
},
Selector: selector,
},
}
}
type deploymentParameters struct {
Name string
Kind string
Image string
Replicas int
Port int
Command []string
Affinity *corev1.Affinity
ReadinessProbe *corev1.Probe
}
func newDeployment(p deploymentParameters) *appsv1.Deployment {
if p.Replicas == 0 {
p.Replicas = 1
}
replicas32 := int32(p.Replicas)
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: p.Name,
Labels: map[string]string{
"name": p.Name,
"kind": p.Kind,
},
},
Spec: appsv1.DeploymentSpec{
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: p.Name,
Labels: map[string]string{
"name": p.Name,
"kind": p.Kind,
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: p.Name,
Env: []corev1.EnvVar{
{Name: "PORT", Value: fmt.Sprintf("%d", p.Port)},
},
Ports: []corev1.ContainerPort{
{ContainerPort: int32(p.Port)},
},
Image: p.Image,
ImagePullPolicy: corev1.PullIfNotPresent,
Command: p.Command,
ReadinessProbe: p.ReadinessProbe,
},
},
Affinity: p.Affinity,
},
},
Replicas: &replicas32,
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"name": p.Name,
"kind": p.Kind,
},
},
},
}
}
func newLocalReadinessProbe(port int, path string) *corev1.Probe {
return &corev1.Probe{
Handler: corev1.Handler{
HTTPGet: &corev1.HTTPGetAction{
Path: path,
Port: intstr.FromInt(port),
Scheme: corev1.URISchemeHTTP,
},
},
TimeoutSeconds: int32(2),
SuccessThreshold: int32(1),
PeriodSeconds: int32(1),
InitialDelaySeconds: int32(1),
FailureThreshold: int32(3),
}
}
type k8sConnectivityImplementation interface {
GetService(ctx context.Context, namespace, service string, opts metav1.GetOptions) (*corev1.Service, error)
CreateService(ctx context.Context, namespace string, service *corev1.Service, opts metav1.CreateOptions) (*corev1.Service, error)
DeleteService(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error
DeleteDeployment(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error
CreateDeployment(ctx context.Context, namespace string, deployment *appsv1.Deployment, opts metav1.CreateOptions) (*appsv1.Deployment, error)
GetDeployment(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*appsv1.Deployment, error)
GetDaemonSet(ctx context.Context, namespace, name string, options metav1.GetOptions) (*appsv1.DaemonSet, error)
DeploymentIsReady(ctx context.Context, namespace, deployment string) error
DeleteNamespace(ctx context.Context, namespace string, opts metav1.DeleteOptions) error
CreateNamespace(ctx context.Context, namespace string, opts metav1.CreateOptions) (*corev1.Namespace, error)
GetNamespace(ctx context.Context, namespace string, options metav1.GetOptions) (*corev1.Namespace, error)
ListPods(ctx context.Context, namespace string, options metav1.ListOptions) (*corev1.PodList, error)
ListServices(ctx context.Context, namespace string, options metav1.ListOptions) (*corev1.ServiceList, error)
GetCiliumEndpoint(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*ciliumv2.CiliumEndpoint, error)
ExecInPod(ctx context.Context, namespace, pod, container string, command []string) (bytes.Buffer, error)
ExecInPodWithStderr(ctx context.Context, namespace, pod, container string, command []string) (bytes.Buffer, bytes.Buffer, error)
ClusterName() (name string)
}
// PodContext is a pod acting as a peer in a connectivity test
type PodContext struct {
// K8sClient is the Kubernetes client of the cluster this pod is
// running in
K8sClient k8sConnectivityImplementation
// Pod is the Kubernetes Pod resource
Pod *corev1.Pod
}
// Name returns the absolute name of the pod
func (p PodContext) Name() string {
return p.Pod.Namespace + "/" + p.Pod.Name
}
// Address returns the network address of the pod
func (p PodContext) Address() string {
return p.Pod.Status.PodIP
}
// ServiceContext is a service acting as a peer in a connectivity test
type ServiceContext struct {
// Service is the Kubernetes service resource
Service *corev1.Service
}
// Name returns the absolute name of the service
func (s ServiceContext) Name() string {
return s.Service.Namespace + "/" + s.Service.Name
}
// Address returns the network address of the service
func (s ServiceContext) Address() string {
return s.Service.Name
}
// NetworkEndpointContext is a network endpoint acting as a peer in a connectivity test
type NetworkEndpointContext struct {
CustomName string
// Peer is the network address
Peer string
}
// Name is the absolute name of the network endpoint
func (n NetworkEndpointContext) Name() string {
if n.CustomName != "" {
return n.CustomName
}
return n.Peer
}
// Address it the network address of the network endpoint
func (n NetworkEndpointContext) Address() string {
return n.Peer
}
// TestContext is the context a test uses to interact with the test framework
type TestContext interface {
// EchoPods returns a map of all deployed echo pods
EchoPods() map[string]PodContext
// ClientPods returns a map of all deployed client pods
ClientPods() map[string]PodContext
// EchoServices returns a map of all deployed echo services
EchoServices() map[string]ServiceContext
// Log is used to log a status update
Log(format string, a ...interface{})
// Header logs a header to segment tests
Header(format string, a ...interface{})
// HubbleClient returns the Hubble client to retrieve flow logs
HubbleClient() observer.ObserverClient
// PrintFlows returns true if flow logs should be printed
PrintFlows() bool
// FlowSettleSleepDuration is the duration to wait before collecting flows
FlowSettleSleepDuration() time.Duration
// PostTestSleepDuration is the duration to sleep after each test
PostTestSleepDuration() time.Duration
// Report is called to report the outcome of a test
Report(r TestResult)
}
// TestRun is the state of an individual test run
type TestRun struct {
// name is the name of the test being run
name string
// verboseName is the name of the test including the name of the peers
verboseName string
// context is the test context of the framework
context TestContext
// src is the peer used as the source (client)
src TestPeer
// dst is the peer used as the destination (server)
dst TestPeer
// flows is a map of all flow logs, indexed by pod name
flows map[string]*flowsSet
// started is the timestamp the test started
started time.Time
// failures is the number of failures encountered in this test run
failures int
// warnings is the number of warnings encountered in this test run
warnings int
// flowsSettled is true once flows have been given time to settle so they can be collected
flowsSettled bool
}
// NewTestRun creates a new test run
func NewTestRun(name string, c TestContext, src, dst TestPeer) *TestRun {
c.Header("🔌 [%s] Testing %s -> %s...", name, src.Name(), dst.Name())
return &TestRun{
name: name,
verboseName: name + ": " + src.Name() + " -> " + dst.Name(),
context: c,
src: src,
dst: dst,
started: time.Now(),
flows: map[string]*flowsSet{},
}
}
// Failure must be called when a failure is detected performing the test
func (t *TestRun) Failure(format string, a ...interface{}) {
t.context.Log("❌ "+format, a...)
t.failures++
}
// Warning must be called when a warning is detected performing the test
func (t *TestRun) Warning(format string, a ...interface{}) {
t.context.Log("⚠️ "+format, a...)
t.warnings++
}
func (t *TestRun) printFlows(pod string, f *flowsSet) {
if f == nil {
t.context.Log("📄 No flows recorded for pod %s", pod)
return
}
t.context.Log("📄 Flow logs of pod %s:", pod)
printer := hubprinter.New(hubprinter.Compact())
defer printer.Close()
for _, flow := range f.flows {
if err := printer.WriteProtoFlow(flow); err != nil {
t.context.Log("Unable to print flow: %s", err)
}
}
}
func (t *TestRun) settleFlows(ctx context.Context) error {
if t.flowsSettled {
return nil
}
select {
case <-time.After(t.context.FlowSettleSleepDuration()):
case <-ctx.Done():
return fmt.Errorf("flow settling interrupted: %w", ctx.Err())
}
t.flowsSettled = true
return nil
}
// ValidateFlows retrieves the flow pods of the specified pod and validates
// that all filters find a match. On failure, t.Failure() is called.
func (t *TestRun) ValidateFlows(ctx context.Context, pod, podIP string, filterPairs []filters.Pair) {
hubbleClient := t.context.HubbleClient()
if hubbleClient == nil {
return
}
if err := t.settleFlows(ctx); err != nil {
return
}
flows, ok := t.flows[pod]
if !ok {
w := utils.NewWaitObserver(ctx, utils.WaitParameters{
Timeout: defaults.FlowWaitTimeout,
RetryInterval: defaults.FlowRetryInterval,
Log: func(err error, wait string) {
t.context.Log("⌛ Waiting (%s) for flows: %s", wait, err)
}})
defer w.Cancel()
var err error
retry:
flows, err = getFlows(ctx, hubbleClient, t.started.Add(-2*time.Second), pod, podIP)
if err != nil || flows == nil || len(flows.flows) == 0 {
if err == nil {
err = fmt.Errorf("no flows returned")
}
if err := w.Retry(err); err != nil {
t.Failure("Unable to retrieve flows of pod %q: %s", pod, err)
return
}
goto retry
}
t.flows[pod] = flows
}
var goodLog []string
for _, p := range filterPairs {
if flows.Contains(p.Filter) != p.Expect {
for _, g := range goodLog {
t.context.Log(g)
}
goodLog = []string{}
msgSuffix := "found"
if p.Expect {
msgSuffix = "not found"
}
t.Failure(fmt.Sprintf("%s %s %s for pod %s", p.Msg, p.Filter.String(), msgSuffix, pod))
} else {
msgSuffix := "not found"
if p.Expect {
msgSuffix = "found"
}
msg := fmt.Sprintf("%s %s for pod %s", p.Msg, msgSuffix, pod)
goodLog = append(goodLog, "✅ "+msg)
}
}
}
// End is called at the end of a test run to signal completion. It must be
// called for both successful and failed test runs. It will log a summary and
// print flow logs if necessary.
func (t *TestRun) End() {
if t.context.PrintFlows() || t.failures > 0 || t.warnings > 0 {
for name, flows := range t.flows {
t.printFlows(name, flows)
}
}
prefix := "✅"
if t.failures > 0 {
prefix = "❌"
} else if t.warnings > 0 {
prefix = "⚠️ "
}
t.context.Log("%s [%s] %s (%s) -> %s (%s)",
prefix, t.name,
t.src.Name(), t.src.Address(),
t.dst.Name(), t.dst.Address())
if duration := t.context.PostTestSleepDuration(); duration != time.Duration(0) {
time.Sleep(duration)
}
t.context.Report(TestResult{
Name: t.verboseName,
Failures: t.failures,
Warnings: t.warnings,
})
}
// TestPeer is the abstraction used for all peer types (pods, services, IPs,
// DNS names) used for connectivity testing
type TestPeer interface {
// Name must return the absolute name of the peer
Name() string
// Address must return the network address of the peer. This can be a
// DNS name or an IP address.
Address() string
}
// ConnectivityTest is the interface to implement for all connectivity tests
type ConnectivityTest interface {
// Name must return the name of the test
Name() string
// Run is called to run the connectivity test
Run(ctx context.Context, c TestContext)
}
type TestResult struct {
Name string
Failures int
Warnings int
}
func (t TestResult) String() string {
switch {
case t.Failures > 0:
return "❌ " + t.Name
case t.Warnings > 0:
return "⚠️ " + t.Name
default:
return "✅ " + t.Name
}
}
type TestResults map[string]TestResult
func (t TestResults) Warnings() (warnings int) {
for _, result := range t {
if result.Warnings > 0 {
warnings++
}
}
return
}
func (t TestResults) Failed() (failed int) {
for _, result := range t {
if result.Failures > 0 {
failed++
}
}
return
}
type K8sConnectivityCheck struct {
client k8sConnectivityImplementation
ciliumNamespace string
hubbleClient observer.ObserverClient
params Parameters
clients *deploymentClients
echoPods map[string]PodContext
clientPods map[string]PodContext
echoServices map[string]ServiceContext
results TestResults
}
func NewK8sConnectivityCheck(client k8sConnectivityImplementation, p Parameters) (*K8sConnectivityCheck, error) {
if err := p.validate(); err != nil {
return nil, err
}
k := &K8sConnectivityCheck{
client: client,
ciliumNamespace: "kube-system",
params: p,
}
return k, nil
}
func (k *K8sConnectivityCheck) enableHubbleClient(ctx context.Context) error {
dialCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
c, err := grpc.DialContext(dialCtx, k.params.HubbleServer, grpc.WithInsecure())
if err != nil {
return err
}
k.hubbleClient = observer.NewObserverClient(c)
status, err := k.hubbleClient.ServerStatus(ctx, &observer.ServerStatusRequest{})
if err != nil {
k.Log("⚠️ Unable to contact Hubble Relay: %s", err)
k.Log("⚠️ Did you enable and expose Hubble + Relay?")
k.Log("ℹ️ You can export Relay with a port-forward: kubectl port-forward -n kube-system deployment/hubble-relay 4245:4245")
k.Log("ℹ️ Disabling Hubble telescope and flow validation...")
k.hubbleClient = nil
k.params.Hubble = false
if k.params.FlowValidation == FlowValidationModeStrict {
k.Log("❌ In --flow-validation=strict mode, Hubble must be available to validate flows")
return fmt.Errorf("hubble is not available: %w", err)
}
} else {
k.Log("ℹ️ Hubble is OK, flows: %d/%d", status.NumFlows, status.MaxFlows)
}
return nil
}
type flowsSet struct {
flows []*observer.GetFlowsResponse
}
func getFlows(ctx context.Context, hubbleClient observer.ObserverClient, since time.Time, pod, podIP string) (*flowsSet, error) {
set := &flowsSet{}
if hubbleClient == nil {
return set, nil
}
sinceTimestamp, err := ptypes.TimestampProto(since)
if err != nil {
return nil, fmt.Errorf("invalid since value %s: %s", since, err)
}
// The filter is liberal, it includes any flow that:
// - source or destination IP matches pod IP
// - source or destination pod name matches pod name
filter := []*flow.FlowFilter{
{SourceIp: []string{podIP}},
{SourcePod: []string{pod}},
{DestinationIp: []string{podIP}},
{DestinationPod: []string{pod}},
}
request := &observer.GetFlowsRequest{
Whitelist: filter,
Since: sinceTimestamp,
}
b, err := hubbleClient.GetFlows(ctx, request)
if err != nil {
return nil, err
}
for {
res, err := b.Recv()
switch err {
case io.EOF, context.Canceled:
return set, nil
case nil:
default:
if status.Code(err) == codes.Canceled {
return set, nil
}
return nil, err
}
switch res.GetResponseTypes().(type) {
case *observer.GetFlowsResponse_Flow:
set.flows = append(set.flows, res)
}
}
}
func (f *flowsSet) Contains(filter filters.FlowFilterImplementation) bool {
if f == nil {
return false
}
for _, res := range f.flows {
if filter.Match(res.GetFlow()) {
return true
}
}
return false
}
func (k *K8sConnectivityCheck) Validate(pod string, f *flowsSet, filterPairs []filters.Pair) (success bool) {
for _, p := range filterPairs {
if f.Contains(p.Filter) != p.Expect {
k.Log("❌ %s in pod %s", p.Msg, pod)
success = false
}
}
return
}
func (k *K8sConnectivityCheck) Print(pod string, f *flowsSet) {
if f == nil {
k.Log("📄 No flows recorded for pod %s", pod)
return
}
k.Log("📄 Flow logs of pod %s:", pod)
printer := hubprinter.New(hubprinter.Compact())
defer printer.Close()
for _, flow := range f.flows {
if err := printer.WriteProtoFlow(flow); err != nil {
k.Log("Unable to print flow: %s", err)
}
}
}
const (
FlowValidationModeDisabled = "disabled"
FlowValidationModeWarning = "warning"
FlowValidationModeStrict = "strict"
)
type Parameters struct {
CiliumNamespace string
TestNamespace string
SingleNode bool
PrintFlows bool
ForceDeploy bool
Hubble bool
HubbleServer string
MultiCluster string
Tests []string
PostTestSleepDuration time.Duration
FlowSettleSleepDuration time.Duration
FlowValidation string
Writer io.Writer
}
func (p Parameters) ciliumEndpointTimeout() time.Duration {
return 5 * time.Minute
}
func (p Parameters) podReadyTimeout() time.Duration {
return 5 * time.Minute
}
func (p Parameters) serviceReadyTimeout() time.Duration {
return 5 * time.Minute
}
func (p Parameters) validate() error {
switch p.FlowValidation {
case FlowValidationModeDisabled, FlowValidationModeWarning, FlowValidationModeStrict:
default:
return fmt.Errorf("invalid flow validation mode %q", p.FlowValidation)
}
return nil
}
func (p Parameters) testEnabled(test string) bool {
if len(p.Tests) == 0 {
return true
}
numAllow := 0
numDeny := 0
for _, p := range p.Tests {
result := true
if p[0] == '!' {
numDeny++
p = p[1:]
result = false
} else {
numAllow++
}
if p == test {
return result
}
}
if numDeny == 0 {
return false
}
if numAllow > 0 {
return false
}
return true
}
func (k *K8sConnectivityCheck) deleteDeployments(ctx context.Context, client k8sConnectivityImplementation) error {
k.Log("🔥 [%s] Deleting connectivity check deployments...", client.ClusterName())
client.DeleteDeployment(ctx, k.params.TestNamespace, echoSameNodeDeploymentName, metav1.DeleteOptions{})
client.DeleteDeployment(ctx, k.params.TestNamespace, echoOtherNodeDeploymentName, metav1.DeleteOptions{})
client.DeleteDeployment(ctx, k.params.TestNamespace, ClientDeploymentName, metav1.DeleteOptions{})
client.DeleteService(ctx, k.params.TestNamespace, echoSameNodeDeploymentName, metav1.DeleteOptions{})
client.DeleteService(ctx, k.params.TestNamespace, echoOtherNodeDeploymentName, metav1.DeleteOptions{})
client.DeleteNamespace(ctx, k.params.TestNamespace, metav1.DeleteOptions{})
_, err := client.GetNamespace(ctx, k.params.TestNamespace, metav1.GetOptions{})
if err == nil {
k.Log("⌛ [%s] Waiting for namespace %s to disappear", client.ClusterName(), k.params.TestNamespace)
for err == nil {
time.Sleep(time.Second)
_, err = client.GetNamespace(ctx, k.params.TestNamespace, metav1.GetOptions{})
}
}
return nil
}
func (k *K8sConnectivityCheck) deploymentList() (srcList []string, dstList []string) {
srcList = []string{ClientDeploymentName, echoSameNodeDeploymentName}
if k.params.MultiCluster != "" || !k.params.SingleNode {
dstList = append(dstList, echoOtherNodeDeploymentName)
}
return srcList, dstList
}
type deploymentClients struct {
dstInOtherCluster bool
src k8sConnectivityImplementation
dst k8sConnectivityImplementation
}
func (d *deploymentClients) clients() []k8sConnectivityImplementation {
if d.dstInOtherCluster {
return []k8sConnectivityImplementation{d.src, d.dst}
}
return []k8sConnectivityImplementation{d.src}
}
func (k *K8sConnectivityCheck) initClients(ctx context.Context) (*deploymentClients, error) {
c := &deploymentClients{
src: k.client,
dst: k.client,
}
// In single-cluster environment, automatically detect a single-node
// environment so we can skip deploying tests which depend on multiple
// nodes
if k.params.MultiCluster == "" {
daemonSet, err := k.client.GetDaemonSet(ctx, k.params.CiliumNamespace, defaults.AgentDaemonSetName, metav1.GetOptions{})
if err != nil {
k.Log("❌ Unable to determine status of Cilium DaemonSet. Run \"cilium status\" for more details")
return nil, fmt.Errorf("unable to determine status of Cilium DaemonSet: %w", err)
}
if daemonSet.Status.DesiredNumberScheduled == 1 && !k.params.SingleNode {
k.Log("ℹ️ Single node environment detected, enabling single node connectivity test")
k.params.SingleNode = true
}
} else {
dst, err := k8s.NewClient(k.params.MultiCluster, "")
if err != nil {
return nil, fmt.Errorf("unable to create Kubernetes client for remote cluster %q: %w", k.params.MultiCluster, err)
}
c.dst = dst
c.dstInOtherCluster = true
}
return c, nil
}
func (k *K8sConnectivityCheck) deploy(ctx context.Context) error {
if k.params.ForceDeploy {
if err := k.deleteDeployments(ctx, k.clients.src); err != nil {
return err
}
}
_, err := k.clients.src.GetNamespace(ctx, k.params.TestNamespace, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Creating namespace for connectivity check...", k.clients.src.ClusterName())
_, err = k.clients.src.CreateNamespace(ctx, k.params.TestNamespace, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("unable to create namespace %s: %s", k.params.TestNamespace, err)
}
}
if k.params.MultiCluster != "" {
if k.params.ForceDeploy {
if err := k.deleteDeployments(ctx, k.clients.dst); err != nil {
return err
}
}
_, err = k.clients.dst.GetNamespace(ctx, k.params.TestNamespace, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Creating namespace for connectivity check...", k.clients.dst.ClusterName())
_, err = k.clients.dst.CreateNamespace(ctx, k.params.TestNamespace, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("unable to create namespace %s: %s", k.params.TestNamespace, err)
}
}
}
_, err = k.clients.src.GetService(ctx, k.params.TestNamespace, echoSameNodeDeploymentName, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Deploying echo-same-node service...", k.clients.src.ClusterName())
svc := newService(echoSameNodeDeploymentName, map[string]string{"name": echoSameNodeDeploymentName}, serviceLabels, "http", 8080)
_, err = k.clients.src.CreateService(ctx, k.params.TestNamespace, svc, metav1.CreateOptions{})
if err != nil {
return err
}
}
if k.params.MultiCluster != "" {
_, err = k.clients.src.GetService(ctx, k.params.TestNamespace, echoOtherNodeDeploymentName, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Deploying echo-other-node service...", k.clients.src.ClusterName())
svc := newService(echoOtherNodeDeploymentName, map[string]string{"name": echoOtherNodeDeploymentName}, serviceLabels, "http", 8080)
svc.ObjectMeta.Annotations = map[string]string{}
svc.ObjectMeta.Annotations["io.cilium/global-service"] = "true"
_, err = k.clients.src.CreateService(ctx, k.params.TestNamespace, svc, metav1.CreateOptions{})
if err != nil {
return err
}
}
}
_, err = k.clients.src.GetDeployment(ctx, k.params.TestNamespace, echoSameNodeDeploymentName, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Deploying same-node deployment...", k.clients.src.ClusterName())
echoDeployment := newDeployment(deploymentParameters{
Name: echoSameNodeDeploymentName,
Kind: kindEchoName,
Port: 8080,
Image: "quay.io/cilium/json-mock:1.2",
Affinity: &corev1.Affinity{
PodAffinity: &corev1.PodAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{Key: "name", Operator: metav1.LabelSelectorOpIn, Values: []string{ClientDeploymentName}},
},
},
TopologyKey: "kubernetes.io/hostname",
},
},
},
},
ReadinessProbe: newLocalReadinessProbe(8080, "/"),
})
_, err = k.clients.src.CreateDeployment(ctx, k.params.TestNamespace, echoDeployment, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("unable to create deployment %s: %s", echoSameNodeDeploymentName, err)
}
}
_, err = k.clients.src.GetDeployment(ctx, k.params.TestNamespace, ClientDeploymentName, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Deploying client deployment...", k.clients.src.ClusterName())
clientDeployment := newDeployment(deploymentParameters{
Name: ClientDeploymentName,
Kind: kindClientName,
Port: 8080,
Image: "quay.io/cilium/alpine-curl:1.1",
Command: []string{"/bin/ash", "-c", "sleep 10000000"},
})
_, err = k.clients.src.CreateDeployment(ctx, k.params.TestNamespace, clientDeployment, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("unable to create deployment %s: %s", ClientDeploymentName, err)
}
}
if !k.params.SingleNode || k.params.MultiCluster != "" {
_, err = k.clients.dst.GetService(ctx, k.params.TestNamespace, echoOtherNodeDeploymentName, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Deploying echo-other-node service...", k.clients.dst.ClusterName())
svc := newService(echoOtherNodeDeploymentName, map[string]string{"name": echoOtherNodeDeploymentName}, serviceLabels, "http", 8080)
if k.params.MultiCluster != "" {
svc.ObjectMeta.Annotations = map[string]string{}
svc.ObjectMeta.Annotations["io.cilium/global-service"] = "true"
}
_, err = k.clients.dst.CreateService(ctx, k.params.TestNamespace, svc, metav1.CreateOptions{})
if err != nil {
return err
}
}
_, err = k.clients.dst.GetDeployment(ctx, k.params.TestNamespace, echoOtherNodeDeploymentName, metav1.GetOptions{})
if err != nil {
k.Log("✨ [%s] Deploying other-node deployment...", k.clients.dst.ClusterName())
echoOtherNodeDeployment := newDeployment(deploymentParameters{
Name: echoOtherNodeDeploymentName,
Kind: kindEchoName,
Port: 8080,
Image: "quay.io/cilium/json-mock:1.2",
Affinity: &corev1.Affinity{
PodAntiAffinity: &corev1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []corev1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{Key: "name", Operator: metav1.LabelSelectorOpIn, Values: []string{ClientDeploymentName}},
},
},
TopologyKey: "kubernetes.io/hostname",
},
},
},
},
ReadinessProbe: newLocalReadinessProbe(8080, "/"),
})
_, err = k.clients.dst.CreateDeployment(ctx, k.params.TestNamespace, echoOtherNodeDeployment, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("unable to create deployment %s: %s", echoOtherNodeDeploymentName, err)
}
}
}
return nil
}
func (k *K8sConnectivityCheck) validateCiliumEndpoint(ctx context.Context, client k8sConnectivityImplementation, namespace, name string) error {
k.Log("⌛ [%s] Waiting for CiliumEndpoint for pod %s to appear...", client.ClusterName(), namespace+"/"+name)
for {
_, err := client.GetCiliumEndpoint(ctx, k.params.TestNamespace, name, metav1.GetOptions{})
if err == nil {
return nil
}
select {
case <-time.After(2 * time.Second):
case <-ctx.Done():
return fmt.Errorf("aborted waiting for CiliumEndpoint for pod %s to appear: %w", name, ctx.Err())
}
}
}
func (k *K8sConnectivityCheck) waitForDeploymentsReady(ctx context.Context, client k8sConnectivityImplementation, deployments []string) error {
k.Log("⌛ [%s] Waiting for deployments %s to become ready...", client.ClusterName(), deployments)
ctx, cancel := context.WithTimeout(ctx, k.params.podReadyTimeout())
defer cancel()
for _, name := range deployments {
for client.DeploymentIsReady(ctx, k.params.TestNamespace, name) != nil {
select {
case <-time.After(time.Second):
case <-ctx.Done():