scheduler_predicates.go 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  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 e2e
  14. import (
  15. "fmt"
  16. "time"
  17. "k8s.io/kubernetes/pkg/api"
  18. "k8s.io/kubernetes/pkg/api/errors"
  19. "k8s.io/kubernetes/pkg/api/resource"
  20. "k8s.io/kubernetes/pkg/api/unversioned"
  21. client "k8s.io/kubernetes/pkg/client/unversioned"
  22. "k8s.io/kubernetes/pkg/util/sets"
  23. "k8s.io/kubernetes/pkg/util/uuid"
  24. "k8s.io/kubernetes/test/e2e/framework"
  25. . "github.com/onsi/ginkgo"
  26. . "github.com/onsi/gomega"
  27. _ "github.com/stretchr/testify/assert"
  28. )
  29. const maxNumberOfPods int64 = 10
  30. const minPodCPURequest int64 = 500
  31. // variable set in BeforeEach, never modified afterwards
  32. var masterNodes sets.String
  33. var podWithNodeAffinity = api.Pod{
  34. ObjectMeta: api.ObjectMeta{
  35. Name: "with-labels",
  36. Annotations: map[string]string{
  37. "scheduler.alpha.kubernetes.io/affinity": `{
  38. "nodeAffinity": {
  39. "requiredDuringSchedulingIgnoredDuringExecution": {
  40. "nodeSelectorTerms": [{
  41. "matchExpressions": [{
  42. "key": "kubernetes.io/e2e-az-name",
  43. "operator": "In",
  44. "values": ["e2e-az1", "e2e-az2"]
  45. }]
  46. }]
  47. }
  48. }
  49. }`,
  50. "another-annotation-key": "another-annotation-value",
  51. },
  52. },
  53. Spec: api.PodSpec{
  54. Containers: []api.Container{
  55. {
  56. Name: "with-labels",
  57. Image: "gcr.io/google_containers/pause:2.0",
  58. },
  59. },
  60. },
  61. }
  62. var podWithPodAffinity = api.Pod{
  63. ObjectMeta: api.ObjectMeta{
  64. Name: "with-newlabels",
  65. Annotations: map[string]string{
  66. "scheduler.alpha.kubernetes.io/affinity": `{
  67. "podAffinity": {
  68. "requiredDuringSchedulingIgnoredDuringExecution": [{
  69. "labelSelector": {
  70. "matchExpressions": [{
  71. "key": "security",
  72. "operator": "In",
  73. "values":["S1"]
  74. }]
  75. },
  76. "topologyKey": "kubernetes.io/hostname"
  77. }]
  78. },
  79. "podAntiAffinity": {
  80. "requiredDuringSchedulingIgnoredDuringExecution": [{
  81. "labelSelector": {
  82. "matchExpressions": [{
  83. "key": "security",
  84. "operator": "In",
  85. "values":["S2"]
  86. }]
  87. },
  88. "topologyKey": "kubernetes.io/hostname"
  89. }]
  90. }
  91. }`,
  92. "another-annotation-key": "another-annotation-value",
  93. },
  94. },
  95. Spec: api.PodSpec{
  96. Containers: []api.Container{
  97. {
  98. Name: "with-newlabels",
  99. Image: "gcr.io/google_containers/pause:2.0",
  100. },
  101. },
  102. },
  103. }
  104. // Returns a number of currently scheduled and not scheduled Pods.
  105. func getPodsScheduled(pods *api.PodList) (scheduledPods, notScheduledPods []api.Pod) {
  106. for _, pod := range pods.Items {
  107. if !masterNodes.Has(pod.Spec.NodeName) {
  108. if pod.Spec.NodeName != "" {
  109. _, scheduledCondition := api.GetPodCondition(&pod.Status, api.PodScheduled)
  110. // We can't assume that the scheduledCondition is always set if Pod is assigned to Node,
  111. // as e.g. DaemonController doesn't set it when assigning Pod to a Node. Currently
  112. // Kubelet sets this condition when it gets a Pod without it, but if we were expecting
  113. // that it would always be not nil, this would cause a rare race condition.
  114. if scheduledCondition != nil {
  115. Expect(scheduledCondition.Status).To(Equal(api.ConditionTrue))
  116. }
  117. scheduledPods = append(scheduledPods, pod)
  118. } else {
  119. _, scheduledCondition := api.GetPodCondition(&pod.Status, api.PodScheduled)
  120. if scheduledCondition != nil {
  121. Expect(scheduledCondition.Status).To(Equal(api.ConditionFalse))
  122. }
  123. if scheduledCondition.Reason == "Unschedulable" {
  124. notScheduledPods = append(notScheduledPods, pod)
  125. }
  126. }
  127. }
  128. }
  129. return
  130. }
  131. func getRequestedCPU(pod api.Pod) int64 {
  132. var result int64
  133. for _, container := range pod.Spec.Containers {
  134. result += container.Resources.Requests.Cpu().MilliValue()
  135. }
  136. return result
  137. }
  138. // TODO: upgrade calls in PodAffinity tests when we're able to run them
  139. func verifyResult(c *client.Client, podName string, expectedScheduled int, expectedNotScheduled int, ns string) {
  140. allPods, err := c.Pods(ns).List(api.ListOptions{})
  141. framework.ExpectNoError(err)
  142. scheduledPods, notScheduledPods := framework.GetPodsScheduled(masterNodes, allPods)
  143. printed := false
  144. printOnce := func(msg string) string {
  145. if !printed {
  146. printed = true
  147. return msg
  148. } else {
  149. return ""
  150. }
  151. }
  152. Expect(len(notScheduledPods)).To(Equal(expectedNotScheduled), printOnce(fmt.Sprintf("Not scheduled Pods: %#v", notScheduledPods)))
  153. Expect(len(scheduledPods)).To(Equal(expectedScheduled), printOnce(fmt.Sprintf("Scheduled Pods: %#v", scheduledPods)))
  154. }
  155. func cleanupPods(c *client.Client, ns string) {
  156. By("Removing all pods in namespace " + ns)
  157. pods, err := c.Pods(ns).List(api.ListOptions{})
  158. framework.ExpectNoError(err)
  159. opt := api.NewDeleteOptions(0)
  160. for _, p := range pods.Items {
  161. framework.ExpectNoError(c.Pods(ns).Delete(p.ObjectMeta.Name, opt))
  162. }
  163. }
  164. var _ = framework.KubeDescribe("SchedulerPredicates [Serial]", func() {
  165. var c *client.Client
  166. var nodeList *api.NodeList
  167. var systemPodsNo int
  168. var totalPodCapacity int64
  169. var RCName string
  170. var ns string
  171. ignoreLabels := framework.ImagePullerLabels
  172. AfterEach(func() {
  173. rc, err := c.ReplicationControllers(ns).Get(RCName)
  174. if err == nil && rc.Spec.Replicas != 0 {
  175. By("Cleaning up the replication controller")
  176. err := framework.DeleteRCAndPods(c, ns, RCName)
  177. framework.ExpectNoError(err)
  178. }
  179. })
  180. f := framework.NewDefaultFramework("sched-pred")
  181. BeforeEach(func() {
  182. c = f.Client
  183. ns = f.Namespace.Name
  184. nodeList = &api.NodeList{}
  185. framework.WaitForAllNodesHealthy(c, time.Minute)
  186. masterNodes, nodeList = framework.GetMasterAndWorkerNodesOrDie(c)
  187. err := framework.CheckTestingNSDeletedExcept(c, ns)
  188. framework.ExpectNoError(err)
  189. // Every test case in this suite assumes that cluster add-on pods stay stable and
  190. // cannot be run in parallel with any other test that touches Nodes or Pods.
  191. // It is so because we need to have precise control on what's running in the cluster.
  192. systemPods, err := framework.GetPodsInNamespace(c, ns, ignoreLabels)
  193. Expect(err).NotTo(HaveOccurred())
  194. systemPodsNo = 0
  195. for _, pod := range systemPods {
  196. if !masterNodes.Has(pod.Spec.NodeName) && pod.DeletionTimestamp == nil {
  197. systemPodsNo++
  198. }
  199. }
  200. err = framework.WaitForPodsRunningReady(c, api.NamespaceSystem, int32(systemPodsNo), framework.PodReadyBeforeTimeout, ignoreLabels)
  201. Expect(err).NotTo(HaveOccurred())
  202. for _, node := range nodeList.Items {
  203. framework.Logf("\nLogging pods the kubelet thinks is on node %v before test", node.Name)
  204. framework.PrintAllKubeletPods(c, node.Name)
  205. }
  206. })
  207. // This test verifies that max-pods flag works as advertised. It assumes that cluster add-on pods stay stable
  208. // and cannot be run in parallel with any other test that touches Nodes or Pods. It is so because to check
  209. // if max-pods is working we need to fully saturate the cluster and keep it in this state for few seconds.
  210. //
  211. // Slow PR #13315 (8 min)
  212. It("validates MaxPods limit number of pods that are allowed to run [Slow]", func() {
  213. totalPodCapacity = 0
  214. for _, node := range nodeList.Items {
  215. framework.Logf("Node: %v", node)
  216. podCapacity, found := node.Status.Capacity["pods"]
  217. Expect(found).To(Equal(true))
  218. totalPodCapacity += podCapacity.Value()
  219. }
  220. currentlyScheduledPods := framework.WaitForStableCluster(c, masterNodes)
  221. podsNeededForSaturation := int(totalPodCapacity) - currentlyScheduledPods
  222. By(fmt.Sprintf("Starting additional %v Pods to fully saturate the cluster max pods and trying to start another one", podsNeededForSaturation))
  223. // As the pods are distributed randomly among nodes,
  224. // it can easily happen that all nodes are satured
  225. // and there is no need to create additional pods.
  226. // StartPods requires at least one pod to replicate.
  227. if podsNeededForSaturation > 0 {
  228. framework.StartPods(c, podsNeededForSaturation, ns, "maxp", api.Pod{
  229. TypeMeta: unversioned.TypeMeta{
  230. Kind: "Pod",
  231. },
  232. ObjectMeta: api.ObjectMeta{
  233. Name: "",
  234. Labels: map[string]string{"name": ""},
  235. },
  236. Spec: api.PodSpec{
  237. Containers: []api.Container{
  238. {
  239. Name: "",
  240. Image: framework.GetPauseImageName(f.Client),
  241. },
  242. },
  243. },
  244. }, true)
  245. }
  246. podName := "additional-pod"
  247. _, err := c.Pods(ns).Create(&api.Pod{
  248. TypeMeta: unversioned.TypeMeta{
  249. Kind: "Pod",
  250. },
  251. ObjectMeta: api.ObjectMeta{
  252. Name: podName,
  253. Labels: map[string]string{"name": "additional"},
  254. },
  255. Spec: api.PodSpec{
  256. Containers: []api.Container{
  257. {
  258. Name: podName,
  259. Image: framework.GetPauseImageName(f.Client),
  260. },
  261. },
  262. },
  263. })
  264. framework.ExpectNoError(err)
  265. // Wait a bit to allow scheduler to do its thing
  266. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  267. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  268. time.Sleep(10 * time.Second)
  269. verifyResult(c, podName, podsNeededForSaturation, 1, ns)
  270. })
  271. // This test verifies we don't allow scheduling of pods in a way that sum of limits of pods is greater than machines capacity.
  272. // It assumes that cluster add-on pods stay stable and cannot be run in parallel with any other test that touches Nodes or Pods.
  273. // It is so because we need to have precise control on what's running in the cluster.
  274. It("validates resource limits of pods that are allowed to run [Conformance]", func() {
  275. nodeMaxCapacity := int64(0)
  276. nodeToCapacityMap := make(map[string]int64)
  277. for _, node := range nodeList.Items {
  278. capacity, found := node.Status.Capacity["cpu"]
  279. Expect(found).To(Equal(true))
  280. nodeToCapacityMap[node.Name] = capacity.MilliValue()
  281. if nodeMaxCapacity < capacity.MilliValue() {
  282. nodeMaxCapacity = capacity.MilliValue()
  283. }
  284. }
  285. framework.WaitForStableCluster(c, masterNodes)
  286. pods, err := c.Pods(api.NamespaceAll).List(api.ListOptions{})
  287. framework.ExpectNoError(err)
  288. for _, pod := range pods.Items {
  289. _, found := nodeToCapacityMap[pod.Spec.NodeName]
  290. if found && pod.Status.Phase != api.PodSucceeded && pod.Status.Phase != api.PodFailed {
  291. framework.Logf("Pod %v requesting resource cpu=%vm on Node %v", pod.Name, getRequestedCPU(pod), pod.Spec.NodeName)
  292. nodeToCapacityMap[pod.Spec.NodeName] -= getRequestedCPU(pod)
  293. }
  294. }
  295. var podsNeededForSaturation int
  296. milliCpuPerPod := nodeMaxCapacity / maxNumberOfPods
  297. if milliCpuPerPod < minPodCPURequest {
  298. milliCpuPerPod = minPodCPURequest
  299. }
  300. framework.Logf("Using pod capacity: %vm", milliCpuPerPod)
  301. for name, leftCapacity := range nodeToCapacityMap {
  302. framework.Logf("Node: %v has cpu capacity: %vm", name, leftCapacity)
  303. podsNeededForSaturation += (int)(leftCapacity / milliCpuPerPod)
  304. }
  305. By(fmt.Sprintf("Starting additional %v Pods to fully saturate the cluster CPU and trying to start another one", podsNeededForSaturation))
  306. // As the pods are distributed randomly among nodes,
  307. // it can easily happen that all nodes are saturated
  308. // and there is no need to create additional pods.
  309. // StartPods requires at least one pod to replicate.
  310. if podsNeededForSaturation > 0 {
  311. framework.StartPods(c, podsNeededForSaturation, ns, "overcommit", api.Pod{
  312. TypeMeta: unversioned.TypeMeta{
  313. Kind: "Pod",
  314. },
  315. ObjectMeta: api.ObjectMeta{
  316. Name: "",
  317. Labels: map[string]string{"name": ""},
  318. },
  319. Spec: api.PodSpec{
  320. Containers: []api.Container{
  321. {
  322. Name: "",
  323. Image: framework.GetPauseImageName(f.Client),
  324. Resources: api.ResourceRequirements{
  325. Limits: api.ResourceList{
  326. "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"),
  327. },
  328. Requests: api.ResourceList{
  329. "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"),
  330. },
  331. },
  332. },
  333. },
  334. },
  335. }, true)
  336. }
  337. podName := "additional-pod"
  338. _, err = c.Pods(ns).Create(&api.Pod{
  339. TypeMeta: unversioned.TypeMeta{
  340. Kind: "Pod",
  341. },
  342. ObjectMeta: api.ObjectMeta{
  343. Name: podName,
  344. Labels: map[string]string{"name": "additional"},
  345. },
  346. Spec: api.PodSpec{
  347. Containers: []api.Container{
  348. {
  349. Name: podName,
  350. Image: framework.GetPauseImageName(f.Client),
  351. Resources: api.ResourceRequirements{
  352. Limits: api.ResourceList{
  353. "cpu": *resource.NewMilliQuantity(milliCpuPerPod, "DecimalSI"),
  354. },
  355. },
  356. },
  357. },
  358. },
  359. })
  360. framework.ExpectNoError(err)
  361. // Wait a bit to allow scheduler to do its thing
  362. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  363. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  364. time.Sleep(10 * time.Second)
  365. verifyResult(c, podName, podsNeededForSaturation, 1, ns)
  366. })
  367. // Test Nodes does not have any label, hence it should be impossible to schedule Pod with
  368. // nonempty Selector set.
  369. It("validates that NodeSelector is respected if not matching [Conformance]", func() {
  370. By("Trying to schedule Pod with nonempty NodeSelector.")
  371. podName := "restricted-pod"
  372. framework.WaitForStableCluster(c, masterNodes)
  373. _, err := c.Pods(ns).Create(&api.Pod{
  374. TypeMeta: unversioned.TypeMeta{
  375. Kind: "Pod",
  376. },
  377. ObjectMeta: api.ObjectMeta{
  378. Name: podName,
  379. Labels: map[string]string{"name": "restricted"},
  380. },
  381. Spec: api.PodSpec{
  382. Containers: []api.Container{
  383. {
  384. Name: podName,
  385. Image: framework.GetPauseImageName(f.Client),
  386. },
  387. },
  388. NodeSelector: map[string]string{
  389. "label": "nonempty",
  390. },
  391. },
  392. })
  393. framework.ExpectNoError(err)
  394. // Wait a bit to allow scheduler to do its thing
  395. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  396. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  397. time.Sleep(10 * time.Second)
  398. verifyResult(c, podName, 0, 1, ns)
  399. })
  400. It("validates that a pod with an invalid NodeAffinity is rejected", func() {
  401. By("Trying to launch a pod with an invalid Affinity data.")
  402. podName := "without-label"
  403. _, err := c.Pods(ns).Create(&api.Pod{
  404. TypeMeta: unversioned.TypeMeta{
  405. Kind: "Pod",
  406. },
  407. ObjectMeta: api.ObjectMeta{
  408. Name: podName,
  409. Annotations: map[string]string{
  410. api.AffinityAnnotationKey: `
  411. {"nodeAffinity": {
  412. "requiredDuringSchedulingIgnoredDuringExecution": {
  413. "nodeSelectorTerms": [{
  414. "matchExpressions": []
  415. }]
  416. },
  417. }}`,
  418. },
  419. },
  420. Spec: api.PodSpec{
  421. Containers: []api.Container{
  422. {
  423. Name: podName,
  424. Image: framework.GetPauseImageName(f.Client),
  425. },
  426. },
  427. },
  428. })
  429. if err == nil || !errors.IsInvalid(err) {
  430. framework.Failf("Expect error of invalid, got : %v", err)
  431. }
  432. // Wait a bit to allow scheduler to do its thing if the pod is not rejected.
  433. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  434. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  435. time.Sleep(10 * time.Second)
  436. })
  437. It("validates that NodeSelector is respected if matching [Conformance]", func() {
  438. // launch a pod to find a node which can launch a pod. We intentionally do
  439. // not just take the node list and choose the first of them. Depending on the
  440. // cluster and the scheduler it might be that a "normal" pod cannot be
  441. // scheduled onto it.
  442. By("Trying to launch a pod without a label to get a node which can launch it.")
  443. podName := "without-label"
  444. pod, err := c.Pods(ns).Create(&api.Pod{
  445. TypeMeta: unversioned.TypeMeta{
  446. Kind: "Pod",
  447. },
  448. ObjectMeta: api.ObjectMeta{
  449. Name: podName,
  450. },
  451. Spec: api.PodSpec{
  452. Containers: []api.Container{
  453. {
  454. Name: podName,
  455. Image: framework.GetPauseImageName(f.Client),
  456. },
  457. },
  458. },
  459. })
  460. framework.ExpectNoError(err)
  461. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  462. pod, err = c.Pods(ns).Get(podName)
  463. framework.ExpectNoError(err)
  464. nodeName := pod.Spec.NodeName
  465. By("Explicitly delete pod here to free the resource it takes.")
  466. err = c.Pods(ns).Delete(podName, api.NewDeleteOptions(0))
  467. framework.ExpectNoError(err)
  468. By("Trying to apply a random label on the found node.")
  469. k := fmt.Sprintf("kubernetes.io/e2e-%s", string(uuid.NewUUID()))
  470. v := "42"
  471. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  472. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  473. defer framework.RemoveLabelOffNode(c, nodeName, k)
  474. By("Trying to relaunch the pod, now with labels.")
  475. labelPodName := "with-labels"
  476. pod, err = c.Pods(ns).Create(&api.Pod{
  477. TypeMeta: unversioned.TypeMeta{
  478. Kind: "Pod",
  479. },
  480. ObjectMeta: api.ObjectMeta{
  481. Name: labelPodName,
  482. },
  483. Spec: api.PodSpec{
  484. Containers: []api.Container{
  485. {
  486. Name: labelPodName,
  487. Image: framework.GetPauseImageName(f.Client),
  488. },
  489. },
  490. NodeSelector: map[string]string{
  491. "kubernetes.io/hostname": nodeName,
  492. k: v,
  493. },
  494. },
  495. })
  496. framework.ExpectNoError(err)
  497. // check that pod got scheduled. We intentionally DO NOT check that the
  498. // pod is running because this will create a race condition with the
  499. // kubelet and the scheduler: the scheduler might have scheduled a pod
  500. // already when the kubelet does not know about its new label yet. The
  501. // kubelet will then refuse to launch the pod.
  502. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, pod.ResourceVersion))
  503. labelPod, err := c.Pods(ns).Get(labelPodName)
  504. framework.ExpectNoError(err)
  505. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  506. })
  507. // Test Nodes does not have any label, hence it should be impossible to schedule Pod with
  508. // non-nil NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.
  509. It("validates that NodeAffinity is respected if not matching", func() {
  510. By("Trying to schedule Pod with nonempty NodeSelector.")
  511. podName := "restricted-pod"
  512. framework.WaitForStableCluster(c, masterNodes)
  513. _, err := c.Pods(ns).Create(&api.Pod{
  514. TypeMeta: unversioned.TypeMeta{
  515. Kind: "Pod",
  516. },
  517. ObjectMeta: api.ObjectMeta{
  518. Name: podName,
  519. Labels: map[string]string{"name": "restricted"},
  520. Annotations: map[string]string{
  521. "scheduler.alpha.kubernetes.io/affinity": `
  522. {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": {
  523. "nodeSelectorTerms": [
  524. {
  525. "matchExpressions": [{
  526. "key": "foo",
  527. "operator": "In",
  528. "values": ["bar", "value2"]
  529. }]
  530. },
  531. {
  532. "matchExpressions": [{
  533. "key": "diffkey",
  534. "operator": "In",
  535. "values": ["wrong", "value2"]
  536. }]
  537. }
  538. ]
  539. }}}`,
  540. },
  541. },
  542. Spec: api.PodSpec{
  543. Containers: []api.Container{
  544. {
  545. Name: podName,
  546. Image: framework.GetPauseImageName(f.Client),
  547. },
  548. },
  549. },
  550. })
  551. framework.ExpectNoError(err)
  552. // Wait a bit to allow scheduler to do its thing
  553. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  554. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  555. time.Sleep(10 * time.Second)
  556. verifyResult(c, podName, 0, 1, ns)
  557. })
  558. // Keep the same steps with the test on NodeSelector,
  559. // but specify Affinity in Pod.Annotations, instead of NodeSelector.
  560. It("validates that required NodeAffinity setting is respected if matching", func() {
  561. // launch a pod to find a node which can launch a pod. We intentionally do
  562. // not just take the node list and choose the first of them. Depending on the
  563. // cluster and the scheduler it might be that a "normal" pod cannot be
  564. // scheduled onto it.
  565. By("Trying to launch a pod without a label to get a node which can launch it.")
  566. podName := "without-label"
  567. pod, err := c.Pods(ns).Create(&api.Pod{
  568. TypeMeta: unversioned.TypeMeta{
  569. Kind: "Pod",
  570. },
  571. ObjectMeta: api.ObjectMeta{
  572. Name: podName,
  573. },
  574. Spec: api.PodSpec{
  575. Containers: []api.Container{
  576. {
  577. Name: podName,
  578. Image: framework.GetPauseImageName(f.Client),
  579. },
  580. },
  581. },
  582. })
  583. framework.ExpectNoError(err)
  584. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  585. pod, err = c.Pods(ns).Get(podName)
  586. framework.ExpectNoError(err)
  587. nodeName := pod.Spec.NodeName
  588. By("Explicitly delete pod here to free the resource it takes.")
  589. err = c.Pods(ns).Delete(podName, api.NewDeleteOptions(0))
  590. framework.ExpectNoError(err)
  591. By("Trying to apply a random label on the found node.")
  592. k := fmt.Sprintf("kubernetes.io/e2e-%s", string(uuid.NewUUID()))
  593. v := "42"
  594. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  595. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  596. defer framework.RemoveLabelOffNode(c, nodeName, k)
  597. By("Trying to relaunch the pod, now with labels.")
  598. labelPodName := "with-labels"
  599. pod, err = c.Pods(ns).Create(&api.Pod{
  600. TypeMeta: unversioned.TypeMeta{
  601. Kind: "Pod",
  602. },
  603. ObjectMeta: api.ObjectMeta{
  604. Name: labelPodName,
  605. Annotations: map[string]string{
  606. "scheduler.alpha.kubernetes.io/affinity": `
  607. {"nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": {
  608. "nodeSelectorTerms": [
  609. {
  610. "matchExpressions": [{
  611. "key": "kubernetes.io/hostname",
  612. "operator": "In",
  613. "values": ["` + nodeName + `"]
  614. },{
  615. "key": "` + k + `",
  616. "operator": "In",
  617. "values": ["` + v + `"]
  618. }]
  619. }
  620. ]
  621. }}}`,
  622. },
  623. },
  624. Spec: api.PodSpec{
  625. Containers: []api.Container{
  626. {
  627. Name: labelPodName,
  628. Image: framework.GetPauseImageName(f.Client),
  629. },
  630. },
  631. },
  632. })
  633. framework.ExpectNoError(err)
  634. // check that pod got scheduled. We intentionally DO NOT check that the
  635. // pod is running because this will create a race condition with the
  636. // kubelet and the scheduler: the scheduler might have scheduled a pod
  637. // already when the kubelet does not know about its new label yet. The
  638. // kubelet will then refuse to launch the pod.
  639. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, pod.ResourceVersion))
  640. labelPod, err := c.Pods(ns).Get(labelPodName)
  641. framework.ExpectNoError(err)
  642. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  643. })
  644. // Verify that an escaped JSON string of NodeAffinity in a YAML PodSpec works.
  645. It("validates that embedding the JSON NodeAffinity setting as a string in the annotation value work", func() {
  646. // launch a pod to find a node which can launch a pod. We intentionally do
  647. // not just take the node list and choose the first of them. Depending on the
  648. // cluster and the scheduler it might be that a "normal" pod cannot be
  649. // scheduled onto it.
  650. By("Trying to launch a pod without a label to get a node which can launch it.")
  651. podName := "without-label"
  652. pod, err := c.Pods(ns).Create(&api.Pod{
  653. TypeMeta: unversioned.TypeMeta{
  654. Kind: "Pod",
  655. },
  656. ObjectMeta: api.ObjectMeta{
  657. Name: podName,
  658. },
  659. Spec: api.PodSpec{
  660. Containers: []api.Container{
  661. {
  662. Name: podName,
  663. Image: framework.GetPauseImageName(f.Client),
  664. },
  665. },
  666. },
  667. })
  668. framework.ExpectNoError(err)
  669. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  670. pod, err = c.Pods(ns).Get(podName)
  671. framework.ExpectNoError(err)
  672. nodeName := pod.Spec.NodeName
  673. By("Explicitly delete pod here to free the resource it takes.")
  674. err = c.Pods(ns).Delete(podName, api.NewDeleteOptions(0))
  675. framework.ExpectNoError(err)
  676. By("Trying to apply a label with fake az info on the found node.")
  677. k := "kubernetes.io/e2e-az-name"
  678. v := "e2e-az1"
  679. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  680. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  681. defer framework.RemoveLabelOffNode(c, nodeName, k)
  682. By("Trying to launch a pod that with NodeAffinity setting as embedded JSON string in the annotation value.")
  683. labelPodName := podWithNodeAffinity.Name
  684. pod, err = c.Pods(ns).Create(&podWithNodeAffinity)
  685. framework.ExpectNoError(err)
  686. // check that pod got scheduled. We intentionally DO NOT check that the
  687. // pod is running because this will create a race condition with the
  688. // kubelet and the scheduler: the scheduler might have scheduled a pod
  689. // already when the kubelet does not know about its new label yet. The
  690. // kubelet will then refuse to launch the pod.
  691. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, ""))
  692. labelPod, err := c.Pods(ns).Get(labelPodName)
  693. framework.ExpectNoError(err)
  694. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  695. })
  696. // labelSelector Operator is DoesNotExist but values are there in requiredDuringSchedulingIgnoredDuringExecution
  697. // part of podAffinity,so validation fails.
  698. It("validates that a pod with an invalid podAffinity is rejected because of the LabelSelectorRequirement is invalid", func() {
  699. By("Trying to launch a pod with an invalid pod Affinity data.")
  700. podName := "without-label-" + string(uuid.NewUUID())
  701. _, err := c.Pods(ns).Create(&api.Pod{
  702. TypeMeta: unversioned.TypeMeta{
  703. Kind: "Pod",
  704. },
  705. ObjectMeta: api.ObjectMeta{
  706. Name: podName,
  707. Labels: map[string]string{"name": "without-label"},
  708. Annotations: map[string]string{
  709. "scheduler.alpha.kubernetes.io/affinity": `
  710. {"podAffinity": {
  711. "requiredDuringSchedulingIgnoredDuringExecution": [{
  712. "weight": 0,
  713. "podAffinityTerm": {
  714. "labelSelector": {
  715. "matchExpressions": [{
  716. "key": "service",
  717. "operator": "DoesNotExist",
  718. "values":["securityscan"]
  719. }]
  720. },
  721. "namespaces": [],
  722. "topologyKey": "kubernetes.io/hostname"
  723. }
  724. }]
  725. }}`,
  726. },
  727. },
  728. Spec: api.PodSpec{
  729. Containers: []api.Container{
  730. {
  731. Name: podName,
  732. Image: framework.GetPauseImageName(f.Client),
  733. },
  734. },
  735. },
  736. })
  737. if err == nil || !errors.IsInvalid(err) {
  738. framework.Failf("Expect error of invalid, got : %v", err)
  739. }
  740. // Wait a bit to allow scheduler to do its thing if the pod is not rejected.
  741. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  742. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  743. time.Sleep(10 * time.Second)
  744. })
  745. // Test Nodes does not have any pod, hence it should be impossible to schedule a Pod with pod affinity.
  746. It("validates that Inter-pod-Affinity is respected if not matching", func() {
  747. By("Trying to schedule Pod with nonempty Pod Affinity.")
  748. podName := "without-label-" + string(uuid.NewUUID())
  749. framework.WaitForStableCluster(c, masterNodes)
  750. _, err := c.Pods(ns).Create(&api.Pod{
  751. TypeMeta: unversioned.TypeMeta{
  752. Kind: "Pod",
  753. },
  754. ObjectMeta: api.ObjectMeta{
  755. Name: podName,
  756. Annotations: map[string]string{
  757. "scheduler.alpha.kubernetes.io/affinity": `
  758. {"podAffinity": {
  759. "requiredDuringSchedulingIgnoredDuringExecution": [{
  760. "labelSelector":{
  761. "matchExpressions": [{
  762. "key": "service",
  763. "operator": "In",
  764. "values": ["securityscan", "value2"]
  765. }]
  766. },
  767. "topologyKey": "kubernetes.io/hostname"
  768. }]
  769. }}`,
  770. },
  771. },
  772. Spec: api.PodSpec{
  773. Containers: []api.Container{
  774. {
  775. Name: podName,
  776. Image: framework.GetPauseImageName(f.Client),
  777. },
  778. },
  779. },
  780. })
  781. framework.ExpectNoError(err)
  782. // Wait a bit to allow scheduler to do its thing
  783. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  784. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  785. time.Sleep(10 * time.Second)
  786. verifyResult(c, podName, 0, 1, ns)
  787. })
  788. // test the pod affinity successful matching scenario.
  789. It("validates that InterPodAffinity is respected if matching", func() {
  790. // launch a pod to find a node which can launch a pod. We intentionally do
  791. // not just take the node list and choose the first of them. Depending on the
  792. // cluster and the scheduler it might be that a "normal" pod cannot be
  793. // scheduled onto it.
  794. By("Trying to launch a pod with a label to get a node which can launch it.")
  795. podName := "with-label-" + string(uuid.NewUUID())
  796. pod, err := c.Pods(ns).Create(&api.Pod{
  797. TypeMeta: unversioned.TypeMeta{
  798. Kind: "Pod",
  799. },
  800. ObjectMeta: api.ObjectMeta{
  801. Name: podName,
  802. Labels: map[string]string{"security": "S1"},
  803. },
  804. Spec: api.PodSpec{
  805. Containers: []api.Container{
  806. {
  807. Name: podName,
  808. Image: framework.GetPauseImageName(f.Client),
  809. },
  810. },
  811. },
  812. })
  813. framework.ExpectNoError(err)
  814. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  815. pod, err = c.Pods(ns).Get(podName)
  816. framework.ExpectNoError(err)
  817. nodeName := pod.Spec.NodeName
  818. By("Trying to apply a random label on the found node.")
  819. k := "e2e.inter-pod-affinity.kubernetes.io/zone"
  820. v := "china-e2etest"
  821. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  822. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  823. defer framework.RemoveLabelOffNode(c, nodeName, k)
  824. By("Trying to launch the pod, now with podAffinity.")
  825. labelPodName := "with-podaffinity-" + string(uuid.NewUUID())
  826. pod, err = c.Pods(ns).Create(&api.Pod{
  827. TypeMeta: unversioned.TypeMeta{
  828. Kind: "Pod",
  829. },
  830. ObjectMeta: api.ObjectMeta{
  831. Name: labelPodName,
  832. Annotations: map[string]string{
  833. "scheduler.alpha.kubernetes.io/affinity": `
  834. {"podAffinity": {
  835. "requiredDuringSchedulingIgnoredDuringExecution": [{
  836. "labelSelector":{
  837. "matchExpressions": [{
  838. "key": "security",
  839. "operator": "In",
  840. "values": ["S1", "value2"]
  841. }]
  842. },
  843. "topologyKey": "` + k + `",
  844. "namespaces":["` + ns + `"]
  845. }]
  846. }}`,
  847. },
  848. },
  849. Spec: api.PodSpec{
  850. Containers: []api.Container{
  851. {
  852. Name: labelPodName,
  853. Image: framework.GetPauseImageName(f.Client),
  854. },
  855. },
  856. },
  857. })
  858. framework.ExpectNoError(err)
  859. // check that pod got scheduled. We intentionally DO NOT check that the
  860. // pod is running because this will create a race condition with the
  861. // kubelet and the scheduler: the scheduler might have scheduled a pod
  862. // already when the kubelet does not know about its new label yet. The
  863. // kubelet will then refuse to launch the pod.
  864. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, pod.ResourceVersion))
  865. labelPod, err := c.Pods(ns).Get(labelPodName)
  866. framework.ExpectNoError(err)
  867. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  868. })
  869. // test when the pod anti affinity rule is not satisfied, the pod would stay pending.
  870. It("validates that InterPodAntiAffinity is respected if matching 2", func() {
  871. // launch pods to find nodes which can launch a pod. We intentionally do
  872. // not just take the node list and choose the first and the second of them.
  873. // Depending on the cluster and the scheduler it might be that a "normal" pod
  874. // cannot be scheduled onto it.
  875. By("Launching two pods on two distinct nodes to get two node names")
  876. CreateHostPortPods(f, "host-port", 2, true)
  877. defer framework.DeleteRCAndPods(f.Client, f.Namespace.Name, "host-port")
  878. podList, err := c.Pods(ns).List(api.ListOptions{})
  879. ExpectNoError(err)
  880. Expect(len(podList.Items)).To(Equal(2))
  881. nodeNames := []string{podList.Items[0].Spec.NodeName, podList.Items[1].Spec.NodeName}
  882. Expect(nodeNames[0]).ToNot(Equal(nodeNames[1]))
  883. By("Applying a random label to both nodes.")
  884. k := "e2e.inter-pod-affinity.kubernetes.io/zone"
  885. v := "china-e2etest"
  886. for _, nodeName := range nodeNames {
  887. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  888. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  889. defer framework.RemoveLabelOffNode(c, nodeName, k)
  890. }
  891. By("Trying to launch another pod on the first node with the service label.")
  892. podName := "with-label-" + string(uuid.NewUUID())
  893. pod, err := c.Pods(ns).Create(&api.Pod{
  894. TypeMeta: unversioned.TypeMeta{
  895. Kind: "Pod",
  896. },
  897. ObjectMeta: api.ObjectMeta{
  898. Name: podName,
  899. Labels: map[string]string{"service": "S1"},
  900. },
  901. Spec: api.PodSpec{
  902. Containers: []api.Container{
  903. {
  904. Name: podName,
  905. Image: framework.GetPauseImageName(f.Client),
  906. },
  907. },
  908. NodeSelector: map[string]string{k: v}, // only launch on our two nodes
  909. },
  910. })
  911. framework.ExpectNoError(err)
  912. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  913. pod, err = c.Pods(ns).Get(podName)
  914. framework.ExpectNoError(err)
  915. By("Trying to launch another pod, now with podAntiAffinity with same Labels.")
  916. labelPodName := "with-podantiaffinity-" + string(uuid.NewUUID())
  917. _, err = c.Pods(ns).Create(&api.Pod{
  918. TypeMeta: unversioned.TypeMeta{
  919. Kind: "Pod",
  920. },
  921. ObjectMeta: api.ObjectMeta{
  922. Name: labelPodName,
  923. Labels: map[string]string{"service": "Diff"},
  924. Annotations: map[string]string{
  925. "scheduler.alpha.kubernetes.io/affinity": `
  926. {"podAntiAffinity": {
  927. "requiredDuringSchedulingIgnoredDuringExecution": [{
  928. "labelSelector":{
  929. "matchExpressions": [{
  930. "key": "service",
  931. "operator": "In",
  932. "values": ["S1", "value2"]
  933. }]
  934. },
  935. "topologyKey": "` + k + `",
  936. "namespaces": ["` + ns + `"]
  937. }]
  938. }}`,
  939. },
  940. },
  941. Spec: api.PodSpec{
  942. Containers: []api.Container{
  943. {
  944. Name: labelPodName,
  945. Image: framework.GetPauseImageName(f.Client),
  946. },
  947. },
  948. NodeSelector: map[string]string{k: v}, // only launch on our two nodes, contradicting the podAntiAffinity
  949. },
  950. })
  951. framework.ExpectNoError(err)
  952. // Wait a bit to allow scheduler to do its thing
  953. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  954. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  955. time.Sleep(10 * time.Second)
  956. verifyResult(c, labelPodName, 3, 1, ns)
  957. })
  958. // test the pod affinity successful matching scenario with multiple Label Operators.
  959. It("validates that InterPodAffinity is respected if matching with multiple Affinities", func() {
  960. // launch a pod to find a node which can launch a pod. We intentionally do
  961. // not just take the node list and choose the first of them. Depending on the
  962. // cluster and the scheduler it might be that a "normal" pod cannot be
  963. // scheduled onto it.
  964. By("Trying to launch a pod with a label to get a node which can launch it.")
  965. podName := "with-label-" + string(uuid.NewUUID())
  966. pod, err := c.Pods(ns).Create(&api.Pod{
  967. TypeMeta: unversioned.TypeMeta{
  968. Kind: "Pod",
  969. },
  970. ObjectMeta: api.ObjectMeta{
  971. Name: podName,
  972. Labels: map[string]string{"security": "S1"},
  973. },
  974. Spec: api.PodSpec{
  975. Containers: []api.Container{
  976. {
  977. Name: podName,
  978. Image: framework.GetPauseImageName(f.Client),
  979. },
  980. },
  981. },
  982. })
  983. framework.ExpectNoError(err)
  984. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  985. pod, err = c.Pods(ns).Get(podName)
  986. framework.ExpectNoError(err)
  987. nodeName := pod.Spec.NodeName
  988. By("Trying to apply a random label on the found node.")
  989. k := "e2e.inter-pod-affinity.kubernetes.io/zone"
  990. v := "kubernetes-e2e"
  991. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  992. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  993. defer framework.RemoveLabelOffNode(c, nodeName, k)
  994. By("Trying to launch the pod, now with multiple pod affinities with diff LabelOperators.")
  995. labelPodName := "with-podaffinity-" + string(uuid.NewUUID())
  996. pod, err = c.Pods(ns).Create(&api.Pod{
  997. TypeMeta: unversioned.TypeMeta{
  998. Kind: "Pod",
  999. },
  1000. ObjectMeta: api.ObjectMeta{
  1001. Name: labelPodName,
  1002. Annotations: map[string]string{
  1003. "scheduler.alpha.kubernetes.io/affinity": `
  1004. {"podAffinity": {
  1005. "requiredDuringSchedulingIgnoredDuringExecution": [{
  1006. "labelSelector":{
  1007. "matchExpressions": [{
  1008. "key": "security",
  1009. "operator": "In",
  1010. "values": ["S1", "value2"]
  1011. },
  1012. {
  1013. "key": "security",
  1014. "operator": "NotIn",
  1015. "values": ["S2"]
  1016. },
  1017. {
  1018. "key": "security",
  1019. "operator":"Exists"
  1020. }]
  1021. },
  1022. "topologyKey": "` + k + `"
  1023. }]
  1024. }}`,
  1025. },
  1026. },
  1027. Spec: api.PodSpec{
  1028. Containers: []api.Container{
  1029. {
  1030. Name: labelPodName,
  1031. Image: framework.GetPauseImageName(f.Client),
  1032. },
  1033. },
  1034. },
  1035. })
  1036. framework.ExpectNoError(err)
  1037. // check that pod got scheduled. We intentionally DO NOT check that the
  1038. // pod is running because this will create a race condition with the
  1039. // kubelet and the scheduler: the scheduler might have scheduled a pod
  1040. // already when the kubelet does not know about its new label yet. The
  1041. // kubelet will then refuse to launch the pod.
  1042. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, pod.ResourceVersion))
  1043. labelPod, err := c.Pods(ns).Get(labelPodName)
  1044. framework.ExpectNoError(err)
  1045. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  1046. })
  1047. // test the pod affinity and anti affinity successful matching scenario.
  1048. It("validates that InterPod Affinity and AntiAffinity is respected if matching", func() {
  1049. // launch a pod to find a node which can launch a pod. We intentionally do
  1050. // not just take the node list and choose the first of them. Depending on the
  1051. // cluster and the scheduler it might be that a "normal" pod cannot be
  1052. // scheduled onto it.
  1053. By("Trying to launch a pod with a label to get a node which can launch it.")
  1054. podName := "with-label-" + string(uuid.NewUUID())
  1055. pod, err := c.Pods(ns).Create(&api.Pod{
  1056. TypeMeta: unversioned.TypeMeta{
  1057. Kind: "Pod",
  1058. },
  1059. ObjectMeta: api.ObjectMeta{
  1060. Name: podName,
  1061. Labels: map[string]string{"security": "S1"},
  1062. },
  1063. Spec: api.PodSpec{
  1064. Containers: []api.Container{
  1065. {
  1066. Name: podName,
  1067. Image: framework.GetPauseImageName(f.Client),
  1068. },
  1069. },
  1070. },
  1071. })
  1072. framework.ExpectNoError(err)
  1073. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  1074. pod, err = c.Pods(ns).Get(podName)
  1075. framework.ExpectNoError(err)
  1076. nodeName := pod.Spec.NodeName
  1077. By("Trying to apply a random label on the found node.")
  1078. k := "e2e.inter-pod-affinity.kubernetes.io/zone"
  1079. v := "e2e-testing"
  1080. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  1081. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  1082. defer framework.RemoveLabelOffNode(c, nodeName, k)
  1083. By("Trying to launch the pod, now with Pod affinity and anti affinity.")
  1084. labelPodName := "with-podantiaffinity-" + string(uuid.NewUUID())
  1085. pod, err = c.Pods(ns).Create(&api.Pod{
  1086. TypeMeta: unversioned.TypeMeta{
  1087. Kind: "Pod",
  1088. },
  1089. ObjectMeta: api.ObjectMeta{
  1090. Name: labelPodName,
  1091. Annotations: map[string]string{
  1092. "scheduler.alpha.kubernetes.io/affinity": `
  1093. {"podAffinity": {
  1094. "requiredDuringSchedulingIgnoredDuringExecution": [{
  1095. "labelSelector": {
  1096. "matchExpressions": [{
  1097. "key": "security",
  1098. "operator": "In",
  1099. "values":["S1"]
  1100. }]
  1101. },
  1102. "topologyKey": "` + k + `"
  1103. }]
  1104. },
  1105. "podAntiAffinity": {
  1106. "requiredDuringSchedulingIgnoredDuringExecution": [{
  1107. "labelSelector": {
  1108. "matchExpressions": [{
  1109. "key": "security",
  1110. "operator": "In",
  1111. "values":["S2"]
  1112. }]
  1113. },
  1114. "topologyKey": "` + k + `"
  1115. }]
  1116. }}`,
  1117. },
  1118. },
  1119. Spec: api.PodSpec{
  1120. Containers: []api.Container{
  1121. {
  1122. Name: labelPodName,
  1123. Image: framework.GetPauseImageName(f.Client),
  1124. },
  1125. },
  1126. },
  1127. })
  1128. framework.ExpectNoError(err)
  1129. // check that pod got scheduled. We intentionally DO NOT check that the
  1130. // pod is running because this will create a race condition with the
  1131. // kubelet and the scheduler: the scheduler might have scheduled a pod
  1132. // already when the kubelet does not know about its new label yet. The
  1133. // kubelet will then refuse to launch the pod.
  1134. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, pod.ResourceVersion))
  1135. labelPod, err := c.Pods(ns).Get(labelPodName)
  1136. framework.ExpectNoError(err)
  1137. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  1138. })
  1139. // Verify that an escaped JSON string of pod affinity and pod anti affinity in a YAML PodSpec works.
  1140. It("validates that embedding the JSON PodAffinity and PodAntiAffinity setting as a string in the annotation value work", func() {
  1141. // launch a pod to find a node which can launch a pod. We intentionally do
  1142. // not just take the node list and choose the first of them. Depending on the
  1143. // cluster and the scheduler it might be that a "normal" pod cannot be
  1144. // scheduled onto it.
  1145. By("Trying to launch a pod with label to get a node which can launch it.")
  1146. podName := "with-label-" + string(uuid.NewUUID())
  1147. pod, err := c.Pods(ns).Create(&api.Pod{
  1148. TypeMeta: unversioned.TypeMeta{
  1149. Kind: "Pod",
  1150. },
  1151. ObjectMeta: api.ObjectMeta{
  1152. Name: podName,
  1153. Labels: map[string]string{"security": "S1"},
  1154. },
  1155. Spec: api.PodSpec{
  1156. Containers: []api.Container{
  1157. {
  1158. Name: podName,
  1159. Image: framework.GetPauseImageName(f.Client),
  1160. },
  1161. },
  1162. },
  1163. })
  1164. framework.ExpectNoError(err)
  1165. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  1166. pod, err = c.Pods(ns).Get(podName)
  1167. framework.ExpectNoError(err)
  1168. nodeName := pod.Spec.NodeName
  1169. By("Trying to apply a label with fake az info on the found node.")
  1170. k := "e2e.inter-pod-affinity.kubernetes.io/zone"
  1171. v := "e2e-az1"
  1172. framework.AddOrUpdateLabelOnNode(c, nodeName, k, v)
  1173. framework.ExpectNodeHasLabel(c, nodeName, k, v)
  1174. defer framework.RemoveLabelOffNode(c, nodeName, k)
  1175. By("Trying to launch a pod that with PodAffinity & PodAntiAffinity setting as embedded JSON string in the annotation value.")
  1176. labelPodName := podWithPodAffinity.Name
  1177. pod, err = c.Pods(ns).Create(&podWithPodAffinity)
  1178. framework.ExpectNoError(err)
  1179. // check that pod got scheduled. We intentionally DO NOT check that the
  1180. // pod is running because this will create a race condition with the
  1181. // kubelet and the scheduler: the scheduler might have scheduled a pod
  1182. // already when the kubelet does not know about its new label yet. The
  1183. // kubelet will then refuse to launch the pod.
  1184. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, labelPodName, pod.ResourceVersion))
  1185. labelPod, err := c.Pods(ns).Get(labelPodName)
  1186. framework.ExpectNoError(err)
  1187. Expect(labelPod.Spec.NodeName).To(Equal(nodeName))
  1188. })
  1189. // 1. Run a pod to get an available node, then delete the pod
  1190. // 2. Taint the node with a random taint
  1191. // 3. Try to relaunch the pod with tolerations tolerate the taints on node,
  1192. // and the pod's nodeName specified to the name of node found in step 1
  1193. It("validates that taints-tolerations is respected if matching", func() {
  1194. // launch a pod to find a node which can launch a pod. We intentionally do
  1195. // not just take the node list and choose the first of them. Depending on the
  1196. // cluster and the scheduler it might be that a "normal" pod cannot be
  1197. // scheduled onto it.
  1198. By("Trying to launch a pod without a toleration to get a node which can launch it.")
  1199. podName := "without-toleration"
  1200. pod, err := c.Pods(ns).Create(&api.Pod{
  1201. TypeMeta: unversioned.TypeMeta{
  1202. Kind: "Pod",
  1203. },
  1204. ObjectMeta: api.ObjectMeta{
  1205. Name: podName,
  1206. },
  1207. Spec: api.PodSpec{
  1208. Containers: []api.Container{
  1209. {
  1210. Name: podName,
  1211. Image: framework.GetPauseImageName(f.Client),
  1212. },
  1213. },
  1214. },
  1215. })
  1216. framework.ExpectNoError(err)
  1217. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  1218. pod, err = c.Pods(ns).Get(podName)
  1219. framework.ExpectNoError(err)
  1220. nodeName := pod.Spec.NodeName
  1221. By("Explicitly delete pod here to free the resource it takes.")
  1222. err = c.Pods(ns).Delete(podName, api.NewDeleteOptions(0))
  1223. framework.ExpectNoError(err)
  1224. By("Trying to apply a random taint on the found node.")
  1225. taintName := fmt.Sprintf("kubernetes.io/e2e-taint-key-%s", string(uuid.NewUUID()))
  1226. taintValue := "testing-taint-value"
  1227. taintEffect := api.TaintEffectNoSchedule
  1228. framework.AddOrUpdateTaintOnNode(c, nodeName, api.Taint{Key: taintName, Value: taintValue, Effect: taintEffect})
  1229. framework.ExpectNodeHasTaint(c, nodeName, taintName)
  1230. defer framework.RemoveTaintOffNode(c, nodeName, taintName)
  1231. By("Trying to apply a random label on the found node.")
  1232. labelKey := fmt.Sprintf("kubernetes.io/e2e-label-key-%s", string(uuid.NewUUID()))
  1233. labelValue := "testing-label-value"
  1234. framework.AddOrUpdateLabelOnNode(c, nodeName, labelKey, labelValue)
  1235. framework.ExpectNodeHasLabel(c, nodeName, labelKey, labelValue)
  1236. defer framework.RemoveLabelOffNode(c, nodeName, labelKey)
  1237. By("Trying to relaunch the pod, now with tolerations.")
  1238. tolerationPodName := "with-tolerations"
  1239. pod, err = c.Pods(ns).Create(&api.Pod{
  1240. TypeMeta: unversioned.TypeMeta{
  1241. Kind: "Pod",
  1242. },
  1243. ObjectMeta: api.ObjectMeta{
  1244. Name: tolerationPodName,
  1245. Annotations: map[string]string{
  1246. "scheduler.alpha.kubernetes.io/tolerations": `
  1247. [
  1248. {
  1249. "key": "` + taintName + `",
  1250. "value": "` + taintValue + `",
  1251. "effect": "` + string(taintEffect) + `"
  1252. }
  1253. ]`,
  1254. },
  1255. },
  1256. Spec: api.PodSpec{
  1257. NodeSelector: map[string]string{labelKey: labelValue},
  1258. Containers: []api.Container{
  1259. {
  1260. Name: tolerationPodName,
  1261. Image: framework.GetPauseImageName(f.Client),
  1262. },
  1263. },
  1264. },
  1265. })
  1266. framework.ExpectNoError(err)
  1267. // check that pod got scheduled. We intentionally DO NOT check that the
  1268. // pod is running because this will create a race condition with the
  1269. // kubelet and the scheduler: the scheduler might have scheduled a pod
  1270. // already when the kubelet does not know about its new taint yet. The
  1271. // kubelet will then refuse to launch the pod.
  1272. framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, tolerationPodName, pod.ResourceVersion))
  1273. deployedPod, err := c.Pods(ns).Get(tolerationPodName)
  1274. framework.ExpectNoError(err)
  1275. Expect(deployedPod.Spec.NodeName).To(Equal(nodeName))
  1276. })
  1277. // 1. Run a pod to get an available node, then delete the pod
  1278. // 2. Taint the node with a random taint
  1279. // 3. Try to relaunch the pod still no tolerations,
  1280. // and the pod's nodeName specified to the name of node found in step 1
  1281. It("validates that taints-tolerations is respected if not matching", func() {
  1282. // launch a pod to find a node which can launch a pod. We intentionally do
  1283. // not just take the node list and choose the first of them. Depending on the
  1284. // cluster and the scheduler it might be that a "normal" pod cannot be
  1285. // scheduled onto it.
  1286. By("Trying to launch a pod without a toleration to get a node which can launch it.")
  1287. podName := "without-toleration"
  1288. pod, err := c.Pods(ns).Create(&api.Pod{
  1289. TypeMeta: unversioned.TypeMeta{
  1290. Kind: "Pod",
  1291. },
  1292. ObjectMeta: api.ObjectMeta{
  1293. Name: podName,
  1294. },
  1295. Spec: api.PodSpec{
  1296. Containers: []api.Container{
  1297. {
  1298. Name: podName,
  1299. Image: framework.GetPauseImageName(f.Client),
  1300. },
  1301. },
  1302. },
  1303. })
  1304. framework.ExpectNoError(err)
  1305. framework.ExpectNoError(framework.WaitForPodRunningInNamespace(c, pod))
  1306. pod, err = c.Pods(ns).Get(podName)
  1307. framework.ExpectNoError(err)
  1308. nodeName := pod.Spec.NodeName
  1309. By("Explicitly delete pod here to free the resource it takes.")
  1310. err = c.Pods(ns).Delete(podName, api.NewDeleteOptions(0))
  1311. framework.ExpectNoError(err)
  1312. By("Trying to apply a random taint on the found node.")
  1313. taintName := fmt.Sprintf("kubernetes.io/e2e-taint-key-%s", string(uuid.NewUUID()))
  1314. taintValue := "testing-taint-value"
  1315. taintEffect := api.TaintEffectNoSchedule
  1316. framework.AddOrUpdateTaintOnNode(c, nodeName, api.Taint{Key: taintName, Value: taintValue, Effect: taintEffect})
  1317. framework.ExpectNodeHasTaint(c, nodeName, taintName)
  1318. defer framework.RemoveTaintOffNode(c, nodeName, taintName)
  1319. By("Trying to apply a random label on the found node.")
  1320. labelKey := fmt.Sprintf("kubernetes.io/e2e-label-key-%s", string(uuid.NewUUID()))
  1321. labelValue := "testing-label-value"
  1322. framework.AddOrUpdateLabelOnNode(c, nodeName, labelKey, labelValue)
  1323. framework.ExpectNodeHasLabel(c, nodeName, labelKey, labelValue)
  1324. defer framework.RemoveLabelOffNode(c, nodeName, labelKey)
  1325. By("Trying to relaunch the pod, still no tolerations.")
  1326. podNameNoTolerations := "still-no-tolerations"
  1327. podNoTolerations := &api.Pod{
  1328. TypeMeta: unversioned.TypeMeta{
  1329. Kind: "Pod",
  1330. },
  1331. ObjectMeta: api.ObjectMeta{
  1332. Name: podNameNoTolerations,
  1333. },
  1334. Spec: api.PodSpec{
  1335. NodeSelector: map[string]string{labelKey: labelValue},
  1336. Containers: []api.Container{
  1337. {
  1338. Name: podNameNoTolerations,
  1339. Image: framework.GetPauseImageName(f.Client),
  1340. },
  1341. },
  1342. },
  1343. }
  1344. _, err = c.Pods(ns).Create(podNoTolerations)
  1345. framework.ExpectNoError(err)
  1346. // Wait a bit to allow scheduler to do its thing
  1347. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  1348. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  1349. time.Sleep(10 * time.Second)
  1350. verifyResult(c, podNameNoTolerations, 0, 1, ns)
  1351. By("Removing taint off the node")
  1352. framework.RemoveTaintOffNode(c, nodeName, taintName)
  1353. // Wait a bit to allow scheduler to do its thing
  1354. // TODO: this is brittle; there's no guarantee the scheduler will have run in 10 seconds.
  1355. framework.Logf("Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.")
  1356. time.Sleep(10 * time.Second)
  1357. // as taint removed off the node, expect the pod can be successfully scheduled
  1358. verifyResult(c, podNameNoTolerations, 1, 0, ns)
  1359. })
  1360. })