prepull.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 upgrade
  14. import (
  15. "fmt"
  16. "time"
  17. "github.com/pkg/errors"
  18. apps "k8s.io/api/apps/v1"
  19. "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. clientset "k8s.io/client-go/kubernetes"
  22. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  23. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  24. "k8s.io/kubernetes/cmd/kubeadm/app/images"
  25. "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
  26. )
  27. const (
  28. prepullPrefix = "upgrade-prepull-"
  29. )
  30. // Prepuller defines an interface for performing a prepull operation in a create-wait-delete fashion in parallel
  31. type Prepuller interface {
  32. CreateFunc(string) error
  33. WaitFunc(string)
  34. DeleteFunc(string) error
  35. }
  36. // DaemonSetPrepuller makes sure the control-plane images are available on all control-planes
  37. type DaemonSetPrepuller struct {
  38. client clientset.Interface
  39. cfg *kubeadmapi.ClusterConfiguration
  40. waiter apiclient.Waiter
  41. }
  42. // NewDaemonSetPrepuller creates a new instance of the DaemonSetPrepuller struct
  43. func NewDaemonSetPrepuller(client clientset.Interface, waiter apiclient.Waiter, cfg *kubeadmapi.ClusterConfiguration) *DaemonSetPrepuller {
  44. return &DaemonSetPrepuller{
  45. client: client,
  46. cfg: cfg,
  47. waiter: waiter,
  48. }
  49. }
  50. // CreateFunc creates a DaemonSet for making the image available on every relevant node
  51. func (d *DaemonSetPrepuller) CreateFunc(component string) error {
  52. var image string
  53. if component == constants.Etcd {
  54. image = images.GetEtcdImage(d.cfg)
  55. } else {
  56. image = images.GetKubernetesImage(component, d.cfg)
  57. }
  58. ds := buildPrePullDaemonSet(component, image)
  59. // Create the DaemonSet in the API Server
  60. if err := apiclient.CreateOrUpdateDaemonSet(d.client, ds); err != nil {
  61. return errors.Wrapf(err, "unable to create a DaemonSet for prepulling the component %q", component)
  62. }
  63. return nil
  64. }
  65. // WaitFunc waits for all Pods in the specified DaemonSet to be in the Running state
  66. func (d *DaemonSetPrepuller) WaitFunc(component string) {
  67. fmt.Printf("[upgrade/prepull] Prepulling image for component %s.\n", component)
  68. d.waiter.WaitForPodsWithLabel("k8s-app=upgrade-prepull-" + component)
  69. }
  70. // DeleteFunc deletes the DaemonSet used for making the image available on every relevant node
  71. func (d *DaemonSetPrepuller) DeleteFunc(component string) error {
  72. dsName := addPrepullPrefix(component)
  73. if err := apiclient.DeleteDaemonSetForeground(d.client, metav1.NamespaceSystem, dsName); err != nil {
  74. return errors.Wrapf(err, "unable to cleanup the DaemonSet used for prepulling %s", component)
  75. }
  76. fmt.Printf("[upgrade/prepull] Prepulled image for component %s.\n", component)
  77. return nil
  78. }
  79. // PrepullImagesInParallel creates DaemonSets synchronously but waits in parallel for the images to pull
  80. func PrepullImagesInParallel(kubePrepuller Prepuller, timeout time.Duration, componentsToPrepull []string) error {
  81. fmt.Printf("[upgrade/prepull] Will prepull images for components %v\n", componentsToPrepull)
  82. timeoutChan := time.After(timeout)
  83. // Synchronously create the DaemonSets
  84. for _, component := range componentsToPrepull {
  85. if err := kubePrepuller.CreateFunc(component); err != nil {
  86. return err
  87. }
  88. }
  89. // Create a channel for streaming data from goroutines that run in parallel to a blocking for loop that cleans up
  90. prePulledChan := make(chan string, len(componentsToPrepull))
  91. for _, component := range componentsToPrepull {
  92. go func(c string) {
  93. // Wait as long as needed. This WaitFunc call should be blocking until completion
  94. kubePrepuller.WaitFunc(c)
  95. // When the task is done, go ahead and cleanup by sending the name to the channel
  96. prePulledChan <- c
  97. }(component)
  98. }
  99. // This call blocks until all expected messages are received from the channel or errors out if timeoutChan fires.
  100. // For every successful wait, kubePrepuller.DeleteFunc is executed
  101. if err := waitForItemsFromChan(timeoutChan, prePulledChan, len(componentsToPrepull), kubePrepuller.DeleteFunc); err != nil {
  102. return err
  103. }
  104. fmt.Println("[upgrade/prepull] Successfully prepulled the images for all the control plane components")
  105. return nil
  106. }
  107. // waitForItemsFromChan waits for n elements from stringChan with a timeout. For every item received from stringChan, cleanupFunc is executed
  108. func waitForItemsFromChan(timeoutChan <-chan time.Time, stringChan chan string, n int, cleanupFunc func(string) error) error {
  109. i := 0
  110. for {
  111. select {
  112. case <-timeoutChan:
  113. return errors.New("The prepull operation timed out")
  114. case result := <-stringChan:
  115. i++
  116. // If the cleanup function errors; error here as well
  117. if err := cleanupFunc(result); err != nil {
  118. return err
  119. }
  120. if i == n {
  121. return nil
  122. }
  123. }
  124. }
  125. }
  126. // addPrepullPrefix adds the prepull prefix for this functionality; can be used in names, labels, etc.
  127. func addPrepullPrefix(component string) string {
  128. return fmt.Sprintf("%s%s", prepullPrefix, component)
  129. }
  130. // buildPrePullDaemonSet builds the DaemonSet that ensures the control plane image is available
  131. func buildPrePullDaemonSet(component, image string) *apps.DaemonSet {
  132. var gracePeriodSecs int64
  133. return &apps.DaemonSet{
  134. ObjectMeta: metav1.ObjectMeta{
  135. Name: addPrepullPrefix(component),
  136. Namespace: metav1.NamespaceSystem,
  137. },
  138. Spec: apps.DaemonSetSpec{
  139. Selector: &metav1.LabelSelector{
  140. MatchLabels: map[string]string{
  141. "k8s-app": addPrepullPrefix(component),
  142. },
  143. },
  144. Template: v1.PodTemplateSpec{
  145. ObjectMeta: metav1.ObjectMeta{
  146. Labels: map[string]string{
  147. "k8s-app": addPrepullPrefix(component),
  148. },
  149. },
  150. Spec: v1.PodSpec{
  151. Containers: []v1.Container{
  152. {
  153. Name: component,
  154. Image: image,
  155. Command: []string{"/bin/sleep", "3600"},
  156. },
  157. },
  158. NodeSelector: map[string]string{
  159. constants.LabelNodeRoleMaster: "",
  160. },
  161. Tolerations: []v1.Toleration{constants.ControlPlaneToleration},
  162. TerminationGracePeriodSeconds: &gracePeriodSecs,
  163. },
  164. },
  165. },
  166. }
  167. }