forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubectl.go
1537 lines (1368 loc) · 56.8 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 2015 The Kubernetes Authors All rights reserved.
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 e2e
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"k8s.io/kubernetes/pkg/api"
apierrs "k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/unversioned"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/kubectl"
"k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/labels"
utilnet "k8s.io/kubernetes/pkg/util/net"
"k8s.io/kubernetes/pkg/util/wait"
"k8s.io/kubernetes/pkg/version"
"k8s.io/kubernetes/test/e2e/framework"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const (
nautilusImage = "gcr.io/google_containers/update-demo:nautilus"
kittenImage = "gcr.io/google_containers/update-demo:kitten"
updateDemoSelector = "name=update-demo"
updateDemoContainer = "update-demo"
frontendSelector = "app=guestbook,tier=frontend"
redisMasterSelector = "app=redis,role=master"
redisSlaveSelector = "app=redis,role=slave"
goproxyContainer = "goproxy"
goproxyPodSelector = "name=goproxy"
netexecContainer = "netexec"
netexecPodSelector = "name=netexec"
kubectlProxyPort = 8011
guestbookStartupTimeout = 10 * time.Minute
guestbookResponseTimeout = 3 * time.Minute
simplePodSelector = "name=nginx"
simplePodName = "nginx"
nginxDefaultOutput = "Welcome to nginx!"
simplePodPort = 80
runJobTimeout = 5 * time.Minute
busyboxImage = "gcr.io/google_containers/busybox:1.24"
nginxImage = "gcr.io/google_containers/nginx:1.7.9"
)
var (
proxyRegexp = regexp.MustCompile("Starting to serve on 127.0.0.1:([0-9]+)")
// Extended pod logging options were introduced in #13780 (v1.1.0) so we don't expect tests
// that rely on extended pod logging options to work on clusters before that.
//
// TODO(ihmccreery): remove once we don't care about v1.0 anymore, (tentatively in v1.3).
extendedPodLogFilterVersion = version.MustParse("v1.1.0")
// NodePorts were made optional in #12831 (v1.1.0) so we don't expect tests that used to
// require NodePorts but no longer include them to work on clusters before that.
//
// TODO(ihmccreery): remove once we don't care about v1.0 anymore, (tentatively in v1.3).
nodePortsOptionalVersion = version.MustParse("v1.1.0")
// Jobs were introduced in v1.1, so we don't expect tests that rely on jobs to work on
// clusters before that.
//
// TODO(ihmccreery): remove once we don't care about v1.0 anymore, (tentatively in v1.3).
jobsVersion = version.MustParse("v1.1.0")
// Deployments were introduced by default in v1.2, so we don't expect tests that rely on
// deployments to work on clusters before that.
//
// TODO(ihmccreery): remove once we don't care about v1.1 anymore, (tentatively in v1.4).
deploymentsVersion = version.MustParse("v1.2.0-alpha.7.726")
// Pod probe parameters were introduced in #15967 (v1.2) so we dont expect tests that use
// these probe parameters to work on clusters before that.
//
// TODO(ihmccreery): remove once we don't care about v1.1 anymore, (tentatively in v1.4).
podProbeParametersVersion = version.MustParse("v1.2.0-alpha.4")
)
var _ = framework.KubeDescribe("Kubectl client", func() {
defer GinkgoRecover()
f := framework.NewDefaultFramework("kubectl")
// Reustable cluster state function. This won't be adversly affected by lazy initialization of framework.
clusterState := func() *framework.ClusterVerification {
return f.NewClusterVerification(
framework.PodStateVerification{
Selectors: map[string]string{"app": "redis"},
ValidPhases: []api.PodPhase{api.PodRunning /*api.PodPending*/},
})
}
// Customized Wait / ForEach wrapper for this test. These demonstrate the
// idiomatic way to wrap the ClusterVerification structs for syntactic sugar in large
// test files.
waitFor := func(atLeast int) {
// 60 seconds can be flakey for some of the containers.
clusterState().WaitFor(atLeast, 90*time.Second)
}
forEachPod := func(podFunc func(p api.Pod)) {
clusterState().ForEach(podFunc)
}
var c *client.Client
var ns string
BeforeEach(func() {
c = f.Client
ns = f.Namespace.Name
})
framework.KubeDescribe("Update Demo", func() {
var updateDemoRoot, nautilusPath, kittenPath string
BeforeEach(func() {
updateDemoRoot = filepath.Join(framework.TestContext.RepoRoot, "docs/user-guide/update-demo")
nautilusPath = filepath.Join(updateDemoRoot, "nautilus-rc.yaml")
kittenPath = filepath.Join(updateDemoRoot, "kitten-rc.yaml")
})
It("should create and stop a replication controller [Conformance]", func() {
defer framework.Cleanup(nautilusPath, ns, updateDemoSelector)
By("creating a replication controller")
framework.RunKubectlOrDie("create", "-f", nautilusPath, fmt.Sprintf("--namespace=%v", ns))
framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
})
It("should scale a replication controller [Conformance]", func() {
defer framework.Cleanup(nautilusPath, ns, updateDemoSelector)
By("creating a replication controller")
framework.RunKubectlOrDie("create", "-f", nautilusPath, fmt.Sprintf("--namespace=%v", ns))
framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
By("scaling down the replication controller")
framework.RunKubectlOrDie("scale", "rc", "update-demo-nautilus", "--replicas=1", "--timeout=5m", fmt.Sprintf("--namespace=%v", ns))
framework.ValidateController(c, nautilusImage, 1, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
By("scaling up the replication controller")
framework.RunKubectlOrDie("scale", "rc", "update-demo-nautilus", "--replicas=2", "--timeout=5m", fmt.Sprintf("--namespace=%v", ns))
framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
})
It("should do a rolling update of a replication controller [Conformance]", func() {
By("creating the initial replication controller")
framework.RunKubectlOrDie("create", "-f", nautilusPath, fmt.Sprintf("--namespace=%v", ns))
framework.ValidateController(c, nautilusImage, 2, "update-demo", updateDemoSelector, getUDData("nautilus.jpg", ns), ns)
By("rolling-update to new replication controller")
framework.RunKubectlOrDie("rolling-update", "update-demo-nautilus", "--update-period=1s", "-f", kittenPath, fmt.Sprintf("--namespace=%v", ns))
framework.ValidateController(c, kittenImage, 2, "update-demo", updateDemoSelector, getUDData("kitten.jpg", ns), ns)
// Everything will hopefully be cleaned up when the namespace is deleted.
})
})
framework.KubeDescribe("Guestbook application", func() {
var guestbookPath string
BeforeEach(func() {
guestbookPath = filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook")
})
It("should create and stop a working application [Conformance]", func() {
framework.SkipUnlessServerVersionGTE(deploymentsVersion, c)
defer framework.Cleanup(guestbookPath, ns, frontendSelector, redisMasterSelector, redisSlaveSelector)
By("creating all guestbook components")
framework.RunKubectlOrDie("create", "-f", guestbookPath, fmt.Sprintf("--namespace=%v", ns))
By("validating guestbook app")
validateGuestbookApp(c, ns)
})
})
framework.KubeDescribe("Simple pod", func() {
var podPath string
BeforeEach(func() {
podPath = filepath.Join(framework.TestContext.RepoRoot, "test", "e2e", "testing-manifests", "kubectl", "pod-with-readiness-probe.yaml")
By(fmt.Sprintf("creating the pod from %v", podPath))
framework.RunKubectlOrDie("create", "-f", podPath, fmt.Sprintf("--namespace=%v", ns))
framework.CheckPodsRunningReady(c, ns, []string{simplePodName}, framework.PodStartTimeout)
})
AfterEach(func() {
framework.Cleanup(podPath, ns, simplePodSelector)
})
It("should support exec", func() {
By("executing a command in the container")
execOutput := framework.RunKubectlOrDie("exec", fmt.Sprintf("--namespace=%v", ns), simplePodName, "echo", "running", "in", "container")
if e, a := "running in container", execOutput; e != a {
framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
}
By("executing a command in the container with noninteractive stdin")
execOutput = framework.NewKubectlCommand("exec", fmt.Sprintf("--namespace=%v", ns), "-i", simplePodName, "cat").
WithStdinData("abcd1234").
ExecOrDie()
if e, a := "abcd1234", execOutput; e != a {
framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
}
// pretend that we're a user in an interactive shell
r, closer, err := newBlockingReader("echo hi\nexit\n")
if err != nil {
framework.Failf("Error creating blocking reader: %v", err)
}
// NOTE this is solely for test cleanup!
defer closer.Close()
By("executing a command in the container with pseudo-interactive stdin")
execOutput = framework.NewKubectlCommand("exec", fmt.Sprintf("--namespace=%v", ns), "-i", simplePodName, "bash").
WithStdinReader(r).
ExecOrDie()
if e, a := "hi", execOutput; e != a {
framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", e, a)
}
})
It("should support exec through an HTTP proxy", func() {
// Note: We are skipping local since we want to verify an apiserver with HTTPS.
// At this time local only supports plain HTTP.
framework.SkipIfProviderIs("local")
// Fail if the variable isn't set
if framework.TestContext.Host == "" {
framework.Failf("--host variable must be set to the full URI to the api server on e2e run.")
}
// Make sure the apiServer is set to what kubectl requires
apiServer := framework.TestContext.Host
apiServerUrl, err := url.Parse(apiServer)
if err != nil {
framework.Failf("Unable to parse URL %s. Error=%s", apiServer, err)
}
apiServerUrl.Scheme = "https"
if !strings.Contains(apiServer, ":443") {
apiServerUrl.Host = apiServerUrl.Host + ":443"
}
apiServer = apiServerUrl.String()
// Build the static kubectl
By("Finding a static kubectl for upload")
testStaticKubectlPath, err := findBinary("kubectl", "linux/386")
if err != nil {
framework.Logf("No kubectl found: %v.\nAttempting a local build...", err)
// Fall back to trying to build a local static kubectl
kubectlContainerPath := path.Join(framework.TestContext.RepoRoot, "/examples/kubectl-container/")
if _, err := os.Stat(path.Join(framework.TestContext.RepoRoot, "hack/build-go.sh")); err != nil {
framework.Failf("Can't build static kubectl due to missing hack/build-go.sh. Error=%s", err)
}
By("Building a static kubectl for upload")
staticKubectlBuild := exec.Command("make", "-C", kubectlContainerPath)
if out, err := staticKubectlBuild.Output(); err != nil {
framework.Failf("Unable to create static kubectl. Error=%s, Output=%q", err, out)
}
// Verify the static kubectl path
testStaticKubectlPath = path.Join(kubectlContainerPath, "kubectl")
_, err := os.Stat(testStaticKubectlPath)
if err != nil {
framework.Failf("static kubectl path could not be found in %s. Error=%s", testStaticKubectlPath, err)
}
}
By(fmt.Sprintf("Using the kubectl in %s", testStaticKubectlPath))
// Verify the kubeconfig path
kubeConfigFilePath := framework.TestContext.KubeConfig
_, err = os.Stat(kubeConfigFilePath)
if err != nil {
framework.Failf("kube config path could not be accessed. Error=%s", err)
}
// start exec-proxy-tester container
netexecPodPath := filepath.Join(framework.TestContext.RepoRoot, "test/images/netexec/pod.yaml")
// Add "validate=false" if the server version is less than 1.2.
// More details: https://github.com/kubernetes/kubernetes/issues/22884.
validateFlag := "--validate=true"
gte, err := framework.ServerVersionGTE(podProbeParametersVersion, c)
if err != nil {
framework.Failf("Failed to get server version: %v", err)
}
if !gte {
validateFlag = "--validate=false"
}
framework.RunKubectlOrDie("create", "-f", netexecPodPath, fmt.Sprintf("--namespace=%v", ns), validateFlag)
framework.CheckPodsRunningReady(c, ns, []string{netexecContainer}, framework.PodStartTimeout)
// Clean up
defer framework.Cleanup(netexecPodPath, ns, netexecPodSelector)
// Upload kubeconfig
type NetexecOutput struct {
Output string `json:"output"`
Error string `json:"error"`
}
var uploadConfigOutput NetexecOutput
// Upload the kubeconfig file
By("uploading kubeconfig to netexec")
pipeConfigReader, postConfigBodyWriter, err := newStreamingUpload(kubeConfigFilePath)
if err != nil {
framework.Failf("unable to create streaming upload. Error: %s", err)
}
subResourceProxyAvailable, err := framework.ServerVersionGTE(framework.SubResourcePodProxyVersion, c)
if err != nil {
framework.Failf("Unable to determine server version. Error: %s", err)
}
var resp []byte
if subResourceProxyAvailable {
resp, err = c.Post().
Namespace(ns).
Name("netexec").
Resource("pods").
SubResource("proxy").
Suffix("upload").
SetHeader("Content-Type", postConfigBodyWriter.FormDataContentType()).
Body(pipeConfigReader).
Do().Raw()
} else {
resp, err = c.Post().
Prefix("proxy").
Namespace(ns).
Name("netexec").
Resource("pods").
Suffix("upload").
SetHeader("Content-Type", postConfigBodyWriter.FormDataContentType()).
Body(pipeConfigReader).
Do().Raw()
}
if err != nil {
framework.Failf("Unable to upload kubeconfig to the remote exec server due to error: %s", err)
}
if err := json.Unmarshal(resp, &uploadConfigOutput); err != nil {
framework.Failf("Unable to read the result from the netexec server. Error: %s", err)
}
kubecConfigRemotePath := uploadConfigOutput.Output
// Upload
pipeReader, postBodyWriter, err := newStreamingUpload(testStaticKubectlPath)
if err != nil {
framework.Failf("unable to create streaming upload. Error: %s", err)
}
By("uploading kubectl to netexec")
var uploadOutput NetexecOutput
// Upload the kubectl binary
if subResourceProxyAvailable {
resp, err = c.Post().
Namespace(ns).
Name("netexec").
Resource("pods").
SubResource("proxy").
Suffix("upload").
SetHeader("Content-Type", postBodyWriter.FormDataContentType()).
Body(pipeReader).
Do().Raw()
} else {
resp, err = c.Post().
Prefix("proxy").
Namespace(ns).
Name("netexec").
Resource("pods").
Suffix("upload").
SetHeader("Content-Type", postBodyWriter.FormDataContentType()).
Body(pipeReader).
Do().Raw()
}
if err != nil {
framework.Failf("Unable to upload kubectl binary to the remote exec server due to error: %s", err)
}
if err := json.Unmarshal(resp, &uploadOutput); err != nil {
framework.Failf("Unable to read the result from the netexec server. Error: %s", err)
}
uploadBinaryName := uploadOutput.Output
// Verify that we got the expected response back in the body
if !strings.HasPrefix(uploadBinaryName, "/uploads/") {
framework.Failf("Unable to upload kubectl binary to remote exec server. /uploads/ not in response. Response: %s", uploadBinaryName)
}
for _, proxyVar := range []string{"https_proxy", "HTTPS_PROXY"} {
By("Running kubectl in netexec via an HTTP proxy using " + proxyVar)
// start the proxy container
goproxyPodPath := filepath.Join(framework.TestContext.RepoRoot, "test/images/goproxy/pod.yaml")
framework.RunKubectlOrDie("create", "-f", goproxyPodPath, fmt.Sprintf("--namespace=%v", ns))
framework.CheckPodsRunningReady(c, ns, []string{goproxyContainer}, framework.PodStartTimeout)
// get the proxy address
goproxyPod, err := c.Pods(ns).Get(goproxyContainer)
if err != nil {
framework.Failf("Unable to get the goproxy pod. Error: %s", err)
}
proxyAddr := fmt.Sprintf("http://%s:8080", goproxyPod.Status.PodIP)
shellCommand := fmt.Sprintf("%s=%s .%s --kubeconfig=%s --server=%s --namespace=%s exec nginx echo running in container",
proxyVar, proxyAddr, uploadBinaryName, kubecConfigRemotePath, apiServer, ns)
framework.Logf("About to remote exec: %v", shellCommand)
// Execute kubectl on remote exec server.
var netexecShellOutput []byte
if subResourceProxyAvailable {
netexecShellOutput, err = c.Post().
Namespace(ns).
Name("netexec").
Resource("pods").
SubResource("proxy").
Suffix("shell").
Param("shellCommand", shellCommand).
Do().Raw()
} else {
netexecShellOutput, err = c.Post().
Prefix("proxy").
Namespace(ns).
Name("netexec").
Resource("pods").
Suffix("shell").
Param("shellCommand", shellCommand).
Do().Raw()
}
if err != nil {
framework.Failf("Unable to execute kubectl binary on the remote exec server due to error: %s", err)
}
var netexecOuput NetexecOutput
if err := json.Unmarshal(netexecShellOutput, &netexecOuput); err != nil {
framework.Failf("Unable to read the result from the netexec server. Error: %s", err)
}
// Get (and print!) the proxy logs here, so
// they'll be present in case the below check
// fails the test, to help diagnose #19500 if
// it recurs.
proxyLog := framework.RunKubectlOrDie("log", "goproxy", fmt.Sprintf("--namespace=%v", ns))
// Verify we got the normal output captured by the exec server
expectedExecOutput := "running in container\n"
if netexecOuput.Output != expectedExecOutput {
framework.Failf("Unexpected kubectl exec output. Wanted %q, got %q", expectedExecOutput, netexecOuput.Output)
}
// Verify the proxy server logs saw the connection
expectedProxyLog := fmt.Sprintf("Accepting CONNECT to %s", strings.TrimRight(strings.TrimLeft(framework.TestContext.Host, "https://"), "/api"))
if !strings.Contains(proxyLog, expectedProxyLog) {
framework.Failf("Missing expected log result on proxy server for %s. Expected: %q, got %q", proxyVar, expectedProxyLog, proxyLog)
}
// Clean up the goproxyPod
framework.Cleanup(goproxyPodPath, ns, goproxyPodSelector)
}
})
It("should support inline execution and attach", func() {
framework.SkipUnlessServerVersionGTE(jobsVersion, c)
nsFlag := fmt.Sprintf("--namespace=%v", ns)
By("executing a command with run and attach with stdin")
runOutput := framework.NewKubectlCommand(nsFlag, "run", "run-test", "--image="+busyboxImage, "--restart=Never", "--attach=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
WithStdinData("abcd1234").
ExecOrDie()
Expect(runOutput).To(ContainSubstring("abcd1234"))
Expect(runOutput).To(ContainSubstring("stdin closed"))
Expect(c.Extensions().Jobs(ns).Delete("run-test", nil)).To(BeNil())
By("executing a command with run and attach without stdin")
runOutput = framework.NewKubectlCommand(fmt.Sprintf("--namespace=%v", ns), "run", "run-test-2", "--image="+busyboxImage, "--restart=Never", "--attach=true", "--leave-stdin-open=true", "--", "sh", "-c", "cat && echo 'stdin closed'").
WithStdinData("abcd1234").
ExecOrDie()
Expect(runOutput).ToNot(ContainSubstring("abcd1234"))
Expect(runOutput).To(ContainSubstring("stdin closed"))
Expect(c.Extensions().Jobs(ns).Delete("run-test-2", nil)).To(BeNil())
By("executing a command with run and attach with stdin with open stdin should remain running")
runOutput = framework.NewKubectlCommand(nsFlag, "run", "run-test-3", "--image="+busyboxImage, "--restart=Never", "--attach=true", "--leave-stdin-open=true", "--stdin", "--", "sh", "-c", "cat && echo 'stdin closed'").
WithStdinData("abcd1234\n").
ExecOrDie()
Expect(runOutput).ToNot(ContainSubstring("stdin closed"))
runTestPod, _, err := util.GetFirstPod(c, ns, labels.SelectorFromSet(map[string]string{"run": "run-test-3"}))
if err != nil {
os.Exit(1)
}
if !framework.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, time.Minute) {
framework.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")
}
// NOTE: we cannot guarantee our output showed up in the container logs before stdin was closed, so we have
// to loop test.
err = wait.PollImmediate(time.Second, time.Minute, func() (bool, error) {
if !framework.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, 1*time.Second) {
framework.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")
}
logOutput := framework.RunKubectlOrDie(nsFlag, "logs", runTestPod.Name)
Expect(logOutput).ToNot(ContainSubstring("stdin closed"))
return strings.Contains(logOutput, "abcd1234"), nil
})
if err != nil {
os.Exit(1)
}
Expect(err).To(BeNil())
Expect(c.Extensions().Jobs(ns).Delete("run-test-3", nil)).To(BeNil())
})
It("should support port-forward", func() {
By("forwarding the container port to a local port")
cmd := runPortForward(ns, simplePodName, simplePodPort)
defer cmd.Stop()
By("curling local port output")
localAddr := fmt.Sprintf("http://localhost:%d", cmd.port)
body, err := curl(localAddr)
framework.Logf("got: %s", body)
if err != nil {
framework.Failf("Failed http.Get of forwarded port (%s): %v", localAddr, err)
}
if !strings.Contains(body, nginxDefaultOutput) {
framework.Failf("Container port output missing expected value. Wanted:'%s', got: %s", nginxDefaultOutput, body)
}
})
})
framework.KubeDescribe("Kubectl api-versions", func() {
It("should check if v1 is in available api versions [Conformance]", func() {
By("validating api verions")
output := framework.RunKubectlOrDie("api-versions")
if !strings.Contains(output, "v1") {
framework.Failf("No v1 in kubectl api-versions")
}
})
})
framework.KubeDescribe("Kubectl apply", func() {
It("should apply a new configuration to an existing RC", func() {
mkpath := func(file string) string {
return filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook-go", file)
}
controllerJson := mkpath("redis-master-controller.json")
nsFlag := fmt.Sprintf("--namespace=%v", ns)
By("creating Redis RC")
framework.RunKubectlOrDie("create", "-f", controllerJson, nsFlag)
By("applying a modified configuration")
stdin := modifyReplicationControllerConfiguration(controllerJson)
framework.NewKubectlCommand("apply", "-f", "-", nsFlag).
WithStdinReader(stdin).
ExecOrDie()
By("checking the result")
forEachReplicationController(c, ns, "app", "redis", validateReplicationControllerConfiguration)
})
It("should reuse nodePort when apply to an existing SVC", func() {
mkpath := func(file string) string {
return filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook-go", file)
}
serviceJson := mkpath("redis-master-service.json")
nsFlag := fmt.Sprintf("--namespace=%v", ns)
By("creating Redis SVC")
framework.RunKubectlOrDie("create", "-f", serviceJson, nsFlag)
By("getting the original nodePort")
originalNodePort := framework.RunKubectlOrDie("get", "service", "redis-master", nsFlag, "-o", "jsonpath={.spec.ports[0].nodePort}")
By("applying the same configuration")
framework.RunKubectlOrDie("apply", "-f", serviceJson, nsFlag)
By("getting the nodePort after applying configuration")
currentNodePort := framework.RunKubectlOrDie("get", "service", "redis-master", nsFlag, "-o", "jsonpath={.spec.ports[0].nodePort}")
By("checking the result")
if originalNodePort != currentNodePort {
framework.Failf("nodePort should keep the same")
}
})
})
framework.KubeDescribe("Kubectl cluster-info", func() {
It("should check if Kubernetes master services is included in cluster-info [Conformance]", func() {
By("validating cluster-info")
output := framework.RunKubectlOrDie("cluster-info")
// Can't check exact strings due to terminal control commands (colors)
requiredItems := []string{"Kubernetes master", "is running at"}
if framework.ProviderIs("gce", "gke") {
requiredItems = append(requiredItems, "KubeDNS", "Heapster")
}
for _, item := range requiredItems {
if !strings.Contains(output, item) {
framework.Failf("Missing %s in kubectl cluster-info", item)
}
}
})
})
framework.KubeDescribe("Kubectl describe", func() {
It("should check if kubectl describe prints relevant information for rc and pods [Conformance]", func() {
framework.SkipUnlessServerVersionGTE(nodePortsOptionalVersion, c)
mkpath := func(file string) string {
return filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook-go", file)
}
controllerJson := mkpath("redis-master-controller.json")
serviceJson := mkpath("redis-master-service.json")
nsFlag := fmt.Sprintf("--namespace=%v", ns)
framework.RunKubectlOrDie("create", "-f", controllerJson, nsFlag)
framework.RunKubectlOrDie("create", "-f", serviceJson, nsFlag)
// Wait for the redis pods to come online...
waitFor(1)
// Pod
forEachPod(func(pod api.Pod) {
output := framework.RunKubectlOrDie("describe", "pod", pod.Name, nsFlag)
requiredStrings := [][]string{
{"Name:", "redis-master-"},
{"Namespace:", ns},
{"Node:"},
{"Labels:", "app=redis", "role=master"},
{"Status:", "Running"},
{"IP:"},
{"Controllers:", "ReplicationController/redis-master"},
{"Image:", "redis"},
{"cpu:", "BestEffort"},
{"State:", "Running"},
}
checkOutput(output, requiredStrings)
})
// Rc
output := framework.RunKubectlOrDie("describe", "rc", "redis-master", nsFlag)
requiredStrings := [][]string{
{"Name:", "redis-master"},
{"Namespace:", ns},
{"Image(s):", "redis"},
{"Selector:", "app=redis,role=master"},
{"Labels:", "app=redis,role=master"},
{"Replicas:", "1 current", "1 desired"},
{"Pods Status:", "1 Running", "0 Waiting", "0 Succeeded", "0 Failed"},
// {"Events:"} would ordinarily go in the list
// here, but in some rare circumstances the
// events are delayed, and instead kubectl
// prints "No events." This string will match
// either way.
{"vents"}}
checkOutput(output, requiredStrings)
// Service
output = framework.RunKubectlOrDie("describe", "service", "redis-master", nsFlag)
requiredStrings = [][]string{
{"Name:", "redis-master"},
{"Namespace:", ns},
{"Labels:", "app=redis", "role=master"},
{"Selector:", "app=redis", "role=master"},
{"Type:", "ClusterIP"},
{"IP:"},
{"Port:", "<unset>", "6379/TCP"},
{"Endpoints:"},
{"Session Affinity:", "None"}}
checkOutput(output, requiredStrings)
// Node
// It should be OK to list unschedulable Nodes here.
nodes, err := c.Nodes().List(api.ListOptions{})
Expect(err).NotTo(HaveOccurred())
node := nodes.Items[0]
output = framework.RunKubectlOrDie("describe", "node", node.Name)
requiredStrings = [][]string{
{"Name:", node.Name},
{"Labels:"},
{"CreationTimestamp:"},
{"Conditions:"},
{"Type", "Status", "LastHeartbeatTime", "LastTransitionTime", "Reason", "Message"},
{"Addresses:"},
{"Capacity:"},
{"Version:"},
{"Kernel Version:"},
{"OS Image:"},
{"Container Runtime Version:"},
{"Kubelet Version:"},
{"Kube-Proxy Version:"},
{"Pods:"}}
checkOutput(output, requiredStrings)
// Namespace
output = framework.RunKubectlOrDie("describe", "namespace", ns)
requiredStrings = [][]string{
{"Name:", ns},
{"Labels:"},
{"Status:", "Active"}}
checkOutput(output, requiredStrings)
// Quota and limitrange are skipped for now.
})
})
framework.KubeDescribe("Kubectl expose", func() {
It("should create services for rc [Conformance]", func() {
mkpath := func(file string) string {
return filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook-go", file)
}
controllerJson := mkpath("redis-master-controller.json")
nsFlag := fmt.Sprintf("--namespace=%v", ns)
redisPort := 6379
By("creating Redis RC")
framework.Logf("namespace %v", ns)
framework.RunKubectlOrDie("create", "-f", controllerJson, nsFlag)
// It may take a while for the pods to get registered in some cases, wait to be sure.
By("Waiting for Redis master to start.")
waitFor(1)
forEachPod(func(pod api.Pod) {
framework.Logf("wait on redis-master startup in %v ", ns)
framework.LookForStringInLog(ns, pod.Name, "redis-master", "The server is now ready to accept connections", framework.PodStartTimeout)
})
validateService := func(name string, servicePort int, timeout time.Duration) {
err := wait.Poll(framework.Poll, timeout, func() (bool, error) {
endpoints, err := c.Endpoints(ns).Get(name)
if err != nil {
if apierrs.IsNotFound(err) {
err = nil
}
framework.Logf("Get endpoints failed (interval %v): %v", framework.Poll, err)
return false, err
}
uidToPort := getContainerPortsByPodUID(endpoints)
if len(uidToPort) == 0 {
framework.Logf("No endpoint found, retrying")
return false, nil
}
if len(uidToPort) > 1 {
Fail("Too many endpoints found")
}
for _, port := range uidToPort {
if port[0] != redisPort {
framework.Failf("Wrong endpoint port: %d", port[0])
}
}
return true, nil
})
Expect(err).NotTo(HaveOccurred())
service, err := c.Services(ns).Get(name)
Expect(err).NotTo(HaveOccurred())
if len(service.Spec.Ports) != 1 {
framework.Failf("1 port is expected")
}
port := service.Spec.Ports[0]
if port.Port != servicePort {
framework.Failf("Wrong service port: %d", port.Port)
}
if port.TargetPort.IntValue() != redisPort {
framework.Failf("Wrong target port: %d")
}
}
By("exposing RC")
framework.RunKubectlOrDie("expose", "rc", "redis-master", "--name=rm2", "--port=1234", fmt.Sprintf("--target-port=%d", redisPort), nsFlag)
framework.WaitForService(c, ns, "rm2", true, framework.Poll, framework.ServiceStartTimeout)
validateService("rm2", 1234, framework.ServiceStartTimeout)
By("exposing service")
framework.RunKubectlOrDie("expose", "service", "rm2", "--name=rm3", "--port=2345", fmt.Sprintf("--target-port=%d", redisPort), nsFlag)
framework.WaitForService(c, ns, "rm3", true, framework.Poll, framework.ServiceStartTimeout)
validateService("rm3", 2345, framework.ServiceStartTimeout)
})
})
framework.KubeDescribe("Kubectl label", func() {
var podPath string
var nsFlag string
BeforeEach(func() {
podPath = filepath.Join(framework.TestContext.RepoRoot, "docs/user-guide/pod.yaml")
By("creating the pod")
nsFlag = fmt.Sprintf("--namespace=%v", ns)
framework.RunKubectlOrDie("create", "-f", podPath, nsFlag)
framework.CheckPodsRunningReady(c, ns, []string{simplePodName}, framework.PodStartTimeout)
})
AfterEach(func() {
framework.Cleanup(podPath, ns, simplePodSelector)
})
It("should update the label on a resource [Conformance]", func() {
labelName := "testing-label"
labelValue := "testing-label-value"
By("adding the label " + labelName + " with value " + labelValue + " to a pod")
framework.RunKubectlOrDie("label", "pods", simplePodName, labelName+"="+labelValue, nsFlag)
By("verifying the pod has the label " + labelName + " with the value " + labelValue)
output := framework.RunKubectlOrDie("get", "pod", simplePodName, "-L", labelName, nsFlag)
if !strings.Contains(output, labelValue) {
framework.Failf("Failed updating label " + labelName + " to the pod " + simplePodName)
}
By("removing the label " + labelName + " of a pod")
framework.RunKubectlOrDie("label", "pods", simplePodName, labelName+"-", nsFlag)
By("verifying the pod doesn't have the label " + labelName)
output = framework.RunKubectlOrDie("get", "pod", simplePodName, "-L", labelName, nsFlag)
if strings.Contains(output, labelValue) {
framework.Failf("Failed removing label " + labelName + " of the pod " + simplePodName)
}
})
})
framework.KubeDescribe("Kubectl logs", func() {
var rcPath string
var nsFlag string
containerName := "redis-master"
BeforeEach(func() {
mkpath := func(file string) string {
return filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook-go", file)
}
rcPath = mkpath("redis-master-controller.json")
By("creating an rc")
nsFlag = fmt.Sprintf("--namespace=%v", ns)
framework.RunKubectlOrDie("create", "-f", rcPath, nsFlag)
})
AfterEach(func() {
framework.Cleanup(rcPath, ns, simplePodSelector)
})
It("should be able to retrieve and filter logs [Conformance]", func() {
framework.SkipUnlessServerVersionGTE(extendedPodLogFilterVersion, c)
forEachPod(func(pod api.Pod) {
By("checking for a matching strings")
_, err := framework.LookForStringInLog(ns, pod.Name, containerName, "The server is now ready to accept connections", framework.PodStartTimeout)
Expect(err).NotTo(HaveOccurred())
By("limiting log lines")
out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--tail=1")
Expect(len(out)).NotTo(BeZero())
Expect(len(strings.Split(out, "\n"))).To(Equal(1))
By("limiting log bytes")
out = framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--limit-bytes=1")
Expect(len(strings.Split(out, "\n"))).To(Equal(1))
Expect(len(out)).To(Equal(1))
By("exposing timestamps")
out = framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--tail=1", "--timestamps")
lines := strings.Split(out, "\n")
Expect(len(lines)).To(Equal(1))
words := strings.Split(lines[0], " ")
Expect(len(words)).To(BeNumerically(">", 1))
if _, err := time.Parse(time.RFC3339Nano, words[0]); err != nil {
if _, err := time.Parse(time.RFC3339, words[0]); err != nil {
framework.Failf("expected %q to be RFC3339 or RFC3339Nano", words[0])
}
}
By("restricting to a time range")
// Note: we must wait at least two seconds,
// because the granularity is only 1 second and
// it could end up rounding the wrong way.
time.Sleep(2500 * time.Millisecond) // ensure that startup logs on the node are seen as older than 1s
recent_out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--since=1s")
recent := len(strings.Split(recent_out, "\n"))
older_out := framework.RunKubectlOrDie("log", pod.Name, containerName, nsFlag, "--since=24h")
older := len(strings.Split(older_out, "\n"))
Expect(recent).To(BeNumerically("<", older), "expected recent(%v) to be less than older(%v)\nrecent lines:\n%v\nolder lines:\n%v\n", recent, older, recent_out, older_out)
})
})
})
framework.KubeDescribe("Kubectl patch", func() {
It("should add annotations for pods in rc [Conformance]", func() {
mkpath := func(file string) string {
return filepath.Join(framework.TestContext.RepoRoot, "examples/guestbook-go", file)
}
controllerJson := mkpath("redis-master-controller.json")
nsFlag := fmt.Sprintf("--namespace=%v", ns)
By("creating Redis RC")
framework.RunKubectlOrDie("create", "-f", controllerJson, nsFlag)
By("patching all pods")
forEachPod(func(pod api.Pod) {
framework.RunKubectlOrDie("patch", "pod", pod.Name, nsFlag, "-p", "{\"metadata\":{\"annotations\":{\"x\":\"y\"}}}")
})
By("checking annotations")
forEachPod(func(pod api.Pod) {
found := false
for key, val := range pod.Annotations {
if key == "x" && val == "y" {
found = true
}
}
if !found {
framework.Failf("Added annotation not found")
}
})
})
})
framework.KubeDescribe("Kubectl version", func() {
It("should check is all data is printed [Conformance]", func() {
version := framework.RunKubectlOrDie("version")
requiredItems := []string{"Client Version:", "Server Version:", "Major:", "Minor:", "GitCommit:"}
for _, item := range requiredItems {
if !strings.Contains(version, item) {
framework.Failf("Required item %s not found in %s", item, version)
}
}
})
})
framework.KubeDescribe("Kubectl run default", func() {
var nsFlag string
var name string
var cleanUp func()
BeforeEach(func() {
nsFlag = fmt.Sprintf("--namespace=%v", ns)
gte, err := framework.ServerVersionGTE(deploymentsVersion, c)
if err != nil {
framework.Failf("Failed to get server version: %v", err)
}
if gte {
name = "e2e-test-nginx-deployment"
cleanUp = func() { framework.RunKubectlOrDie("delete", "deployment", name, nsFlag) }
} else {
name = "e2e-test-nginx-rc"
cleanUp = func() { framework.RunKubectlOrDie("delete", "rc", name, nsFlag) }
}
})
AfterEach(func() {
cleanUp()
})
It("should create an rc or deployment from an image [Conformance]", func() {
By("running the image " + nginxImage)
framework.RunKubectlOrDie("run", name, "--image="+nginxImage, nsFlag)
By("verifying the pod controlled by " + name + " gets created")
label := labels.SelectorFromSet(labels.Set(map[string]string{"run": name}))
podlist, err := framework.WaitForPodsWithLabel(c, ns, label)
if err != nil {
framework.Failf("Failed getting pod controlled by %s: %v", name, err)
}
pods := podlist.Items
if pods == nil || len(pods) != 1 || len(pods[0].Spec.Containers) != 1 || pods[0].Spec.Containers[0].Image != nginxImage {
framework.RunKubectlOrDie("get", "pods", "-L", "run", nsFlag)
framework.Failf("Failed creating 1 pod with expected image %s. Number of pods = %v", nginxImage, len(pods))
}
})
})
framework.KubeDescribe("Kubectl run rc", func() {
var nsFlag string
var rcName string
BeforeEach(func() {
nsFlag = fmt.Sprintf("--namespace=%v", ns)
rcName = "e2e-test-nginx-rc"
})
AfterEach(func() {
framework.RunKubectlOrDie("delete", "rc", rcName, nsFlag)
})
It("should create an rc from an image [Conformance]", func() {
By("running the image " + nginxImage)
framework.RunKubectlOrDie("run", rcName, "--image="+nginxImage, "--generator=run/v1", nsFlag)
By("verifying the rc " + rcName + " was created")
rc, err := c.ReplicationControllers(ns).Get(rcName)
if err != nil {
framework.Failf("Failed getting rc %s: %v", rcName, err)
}
containers := rc.Spec.Template.Spec.Containers
if containers == nil || len(containers) != 1 || containers[0].Image != nginxImage {
framework.Failf("Failed creating rc %s for 1 pod with expected image %s", rcName, nginxImage)
}
By("verifying the pod controlled by rc " + rcName + " was created")
label := labels.SelectorFromSet(labels.Set(map[string]string{"run": rcName}))