cluster.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/client-go/tools/clientcmd"
  27. certutil "k8s.io/client-go/util/cert"
  28. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  29. kubeadmscheme "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme"
  30. "k8s.io/kubernetes/cmd/kubeadm/app/componentconfigs"
  31. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
  33. )
  34. // FetchInitConfigurationFromCluster fetches configuration from a ConfigMap in the cluster
  35. func FetchInitConfigurationFromCluster(client clientset.Interface, w io.Writer, logPrefix string, newControlPlane bool) (*kubeadmapi.InitConfiguration, error) {
  36. fmt.Fprintf(w, "[%s] Reading configuration from the cluster...\n", logPrefix)
  37. 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)
  38. // Fetch the actual config from cluster
  39. cfg, err := getInitConfigurationFromCluster(constants.KubernetesDir, client, newControlPlane)
  40. if err != nil {
  41. return nil, err
  42. }
  43. // Apply dynamic defaults
  44. if err := SetInitDynamicDefaults(cfg); err != nil {
  45. return nil, err
  46. }
  47. return cfg, nil
  48. }
  49. // getInitConfigurationFromCluster is separate only for testing purposes, don't call it directly, use FetchInitConfigurationFromCluster instead
  50. func getInitConfigurationFromCluster(kubeconfigDir string, client clientset.Interface, newControlPlane bool) (*kubeadmapi.InitConfiguration, error) {
  51. // Also, the config map really should be KubeadmConfigConfigMap...
  52. configMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)
  53. if err != nil {
  54. return nil, errors.Wrap(err, "failed to get config map")
  55. }
  56. // InitConfiguration is composed with data from different places
  57. initcfg := &kubeadmapi.InitConfiguration{}
  58. // gets ClusterConfiguration from kubeadm-config
  59. clusterConfigurationData, ok := configMap.Data[constants.ClusterConfigurationConfigMapKey]
  60. if !ok {
  61. return nil, errors.Errorf("unexpected error when reading kubeadm-config ConfigMap: %s key value pair missing", constants.ClusterConfigurationConfigMapKey)
  62. }
  63. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), []byte(clusterConfigurationData), &initcfg.ClusterConfiguration); err != nil {
  64. return nil, errors.Wrap(err, "failed to decode cluster configuration data")
  65. }
  66. // gets the component configs from the corresponding config maps
  67. if err := componentconfigs.FetchFromCluster(&initcfg.ClusterConfiguration, client); err != nil {
  68. return nil, errors.Wrap(err, "failed to get component configs")
  69. }
  70. // if this isn't a new controlplane instance (e.g. in case of kubeadm upgrades)
  71. // get nodes specific information as well
  72. if !newControlPlane {
  73. // gets the nodeRegistration for the current from the node object
  74. if err := getNodeRegistration(kubeconfigDir, client, &initcfg.NodeRegistration); err != nil {
  75. return nil, errors.Wrap(err, "failed to get node registration")
  76. }
  77. // gets the APIEndpoint for the current node from then ClusterStatus in the kubeadm-config ConfigMap
  78. if err := getAPIEndpoint(configMap.Data, initcfg.NodeRegistration.Name, &initcfg.LocalAPIEndpoint); err != nil {
  79. return nil, errors.Wrap(err, "failed to getAPIEndpoint")
  80. }
  81. } else {
  82. // In the case where newControlPlane is true we don't go through getNodeRegistration() and initcfg.NodeRegistration.CRISocket is empty.
  83. // This forces DetectCRISocket() to be called later on, and if there is more than one CRI installed on the system, it will error out,
  84. // while asking for the user to provide an override for the CRI socket. Even if the user provides an override, the call to
  85. // DetectCRISocket() can happen too early and thus ignore it (while still erroring out).
  86. // However, if newControlPlane == true, initcfg.NodeRegistration is not used at all and it's overwritten later on.
  87. // Thus it's necessary to supply some default value, that will avoid the call to DetectCRISocket() and as
  88. // initcfg.NodeRegistration is discarded, setting whatever value here is harmless.
  89. initcfg.NodeRegistration.CRISocket = constants.DefaultDockerCRISocket
  90. }
  91. return initcfg, nil
  92. }
  93. // getNodeRegistration returns the nodeRegistration for the current node
  94. func getNodeRegistration(kubeconfigDir string, client clientset.Interface, nodeRegistration *kubeadmapi.NodeRegistrationOptions) error {
  95. // gets the name of the current node
  96. nodeName, err := getNodeNameFromKubeletConfig(kubeconfigDir)
  97. if err != nil {
  98. return errors.Wrap(err, "failed to get node name from kubelet config")
  99. }
  100. // gets the corresponding node and retrieves attributes stored there.
  101. node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
  102. if err != nil {
  103. return errors.Wrap(err, "failed to get corresponding node")
  104. }
  105. criSocket, ok := node.ObjectMeta.Annotations[constants.AnnotationKubeadmCRISocket]
  106. if !ok {
  107. return errors.Errorf("node %s doesn't have %s annotation", nodeName, constants.AnnotationKubeadmCRISocket)
  108. }
  109. // returns the nodeRegistration attributes
  110. nodeRegistration.Name = nodeName
  111. nodeRegistration.CRISocket = criSocket
  112. nodeRegistration.Taints = node.Spec.Taints
  113. // NB. currently nodeRegistration.KubeletExtraArgs isn't stored at node level but only in the kubeadm-flags.env
  114. // that isn't modified during upgrades
  115. // in future we might reconsider this thus enabling changes to the kubeadm-flags.env during upgrades as well
  116. return nil
  117. }
  118. // getNodeNameFromKubeletConfig gets the node name from a kubelet config file
  119. // TODO: in future we want to switch to a more canonical way for doing this e.g. by having this
  120. // information in the local kubelet config.yaml
  121. func getNodeNameFromKubeletConfig(kubeconfigDir string) (string, error) {
  122. // loads the kubelet.conf file
  123. fileName := filepath.Join(kubeconfigDir, constants.KubeletKubeConfigFileName)
  124. config, err := clientcmd.LoadFromFile(fileName)
  125. if err != nil {
  126. return "", err
  127. }
  128. // gets the info about the current user
  129. currentContext, exists := config.Contexts[config.CurrentContext]
  130. if !exists {
  131. return "", errors.Errorf("invalid kubeconfig file %s: missing context %s", fileName, config.CurrentContext)
  132. }
  133. authInfo, exists := config.AuthInfos[currentContext.AuthInfo]
  134. if !exists {
  135. return "", errors.Errorf("invalid kubeconfig file %s: missing AuthInfo %s", fileName, currentContext.AuthInfo)
  136. }
  137. // gets the X509 certificate with current user credentials
  138. var certs []*x509.Certificate
  139. if len(authInfo.ClientCertificateData) > 0 {
  140. // if the config file uses an embedded x509 certificate (e.g. kubelet.conf created by kubeadm), parse it
  141. if certs, err = certutil.ParseCertsPEM(authInfo.ClientCertificateData); err != nil {
  142. return "", err
  143. }
  144. } else if len(authInfo.ClientCertificate) > 0 {
  145. // if the config file links an external x509 certificate (e.g. kubelet.conf created by TLS bootstrap), load it
  146. if certs, err = certutil.CertsFromFile(authInfo.ClientCertificate); err != nil {
  147. return "", err
  148. }
  149. } else {
  150. return "", errors.Errorf("invalid kubeconfig file %s. x509 certificate expected", fileName)
  151. }
  152. // We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
  153. // TODO: Support multiple certs here in order to be able to rotate certs
  154. cert := certs[0]
  155. // gets the node name from the certificate common name
  156. return strings.TrimPrefix(cert.Subject.CommonName, constants.NodesUserPrefix), nil
  157. }
  158. // getAPIEndpoint returns the APIEndpoint for the current node
  159. func getAPIEndpoint(data map[string]string, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint) error {
  160. // gets the ClusterStatus from kubeadm-config
  161. clusterStatus, err := UnmarshalClusterStatus(data)
  162. if err != nil {
  163. return err
  164. }
  165. // gets the APIEndpoint for the current machine from the ClusterStatus
  166. e, ok := clusterStatus.APIEndpoints[nodeName]
  167. if !ok {
  168. return errors.New("failed to get APIEndpoint information for this node")
  169. }
  170. apiEndpoint.AdvertiseAddress = e.AdvertiseAddress
  171. apiEndpoint.BindPort = e.BindPort
  172. return nil
  173. }
  174. // GetClusterStatus returns the kubeadm cluster status read from the kubeadm-config ConfigMap
  175. func GetClusterStatus(client clientset.Interface) (*kubeadmapi.ClusterStatus, error) {
  176. configMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)
  177. if apierrors.IsNotFound(err) {
  178. return &kubeadmapi.ClusterStatus{}, nil
  179. }
  180. if err != nil {
  181. return nil, err
  182. }
  183. clusterStatus, err := UnmarshalClusterStatus(configMap.Data)
  184. if err != nil {
  185. return nil, err
  186. }
  187. return clusterStatus, nil
  188. }
  189. // UnmarshalClusterStatus takes raw ConfigMap.Data and converts it to a ClusterStatus object
  190. func UnmarshalClusterStatus(data map[string]string) (*kubeadmapi.ClusterStatus, error) {
  191. clusterStatusData, ok := data[constants.ClusterStatusConfigMapKey]
  192. if !ok {
  193. return nil, errors.Errorf("unexpected error when reading kubeadm-config ConfigMap: %s key value pair missing", constants.ClusterStatusConfigMapKey)
  194. }
  195. clusterStatus := &kubeadmapi.ClusterStatus{}
  196. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), []byte(clusterStatusData), clusterStatus); err != nil {
  197. return nil, err
  198. }
  199. return clusterStatus, nil
  200. }