cluster.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. "crypto/x509"
  16. "fmt"
  17. "io"
  18. "path/filepath"
  19. "strings"
  20. "github.com/pkg/errors"
  21. apierrors "k8s.io/apimachinery/pkg/api/errors"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/util/version"
  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 := getComponentConfigs(client, &initcfg.ClusterConfiguration); 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(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. authInfo := config.AuthInfos[config.Contexts[config.CurrentContext].AuthInfo]
  130. // gets the X509 certificate with current user credentials
  131. var certs []*x509.Certificate
  132. if len(authInfo.ClientCertificateData) > 0 {
  133. // if the config file uses an embedded x509 certificate (e.g. kubelet.conf created by kubeadm), parse it
  134. if certs, err = certutil.ParseCertsPEM(authInfo.ClientCertificateData); err != nil {
  135. return "", err
  136. }
  137. } else if len(authInfo.ClientCertificate) > 0 {
  138. // if the config file links an external x509 certificate (e.g. kubelet.conf created by TLS bootstrap), load it
  139. if certs, err = certutil.CertsFromFile(authInfo.ClientCertificate); err != nil {
  140. return "", err
  141. }
  142. } else {
  143. return "", errors.New("invalid kubelet.conf. X509 certificate expected")
  144. }
  145. // We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
  146. // TODO: Support multiple certs here in order to be able to rotate certs
  147. cert := certs[0]
  148. // gets the node name from the certificate common name
  149. return strings.TrimPrefix(cert.Subject.CommonName, constants.NodesUserPrefix), nil
  150. }
  151. // getAPIEndpoint returns the APIEndpoint for the current node
  152. func getAPIEndpoint(data map[string]string, nodeName string, apiEndpoint *kubeadmapi.APIEndpoint) error {
  153. // gets the ClusterStatus from kubeadm-config
  154. clusterStatus, err := UnmarshalClusterStatus(data)
  155. if err != nil {
  156. return err
  157. }
  158. // gets the APIEndpoint for the current machine from the ClusterStatus
  159. e, ok := clusterStatus.APIEndpoints[nodeName]
  160. if !ok {
  161. return errors.New("failed to get APIEndpoint information for this node")
  162. }
  163. apiEndpoint.AdvertiseAddress = e.AdvertiseAddress
  164. apiEndpoint.BindPort = e.BindPort
  165. return nil
  166. }
  167. // getComponentConfigs gets the component configs from the corresponding config maps
  168. func getComponentConfigs(client clientset.Interface, clusterConfiguration *kubeadmapi.ClusterConfiguration) error {
  169. // some config maps is versioned, so we need the KubernetesVersion for getting the right config map
  170. k8sVersion := version.MustParseGeneric(clusterConfiguration.KubernetesVersion)
  171. for kind, registration := range componentconfigs.Known {
  172. obj, err := registration.GetFromConfigMap(client, k8sVersion)
  173. if err != nil {
  174. return err
  175. }
  176. if ok := registration.SetToInternalConfig(obj, clusterConfiguration); !ok {
  177. return errors.Errorf("couldn't save componentconfig value for kind %q", string(kind))
  178. }
  179. }
  180. return nil
  181. }
  182. // GetClusterStatus returns the kubeadm cluster status read from the kubeadm-config ConfigMap
  183. func GetClusterStatus(client clientset.Interface) (*kubeadmapi.ClusterStatus, error) {
  184. configMap, err := apiclient.GetConfigMapWithRetry(client, metav1.NamespaceSystem, constants.KubeadmConfigConfigMap)
  185. if apierrors.IsNotFound(err) {
  186. return &kubeadmapi.ClusterStatus{}, nil
  187. }
  188. if err != nil {
  189. return nil, err
  190. }
  191. clusterStatus, err := UnmarshalClusterStatus(configMap.Data)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return clusterStatus, nil
  196. }
  197. // UnmarshalClusterStatus takes raw ConfigMap.Data and converts it to a ClusterStatus object
  198. func UnmarshalClusterStatus(data map[string]string) (*kubeadmapi.ClusterStatus, error) {
  199. clusterStatusData, ok := data[constants.ClusterStatusConfigMapKey]
  200. if !ok {
  201. return nil, errors.Errorf("unexpected error when reading kubeadm-config ConfigMap: %s key value pair missing", constants.ClusterStatusConfigMapKey)
  202. }
  203. clusterStatus := &kubeadmapi.ClusterStatus{}
  204. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), []byte(clusterStatusData), clusterStatus); err != nil {
  205. return nil, err
  206. }
  207. return clusterStatus, nil
  208. }