update.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /*
  2. Copyright 2017 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 daemon
  14. import (
  15. "bytes"
  16. "context"
  17. "fmt"
  18. "reflect"
  19. "sort"
  20. "k8s.io/klog"
  21. apps "k8s.io/api/apps/v1"
  22. "k8s.io/api/core/v1"
  23. "k8s.io/apimachinery/pkg/api/errors"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/labels"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. intstrutil "k8s.io/apimachinery/pkg/util/intstr"
  28. "k8s.io/apimachinery/pkg/util/json"
  29. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  30. "k8s.io/kubernetes/pkg/controller"
  31. "k8s.io/kubernetes/pkg/controller/daemon/util"
  32. labelsutil "k8s.io/kubernetes/pkg/util/labels"
  33. )
  34. // rollingUpdate deletes old daemon set pods making sure that no more than
  35. // ds.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable pods are unavailable
  36. func (dsc *DaemonSetsController) rollingUpdate(ds *apps.DaemonSet, nodeList []*v1.Node, hash string) error {
  37. nodeToDaemonPods, err := dsc.getNodesToDaemonPods(ds)
  38. if err != nil {
  39. return fmt.Errorf("couldn't get node to daemon pod mapping for daemon set %q: %v", ds.Name, err)
  40. }
  41. _, oldPods := dsc.getAllDaemonSetPods(ds, nodeToDaemonPods, hash)
  42. maxUnavailable, numUnavailable, err := dsc.getUnavailableNumbers(ds, nodeList, nodeToDaemonPods)
  43. if err != nil {
  44. return fmt.Errorf("couldn't get unavailable numbers: %v", err)
  45. }
  46. oldAvailablePods, oldUnavailablePods := util.SplitByAvailablePods(ds.Spec.MinReadySeconds, oldPods)
  47. // for oldPods delete all not running pods
  48. var oldPodsToDelete []string
  49. klog.V(4).Infof("Marking all unavailable old pods for deletion")
  50. for _, pod := range oldUnavailablePods {
  51. // Skip terminating pods. We won't delete them again
  52. if pod.DeletionTimestamp != nil {
  53. continue
  54. }
  55. klog.V(4).Infof("Marking pod %s/%s for deletion", ds.Name, pod.Name)
  56. oldPodsToDelete = append(oldPodsToDelete, pod.Name)
  57. }
  58. klog.V(4).Infof("Marking old pods for deletion")
  59. for _, pod := range oldAvailablePods {
  60. if numUnavailable >= maxUnavailable {
  61. klog.V(4).Infof("Number of unavailable DaemonSet pods: %d, is equal to or exceeds allowed maximum: %d", numUnavailable, maxUnavailable)
  62. break
  63. }
  64. klog.V(4).Infof("Marking pod %s/%s for deletion", ds.Name, pod.Name)
  65. oldPodsToDelete = append(oldPodsToDelete, pod.Name)
  66. numUnavailable++
  67. }
  68. return dsc.syncNodes(ds, oldPodsToDelete, []string{}, hash)
  69. }
  70. // constructHistory finds all histories controlled by the given DaemonSet, and
  71. // update current history revision number, or create current history if need to.
  72. // It also deduplicates current history, and adds missing unique labels to existing histories.
  73. func (dsc *DaemonSetsController) constructHistory(ds *apps.DaemonSet) (cur *apps.ControllerRevision, old []*apps.ControllerRevision, err error) {
  74. var histories []*apps.ControllerRevision
  75. var currentHistories []*apps.ControllerRevision
  76. histories, err = dsc.controlledHistories(ds)
  77. if err != nil {
  78. return nil, nil, err
  79. }
  80. for _, history := range histories {
  81. // Add the unique label if it's not already added to the history
  82. // We use history name instead of computing hash, so that we don't need to worry about hash collision
  83. if _, ok := history.Labels[apps.DefaultDaemonSetUniqueLabelKey]; !ok {
  84. toUpdate := history.DeepCopy()
  85. toUpdate.Labels[apps.DefaultDaemonSetUniqueLabelKey] = toUpdate.Name
  86. history, err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Update(context.TODO(), toUpdate, metav1.UpdateOptions{})
  87. if err != nil {
  88. return nil, nil, err
  89. }
  90. }
  91. // Compare histories with ds to separate cur and old history
  92. found := false
  93. found, err = Match(ds, history)
  94. if err != nil {
  95. return nil, nil, err
  96. }
  97. if found {
  98. currentHistories = append(currentHistories, history)
  99. } else {
  100. old = append(old, history)
  101. }
  102. }
  103. currRevision := maxRevision(old) + 1
  104. switch len(currentHistories) {
  105. case 0:
  106. // Create a new history if the current one isn't found
  107. cur, err = dsc.snapshot(ds, currRevision)
  108. if err != nil {
  109. return nil, nil, err
  110. }
  111. default:
  112. cur, err = dsc.dedupCurHistories(ds, currentHistories)
  113. if err != nil {
  114. return nil, nil, err
  115. }
  116. // Update revision number if necessary
  117. if cur.Revision < currRevision {
  118. toUpdate := cur.DeepCopy()
  119. toUpdate.Revision = currRevision
  120. _, err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Update(context.TODO(), toUpdate, metav1.UpdateOptions{})
  121. if err != nil {
  122. return nil, nil, err
  123. }
  124. }
  125. }
  126. return cur, old, err
  127. }
  128. func (dsc *DaemonSetsController) cleanupHistory(ds *apps.DaemonSet, old []*apps.ControllerRevision) error {
  129. nodesToDaemonPods, err := dsc.getNodesToDaemonPods(ds)
  130. if err != nil {
  131. return fmt.Errorf("couldn't get node to daemon pod mapping for daemon set %q: %v", ds.Name, err)
  132. }
  133. toKeep := int(*ds.Spec.RevisionHistoryLimit)
  134. toKill := len(old) - toKeep
  135. if toKill <= 0 {
  136. return nil
  137. }
  138. // Find all hashes of live pods
  139. liveHashes := make(map[string]bool)
  140. for _, pods := range nodesToDaemonPods {
  141. for _, pod := range pods {
  142. if hash := pod.Labels[apps.DefaultDaemonSetUniqueLabelKey]; len(hash) > 0 {
  143. liveHashes[hash] = true
  144. }
  145. }
  146. }
  147. // Clean up old history from smallest to highest revision (from oldest to newest)
  148. sort.Sort(historiesByRevision(old))
  149. for _, history := range old {
  150. if toKill <= 0 {
  151. break
  152. }
  153. if hash := history.Labels[apps.DefaultDaemonSetUniqueLabelKey]; liveHashes[hash] {
  154. continue
  155. }
  156. // Clean up
  157. err := dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Delete(context.TODO(), history.Name, nil)
  158. if err != nil {
  159. return err
  160. }
  161. toKill--
  162. }
  163. return nil
  164. }
  165. // maxRevision returns the max revision number of the given list of histories
  166. func maxRevision(histories []*apps.ControllerRevision) int64 {
  167. max := int64(0)
  168. for _, history := range histories {
  169. if history.Revision > max {
  170. max = history.Revision
  171. }
  172. }
  173. return max
  174. }
  175. func (dsc *DaemonSetsController) dedupCurHistories(ds *apps.DaemonSet, curHistories []*apps.ControllerRevision) (*apps.ControllerRevision, error) {
  176. if len(curHistories) == 1 {
  177. return curHistories[0], nil
  178. }
  179. var maxRevision int64
  180. var keepCur *apps.ControllerRevision
  181. for _, cur := range curHistories {
  182. if cur.Revision >= maxRevision {
  183. keepCur = cur
  184. maxRevision = cur.Revision
  185. }
  186. }
  187. // Clean up duplicates and relabel pods
  188. for _, cur := range curHistories {
  189. if cur.Name == keepCur.Name {
  190. continue
  191. }
  192. // Relabel pods before dedup
  193. pods, err := dsc.getDaemonPods(ds)
  194. if err != nil {
  195. return nil, err
  196. }
  197. for _, pod := range pods {
  198. if pod.Labels[apps.DefaultDaemonSetUniqueLabelKey] != keepCur.Labels[apps.DefaultDaemonSetUniqueLabelKey] {
  199. toUpdate := pod.DeepCopy()
  200. if toUpdate.Labels == nil {
  201. toUpdate.Labels = make(map[string]string)
  202. }
  203. toUpdate.Labels[apps.DefaultDaemonSetUniqueLabelKey] = keepCur.Labels[apps.DefaultDaemonSetUniqueLabelKey]
  204. _, err = dsc.kubeClient.CoreV1().Pods(ds.Namespace).Update(context.TODO(), toUpdate, metav1.UpdateOptions{})
  205. if err != nil {
  206. return nil, err
  207. }
  208. }
  209. }
  210. // Remove duplicates
  211. err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Delete(context.TODO(), cur.Name, nil)
  212. if err != nil {
  213. return nil, err
  214. }
  215. }
  216. return keepCur, nil
  217. }
  218. // controlledHistories returns all ControllerRevisions controlled by the given DaemonSet.
  219. // This also reconciles ControllerRef by adopting/orphaning.
  220. // Note that returned histories are pointers to objects in the cache.
  221. // If you want to modify one, you need to deep-copy it first.
  222. func (dsc *DaemonSetsController) controlledHistories(ds *apps.DaemonSet) ([]*apps.ControllerRevision, error) {
  223. selector, err := metav1.LabelSelectorAsSelector(ds.Spec.Selector)
  224. if err != nil {
  225. return nil, err
  226. }
  227. // List all histories to include those that don't match the selector anymore
  228. // but have a ControllerRef pointing to the controller.
  229. histories, err := dsc.historyLister.List(labels.Everything())
  230. if err != nil {
  231. return nil, err
  232. }
  233. // If any adoptions are attempted, we should first recheck for deletion with
  234. // an uncached quorum read sometime after listing Pods (see #42639).
  235. canAdoptFunc := controller.RecheckDeletionTimestamp(func() (metav1.Object, error) {
  236. fresh, err := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).Get(context.TODO(), ds.Name, metav1.GetOptions{})
  237. if err != nil {
  238. return nil, err
  239. }
  240. if fresh.UID != ds.UID {
  241. return nil, fmt.Errorf("original DaemonSet %v/%v is gone: got uid %v, wanted %v", ds.Namespace, ds.Name, fresh.UID, ds.UID)
  242. }
  243. return fresh, nil
  244. })
  245. // Use ControllerRefManager to adopt/orphan as needed.
  246. cm := controller.NewControllerRevisionControllerRefManager(dsc.crControl, ds, selector, controllerKind, canAdoptFunc)
  247. return cm.ClaimControllerRevisions(histories)
  248. }
  249. // Match check if the given DaemonSet's template matches the template stored in the given history.
  250. func Match(ds *apps.DaemonSet, history *apps.ControllerRevision) (bool, error) {
  251. patch, err := getPatch(ds)
  252. if err != nil {
  253. return false, err
  254. }
  255. return bytes.Equal(patch, history.Data.Raw), nil
  256. }
  257. // getPatch returns a strategic merge patch that can be applied to restore a Daemonset to a
  258. // previous version. If the returned error is nil the patch is valid. The current state that we save is just the
  259. // PodSpecTemplate. We can modify this later to encompass more state (or less) and remain compatible with previously
  260. // recorded patches.
  261. func getPatch(ds *apps.DaemonSet) ([]byte, error) {
  262. dsBytes, err := json.Marshal(ds)
  263. if err != nil {
  264. return nil, err
  265. }
  266. var raw map[string]interface{}
  267. err = json.Unmarshal(dsBytes, &raw)
  268. if err != nil {
  269. return nil, err
  270. }
  271. objCopy := make(map[string]interface{})
  272. specCopy := make(map[string]interface{})
  273. // Create a patch of the DaemonSet that replaces spec.template
  274. spec := raw["spec"].(map[string]interface{})
  275. template := spec["template"].(map[string]interface{})
  276. specCopy["template"] = template
  277. template["$patch"] = "replace"
  278. objCopy["spec"] = specCopy
  279. patch, err := json.Marshal(objCopy)
  280. return patch, err
  281. }
  282. func (dsc *DaemonSetsController) snapshot(ds *apps.DaemonSet, revision int64) (*apps.ControllerRevision, error) {
  283. patch, err := getPatch(ds)
  284. if err != nil {
  285. return nil, err
  286. }
  287. hash := controller.ComputeHash(&ds.Spec.Template, ds.Status.CollisionCount)
  288. name := ds.Name + "-" + hash
  289. history := &apps.ControllerRevision{
  290. ObjectMeta: metav1.ObjectMeta{
  291. Name: name,
  292. Namespace: ds.Namespace,
  293. Labels: labelsutil.CloneAndAddLabel(ds.Spec.Template.Labels, apps.DefaultDaemonSetUniqueLabelKey, hash),
  294. Annotations: ds.Annotations,
  295. OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(ds, controllerKind)},
  296. },
  297. Data: runtime.RawExtension{Raw: patch},
  298. Revision: revision,
  299. }
  300. history, err = dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Create(context.TODO(), history, metav1.CreateOptions{})
  301. if outerErr := err; errors.IsAlreadyExists(outerErr) {
  302. // TODO: Is it okay to get from historyLister?
  303. existedHistory, getErr := dsc.kubeClient.AppsV1().ControllerRevisions(ds.Namespace).Get(context.TODO(), name, metav1.GetOptions{})
  304. if getErr != nil {
  305. return nil, getErr
  306. }
  307. // Check if we already created it
  308. done, matchErr := Match(ds, existedHistory)
  309. if matchErr != nil {
  310. return nil, matchErr
  311. }
  312. if done {
  313. return existedHistory, nil
  314. }
  315. // Handle name collisions between different history
  316. // Get the latest DaemonSet from the API server to make sure collision count is only increased when necessary
  317. currDS, getErr := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).Get(context.TODO(), ds.Name, metav1.GetOptions{})
  318. if getErr != nil {
  319. return nil, getErr
  320. }
  321. // If the collision count used to compute hash was in fact stale, there's no need to bump collision count; retry again
  322. if !reflect.DeepEqual(currDS.Status.CollisionCount, ds.Status.CollisionCount) {
  323. return nil, fmt.Errorf("found a stale collision count (%d, expected %d) of DaemonSet %q while processing; will retry until it is updated", ds.Status.CollisionCount, currDS.Status.CollisionCount, ds.Name)
  324. }
  325. if currDS.Status.CollisionCount == nil {
  326. currDS.Status.CollisionCount = new(int32)
  327. }
  328. *currDS.Status.CollisionCount++
  329. _, updateErr := dsc.kubeClient.AppsV1().DaemonSets(ds.Namespace).UpdateStatus(context.TODO(), currDS, metav1.UpdateOptions{})
  330. if updateErr != nil {
  331. return nil, updateErr
  332. }
  333. klog.V(2).Infof("Found a hash collision for DaemonSet %q - bumping collisionCount to %d to resolve it", ds.Name, *currDS.Status.CollisionCount)
  334. return nil, outerErr
  335. }
  336. return history, err
  337. }
  338. func (dsc *DaemonSetsController) getAllDaemonSetPods(ds *apps.DaemonSet, nodeToDaemonPods map[string][]*v1.Pod, hash string) ([]*v1.Pod, []*v1.Pod) {
  339. var newPods []*v1.Pod
  340. var oldPods []*v1.Pod
  341. for _, pods := range nodeToDaemonPods {
  342. for _, pod := range pods {
  343. // If the returned error is not nil we have a parse error.
  344. // The controller handles this via the hash.
  345. generation, err := util.GetTemplateGeneration(ds)
  346. if err != nil {
  347. generation = nil
  348. }
  349. if util.IsPodUpdated(pod, hash, generation) {
  350. newPods = append(newPods, pod)
  351. } else {
  352. oldPods = append(oldPods, pod)
  353. }
  354. }
  355. }
  356. return newPods, oldPods
  357. }
  358. func (dsc *DaemonSetsController) getUnavailableNumbers(ds *apps.DaemonSet, nodeList []*v1.Node, nodeToDaemonPods map[string][]*v1.Pod) (int, int, error) {
  359. klog.V(4).Infof("Getting unavailable numbers")
  360. var numUnavailable, desiredNumberScheduled int
  361. for i := range nodeList {
  362. node := nodeList[i]
  363. wantToRun, _, err := dsc.nodeShouldRunDaemonPod(node, ds)
  364. if err != nil {
  365. return -1, -1, err
  366. }
  367. if !wantToRun {
  368. continue
  369. }
  370. desiredNumberScheduled++
  371. daemonPods, exists := nodeToDaemonPods[node.Name]
  372. if !exists {
  373. numUnavailable++
  374. continue
  375. }
  376. available := false
  377. for _, pod := range daemonPods {
  378. //for the purposes of update we ensure that the Pod is both available and not terminating
  379. if podutil.IsPodAvailable(pod, ds.Spec.MinReadySeconds, metav1.Now()) && pod.DeletionTimestamp == nil {
  380. available = true
  381. break
  382. }
  383. }
  384. if !available {
  385. numUnavailable++
  386. }
  387. }
  388. maxUnavailable, err := intstrutil.GetValueFromIntOrPercent(ds.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable, desiredNumberScheduled, true)
  389. if err != nil {
  390. return -1, -1, fmt.Errorf("invalid value for MaxUnavailable: %v", err)
  391. }
  392. klog.V(4).Infof(" DaemonSet %s/%s, maxUnavailable: %d, numUnavailable: %d", ds.Namespace, ds.Name, maxUnavailable, numUnavailable)
  393. return maxUnavailable, numUnavailable, nil
  394. }
  395. type historiesByRevision []*apps.ControllerRevision
  396. func (h historiesByRevision) Len() int { return len(h) }
  397. func (h historiesByRevision) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  398. func (h historiesByRevision) Less(i, j int) bool {
  399. return h[i].Revision < h[j].Revision
  400. }