health.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. "fmt"
  17. "os"
  18. "time"
  19. "github.com/pkg/errors"
  20. apps "k8s.io/api/apps/v1"
  21. batchv1 "k8s.io/api/batch/v1"
  22. v1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/labels"
  25. "k8s.io/apimachinery/pkg/util/sets"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. clientset "k8s.io/client-go/kubernetes"
  28. "k8s.io/klog"
  29. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  30. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  31. "k8s.io/kubernetes/cmd/kubeadm/app/images"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/preflight"
  33. utilpointer "k8s.io/utils/pointer"
  34. )
  35. // healthCheck is a helper struct for easily performing healthchecks against the cluster and printing the output
  36. type healthCheck struct {
  37. name string
  38. client clientset.Interface
  39. cfg *kubeadmapi.ClusterConfiguration
  40. // f is invoked with a k8s client and a kubeadm ClusterConfiguration passed to it. Should return an optional error
  41. f func(clientset.Interface, *kubeadmapi.ClusterConfiguration) error
  42. }
  43. // Check is part of the preflight.Checker interface
  44. func (c *healthCheck) Check() (warnings, errors []error) {
  45. if err := c.f(c.client, c.cfg); err != nil {
  46. return nil, []error{err}
  47. }
  48. return nil, nil
  49. }
  50. // Name is part of the preflight.Checker interface
  51. func (c *healthCheck) Name() string {
  52. return c.name
  53. }
  54. // CheckClusterHealth makes sure:
  55. // - the API /healthz endpoint is healthy
  56. // - all control-plane Nodes are Ready
  57. // - (if self-hosted) that there are DaemonSets with at least one Pod for all control plane components
  58. // - (if static pod-hosted) that all required Static Pod manifests exist on disk
  59. func CheckClusterHealth(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration, ignoreChecksErrors sets.String) error {
  60. fmt.Println("[upgrade] Running cluster health checks")
  61. healthChecks := []preflight.Checker{
  62. &healthCheck{
  63. name: "CreateJob",
  64. client: client,
  65. cfg: cfg,
  66. f: createJob,
  67. },
  68. &healthCheck{
  69. name: "ControlPlaneNodesReady",
  70. client: client,
  71. f: controlPlaneNodesReady,
  72. },
  73. &healthCheck{
  74. name: "StaticPodManifest",
  75. client: client,
  76. cfg: cfg,
  77. f: staticPodManifestHealth,
  78. },
  79. }
  80. return preflight.RunChecks(healthChecks, os.Stderr, ignoreChecksErrors)
  81. }
  82. // CreateJob is a check that verifies that a Job can be created in the cluster
  83. func createJob(client clientset.Interface, cfg *kubeadmapi.ClusterConfiguration) (lastError error) {
  84. const (
  85. jobName = "upgrade-health-check"
  86. ns = metav1.NamespaceSystem
  87. timeout = 15 * time.Second
  88. )
  89. // If client.Discovery().RESTClient() is nil, the fake client is used.
  90. // Return early because the kubeadm dryrun dynamic client only handles the core/v1 GroupVersion.
  91. if client.Discovery().RESTClient() == nil {
  92. fmt.Printf("[dryrun] Would create the Job %q in namespace %q and wait until it completes\n", jobName, ns)
  93. return nil
  94. }
  95. // Prepare Job
  96. job := &batchv1.Job{
  97. ObjectMeta: metav1.ObjectMeta{
  98. Name: jobName,
  99. Namespace: ns,
  100. },
  101. Spec: batchv1.JobSpec{
  102. BackoffLimit: utilpointer.Int32Ptr(0),
  103. Template: v1.PodTemplateSpec{
  104. Spec: v1.PodSpec{
  105. RestartPolicy: v1.RestartPolicyNever,
  106. SecurityContext: &v1.PodSecurityContext{
  107. RunAsUser: utilpointer.Int64Ptr(999),
  108. RunAsGroup: utilpointer.Int64Ptr(999),
  109. RunAsNonRoot: utilpointer.BoolPtr(true),
  110. },
  111. Tolerations: []v1.Toleration{
  112. {
  113. Key: "node-role.kubernetes.io/master",
  114. Effect: v1.TaintEffectNoSchedule,
  115. },
  116. },
  117. Containers: []v1.Container{
  118. {
  119. Name: jobName,
  120. Image: images.GetPauseImage(cfg),
  121. Args: []string{"-v"},
  122. },
  123. },
  124. },
  125. },
  126. },
  127. }
  128. // Check if the Job already exists and delete it
  129. if _, err := client.BatchV1().Jobs(ns).Get(context.TODO(), jobName, metav1.GetOptions{}); err == nil {
  130. if err = deleteHealthCheckJob(client, ns, jobName); err != nil {
  131. return err
  132. }
  133. }
  134. // Cleanup the Job on exit
  135. defer func() {
  136. lastError = deleteHealthCheckJob(client, ns, jobName)
  137. }()
  138. // Create the Job, but retry in case it is being currently deleted
  139. klog.V(2).Infof("Creating Job %q in the namespace %q", jobName, ns)
  140. err := wait.PollImmediate(time.Second*1, timeout, func() (bool, error) {
  141. if _, err := client.BatchV1().Jobs(ns).Create(context.TODO(), job, metav1.CreateOptions{}); err != nil {
  142. klog.V(2).Infof("Could not create Job %q in the namespace %q, retrying: %v", jobName, ns, err)
  143. lastError = err
  144. return false, nil
  145. }
  146. return true, nil
  147. })
  148. if err != nil {
  149. return errors.Wrapf(lastError, "could not create Job %q in the namespace %q", jobName, ns)
  150. }
  151. // Waiting and manually deleteing the Job is a workaround to not enabling the TTL controller.
  152. // TODO: refactor this if the TTL controller is enabled in kubeadm once it goes Beta.
  153. // Wait for the Job to complete
  154. err = wait.PollImmediate(time.Second*1, timeout, func() (bool, error) {
  155. job, err := client.BatchV1().Jobs(ns).Get(context.TODO(), jobName, metav1.GetOptions{})
  156. if err != nil {
  157. lastError = err
  158. klog.V(2).Infof("could not get Job %q in the namespace %q, retrying: %v", jobName, ns, err)
  159. return false, nil
  160. }
  161. for _, cond := range job.Status.Conditions {
  162. if cond.Type == batchv1.JobComplete {
  163. return true, nil
  164. }
  165. }
  166. lastError = errors.Errorf("no condition of type %v", batchv1.JobComplete)
  167. klog.V(2).Infof("Job %q in the namespace %q is not yet complete, retrying", jobName, ns)
  168. return false, nil
  169. })
  170. if err != nil {
  171. return errors.Wrapf(lastError, "Job %q in the namespace %q did not complete in %v", jobName, ns, timeout)
  172. }
  173. klog.V(2).Infof("Job %q in the namespace %q completed", jobName, ns)
  174. return nil
  175. }
  176. func deleteHealthCheckJob(client clientset.Interface, ns, jobName string) error {
  177. klog.V(2).Infof("Deleting Job %q in the namespace %q", jobName, ns)
  178. propagation := metav1.DeletePropagationForeground
  179. deleteOptions := &metav1.DeleteOptions{
  180. PropagationPolicy: &propagation,
  181. }
  182. if err := client.BatchV1().Jobs(ns).Delete(context.TODO(), jobName, deleteOptions); err != nil {
  183. return errors.Wrapf(err, "could not delete Job %q in the namespace %q", jobName, ns)
  184. }
  185. return nil
  186. }
  187. // controlPlaneNodesReady checks whether all control-plane Nodes in the cluster are in the Running state
  188. func controlPlaneNodesReady(client clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error {
  189. selector := labels.SelectorFromSet(labels.Set(map[string]string{
  190. constants.LabelNodeRoleMaster: "",
  191. }))
  192. controlPlanes, err := client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{
  193. LabelSelector: selector.String(),
  194. })
  195. if err != nil {
  196. return errors.Wrap(err, "couldn't list control-planes in cluster")
  197. }
  198. if len(controlPlanes.Items) == 0 {
  199. return errors.New("failed to find any nodes with a control-plane role")
  200. }
  201. notReadyControlPlanes := getNotReadyNodes(controlPlanes.Items)
  202. if len(notReadyControlPlanes) != 0 {
  203. return errors.Errorf("there are NotReady control-planes in the cluster: %v", notReadyControlPlanes)
  204. }
  205. return nil
  206. }
  207. // staticPodManifestHealth makes sure the required static pods are presents
  208. func staticPodManifestHealth(_ clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error {
  209. nonExistentManifests := []string{}
  210. for _, component := range constants.ControlPlaneComponents {
  211. manifestFile := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory())
  212. if _, err := os.Stat(manifestFile); os.IsNotExist(err) {
  213. nonExistentManifests = append(nonExistentManifests, manifestFile)
  214. }
  215. }
  216. if len(nonExistentManifests) == 0 {
  217. return nil
  218. }
  219. return errors.Errorf("The control plane seems to be Static Pod-hosted, but some of the manifests don't seem to exist on disk. This probably means you're running 'kubeadm upgrade' on a remote machine, which is not supported for a Static Pod-hosted cluster. Manifest files not found: %v", nonExistentManifests)
  220. }
  221. // IsControlPlaneSelfHosted returns whether the control plane is self hosted or not
  222. func IsControlPlaneSelfHosted(client clientset.Interface) bool {
  223. notReadyDaemonSets, err := getNotReadyDaemonSets(client)
  224. if err != nil {
  225. return false
  226. }
  227. // If there are no NotReady DaemonSets, we are using selfhosting
  228. return len(notReadyDaemonSets) == 0
  229. }
  230. // getNotReadyDaemonSets gets the amount of Ready control plane DaemonSets
  231. func getNotReadyDaemonSets(client clientset.Interface) ([]error, error) {
  232. notReadyDaemonSets := []error{}
  233. for _, component := range constants.ControlPlaneComponents {
  234. dsName := constants.AddSelfHostedPrefix(component)
  235. ds, err := client.AppsV1().DaemonSets(metav1.NamespaceSystem).Get(context.TODO(), dsName, metav1.GetOptions{})
  236. if err != nil {
  237. return nil, errors.Errorf("couldn't get daemonset %q in the %s namespace", dsName, metav1.NamespaceSystem)
  238. }
  239. if err := daemonSetHealth(&ds.Status); err != nil {
  240. notReadyDaemonSets = append(notReadyDaemonSets, errors.Wrapf(err, "DaemonSet %q not healthy", dsName))
  241. }
  242. }
  243. return notReadyDaemonSets, nil
  244. }
  245. // daemonSetHealth is a helper function for getting the health of a DaemonSet's status
  246. func daemonSetHealth(dsStatus *apps.DaemonSetStatus) error {
  247. if dsStatus.CurrentNumberScheduled != dsStatus.DesiredNumberScheduled {
  248. return errors.Errorf("current number of scheduled Pods ('%d') doesn't match the amount of desired Pods ('%d')",
  249. dsStatus.CurrentNumberScheduled, dsStatus.DesiredNumberScheduled)
  250. }
  251. if dsStatus.NumberAvailable == 0 {
  252. return errors.New("no available Pods for DaemonSet")
  253. }
  254. if dsStatus.NumberReady == 0 {
  255. return errors.New("no ready Pods for DaemonSet")
  256. }
  257. return nil
  258. }
  259. // getNotReadyNodes returns a string slice of nodes in the cluster that are NotReady
  260. func getNotReadyNodes(nodes []v1.Node) []string {
  261. notReadyNodes := []string{}
  262. for _, node := range nodes {
  263. for _, condition := range node.Status.Conditions {
  264. if condition.Type == v1.NodeReady && condition.Status != v1.ConditionTrue {
  265. notReadyNodes = append(notReadyNodes, node.ObjectMeta.Name)
  266. }
  267. }
  268. }
  269. return notReadyNodes
  270. }