postupgrade.go 9.1 KB

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