initconfiguration.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 config
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "strconv"
  20. "github.com/pkg/errors"
  21. "k8s.io/klog"
  22. v1 "k8s.io/api/core/v1"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/runtime/schema"
  25. netutil "k8s.io/apimachinery/pkg/util/net"
  26. bootstraputil "k8s.io/cluster-bootstrap/token/util"
  27. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  28. kubeadmscheme "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme"
  29. kubeadmapiv1beta2 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2"
  30. "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation"
  31. "k8s.io/kubernetes/cmd/kubeadm/app/componentconfigs"
  32. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  33. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  34. "k8s.io/kubernetes/cmd/kubeadm/app/util/config/strict"
  35. kubeadmruntime "k8s.io/kubernetes/cmd/kubeadm/app/util/runtime"
  36. )
  37. // SetInitDynamicDefaults checks and sets configuration values for the InitConfiguration object
  38. func SetInitDynamicDefaults(cfg *kubeadmapi.InitConfiguration) error {
  39. if err := SetBootstrapTokensDynamicDefaults(&cfg.BootstrapTokens); err != nil {
  40. return err
  41. }
  42. if err := SetNodeRegistrationDynamicDefaults(&cfg.NodeRegistration, true); err != nil {
  43. return err
  44. }
  45. if err := SetAPIEndpointDynamicDefaults(&cfg.LocalAPIEndpoint); err != nil {
  46. return err
  47. }
  48. return SetClusterDynamicDefaults(&cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint)
  49. }
  50. // SetBootstrapTokensDynamicDefaults checks and sets configuration values for the BootstrapTokens object
  51. func SetBootstrapTokensDynamicDefaults(cfg *[]kubeadmapi.BootstrapToken) error {
  52. // Populate the .Token field with a random value if unset
  53. // We do this at this layer, and not the API defaulting layer
  54. // because of possible security concerns, and more practically
  55. // because we can't return errors in the API object defaulting
  56. // process but here we can.
  57. for i, bt := range *cfg {
  58. if bt.Token != nil && len(bt.Token.String()) > 0 {
  59. continue
  60. }
  61. tokenStr, err := bootstraputil.GenerateBootstrapToken()
  62. if err != nil {
  63. return errors.Wrap(err, "couldn't generate random token")
  64. }
  65. token, err := kubeadmapi.NewBootstrapTokenString(tokenStr)
  66. if err != nil {
  67. return err
  68. }
  69. (*cfg)[i].Token = token
  70. }
  71. return nil
  72. }
  73. // SetNodeRegistrationDynamicDefaults checks and sets configuration values for the NodeRegistration object
  74. func SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, ControlPlaneTaint bool) error {
  75. var err error
  76. cfg.Name, err = kubeadmutil.GetHostname(cfg.Name)
  77. if err != nil {
  78. return err
  79. }
  80. // Only if the slice is nil, we should append the control-plane taint. This allows the user to specify an empty slice for no default control-plane taint
  81. if ControlPlaneTaint && cfg.Taints == nil {
  82. cfg.Taints = []v1.Taint{kubeadmconstants.ControlPlaneTaint}
  83. }
  84. if cfg.CRISocket == "" {
  85. cfg.CRISocket, err = kubeadmruntime.DetectCRISocket()
  86. if err != nil {
  87. return err
  88. }
  89. klog.V(1).Infof("detected and using CRI socket: %s", cfg.CRISocket)
  90. }
  91. return nil
  92. }
  93. // SetAPIEndpointDynamicDefaults checks and sets configuration values for the APIEndpoint object
  94. func SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error {
  95. // validate cfg.API.AdvertiseAddress.
  96. addressIP := net.ParseIP(cfg.AdvertiseAddress)
  97. if addressIP == nil && cfg.AdvertiseAddress != "" {
  98. return errors.Errorf("couldn't use \"%s\" as \"apiserver-advertise-address\", must be ipv4 or ipv6 address", cfg.AdvertiseAddress)
  99. }
  100. // kubeadm allows users to specify address=Loopback as a selector for global unicast IP address that can be found on loopback interface.
  101. // e.g. This is required for network setups where default routes are present, but network interfaces use only link-local addresses (e.g. as described in RFC5549).
  102. if addressIP.IsLoopback() {
  103. loopbackIP, err := netutil.ChooseBindAddressForInterface(netutil.LoopbackInterfaceName)
  104. if err != nil {
  105. return err
  106. }
  107. if loopbackIP != nil {
  108. klog.V(4).Infof("Found active IP %v on loopback interface", loopbackIP.String())
  109. cfg.AdvertiseAddress = loopbackIP.String()
  110. return nil
  111. }
  112. return errors.New("unable to resolve link-local addresses")
  113. }
  114. // This is the same logic as the API Server uses, except that if no interface is found the address is set to 0.0.0.0, which is invalid and cannot be used
  115. // for bootstrapping a cluster.
  116. ip, err := ChooseAPIServerBindAddress(addressIP)
  117. if err != nil {
  118. return err
  119. }
  120. cfg.AdvertiseAddress = ip.String()
  121. return nil
  122. }
  123. // SetClusterDynamicDefaults checks and sets values for the ClusterConfiguration object
  124. func SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, LocalAPIEndpoint *kubeadmapi.APIEndpoint) error {
  125. // Default all the embedded ComponentConfig structs
  126. componentconfigs.Default(cfg, LocalAPIEndpoint)
  127. // Resolve possible version labels and validate version string
  128. if err := NormalizeKubernetesVersion(cfg); err != nil {
  129. return err
  130. }
  131. // If ControlPlaneEndpoint is specified without a port number defaults it to
  132. // the bindPort number of the APIEndpoint.
  133. // This will allow join of additional control plane instances with different bindPort number
  134. if cfg.ControlPlaneEndpoint != "" {
  135. host, port, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint)
  136. if err != nil {
  137. return err
  138. }
  139. if port == "" {
  140. cfg.ControlPlaneEndpoint = net.JoinHostPort(host, strconv.FormatInt(int64(LocalAPIEndpoint.BindPort), 10))
  141. }
  142. }
  143. // Downcase SANs. Some domain names (like ELBs) have capitals in them.
  144. LowercaseSANs(cfg.APIServer.CertSANs)
  145. return nil
  146. }
  147. // DefaultedInitConfiguration takes a versioned init config (often populated by flags), defaults it and converts it into internal InitConfiguration
  148. func DefaultedInitConfiguration(versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {
  149. internalcfg := &kubeadmapi.InitConfiguration{}
  150. // Takes passed flags into account; the defaulting is executed once again enforcing assignment of
  151. // static default values to cfg only for values not provided with flags
  152. kubeadmscheme.Scheme.Default(versionedInitCfg)
  153. if err := kubeadmscheme.Scheme.Convert(versionedInitCfg, internalcfg, nil); err != nil {
  154. return nil, err
  155. }
  156. kubeadmscheme.Scheme.Default(versionedClusterCfg)
  157. if err := kubeadmscheme.Scheme.Convert(versionedClusterCfg, &internalcfg.ClusterConfiguration, nil); err != nil {
  158. return nil, err
  159. }
  160. // Applies dynamic defaults to settings not provided with flags
  161. if err := SetInitDynamicDefaults(internalcfg); err != nil {
  162. return nil, err
  163. }
  164. // Validates cfg (flags/configs + defaults + dynamic defaults)
  165. if err := validation.ValidateInitConfiguration(internalcfg).ToAggregate(); err != nil {
  166. return nil, err
  167. }
  168. return internalcfg, nil
  169. }
  170. // LoadInitConfigurationFromFile loads a supported versioned InitConfiguration from a file, converts it into internal config, defaults it and verifies it.
  171. func LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error) {
  172. klog.V(1).Infof("loading configuration from %q", cfgPath)
  173. b, err := ioutil.ReadFile(cfgPath)
  174. if err != nil {
  175. return nil, errors.Wrapf(err, "unable to read config from %q ", cfgPath)
  176. }
  177. return BytesToInitConfiguration(b)
  178. }
  179. // LoadOrDefaultInitConfiguration takes a path to a config file and a versioned configuration that can serve as the default config
  180. // If cfgPath is specified, the versioned configs will always get overridden with the one in the file (specified by cfgPath).
  181. // The external, versioned configuration is defaulted and converted to the internal type.
  182. // Right thereafter, the configuration is defaulted again with dynamic values (like IP addresses of a machine, etc)
  183. // Lastly, the internal config is validated and returned.
  184. func LoadOrDefaultInitConfiguration(cfgPath string, versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {
  185. if cfgPath != "" {
  186. // Loads configuration from config file, if provided
  187. // Nb. --config overrides command line flags
  188. return LoadInitConfigurationFromFile(cfgPath)
  189. }
  190. return DefaultedInitConfiguration(versionedInitCfg, versionedClusterCfg)
  191. }
  192. // BytesToInitConfiguration converts a byte slice to an internal, defaulted and validated InitConfiguration object.
  193. // The map may contain many different YAML documents. These YAML documents are parsed one-by-one
  194. // and well-known ComponentConfig GroupVersionKinds are stored inside of the internal InitConfiguration struct.
  195. // The resulting InitConfiguration is then dynamically defaulted and validated prior to return.
  196. func BytesToInitConfiguration(b []byte) (*kubeadmapi.InitConfiguration, error) {
  197. gvkmap, err := kubeadmutil.SplitYAMLDocuments(b)
  198. if err != nil {
  199. return nil, err
  200. }
  201. return documentMapToInitConfiguration(gvkmap, false)
  202. }
  203. // documentMapToInitConfiguration converts a map of GVKs and YAML documents to defaulted and validated configuration object.
  204. func documentMapToInitConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.InitConfiguration, error) {
  205. var initcfg *kubeadmapi.InitConfiguration
  206. var clustercfg *kubeadmapi.ClusterConfiguration
  207. for gvk, fileContent := range gvkmap {
  208. // first, check if this GVK is supported and possibly not deprecated
  209. if err := validateSupportedVersion(gvk.GroupVersion(), allowDeprecated); err != nil {
  210. return nil, err
  211. }
  212. // verify the validity of the YAML
  213. strict.VerifyUnmarshalStrict(fileContent, gvk)
  214. if kubeadmutil.GroupVersionKindsHasInitConfiguration(gvk) {
  215. // Set initcfg to an empty struct value the deserializer will populate
  216. initcfg = &kubeadmapi.InitConfiguration{}
  217. // Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the
  218. // right external version, defaulted, and converted into the internal version.
  219. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, initcfg); err != nil {
  220. return nil, err
  221. }
  222. continue
  223. }
  224. if kubeadmutil.GroupVersionKindsHasClusterConfiguration(gvk) {
  225. // Set clustercfg to an empty struct value the deserializer will populate
  226. clustercfg = &kubeadmapi.ClusterConfiguration{}
  227. // Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the
  228. // right external version, defaulted, and converted into the internal version.
  229. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, clustercfg); err != nil {
  230. return nil, err
  231. }
  232. continue
  233. }
  234. // If the group is neither a kubeadm core type or of a supported component config group, we dump a warning about it being ignored
  235. if !componentconfigs.Scheme.IsGroupRegistered(gvk.Group) {
  236. fmt.Printf("[config] WARNING: Ignored YAML document with GroupVersionKind %v\n", gvk)
  237. }
  238. }
  239. // Enforce that InitConfiguration and/or ClusterConfiguration has to exist among the YAML documents
  240. if initcfg == nil && clustercfg == nil {
  241. return nil, errors.New("no InitConfiguration or ClusterConfiguration kind was found in the YAML file")
  242. }
  243. // If InitConfiguration wasn't given, default it by creating an external struct instance, default it and convert into the internal type
  244. if initcfg == nil {
  245. extinitcfg := &kubeadmapiv1beta2.InitConfiguration{}
  246. kubeadmscheme.Scheme.Default(extinitcfg)
  247. // Set initcfg to an empty struct value the deserializer will populate
  248. initcfg = &kubeadmapi.InitConfiguration{}
  249. if err := kubeadmscheme.Scheme.Convert(extinitcfg, initcfg, nil); err != nil {
  250. return nil, err
  251. }
  252. }
  253. // If ClusterConfiguration was given, populate it in the InitConfiguration struct
  254. if clustercfg != nil {
  255. initcfg.ClusterConfiguration = *clustercfg
  256. }
  257. // Load any component configs
  258. if err := componentconfigs.FetchFromDocumentMap(&initcfg.ClusterConfiguration, gvkmap); err != nil {
  259. return nil, err
  260. }
  261. // Applies dynamic defaults to settings not provided with flags
  262. if err := SetInitDynamicDefaults(initcfg); err != nil {
  263. return nil, err
  264. }
  265. // Validates cfg (flags/configs + defaults + dynamic defaults)
  266. if err := validation.ValidateInitConfiguration(initcfg).ToAggregate(); err != nil {
  267. return nil, err
  268. }
  269. return initcfg, nil
  270. }
  271. // MarshalInitConfigurationToBytes marshals the internal InitConfiguration object to bytes. It writes the embedded
  272. // ClusterConfiguration object with ComponentConfigs out as separate YAML documents
  273. func MarshalInitConfigurationToBytes(cfg *kubeadmapi.InitConfiguration, gv schema.GroupVersion) ([]byte, error) {
  274. initbytes, err := kubeadmutil.MarshalToYamlForCodecs(cfg, gv, kubeadmscheme.Codecs)
  275. if err != nil {
  276. return []byte{}, err
  277. }
  278. allFiles := [][]byte{initbytes}
  279. // Exception: If the specified groupversion is targeting the internal type, don't print embedded ClusterConfiguration contents
  280. // This is mostly used for unit testing. In a real scenario the internal version of the API is never marshalled as-is.
  281. if gv.Version != runtime.APIVersionInternal {
  282. clusterbytes, err := kubeadmutil.MarshalToYamlForCodecs(&cfg.ClusterConfiguration, gv, kubeadmscheme.Codecs)
  283. if err != nil {
  284. return []byte{}, err
  285. }
  286. allFiles = append(allFiles, clusterbytes)
  287. }
  288. return bytes.Join(allFiles, []byte(kubeadmconstants.YAMLDocumentSeparator)), nil
  289. }