cluster.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. Copyright 2018 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 config
  14. import (
  15. "context"
  16. "crypto/x509"
  17. "fmt"
  18. "io"
  19. "path/filepath"
  20. "strings"
  21. "github.com/pkg/errors"
  22. apierrors "k8s.io/apimachinery/pkg/api/errors"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/runtime"
  25. errorsutil "k8s.io/apimachinery/pkg/util/errors"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. clientset "k8s.io/client-go/kubernetes"
  28. "k8s.io/client-go/tools/clientcmd"
  29. certutil "k8s.io/client-go/util/cert"
  30. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  31. kubeadmscheme "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/componentconfigs"
  33. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  34. "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
  35. )
  36. // unretriableError is an error used temporarily while we are migrating from the
  37. // ClusterStatus struct to an annotation Pod based information. When performing
  38. // the upgrade of all control plane nodes with `kubeadm upgrade apply` and
  39. // `kubeadm upgrade node` we don't want to retry as if we were hitting connectivity
  40. // issues when the pod annotation is missing on the API server pods. This error will
  41. // be used in such scenario, for failing fast, and falling back to the ClusterStatus
  42. // retrieval in those cases.
  43. type unretriableError struct {
  44. err error
  45. }
  46. func newUnretriableError(err error) *unretriableError {
  47. return &unretriableError{err: err}
  48. }
  49. func (ue *unretriableError) Error() string {
  50. return fmt.Sprintf("unretriable error: %s", ue.err.Error())
  51. }
  52. // FetchInitConfigurationFromCluster fetches configuration from a ConfigMap in the cluster
  53. func FetchInitConfigurationFromCluster(client clientset.Interface, w io.Writer, logPrefix string, newControlPlane bool) (*kubeadmapi.InitConfiguration, error) {
  54. fmt.Fprintf(w, "[%s] Reading configuration from the cluster...\n", logPrefix)
  55. fmt.Fprintf(w, "[%s] FYI: You can look at this config file with 'kubectl -n %s get cm %s -oyaml'\n", logPrefix, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)
  56. // Fetch the actual config from cluster
  57. cfg, err := getInitConfigurationFromCluster(constants.KubernetesDir, client, newControlPlane)
  58. if err != nil {
  59. return nil, err
  60. }
  61. // Apply dynamic defaults
  62. if err := SetInitDynamicDefaults(cfg); err != nil {
  63. return nil, err
  64. }
  65. return cfg, nil
  66. }
  67. // getInitConfigurationFromCluster is separate only for testing purposes, don't call it directly, use FetchInitConfigurationFromCluster instead
  68. func getInitConfigurationFromCluster(kubeconfigDir string, client clientset.Interface, newControlPlane bool) (*kubeadmapi.InitConfiguration, error) {
  69. // Also, the config map really should be KubeadmConfigConfigMap...
  70. configMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)
  71. if err != nil {
  72. return nil, errors.Wrap(err, "failed to get config map")
  73. }
  74. // InitConfiguration is composed with data from different places
  75. initcfg := &kubeadmapi.InitConfiguration{}
  76. // gets ClusterConfiguration from kubeadm-config
  77. clusterConfigurationData, ok := configMap.Data[constants.ClusterConfigurationConfigMapKey]
  78. if !ok {
  79. return nil, errors.Errorf("unexpected error when reading kubeadm-config ConfigMap: %s key value pair missing", constants.ClusterConfigurationConfigMapKey)
  80. }
  81. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), []byte(clusterConfigurationData), &initcfg.ClusterConfiguration); err != nil {
  82. return nil, errors.Wrap(err, "failed to decode cluster configuration data")
  83. }
  84. // gets the component configs from the corresponding config maps
  85. if err := componentconfigs.FetchFromCluster(&initcfg.ClusterConfiguration, client); err != nil {
  86. return nil, errors.Wrap(err, "failed to get component configs")
  87. }
  88. // if this isn't a new controlplane instance (e.g. in case of kubeadm upgrades)
  89. // get nodes specific information as well
  90. if !newControlPlane {
  91. // gets the nodeRegistration for the current from the node object
  92. if err := getNodeRegistration(kubeconfigDir, client, &initcfg.NodeRegistration); err != nil {
  93. return nil, errors.Wrap(err, "failed to get node registration")
  94. }
  95. // gets the APIEndpoint for the current node
  96. if err := getAPIEndpoint(client, initcfg.NodeRegistration.Name, &initcfg.LocalAPIEndpoint); err != nil {
  97. return nil, errors.Wrap(err, "failed to getAPIEndpoint")
  98. }
  99. } else {
  100. // In the case where newControlPlane is true we don't go through getNodeRegistration() and initcfg.NodeRegistration.CRISocket is empty.
  101. // This forces DetectCRISocket() to be called later on, and if there is more than one CRI installed on the system, it will error out,
  102. // while asking for the user to provide an override for the CRI socket. Even if the user provides an override, the call to
  103. // DetectCRISocket() can happen too early and thus ignore it (while still erroring out).
  104. // However, if newControlPlane == true, initcfg.NodeRegistration is not used at all and it's overwritten later on.
  105. // Thus it's necessary to supply some default value, that will avoid the call to DetectCRISocket() and as
  106. // initcfg.NodeRegistration is discarded, setting whatever value here is harmless.
  107. initcfg.NodeRegistration.CRISocket = constants.DefaultDockerCRISocket
  108. }
  109. return initcfg, nil
  110. }
  111. // getNodeRegistration returns the nodeRegistration for the current node
  112. func getNodeRegistration(kubeconfigDir string, client clientset.Interface, nodeRegistration *kubeadmapi.NodeRegistrationOptions) error {
  113. // gets the name of the current node
  114. nodeName, err := getNodeNameFromKubeletConfig(kubeconfigDir)
  115. if err != nil {
  116. return errors.Wrap(err, "failed to get node name from kubelet config")
  117. }
  118. // gets the corresponding node and retrieves attributes stored there.
  119. node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
  120. if err != nil {
  121. return errors.Wrap(err, "failed to get corresponding node")
  122. }
  123. criSocket, ok := node.ObjectMeta.Annotations[constants.AnnotationKubeadmCRISocket]
  124. if !ok {
  125. return errors.Errorf("node %s doesn't have %s annotation", nodeName, constants.AnnotationKubeadmCRISocket)
  126. }
  127. // returns the nodeRegistration attributes
  128. nodeRegistration.Name = nodeName
  129. nodeRegistration.CRISocket = criSocket
  130. nodeRegistration.Taints = node.Spec.Taints
  131. // NB. currently nodeRegistration.KubeletExtraArgs isn't stored at node level but only in the kubeadm-flags.env
  132. // that isn't modified during upgrades
  133. // in future we might reconsider this thus enabling changes to the kubeadm-flags.env during upgrades as well
  134. return nil
  135. }
  136. // getNodeNameFromKubeletConfig gets the node name from a kubelet config file
  137. // TODO: in future we want to switch to a more canonical way for doing this e.g. by having this
  138. // information in the local kubelet config.yaml
  139. func getNodeNameFromKubeletConfig(kubeconfigDir string) (string, error) {
  140. // loads the kubelet.conf file
  141. fileName := filepath.Join(kubeconfigDir, constants.KubeletKubeConfigFileName)
  142. config, err := clientcmd.LoadFromFile(fileName)
  143. if err != nil {
  144. return "", err
  145. }
  146. // gets the info about the current user
  147. currentContext, exists := config.Contexts[config.CurrentContext]
  148. if !exists {
  149. return "", errors.Errorf("invalid kubeconfig file %s: missing context %s", fileName, config.CurrentContext)
  150. }
  151. authInfo, exists := config.AuthInfos[currentContext.AuthInfo]
  152. if !exists {
  153. return "", errors.Errorf("invalid kubeconfig file %s: missing AuthInfo %s", fileName, currentContext.AuthInfo)
  154. }
  155. // gets the X509 certificate with current user credentials
  156. var certs []*x509.Certificate
  157. if len(authInfo.ClientCertificateData) > 0 {
  158. // if the config file uses an embedded x509 certificate (e.g. kubelet.conf created by kubeadm), parse it
  159. if certs, err = certutil.ParseCertsPEM(authInfo.ClientCertificateData); err != nil {
  160. return "", err
  161. }
  162. } else if len(authInfo.ClientCertificate) > 0 {
  163. // if the config file links an external x509 certificate (e.g. kubelet.conf created by TLS bootstrap), load it
  164. if certs, err = certutil.CertsFromFile(authInfo.ClientCertificate); err != nil {
  165. return "", err
  166. }
  167. } else {
  168. return "", errors.Errorf("invalid kubeconfig file %s. x509 certificate expected", fileName)
  169. }
  170. // We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
  171. // TODO: Support multiple certs here in order to be able to rotate certs
  172. cert := certs[0]
  173. // gets the node name from the certificate common name
  174. return strings.TrimPrefix(cert.Subject.CommonName, constants.NodesUserPrefix), nil
  175. }
  176. func getAPIEndpoint(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint) error {
  177. return getAPIEndpointWithBackoff(client, nodeName, apiEndpoint, constants.StaticPodMirroringDefaultRetry)
  178. }
  179. func getAPIEndpointWithBackoff(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint, backoff wait.Backoff) error {
  180. var err error
  181. var errs []error
  182. if err = getAPIEndpointFromPodAnnotation(client, nodeName, apiEndpoint, backoff); err == nil {
  183. return nil
  184. }
  185. errs = append(errs, errors.WithMessagef(err, "could not retrieve API endpoints for node %q using pod annotations", nodeName))
  186. // NB: this is a fallback when there is no annotation found in the API server pod that contains
  187. // the API endpoint, and so we fallback to reading the ClusterStatus struct present in the
  188. // kubeadm-config ConfigMap. This can happen for example, when performing the first
  189. // `kubeadm upgrade apply` and `kubeadm upgrade node` cycle on the whole cluster. This logic
  190. // will be removed when the cluster status struct is removed from the kubeadm-config ConfigMap.
  191. if err = getAPIEndpointFromClusterStatus(client, nodeName, apiEndpoint); err == nil {
  192. return nil
  193. }
  194. errs = append(errs, errors.WithMessagef(err, "could not retrieve API endpoints for node %q using cluster status", nodeName))
  195. return errorsutil.NewAggregate(errs)
  196. }
  197. func getAPIEndpointFromPodAnnotation(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint, backoff wait.Backoff) error {
  198. var rawAPIEndpoint string
  199. var lastErr error
  200. // Let's tolerate some unexpected transient failures from the API server or load balancers. Also, if
  201. // static pods were not yet mirrored into the API server we want to wait for this propagation.
  202. err := wait.ExponentialBackoff(backoff, func() (bool, error) {
  203. rawAPIEndpoint, lastErr = getRawAPIEndpointFromPodAnnotationWithoutRetry(client, nodeName)
  204. // TODO (ereslibre): this logic will need tweaking once that we get rid of the ClusterStatus, since we won't have
  205. // the ClusterStatus safety net, we will want to remove the UnretriableError and not make the distinction here
  206. // anymore.
  207. if _, ok := lastErr.(*unretriableError); ok {
  208. // Fail fast scenario, to be removed once we get rid of the ClusterStatus
  209. return true, errors.Wrapf(lastErr, "API server Pods exist, but no API endpoint annotations were found")
  210. }
  211. return lastErr == nil, nil
  212. })
  213. if err != nil {
  214. return err
  215. }
  216. parsedAPIEndpoint, err := kubeadmapi.APIEndpointFromString(rawAPIEndpoint)
  217. if err != nil {
  218. return errors.Wrapf(err, "could not parse API endpoint for node %q", nodeName)
  219. }
  220. *apiEndpoint = parsedAPIEndpoint
  221. return nil
  222. }
  223. func getRawAPIEndpointFromPodAnnotationWithoutRetry(client clientset.Interface, nodeName string) (string, error) {
  224. podList, err := client.CoreV1().Pods(metav1.NamespaceSystem).List(
  225. context.TODO(),
  226. metav1.ListOptions{
  227. FieldSelector: fmt.Sprintf("spec.nodeName=%s", nodeName),
  228. LabelSelector: fmt.Sprintf("component=%s,tier=%s", constants.KubeAPIServer, constants.ControlPlaneTier),
  229. },
  230. )
  231. if err != nil {
  232. return "", errors.Wrap(err, "could not retrieve list of pods to determine api server endpoints")
  233. }
  234. if len(podList.Items) != 1 {
  235. return "", errors.Errorf("API server pod for node name %q has %d entries, only one was expected", nodeName, len(podList.Items))
  236. }
  237. if apiServerEndpoint, ok := podList.Items[0].Annotations[constants.KubeAPIServerAdvertiseAddressEndpointAnnotationKey]; ok {
  238. return apiServerEndpoint, nil
  239. }
  240. return "", newUnretriableError(errors.Errorf("API server pod for node name %q hasn't got a %q annotation, cannot retrieve API endpoint", nodeName, constants.KubeAPIServerAdvertiseAddressEndpointAnnotationKey))
  241. }
  242. // TODO: remove after 1.20, when the ClusterStatus struct is removed from the kubeadm-config ConfigMap.
  243. func getAPIEndpointFromClusterStatus(client clientset.Interface, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint) error {
  244. clusterStatus, err := GetClusterStatus(client)
  245. if err != nil {
  246. return errors.Wrap(err, "could not retrieve cluster status")
  247. }
  248. if statusAPIEndpoint, ok := clusterStatus.APIEndpoints[nodeName]; ok {
  249. *apiEndpoint = statusAPIEndpoint
  250. return nil
  251. }
  252. return errors.Errorf("could not find node %s in the cluster status", nodeName)
  253. }
  254. // GetClusterStatus returns the kubeadm cluster status read from the kubeadm-config ConfigMap
  255. func GetClusterStatus(client clientset.Interface) (*kubeadmapi.ClusterStatus, error) {
  256. configMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)
  257. if apierrors.IsNotFound(err) {
  258. return &kubeadmapi.ClusterStatus{}, nil
  259. }
  260. if err != nil {
  261. return nil, err
  262. }
  263. clusterStatus, err := UnmarshalClusterStatus(configMap.Data)
  264. if err != nil {
  265. return nil, err
  266. }
  267. return clusterStatus, nil
  268. }
  269. // UnmarshalClusterStatus takes raw ConfigMap.Data and converts it to a ClusterStatus object
  270. func UnmarshalClusterStatus(data map[string]string) (*kubeadmapi.ClusterStatus, error) {
  271. clusterStatusData, ok := data[constants.ClusterStatusConfigMapKey]
  272. if !ok {
  273. return nil, errors.Errorf("unexpected error when reading kubeadm-config ConfigMap: %s key value pair missing", constants.ClusterStatusConfigMapKey)
  274. }
  275. clusterStatus := &kubeadmapi.ClusterStatus{}
  276. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), []byte(clusterStatusData), clusterStatus); err != nil {
  277. return nil, err
  278. }
  279. return clusterStatus, nil
  280. }