/
kubectl.go
3457 lines (3004 loc) · 120 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
// Copyright 2018-2020 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 helpers
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"text/tabwriter"
"time"
"github.com/cilium/cilium/api/v1/models"
cnpv2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
"github.com/cilium/cilium/test/config"
ginkgoext "github.com/cilium/cilium/test/ginkgo-ext"
"github.com/cilium/cilium/test/helpers/logutils"
"github.com/asaskevich/govalidator"
"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"
)
const (
// KubectlCmd Kubernetes controller command
KubectlCmd = "kubectl"
manifestsPath = "k8sT/manifests/"
descriptorsPath = "../examples/kubernetes"
kubeDNSLabel = "k8s-app=kube-dns"
// 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
// CIIntegrationFlannel contains the constant to be used when flannel is
// used in the CI.
CIIntegrationFlannel = "flannel"
// CIIntegrationEKS contains the constants to be used when running tests on EKS.
CIIntegrationEKS = "eks"
// CIIntegrationGKE contains the constants to be used when running tests on GKE.
CIIntegrationGKE = "gke"
// 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"
)
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{
"global.registry": "k8s1:5000/cilium",
"agent.image": "cilium-dev",
"preflight.image": "cilium-dev", // Set again in init to match agent.image!
"global.tag": "latest",
"operator.image": "operator",
"global.debug.enabled": "true",
"global.k8s.requireIPv4PodCIDR": "true",
"global.pprof.enabled": "true",
"global.logSystemLoad": "true",
"global.bpf.preallocateMaps": "true",
"global.etcd.leaseTTL": "30s",
"global.ipv4.enabled": "true",
"global.ipv6.enabled": "true",
"global.psp.enabled": "true",
"global.ci.kubeCacheMutationDetector": "true",
// Disable by default, so that 4.9 CI build does not panic due to
// missing LRU support. On 4.19 and net-next we enable it with
// kubeProxyReplacement=strict.
"global.sessionAffinity.enabled": "false",
// Enable embedded Hubble, both on unix socket and TCP port 4244.
"global.hubble.enabled": "true",
"global.hubble.listenAddress": ":4244",
}
flannelHelmOverrides = map[string]string{
"global.flannel.enabled": "true",
"global.ipv6.enabled": "false",
"global.tunnel": "disabled",
}
eksHelmOverrides = map[string]string{
"global.k8s.requireIPv4PodCIDR": "false",
"global.cni.chainingMode": "aws-cni",
"global.masquerade": "false",
"global.tunnel": "disabled",
"global.nodeinit.enabled": "true",
}
gkeHelmOverrides = map[string]string{
"global.ipv6.enabled": "false",
"global.nodeinit.enabled": "true",
"nodeinit.reconfigureKubelet": "true",
"nodeinit.removeCbrBridge": "true",
"global.cni.binPath": "/home/kubernetes/bin",
"global.nodePort.mode": "snat",
"global.gke.enabled": "true",
"global.nativeRoutingCIDR": "10.0.0.0/8",
}
microk8sHelmOverrides = map[string]string{
"global.cni.confPath": "/var/snap/microk8s/current/args/cni-network",
"global.cni.binPath": "/var/snap/microk8s/current/opt/cni/bin",
"global.cni.customConf": "true",
"global.daemon.runPath": "/var/snap/microk8s/current/var/run/cilium",
}
minikubeHelmOverrides = map[string]string{
"global.ipv6.enabled": "false",
"global.bpf.preallocateMaps": "false",
"global.k8s.requireIPv4PodCIDR": "false",
}
// 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{
CIIntegrationFlannel: flannelHelmOverrides,
CIIntegrationEKS: eksHelmOverrides,
CIIntegrationGKE: gkeHelmOverrides,
CIIntegrationMicrok8s: microk8sHelmOverrides,
CIIntegrationMinikube: minikubeHelmOverrides,
}
)
// HelmOverride returns the value of a Helm override option for the currently
// enabled CNI_INTEGRATION
func HelmOverride(option string) string {
integration := strings.ToLower(os.Getenv("CNI_INTEGRATION"))
if overrides, exists := helmOverrides[integration]; exists {
return overrides[option]
}
return ""
}
// NativeRoutingEnabled returns true when native routing is enabled for a
// particular CNI_INTEGRATION
func NativeRoutingEnabled() bool {
tunnelDisabled := HelmOverride("global.tunnel") == "disabled"
gkeEnabled := HelmOverride("global.gke.enabled") == "true"
return tunnelDisabled || gkeEnabled
}
func Init() {
if config.CiliumTestConfig.CiliumImage != "" {
os.Setenv("CILIUM_IMAGE", config.CiliumTestConfig.CiliumImage)
}
if config.CiliumTestConfig.CiliumOperatorImage != "" {
os.Setenv("CILIUM_OPERATOR_IMAGE", config.CiliumTestConfig.CiliumOperatorImage)
}
if config.CiliumTestConfig.HubbleRelayImage != "" {
os.Setenv("HUBBLE_RELAY_IMAGE", config.CiliumTestConfig.HubbleRelayImage)
}
if config.CiliumTestConfig.Registry != "" {
os.Setenv("CILIUM_REGISTRY", config.CiliumTestConfig.Registry)
}
if config.CiliumTestConfig.ProvisionK8s == false {
os.Setenv("SKIP_K8S_PROVISION", "true")
}
// Set defaults to match passed-in fully-qualified image
// If these are further set via CLI, they will be overwritten below
if v := os.Getenv("CILIUM_IMAGE"); v != "" {
registry, image, version, isFullyQualified := SplitContainerURL(v)
if isFullyQualified {
defaultHelmOptions["global.tag"] = version
// This always works because SplitContainerURL would not return
// isFullyQualified == true otherwise
parts := strings.SplitN(image, "/", 2)
defaultHelmOptions["global.registry"] = registry + "/" + parts[0]
}
}
// Copy over envronment variables that are passed in.
for envVar, helmVar := range map[string]string{
"CILIUM_REGISTRY": "global.registry",
"CILIUM_TAG": "global.tag",
"CILIUM_IMAGE": "agent.image",
"CILIUM_OPERATOR_IMAGE": "operator.image",
} {
if v := os.Getenv(envVar); v != "" {
defaultHelmOptions[helmVar] = v
}
}
// preflight must match the cilium agent image (that's the point)
defaultHelmOptions["preflight.image"] = defaultHelmOptions["agent.image"]
}
// GetCurrentK8SEnv returns the value of K8S_VERSION from the OS environment.
func GetCurrentK8SEnv() string { return os.Getenv("K8S_VERSION") }
// 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
}
// GetCiliumNamespace returns the namespace into which cilium should be
// installed for this integration.
func GetCiliumNamespace(integration string) string {
switch integration {
case CIIntegrationGKE:
return CiliumNamespaceGKE
default:
return CiliumNamespaceDefault
}
}
// 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
}
// 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)
// Create the executor
exec := CreateLocalExecutor(environ)
exec.logger = log
k = &Kubectl{
Executor: exec,
}
k.setBasePath()
}
// config flags are already parsed here
if config.CiliumTestConfig.Registry != "" {
defaultHelmOptions["global.registry"] = config.CiliumTestConfig.Registry + "/cilium"
}
// 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(), manifestsPath, "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
}
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: %s", 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
}
// 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() error {
ginkgoext.By("Waiting for Cilium to become ready")
return RepeatUntilTrue(func() bool {
numPods, err := kub.DaemonSetIsReady(CiliumNamespace, "cilium")
if err != nil {
ginkgoext.By("Cilium DaemonSet not ready yet: %s", err)
} else {
ginkgoext.By("Number of ready Cilium pods: %d", numPods)
}
return err == nil
}, &TimeoutConfig{Timeout: 4 * time.Minute})
}
// 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': %s", 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
}
// 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': %s", 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,
GetCiliumNamespace(GetCurrentIntegration()),
"default",
"kube-node-lease",
"kube-public",
})
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)
}
}
// 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[].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': %s", nodesList, err)
}
index := 1
for _, nodeName := range nodesList {
cmd := fmt.Sprintf("%s label --overwrite node %s cilium.io/ci-node=k8s%d", KubectlCmd, nodeName, index)
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to label node with '%s': %s", cmd, res.OutputPrettyPrint())
}
index++
}
node := GetNodeWithoutCilium()
if node != "" {
// 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 key=value:NoSchedule", KubectlCmd, node)
res := kub.ExecMiddle(cmd)
if !res.WasSuccessful() {
return fmt.Errorf("unable to taint node with '%s': %s", cmd, res.OutputPrettyPrint())
}
}
return nil
}
// CepGet returns the endpoint model for the given pod name in the specified
// namespaces. If the pod is not present it returns nil
func (kub *Kubectl) CepGet(namespace string, pod string) *cnpv2.EndpointStatus {
log := kub.Logger().WithFields(logrus.Fields{
"cep": pod,
"namespace": namespace})
cmd := fmt.Sprintf("%s -n %s get cep %s -o json | jq '.status'", KubectlCmd, namespace, pod)
res := kub.ExecShort(cmd)
if !res.WasSuccessful() {
log.Debug("cep is not present")
return nil
}
var data *cnpv2.EndpointStatus
err := res.Unmarshal(&data)
if err != nil {
log.WithError(err).Error("cannot Unmarshal json")
return nil
}
return data
}
// 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
}
sub := 0
if ExistNodeWithoutCilium() {
sub = 1
}
return len(strings.Split(res.SingleOut(), " ")) - sub
}
// 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.GetStdErr(), "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 string, cmd string, options ...ExecOptions) *CmdRes {
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.GetStdOut(), -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 %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
}
func (kub *Kubectl) GetPodOnNodeWithOffset(nodeName string, podFilter string, callOffset int) (string, string) {
var podName string
callOffset++
podsNodes, err := kub.GetPodsNodes(DefaultNamespace, fmt.Sprintf("-l %s", 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())
}
return res.KVOutput(), nil
}
// GetPodsHostIPs returns a map with pod name as a key and host 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) GetPodsHostIPs(namespace string, label string) (map[string]string, error) {
jsonFilter := `{range .items[*]}{@.metadata.name}{"="}{@.status.hostIP}{"\n"}{end}`
res := kub.ExecShort(fmt.Sprintf("%s -n %s get pods -l %s -o jsonpath='%s'",
KubectlCmd, namespace, label, jsonFilter))
if !res.WasSuccessful() {
return nil, fmt.Errorf("cannot retrieve pods: %s", res.CombineOutput())
}
return res.KVOutput(), nil
}
// GetEndpoints gets all of the endpoints in the given namespace that match the
// provided filter.
func (kub *Kubectl) GetEndpoints(namespace string, filter string) *CmdRes {
return kub.ExecShort(fmt.Sprintf("%s -n %s get endpoints %s -o json", KubectlCmd, namespace, filter))
}
// GetAllPods returns a slice of all pods present in Kubernetes cluster, along
// with an error if the pods could not be retrieved via `kubectl`, or if the
// pod objects are unable to be marshaled from JSON.
func (kub *Kubectl) GetAllPods(ctx context.Context, options ...ExecOptions) ([]v1.Pod, error) {
var ops ExecOptions
if len(options) > 0 {
ops = options[0]
}
getPodsCtx, cancel := context.WithTimeout(ctx, ShortCommandTimeout)
defer cancel()
var podsList v1.List
err := kub.ExecContext(getPodsCtx,
fmt.Sprintf("%s get pods --all-namespaces -o json", KubectlCmd),
ExecOptions{SkipLog: ops.SkipLog}).Unmarshal(&podsList)
if err != nil {
return nil, err
}
pods := make([]v1.Pod, len(podsList.Items))
for _, item := range podsList.Items {
var pod v1.Pod
err = json.Unmarshal(item.Raw, &pod)
if err != nil {
return nil, err
}
pods = append(pods, pod)
}
return pods, nil
}
// GetPodNames returns the names of all of the pods that are labeled with label
// in the specified namespace, along with an error if the pod names cannot be
// retrieved.
func (kub *Kubectl) GetPodNames(namespace string, label string) ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), ShortCommandTimeout)
defer cancel()
return kub.GetPodNamesContext(ctx, namespace, label)
}
// GetPodNamesContext returns the names of all of the pods that are labeled with
// label in the specified namespace, along with an error if the pod names cannot
// be retrieved.
func (kub *Kubectl) GetPodNamesContext(ctx context.Context, namespace string, label string) ([]string, error) {
stdout := new(bytes.Buffer)
filter := "-o jsonpath='{.items[*].metadata.name}'"
cmd := fmt.Sprintf("%s -n %s get pods -l %s %s", KubectlCmd, namespace, label, filter)
// Taking more than 30 seconds to get pods means that something is wrong
// connecting to the node.
podNamesCtx, cancel := context.WithTimeout(ctx, ShortCommandTimeout)
defer cancel()
err := kub.ExecuteContext(podNamesCtx, cmd, stdout, nil)
if err != nil {
return nil, fmt.Errorf(
"could not find pods in namespace '%v' with label '%v': %s", namespace, label, err)
}
out := strings.Trim(stdout.String(), "\n")
if len(out) == 0 {
//Small hack. String split always return an array with an empty string
return []string{}, nil
}
return strings.Split(out, " "), nil
}
// GetNodeNameByLabel returns the names of the node with a matching cilium.io/ci-node label
func (kub *Kubectl) GetNodeNameByLabel(label string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), ShortCommandTimeout)
defer cancel()
return kub.GetNodeNameByLabelContext(ctx, label)
}
// GetNodeNameByLabelContext returns the names of all nodes with a matching label
func (kub *Kubectl) GetNodeNameByLabelContext(ctx context.Context, label string) (string, error) {
filter := `{.items[*].metadata.name}`
res := kub.ExecShort(fmt.Sprintf("%s get nodes -l cilium.io/ci-node=%s -o jsonpath='%s'",
KubectlCmd, label, filter))
if !res.WasSuccessful() {
return "", fmt.Errorf("cannot retrieve node to read name: %s", res.CombineOutput())
}
out := strings.Trim(res.GetStdOut(), "\n")
if len(out) == 0 {
return "", fmt.Errorf("no matching node to read name with label '%v'", label)
}
return out, nil
}
// GetNodeIPByLabel returns the IP of the node with cilium.io/ci-node=label.
// An error is returned if a node cannot be found.
func (kub *Kubectl) GetNodeIPByLabel(label string, external bool) (string, error) {
ipType := "InternalIP"
if external {
ipType = "ExternalIP"
}
filter := `{@.items[*].status.addresses[?(@.type == "` + ipType + `")].address}`
res := kub.ExecShort(fmt.Sprintf("%s get nodes -l cilium.io/ci-node=%s -o jsonpath='%s'",
KubectlCmd, label, filter))
if !res.WasSuccessful() {
return "", fmt.Errorf("cannot retrieve node to read IP: %s", res.CombineOutput())
}
out := strings.Trim(res.GetStdOut(), "\n")
if len(out) == 0 {
return "", fmt.Errorf("no matching node to read IP with label '%v'", label)
}
return out, nil
}
func (kub *Kubectl) getIfaceByIPAddr(label string, ipAddr string) (string, error) {
cmd := fmt.Sprintf(
`ip -j a s | jq -r '.[] | select(.addr_info[] | .local == "%s") | .ifname'`,
ipAddr)
iface, err := kub.ExecInHostNetNSByLabel(context.TODO(), label, cmd)
if err != nil {
return "", fmt.Errorf("Failed to retrieve iface by IP addr: %s", err)
}
return strings.Trim(iface, "\n"), nil
}
// GetServiceHostPort returns the host and the first port for the given service name.
// It will return an error if service cannot be retrieved.
func (kub *Kubectl) GetServiceHostPort(namespace string, service string) (string, int, error) {
var data v1.Service
err := kub.Get(namespace, fmt.Sprintf("service %s", service)).Unmarshal(&data)
if err != nil {
return "", 0, err
}
if len(data.Spec.Ports) == 0 {
return "", 0, fmt.Errorf("Service '%s' does not have ports defined", service)
}
return data.Spec.ClusterIP, int(data.Spec.Ports[0].Port), nil
}
// GetLoadBalancerIP waits until a loadbalancer IP addr has been assigned for
// the given service, and then returns the IP addr.
func (kub *Kubectl) GetLoadBalancerIP(namespace string, service string, timeout time.Duration) (string, error) {
var data v1.Service
body := func() bool {
err := kub.Get(namespace, fmt.Sprintf("service %s", service)).Unmarshal(&data)
if err != nil {
kub.Logger().WithError(err)
return false
}
if len(data.Status.LoadBalancer.Ingress) != 0 {
return true
}
kub.Logger().WithFields(logrus.Fields{
"namespace": namespace,
"service": service,
}).Info("GetLoadBalancerIP: loadbalancer IP was not assigned")
return false
}
err := WithTimeout(body, "could not get service LoadBalancer IP addr",
&TimeoutConfig{Timeout: timeout})
if err != nil {
return "", err
}
return data.Status.LoadBalancer.Ingress[0].IP, nil
}
// Logs returns a CmdRes with containing the resulting metadata from the
// execution of `kubectl logs <pod> -n <namespace>`.
func (kub *Kubectl) Logs(namespace string, pod string) *CmdRes {
return kub.Exec(
fmt.Sprintf("%s -n %s logs %s", KubectlCmd, namespace, pod))
}
// MonitorStart runs cilium monitor in the background and returns the command
// result, CmdRes, along with a cancel function. The cancel function is used to
// stop the monitor.
func (kub *Kubectl) MonitorStart(namespace, pod string) (res *CmdRes, cancel func()) {
cmd := fmt.Sprintf("%s exec -n %s %s -- cilium monitor -vv", KubectlCmd, namespace, pod)
ctx, cancel := context.WithCancel(context.Background())
return kub.ExecInBackground(ctx, cmd, ExecOptions{SkipLog: true}), cancel
}
// BackgroundReport dumps the result of the given commands on cilium pods each
// five seconds.
func (kub *Kubectl) BackgroundReport(commands ...string) (context.CancelFunc, error) {
backgroundCtx, cancel := context.WithCancel(context.Background())
pods, err := kub.GetCiliumPods(GetCiliumNamespace(GetCurrentIntegration()))
if err != nil {
return cancel, fmt.Errorf("Cannot retrieve cilium pods: %s", err)
}
retrieveInfo := func() {
for _, pod := range pods {
for _, cmd := range commands {
kub.CiliumExecContext(context.TODO(), pod, cmd)
}
}
}
go func(ctx context.Context) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
retrieveInfo()
}
}
}(backgroundCtx)
return cancel, nil
}
// PprofReport runs pprof on cilium nodes each 5 minutes and saves the data
// into the test folder saved with pprof suffix.
func (kub *Kubectl) PprofReport() {
PProfCadence := 5 * time.Minute
ticker := time.NewTicker(PProfCadence)
log := kub.Logger().WithField("subsys", "pprofReport")
retrievePProf := func(pod, testPath string) {
res := kub.ExecPodCmd(GetCiliumNamespace(GetCurrentIntegration()), pod, "gops pprof-cpu 1")
if !res.WasSuccessful() {
log.Errorf("cannot execute pprof: %s", res.OutputPrettyPrint())