staticpods.go 28 KB

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