replica_set_test.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  1. /*
  2. Copyright 2016 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 replicaset
  14. import (
  15. "errors"
  16. "fmt"
  17. "math/rand"
  18. "net/http/httptest"
  19. "net/url"
  20. "reflect"
  21. "strings"
  22. "sync"
  23. "testing"
  24. "time"
  25. apps "k8s.io/api/apps/v1"
  26. "k8s.io/api/core/v1"
  27. apiequality "k8s.io/apimachinery/pkg/api/equality"
  28. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  29. "k8s.io/apimachinery/pkg/runtime"
  30. "k8s.io/apimachinery/pkg/runtime/schema"
  31. "k8s.io/apimachinery/pkg/util/sets"
  32. "k8s.io/apimachinery/pkg/util/uuid"
  33. "k8s.io/apimachinery/pkg/util/wait"
  34. "k8s.io/apimachinery/pkg/watch"
  35. "k8s.io/client-go/informers"
  36. clientset "k8s.io/client-go/kubernetes"
  37. "k8s.io/client-go/kubernetes/fake"
  38. restclient "k8s.io/client-go/rest"
  39. core "k8s.io/client-go/testing"
  40. "k8s.io/client-go/tools/cache"
  41. utiltesting "k8s.io/client-go/util/testing"
  42. "k8s.io/client-go/util/workqueue"
  43. "k8s.io/kubernetes/pkg/controller"
  44. . "k8s.io/kubernetes/pkg/controller/testutil"
  45. "k8s.io/kubernetes/pkg/securitycontext"
  46. )
  47. func testNewReplicaSetControllerFromClient(client clientset.Interface, stopCh chan struct{}, burstReplicas int) (*ReplicaSetController, informers.SharedInformerFactory) {
  48. informers := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc())
  49. ret := NewReplicaSetController(
  50. informers.Apps().V1().ReplicaSets(),
  51. informers.Core().V1().Pods(),
  52. client,
  53. burstReplicas,
  54. )
  55. ret.podListerSynced = alwaysReady
  56. ret.rsListerSynced = alwaysReady
  57. return ret, informers
  58. }
  59. func skipListerFunc(verb string, url url.URL) bool {
  60. if verb != "GET" {
  61. return false
  62. }
  63. if strings.HasSuffix(url.Path, "/pods") || strings.Contains(url.Path, "/replicasets") {
  64. return true
  65. }
  66. return false
  67. }
  68. var alwaysReady = func() bool { return true }
  69. func newReplicaSet(replicas int, selectorMap map[string]string) *apps.ReplicaSet {
  70. rs := &apps.ReplicaSet{
  71. TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "ReplicaSet"},
  72. ObjectMeta: metav1.ObjectMeta{
  73. UID: uuid.NewUUID(),
  74. Name: "foobar",
  75. Namespace: metav1.NamespaceDefault,
  76. ResourceVersion: "18",
  77. },
  78. Spec: apps.ReplicaSetSpec{
  79. Replicas: func() *int32 { i := int32(replicas); return &i }(),
  80. Selector: &metav1.LabelSelector{MatchLabels: selectorMap},
  81. Template: v1.PodTemplateSpec{
  82. ObjectMeta: metav1.ObjectMeta{
  83. Labels: map[string]string{
  84. "name": "foo",
  85. "type": "production",
  86. },
  87. },
  88. Spec: v1.PodSpec{
  89. Containers: []v1.Container{
  90. {
  91. Image: "foo/bar",
  92. TerminationMessagePath: v1.TerminationMessagePathDefault,
  93. ImagePullPolicy: v1.PullIfNotPresent,
  94. SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(),
  95. },
  96. },
  97. RestartPolicy: v1.RestartPolicyAlways,
  98. DNSPolicy: v1.DNSDefault,
  99. NodeSelector: map[string]string{
  100. "baz": "blah",
  101. },
  102. },
  103. },
  104. },
  105. }
  106. return rs
  107. }
  108. // create a pod with the given phase for the given rs (same selectors and namespace)
  109. func newPod(name string, rs *apps.ReplicaSet, status v1.PodPhase, lastTransitionTime *metav1.Time, properlyOwned bool) *v1.Pod {
  110. var conditions []v1.PodCondition
  111. if status == v1.PodRunning {
  112. condition := v1.PodCondition{Type: v1.PodReady, Status: v1.ConditionTrue}
  113. if lastTransitionTime != nil {
  114. condition.LastTransitionTime = *lastTransitionTime
  115. }
  116. conditions = append(conditions, condition)
  117. }
  118. var controllerReference metav1.OwnerReference
  119. if properlyOwned {
  120. var trueVar = true
  121. controllerReference = metav1.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar}
  122. }
  123. return &v1.Pod{
  124. ObjectMeta: metav1.ObjectMeta{
  125. Name: name,
  126. Namespace: rs.Namespace,
  127. Labels: rs.Spec.Selector.MatchLabels,
  128. OwnerReferences: []metav1.OwnerReference{controllerReference},
  129. },
  130. Status: v1.PodStatus{Phase: status, Conditions: conditions},
  131. }
  132. }
  133. // create count pods with the given phase for the given ReplicaSet (same selectors and namespace), and add them to the store.
  134. func newPodList(store cache.Store, count int, status v1.PodPhase, labelMap map[string]string, rs *apps.ReplicaSet, name string) *v1.PodList {
  135. pods := []v1.Pod{}
  136. var trueVar = true
  137. controllerReference := metav1.OwnerReference{UID: rs.UID, APIVersion: "v1beta1", Kind: "ReplicaSet", Name: rs.Name, Controller: &trueVar}
  138. for i := 0; i < count; i++ {
  139. pod := newPod(fmt.Sprintf("%s%d", name, i), rs, status, nil, false)
  140. pod.ObjectMeta.Labels = labelMap
  141. pod.OwnerReferences = []metav1.OwnerReference{controllerReference}
  142. if store != nil {
  143. store.Add(pod)
  144. }
  145. pods = append(pods, *pod)
  146. }
  147. return &v1.PodList{
  148. Items: pods,
  149. }
  150. }
  151. // processSync initiates a sync via processNextWorkItem() to test behavior that
  152. // depends on both functions (such as re-queueing on sync error).
  153. func processSync(rsc *ReplicaSetController, key string) error {
  154. // Save old syncHandler and replace with one that captures the error.
  155. oldSyncHandler := rsc.syncHandler
  156. defer func() {
  157. rsc.syncHandler = oldSyncHandler
  158. }()
  159. var syncErr error
  160. rsc.syncHandler = func(key string) error {
  161. syncErr = oldSyncHandler(key)
  162. return syncErr
  163. }
  164. rsc.queue.Add(key)
  165. rsc.processNextWorkItem()
  166. return syncErr
  167. }
  168. func validateSyncReplicaSet(t *testing.T, fakePodControl *controller.FakePodControl, expectedCreates, expectedDeletes, expectedPatches int) {
  169. if e, a := expectedCreates, len(fakePodControl.Templates); e != a {
  170. t.Errorf("Unexpected number of creates. Expected %d, saw %d\n", e, a)
  171. }
  172. if e, a := expectedDeletes, len(fakePodControl.DeletePodName); e != a {
  173. t.Errorf("Unexpected number of deletes. Expected %d, saw %d\n", e, a)
  174. }
  175. if e, a := expectedPatches, len(fakePodControl.Patches); e != a {
  176. t.Errorf("Unexpected number of patches. Expected %d, saw %d\n", e, a)
  177. }
  178. }
  179. func TestSyncReplicaSetDoesNothing(t *testing.T) {
  180. client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  181. fakePodControl := controller.FakePodControl{}
  182. stopCh := make(chan struct{})
  183. defer close(stopCh)
  184. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas)
  185. // 2 running pods, a controller with 2 replicas, sync is a no-op
  186. labelMap := map[string]string{"foo": "bar"}
  187. rsSpec := newReplicaSet(2, labelMap)
  188. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec)
  189. newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 2, v1.PodRunning, labelMap, rsSpec, "pod")
  190. manager.podControl = &fakePodControl
  191. manager.syncReplicaSet(GetKey(rsSpec, t))
  192. validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0)
  193. }
  194. func TestDeleteFinalStateUnknown(t *testing.T) {
  195. client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  196. fakePodControl := controller.FakePodControl{}
  197. stopCh := make(chan struct{})
  198. defer close(stopCh)
  199. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas)
  200. manager.podControl = &fakePodControl
  201. received := make(chan string)
  202. manager.syncHandler = func(key string) error {
  203. received <- key
  204. return nil
  205. }
  206. // The DeletedFinalStateUnknown object should cause the ReplicaSet manager to insert
  207. // the controller matching the selectors of the deleted pod into the work queue.
  208. labelMap := map[string]string{"foo": "bar"}
  209. rsSpec := newReplicaSet(1, labelMap)
  210. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec)
  211. pods := newPodList(nil, 1, v1.PodRunning, labelMap, rsSpec, "pod")
  212. manager.deletePod(cache.DeletedFinalStateUnknown{Key: "foo", Obj: &pods.Items[0]})
  213. go manager.worker()
  214. expected := GetKey(rsSpec, t)
  215. select {
  216. case key := <-received:
  217. if key != expected {
  218. t.Errorf("Unexpected sync all for ReplicaSet %v, expected %v", key, expected)
  219. }
  220. case <-time.After(wait.ForeverTestTimeout):
  221. t.Errorf("Processing DeleteFinalStateUnknown took longer than expected")
  222. }
  223. }
  224. // Tell the rs to create 100 replicas, but simulate a limit (like a quota limit)
  225. // of 10, and verify that the rs doesn't make 100 create calls per sync pass
  226. func TestSyncReplicaSetCreateFailures(t *testing.T) {
  227. fakePodControl := controller.FakePodControl{}
  228. fakePodControl.CreateLimit = 10
  229. labelMap := map[string]string{"foo": "bar"}
  230. rs := newReplicaSet(fakePodControl.CreateLimit*10, labelMap)
  231. client := fake.NewSimpleClientset(rs)
  232. stopCh := make(chan struct{})
  233. defer close(stopCh)
  234. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas)
  235. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  236. manager.podControl = &fakePodControl
  237. manager.syncReplicaSet(GetKey(rs, t))
  238. validateSyncReplicaSet(t, &fakePodControl, fakePodControl.CreateLimit, 0, 0)
  239. expectedLimit := 0
  240. for pass := uint8(0); expectedLimit <= fakePodControl.CreateLimit; pass++ {
  241. expectedLimit += controller.SlowStartInitialBatchSize << pass
  242. }
  243. if fakePodControl.CreateCallCount > expectedLimit {
  244. t.Errorf("Unexpected number of create calls. Expected <= %d, saw %d\n", fakePodControl.CreateLimit*2, fakePodControl.CreateCallCount)
  245. }
  246. }
  247. func TestSyncReplicaSetDormancy(t *testing.T) {
  248. // Setup a test server so we can lie about the current state of pods
  249. fakeHandler := utiltesting.FakeHandler{
  250. StatusCode: 200,
  251. ResponseBody: "{}",
  252. SkipRequestFn: skipListerFunc,
  253. T: t,
  254. }
  255. testServer := httptest.NewServer(&fakeHandler)
  256. defer testServer.Close()
  257. client := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  258. fakePodControl := controller.FakePodControl{}
  259. stopCh := make(chan struct{})
  260. defer close(stopCh)
  261. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas)
  262. manager.podControl = &fakePodControl
  263. labelMap := map[string]string{"foo": "bar"}
  264. rsSpec := newReplicaSet(2, labelMap)
  265. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec)
  266. newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap, rsSpec, "pod")
  267. // Creates a replica and sets expectations
  268. rsSpec.Status.Replicas = 1
  269. rsSpec.Status.ReadyReplicas = 1
  270. rsSpec.Status.AvailableReplicas = 1
  271. manager.syncReplicaSet(GetKey(rsSpec, t))
  272. validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0)
  273. // Expectations prevents replicas but not an update on status
  274. rsSpec.Status.Replicas = 0
  275. rsSpec.Status.ReadyReplicas = 0
  276. rsSpec.Status.AvailableReplicas = 0
  277. fakePodControl.Clear()
  278. manager.syncReplicaSet(GetKey(rsSpec, t))
  279. validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0)
  280. // Get the key for the controller
  281. rsKey, err := controller.KeyFunc(rsSpec)
  282. if err != nil {
  283. t.Errorf("Couldn't get key for object %#v: %v", rsSpec, err)
  284. }
  285. // Lowering expectations should lead to a sync that creates a replica, however the
  286. // fakePodControl error will prevent this, leaving expectations at 0, 0
  287. manager.expectations.CreationObserved(rsKey)
  288. rsSpec.Status.Replicas = 1
  289. rsSpec.Status.ReadyReplicas = 1
  290. rsSpec.Status.AvailableReplicas = 1
  291. fakePodControl.Clear()
  292. fakePodControl.Err = fmt.Errorf("Fake Error")
  293. manager.syncReplicaSet(GetKey(rsSpec, t))
  294. validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0)
  295. // This replica should not need a Lowering of expectations, since the previous create failed
  296. fakePodControl.Clear()
  297. fakePodControl.Err = nil
  298. manager.syncReplicaSet(GetKey(rsSpec, t))
  299. validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0)
  300. // 2 PUT for the ReplicaSet status during dormancy window.
  301. // Note that the pod creates go through pod control so they're not recorded.
  302. fakeHandler.ValidateRequestCount(t, 2)
  303. }
  304. func TestPodControllerLookup(t *testing.T) {
  305. stopCh := make(chan struct{})
  306. defer close(stopCh)
  307. manager, informers := testNewReplicaSetControllerFromClient(clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}}), stopCh, BurstReplicas)
  308. testCases := []struct {
  309. inRSs []*apps.ReplicaSet
  310. pod *v1.Pod
  311. outRSName string
  312. }{
  313. // pods without labels don't match any ReplicaSets
  314. {
  315. inRSs: []*apps.ReplicaSet{
  316. {ObjectMeta: metav1.ObjectMeta{Name: "basic"}}},
  317. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo1", Namespace: metav1.NamespaceAll}},
  318. outRSName: "",
  319. },
  320. // Matching labels, not namespace
  321. {
  322. inRSs: []*apps.ReplicaSet{
  323. {
  324. ObjectMeta: metav1.ObjectMeta{Name: "foo"},
  325. Spec: apps.ReplicaSetSpec{
  326. Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}},
  327. },
  328. },
  329. },
  330. pod: &v1.Pod{
  331. ObjectMeta: metav1.ObjectMeta{
  332. Name: "foo2", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}},
  333. outRSName: "",
  334. },
  335. // Matching ns and labels returns the key to the ReplicaSet, not the ReplicaSet name
  336. {
  337. inRSs: []*apps.ReplicaSet{
  338. {
  339. ObjectMeta: metav1.ObjectMeta{Name: "bar", Namespace: "ns"},
  340. Spec: apps.ReplicaSetSpec{
  341. Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}},
  342. },
  343. },
  344. },
  345. pod: &v1.Pod{
  346. ObjectMeta: metav1.ObjectMeta{
  347. Name: "foo3", Namespace: "ns", Labels: map[string]string{"foo": "bar"}}},
  348. outRSName: "bar",
  349. },
  350. }
  351. for _, c := range testCases {
  352. for _, r := range c.inRSs {
  353. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(r)
  354. }
  355. if rss := manager.getPodReplicaSets(c.pod); rss != nil {
  356. if len(rss) != 1 {
  357. t.Errorf("len(rss) = %v, want %v", len(rss), 1)
  358. continue
  359. }
  360. rs := rss[0]
  361. if c.outRSName != rs.Name {
  362. t.Errorf("Got replica set %+v expected %+v", rs.Name, c.outRSName)
  363. }
  364. } else if c.outRSName != "" {
  365. t.Errorf("Expected a replica set %v pod %v, found none", c.outRSName, c.pod.Name)
  366. }
  367. }
  368. }
  369. func TestWatchControllers(t *testing.T) {
  370. fakeWatch := watch.NewFake()
  371. client := fake.NewSimpleClientset()
  372. client.PrependWatchReactor("replicasets", core.DefaultWatchReactor(fakeWatch, nil))
  373. stopCh := make(chan struct{})
  374. defer close(stopCh)
  375. informers := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc())
  376. manager := NewReplicaSetController(
  377. informers.Apps().V1().ReplicaSets(),
  378. informers.Core().V1().Pods(),
  379. client,
  380. BurstReplicas,
  381. )
  382. informers.Start(stopCh)
  383. var testRSSpec apps.ReplicaSet
  384. received := make(chan string)
  385. // The update sent through the fakeWatcher should make its way into the workqueue,
  386. // and eventually into the syncHandler. The handler validates the received controller
  387. // and closes the received channel to indicate that the test can finish.
  388. manager.syncHandler = func(key string) error {
  389. obj, exists, err := informers.Apps().V1().ReplicaSets().Informer().GetIndexer().GetByKey(key)
  390. if !exists || err != nil {
  391. t.Errorf("Expected to find replica set under key %v", key)
  392. }
  393. rsSpec := *obj.(*apps.ReplicaSet)
  394. if !apiequality.Semantic.DeepDerivative(rsSpec, testRSSpec) {
  395. t.Errorf("Expected %#v, but got %#v", testRSSpec, rsSpec)
  396. }
  397. close(received)
  398. return nil
  399. }
  400. // Start only the ReplicaSet watcher and the workqueue, send a watch event,
  401. // and make sure it hits the sync method.
  402. go wait.Until(manager.worker, 10*time.Millisecond, stopCh)
  403. testRSSpec.Name = "foo"
  404. fakeWatch.Add(&testRSSpec)
  405. select {
  406. case <-received:
  407. case <-time.After(wait.ForeverTestTimeout):
  408. t.Errorf("unexpected timeout from result channel")
  409. }
  410. }
  411. func TestWatchPods(t *testing.T) {
  412. client := fake.NewSimpleClientset()
  413. fakeWatch := watch.NewFake()
  414. client.PrependWatchReactor("pods", core.DefaultWatchReactor(fakeWatch, nil))
  415. stopCh := make(chan struct{})
  416. defer close(stopCh)
  417. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas)
  418. // Put one ReplicaSet into the shared informer
  419. labelMap := map[string]string{"foo": "bar"}
  420. testRSSpec := newReplicaSet(1, labelMap)
  421. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(testRSSpec)
  422. received := make(chan string)
  423. // The pod update sent through the fakeWatcher should figure out the managing ReplicaSet and
  424. // send it into the syncHandler.
  425. manager.syncHandler = func(key string) error {
  426. namespace, name, err := cache.SplitMetaNamespaceKey(key)
  427. if err != nil {
  428. t.Errorf("Error splitting key: %v", err)
  429. }
  430. rsSpec, err := manager.rsLister.ReplicaSets(namespace).Get(name)
  431. if err != nil {
  432. t.Errorf("Expected to find replica set under key %v: %v", key, err)
  433. }
  434. if !apiequality.Semantic.DeepDerivative(rsSpec, testRSSpec) {
  435. t.Errorf("\nExpected %#v,\nbut got %#v", testRSSpec, rsSpec)
  436. }
  437. close(received)
  438. return nil
  439. }
  440. // Start only the pod watcher and the workqueue, send a watch event,
  441. // and make sure it hits the sync method for the right ReplicaSet.
  442. go informers.Core().V1().Pods().Informer().Run(stopCh)
  443. go manager.Run(1, stopCh)
  444. pods := newPodList(nil, 1, v1.PodRunning, labelMap, testRSSpec, "pod")
  445. testPod := pods.Items[0]
  446. testPod.Status.Phase = v1.PodFailed
  447. fakeWatch.Add(&testPod)
  448. select {
  449. case <-received:
  450. case <-time.After(wait.ForeverTestTimeout):
  451. t.Errorf("unexpected timeout from result channel")
  452. }
  453. }
  454. func TestUpdatePods(t *testing.T) {
  455. stopCh := make(chan struct{})
  456. defer close(stopCh)
  457. manager, informers := testNewReplicaSetControllerFromClient(fake.NewSimpleClientset(), stopCh, BurstReplicas)
  458. received := make(chan string)
  459. manager.syncHandler = func(key string) error {
  460. namespace, name, err := cache.SplitMetaNamespaceKey(key)
  461. if err != nil {
  462. t.Errorf("Error splitting key: %v", err)
  463. }
  464. rsSpec, err := manager.rsLister.ReplicaSets(namespace).Get(name)
  465. if err != nil {
  466. t.Errorf("Expected to find replica set under key %v: %v", key, err)
  467. }
  468. received <- rsSpec.Name
  469. return nil
  470. }
  471. go wait.Until(manager.worker, 10*time.Millisecond, stopCh)
  472. // Put 2 ReplicaSets and one pod into the informers
  473. labelMap1 := map[string]string{"foo": "bar"}
  474. testRSSpec1 := newReplicaSet(1, labelMap1)
  475. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(testRSSpec1)
  476. testRSSpec2 := *testRSSpec1
  477. labelMap2 := map[string]string{"bar": "foo"}
  478. testRSSpec2.Spec.Selector = &metav1.LabelSelector{MatchLabels: labelMap2}
  479. testRSSpec2.Name = "barfoo"
  480. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(&testRSSpec2)
  481. isController := true
  482. controllerRef1 := metav1.OwnerReference{UID: testRSSpec1.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: testRSSpec1.Name, Controller: &isController}
  483. controllerRef2 := metav1.OwnerReference{UID: testRSSpec2.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: testRSSpec2.Name, Controller: &isController}
  484. // case 1: Pod with a ControllerRef
  485. pod1 := newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0]
  486. pod1.OwnerReferences = []metav1.OwnerReference{controllerRef1}
  487. pod1.ResourceVersion = "1"
  488. pod2 := pod1
  489. pod2.Labels = labelMap2
  490. pod2.ResourceVersion = "2"
  491. manager.updatePod(&pod1, &pod2)
  492. expected := sets.NewString(testRSSpec1.Name)
  493. for _, name := range expected.List() {
  494. t.Logf("Expecting update for %+v", name)
  495. select {
  496. case got := <-received:
  497. if !expected.Has(got) {
  498. t.Errorf("Expected keys %#v got %v", expected, got)
  499. }
  500. case <-time.After(wait.ForeverTestTimeout):
  501. t.Errorf("Expected update notifications for replica sets")
  502. }
  503. }
  504. // case 2: Remove ControllerRef (orphan). Expect to sync label-matching RS.
  505. pod1 = newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0]
  506. pod1.ResourceVersion = "1"
  507. pod1.Labels = labelMap2
  508. pod1.OwnerReferences = []metav1.OwnerReference{controllerRef2}
  509. pod2 = pod1
  510. pod2.OwnerReferences = nil
  511. pod2.ResourceVersion = "2"
  512. manager.updatePod(&pod1, &pod2)
  513. expected = sets.NewString(testRSSpec2.Name)
  514. for _, name := range expected.List() {
  515. t.Logf("Expecting update for %+v", name)
  516. select {
  517. case got := <-received:
  518. if !expected.Has(got) {
  519. t.Errorf("Expected keys %#v got %v", expected, got)
  520. }
  521. case <-time.After(wait.ForeverTestTimeout):
  522. t.Errorf("Expected update notifications for replica sets")
  523. }
  524. }
  525. // case 2: Remove ControllerRef (orphan). Expect to sync both former owner and
  526. // any label-matching RS.
  527. pod1 = newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0]
  528. pod1.ResourceVersion = "1"
  529. pod1.Labels = labelMap2
  530. pod1.OwnerReferences = []metav1.OwnerReference{controllerRef1}
  531. pod2 = pod1
  532. pod2.OwnerReferences = nil
  533. pod2.ResourceVersion = "2"
  534. manager.updatePod(&pod1, &pod2)
  535. expected = sets.NewString(testRSSpec1.Name, testRSSpec2.Name)
  536. for _, name := range expected.List() {
  537. t.Logf("Expecting update for %+v", name)
  538. select {
  539. case got := <-received:
  540. if !expected.Has(got) {
  541. t.Errorf("Expected keys %#v got %v", expected, got)
  542. }
  543. case <-time.After(wait.ForeverTestTimeout):
  544. t.Errorf("Expected update notifications for replica sets")
  545. }
  546. }
  547. // case 4: Keep ControllerRef, change labels. Expect to sync owning RS.
  548. pod1 = newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap1, testRSSpec1, "pod").Items[0]
  549. pod1.ResourceVersion = "1"
  550. pod1.Labels = labelMap1
  551. pod1.OwnerReferences = []metav1.OwnerReference{controllerRef2}
  552. pod2 = pod1
  553. pod2.Labels = labelMap2
  554. pod2.ResourceVersion = "2"
  555. manager.updatePod(&pod1, &pod2)
  556. expected = sets.NewString(testRSSpec2.Name)
  557. for _, name := range expected.List() {
  558. t.Logf("Expecting update for %+v", name)
  559. select {
  560. case got := <-received:
  561. if !expected.Has(got) {
  562. t.Errorf("Expected keys %#v got %v", expected, got)
  563. }
  564. case <-time.After(wait.ForeverTestTimeout):
  565. t.Errorf("Expected update notifications for replica sets")
  566. }
  567. }
  568. }
  569. func TestControllerUpdateRequeue(t *testing.T) {
  570. // This server should force a requeue of the controller because it fails to update status.Replicas.
  571. labelMap := map[string]string{"foo": "bar"}
  572. rs := newReplicaSet(1, labelMap)
  573. client := fake.NewSimpleClientset(rs)
  574. client.PrependReactor("update", "replicasets",
  575. func(action core.Action) (bool, runtime.Object, error) {
  576. if action.GetSubresource() != "status" {
  577. return false, nil, nil
  578. }
  579. return true, nil, errors.New("failed to update status")
  580. })
  581. stopCh := make(chan struct{})
  582. defer close(stopCh)
  583. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas)
  584. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  585. rs.Status = apps.ReplicaSetStatus{Replicas: 2}
  586. newPodList(informers.Core().V1().Pods().Informer().GetIndexer(), 1, v1.PodRunning, labelMap, rs, "pod")
  587. fakePodControl := controller.FakePodControl{}
  588. manager.podControl = &fakePodControl
  589. // Enqueue once. Then process it. Disable rate-limiting for this.
  590. manager.queue = workqueue.NewRateLimitingQueue(workqueue.NewMaxOfRateLimiter())
  591. manager.enqueueReplicaSet(rs)
  592. manager.processNextWorkItem()
  593. // It should have been requeued.
  594. if got, want := manager.queue.Len(), 1; got != want {
  595. t.Errorf("queue.Len() = %v, want %v", got, want)
  596. }
  597. }
  598. func TestControllerUpdateStatusWithFailure(t *testing.T) {
  599. rs := newReplicaSet(1, map[string]string{"foo": "bar"})
  600. fakeClient := &fake.Clientset{}
  601. fakeClient.AddReactor("get", "replicasets", func(action core.Action) (bool, runtime.Object, error) { return true, rs, nil })
  602. fakeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) {
  603. return true, &apps.ReplicaSet{}, fmt.Errorf("Fake error")
  604. })
  605. fakeRSClient := fakeClient.AppsV1().ReplicaSets("default")
  606. numReplicas := int32(10)
  607. newStatus := apps.ReplicaSetStatus{Replicas: numReplicas}
  608. updateReplicaSetStatus(fakeRSClient, rs, newStatus)
  609. updates, gets := 0, 0
  610. for _, a := range fakeClient.Actions() {
  611. if a.GetResource().Resource != "replicasets" {
  612. t.Errorf("Unexpected action %+v", a)
  613. continue
  614. }
  615. switch action := a.(type) {
  616. case core.GetAction:
  617. gets++
  618. // Make sure the get is for the right ReplicaSet even though the update failed.
  619. if action.GetName() != rs.Name {
  620. t.Errorf("Expected get for ReplicaSet %v, got %+v instead", rs.Name, action.GetName())
  621. }
  622. case core.UpdateAction:
  623. updates++
  624. // Confirm that the update has the right status.Replicas even though the Get
  625. // returned a ReplicaSet with replicas=1.
  626. if c, ok := action.GetObject().(*apps.ReplicaSet); !ok {
  627. t.Errorf("Expected a ReplicaSet as the argument to update, got %T", c)
  628. } else if c.Status.Replicas != numReplicas {
  629. t.Errorf("Expected update for ReplicaSet to contain replicas %v, got %v instead",
  630. numReplicas, c.Status.Replicas)
  631. }
  632. default:
  633. t.Errorf("Unexpected action %+v", a)
  634. break
  635. }
  636. }
  637. if gets != 1 || updates != 2 {
  638. t.Errorf("Expected 1 get and 2 updates, got %d gets %d updates", gets, updates)
  639. }
  640. }
  641. // TODO: This test is too hairy for a unittest. It should be moved to an E2E suite.
  642. func doTestControllerBurstReplicas(t *testing.T, burstReplicas, numReplicas int) {
  643. labelMap := map[string]string{"foo": "bar"}
  644. rsSpec := newReplicaSet(numReplicas, labelMap)
  645. client := fake.NewSimpleClientset(rsSpec)
  646. fakePodControl := controller.FakePodControl{}
  647. stopCh := make(chan struct{})
  648. defer close(stopCh)
  649. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, burstReplicas)
  650. manager.podControl = &fakePodControl
  651. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec)
  652. expectedPods := int32(0)
  653. pods := newPodList(nil, numReplicas, v1.PodPending, labelMap, rsSpec, "pod")
  654. rsKey, err := controller.KeyFunc(rsSpec)
  655. if err != nil {
  656. t.Errorf("Couldn't get key for object %#v: %v", rsSpec, err)
  657. }
  658. // Size up the controller, then size it down, and confirm the expected create/delete pattern
  659. for _, replicas := range []int32{int32(numReplicas), 0} {
  660. *(rsSpec.Spec.Replicas) = replicas
  661. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec)
  662. for i := 0; i < numReplicas; i += burstReplicas {
  663. manager.syncReplicaSet(GetKey(rsSpec, t))
  664. // The store accrues active pods. It's also used by the ReplicaSet to determine how many
  665. // replicas to create.
  666. activePods := int32(len(informers.Core().V1().Pods().Informer().GetIndexer().List()))
  667. if replicas != 0 {
  668. // This is the number of pods currently "in flight". They were created by the
  669. // ReplicaSet controller above, which then puts the ReplicaSet to sleep till
  670. // all of them have been observed.
  671. expectedPods = replicas - activePods
  672. if expectedPods > int32(burstReplicas) {
  673. expectedPods = int32(burstReplicas)
  674. }
  675. // This validates the ReplicaSet manager sync actually created pods
  676. validateSyncReplicaSet(t, &fakePodControl, int(expectedPods), 0, 0)
  677. // This simulates the watch events for all but 1 of the expected pods.
  678. // None of these should wake the controller because it has expectations==BurstReplicas.
  679. for i := int32(0); i < expectedPods-1; i++ {
  680. informers.Core().V1().Pods().Informer().GetIndexer().Add(&pods.Items[i])
  681. manager.addPod(&pods.Items[i])
  682. }
  683. podExp, exists, err := manager.expectations.GetExpectations(rsKey)
  684. if !exists || err != nil {
  685. t.Fatalf("Did not find expectations for rs.")
  686. }
  687. if add, _ := podExp.GetExpectations(); add != 1 {
  688. t.Fatalf("Expectations are wrong %v", podExp)
  689. }
  690. } else {
  691. expectedPods = (replicas - activePods) * -1
  692. if expectedPods > int32(burstReplicas) {
  693. expectedPods = int32(burstReplicas)
  694. }
  695. validateSyncReplicaSet(t, &fakePodControl, 0, int(expectedPods), 0)
  696. // To accurately simulate a watch we must delete the exact pods
  697. // the rs is waiting for.
  698. expectedDels := manager.expectations.GetUIDs(GetKey(rsSpec, t))
  699. podsToDelete := []*v1.Pod{}
  700. isController := true
  701. for _, key := range expectedDels.List() {
  702. nsName := strings.Split(key, "/")
  703. podsToDelete = append(podsToDelete, &v1.Pod{
  704. ObjectMeta: metav1.ObjectMeta{
  705. Name: nsName[1],
  706. Namespace: nsName[0],
  707. Labels: rsSpec.Spec.Selector.MatchLabels,
  708. OwnerReferences: []metav1.OwnerReference{
  709. {UID: rsSpec.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rsSpec.Name, Controller: &isController},
  710. },
  711. },
  712. })
  713. }
  714. // Don't delete all pods because we confirm that the last pod
  715. // has exactly one expectation at the end, to verify that we
  716. // don't double delete.
  717. for i := range podsToDelete[1:] {
  718. informers.Core().V1().Pods().Informer().GetIndexer().Delete(podsToDelete[i])
  719. manager.deletePod(podsToDelete[i])
  720. }
  721. podExp, exists, err := manager.expectations.GetExpectations(rsKey)
  722. if !exists || err != nil {
  723. t.Fatalf("Did not find expectations for ReplicaSet.")
  724. }
  725. if _, del := podExp.GetExpectations(); del != 1 {
  726. t.Fatalf("Expectations are wrong %v", podExp)
  727. }
  728. }
  729. // Check that the ReplicaSet didn't take any action for all the above pods
  730. fakePodControl.Clear()
  731. manager.syncReplicaSet(GetKey(rsSpec, t))
  732. validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0)
  733. // Create/Delete the last pod
  734. // The last add pod will decrease the expectation of the ReplicaSet to 0,
  735. // which will cause it to create/delete the remaining replicas up to burstReplicas.
  736. if replicas != 0 {
  737. informers.Core().V1().Pods().Informer().GetIndexer().Add(&pods.Items[expectedPods-1])
  738. manager.addPod(&pods.Items[expectedPods-1])
  739. } else {
  740. expectedDel := manager.expectations.GetUIDs(GetKey(rsSpec, t))
  741. if expectedDel.Len() != 1 {
  742. t.Fatalf("Waiting on unexpected number of deletes.")
  743. }
  744. nsName := strings.Split(expectedDel.List()[0], "/")
  745. isController := true
  746. lastPod := &v1.Pod{
  747. ObjectMeta: metav1.ObjectMeta{
  748. Name: nsName[1],
  749. Namespace: nsName[0],
  750. Labels: rsSpec.Spec.Selector.MatchLabels,
  751. OwnerReferences: []metav1.OwnerReference{
  752. {UID: rsSpec.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rsSpec.Name, Controller: &isController},
  753. },
  754. },
  755. }
  756. informers.Core().V1().Pods().Informer().GetIndexer().Delete(lastPod)
  757. manager.deletePod(lastPod)
  758. }
  759. pods.Items = pods.Items[expectedPods:]
  760. }
  761. // Confirm that we've created the right number of replicas
  762. activePods := int32(len(informers.Core().V1().Pods().Informer().GetIndexer().List()))
  763. if activePods != *(rsSpec.Spec.Replicas) {
  764. t.Fatalf("Unexpected number of active pods, expected %d, got %d", *(rsSpec.Spec.Replicas), activePods)
  765. }
  766. // Replenish the pod list, since we cut it down sizing up
  767. pods = newPodList(nil, int(replicas), v1.PodRunning, labelMap, rsSpec, "pod")
  768. }
  769. }
  770. func TestControllerBurstReplicas(t *testing.T) {
  771. doTestControllerBurstReplicas(t, 5, 30)
  772. doTestControllerBurstReplicas(t, 5, 12)
  773. doTestControllerBurstReplicas(t, 3, 2)
  774. }
  775. type FakeRSExpectations struct {
  776. *controller.ControllerExpectations
  777. satisfied bool
  778. expSatisfied func()
  779. }
  780. func (fe FakeRSExpectations) SatisfiedExpectations(controllerKey string) bool {
  781. fe.expSatisfied()
  782. return fe.satisfied
  783. }
  784. // TestRSSyncExpectations tests that a pod cannot sneak in between counting active pods
  785. // and checking expectations.
  786. func TestRSSyncExpectations(t *testing.T) {
  787. client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  788. fakePodControl := controller.FakePodControl{}
  789. stopCh := make(chan struct{})
  790. defer close(stopCh)
  791. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, 2)
  792. manager.podControl = &fakePodControl
  793. labelMap := map[string]string{"foo": "bar"}
  794. rsSpec := newReplicaSet(2, labelMap)
  795. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rsSpec)
  796. pods := newPodList(nil, 2, v1.PodPending, labelMap, rsSpec, "pod")
  797. informers.Core().V1().Pods().Informer().GetIndexer().Add(&pods.Items[0])
  798. postExpectationsPod := pods.Items[1]
  799. manager.expectations = controller.NewUIDTrackingControllerExpectations(FakeRSExpectations{
  800. controller.NewControllerExpectations(), true, func() {
  801. // If we check active pods before checking expectataions, the
  802. // ReplicaSet will create a new replica because it doesn't see
  803. // this pod, but has fulfilled its expectations.
  804. informers.Core().V1().Pods().Informer().GetIndexer().Add(&postExpectationsPod)
  805. },
  806. })
  807. manager.syncReplicaSet(GetKey(rsSpec, t))
  808. validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0)
  809. }
  810. func TestDeleteControllerAndExpectations(t *testing.T) {
  811. rs := newReplicaSet(1, map[string]string{"foo": "bar"})
  812. client := fake.NewSimpleClientset(rs)
  813. stopCh := make(chan struct{})
  814. defer close(stopCh)
  815. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, 10)
  816. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  817. fakePodControl := controller.FakePodControl{}
  818. manager.podControl = &fakePodControl
  819. // This should set expectations for the ReplicaSet
  820. manager.syncReplicaSet(GetKey(rs, t))
  821. validateSyncReplicaSet(t, &fakePodControl, 1, 0, 0)
  822. fakePodControl.Clear()
  823. // Get the ReplicaSet key
  824. rsKey, err := controller.KeyFunc(rs)
  825. if err != nil {
  826. t.Errorf("Couldn't get key for object %#v: %v", rs, err)
  827. }
  828. // This is to simulate a concurrent addPod, that has a handle on the expectations
  829. // as the controller deletes it.
  830. podExp, exists, err := manager.expectations.GetExpectations(rsKey)
  831. if !exists || err != nil {
  832. t.Errorf("No expectations found for ReplicaSet")
  833. }
  834. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Delete(rs)
  835. manager.syncReplicaSet(GetKey(rs, t))
  836. if _, exists, err = manager.expectations.GetExpectations(rsKey); exists {
  837. t.Errorf("Found expectaions, expected none since the ReplicaSet has been deleted.")
  838. }
  839. // This should have no effect, since we've deleted the ReplicaSet.
  840. podExp.Add(-1, 0)
  841. informers.Core().V1().Pods().Informer().GetIndexer().Replace(make([]interface{}, 0), "0")
  842. manager.syncReplicaSet(GetKey(rs, t))
  843. validateSyncReplicaSet(t, &fakePodControl, 0, 0, 0)
  844. }
  845. // shuffle returns a new shuffled list of container controllers.
  846. func shuffle(controllers []*apps.ReplicaSet) []*apps.ReplicaSet {
  847. numControllers := len(controllers)
  848. randIndexes := rand.Perm(numControllers)
  849. shuffled := make([]*apps.ReplicaSet, numControllers)
  850. for i := 0; i < numControllers; i++ {
  851. shuffled[i] = controllers[randIndexes[i]]
  852. }
  853. return shuffled
  854. }
  855. func TestOverlappingRSs(t *testing.T) {
  856. client := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  857. labelMap := map[string]string{"foo": "bar"}
  858. stopCh := make(chan struct{})
  859. defer close(stopCh)
  860. manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, 10)
  861. // Create 10 ReplicaSets, shuffled them randomly and insert them into the
  862. // ReplicaSet controller's store.
  863. // All use the same CreationTimestamp since ControllerRef should be able
  864. // to handle that.
  865. timestamp := metav1.Date(2014, time.December, 0, 0, 0, 0, 0, time.Local)
  866. var controllers []*apps.ReplicaSet
  867. for j := 1; j < 10; j++ {
  868. rsSpec := newReplicaSet(1, labelMap)
  869. rsSpec.CreationTimestamp = timestamp
  870. rsSpec.Name = fmt.Sprintf("rs%d", j)
  871. controllers = append(controllers, rsSpec)
  872. }
  873. shuffledControllers := shuffle(controllers)
  874. for j := range shuffledControllers {
  875. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(shuffledControllers[j])
  876. }
  877. // Add a pod with a ControllerRef and make sure only the corresponding
  878. // ReplicaSet is synced. Pick a RS in the middle since the old code used to
  879. // sort by name if all timestamps were equal.
  880. rs := controllers[3]
  881. pods := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod")
  882. pod := &pods.Items[0]
  883. isController := true
  884. pod.OwnerReferences = []metav1.OwnerReference{
  885. {UID: rs.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rs.Name, Controller: &isController},
  886. }
  887. rsKey := GetKey(rs, t)
  888. manager.addPod(pod)
  889. queueRS, _ := manager.queue.Get()
  890. if queueRS != rsKey {
  891. t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS)
  892. }
  893. }
  894. func TestDeletionTimestamp(t *testing.T) {
  895. c := clientset.NewForConfigOrDie(&restclient.Config{Host: "", ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  896. labelMap := map[string]string{"foo": "bar"}
  897. stopCh := make(chan struct{})
  898. defer close(stopCh)
  899. manager, informers := testNewReplicaSetControllerFromClient(c, stopCh, 10)
  900. rs := newReplicaSet(1, labelMap)
  901. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  902. rsKey, err := controller.KeyFunc(rs)
  903. if err != nil {
  904. t.Errorf("Couldn't get key for object %#v: %v", rs, err)
  905. }
  906. pod := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod").Items[0]
  907. pod.DeletionTimestamp = &metav1.Time{Time: time.Now()}
  908. pod.ResourceVersion = "1"
  909. manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(&pod)})
  910. // A pod added with a deletion timestamp should decrement deletions, not creations.
  911. manager.addPod(&pod)
  912. queueRS, _ := manager.queue.Get()
  913. if queueRS != rsKey {
  914. t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS)
  915. }
  916. manager.queue.Done(rsKey)
  917. podExp, exists, err := manager.expectations.GetExpectations(rsKey)
  918. if !exists || err != nil || !podExp.Fulfilled() {
  919. t.Fatalf("Wrong expectations %#v", podExp)
  920. }
  921. // An update from no deletion timestamp to having one should be treated
  922. // as a deletion.
  923. oldPod := newPodList(nil, 1, v1.PodPending, labelMap, rs, "pod").Items[0]
  924. oldPod.ResourceVersion = "2"
  925. manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(&pod)})
  926. manager.updatePod(&oldPod, &pod)
  927. queueRS, _ = manager.queue.Get()
  928. if queueRS != rsKey {
  929. t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS)
  930. }
  931. manager.queue.Done(rsKey)
  932. podExp, exists, err = manager.expectations.GetExpectations(rsKey)
  933. if !exists || err != nil || !podExp.Fulfilled() {
  934. t.Fatalf("Wrong expectations %#v", podExp)
  935. }
  936. // An update to the pod (including an update to the deletion timestamp)
  937. // should not be counted as a second delete.
  938. isController := true
  939. secondPod := &v1.Pod{
  940. ObjectMeta: metav1.ObjectMeta{
  941. Namespace: pod.Namespace,
  942. Name: "secondPod",
  943. Labels: pod.Labels,
  944. OwnerReferences: []metav1.OwnerReference{
  945. {UID: rs.UID, APIVersion: "v1", Kind: "ReplicaSet", Name: rs.Name, Controller: &isController},
  946. },
  947. },
  948. }
  949. manager.expectations.ExpectDeletions(rsKey, []string{controller.PodKey(secondPod)})
  950. oldPod.DeletionTimestamp = &metav1.Time{Time: time.Now()}
  951. oldPod.ResourceVersion = "2"
  952. manager.updatePod(&oldPod, &pod)
  953. podExp, exists, err = manager.expectations.GetExpectations(rsKey)
  954. if !exists || err != nil || podExp.Fulfilled() {
  955. t.Fatalf("Wrong expectations %#v", podExp)
  956. }
  957. // A pod with a non-nil deletion timestamp should also be ignored by the
  958. // delete handler, because it's already been counted in the update.
  959. manager.deletePod(&pod)
  960. podExp, exists, err = manager.expectations.GetExpectations(rsKey)
  961. if !exists || err != nil || podExp.Fulfilled() {
  962. t.Fatalf("Wrong expectations %#v", podExp)
  963. }
  964. // Deleting the second pod should clear expectations.
  965. manager.deletePod(secondPod)
  966. queueRS, _ = manager.queue.Get()
  967. if queueRS != rsKey {
  968. t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS)
  969. }
  970. manager.queue.Done(rsKey)
  971. podExp, exists, err = manager.expectations.GetExpectations(rsKey)
  972. if !exists || err != nil || !podExp.Fulfilled() {
  973. t.Fatalf("Wrong expectations %#v", podExp)
  974. }
  975. }
  976. // setupManagerWithGCEnabled creates a RS manager with a fakePodControl
  977. func setupManagerWithGCEnabled(stopCh chan struct{}, objs ...runtime.Object) (manager *ReplicaSetController, fakePodControl *controller.FakePodControl, informers informers.SharedInformerFactory) {
  978. c := fake.NewSimpleClientset(objs...)
  979. fakePodControl = &controller.FakePodControl{}
  980. manager, informers = testNewReplicaSetControllerFromClient(c, stopCh, BurstReplicas)
  981. manager.podControl = fakePodControl
  982. return manager, fakePodControl, informers
  983. }
  984. func TestDoNotPatchPodWithOtherControlRef(t *testing.T) {
  985. labelMap := map[string]string{"foo": "bar"}
  986. rs := newReplicaSet(2, labelMap)
  987. stopCh := make(chan struct{})
  988. defer close(stopCh)
  989. manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs)
  990. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  991. var trueVar = true
  992. otherControllerReference := metav1.OwnerReference{UID: uuid.NewUUID(), APIVersion: "v1beta1", Kind: "ReplicaSet", Name: "AnotherRS", Controller: &trueVar}
  993. // add to podLister a matching Pod controlled by another controller. Expect no patch.
  994. pod := newPod("pod", rs, v1.PodRunning, nil, true)
  995. pod.OwnerReferences = []metav1.OwnerReference{otherControllerReference}
  996. informers.Core().V1().Pods().Informer().GetIndexer().Add(pod)
  997. err := manager.syncReplicaSet(GetKey(rs, t))
  998. if err != nil {
  999. t.Fatal(err)
  1000. }
  1001. // because the matching pod already has a controller, so 2 pods should be created.
  1002. validateSyncReplicaSet(t, fakePodControl, 2, 0, 0)
  1003. }
  1004. func TestPatchPodFails(t *testing.T) {
  1005. labelMap := map[string]string{"foo": "bar"}
  1006. rs := newReplicaSet(2, labelMap)
  1007. stopCh := make(chan struct{})
  1008. defer close(stopCh)
  1009. manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs)
  1010. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  1011. // add to podLister two matching pods. Expect two patches to take control
  1012. // them.
  1013. informers.Core().V1().Pods().Informer().GetIndexer().Add(newPod("pod1", rs, v1.PodRunning, nil, false))
  1014. informers.Core().V1().Pods().Informer().GetIndexer().Add(newPod("pod2", rs, v1.PodRunning, nil, false))
  1015. // let both patches fail. The rs controller will assume it fails to take
  1016. // control of the pods and requeue to try again.
  1017. fakePodControl.Err = fmt.Errorf("Fake Error")
  1018. rsKey := GetKey(rs, t)
  1019. err := processSync(manager, rsKey)
  1020. if err == nil || !strings.Contains(err.Error(), "Fake Error") {
  1021. t.Errorf("expected Fake Error, got %+v", err)
  1022. }
  1023. // 2 patches to take control of pod1 and pod2 (both fail).
  1024. validateSyncReplicaSet(t, fakePodControl, 0, 0, 2)
  1025. // RS should requeue itself.
  1026. queueRS, _ := manager.queue.Get()
  1027. if queueRS != rsKey {
  1028. t.Fatalf("Expected to find key %v in queue, found %v", rsKey, queueRS)
  1029. }
  1030. }
  1031. // RS controller shouldn't adopt or create more pods if the rc is about to be
  1032. // deleted.
  1033. func TestDoNotAdoptOrCreateIfBeingDeleted(t *testing.T) {
  1034. labelMap := map[string]string{"foo": "bar"}
  1035. rs := newReplicaSet(2, labelMap)
  1036. now := metav1.Now()
  1037. rs.DeletionTimestamp = &now
  1038. stopCh := make(chan struct{})
  1039. defer close(stopCh)
  1040. manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs)
  1041. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(rs)
  1042. pod1 := newPod("pod1", rs, v1.PodRunning, nil, false)
  1043. informers.Core().V1().Pods().Informer().GetIndexer().Add(pod1)
  1044. // no patch, no create
  1045. err := manager.syncReplicaSet(GetKey(rs, t))
  1046. if err != nil {
  1047. t.Fatal(err)
  1048. }
  1049. validateSyncReplicaSet(t, fakePodControl, 0, 0, 0)
  1050. }
  1051. func TestDoNotAdoptOrCreateIfBeingDeletedRace(t *testing.T) {
  1052. labelMap := map[string]string{"foo": "bar"}
  1053. // Bare client says it IS deleted.
  1054. rs := newReplicaSet(2, labelMap)
  1055. now := metav1.Now()
  1056. rs.DeletionTimestamp = &now
  1057. stopCh := make(chan struct{})
  1058. defer close(stopCh)
  1059. manager, fakePodControl, informers := setupManagerWithGCEnabled(stopCh, rs)
  1060. // Lister (cache) says it's NOT deleted.
  1061. rs2 := *rs
  1062. rs2.DeletionTimestamp = nil
  1063. informers.Apps().V1().ReplicaSets().Informer().GetIndexer().Add(&rs2)
  1064. // Recheck occurs if a matching orphan is present.
  1065. pod1 := newPod("pod1", rs, v1.PodRunning, nil, false)
  1066. informers.Core().V1().Pods().Informer().GetIndexer().Add(pod1)
  1067. // sync should abort.
  1068. err := manager.syncReplicaSet(GetKey(rs, t))
  1069. if err == nil {
  1070. t.Error("syncReplicaSet() err = nil, expected non-nil")
  1071. }
  1072. // no patch, no create.
  1073. validateSyncReplicaSet(t, fakePodControl, 0, 0, 0)
  1074. }
  1075. var (
  1076. imagePullBackOff apps.ReplicaSetConditionType = "ImagePullBackOff"
  1077. condImagePullBackOff = func() apps.ReplicaSetCondition {
  1078. return apps.ReplicaSetCondition{
  1079. Type: imagePullBackOff,
  1080. Status: v1.ConditionTrue,
  1081. Reason: "NonExistentImage",
  1082. }
  1083. }
  1084. condReplicaFailure = func() apps.ReplicaSetCondition {
  1085. return apps.ReplicaSetCondition{
  1086. Type: apps.ReplicaSetReplicaFailure,
  1087. Status: v1.ConditionTrue,
  1088. Reason: "OtherFailure",
  1089. }
  1090. }
  1091. condReplicaFailure2 = func() apps.ReplicaSetCondition {
  1092. return apps.ReplicaSetCondition{
  1093. Type: apps.ReplicaSetReplicaFailure,
  1094. Status: v1.ConditionTrue,
  1095. Reason: "AnotherFailure",
  1096. }
  1097. }
  1098. status = func() *apps.ReplicaSetStatus {
  1099. return &apps.ReplicaSetStatus{
  1100. Conditions: []apps.ReplicaSetCondition{condReplicaFailure()},
  1101. }
  1102. }
  1103. )
  1104. func TestGetCondition(t *testing.T) {
  1105. exampleStatus := status()
  1106. tests := []struct {
  1107. name string
  1108. status apps.ReplicaSetStatus
  1109. condType apps.ReplicaSetConditionType
  1110. expected bool
  1111. }{
  1112. {
  1113. name: "condition exists",
  1114. status: *exampleStatus,
  1115. condType: apps.ReplicaSetReplicaFailure,
  1116. expected: true,
  1117. },
  1118. {
  1119. name: "condition does not exist",
  1120. status: *exampleStatus,
  1121. condType: imagePullBackOff,
  1122. expected: false,
  1123. },
  1124. }
  1125. for _, test := range tests {
  1126. cond := GetCondition(test.status, test.condType)
  1127. exists := cond != nil
  1128. if exists != test.expected {
  1129. t.Errorf("%s: expected condition to exist: %t, got: %t", test.name, test.expected, exists)
  1130. }
  1131. }
  1132. }
  1133. func TestSetCondition(t *testing.T) {
  1134. tests := []struct {
  1135. name string
  1136. status *apps.ReplicaSetStatus
  1137. cond apps.ReplicaSetCondition
  1138. expectedStatus *apps.ReplicaSetStatus
  1139. }{
  1140. {
  1141. name: "set for the first time",
  1142. status: &apps.ReplicaSetStatus{},
  1143. cond: condReplicaFailure(),
  1144. expectedStatus: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}},
  1145. },
  1146. {
  1147. name: "simple set",
  1148. status: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condImagePullBackOff()}},
  1149. cond: condReplicaFailure(),
  1150. expectedStatus: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condImagePullBackOff(), condReplicaFailure()}},
  1151. },
  1152. {
  1153. name: "overwrite",
  1154. status: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}},
  1155. cond: condReplicaFailure2(),
  1156. expectedStatus: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure2()}},
  1157. },
  1158. }
  1159. for _, test := range tests {
  1160. SetCondition(test.status, test.cond)
  1161. if !reflect.DeepEqual(test.status, test.expectedStatus) {
  1162. t.Errorf("%s: expected status: %v, got: %v", test.name, test.expectedStatus, test.status)
  1163. }
  1164. }
  1165. }
  1166. func TestRemoveCondition(t *testing.T) {
  1167. tests := []struct {
  1168. name string
  1169. status *apps.ReplicaSetStatus
  1170. condType apps.ReplicaSetConditionType
  1171. expectedStatus *apps.ReplicaSetStatus
  1172. }{
  1173. {
  1174. name: "remove from empty status",
  1175. status: &apps.ReplicaSetStatus{},
  1176. condType: apps.ReplicaSetReplicaFailure,
  1177. expectedStatus: &apps.ReplicaSetStatus{},
  1178. },
  1179. {
  1180. name: "simple remove",
  1181. status: &apps.ReplicaSetStatus{Conditions: []apps.ReplicaSetCondition{condReplicaFailure()}},
  1182. condType: apps.ReplicaSetReplicaFailure,
  1183. expectedStatus: &apps.ReplicaSetStatus{},
  1184. },
  1185. {
  1186. name: "doesn't remove anything",
  1187. status: status(),
  1188. condType: imagePullBackOff,
  1189. expectedStatus: status(),
  1190. },
  1191. }
  1192. for _, test := range tests {
  1193. RemoveCondition(test.status, test.condType)
  1194. if !reflect.DeepEqual(test.status, test.expectedStatus) {
  1195. t.Errorf("%s: expected status: %v, got: %v", test.name, test.expectedStatus, test.status)
  1196. }
  1197. }
  1198. }
  1199. func TestSlowStartBatch(t *testing.T) {
  1200. fakeErr := fmt.Errorf("fake error")
  1201. callCnt := 0
  1202. callLimit := 0
  1203. var lock sync.Mutex
  1204. fn := func() error {
  1205. lock.Lock()
  1206. defer lock.Unlock()
  1207. callCnt++
  1208. if callCnt > callLimit {
  1209. return fakeErr
  1210. }
  1211. return nil
  1212. }
  1213. tests := []struct {
  1214. name string
  1215. count int
  1216. callLimit int
  1217. fn func() error
  1218. expectedSuccesses int
  1219. expectedErr error
  1220. expectedCallCnt int
  1221. }{
  1222. {
  1223. name: "callLimit = 0 (all fail)",
  1224. count: 10,
  1225. callLimit: 0,
  1226. fn: fn,
  1227. expectedSuccesses: 0,
  1228. expectedErr: fakeErr,
  1229. expectedCallCnt: 1, // 1(first batch): function will be called at least once
  1230. },
  1231. {
  1232. name: "callLimit = count (all succeed)",
  1233. count: 10,
  1234. callLimit: 10,
  1235. fn: fn,
  1236. expectedSuccesses: 10,
  1237. expectedErr: nil,
  1238. expectedCallCnt: 10, // 1(first batch) + 2(2nd batch) + 4(3rd batch) + 3(4th batch) = 10
  1239. },
  1240. {
  1241. name: "callLimit < count (some succeed)",
  1242. count: 10,
  1243. callLimit: 5,
  1244. fn: fn,
  1245. expectedSuccesses: 5,
  1246. expectedErr: fakeErr,
  1247. expectedCallCnt: 7, // 1(first batch) + 2(2nd batch) + 4(3rd batch) = 7
  1248. },
  1249. }
  1250. for _, test := range tests {
  1251. callCnt = 0
  1252. callLimit = test.callLimit
  1253. successes, err := slowStartBatch(test.count, 1, test.fn)
  1254. if successes != test.expectedSuccesses {
  1255. t.Errorf("%s: unexpected processed batch size, expected %d, got %d", test.name, test.expectedSuccesses, successes)
  1256. }
  1257. if err != test.expectedErr {
  1258. t.Errorf("%s: unexpected processed batch size, expected %v, got %v", test.name, test.expectedErr, err)
  1259. }
  1260. // verify that slowStartBatch stops trying more calls after a batch fails
  1261. if callCnt != test.expectedCallCnt {
  1262. t.Errorf("%s: slowStartBatch() still tries calls after a batch fails, expected %d calls, got %d", test.name, test.expectedCallCnt, callCnt)
  1263. }
  1264. }
  1265. }
  1266. func TestGetPodsToDelete(t *testing.T) {
  1267. labelMap := map[string]string{"name": "foo"}
  1268. rs := newReplicaSet(1, labelMap)
  1269. // an unscheduled, pending pod
  1270. unscheduledPendingPod := newPod("unscheduled-pending-pod", rs, v1.PodPending, nil, true)
  1271. // a scheduled, pending pod
  1272. scheduledPendingPod := newPod("scheduled-pending-pod", rs, v1.PodPending, nil, true)
  1273. scheduledPendingPod.Spec.NodeName = "fake-node"
  1274. // a scheduled, running, not-ready pod
  1275. scheduledRunningNotReadyPod := newPod("scheduled-running-not-ready-pod", rs, v1.PodRunning, nil, true)
  1276. scheduledRunningNotReadyPod.Spec.NodeName = "fake-node"
  1277. scheduledRunningNotReadyPod.Status.Conditions = []v1.PodCondition{
  1278. {
  1279. Type: v1.PodReady,
  1280. Status: v1.ConditionFalse,
  1281. },
  1282. }
  1283. // a scheduled, running, ready pod
  1284. scheduledRunningReadyPod := newPod("scheduled-running-ready-pod", rs, v1.PodRunning, nil, true)
  1285. scheduledRunningReadyPod.Spec.NodeName = "fake-node"
  1286. scheduledRunningReadyPod.Status.Conditions = []v1.PodCondition{
  1287. {
  1288. Type: v1.PodReady,
  1289. Status: v1.ConditionTrue,
  1290. },
  1291. }
  1292. tests := []struct {
  1293. name string
  1294. pods []*v1.Pod
  1295. diff int
  1296. expectedPodsToDelete []*v1.Pod
  1297. }{
  1298. // Order used when selecting pods for deletion:
  1299. // an unscheduled, pending pod
  1300. // a scheduled, pending pod
  1301. // a scheduled, running, not-ready pod
  1302. // a scheduled, running, ready pod
  1303. // Note that a pending pod cannot be ready
  1304. {
  1305. "len(pods) = 0 (i.e., diff = 0 too)",
  1306. []*v1.Pod{},
  1307. 0,
  1308. []*v1.Pod{},
  1309. },
  1310. {
  1311. "diff = len(pods)",
  1312. []*v1.Pod{
  1313. scheduledRunningNotReadyPod,
  1314. scheduledRunningReadyPod,
  1315. },
  1316. 2,
  1317. []*v1.Pod{scheduledRunningNotReadyPod, scheduledRunningReadyPod},
  1318. },
  1319. {
  1320. "diff < len(pods)",
  1321. []*v1.Pod{
  1322. scheduledRunningReadyPod,
  1323. scheduledRunningNotReadyPod,
  1324. },
  1325. 1,
  1326. []*v1.Pod{scheduledRunningNotReadyPod},
  1327. },
  1328. {
  1329. "various pod phases and conditions, diff = len(pods)",
  1330. []*v1.Pod{
  1331. scheduledRunningReadyPod,
  1332. scheduledRunningNotReadyPod,
  1333. scheduledPendingPod,
  1334. unscheduledPendingPod,
  1335. },
  1336. 4,
  1337. []*v1.Pod{
  1338. scheduledRunningReadyPod,
  1339. scheduledRunningNotReadyPod,
  1340. scheduledPendingPod,
  1341. unscheduledPendingPod,
  1342. },
  1343. },
  1344. {
  1345. "scheduled vs unscheduled, diff < len(pods)",
  1346. []*v1.Pod{
  1347. scheduledPendingPod,
  1348. unscheduledPendingPod,
  1349. },
  1350. 1,
  1351. []*v1.Pod{
  1352. unscheduledPendingPod,
  1353. },
  1354. },
  1355. {
  1356. "ready vs not-ready, diff < len(pods)",
  1357. []*v1.Pod{
  1358. scheduledRunningReadyPod,
  1359. scheduledRunningNotReadyPod,
  1360. scheduledRunningNotReadyPod,
  1361. },
  1362. 2,
  1363. []*v1.Pod{
  1364. scheduledRunningNotReadyPod,
  1365. scheduledRunningNotReadyPod,
  1366. },
  1367. },
  1368. {
  1369. "pending vs running, diff < len(pods)",
  1370. []*v1.Pod{
  1371. scheduledPendingPod,
  1372. scheduledRunningNotReadyPod,
  1373. },
  1374. 1,
  1375. []*v1.Pod{
  1376. scheduledPendingPod,
  1377. },
  1378. },
  1379. {
  1380. "various pod phases and conditions, diff < len(pods)",
  1381. []*v1.Pod{
  1382. scheduledRunningReadyPod,
  1383. scheduledRunningNotReadyPod,
  1384. scheduledPendingPod,
  1385. unscheduledPendingPod,
  1386. },
  1387. 3,
  1388. []*v1.Pod{
  1389. unscheduledPendingPod,
  1390. scheduledPendingPod,
  1391. scheduledRunningNotReadyPod,
  1392. },
  1393. },
  1394. }
  1395. for _, test := range tests {
  1396. podsToDelete := getPodsToDelete(test.pods, test.diff)
  1397. if len(podsToDelete) != len(test.expectedPodsToDelete) {
  1398. t.Errorf("%s: unexpected pods to delete, expected %v, got %v", test.name, test.expectedPodsToDelete, podsToDelete)
  1399. }
  1400. if !reflect.DeepEqual(podsToDelete, test.expectedPodsToDelete) {
  1401. t.Errorf("%s: unexpected pods to delete, expected %v, got %v", test.name, test.expectedPodsToDelete, podsToDelete)
  1402. }
  1403. }
  1404. }
  1405. func TestGetPodKeys(t *testing.T) {
  1406. labelMap := map[string]string{"name": "foo"}
  1407. rs := newReplicaSet(1, labelMap)
  1408. pod1 := newPod("pod1", rs, v1.PodRunning, nil, true)
  1409. pod2 := newPod("pod2", rs, v1.PodRunning, nil, true)
  1410. tests := []struct {
  1411. name string
  1412. pods []*v1.Pod
  1413. expectedPodKeys []string
  1414. }{
  1415. {
  1416. "len(pods) = 0 (i.e., pods = nil)",
  1417. []*v1.Pod{},
  1418. []string{},
  1419. },
  1420. {
  1421. "len(pods) > 0",
  1422. []*v1.Pod{
  1423. pod1,
  1424. pod2,
  1425. },
  1426. []string{"default/pod1", "default/pod2"},
  1427. },
  1428. }
  1429. for _, test := range tests {
  1430. podKeys := getPodKeys(test.pods)
  1431. if len(podKeys) != len(test.expectedPodKeys) {
  1432. t.Errorf("%s: unexpected keys for pods to delete, expected %v, got %v", test.name, test.expectedPodKeys, podKeys)
  1433. }
  1434. for i := 0; i < len(podKeys); i++ {
  1435. if podKeys[i] != test.expectedPodKeys[i] {
  1436. t.Errorf("%s: unexpected keys for pods to delete, expected %v, got %v", test.name, test.expectedPodKeys, podKeys)
  1437. }
  1438. }
  1439. }
  1440. }