-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
kubectl.go
4830 lines (4192 loc) · 167 KB
/
kubectl.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package helpers
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"text/tabwriter"
"time"
"unicode"
"github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"github.com/cilium/cilium/api/v1/models"
cnpv2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
"github.com/cilium/cilium/pkg/k8s/synced"
"github.com/cilium/cilium/test/config"
ginkgoext "github.com/cilium/cilium/test/ginkgo-ext"
"github.com/cilium/cilium/test/helpers/logutils"
)
const (
// KubectlCmd Kubernetes controller command
KubectlCmd = "kubectl"
kubeDNSLabel = "k8s-app=kube-dns"
operatorLabel = "io.cilium/app=operator"
// DNSHelperTimeout is a predefined timeout value for K8s DNS commands. It
// must be larger than 5 minutes because kubedns has a hardcoded resync
// period of 5 minutes. We have experienced test failures because kubedns
// needed this time to recover from a connection problem to kube-apiserver.
// The kubedns resyncPeriod is defined at
// https://github.com/kubernetes/dns/blob/80fdd88276adba36a87c4f424b66fdf37cd7c9a8/pkg/dns/dns.go#L53
DNSHelperTimeout = 7 * time.Minute
// CIIntegrationEKSChaining contains the constants to be used when running tests on EKS with aws-cni in chaining mode.
CIIntegrationEKSChaining = "eks-chaining"
// CIIntegrationEKS contains the constants to be used when running tests on EKS in ENI mode.
CIIntegrationEKS = "eks"
// CIIntegrationGKE contains the constants to be used when running tests on GKE.
CIIntegrationGKE = "gke"
// CIIntegrationAKS contains the constants to be used when running tests on AKS.
CIIntegrationAKS = "aks"
// CIIntegrationKind contains the constant to be used when running tests on kind.
CIIntegrationKind = "kind"
// CIIntegrationMicrok8s contains the constant to be used when running tests on microk8s.
CIIntegrationMicrok8s = "microk8s"
// CIIntegrationMicrok8s is the value to set CNI_INTEGRATION when running with minikube.
CIIntegrationMinikube = "minikube"
LogGathererSelector = "k8s-app=cilium-test-logs"
CiliumSelector = "k8s-app=cilium"
IPv4NativeRoutingCIDR = "10.0.0.0/8"
IPv6NativeRoutingCIDR = "fd02::/112"
)
var (
// defaultHelmOptions are passed to helm in ciliumInstallHelm, unless
// overridden by options passed in at invocation. In those cases, the test
// has a specific need to override the option.
// These defaults are made to match some environment variables in init(),
// below. These overrides represent a desire to set the default for all
// tests, instead of test-specific variations.
defaultHelmOptions = map[string]string{
"image.repository": "k8s1:5000/cilium/cilium-dev",
"image.tag": "latest",
"image.useDigest": "false",
"preflight.image.repository": "k8s1:5000/cilium/cilium-dev", // Set again in init to match agent.image!
"preflight.image.tag": "latest",
"preflight.image.useDigest": "false",
"operator.image.repository": "k8s1:5000/cilium/operator",
"operator.image.tag": "latest",
"operator.image.suffix": "",
"operator.image.useDigest": "false",
// Enable embedded Hubble, both on unix socket and TCP port 4244.
"hubble.enabled": "true",
"hubble.listenAddress": ":4244",
"hubble.eventBufferCapacity": "65535",
"hubble.relay.image.repository": "k8s1:5000/cilium/hubble-relay",
"hubble.relay.image.tag": "latest",
"hubble.relay.image.useDigest": "false",
"debug.enabled": "true",
"debug.verbose": "flow",
"k8s.requireIPv4PodCIDR": "true",
"pprof.enabled": "true",
"logSystemLoad": "true",
"bpf.preallocateMaps": "false",
"etcd.leaseTTL": "30s",
"ipv4.enabled": "true",
"ipv6.enabled": "true",
// "extraEnv[0].name": "KUBE_CACHE_MUTATION_DETECTOR",
// "extraEnv[0].value": "true",
// We need CNP node status to know when a policy is being enforced
"ipv4NativeRoutingCIDR": IPv4NativeRoutingCIDR,
"ipv6NativeRoutingCIDR": IPv6NativeRoutingCIDR,
"ipam.operator.clusterPoolIPv6PodCIDRList": "fd02::/112",
"extraConfig.max-internal-timer-delay": "5s",
}
eksChainingHelmOverrides = map[string]string{
"k8s.requireIPv4PodCIDR": "false",
"cni.chainingMode": "aws-cni",
"masquerade": "false",
"routingMode": "native",
"nodeinit.enabled": "true",
}
eksHelmOverrides = map[string]string{
"egressMasqueradeInterfaces": "eth0",
"eni.enabled": "true",
"ipam.mode": "eni",
"ipv6.enabled": "false",
"k8s.requireIPv4PodCIDR": "false",
"nodeinit.enabled": "true",
"routingMode": "native",
}
gkeHelmOverrides = map[string]string{
"ipv6.enabled": "false",
"nodeinit.enabled": "true",
"nodeinit.reconfigureKubelet": "true",
"nodeinit.removeCbrBridge": "true",
"nodeinit.restartPods": "true",
"cni.binPath": "/home/kubernetes/bin",
"gke.enabled": "true",
"loadBalancer.mode": "snat",
"ipv4NativeRoutingCIDR": NativeRoutingCIDR(),
"hostFirewall.enabled": "false",
"ipam.mode": "kubernetes",
"devices": "", // Override "eth0 eth0\neth0"
}
aksHelmOverrides = map[string]string{
"ipam.mode": "delegated-plugin",
"routingMode": "native",
"endpointRoutes.enabled": "true",
"extraArgs": "{--local-router-ipv4=169.254.23.0}",
"k8s.requireIPv4PodCIDR": "false",
"ipv6.enabled": "false",
"ipv4NativeRoutingCIDR": NativeRoutingCIDR(),
"enableIPv4Masquerade": "false",
"install-no-conntrack-iptables-rules": "false",
"l7Proxy": "false",
"hubble.enabled": "false",
"kubeProxyReplacement": "true",
"endpointHealthChecking.enabled": "false",
"cni.install": "true",
"cni.customConf": "true",
"cni.configMap": "cni-configuration",
}
microk8sHelmOverrides = map[string]string{
"cni.confPath": "/var/snap/microk8s/current/args/cni-network",
"cni.binPath": "/var/snap/microk8s/current/opt/cni/bin",
"cni.customConf": "true",
"daemon.runPath": "/var/snap/microk8s/current/var/run/cilium",
"image.pullPolicy": "IfNotPresent",
"ipv6.enabled": "false",
"operator.replicas": "1",
}
minikubeHelmOverrides = map[string]string{
"ipv6.enabled": "false",
"bpf.preallocateMaps": "false",
"k8s.requireIPv4PodCIDR": "false",
}
kindHelmOverrides = map[string]string{
// To mount the cgroupv2 sub-root
"nodeinit.enabled": "true",
"image.pullPolicy": "IfNotPresent",
}
// helmOverrides allows overriding of cilium-agent options for
// specific CI environment integrations.
// The key must be a string consisting of lower case characters.
helmOverrides = map[string]map[string]string{
CIIntegrationEKSChaining: eksChainingHelmOverrides,
CIIntegrationEKS: eksHelmOverrides,
CIIntegrationGKE: gkeHelmOverrides,
CIIntegrationAKS: aksHelmOverrides,
CIIntegrationKind: kindHelmOverrides,
CIIntegrationMicrok8s: microk8sHelmOverrides,
CIIntegrationMinikube: minikubeHelmOverrides,
}
// resourcesToClean is the list of resources which should be cleaned
// from default namespace before tests are being run. It's not possible
// to delete all resources as services like "kubernetes" must be
// preserved. This helps reduce contamination between tests if tests
// are leaking resources into the default namespace for some reason.
resourcesToClean = []string{
"deployment",
"daemonset",
"rs",
"rc",
"statefulset",
"pods",
"netpol",
"cnp",
"cep",
}
)
func Init() {
if config.CiliumTestConfig.CiliumImage != "" {
os.Setenv("CILIUM_IMAGE", config.CiliumTestConfig.CiliumImage)
}
if config.CiliumTestConfig.CiliumTag != "" {
os.Setenv("CILIUM_TAG", config.CiliumTestConfig.CiliumTag)
}
if config.CiliumTestConfig.CiliumOperatorImage != "" {
os.Setenv("CILIUM_OPERATOR_IMAGE", config.CiliumTestConfig.CiliumOperatorImage)
}
if config.CiliumTestConfig.CiliumOperatorTag != "" {
os.Setenv("CILIUM_OPERATOR_TAG", config.CiliumTestConfig.CiliumOperatorTag)
}
if config.CiliumTestConfig.CiliumOperatorSuffix != "" {
os.Setenv("CILIUM_OPERATOR_SUFFIX", config.CiliumTestConfig.CiliumOperatorSuffix)
}
if config.CiliumTestConfig.HubbleRelayImage != "" {
os.Setenv("HUBBLE_RELAY_IMAGE", config.CiliumTestConfig.HubbleRelayImage)
}
if config.CiliumTestConfig.HubbleRelayTag != "" {
os.Setenv("HUBBLE_RELAY_TAG", config.CiliumTestConfig.HubbleRelayTag)
}
if !config.CiliumTestConfig.ProvisionK8s {
os.Setenv("SKIP_K8S_PROVISION", "true")
}
// Copy over envronment variables that are passed in.
for envVar, helmVar := range map[string]string{
"CILIUM_TAG": "image.tag",
"CILIUM_IMAGE": "image.repository",
"CILIUM_OPERATOR_TAG": "operator.image.tag",
"CILIUM_OPERATOR_IMAGE": "operator.image.repository",
"CILIUM_OPERATOR_SUFFIX": "operator.image.suffix",
"HUBBLE_RELAY_IMAGE": "hubble.relay.image.repository",
"HUBBLE_RELAY_TAG": "hubble.relay.image.tag",
} {
if v := os.Getenv(envVar); v != "" {
defaultHelmOptions[helmVar] = v
}
}
// preflight must match the cilium agent image (that's the point)
defaultHelmOptions["preflight.image.repository"] = defaultHelmOptions["image.repository"]
defaultHelmOptions["preflight.image.tag"] = defaultHelmOptions["image.tag"]
}
// GetCurrentK8SEnv returns the value of K8S_VERSION from the OS environment.
func GetCurrentK8SEnv() string { return os.Getenv("K8S_VERSION") }
func GetKubectlPath() string {
return path.Join(config.CiliumTestConfig.KubectlPath, GetCurrentK8SEnv())
}
// GetCurrentIntegration returns CI integration set up to run against Cilium.
func GetCurrentIntegration() string {
integration := strings.ToLower(os.Getenv("CNI_INTEGRATION"))
if _, exists := helmOverrides[integration]; exists {
return integration
}
return ""
}
// IsIntegration returns true when integration matches the configuration of
// this test run
func IsIntegration(integration string) bool {
return GetCurrentIntegration() == integration
}
// Kubectl is a wrapper around an SSHMeta. It is used to run Kubernetes-specific
// commands on the node which is accessible via the SSH metadata stored in its
// SSHMeta.
type Kubectl struct {
Executor
*serviceCache
// ciliumOptions is a cache of the most recent configuration options
// used to install Cilium via CiliumInstall().
ciliumOptions map[string]string
// nDNSReplicas is the number of replicas for DNS pods in the cluster.
// Stored via kub.ScaleDownDNS(), used by kub.ScaleUpDNS().
nDNSReplicas int
}
// CreateKubectl initializes a Kubectl helper with the provided vmName and log
// It marks the test as Fail if cannot get the ssh meta information or cannot
// execute a `ls` on the virtual machine.
func CreateKubectl(vmName string, log *logrus.Entry) (k *Kubectl) {
if config.CiliumTestConfig.Kubeconfig == "" {
node := GetVagrantSSHMeta(vmName)
if node == nil {
ginkgoext.Fail(fmt.Sprintf("Cannot connect to vmName '%s'", vmName), 1)
return nil
}
// This `ls` command is a sanity check, sometimes the meta ssh info is not
// nil but new commands cannot be executed using SSH, tests failed and it
// was hard to debug.
res := node.ExecShort("ls /tmp/")
if !res.WasSuccessful() {
ginkgoext.Fail(fmt.Sprintf(
"Cannot execute ls command on vmName '%s'", vmName), 1)
return nil
}
node.logger = log
k = &Kubectl{
Executor: node,
}
k.setBasePath()
} else {
// Prepare environment variables
// NOTE: order matters and we want the KUBECONFIG from config to win
var environ []string
if config.CiliumTestConfig.PassCLIEnvironment {
environ = append(environ, os.Environ()...)
}
environ = append(environ, "KUBECONFIG="+config.CiliumTestConfig.Kubeconfig)
environ = append(environ, fmt.Sprintf("PATH=%s:%s", GetKubectlPath(), os.Getenv("PATH")))
// Create the executor
exec := CreateLocalExecutor(environ)
exec.logger = log
k = &Kubectl{
Executor: exec,
}
k.setBasePath()
if err := k.ensureKubectlVersion(); err != nil {
ginkgoext.Failf("failed to ensure kubectl version: %s", err)
}
}
// Make sure the namespace Cilium uses exists.
if err := k.EnsureNamespaceExists(CiliumNamespace); err != nil {
ginkgoext.Failf("failed to ensure the namespace %s exists: %s", CiliumNamespace, err)
}
res := k.Apply(ApplyOptions{FilePath: filepath.Join(k.BasePath(), K8sManifestBase, "log-gatherer.yaml"), Namespace: LogGathererNamespace})
if !res.WasSuccessful() {
ginkgoext.Fail(fmt.Sprintf("Cannot connect to k8s cluster, output:\n%s", res.CombineOutput().String()), 1)
return nil
}
if err := k.WaitforPods(LogGathererNamespace, "-l "+logGathererSelector(true), HelperTimeout); err != nil {
ginkgoext.Fail(fmt.Sprintf("Failed waiting for log-gatherer pods: %s", err), 1)
return nil
}
// Clean any leftover resources in the default namespace
k.CleanNamespace(DefaultNamespace)
k.ciliumOptions = make(map[string]string)
return k
}
// DaemonSetIsReady validate that a DaemonSet is scheduled on all required
// nodes and all pods are ready. If this condition is not met, an error is
// returned. If all pods are ready, then the number of pods is returned.
func (kub *Kubectl) DaemonSetIsReady(namespace, daemonset string) (int, error) {
fullName := namespace + "/" + daemonset
res := kub.ExecShort(fmt.Sprintf("%s -n %s get daemonset %s -o json", KubectlCmd, namespace, daemonset))
if !res.WasSuccessful() {
return 0, fmt.Errorf("unable to retrieve daemonset %s: %s", fullName, res.OutputPrettyPrint())
}
d := &appsv1.DaemonSet{}
err := res.Unmarshal(d)
if err != nil {
return 0, fmt.Errorf("unable to unmarshal DaemonSet %s: %w", fullName, err)
}
if d.Status.DesiredNumberScheduled == 0 {
return 0, fmt.Errorf("desired number of pods is zero")
}
if d.Status.CurrentNumberScheduled != d.Status.DesiredNumberScheduled {
return 0, fmt.Errorf("only %d of %d desired pods are scheduled", d.Status.CurrentNumberScheduled, d.Status.DesiredNumberScheduled)
}
if d.Status.NumberAvailable != d.Status.DesiredNumberScheduled {
return 0, fmt.Errorf("only %d of %d desired pods are ready", d.Status.NumberAvailable, d.Status.DesiredNumberScheduled)
}
return int(d.Status.DesiredNumberScheduled), nil
}
// AddRegistryCredentials adds a registry credentials secret into the
// cluster
func (kub *Kubectl) AddRegistryCredentials(cred string, registry string) error {
if len(cred) == 0 || cred == ":" {
return nil
}
if kub.ExecShort(fmt.Sprintf("%s get secret regcred", KubectlCmd)).WasSuccessful() {
return nil
}
up := strings.SplitN(cred, ":", 2)
if len(up) != 2 {
return fmt.Errorf("registry credentials had an invalid format")
}
cmd := fmt.Sprintf("%s secret docker-registry regcred --docker-server=%s --docker-username=%s --docker-password=%s", KubectlCmd, registry, up[0], up[1])
if !kub.ExecShort(cmd).WasSuccessful() {
return fmt.Errorf("unable to create registry credentials")
}
return nil
}
// WaitForCiliumReadiness waits for the Cilium DaemonSet to become ready.
// Readiness is achieved when all Cilium pods which are desired to run on a
// node are in ready state.
func (kub *Kubectl) WaitForCiliumReadiness(offset int, errMsg string) {
ginkgoext.By("Waiting for Cilium to become ready")
gomega.EventuallyWithOffset(1+offset, func() error {
_, err := kub.DaemonSetIsReady(CiliumNamespace, "cilium")
return err
}, 4*time.Minute, time.Second).Should(gomega.BeNil(), errMsg)
}
// DeleteResourceInAnyNamespace deletes all objects with the provided name of
// the specified resource type in all namespaces.
func (kub *Kubectl) DeleteResourcesInAnyNamespace(resource string, names []string) error {
cmd := KubectlCmd + " get " + resource + " --all-namespaces -o json | jq -r '[ .items[].metadata | (.namespace + \"/\" + .name) ]'"
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to retrieve %s in all namespaces '%s': %s", resource, cmd, res.OutputPrettyPrint())
}
var allNames []string
if err := res.Unmarshal(&allNames); err != nil {
return fmt.Errorf("unable to unmarshal string slice '%#v': %w", res.OutputPrettyPrint(), err)
}
namesMap := map[string]struct{}{}
for _, name := range names {
namesMap[name] = struct{}{}
}
for _, combinedName := range allNames {
parts := strings.SplitN(combinedName, "/", 2)
if len(parts) != 2 {
return fmt.Errorf("The %s idenfifier '%s' is not in the form <namespace>/<name>", resource, combinedName)
}
namespace, name := parts[0], parts[1]
if _, ok := namesMap[name]; ok {
ginkgoext.By("Deleting %s %s in namespace %s", resource, name, namespace)
cmd = KubectlCmd + " -n " + namespace + " delete " + resource + " " + name
res = kub.ExecShort(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to delete %s %s in namespaces %s with command '%s': %s",
resource, name, namespace, cmd, res.OutputPrettyPrint())
}
}
}
return nil
}
// ParallelResourceDelete deletes all instances of a resource in a namespace
// based on the list of names provided. Waits until all delete API calls
// return.
func (kub *Kubectl) ParallelResourceDelete(namespace, resource string, names []string) {
ginkgoext.By("Deleting %s [%s] in namespace %s", resource, strings.Join(names, ","), namespace)
var wg sync.WaitGroup
for _, name := range names {
wg.Add(1)
go func(name string) {
cmd := fmt.Sprintf("%s -n %s delete %s %s",
KubectlCmd, namespace, resource, name)
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
ginkgoext.By("Unable to delete %s %s with '%s': %s",
resource, name, cmd, res.OutputPrettyPrint())
}
wg.Done()
}(name)
}
ginkgoext.By("Waiting for %d deletes to return (%s)",
len(names), strings.Join(names, ","))
wg.Wait()
}
// DeleteAllResourceInNamespace deletes all instances of a resource in a namespace
func (kub *Kubectl) DeleteAllResourceInNamespace(namespace, resource string) {
cmd := fmt.Sprintf("%s -n %s get %s -o json | jq -r '[ .items[].metadata.name ]'",
KubectlCmd, namespace, resource)
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
ginkgoext.By("Unable to retrieve list of resource '%s' with '%s': %s",
resource, cmd, res.stdout.Bytes())
return
}
if len(res.stdout.Bytes()) > 0 {
var nameList []string
if err := res.Unmarshal(&nameList); err != nil {
ginkgoext.By("Unable to unmarshal string slice '%#v': %s",
res.OutputPrettyPrint(), err)
return
}
if len(nameList) > 0 {
kub.ParallelResourceDelete(namespace, resource, nameList)
}
}
}
// CleanNamespace removes all artifacts from a namespace
func (kub *Kubectl) CleanNamespace(namespace string) {
var wg sync.WaitGroup
for _, resource := range resourcesToClean {
wg.Add(1)
go func(resource string) {
kub.DeleteAllResourceInNamespace(namespace, resource)
wg.Done()
}(resource)
}
wg.Wait()
}
// DeleteAllInNamespace deletes all namespaces except the ones provided in the
// exception list
func (kub *Kubectl) DeleteAllNamespacesExcept(except []string) error {
cmd := KubectlCmd + " get namespace -o json | jq -r '[ .items[].metadata.name ]'"
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to retrieve all namespaces with '%s': %s", cmd, res.OutputPrettyPrint())
}
var namespaceList []string
if err := res.Unmarshal(&namespaceList); err != nil {
return fmt.Errorf("unable to unmarshal string slice '%#v': %w", namespaceList, err)
}
exceptMap := map[string]struct{}{}
for _, e := range except {
exceptMap[e] = struct{}{}
}
for _, namespace := range namespaceList {
if _, ok := exceptMap[namespace]; !ok {
kub.NamespaceDelete(namespace)
}
}
return nil
}
// PrepareCluster will prepare the cluster to run tests. It will:
// - Delete all existing namespaces
// - Label all nodes so the tests can use them
func (kub *Kubectl) PrepareCluster() {
ginkgoext.By("Preparing cluster")
err := kub.DeleteAllNamespacesExcept([]string{
KubeSystemNamespace,
CiliumNamespace,
"default",
"kube-node-lease",
"kube-public",
"container-registry",
"cilium-ci-lock",
"prom",
})
if err != nil {
ginkgoext.Failf("Unable to delete non-essential namespaces: %s", err)
}
ginkgoext.By("Labelling nodes")
if err = kub.labelNodes(); err != nil {
ginkgoext.Failf("unable label nodes: %s", err)
}
err = kub.AddRegistryCredentials(config.CiliumTestConfig.RegistryCredentials, config.RegistryDomain)
if err != nil {
ginkgoext.Failf("unable to add registry credentials to cluster: %s", err)
}
}
// NumNodes returns the number of Kubernetes nodes
func (kub *Kubectl) NumNodes() int {
cmd := KubectlCmd + " get nodes -o json | jq '.items | length'"
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
ginkgoext.Failf("unable to retrieve all nodes with '%s': %s", cmd, res.OutputPrettyPrint())
}
i, err := strconv.Atoi(strings.TrimSpace(res.Stdout()))
if err != nil {
ginkgoext.Failf("unable to parse number of nodes from '%s': %s", res.Stdout(), err)
}
return i
}
// labelNodes labels all Kubernetes nodes for use by the CI tests
func (kub *Kubectl) labelNodes() error {
cmd := KubectlCmd + " get nodes -o json | jq -r '[ .items[] | select(.metadata.labels[\"node-role.kubernetes.io/controlplane\"] == null).metadata.name ]'"
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to retrieve all nodes with '%s': %s", cmd, res.OutputPrettyPrint())
}
var nodesList []string
if err := res.Unmarshal(&nodesList); err != nil {
return fmt.Errorf("unable to unmarshal string slice '%#v': %w", nodesList, err)
}
index := 1
for _, nodeName := range nodesList {
ciNodeName := fmt.Sprintf("k8s%d", index)
cmd := fmt.Sprintf("%s label --overwrite node %s cilium.io/ci-node=%s", KubectlCmd, nodeName, ciNodeName)
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to label node with '%s': %s", cmd, res.OutputPrettyPrint())
}
index++
}
noCiliumNodeNames := strings.Join(GetNodesWithoutCilium(), " ")
if noCiliumNodeNames != "" {
// Prevent scheduling any pods on the node, as it will be used as an external client
// to send requests to k8s{1,2}
cmd := fmt.Sprintf("%s taint --overwrite nodes %s prevent-scheduling:NoSchedule", KubectlCmd, noCiliumNodeNames)
res := kub.ExecMiddle(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to taint node with '%s': %s", cmd, res.OutputPrettyPrint())
}
}
return nil
}
// GetCiliumEndpoint returns the CiliumEndpoint for the specified pod.
func (kub *Kubectl) GetCiliumEndpoint(namespace string, pod string) (*cnpv2.EndpointStatus, error) {
fullName := namespace + "/" + pod
cmd := fmt.Sprintf("%s -n %s get cep %s -o json | jq '.status'", KubectlCmd, namespace, pod)
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
return nil, fmt.Errorf("unable to run command '%s' to retrieve CiliumEndpoint %s: %s",
cmd, fullName, res.OutputPrettyPrint())
}
if len(res.stdout.Bytes()) == 0 {
return nil, fmt.Errorf("CiliumEndpoint does not exist")
}
var data *cnpv2.EndpointStatus
err := res.Unmarshal(&data)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal CiliumEndpoint %s: %w", fullName, err)
}
if data == nil {
return nil, fmt.Errorf("CiliumEndpoint does not have a status yet")
}
return data, nil
}
// GetCiliumHostEndpointID returns the ID of the host endpoint on a given node.
func (kub *Kubectl) GetCiliumHostEndpointID(ciliumPod string) (int64, error) {
cmd := fmt.Sprintf("cilium endpoint list -o jsonpath='{[?(@.status.identity.id==%d)].id}'",
ReservedIdentityHost)
res := kub.CiliumExecContext(context.Background(), ciliumPod, cmd)
if !res.WasSuccessful() {
return 0, fmt.Errorf("unable to run command '%s' to retrieve ID of host endpoint from %s: %s",
cmd, ciliumPod, res.OutputPrettyPrint())
}
hostEpID, err := strconv.ParseInt(strings.TrimSpace(res.Stdout()), 10, 64)
if err != nil || hostEpID == 0 {
return 0, fmt.Errorf("incorrect host endpoint ID %s: %w",
strings.TrimSpace(res.Stdout()), err)
}
return hostEpID, nil
}
// GetCiliumHostEndpointState returns the state of the host endpoint on a given node.
func (kub *Kubectl) GetCiliumHostEndpointState(ciliumPod string) (string, error) {
cmd := fmt.Sprintf("cilium endpoint list -o jsonpath='{[?(@.status.identity.id==%d)].status.state}'",
ReservedIdentityHost)
res := kub.CiliumExecContext(context.Background(), ciliumPod, cmd)
if !res.WasSuccessful() {
return "", fmt.Errorf("unable to run command '%s' to retrieve state of host endpoint from %s: %s",
cmd, ciliumPod, res.OutputPrettyPrint())
}
return strings.TrimSpace(res.Stdout()), nil
}
// GetCiliumIdentityForIP returns the numeric identity for a given IP address
// according to a node's BPF ipcache.
func (kub *Kubectl) GetCiliumIdentityForIP(ciliumPod, ip string) (int, error) {
cmd := fmt.Sprintf("cilium-dbg bpf ipcache get %s", ip)
res := kub.CiliumExecContext(context.Background(), ciliumPod, cmd)
if !res.WasSuccessful() {
return 0, fmt.Errorf("unable to run command '%s' to retrieve state of host endpoint from %s: %s",
cmd, ciliumPod, res.OutputPrettyPrint())
}
// output looks like
// 172.19.0.2 maps to identity identity=16777217 encryptkey=0 tunnelendpoint=0.0.0.0
words := strings.Fields(res.Stdout())
if len(words) < 5 {
return 0, fmt.Errorf("could not parse output %s from command %s on from %s", res.Stdout(), cmd, ciliumPod)
}
kv := strings.SplitN(words[4], "=", 2)
if len(kv) < 2 {
return 0, fmt.Errorf("could not parse output %s from command %s on from %s", res.Stdout(), cmd, ciliumPod)
}
i, err := strconv.Atoi(kv[1])
if err != nil {
return 0, fmt.Errorf("could not parse output %s from command %s on from %s", res.Stdout(), cmd, ciliumPod)
}
return i, nil
}
// GetNumCiliumNodes returns the number of Kubernetes nodes running cilium
func (kub *Kubectl) GetNumCiliumNodes() int {
getNodesCmd := fmt.Sprintf("%s get nodes -o jsonpath='{.items.*.metadata.name}'", KubectlCmd)
res := kub.ExecShort(getNodesCmd)
if !res.WasSuccessful() {
return 0
}
return len(strings.Split(res.SingleOut(), " ")) - len(GetNodesWithoutCilium())
}
// CountMissedTailCalls returns the number of the sum of all drops due to
// missed tail calls that happened on all Cilium-managed nodes.
func (kub *Kubectl) CountMissedTailCalls() (int, error) {
ciliumPods, err := kub.GetCiliumPods()
if err != nil {
return -1, err
}
totalMissedTailCalls := 0
for _, ciliumPod := range ciliumPods {
cmd := "cilium metrics list -o json | jq '.[] | select( .name == \"cilium_drop_count_total\" and .labels.reason == \"Missed tail call\" ).value'"
res := kub.CiliumExecContext(context.Background(), ciliumPod, cmd)
if !res.WasSuccessful() {
return -1, fmt.Errorf("Failed to run %s in pod %s: %s", cmd, ciliumPod, res.CombineOutput())
}
if res.Stdout() == "" {
continue
}
for _, cnt := range res.ByLines() {
nbMissedTailCalls, err := strconv.Atoi(cnt)
if err != nil {
return -1, err
}
totalMissedTailCalls += nbMissedTailCalls
}
}
return totalMissedTailCalls, nil
}
// CreateSecret is a wrapper around `kubernetes create secret
// <resourceName>.
func (kub *Kubectl) CreateSecret(secretType, name, namespace, args string) *CmdRes {
kub.Logger().Debug(fmt.Sprintf("creating secret %s in namespace %s", name, namespace))
kub.ExecShort(fmt.Sprintf("kubectl delete secret %s %s -n %s", secretType, name, namespace))
return kub.ExecShort(fmt.Sprintf("kubectl create secret %s %s -n %s %s", secretType, name, namespace, args))
}
// CopyFileToPod copies a file to a pod's file-system.
func (kub *Kubectl) CopyFileToPod(namespace string, pod string, fromFile, toFile string) *CmdRes {
kub.Logger().Debug(fmt.Sprintf("copyiong file %s to pod %s/%s:%s", fromFile, namespace, pod, toFile))
return kub.Exec(fmt.Sprintf("%s cp %s %s/%s:%s", KubectlCmd, fromFile, namespace, pod, toFile))
}
// ExecKafkaPodCmd executes shell command with arguments arg in the specified pod residing in the specified
// namespace. It returns the stdout of the command that was executed.
// The kafka producer and consumer scripts do not return error if command
// leads to TopicAuthorizationException or any other error. Hence the
// function needs to also take into account the stderr messages returned.
func (kub *Kubectl) ExecKafkaPodCmd(namespace string, pod string, arg string) error {
command := fmt.Sprintf("%s exec -n %s %s -- %s", KubectlCmd, namespace, pod, arg)
res := kub.Exec(command)
if !res.WasSuccessful() {
return fmt.Errorf("ExecKafkaPodCmd: command '%s' failed %s",
res.GetCmd(), res.OutputPrettyPrint())
}
if strings.Contains(res.Stderr(), "ERROR") {
return fmt.Errorf("ExecKafkaPodCmd: command '%s' failed '%s'",
res.GetCmd(), res.OutputPrettyPrint())
}
return nil
}
// ExecPodCmd executes command cmd in the specified pod residing in the specified
// namespace. It returns a pointer to CmdRes with all the output
func (kub *Kubectl) ExecPodCmd(namespace string, pod string, cmd string, options ...ExecOptions) *CmdRes {
command := fmt.Sprintf("%s exec -n %s %s -- %s", KubectlCmd, namespace, pod, cmd)
return kub.Exec(command, options...)
}
// ExecPodContainerCmd executes command cmd in the specified container residing
// in the specified namespace and pod. It returns a pointer to CmdRes with all
// the output
func (kub *Kubectl) ExecPodContainerCmd(namespace, pod, container, cmd string, options ...ExecOptions) *CmdRes {
command := fmt.Sprintf("%s exec -n %s %s -c %s -- %s", KubectlCmd, namespace, pod, container, cmd)
return kub.Exec(command, options...)
}
// ExecPodCmdContext synchronously executes command cmd in the specified pod residing in the
// specified namespace. It returns a pointer to CmdRes with all the output.
func (kub *Kubectl) ExecPodCmdContext(ctx context.Context, namespace string, pod string, cmd string, options ...ExecOptions) *CmdRes {
command := fmt.Sprintf("%s exec -n %s %s -- %s", KubectlCmd, namespace, pod, cmd)
return kub.ExecContext(ctx, command, options...)
}
// ExecPodCmdBackground executes command cmd in background in the specified pod residing
// in the specified namespace. It returns a pointer to CmdRes with all the
// output
//
// To receive the output of this function, the caller must invoke either
// kub.WaitUntilFinish() or kub.WaitUntilMatch() then subsequently fetch the
// output out of the result.
func (kub *Kubectl) ExecPodCmdBackground(ctx context.Context, namespace string, pod, container string, cmd string, options ...ExecOptions) *CmdRes {
if container != "" {
pod += " -c " + container
}
command := fmt.Sprintf("%s exec -n %s %s -- %s", KubectlCmd, namespace, pod, cmd)
return kub.ExecInBackground(ctx, command, options...)
}
// Get retrieves the provided Kubernetes objects from the specified namespace.
func (kub *Kubectl) Get(namespace string, command string) *CmdRes {
return kub.ExecShort(fmt.Sprintf(
"%s -n %s get %s -o json", KubectlCmd, namespace, command))
}
// GetFromAllNS retrieves provided Kubernetes objects from all namespaces
func (kub *Kubectl) GetFromAllNS(kind string) *CmdRes {
return kub.ExecShort(fmt.Sprintf(
"%s get %s --all-namespaces -o json", KubectlCmd, kind))
}
// GetCNP retrieves the output of `kubectl get cnp` in the given namespace for
// the given CNP and return a CNP struct. If the CNP does not exists or cannot
// unmarshal the Json output will return nil.
func (kub *Kubectl) GetCNP(namespace string, cnp string) *cnpv2.CiliumNetworkPolicy {
log := kub.Logger().WithFields(logrus.Fields{
"fn": "GetCNP",
"cnp": cnp,
"ns": namespace,
})
res := kub.Get(namespace, fmt.Sprintf("cnp %s", cnp))
if !res.WasSuccessful() {
log.WithField("error", res.CombineOutput()).Info("cannot get CNP")
return nil
}
var result cnpv2.CiliumNetworkPolicy
err := res.Unmarshal(&result)
if err != nil {
log.WithError(err).Errorf("cannot unmarshal CNP output")
return nil
}
return &result
}
func (kub *Kubectl) WaitForCRDCount(filter string, count int, timeout time.Duration) error {
// Set regexp flag m for multi-line matching, then add the
// matches for beginning and end of a line, so that we count
// at most one match per line (like "grep <filter> | wc -l")
regex := regexp.MustCompile("(?m:^.*(?:" + filter + ").*$)")
body := func() bool {
res := kub.ExecShort(fmt.Sprintf("%s get crds", KubectlCmd))
if !res.WasSuccessful() {
log.Error(res.GetErr("kubectl get crds failed"))
return false
}
return len(regex.FindAllString(res.Stdout(), -1)) == count
}
return WithTimeout(
body,
fmt.Sprintf("timed out waiting for %d CRDs matching filter \"%s\" to be ready", count, filter),
&TimeoutConfig{Timeout: timeout})
}
// GetPods gets all of the pods in the given namespace that match the provided
// filter.
func (kub *Kubectl) GetPods(namespace string, filter string) *CmdRes {
return kub.ExecShort(fmt.Sprintf("%s -n %s get pods %s -o json", KubectlCmd, namespace, filter))
}
// GetPodsNodes returns a map with pod name as a key and node name as value. It
// only gets pods in the given namespace that match the provided filter. It
// returns an error if pods cannot be retrieved correctly
func (kub *Kubectl) GetPodsNodes(namespace string, filter string) (map[string]string, error) {
jsonFilter := `{range .items[*]}{@.metadata.name}{"="}{@.spec.nodeName}{"\n"}{end}`
res := kub.Exec(fmt.Sprintf("%s -n %s get pods -l '%s' -o jsonpath='%s'",
KubectlCmd, namespace, filter, jsonFilter))
if !res.WasSuccessful() {
return nil, fmt.Errorf("cannot retrieve pods: %s", res.CombineOutput())
}
return res.KVOutput(), nil
}
// GetPodOnNodeLabeledWithOffset retrieves name and ip of a pod matching filter and residing on a node with label cilium.io/ci-node=<label>
func (kub *Kubectl) GetPodOnNodeLabeledWithOffset(label string, podFilter string, callOffset int) (string, string) {
callOffset++
nodeName, err := kub.GetNodeNameByLabel(label)
gomega.ExpectWithOffset(callOffset, err).Should(gomega.BeNil())
gomega.ExpectWithOffset(callOffset, nodeName).ShouldNot(gomega.BeEmpty(), "Cannot retrieve node name with label cilium.io/ci-node=%s", label)
var podName string
podsNodes, err := kub.GetPodsNodes(DefaultNamespace, podFilter)
gomega.ExpectWithOffset(callOffset, err).Should(gomega.BeNil(), "Cannot retrieve pods nodes with filter %q", podFilter)
gomega.Expect(podsNodes).ShouldNot(gomega.BeEmpty(), "No pod found in namespace %s with filter %q", DefaultNamespace, podFilter)
for pod, node := range podsNodes {
if node == nodeName {
podName = pod
break
}
}
gomega.ExpectWithOffset(callOffset, podName).ShouldNot(gomega.BeEmpty(), "Cannot retrieve pod on node %s with filter %q", nodeName, podFilter)
podsIPs, err := kub.GetPodsIPs(DefaultNamespace, podFilter)
gomega.ExpectWithOffset(callOffset, err).Should(gomega.BeNil(), "Cannot retrieve pods IPs with filter %q", podFilter)
gomega.Expect(podsIPs).ShouldNot(gomega.BeEmpty(), "No pod IP found in namespace %s with filter %q", DefaultNamespace, podFilter)
podIP := podsIPs[podName]
return podName, podIP
}
// GetSvcIP returns the cluster IP for the given service. If the service
// does not contain a cluster IP, the function keeps retrying until it has or
// the context timesout.
func (kub *Kubectl) GetSvcIP(ctx context.Context, namespace, name string) (string, error) {
for {
select {
case <-ctx.Done():
return "", ctx.Err()
default:
}
jsonFilter := `{.spec.clusterIP}`
res := kub.ExecContext(ctx, fmt.Sprintf("%s -n %s get svc %s -o jsonpath='%s'",
KubectlCmd, namespace, name, jsonFilter))
if !res.WasSuccessful() {
return "", fmt.Errorf("cannot retrieve pods: %s", res.CombineOutput())
}
clusterIP := res.CombineOutput().String()
if clusterIP != "" {
return clusterIP, nil
}
time.Sleep(time.Second)
}
}
// GetPodsIPs returns a map with pod name as a key and pod IP name as value. It
// only gets pods in the given namespace that match the provided filter. It
// returns an error if pods cannot be retrieved correctly
func (kub *Kubectl) GetPodsIPs(namespace string, filter string) (map[string]string, error) {
jsonFilter := `{range .items[*]}{@.metadata.name}{"="}{@.status.podIP}{"\n"}{end}`
res := kub.ExecShort(fmt.Sprintf("%s -n %s get pods -l %s -o jsonpath='%s'",
KubectlCmd, namespace, filter, jsonFilter))
if !res.WasSuccessful() {
return nil, fmt.Errorf("cannot retrieve pods: %s", res.CombineOutput())