health.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. "net/http"
  17. "os"
  18. "github.com/pkg/errors"
  19. apps "k8s.io/api/apps/v1"
  20. "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/labels"
  23. "k8s.io/apimachinery/pkg/util/sets"
  24. clientset "k8s.io/client-go/kubernetes"
  25. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  26. "k8s.io/kubernetes/cmd/kubeadm/app/preflight"
  27. )
  28. // healthCheck is a helper struct for easily performing healthchecks against the cluster and printing the output
  29. type healthCheck struct {
  30. name string
  31. client clientset.Interface
  32. // f is invoked with a k8s client passed to it. Should return an optional error
  33. f func(clientset.Interface) error
  34. }
  35. // Check is part of the preflight.Checker interface
  36. func (c *healthCheck) Check() (warnings, errors []error) {
  37. if err := c.f(c.client); err != nil {
  38. return nil, []error{err}
  39. }
  40. return nil, nil
  41. }
  42. // Name is part of the preflight.Checker interface
  43. func (c *healthCheck) Name() string {
  44. return c.name
  45. }
  46. // CheckClusterHealth makes sure:
  47. // - the API /healthz endpoint is healthy
  48. // - all control-plane Nodes are Ready
  49. // - (if self-hosted) that there are DaemonSets with at least one Pod for all control plane components
  50. // - (if static pod-hosted) that all required Static Pod manifests exist on disk
  51. func CheckClusterHealth(client clientset.Interface, ignoreChecksErrors sets.String) error {
  52. fmt.Println("[upgrade] Making sure the cluster is healthy:")
  53. healthChecks := []preflight.Checker{
  54. &healthCheck{
  55. name: "APIServerHealth",
  56. client: client,
  57. f: apiServerHealthy,
  58. },
  59. &healthCheck{
  60. name: "ControlPlaneNodesReady",
  61. client: client,
  62. f: controlPlaneNodesReady,
  63. },
  64. // TODO: Add a check for ComponentStatuses here?
  65. }
  66. healthChecks = append(healthChecks, &healthCheck{
  67. name: "StaticPodManifest",
  68. client: client,
  69. f: staticPodManifestHealth,
  70. })
  71. return preflight.RunChecks(healthChecks, os.Stderr, ignoreChecksErrors)
  72. }
  73. // apiServerHealthy checks whether the API server's /healthz endpoint is healthy
  74. func apiServerHealthy(client clientset.Interface) error {
  75. healthStatus := 0
  76. // If client.Discovery().RESTClient() is nil, the fake client is used, and that means we are dry-running. Just proceed
  77. if client.Discovery().RESTClient() == nil {
  78. return nil
  79. }
  80. client.Discovery().RESTClient().Get().AbsPath("/healthz").Do().StatusCode(&healthStatus)
  81. if healthStatus != http.StatusOK {
  82. return errors.Errorf("the API Server is unhealthy; /healthz didn't return %q", "ok")
  83. }
  84. return nil
  85. }
  86. // controlPlaneNodesReady checks whether all control-plane Nodes in the cluster are in the Running state
  87. func controlPlaneNodesReady(client clientset.Interface) error {
  88. selector := labels.SelectorFromSet(labels.Set(map[string]string{
  89. constants.LabelNodeRoleMaster: "",
  90. }))
  91. controlPlanes, err := client.CoreV1().Nodes().List(metav1.ListOptions{
  92. LabelSelector: selector.String(),
  93. })
  94. if err != nil {
  95. return errors.Wrap(err, "couldn't list control-planes in cluster")
  96. }
  97. if len(controlPlanes.Items) == 0 {
  98. return errors.New("failed to find any nodes with a control-plane role")
  99. }
  100. notReadyControlPlanes := getNotReadyNodes(controlPlanes.Items)
  101. if len(notReadyControlPlanes) != 0 {
  102. return errors.Errorf("there are NotReady control-planes in the cluster: %v", notReadyControlPlanes)
  103. }
  104. return nil
  105. }
  106. // staticPodManifestHealth makes sure the required static pods are presents
  107. func staticPodManifestHealth(_ clientset.Interface) error {
  108. nonExistentManifests := []string{}
  109. for _, component := range constants.ControlPlaneComponents {
  110. manifestFile := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory())
  111. if _, err := os.Stat(manifestFile); os.IsNotExist(err) {
  112. nonExistentManifests = append(nonExistentManifests, manifestFile)
  113. }
  114. }
  115. if len(nonExistentManifests) == 0 {
  116. return nil
  117. }
  118. 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)
  119. }
  120. // IsControlPlaneSelfHosted returns whether the control plane is self hosted or not
  121. func IsControlPlaneSelfHosted(client clientset.Interface) bool {
  122. notReadyDaemonSets, err := getNotReadyDaemonSets(client)
  123. if err != nil {
  124. return false
  125. }
  126. // If there are no NotReady DaemonSets, we are using selfhosting
  127. return len(notReadyDaemonSets) == 0
  128. }
  129. // getNotReadyDaemonSets gets the amount of Ready control plane DaemonSets
  130. func getNotReadyDaemonSets(client clientset.Interface) ([]error, error) {
  131. notReadyDaemonSets := []error{}
  132. for _, component := range constants.ControlPlaneComponents {
  133. dsName := constants.AddSelfHostedPrefix(component)
  134. ds, err := client.AppsV1().DaemonSets(metav1.NamespaceSystem).Get(dsName, metav1.GetOptions{})
  135. if err != nil {
  136. return nil, errors.Errorf("couldn't get daemonset %q in the %s namespace", dsName, metav1.NamespaceSystem)
  137. }
  138. if err := daemonSetHealth(&ds.Status); err != nil {
  139. notReadyDaemonSets = append(notReadyDaemonSets, errors.Wrapf(err, "DaemonSet %q not healthy", dsName))
  140. }
  141. }
  142. return notReadyDaemonSets, nil
  143. }
  144. // daemonSetHealth is a helper function for getting the health of a DaemonSet's status
  145. func daemonSetHealth(dsStatus *apps.DaemonSetStatus) error {
  146. if dsStatus.CurrentNumberScheduled != dsStatus.DesiredNumberScheduled {
  147. return errors.Errorf("current number of scheduled Pods ('%d') doesn't match the amount of desired Pods ('%d')",
  148. dsStatus.CurrentNumberScheduled, dsStatus.DesiredNumberScheduled)
  149. }
  150. if dsStatus.NumberAvailable == 0 {
  151. return errors.New("no available Pods for DaemonSet")
  152. }
  153. if dsStatus.NumberReady == 0 {
  154. return errors.New("no ready Pods for DaemonSet")
  155. }
  156. return nil
  157. }
  158. // getNotReadyNodes returns a string slice of nodes in the cluster that are NotReady
  159. func getNotReadyNodes(nodes []v1.Node) []string {
  160. notReadyNodes := []string{}
  161. for _, node := range nodes {
  162. for _, condition := range node.Status.Conditions {
  163. if condition.Type == v1.NodeReady && condition.Status != v1.ConditionTrue {
  164. notReadyNodes = append(notReadyNodes, node.ObjectMeta.Name)
  165. }
  166. }
  167. }
  168. return notReadyNodes
  169. }