pet_set.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 petset
  14. import (
  15. "fmt"
  16. "reflect"
  17. "sort"
  18. "time"
  19. "k8s.io/kubernetes/pkg/api"
  20. "k8s.io/kubernetes/pkg/api/unversioned"
  21. "k8s.io/kubernetes/pkg/apis/apps"
  22. "k8s.io/kubernetes/pkg/client/cache"
  23. "k8s.io/kubernetes/pkg/client/record"
  24. client "k8s.io/kubernetes/pkg/client/unversioned"
  25. "k8s.io/kubernetes/pkg/controller"
  26. "k8s.io/kubernetes/pkg/controller/framework"
  27. "k8s.io/kubernetes/pkg/runtime"
  28. utilruntime "k8s.io/kubernetes/pkg/util/runtime"
  29. "k8s.io/kubernetes/pkg/util/wait"
  30. "k8s.io/kubernetes/pkg/util/workqueue"
  31. "k8s.io/kubernetes/pkg/watch"
  32. "github.com/golang/glog"
  33. )
  34. const (
  35. // Time to sleep before polling to see if the pod cache has synced.
  36. PodStoreSyncedPollPeriod = 100 * time.Millisecond
  37. // number of retries for a status update.
  38. statusUpdateRetries = 2
  39. // period to relist petsets and verify pets
  40. petSetResyncPeriod = 30 * time.Second
  41. )
  42. // PetSetController controls petsets.
  43. type PetSetController struct {
  44. kubeClient *client.Client
  45. // newSyncer returns an interface capable of syncing a single pet.
  46. // Abstracted out for testing.
  47. newSyncer func(*pcb) *petSyncer
  48. // podStore is a cache of watched pods.
  49. podStore cache.StoreToPodLister
  50. // podStoreSynced returns true if the pod store has synced at least once.
  51. podStoreSynced func() bool
  52. // Watches changes to all pods.
  53. podController framework.ControllerInterface
  54. // A store of PetSets, populated by the psController.
  55. psStore cache.StoreToPetSetLister
  56. // Watches changes to all PetSets.
  57. psController *framework.Controller
  58. // A store of the 1 unhealthy pet blocking progress for a given ps
  59. blockingPetStore *unhealthyPetTracker
  60. // Controllers that need to be synced.
  61. queue workqueue.RateLimitingInterface
  62. // syncHandler handles sync events for petsets.
  63. // Abstracted as a func to allow injection for testing.
  64. syncHandler func(psKey string) []error
  65. }
  66. // NewPetSetController creates a new petset controller.
  67. func NewPetSetController(podInformer framework.SharedIndexInformer, kubeClient *client.Client, resyncPeriod time.Duration) *PetSetController {
  68. eventBroadcaster := record.NewBroadcaster()
  69. eventBroadcaster.StartLogging(glog.Infof)
  70. eventBroadcaster.StartRecordingToSink(kubeClient.Events(""))
  71. recorder := eventBroadcaster.NewRecorder(api.EventSource{Component: "petset"})
  72. pc := &apiServerPetClient{kubeClient, recorder, &defaultPetHealthChecker{}}
  73. psc := &PetSetController{
  74. kubeClient: kubeClient,
  75. blockingPetStore: newUnHealthyPetTracker(pc),
  76. newSyncer: func(blockingPet *pcb) *petSyncer {
  77. return &petSyncer{pc, blockingPet}
  78. },
  79. queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "petset"),
  80. }
  81. podInformer.AddEventHandler(framework.ResourceEventHandlerFuncs{
  82. // lookup the petset and enqueue
  83. AddFunc: psc.addPod,
  84. // lookup current and old petset if labels changed
  85. UpdateFunc: psc.updatePod,
  86. // lookup petset accounting for deletion tombstones
  87. DeleteFunc: psc.deletePod,
  88. })
  89. psc.podStore.Indexer = podInformer.GetIndexer()
  90. psc.podController = podInformer.GetController()
  91. psc.psStore.Store, psc.psController = framework.NewInformer(
  92. &cache.ListWatch{
  93. ListFunc: func(options api.ListOptions) (runtime.Object, error) {
  94. return psc.kubeClient.Apps().PetSets(api.NamespaceAll).List(options)
  95. },
  96. WatchFunc: func(options api.ListOptions) (watch.Interface, error) {
  97. return psc.kubeClient.Apps().PetSets(api.NamespaceAll).Watch(options)
  98. },
  99. },
  100. &apps.PetSet{},
  101. petSetResyncPeriod,
  102. framework.ResourceEventHandlerFuncs{
  103. AddFunc: psc.enqueuePetSet,
  104. UpdateFunc: func(old, cur interface{}) {
  105. oldPS := old.(*apps.PetSet)
  106. curPS := cur.(*apps.PetSet)
  107. if oldPS.Status.Replicas != curPS.Status.Replicas {
  108. glog.V(4).Infof("Observed updated replica count for PetSet: %v, %d->%d", curPS.Name, oldPS.Status.Replicas, curPS.Status.Replicas)
  109. }
  110. psc.enqueuePetSet(cur)
  111. },
  112. DeleteFunc: psc.enqueuePetSet,
  113. },
  114. )
  115. // TODO: Watch volumes
  116. psc.podStoreSynced = psc.podController.HasSynced
  117. psc.syncHandler = psc.Sync
  118. return psc
  119. }
  120. // Run runs the petset controller.
  121. func (psc *PetSetController) Run(workers int, stopCh <-chan struct{}) {
  122. defer utilruntime.HandleCrash()
  123. glog.Infof("Starting petset controller")
  124. go psc.podController.Run(stopCh)
  125. go psc.psController.Run(stopCh)
  126. for i := 0; i < workers; i++ {
  127. go wait.Until(psc.worker, time.Second, stopCh)
  128. }
  129. <-stopCh
  130. glog.Infof("Shutting down petset controller")
  131. psc.queue.ShutDown()
  132. }
  133. // addPod adds the petset for the pod to the sync queue
  134. func (psc *PetSetController) addPod(obj interface{}) {
  135. pod := obj.(*api.Pod)
  136. glog.V(4).Infof("Pod %s created, labels: %+v", pod.Name, pod.Labels)
  137. ps := psc.getPetSetForPod(pod)
  138. if ps == nil {
  139. return
  140. }
  141. psc.enqueuePetSet(ps)
  142. }
  143. // updatePod adds the petset for the current and old pods to the sync queue.
  144. // If the labels of the pod didn't change, this method enqueues a single petset.
  145. func (psc *PetSetController) updatePod(old, cur interface{}) {
  146. curPod := cur.(*api.Pod)
  147. oldPod := old.(*api.Pod)
  148. if curPod.ResourceVersion == oldPod.ResourceVersion {
  149. // Periodic resync will send update events for all known pods.
  150. // Two different versions of the same pod will always have different RVs.
  151. return
  152. }
  153. ps := psc.getPetSetForPod(curPod)
  154. if ps == nil {
  155. return
  156. }
  157. psc.enqueuePetSet(ps)
  158. if !reflect.DeepEqual(curPod.Labels, oldPod.Labels) {
  159. if oldPS := psc.getPetSetForPod(oldPod); oldPS != nil {
  160. psc.enqueuePetSet(oldPS)
  161. }
  162. }
  163. }
  164. // deletePod enqueues the petset for the pod accounting for deletion tombstones.
  165. func (psc *PetSetController) deletePod(obj interface{}) {
  166. pod, ok := obj.(*api.Pod)
  167. // When a delete is dropped, the relist will notice a pod in the store not
  168. // in the list, leading to the insertion of a tombstone object which contains
  169. // the deleted key/value. Note that this value might be stale. If the pod
  170. // changed labels the new PetSet will not be woken up till the periodic resync.
  171. if !ok {
  172. tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
  173. if !ok {
  174. glog.Errorf("couldn't get object from tombstone %+v", obj)
  175. return
  176. }
  177. pod, ok = tombstone.Obj.(*api.Pod)
  178. if !ok {
  179. glog.Errorf("tombstone contained object that is not a pod %+v", obj)
  180. return
  181. }
  182. }
  183. glog.V(4).Infof("Pod %s/%s deleted through %v.", pod.Namespace, pod.Name, utilruntime.GetCaller())
  184. if ps := psc.getPetSetForPod(pod); ps != nil {
  185. psc.enqueuePetSet(ps)
  186. }
  187. }
  188. // getPodsForPetSets returns the pods that match the selectors of the given petset.
  189. func (psc *PetSetController) getPodsForPetSet(ps *apps.PetSet) ([]*api.Pod, error) {
  190. // TODO: Do we want the petset to fight with RCs? check parent petset annoation, or name prefix?
  191. sel, err := unversioned.LabelSelectorAsSelector(ps.Spec.Selector)
  192. if err != nil {
  193. return []*api.Pod{}, err
  194. }
  195. pods, err := psc.podStore.Pods(ps.Namespace).List(sel)
  196. if err != nil {
  197. return []*api.Pod{}, err
  198. }
  199. // TODO: Do we need to copy?
  200. result := make([]*api.Pod, 0, len(pods))
  201. for i := range pods {
  202. result = append(result, &(*pods[i]))
  203. }
  204. return result, nil
  205. }
  206. // getPetSetForPod returns the pet set managing the given pod.
  207. func (psc *PetSetController) getPetSetForPod(pod *api.Pod) *apps.PetSet {
  208. ps, err := psc.psStore.GetPodPetSets(pod)
  209. if err != nil {
  210. glog.V(4).Infof("No PetSets found for pod %v, PetSet controller will avoid syncing", pod.Name)
  211. return nil
  212. }
  213. // Resolve a overlapping petset tie by creation timestamp.
  214. // Let's hope users don't create overlapping petsets.
  215. if len(ps) > 1 {
  216. glog.Errorf("user error! more than one PetSet is selecting pods with labels: %+v", pod.Labels)
  217. sort.Sort(overlappingPetSets(ps))
  218. }
  219. return &ps[0]
  220. }
  221. // enqueuePetSet enqueues the given petset in the work queue.
  222. func (psc *PetSetController) enqueuePetSet(obj interface{}) {
  223. key, err := controller.KeyFunc(obj)
  224. if err != nil {
  225. glog.Errorf("Cound't get key for object %+v: %v", obj, err)
  226. return
  227. }
  228. psc.queue.Add(key)
  229. }
  230. // worker runs a worker thread that just dequeues items, processes them, and marks them done.
  231. // It enforces that the syncHandler is never invoked concurrently with the same key.
  232. func (psc *PetSetController) worker() {
  233. for {
  234. func() {
  235. key, quit := psc.queue.Get()
  236. if quit {
  237. return
  238. }
  239. defer psc.queue.Done(key)
  240. if errs := psc.syncHandler(key.(string)); len(errs) != 0 {
  241. glog.Errorf("Error syncing PetSet %v, requeuing: %v", key.(string), errs)
  242. psc.queue.AddRateLimited(key)
  243. } else {
  244. psc.queue.Forget(key)
  245. }
  246. }()
  247. }
  248. }
  249. // Sync syncs the given petset.
  250. func (psc *PetSetController) Sync(key string) []error {
  251. startTime := time.Now()
  252. defer func() {
  253. glog.V(4).Infof("Finished syncing pet set %q (%v)", key, time.Now().Sub(startTime))
  254. }()
  255. if !psc.podStoreSynced() {
  256. // Sleep so we give the pod reflector goroutine a chance to run.
  257. time.Sleep(PodStoreSyncedPollPeriod)
  258. return []error{fmt.Errorf("waiting for pods controller to sync")}
  259. }
  260. obj, exists, err := psc.psStore.Store.GetByKey(key)
  261. if !exists {
  262. if err = psc.blockingPetStore.store.Delete(key); err != nil {
  263. return []error{err}
  264. }
  265. glog.Infof("PetSet has been deleted %v", key)
  266. return []error{}
  267. }
  268. if err != nil {
  269. glog.Errorf("Unable to retrieve PetSet %v from store: %v", key, err)
  270. return []error{err}
  271. }
  272. ps := *obj.(*apps.PetSet)
  273. petList, err := psc.getPodsForPetSet(&ps)
  274. if err != nil {
  275. return []error{err}
  276. }
  277. numPets, errs := psc.syncPetSet(&ps, petList)
  278. if err := updatePetCount(psc.kubeClient, ps, numPets); err != nil {
  279. glog.Infof("Failed to update replica count for petset %v/%v; requeuing; error: %v", ps.Namespace, ps.Name, err)
  280. errs = append(errs, err)
  281. }
  282. return errs
  283. }
  284. // syncPetSet syncs a tuple of (petset, pets).
  285. func (psc *PetSetController) syncPetSet(ps *apps.PetSet, pets []*api.Pod) (int, []error) {
  286. glog.Infof("Syncing PetSet %v/%v with %d pets", ps.Namespace, ps.Name, len(pets))
  287. it := NewPetSetIterator(ps, pets)
  288. blockingPet, err := psc.blockingPetStore.Get(ps, pets)
  289. if err != nil {
  290. return 0, []error{err}
  291. }
  292. if blockingPet != nil {
  293. glog.Infof("PetSet %v blocked from scaling on pet %v", ps.Name, blockingPet.pod.Name)
  294. }
  295. petManager := psc.newSyncer(blockingPet)
  296. numPets := 0
  297. for it.Next() {
  298. pet := it.Value()
  299. if pet == nil {
  300. continue
  301. }
  302. switch pet.event {
  303. case syncPet:
  304. err = petManager.Sync(pet)
  305. if err == nil {
  306. numPets++
  307. }
  308. case deletePet:
  309. err = petManager.Delete(pet)
  310. }
  311. if err != nil {
  312. it.errs = append(it.errs, err)
  313. }
  314. }
  315. if err := psc.blockingPetStore.Add(petManager.blockingPet); err != nil {
  316. it.errs = append(it.errs, err)
  317. }
  318. // TODO: GC pvcs. We can't delete them per pet because of grace period, and
  319. // in fact we *don't want to* till petset is stable to guarantee that bugs
  320. // in the controller don't corrupt user data.
  321. return numPets, it.errs
  322. }