/
pods.go
339 lines (303 loc) · 12 KB
/
pods.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
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package node
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strconv"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/kubernetes/test/e2e/framework"
e2elog "k8s.io/kubernetes/test/e2e/framework/log"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
imageutils "k8s.io/kubernetes/test/utils/image"
)
var _ = SIGDescribe("Pods Extended", func() {
f := framework.NewDefaultFramework("pods")
framework.KubeDescribe("Delete Grace Period", func() {
var podClient *framework.PodClient
ginkgo.BeforeEach(func() {
podClient = f.PodClient()
})
/*
Release : v1.15
Testname: Pods, delete grace period
Description: Create a pod, make sure it is running. Create a 'kubectl local proxy', capture the port the proxy is listening. Using the http client send a ‘delete’ with gracePeriodSeconds=30. Pod SHOULD get deleted within 30 seconds.
*/
framework.ConformanceIt("should be submitted and removed", func() {
ginkgo.By("creating the pod")
name := "pod-submit-remove-" + string(uuid.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "nginx",
Image: imageutils.GetE2EImage(imageutils.Nginx),
},
},
},
}
ginkgo.By("setting up selector")
selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options := metav1.ListOptions{LabelSelector: selector.String()}
pods, err := podClient.List(options)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to query for pod")
gomega.Expect(len(pods.Items)).To(gomega.Equal(0))
options = metav1.ListOptions{
LabelSelector: selector.String(),
ResourceVersion: pods.ListMeta.ResourceVersion,
}
ginkgo.By("submitting the pod to kubernetes")
podClient.Create(pod)
ginkgo.By("verifying the pod is in kubernetes")
selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options = metav1.ListOptions{LabelSelector: selector.String()}
pods, err = podClient.List(options)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to query for pod")
gomega.Expect(len(pods.Items)).To(gomega.Equal(1))
// We need to wait for the pod to be running, otherwise the deletion
// may be carried out immediately rather than gracefully.
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
// save the running pod
pod, err = podClient.Get(pod.Name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to GET scheduled pod")
// start local proxy, so we can send graceful deletion over query string, rather than body parameter
cmd := framework.KubectlCmd("proxy", "-p", "0")
stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to start up proxy")
defer stdout.Close()
defer stderr.Close()
defer framework.TryKill(cmd)
buf := make([]byte, 128)
var n int
n, err = stdout.Read(buf)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to read from kubectl proxy stdout")
output := string(buf[:n])
proxyRegexp := regexp.MustCompile("Starting to serve on 127.0.0.1:([0-9]+)")
match := proxyRegexp.FindStringSubmatch(output)
gomega.Expect(len(match)).To(gomega.Equal(2))
port, err := strconv.Atoi(match[1])
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to convert port into string")
endpoint := fmt.Sprintf("http://localhost:%d/api/v1/namespaces/%s/pods/%s?gracePeriodSeconds=30", port, pod.Namespace, pod.Name)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("DELETE", endpoint, nil)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to create http request")
ginkgo.By("deleting the pod gracefully")
rsp, err := client.Do(req)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to use http client to send delete")
gomega.Expect(rsp.StatusCode).Should(gomega.Equal(http.StatusOK), "failed to delete gracefully by client request")
var lastPod v1.Pod
err = json.NewDecoder(rsp.Body).Decode(&lastPod)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to decode graceful termination proxy response")
defer rsp.Body.Close()
ginkgo.By("verifying the kubelet observed the termination notice")
gomega.Expect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {
podList, err := framework.GetKubeletPods(f.ClientSet, pod.Spec.NodeName)
if err != nil {
e2elog.Logf("Unable to retrieve kubelet pods for node %v: %v", pod.Spec.NodeName, err)
return false, nil
}
for _, kubeletPod := range podList.Items {
if pod.Name != kubeletPod.Name {
continue
}
if kubeletPod.ObjectMeta.DeletionTimestamp == nil {
e2elog.Logf("deletion has not yet been observed")
return false, nil
}
return false, nil
}
e2elog.Logf("no pod exists with the name we were looking for, assuming the termination request was observed and completed")
return true, nil
})).NotTo(gomega.HaveOccurred(), "kubelet never observed the termination notice")
gomega.Expect(lastPod.DeletionTimestamp).ToNot(gomega.BeNil())
gomega.Expect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(gomega.BeZero())
selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options = metav1.ListOptions{LabelSelector: selector.String()}
pods, err = podClient.List(options)
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to query for pods")
gomega.Expect(len(pods.Items)).To(gomega.Equal(0))
})
})
framework.KubeDescribe("Pods Set QOS Class", func() {
var podClient *framework.PodClient
ginkgo.BeforeEach(func() {
podClient = f.PodClient()
})
/*
Release : v1.9
Testname: Pods, QOS
Description: Create a Pod with CPU and Memory request and limits. Pos status MUST have QOSClass set to PodQOSGuaranteed.
*/
framework.ConformanceIt("should be submitted and removed ", func() {
ginkgo.By("creating the pod")
name := "pod-qos-class-" + string(uuid.NewUUID())
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": name,
},
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "nginx",
Image: imageutils.GetE2EImage(imageutils.Nginx),
Resources: v1.ResourceRequirements{
Limits: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("100m"),
v1.ResourceMemory: resource.MustParse("100Mi"),
},
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("100m"),
v1.ResourceMemory: resource.MustParse("100Mi"),
},
},
},
},
},
}
ginkgo.By("submitting the pod to kubernetes")
podClient.Create(pod)
ginkgo.By("verifying QOS class is set on the pod")
pod, err := podClient.Get(name, metav1.GetOptions{})
gomega.Expect(err).NotTo(gomega.HaveOccurred(), "failed to query for pod")
gomega.Expect(pod.Status.QOSClass == v1.PodQOSGuaranteed)
})
})
ginkgo.It("should get killed, if pod exceed memory utilization limit", func() {
ginkgo.By("Creating a LimitRange")
min := getResourceList("100m", "100Mi", "100Mi")
max := getResourceList("500m", "500Mi", "500Mi")
defaultLimit := getResourceList("500m", "500Mi", "500Mi")
defaultRequest := getResourceList("100m", "200Mi", "200Mi")
maxLimitRequestRatio := v1.ResourceList{}
limitRange := newLimitRange("limit-range", v1.LimitTypeContainer,
min, max,
defaultLimit, defaultRequest,
maxLimitRequestRatio)
ginkgo.By("Submitting a LimitRange")
limitRange, err := f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Create(limitRange)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("creating a Pod with requested and limited resources")
pod := getResourcePod("pod-resource-max", "max-container")
pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(pod)
gomega.Expect(err).ShouldNot(gomega.HaveOccurred(), "failed created pod the cpu limit")
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
gomega.Expect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {
pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})
if err != nil {
e2elog.Logf("Unable to retrieve pod %v: %v", pod.Name, err)
return false, nil
}
if pod.Status.ContainerStatuses[0].State.Terminated != nil &&
pod.Status.ContainerStatuses[0].State.Terminated.Reason == "OOMKilled" &&
pod.Status.Phase == v1.PodFailed {
return true, nil
}
return false, nil
})).NotTo(gomega.HaveOccurred(), "cotaier not get killed")
ginkgo.By("Deleting a LimitRange")
err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Delete(limitRange.Name, nil)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
ginkgo.By("Verifying the deletion of LimitRange")
_, err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Get(limitRange.Name, metav1.GetOptions{})
gomega.Expect(err).Should(gomega.HaveOccurred())
ginkgo.By("creating a Pod with requested resources")
pod = getResourcePod("pod-resource-nolimit", "nolimit-container")
pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(pod)
gomega.Expect(err).ShouldNot(gomega.HaveOccurred(), "failed to created pod with above the cpu limit")
framework.ExpectNoError(f.WaitForPodRunning(pod.Name), "failed to created pod with above the memory limit")
pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})
gomega.Expect(err).ShouldNot(gomega.HaveOccurred(), "error getting pod")
})
})
// newLimitRange returns a limit range with specified data
func newLimitRange(name string, limitType v1.LimitType,
min, max,
defaultLimit, defaultRequest,
maxLimitRequestRatio v1.ResourceList) *v1.LimitRange {
return &v1.LimitRange{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Spec: v1.LimitRangeSpec{
Limits: []v1.LimitRangeItem{
{
Type: limitType,
Min: min,
Max: max,
Default: defaultLimit,
DefaultRequest: defaultRequest,
MaxLimitRequestRatio: maxLimitRequestRatio,
},
},
},
}
}
func getResourceList(cpu, memory string, ephemeralStorage string) v1.ResourceList {
res := v1.ResourceList{}
if cpu != "" {
res[v1.ResourceCPU] = resource.MustParse(cpu)
}
if memory != "" {
res[v1.ResourceMemory] = resource.MustParse(memory)
}
if ephemeralStorage != "" {
res[v1.ResourceEphemeralStorage] = resource.MustParse(ephemeralStorage)
}
return res
}
func getResourcePod(podName, containerName string) *v1.Pod {
return &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: containerName,
//imageutils.GetE2EImage(imageutils.BusyBox), busyBox image not suporting the stress.
Image: "polinux/stress",
Command: []string{"stress"},
Args: []string{"--vm", "1", "--vm-bytes", "5G", "--vm-hang", "1"},
Resources: v1.ResourceRequirements{
Requests: getResourceList("500m", "500Mi", "500Mi"),
},
},
},
RestartPolicy: v1.RestartPolicyNever,
},
}
}