staticpods.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. "os"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. "github.com/pkg/errors"
  21. utilerrors "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. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  26. certsphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs"
  27. "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs/renewal"
  28. "k8s.io/kubernetes/cmd/kubeadm/app/phases/controlplane"
  29. etcdphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/etcd"
  30. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  31. "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
  32. dryrunutil "k8s.io/kubernetes/cmd/kubeadm/app/util/dryrun"
  33. etcdutil "k8s.io/kubernetes/cmd/kubeadm/app/util/etcd"
  34. "k8s.io/kubernetes/cmd/kubeadm/app/util/staticpod"
  35. )
  36. const (
  37. // UpgradeManifestTimeout is timeout of upgrading the static pod manifest
  38. UpgradeManifestTimeout = 5 * time.Minute
  39. )
  40. // StaticPodPathManager is responsible for tracking the directories used in the static pod upgrade transition
  41. type StaticPodPathManager interface {
  42. // MoveFile should move a file from oldPath to newPath
  43. MoveFile(oldPath, newPath string) error
  44. // KubernetesDir is the directory Kubernetes owns for storing various configuration files
  45. KubernetesDir() string
  46. // KustomizeDir should point to the folder where kustomize patches for static pod manifest are stored
  47. KustomizeDir() string
  48. // RealManifestPath gets the file path for the component in the "real" static pod manifest directory used by the kubelet
  49. RealManifestPath(component string) string
  50. // RealManifestDir should point to the static pod manifest directory used by the kubelet
  51. RealManifestDir() string
  52. // TempManifestPath gets the file path for the component in the temporary directory created for generating new manifests for the upgrade
  53. TempManifestPath(component string) string
  54. // TempManifestDir should point to the temporary directory created for generating new manifests for the upgrade
  55. TempManifestDir() string
  56. // BackupManifestPath gets the file path for the component in the backup directory used for backuping manifests during the transition
  57. BackupManifestPath(component string) string
  58. // BackupManifestDir should point to the backup directory used for backuping manifests during the transition
  59. BackupManifestDir() string
  60. // BackupEtcdDir should point to the backup directory used for backuping manifests during the transition
  61. BackupEtcdDir() string
  62. // CleanupDirs cleans up all temporary directories
  63. CleanupDirs() error
  64. }
  65. // KubeStaticPodPathManager is a real implementation of StaticPodPathManager that is used when upgrading a static pod cluster
  66. type KubeStaticPodPathManager struct {
  67. kubernetesDir string
  68. kustomizeDir string
  69. realManifestDir string
  70. tempManifestDir string
  71. backupManifestDir string
  72. backupEtcdDir string
  73. keepManifestDir bool
  74. keepEtcdDir bool
  75. }
  76. // NewKubeStaticPodPathManager creates a new instance of KubeStaticPodPathManager
  77. func NewKubeStaticPodPathManager(kubernetesDir, kustomizeDir, tempDir, backupDir, backupEtcdDir string, keepManifestDir, keepEtcdDir bool) StaticPodPathManager {
  78. return &KubeStaticPodPathManager{
  79. kubernetesDir: kubernetesDir,
  80. kustomizeDir: kustomizeDir,
  81. realManifestDir: filepath.Join(kubernetesDir, constants.ManifestsSubDirName),
  82. tempManifestDir: tempDir,
  83. backupManifestDir: backupDir,
  84. backupEtcdDir: backupEtcdDir,
  85. keepManifestDir: keepManifestDir,
  86. keepEtcdDir: keepEtcdDir,
  87. }
  88. }
  89. // NewKubeStaticPodPathManagerUsingTempDirs creates a new instance of KubeStaticPodPathManager with temporary directories backing it
  90. func NewKubeStaticPodPathManagerUsingTempDirs(kubernetesDir, kustomizeDir string, saveManifestsDir, saveEtcdDir bool) (StaticPodPathManager, error) {
  91. upgradedManifestsDir, err := constants.CreateTempDirForKubeadm(kubernetesDir, "kubeadm-upgraded-manifests")
  92. if err != nil {
  93. return nil, err
  94. }
  95. backupManifestsDir, err := constants.CreateTimestampDirForKubeadm(kubernetesDir, "kubeadm-backup-manifests")
  96. if err != nil {
  97. return nil, err
  98. }
  99. backupEtcdDir, err := constants.CreateTimestampDirForKubeadm(kubernetesDir, "kubeadm-backup-etcd")
  100. if err != nil {
  101. return nil, err
  102. }
  103. return NewKubeStaticPodPathManager(kubernetesDir, kustomizeDir, upgradedManifestsDir, backupManifestsDir, backupEtcdDir, saveManifestsDir, saveEtcdDir), nil
  104. }
  105. // MoveFile should move a file from oldPath to newPath
  106. func (spm *KubeStaticPodPathManager) MoveFile(oldPath, newPath string) error {
  107. return os.Rename(oldPath, newPath)
  108. }
  109. // KubernetesDir should point to the directory Kubernetes owns for storing various configuration files
  110. func (spm *KubeStaticPodPathManager) KubernetesDir() string {
  111. return spm.kubernetesDir
  112. }
  113. // KustomizeDir should point to the folder where kustomize patches for static pod manifest are stored
  114. func (spm *KubeStaticPodPathManager) KustomizeDir() string {
  115. return spm.kustomizeDir
  116. }
  117. // RealManifestPath gets the file path for the component in the "real" static pod manifest directory used by the kubelet
  118. func (spm *KubeStaticPodPathManager) RealManifestPath(component string) string {
  119. return constants.GetStaticPodFilepath(component, spm.realManifestDir)
  120. }
  121. // RealManifestDir should point to the static pod manifest directory used by the kubelet
  122. func (spm *KubeStaticPodPathManager) RealManifestDir() string {
  123. return spm.realManifestDir
  124. }
  125. // TempManifestPath gets the file path for the component in the temporary directory created for generating new manifests for the upgrade
  126. func (spm *KubeStaticPodPathManager) TempManifestPath(component string) string {
  127. return constants.GetStaticPodFilepath(component, spm.tempManifestDir)
  128. }
  129. // TempManifestDir should point to the temporary directory created for generating new manifests for the upgrade
  130. func (spm *KubeStaticPodPathManager) TempManifestDir() string {
  131. return spm.tempManifestDir
  132. }
  133. // BackupManifestPath gets the file path for the component in the backup directory used for backuping manifests during the transition
  134. func (spm *KubeStaticPodPathManager) BackupManifestPath(component string) string {
  135. return constants.GetStaticPodFilepath(component, spm.backupManifestDir)
  136. }
  137. // BackupManifestDir should point to the backup directory used for backuping manifests during the transition
  138. func (spm *KubeStaticPodPathManager) BackupManifestDir() string {
  139. return spm.backupManifestDir
  140. }
  141. // BackupEtcdDir should point to the backup directory used for backuping manifests during the transition
  142. func (spm *KubeStaticPodPathManager) BackupEtcdDir() string {
  143. return spm.backupEtcdDir
  144. }
  145. // CleanupDirs cleans up all temporary directories except those the user has requested to keep around
  146. func (spm *KubeStaticPodPathManager) CleanupDirs() error {
  147. var errlist []error
  148. if err := os.RemoveAll(spm.TempManifestDir()); err != nil {
  149. errlist = append(errlist, err)
  150. }
  151. if !spm.keepManifestDir {
  152. if err := os.RemoveAll(spm.BackupManifestDir()); err != nil {
  153. errlist = append(errlist, err)
  154. }
  155. }
  156. if !spm.keepEtcdDir {
  157. if err := os.RemoveAll(spm.BackupEtcdDir()); err != nil {
  158. errlist = append(errlist, err)
  159. }
  160. }
  161. return utilerrors.NewAggregate(errlist)
  162. }
  163. func upgradeComponent(component string, certsRenewMgr *renewal.Manager, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, beforePodHash string, recoverManifests map[string]string) error {
  164. // Special treatment is required for etcd case, when rollbackOldManifests should roll back etcd
  165. // manifests only for the case when component is Etcd
  166. recoverEtcd := false
  167. if component == constants.Etcd {
  168. recoverEtcd = true
  169. }
  170. fmt.Printf("[upgrade/staticpods] Preparing for %q upgrade\n", component)
  171. // The old manifest is here; in the /etc/kubernetes/manifests/
  172. currentManifestPath := pathMgr.RealManifestPath(component)
  173. // The new, upgraded manifest will be written here
  174. newManifestPath := pathMgr.TempManifestPath(component)
  175. // The old manifest will be moved here; into a subfolder of the temporary directory
  176. // If a rollback is needed, these manifests will be put back to where they where initially
  177. backupManifestPath := pathMgr.BackupManifestPath(component)
  178. // Store the backup path in the recover list. If something goes wrong now, this component will be rolled back.
  179. recoverManifests[component] = backupManifestPath
  180. // Skip upgrade if current and new manifests are equal
  181. equal, err := staticpod.ManifestFilesAreEqual(currentManifestPath, newManifestPath)
  182. if err != nil {
  183. return err
  184. }
  185. if equal {
  186. fmt.Printf("[upgrade/staticpods] Current and new manifests of %s are equal, skipping upgrade\n", component)
  187. return nil
  188. }
  189. // if certificate renewal should be performed
  190. if certsRenewMgr != nil {
  191. // renew all the certificates used by the current component
  192. if err := renewCertsByComponent(cfg, component, certsRenewMgr); err != nil {
  193. return rollbackOldManifests(recoverManifests, errors.Wrapf(err, "failed to renew certificates for component %q", component), pathMgr, recoverEtcd)
  194. }
  195. }
  196. // Move the old manifest into the old-manifests directory
  197. if err := pathMgr.MoveFile(currentManifestPath, backupManifestPath); err != nil {
  198. return rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)
  199. }
  200. // Move the new manifest into the manifests directory
  201. if err := pathMgr.MoveFile(newManifestPath, currentManifestPath); err != nil {
  202. return rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)
  203. }
  204. fmt.Printf("[upgrade/staticpods] Moved new manifest to %q and backed up old manifest to %q\n", currentManifestPath, backupManifestPath)
  205. fmt.Println("[upgrade/staticpods] Waiting for the kubelet to restart the component")
  206. fmt.Printf("[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout %v)\n", UpgradeManifestTimeout)
  207. // Wait for the mirror Pod hash to change; otherwise we'll run into race conditions here when the kubelet hasn't had time to
  208. // notice the removal of the Static Pod, leading to a false positive below where we check that the API endpoint is healthy
  209. // If we don't do this, there is a case where we remove the Static Pod manifest, kubelet is slow to react, kubeadm checks the
  210. // API endpoint below of the OLD Static Pod component and proceeds quickly enough, which might lead to unexpected results.
  211. if err := waiter.WaitForStaticPodHashChange(cfg.NodeRegistration.Name, component, beforePodHash); err != nil {
  212. return rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)
  213. }
  214. // Wait for the static pod component to come up and register itself as a mirror pod
  215. if err := waiter.WaitForPodsWithLabel("component=" + component); err != nil {
  216. return rollbackOldManifests(recoverManifests, err, pathMgr, recoverEtcd)
  217. }
  218. fmt.Printf("[upgrade/staticpods] Component %q upgraded successfully!\n", component)
  219. return nil
  220. }
  221. // performEtcdStaticPodUpgrade performs upgrade of etcd, it returns bool which indicates fatal error or not and the actual error.
  222. func performEtcdStaticPodUpgrade(certsRenewMgr *renewal.Manager, client clientset.Interface, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, recoverManifests map[string]string, oldEtcdClient, newEtcdClient etcdutil.ClusterInterrogator) (bool, error) {
  223. // Add etcd static pod spec only if external etcd is not configured
  224. if cfg.Etcd.External != nil {
  225. return false, errors.New("external etcd detected, won't try to change any etcd state")
  226. }
  227. // Checking health state of etcd before proceeding with the upgrade
  228. err := oldEtcdClient.CheckClusterHealth()
  229. if err != nil {
  230. return true, errors.Wrap(err, "etcd cluster is not healthy")
  231. }
  232. // Backing up etcd data store
  233. backupEtcdDir := pathMgr.BackupEtcdDir()
  234. runningEtcdDir := cfg.Etcd.Local.DataDir
  235. if err := kubeadmutil.CopyDir(runningEtcdDir, backupEtcdDir); err != nil {
  236. return true, errors.Wrap(err, "failed to back up etcd data")
  237. }
  238. // Need to check currently used version and version from constants, if differs then upgrade
  239. desiredEtcdVersion, err := constants.EtcdSupportedVersion(cfg.KubernetesVersion)
  240. if err != nil {
  241. return true, errors.Wrap(err, "failed to retrieve an etcd version for the target Kubernetes version")
  242. }
  243. // gets the etcd version of the local/stacked etcd member running on the current machine
  244. currentEtcdVersions, err := oldEtcdClient.GetClusterVersions()
  245. if err != nil {
  246. return true, errors.Wrap(err, "failed to retrieve the current etcd version")
  247. }
  248. currentEtcdVersionStr, ok := currentEtcdVersions[etcdutil.GetClientURL(&cfg.LocalAPIEndpoint)]
  249. if !ok {
  250. return true, errors.Wrap(err, "failed to retrieve the current etcd version")
  251. }
  252. currentEtcdVersion, err := version.ParseSemantic(currentEtcdVersionStr)
  253. if err != nil {
  254. return true, errors.Wrapf(err, "failed to parse the current etcd version(%s)", currentEtcdVersionStr)
  255. }
  256. // Comparing current etcd version with desired to catch the same version or downgrade condition and fail on them.
  257. if desiredEtcdVersion.LessThan(currentEtcdVersion) {
  258. return false, errors.Errorf("the desired etcd version for this Kubernetes version %q is %q, but the current etcd version is %q. Won't downgrade etcd, instead just continue", cfg.KubernetesVersion, desiredEtcdVersion.String(), currentEtcdVersion.String())
  259. }
  260. // For the case when desired etcd version is the same as current etcd version
  261. if strings.Compare(desiredEtcdVersion.String(), currentEtcdVersion.String()) == 0 {
  262. return false, nil
  263. }
  264. beforeEtcdPodHash, err := waiter.WaitForStaticPodSingleHash(cfg.NodeRegistration.Name, constants.Etcd)
  265. if err != nil {
  266. return true, errors.Wrap(err, "failed to get etcd pod's hash")
  267. }
  268. // Write the updated etcd static Pod manifest into the temporary directory, at this point no etcd change
  269. // has occurred in any aspects.
  270. if err := etcdphase.CreateLocalEtcdStaticPodManifestFile(pathMgr.TempManifestDir(), pathMgr.KustomizeDir(), cfg.NodeRegistration.Name, &cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint); err != nil {
  271. return true, errors.Wrap(err, "error creating local etcd static pod manifest file")
  272. }
  273. retries := 10
  274. retryInterval := 15 * time.Second
  275. // Perform etcd upgrade using common to all control plane components function
  276. if err := upgradeComponent(constants.Etcd, certsRenewMgr, waiter, pathMgr, cfg, beforeEtcdPodHash, recoverManifests); err != nil {
  277. fmt.Printf("[upgrade/etcd] Failed to upgrade etcd: %v\n", err)
  278. // Since upgrade component failed, the old etcd manifest has either been restored or was never touched
  279. // Now we need to check the health of etcd cluster if it is up with old manifest
  280. fmt.Println("[upgrade/etcd] Waiting for previous etcd to become available")
  281. if _, err := oldEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {
  282. fmt.Printf("[upgrade/etcd] Failed to healthcheck previous etcd: %v\n", err)
  283. // At this point we know that etcd cluster is dead and it is safe to copy backup datastore and to rollback old etcd manifest
  284. fmt.Println("[upgrade/etcd] Rolling back etcd data")
  285. if err := rollbackEtcdData(cfg, pathMgr); err != nil {
  286. // Even copying back datastore failed, no options for recovery left, bailing out
  287. return true, errors.Errorf("fatal error rolling back local etcd cluster datadir: %v, the backup of etcd database is stored here:(%s)", err, backupEtcdDir)
  288. }
  289. fmt.Println("[upgrade/etcd] Etcd data rollback successful")
  290. // Now that we've rolled back the data, let's check if the cluster comes up
  291. fmt.Println("[upgrade/etcd] Waiting for previous etcd to become available")
  292. if _, err := oldEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {
  293. fmt.Printf("[upgrade/etcd] Failed to healthcheck previous etcd: %v\n", err)
  294. // Nothing else left to try to recover etcd cluster
  295. return true, errors.Wrapf(err, "fatal error rolling back local etcd cluster manifest, the backup of etcd database is stored here:(%s)", backupEtcdDir)
  296. }
  297. // We've recovered to the previous etcd from this case
  298. }
  299. fmt.Println("[upgrade/etcd] Etcd was rolled back and is now available")
  300. // Since etcd cluster came back up with the old manifest
  301. return true, errors.Wrap(err, "fatal error when trying to upgrade the etcd cluster, rolled the state back to pre-upgrade state")
  302. }
  303. // Initialize the new etcd client if it wasn't pre-initialized
  304. if newEtcdClient == nil {
  305. etcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)
  306. if err != nil {
  307. return true, errors.Wrap(err, "fatal error creating etcd client")
  308. }
  309. newEtcdClient = etcdClient
  310. }
  311. // Checking health state of etcd after the upgrade
  312. fmt.Println("[upgrade/etcd] Waiting for etcd to become available")
  313. if _, err = newEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {
  314. fmt.Printf("[upgrade/etcd] Failed to healthcheck etcd: %v\n", err)
  315. // Despite the fact that upgradeComponent was successful, there is something wrong with the etcd cluster
  316. // First step is to restore back up of datastore
  317. fmt.Println("[upgrade/etcd] Rolling back etcd data")
  318. if err := rollbackEtcdData(cfg, pathMgr); err != nil {
  319. // Even copying back datastore failed, no options for recovery left, bailing out
  320. return true, errors.Wrapf(err, "fatal error rolling back local etcd cluster datadir, the backup of etcd database is stored here:(%s)", backupEtcdDir)
  321. }
  322. fmt.Println("[upgrade/etcd] Etcd data rollback successful")
  323. // Old datastore has been copied, rolling back old manifests
  324. fmt.Println("[upgrade/etcd] Rolling back etcd manifest")
  325. rollbackOldManifests(recoverManifests, err, pathMgr, true)
  326. // rollbackOldManifests() always returns an error -- ignore it and continue
  327. // Assuming rollback of the old etcd manifest was successful, check the status of etcd cluster again
  328. fmt.Println("[upgrade/etcd] Waiting for previous etcd to become available")
  329. if _, err := oldEtcdClient.WaitForClusterAvailable(retries, retryInterval); err != nil {
  330. fmt.Printf("[upgrade/etcd] Failed to healthcheck previous etcd: %v\n", err)
  331. // Nothing else left to try to recover etcd cluster
  332. return true, errors.Wrapf(err, "fatal error rolling back local etcd cluster manifest, the backup of etcd database is stored here:(%s)", backupEtcdDir)
  333. }
  334. fmt.Println("[upgrade/etcd] Etcd was rolled back and is now available")
  335. // We've successfully rolled back etcd, and now return an error describing that the upgrade failed
  336. return true, errors.Wrap(err, "fatal error upgrading local etcd cluster, rolled the state back to pre-upgrade state")
  337. }
  338. return false, nil
  339. }
  340. // StaticPodControlPlane upgrades a static pod-hosted control plane
  341. func StaticPodControlPlane(client clientset.Interface, waiter apiclient.Waiter, pathMgr StaticPodPathManager, cfg *kubeadmapi.InitConfiguration, etcdUpgrade, renewCerts bool, oldEtcdClient, newEtcdClient etcdutil.ClusterInterrogator) error {
  342. recoverManifests := map[string]string{}
  343. var isExternalEtcd bool
  344. beforePodHashMap, err := waiter.WaitForStaticPodControlPlaneHashes(cfg.NodeRegistration.Name)
  345. if err != nil {
  346. return err
  347. }
  348. if oldEtcdClient == nil {
  349. if cfg.Etcd.External != nil {
  350. // External etcd
  351. isExternalEtcd = true
  352. etcdClient, err := etcdutil.New(
  353. cfg.Etcd.External.Endpoints,
  354. cfg.Etcd.External.CAFile,
  355. cfg.Etcd.External.CertFile,
  356. cfg.Etcd.External.KeyFile,
  357. )
  358. if err != nil {
  359. return errors.Wrap(err, "failed to create etcd client for external etcd")
  360. }
  361. oldEtcdClient = etcdClient
  362. // Since etcd is managed externally, the new etcd client will be the same as the old client
  363. if newEtcdClient == nil {
  364. newEtcdClient = etcdClient
  365. }
  366. } else {
  367. // etcd Static Pod
  368. etcdClient, err := etcdutil.NewFromCluster(client, cfg.CertificatesDir)
  369. if err != nil {
  370. return errors.Wrap(err, "failed to create etcd client")
  371. }
  372. oldEtcdClient = etcdClient
  373. }
  374. }
  375. var certsRenewMgr *renewal.Manager
  376. if renewCerts {
  377. certsRenewMgr, err = renewal.NewManager(&cfg.ClusterConfiguration, pathMgr.KubernetesDir())
  378. if err != nil {
  379. return errors.Wrap(err, "failed to create the certificate renewal manager")
  380. }
  381. }
  382. // etcd upgrade is done prior to other control plane components
  383. if !isExternalEtcd && etcdUpgrade {
  384. // set the TLS upgrade flag for all components
  385. fmt.Printf("[upgrade/etcd] Upgrading to TLS for %s\n", constants.Etcd)
  386. // Perform etcd upgrade using common to all control plane components function
  387. fatal, err := performEtcdStaticPodUpgrade(certsRenewMgr, client, waiter, pathMgr, cfg, recoverManifests, oldEtcdClient, newEtcdClient)
  388. if err != nil {
  389. if fatal {
  390. return err
  391. }
  392. fmt.Printf("[upgrade/etcd] Non fatal issue encountered during upgrade: %v\n", err)
  393. }
  394. }
  395. // Write the updated static Pod manifests into the temporary directory
  396. fmt.Printf("[upgrade/staticpods] Writing new Static Pod manifests to %q\n", pathMgr.TempManifestDir())
  397. err = controlplane.CreateInitStaticPodManifestFiles(pathMgr.TempManifestDir(), pathMgr.KustomizeDir(), cfg)
  398. if err != nil {
  399. return errors.Wrap(err, "error creating init static pod manifest files")
  400. }
  401. for _, component := range constants.ControlPlaneComponents {
  402. if err = upgradeComponent(component, certsRenewMgr, waiter, pathMgr, cfg, beforePodHashMap[component], recoverManifests); err != nil {
  403. return err
  404. }
  405. }
  406. if renewCerts {
  407. // renew the certificate embedded in the admin.conf file
  408. renewed, err := certsRenewMgr.RenewUsingLocalCA(constants.AdminKubeConfigFileName)
  409. if err != nil {
  410. return rollbackOldManifests(recoverManifests, errors.Wrapf(err, "failed to upgrade the %s certificates", constants.AdminKubeConfigFileName), pathMgr, false)
  411. }
  412. if !renewed {
  413. // if not error, but not renewed because of external CA detected, inform the user
  414. fmt.Printf("[upgrade/staticpods] External CA detected, %s certificate can't be renewed\n", constants.AdminKubeConfigFileName)
  415. }
  416. }
  417. // Remove the temporary directories used on a best-effort (don't fail if the calls error out)
  418. // The calls are set here by design; we should _not_ use "defer" above as that would remove the directories
  419. // even in the "fail and rollback" case, where we want the directories preserved for the user.
  420. return pathMgr.CleanupDirs()
  421. }
  422. // rollbackOldManifests rolls back the backed-up manifests if something went wrong.
  423. // It always returns an error to the caller.
  424. func rollbackOldManifests(oldManifests map[string]string, origErr error, pathMgr StaticPodPathManager, restoreEtcd bool) error {
  425. errs := []error{origErr}
  426. for component, backupPath := range oldManifests {
  427. // Will restore etcd manifest only if it was explicitly requested by setting restoreEtcd to True
  428. if component == constants.Etcd && !restoreEtcd {
  429. continue
  430. }
  431. // Where we should put back the backed up manifest
  432. realManifestPath := pathMgr.RealManifestPath(component)
  433. // Move the backup manifest back into the manifests directory
  434. err := pathMgr.MoveFile(backupPath, realManifestPath)
  435. if err != nil {
  436. errs = append(errs, err)
  437. }
  438. }
  439. // Let the user know there were problems, but we tried to recover
  440. return errors.Wrap(utilerrors.NewAggregate(errs),
  441. "couldn't upgrade control plane. kubeadm has tried to recover everything into the earlier state. Errors faced")
  442. }
  443. // rollbackEtcdData rolls back the content of etcd folder if something went wrong.
  444. // When the folder contents are successfully rolled back, nil is returned, otherwise an error is returned.
  445. func rollbackEtcdData(cfg *kubeadmapi.InitConfiguration, pathMgr StaticPodPathManager) error {
  446. backupEtcdDir := pathMgr.BackupEtcdDir()
  447. runningEtcdDir := cfg.Etcd.Local.DataDir
  448. if err := kubeadmutil.CopyDir(backupEtcdDir, runningEtcdDir); err != nil {
  449. // Let the user know there we're problems, but we tried to reçover
  450. return errors.Wrapf(err, "couldn't recover etcd database with error, the location of etcd backup: %s ", backupEtcdDir)
  451. }
  452. return nil
  453. }
  454. // renewCertsByComponent takes charge of renewing certificates used by a specific component before
  455. // the static pod of the component is upgraded
  456. func renewCertsByComponent(cfg *kubeadmapi.InitConfiguration, component string, certsRenewMgr *renewal.Manager) error {
  457. var certificates []string
  458. // if etcd, only in case of local etcd, renew server, peer and health check certificate
  459. if component == constants.Etcd {
  460. if cfg.Etcd.Local != nil {
  461. certificates = []string{
  462. certsphase.KubeadmCertEtcdServer.Name,
  463. certsphase.KubeadmCertEtcdPeer.Name,
  464. certsphase.KubeadmCertEtcdHealthcheck.Name,
  465. }
  466. }
  467. }
  468. // if apiserver, renew apiserver serving certificate, kubelet and front-proxy client certificate.
  469. //if local etcd, renew also the etcd client certificate
  470. if component == constants.KubeAPIServer {
  471. certificates = []string{
  472. certsphase.KubeadmCertAPIServer.Name,
  473. certsphase.KubeadmCertKubeletClient.Name,
  474. certsphase.KubeadmCertFrontProxyClient.Name,
  475. }
  476. if cfg.Etcd.Local != nil {
  477. certificates = append(certificates, certsphase.KubeadmCertEtcdAPIClient.Name)
  478. }
  479. }
  480. // if controller-manager, renew the certificate embedded in the controller-manager kubeConfig file
  481. if component == constants.KubeControllerManager {
  482. certificates = []string{
  483. constants.ControllerManagerKubeConfigFileName,
  484. }
  485. }
  486. // if scheduler, renew the certificate embedded in the scheduler kubeConfig file
  487. if component == constants.KubeScheduler {
  488. certificates = []string{
  489. constants.SchedulerKubeConfigFileName,
  490. }
  491. }
  492. // renew the selected components
  493. for _, cert := range certificates {
  494. fmt.Printf("[upgrade/staticpods] Renewing %s certificate\n", cert)
  495. renewed, err := certsRenewMgr.RenewUsingLocalCA(cert)
  496. if err != nil {
  497. return err
  498. }
  499. if !renewed {
  500. // if not error, but not renewed because of external CA detected, inform the user
  501. fmt.Printf("[upgrade/staticpods] External CA detected, %s certificate can't be renewed\n", cert)
  502. }
  503. }
  504. return nil
  505. }
  506. // GetPathManagerForUpgrade returns a path manager properly configured for the given InitConfiguration.
  507. func GetPathManagerForUpgrade(kubernetesDir, kustomizeDir string, internalcfg *kubeadmapi.InitConfiguration, etcdUpgrade bool) (StaticPodPathManager, error) {
  508. isExternalEtcd := internalcfg.Etcd.External != nil
  509. return NewKubeStaticPodPathManagerUsingTempDirs(kubernetesDir, kustomizeDir, true, etcdUpgrade && !isExternalEtcd)
  510. }
  511. // PerformStaticPodUpgrade performs the upgrade of the control plane components for a static pod hosted cluster
  512. func PerformStaticPodUpgrade(client clientset.Interface, waiter apiclient.Waiter, internalcfg *kubeadmapi.InitConfiguration, etcdUpgrade, renewCerts bool, kustomizeDir string) error {
  513. pathManager, err := GetPathManagerForUpgrade(constants.KubernetesDir, kustomizeDir, internalcfg, etcdUpgrade)
  514. if err != nil {
  515. return err
  516. }
  517. // The arguments oldEtcdClient and newEtdClient, are uninitialized because passing in the clients allow for mocking the client during testing
  518. return StaticPodControlPlane(client, waiter, pathManager, internalcfg, etcdUpgrade, renewCerts, nil, nil)
  519. }
  520. // DryRunStaticPodUpgrade fakes an upgrade of the control plane
  521. func DryRunStaticPodUpgrade(kustomizeDir string, internalcfg *kubeadmapi.InitConfiguration) error {
  522. dryRunManifestDir, err := constants.CreateTempDirForKubeadm("", "kubeadm-upgrade-dryrun")
  523. if err != nil {
  524. return err
  525. }
  526. defer os.RemoveAll(dryRunManifestDir)
  527. if err := controlplane.CreateInitStaticPodManifestFiles(dryRunManifestDir, kustomizeDir, internalcfg); err != nil {
  528. return err
  529. }
  530. // Print the contents of the upgraded manifests and pretend like they were in /etc/kubernetes/manifests
  531. files := []dryrunutil.FileToPrint{}
  532. for _, component := range constants.ControlPlaneComponents {
  533. realPath := constants.GetStaticPodFilepath(component, dryRunManifestDir)
  534. outputPath := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory())
  535. files = append(files, dryrunutil.NewFileToPrint(realPath, outputPath))
  536. }
  537. return dryrunutil.PrintDryRunFiles(files, os.Stdout)
  538. }