kubelet.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package node
  14. import (
  15. "fmt"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/util/sets"
  22. "k8s.io/apimachinery/pkg/util/uuid"
  23. "k8s.io/apimachinery/pkg/util/wait"
  24. clientset "k8s.io/client-go/kubernetes"
  25. "k8s.io/kubernetes/test/e2e/framework"
  26. e2elog "k8s.io/kubernetes/test/e2e/framework/log"
  27. e2essh "k8s.io/kubernetes/test/e2e/framework/ssh"
  28. "k8s.io/kubernetes/test/e2e/framework/volume"
  29. testutils "k8s.io/kubernetes/test/utils"
  30. imageutils "k8s.io/kubernetes/test/utils/image"
  31. "github.com/onsi/ginkgo"
  32. "github.com/onsi/gomega"
  33. )
  34. const (
  35. // Interval to framework.Poll /runningpods on a node
  36. pollInterval = 1 * time.Second
  37. // Interval to framework.Poll /stats/container on a node
  38. containerStatsPollingInterval = 5 * time.Second
  39. // Maximum number of nodes that we constraint to
  40. maxNodesToCheck = 10
  41. )
  42. // getPodMatches returns a set of pod names on the given node that matches the
  43. // podNamePrefix and namespace.
  44. func getPodMatches(c clientset.Interface, nodeName string, podNamePrefix string, namespace string) sets.String {
  45. matches := sets.NewString()
  46. e2elog.Logf("Checking pods on node %v via /runningpods endpoint", nodeName)
  47. runningPods, err := framework.GetKubeletPods(c, nodeName)
  48. if err != nil {
  49. e2elog.Logf("Error checking running pods on %v: %v", nodeName, err)
  50. return matches
  51. }
  52. for _, pod := range runningPods.Items {
  53. if pod.Namespace == namespace && strings.HasPrefix(pod.Name, podNamePrefix) {
  54. matches.Insert(pod.Name)
  55. }
  56. }
  57. return matches
  58. }
  59. // waitTillNPodsRunningOnNodes polls the /runningpods endpoint on kubelet until
  60. // it finds targetNumPods pods that match the given criteria (namespace and
  61. // podNamePrefix). Note that we usually use label selector to filter pods that
  62. // belong to the same RC. However, we use podNamePrefix with namespace here
  63. // because pods returned from /runningpods do not contain the original label
  64. // information; they are reconstructed by examining the container runtime. In
  65. // the scope of this test, we do not expect pod naming conflicts so
  66. // podNamePrefix should be sufficient to identify the pods.
  67. func waitTillNPodsRunningOnNodes(c clientset.Interface, nodeNames sets.String, podNamePrefix string, namespace string, targetNumPods int, timeout time.Duration) error {
  68. return wait.Poll(pollInterval, timeout, func() (bool, error) {
  69. matchCh := make(chan sets.String, len(nodeNames))
  70. for _, item := range nodeNames.List() {
  71. // Launch a goroutine per node to check the pods running on the nodes.
  72. nodeName := item
  73. go func() {
  74. matchCh <- getPodMatches(c, nodeName, podNamePrefix, namespace)
  75. }()
  76. }
  77. seen := sets.NewString()
  78. for i := 0; i < len(nodeNames.List()); i++ {
  79. seen = seen.Union(<-matchCh)
  80. }
  81. if seen.Len() == targetNumPods {
  82. return true, nil
  83. }
  84. e2elog.Logf("Waiting for %d pods to be running on the node; %d are currently running;", targetNumPods, seen.Len())
  85. return false, nil
  86. })
  87. }
  88. // Restart the passed-in nfs-server by issuing a `/usr/sbin/rpc.nfsd 1` command in the
  89. // pod's (only) container. This command changes the number of nfs server threads from
  90. // (presumably) zero back to 1, and therefore allows nfs to open connections again.
  91. func restartNfsServer(serverPod *v1.Pod) {
  92. const startcmd = "/usr/sbin/rpc.nfsd 1"
  93. ns := fmt.Sprintf("--namespace=%v", serverPod.Namespace)
  94. framework.RunKubectlOrDie("exec", ns, serverPod.Name, "--", "/bin/sh", "-c", startcmd)
  95. }
  96. // Stop the passed-in nfs-server by issuing a `/usr/sbin/rpc.nfsd 0` command in the
  97. // pod's (only) container. This command changes the number of nfs server threads to 0,
  98. // thus closing all open nfs connections.
  99. func stopNfsServer(serverPod *v1.Pod) {
  100. const stopcmd = "/usr/sbin/rpc.nfsd 0"
  101. ns := fmt.Sprintf("--namespace=%v", serverPod.Namespace)
  102. framework.RunKubectlOrDie("exec", ns, serverPod.Name, "--", "/bin/sh", "-c", stopcmd)
  103. }
  104. // Creates a pod that mounts an nfs volume that is served by the nfs-server pod. The container
  105. // will execute the passed in shell cmd. Waits for the pod to start.
  106. // Note: the nfs plugin is defined inline, no PV or PVC.
  107. func createPodUsingNfs(f *framework.Framework, c clientset.Interface, ns, nfsIP, cmd string) *v1.Pod {
  108. ginkgo.By("create pod using nfs volume")
  109. isPrivileged := true
  110. cmdLine := []string{"-c", cmd}
  111. pod := &v1.Pod{
  112. TypeMeta: metav1.TypeMeta{
  113. Kind: "Pod",
  114. APIVersion: "v1",
  115. },
  116. ObjectMeta: metav1.ObjectMeta{
  117. GenerateName: "pod-nfs-vol-",
  118. Namespace: ns,
  119. },
  120. Spec: v1.PodSpec{
  121. Containers: []v1.Container{
  122. {
  123. Name: "pod-nfs-vol",
  124. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  125. Command: []string{"/bin/sh"},
  126. Args: cmdLine,
  127. VolumeMounts: []v1.VolumeMount{
  128. {
  129. Name: "nfs-vol",
  130. MountPath: "/mnt",
  131. },
  132. },
  133. SecurityContext: &v1.SecurityContext{
  134. Privileged: &isPrivileged,
  135. },
  136. },
  137. },
  138. RestartPolicy: v1.RestartPolicyNever, //don't restart pod
  139. Volumes: []v1.Volume{
  140. {
  141. Name: "nfs-vol",
  142. VolumeSource: v1.VolumeSource{
  143. NFS: &v1.NFSVolumeSource{
  144. Server: nfsIP,
  145. Path: "/exports",
  146. ReadOnly: false,
  147. },
  148. },
  149. },
  150. },
  151. },
  152. }
  153. rtnPod, err := c.CoreV1().Pods(ns).Create(pod)
  154. framework.ExpectNoError(err)
  155. err = f.WaitForPodReady(rtnPod.Name) // running & ready
  156. framework.ExpectNoError(err)
  157. rtnPod, err = c.CoreV1().Pods(ns).Get(rtnPod.Name, metav1.GetOptions{}) // return fresh pod
  158. framework.ExpectNoError(err)
  159. return rtnPod
  160. }
  161. // Checks for a lingering nfs mount and/or uid directory on the pod's host. The host IP is used
  162. // so that this test runs in GCE, where it appears that SSH cannot resolve the hostname.
  163. // If expectClean is true then we expect the node to be cleaned up and thus commands like
  164. // `ls <uid-dir>` should fail (since that dir was removed). If expectClean is false then we expect
  165. // the node is not cleaned up, and thus cmds like `ls <uid-dir>` should succeed. We wait for the
  166. // kubelet to be cleaned up, afterwhich an error is reported.
  167. func checkPodCleanup(c clientset.Interface, pod *v1.Pod, expectClean bool) {
  168. timeout := 5 * time.Minute
  169. poll := 20 * time.Second
  170. podDir := filepath.Join("/var/lib/kubelet/pods", string(pod.UID))
  171. mountDir := filepath.Join(podDir, "volumes", "kubernetes.io~nfs")
  172. // use ip rather than hostname in GCE
  173. nodeIP, err := framework.GetHostExternalAddress(c, pod)
  174. framework.ExpectNoError(err)
  175. condMsg := "deleted"
  176. if !expectClean {
  177. condMsg = "present"
  178. }
  179. // table of host tests to perform (order may matter so not using a map)
  180. type testT struct {
  181. feature string // feature to test
  182. cmd string // remote command to execute on node
  183. }
  184. tests := []testT{
  185. {
  186. feature: "pod UID directory",
  187. cmd: fmt.Sprintf("sudo ls %v", podDir),
  188. },
  189. {
  190. feature: "pod nfs mount",
  191. cmd: fmt.Sprintf("sudo mount | grep %v", mountDir),
  192. },
  193. }
  194. for _, test := range tests {
  195. e2elog.Logf("Wait up to %v for host's (%v) %q to be %v", timeout, nodeIP, test.feature, condMsg)
  196. err = wait.Poll(poll, timeout, func() (bool, error) {
  197. result, err := e2essh.NodeExec(nodeIP, test.cmd, framework.TestContext.Provider)
  198. framework.ExpectNoError(err)
  199. e2essh.LogResult(result)
  200. ok := (result.Code == 0 && len(result.Stdout) > 0 && len(result.Stderr) == 0)
  201. if expectClean && ok { // keep trying
  202. return false, nil
  203. }
  204. if !expectClean && !ok { // stop wait loop
  205. return true, fmt.Errorf("%v is gone but expected to exist", test.feature)
  206. }
  207. return true, nil // done, host is as expected
  208. })
  209. framework.ExpectNoError(err, fmt.Sprintf("Host (%v) cleanup error: %v. Expected %q to be %v", nodeIP, err, test.feature, condMsg))
  210. }
  211. if expectClean {
  212. e2elog.Logf("Pod's host has been cleaned up")
  213. } else {
  214. e2elog.Logf("Pod's host has not been cleaned up (per expectation)")
  215. }
  216. }
  217. var _ = SIGDescribe("kubelet", func() {
  218. var (
  219. c clientset.Interface
  220. ns string
  221. )
  222. f := framework.NewDefaultFramework("kubelet")
  223. ginkgo.BeforeEach(func() {
  224. c = f.ClientSet
  225. ns = f.Namespace.Name
  226. })
  227. SIGDescribe("Clean up pods on node", func() {
  228. var (
  229. numNodes int
  230. nodeNames sets.String
  231. nodeLabels map[string]string
  232. resourceMonitor *framework.ResourceMonitor
  233. )
  234. type DeleteTest struct {
  235. podsPerNode int
  236. timeout time.Duration
  237. }
  238. deleteTests := []DeleteTest{
  239. {podsPerNode: 10, timeout: 1 * time.Minute},
  240. }
  241. ginkgo.BeforeEach(func() {
  242. // Use node labels to restrict the pods to be assigned only to the
  243. // nodes we observe initially.
  244. nodeLabels = make(map[string]string)
  245. nodeLabels["kubelet_cleanup"] = "true"
  246. nodes := framework.GetReadySchedulableNodesOrDie(c)
  247. numNodes = len(nodes.Items)
  248. gomega.Expect(numNodes).NotTo(gomega.BeZero())
  249. nodeNames = sets.NewString()
  250. // If there are a lot of nodes, we don't want to use all of them
  251. // (if there are 1000 nodes in the cluster, starting 10 pods/node
  252. // will take ~10 minutes today). And there is also deletion phase.
  253. // Instead, we choose at most 10 nodes.
  254. if numNodes > maxNodesToCheck {
  255. numNodes = maxNodesToCheck
  256. }
  257. for i := 0; i < numNodes; i++ {
  258. nodeNames.Insert(nodes.Items[i].Name)
  259. }
  260. for nodeName := range nodeNames {
  261. for k, v := range nodeLabels {
  262. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  263. }
  264. }
  265. // Start resourceMonitor only in small clusters.
  266. if len(nodes.Items) <= maxNodesToCheck {
  267. resourceMonitor = framework.NewResourceMonitor(f.ClientSet, framework.TargetContainers(), containerStatsPollingInterval)
  268. resourceMonitor.Start()
  269. }
  270. })
  271. ginkgo.AfterEach(func() {
  272. if resourceMonitor != nil {
  273. resourceMonitor.Stop()
  274. }
  275. // If we added labels to nodes in this test, remove them now.
  276. for nodeName := range nodeNames {
  277. for k := range nodeLabels {
  278. framework.RemoveLabelOffNode(c, nodeName, k)
  279. }
  280. }
  281. })
  282. for _, itArg := range deleteTests {
  283. name := fmt.Sprintf(
  284. "kubelet should be able to delete %d pods per node in %v.", itArg.podsPerNode, itArg.timeout)
  285. ginkgo.It(name, func() {
  286. totalPods := itArg.podsPerNode * numNodes
  287. ginkgo.By(fmt.Sprintf("Creating a RC of %d pods and wait until all pods of this RC are running", totalPods))
  288. rcName := fmt.Sprintf("cleanup%d-%s", totalPods, string(uuid.NewUUID()))
  289. err := framework.RunRC(testutils.RCConfig{
  290. Client: f.ClientSet,
  291. Name: rcName,
  292. Namespace: f.Namespace.Name,
  293. Image: imageutils.GetPauseImageName(),
  294. Replicas: totalPods,
  295. NodeSelector: nodeLabels,
  296. })
  297. framework.ExpectNoError(err)
  298. // Perform a sanity check so that we know all desired pods are
  299. // running on the nodes according to kubelet. The timeout is set to
  300. // only 30 seconds here because framework.RunRC already waited for all pods to
  301. // transition to the running status.
  302. err = waitTillNPodsRunningOnNodes(f.ClientSet, nodeNames, rcName, ns, totalPods, time.Second*30)
  303. framework.ExpectNoError(err)
  304. if resourceMonitor != nil {
  305. resourceMonitor.LogLatest()
  306. }
  307. ginkgo.By("Deleting the RC")
  308. framework.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, rcName)
  309. // Check that the pods really are gone by querying /runningpods on the
  310. // node. The /runningpods handler checks the container runtime (or its
  311. // cache) and returns a list of running pods. Some possible causes of
  312. // failures are:
  313. // - kubelet deadlock
  314. // - a bug in graceful termination (if it is enabled)
  315. // - docker slow to delete pods (or resource problems causing slowness)
  316. start := time.Now()
  317. err = waitTillNPodsRunningOnNodes(f.ClientSet, nodeNames, rcName, ns, 0, itArg.timeout)
  318. framework.ExpectNoError(err)
  319. e2elog.Logf("Deleting %d pods on %d nodes completed in %v after the RC was deleted", totalPods, len(nodeNames),
  320. time.Since(start))
  321. if resourceMonitor != nil {
  322. resourceMonitor.LogCPUSummary()
  323. }
  324. })
  325. }
  326. })
  327. // Test host cleanup when disrupting the volume environment.
  328. SIGDescribe("host cleanup with volume mounts [sig-storage][HostCleanup][Flaky]", func() {
  329. type hostCleanupTest struct {
  330. itDescr string
  331. podCmd string
  332. }
  333. // Disrupt the nfs-server pod after a client pod accesses the nfs volume.
  334. // Note: the nfs-server is stopped NOT deleted. This is done to preserve its ip addr.
  335. // If the nfs-server pod is deleted the client pod's mount can not be unmounted.
  336. // If the nfs-server pod is deleted and re-created, due to having a different ip
  337. // addr, the client pod's mount still cannot be unmounted.
  338. ginkgo.Context("Host cleanup after disrupting NFS volume [NFS]", func() {
  339. // issue #31272
  340. var (
  341. nfsServerPod *v1.Pod
  342. nfsIP string
  343. pod *v1.Pod // client pod
  344. )
  345. // fill in test slice for this context
  346. testTbl := []hostCleanupTest{
  347. {
  348. itDescr: "after stopping the nfs-server and deleting the (sleeping) client pod, the NFS mount and the pod's UID directory should be removed.",
  349. podCmd: "sleep 6000", // keep pod running
  350. },
  351. {
  352. itDescr: "after stopping the nfs-server and deleting the (active) client pod, the NFS mount and the pod's UID directory should be removed.",
  353. podCmd: "while true; do echo FeFieFoFum >>/mnt/SUCCESS; sleep 1; cat /mnt/SUCCESS; done",
  354. },
  355. }
  356. ginkgo.BeforeEach(func() {
  357. framework.SkipUnlessProviderIs(framework.ProvidersWithSSH...)
  358. _, nfsServerPod, nfsIP = volume.NewNFSServer(c, ns, []string{"-G", "777", "/exports"})
  359. })
  360. ginkgo.AfterEach(func() {
  361. err := framework.DeletePodWithWait(f, c, pod)
  362. framework.ExpectNoError(err, "AfterEach: Failed to delete client pod ", pod.Name)
  363. err = framework.DeletePodWithWait(f, c, nfsServerPod)
  364. framework.ExpectNoError(err, "AfterEach: Failed to delete server pod ", nfsServerPod.Name)
  365. })
  366. // execute It blocks from above table of tests
  367. for _, t := range testTbl {
  368. ginkgo.It(t.itDescr, func() {
  369. pod = createPodUsingNfs(f, c, ns, nfsIP, t.podCmd)
  370. ginkgo.By("Stop the NFS server")
  371. stopNfsServer(nfsServerPod)
  372. ginkgo.By("Delete the pod mounted to the NFS volume -- expect failure")
  373. err := framework.DeletePodWithWait(f, c, pod)
  374. framework.ExpectError(err)
  375. // pod object is now stale, but is intentionally not nil
  376. ginkgo.By("Check if pod's host has been cleaned up -- expect not")
  377. checkPodCleanup(c, pod, false)
  378. ginkgo.By("Restart the nfs server")
  379. restartNfsServer(nfsServerPod)
  380. ginkgo.By("Verify that the deleted client pod is now cleaned up")
  381. checkPodCleanup(c, pod, true)
  382. })
  383. }
  384. })
  385. })
  386. })