postupgrade.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. "context"
  16. "os"
  17. "github.com/pkg/errors"
  18. apierrors "k8s.io/apimachinery/pkg/api/errors"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/fields"
  21. errorsutil "k8s.io/apimachinery/pkg/util/errors"
  22. "k8s.io/apimachinery/pkg/util/version"
  23. clientset "k8s.io/client-go/kubernetes"
  24. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  25. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  26. "k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/dns"
  27. "k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/proxy"
  28. "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/clusterinfo"
  29. nodebootstraptoken "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/node"
  30. kubeletphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/kubelet"
  31. patchnodephase "k8s.io/kubernetes/cmd/kubeadm/app/phases/patchnode"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/phases/uploadconfig"
  33. "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
  34. dryrunutil "k8s.io/kubernetes/cmd/kubeadm/app/util/dryrun"
  35. )
  36. // PerformPostUpgradeTasks runs nearly the same functions as 'kubeadm init' would do
  37. // Note that the mark-control-plane phase is left out, not needed, and no token is created as that doesn't belong to the upgrade
  38. func PerformPostUpgradeTasks(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error {
  39. errs := []error{}
  40. // Upload currently used configuration to the cluster
  41. // Note: This is done right in the beginning of cluster initialization; as we might want to make other phases
  42. // depend on centralized information from this source in the future
  43. if err := uploadconfig.UploadConfiguration(cfg, client); err != nil {
  44. errs = append(errs, err)
  45. }
  46. // Create the new, version-branched kubelet ComponentConfig ConfigMap
  47. if err := kubeletphase.CreateConfigMap(&cfg.ClusterConfiguration, client); err != nil {
  48. errs = append(errs, errors.Wrap(err, "error creating kubelet configuration ConfigMap"))
  49. }
  50. // Write the new kubelet config down to disk and the env file if needed
  51. if err := writeKubeletConfigFiles(client, cfg, newK8sVer, dryRun); err != nil {
  52. errs = append(errs, err)
  53. }
  54. // Annotate the node with the crisocket information, sourced either from the InitConfiguration struct or
  55. // --cri-socket.
  56. // TODO: In the future we want to use something more official like NodeStatus or similar for detecting this properly
  57. if err := patchnodephase.AnnotateCRISocket(client, cfg.NodeRegistration.Name, cfg.NodeRegistration.CRISocket); err != nil {
  58. errs = append(errs, errors.Wrap(err, "error uploading crisocket"))
  59. }
  60. // Create/update RBAC rules that makes the bootstrap tokens able to post CSRs
  61. if err := nodebootstraptoken.AllowBootstrapTokensToPostCSRs(client); err != nil {
  62. errs = append(errs, err)
  63. }
  64. // Create/update RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically
  65. if err := nodebootstraptoken.AutoApproveNodeBootstrapTokens(client); err != nil {
  66. errs = append(errs, err)
  67. }
  68. // Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically
  69. if err := nodebootstraptoken.AutoApproveNodeCertificateRotation(client); err != nil {
  70. errs = append(errs, err)
  71. }
  72. // TODO: Is this needed to do here? I think that updating cluster info should probably be separate from a normal upgrade
  73. // Create the cluster-info ConfigMap with the associated RBAC rules
  74. // if err := clusterinfo.CreateBootstrapConfigMapIfNotExists(client, kubeadmconstants.GetAdminKubeConfigPath()); err != nil {
  75. // return err
  76. //}
  77. // Create/update RBAC rules that makes the cluster-info ConfigMap reachable
  78. if err := clusterinfo.CreateClusterInfoRBACRules(client); err != nil {
  79. errs = append(errs, err)
  80. }
  81. // Upgrade kube-dns/CoreDNS and kube-proxy
  82. if err := dns.EnsureDNSAddon(&cfg.ClusterConfiguration, client); err != nil {
  83. errs = append(errs, err)
  84. }
  85. // Remove the old DNS deployment if a new DNS service is now used (kube-dns to CoreDNS or vice versa)
  86. if err := removeOldDNSDeploymentIfAnotherDNSIsUsed(&cfg.ClusterConfiguration, client, dryRun); err != nil {
  87. errs = append(errs, err)
  88. }
  89. if err := proxy.EnsureProxyAddon(&cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint, client); err != nil {
  90. errs = append(errs, err)
  91. }
  92. return errorsutil.NewAggregate(errs)
  93. }
  94. func removeOldDNSDeploymentIfAnotherDNSIsUsed(cfg *kubeadmapi.ClusterConfiguration, client clientset.Interface, dryRun bool) error {
  95. return apiclient.TryRunCommand(func() error {
  96. installedDeploymentName := kubeadmconstants.KubeDNSDeploymentName
  97. deploymentToDelete := kubeadmconstants.CoreDNSDeploymentName
  98. if cfg.DNS.Type == kubeadmapi.CoreDNS {
  99. installedDeploymentName = kubeadmconstants.CoreDNSDeploymentName
  100. deploymentToDelete = kubeadmconstants.KubeDNSDeploymentName
  101. }
  102. nodes, err := client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{
  103. FieldSelector: fields.Set{"spec.unschedulable": "false"}.AsSelector().String(),
  104. })
  105. if err != nil {
  106. return err
  107. }
  108. // If we're dry-running or there are no scheduable nodes available, we don't need to wait for the new DNS addon to become ready
  109. if !dryRun && len(nodes.Items) != 0 {
  110. dnsDeployment, err := client.AppsV1().Deployments(metav1.NamespaceSystem).Get(context.TODO(), installedDeploymentName, metav1.GetOptions{})
  111. if err != nil {
  112. return err
  113. }
  114. if dnsDeployment.Status.ReadyReplicas == 0 {
  115. return errors.New("the DNS deployment isn't ready yet")
  116. }
  117. }
  118. // We don't want to wait for the DNS deployment above to become ready when dryrunning (as it never will)
  119. // but here we should execute the DELETE command against the dryrun clientset, as it will only be logged
  120. err = apiclient.DeleteDeploymentForeground(client, metav1.NamespaceSystem, deploymentToDelete)
  121. if err != nil && !apierrors.IsNotFound(err) {
  122. return err
  123. }
  124. return nil
  125. }, 10)
  126. }
  127. func writeKubeletConfigFiles(client clientset.Interface, cfg *kubeadmapi.InitConfiguration, newK8sVer *version.Version, dryRun bool) error {
  128. kubeletDir, err := GetKubeletDir(dryRun)
  129. if err != nil {
  130. // The error here should never occur in reality, would only be thrown if /tmp doesn't exist on the machine.
  131. return err
  132. }
  133. errs := []error{}
  134. // Write the configuration for the kubelet down to disk so the upgraded kubelet can start with fresh config
  135. if err := kubeletphase.DownloadConfig(client, newK8sVer, kubeletDir); err != nil {
  136. // Tolerate the error being NotFound when dryrunning, as there is a pretty common scenario: the dryrun process
  137. // *would* post the new kubelet-config-1.X configmap that doesn't exist now when we're trying to download it
  138. // again.
  139. if !(apierrors.IsNotFound(err) && dryRun) {
  140. errs = append(errs, errors.Wrap(err, "error downloading kubelet configuration from the ConfigMap"))
  141. }
  142. }
  143. if dryRun { // Print what contents would be written
  144. dryrunutil.PrintDryRunFile(kubeadmconstants.KubeletConfigurationFileName, kubeletDir, kubeadmconstants.KubeletRunDirectory, os.Stdout)
  145. }
  146. return errorsutil.NewAggregate(errs)
  147. }
  148. // GetKubeletDir gets the kubelet directory based on whether the user is dry-running this command or not.
  149. func GetKubeletDir(dryRun bool) (string, error) {
  150. if dryRun {
  151. return kubeadmconstants.CreateTempDirForKubeadm("", "kubeadm-upgrade-dryrun")
  152. }
  153. return kubeadmconstants.KubeletRunDirectory, nil
  154. }
  155. // moveFiles moves files from one directory to another.
  156. func moveFiles(files map[string]string) error {
  157. filesToRecover := map[string]string{}
  158. for from, to := range files {
  159. if err := os.Rename(from, to); err != nil {
  160. return rollbackFiles(filesToRecover, err)
  161. }
  162. filesToRecover[to] = from
  163. }
  164. return nil
  165. }
  166. // rollbackFiles moves the files back to the original directory.
  167. func rollbackFiles(files map[string]string, originalErr error) error {
  168. errs := []error{originalErr}
  169. for from, to := range files {
  170. if err := os.Rename(from, to); err != nil {
  171. errs = append(errs, err)
  172. }
  173. }
  174. return errors.Errorf("couldn't move these files: %v. Got errors: %v", files, errorsutil.NewAggregate(errs))
  175. }