initconfiguration.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. "reflect"
  20. "sort"
  21. "strconv"
  22. "github.com/pkg/errors"
  23. "k8s.io/klog"
  24. "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/runtime"
  26. "k8s.io/apimachinery/pkg/runtime/schema"
  27. bootstraputil "k8s.io/cluster-bootstrap/token/util"
  28. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  29. kubeadmscheme "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/scheme"
  30. kubeadmapiv1beta2 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta2"
  31. "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation"
  32. "k8s.io/kubernetes/cmd/kubeadm/app/componentconfigs"
  33. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  34. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  35. "k8s.io/kubernetes/cmd/kubeadm/app/util/config/strict"
  36. kubeadmruntime "k8s.io/kubernetes/cmd/kubeadm/app/util/runtime"
  37. nodeutil "k8s.io/kubernetes/pkg/util/node"
  38. )
  39. // SetInitDynamicDefaults checks and sets configuration values for the InitConfiguration object
  40. func SetInitDynamicDefaults(cfg *kubeadmapi.InitConfiguration) error {
  41. if err := SetBootstrapTokensDynamicDefaults(&cfg.BootstrapTokens); err != nil {
  42. return err
  43. }
  44. if err := SetNodeRegistrationDynamicDefaults(&cfg.NodeRegistration, true); err != nil {
  45. return err
  46. }
  47. if err := SetAPIEndpointDynamicDefaults(&cfg.LocalAPIEndpoint); err != nil {
  48. return err
  49. }
  50. return SetClusterDynamicDefaults(&cfg.ClusterConfiguration, cfg.LocalAPIEndpoint.AdvertiseAddress, cfg.LocalAPIEndpoint.BindPort)
  51. }
  52. // SetBootstrapTokensDynamicDefaults checks and sets configuration values for the BootstrapTokens object
  53. func SetBootstrapTokensDynamicDefaults(cfg *[]kubeadmapi.BootstrapToken) error {
  54. // Populate the .Token field with a random value if unset
  55. // We do this at this layer, and not the API defaulting layer
  56. // because of possible security concerns, and more practically
  57. // because we can't return errors in the API object defaulting
  58. // process but here we can.
  59. for i, bt := range *cfg {
  60. if bt.Token != nil && len(bt.Token.String()) > 0 {
  61. continue
  62. }
  63. tokenStr, err := bootstraputil.GenerateBootstrapToken()
  64. if err != nil {
  65. return errors.Wrap(err, "couldn't generate random token")
  66. }
  67. token, err := kubeadmapi.NewBootstrapTokenString(tokenStr)
  68. if err != nil {
  69. return err
  70. }
  71. (*cfg)[i].Token = token
  72. }
  73. return nil
  74. }
  75. // SetNodeRegistrationDynamicDefaults checks and sets configuration values for the NodeRegistration object
  76. func SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, ControlPlaneTaint bool) error {
  77. var err error
  78. cfg.Name, err = nodeutil.GetHostname(cfg.Name)
  79. if err != nil {
  80. return err
  81. }
  82. // 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
  83. if ControlPlaneTaint && cfg.Taints == nil {
  84. cfg.Taints = []v1.Taint{kubeadmconstants.ControlPlaneTaint}
  85. }
  86. if cfg.CRISocket == "" {
  87. cfg.CRISocket, err = kubeadmruntime.DetectCRISocket()
  88. if err != nil {
  89. return err
  90. }
  91. klog.V(1).Infof("detected and using CRI socket: %s", cfg.CRISocket)
  92. }
  93. return nil
  94. }
  95. // SetAPIEndpointDynamicDefaults checks and sets configuration values for the APIEndpoint object
  96. func SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error {
  97. // validate cfg.API.AdvertiseAddress.
  98. addressIP := net.ParseIP(cfg.AdvertiseAddress)
  99. if addressIP == nil && cfg.AdvertiseAddress != "" {
  100. return errors.Errorf("couldn't use \"%s\" as \"apiserver-advertise-address\", must be ipv4 or ipv6 address", cfg.AdvertiseAddress)
  101. }
  102. // 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
  103. // for bootstrapping a cluster.
  104. ip, err := ChooseAPIServerBindAddress(addressIP)
  105. if err != nil {
  106. return err
  107. }
  108. cfg.AdvertiseAddress = ip.String()
  109. return nil
  110. }
  111. // SetClusterDynamicDefaults checks and sets values for the ClusterConfiguration object
  112. func SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, advertiseAddress string, bindPort int32) error {
  113. // Default all the embedded ComponentConfig structs
  114. componentconfigs.Known.Default(cfg)
  115. ip := net.ParseIP(advertiseAddress)
  116. if ip.To4() != nil {
  117. cfg.ComponentConfigs.KubeProxy.BindAddress = kubeadmapiv1beta2.DefaultProxyBindAddressv4
  118. } else {
  119. cfg.ComponentConfigs.KubeProxy.BindAddress = kubeadmapiv1beta2.DefaultProxyBindAddressv6
  120. }
  121. // Resolve possible version labels and validate version string
  122. if err := NormalizeKubernetesVersion(cfg); err != nil {
  123. return err
  124. }
  125. // If ControlPlaneEndpoint is specified without a port number defaults it to
  126. // the bindPort number of the APIEndpoint.
  127. // This will allow join of additional control plane instances with different bindPort number
  128. if cfg.ControlPlaneEndpoint != "" {
  129. host, port, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint)
  130. if err != nil {
  131. return err
  132. }
  133. if port == "" {
  134. cfg.ControlPlaneEndpoint = net.JoinHostPort(host, strconv.FormatInt(int64(bindPort), 10))
  135. }
  136. }
  137. // Downcase SANs. Some domain names (like ELBs) have capitals in them.
  138. LowercaseSANs(cfg.APIServer.CertSANs)
  139. return nil
  140. }
  141. // DefaultedInitConfiguration takes a versioned init config (often populated by flags), defaults it and converts it into internal InitConfiguration
  142. func DefaultedInitConfiguration(versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {
  143. internalcfg := &kubeadmapi.InitConfiguration{}
  144. // Takes passed flags into account; the defaulting is executed once again enforcing assignment of
  145. // static default values to cfg only for values not provided with flags
  146. kubeadmscheme.Scheme.Default(versionedInitCfg)
  147. kubeadmscheme.Scheme.Convert(versionedInitCfg, internalcfg, nil)
  148. kubeadmscheme.Scheme.Default(versionedClusterCfg)
  149. kubeadmscheme.Scheme.Convert(versionedClusterCfg, &internalcfg.ClusterConfiguration, nil)
  150. // Applies dynamic defaults to settings not provided with flags
  151. if err := SetInitDynamicDefaults(internalcfg); err != nil {
  152. return nil, err
  153. }
  154. // Validates cfg (flags/configs + defaults + dynamic defaults)
  155. if err := validation.ValidateInitConfiguration(internalcfg).ToAggregate(); err != nil {
  156. return nil, err
  157. }
  158. return internalcfg, nil
  159. }
  160. // LoadInitConfigurationFromFile loads a supported versioned InitConfiguration from a file, converts it into internal config, defaults it and verifies it.
  161. func LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error) {
  162. klog.V(1).Infof("loading configuration from %q", cfgPath)
  163. b, err := ioutil.ReadFile(cfgPath)
  164. if err != nil {
  165. return nil, errors.Wrapf(err, "unable to read config from %q ", cfgPath)
  166. }
  167. return BytesToInitConfiguration(b)
  168. }
  169. // LoadOrDefaultInitConfiguration takes a path to a config file and a versioned configuration that can serve as the default config
  170. // If cfgPath is specified, the versioned configs will always get overridden with the one in the file (specified by cfgPath).
  171. // The the external, versioned configuration is defaulted and converted to the internal type.
  172. // Right thereafter, the configuration is defaulted again with dynamic values (like IP addresses of a machine, etc)
  173. // Lastly, the internal config is validated and returned.
  174. func LoadOrDefaultInitConfiguration(cfgPath string, versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {
  175. if cfgPath != "" {
  176. // Loads configuration from config file, if provided
  177. // Nb. --config overrides command line flags
  178. return LoadInitConfigurationFromFile(cfgPath)
  179. }
  180. return DefaultedInitConfiguration(versionedInitCfg, versionedClusterCfg)
  181. }
  182. // BytesToInitConfiguration converts a byte slice to an internal, defaulted and validated InitConfiguration object.
  183. // The map may contain many different YAML documents. These YAML documents are parsed one-by-one
  184. // and well-known ComponentConfig GroupVersionKinds are stored inside of the internal InitConfiguration struct.
  185. // The resulting InitConfiguration is then dynamically defaulted and validated prior to return.
  186. func BytesToInitConfiguration(b []byte) (*kubeadmapi.InitConfiguration, error) {
  187. gvkmap, err := kubeadmutil.SplitYAMLDocuments(b)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return documentMapToInitConfiguration(gvkmap, false)
  192. }
  193. // documentMapToInitConfiguration converts a map of GVKs and YAML documents to defaulted and validated configuration object.
  194. func documentMapToInitConfiguration(gvkmap map[schema.GroupVersionKind][]byte, allowDeprecated bool) (*kubeadmapi.InitConfiguration, error) {
  195. var initcfg *kubeadmapi.InitConfiguration
  196. var clustercfg *kubeadmapi.ClusterConfiguration
  197. decodedComponentConfigObjects := map[componentconfigs.RegistrationKind]runtime.Object{}
  198. for gvk, fileContent := range gvkmap {
  199. // first, check if this GVK is supported and possibly not deprecated
  200. if err := validateSupportedVersion(gvk.GroupVersion(), allowDeprecated); err != nil {
  201. return nil, err
  202. }
  203. // verify the validity of the YAML
  204. strict.VerifyUnmarshalStrict(fileContent, gvk)
  205. // Try to get the registration for the ComponentConfig based on the kind
  206. regKind := componentconfigs.RegistrationKind(gvk.Kind)
  207. if registration, found := componentconfigs.Known[regKind]; found {
  208. // Unmarshal the bytes from the YAML document into a runtime.Object containing the ComponentConfiguration struct
  209. obj, err := registration.Unmarshal(fileContent)
  210. if err != nil {
  211. return nil, err
  212. }
  213. decodedComponentConfigObjects[regKind] = obj
  214. continue
  215. }
  216. if kubeadmutil.GroupVersionKindsHasInitConfiguration(gvk) {
  217. // Set initcfg to an empty struct value the deserializer will populate
  218. initcfg = &kubeadmapi.InitConfiguration{}
  219. // Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the
  220. // right external version, defaulted, and converted into the internal version.
  221. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, initcfg); err != nil {
  222. return nil, err
  223. }
  224. continue
  225. }
  226. if kubeadmutil.GroupVersionKindsHasClusterConfiguration(gvk) {
  227. // Set clustercfg to an empty struct value the deserializer will populate
  228. clustercfg = &kubeadmapi.ClusterConfiguration{}
  229. // Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the
  230. // right external version, defaulted, and converted into the internal version.
  231. if err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, clustercfg); err != nil {
  232. return nil, err
  233. }
  234. continue
  235. }
  236. fmt.Printf("[config] WARNING: Ignored YAML document with GroupVersionKind %v\n", gvk)
  237. }
  238. // Enforce that InitConfiguration and/or ClusterConfiguration has to exist among the YAML documents
  239. if initcfg == nil && clustercfg == nil {
  240. return nil, errors.New("no InitConfiguration or ClusterConfiguration kind was found in the YAML file")
  241. }
  242. // If InitConfiguration wasn't given, default it by creating an external struct instance, default it and convert into the internal type
  243. if initcfg == nil {
  244. extinitcfg := &kubeadmapiv1beta2.InitConfiguration{}
  245. kubeadmscheme.Scheme.Default(extinitcfg)
  246. // Set initcfg to an empty struct value the deserializer will populate
  247. initcfg = &kubeadmapi.InitConfiguration{}
  248. kubeadmscheme.Scheme.Convert(extinitcfg, initcfg, nil)
  249. }
  250. // If ClusterConfiguration was given, populate it in the InitConfiguration struct
  251. if clustercfg != nil {
  252. initcfg.ClusterConfiguration = *clustercfg
  253. }
  254. // Save the loaded ComponentConfig objects in the initcfg object
  255. for kind, obj := range decodedComponentConfigObjects {
  256. if registration, found := componentconfigs.Known[kind]; found {
  257. if ok := registration.SetToInternalConfig(obj, &initcfg.ClusterConfiguration); !ok {
  258. return nil, errors.Errorf("couldn't save componentconfig value for kind %q", string(kind))
  259. }
  260. } else {
  261. // This should never happen in practice
  262. fmt.Printf("[config] WARNING: Decoded a kind that couldn't be saved to the internal configuration: %q\n", string(kind))
  263. }
  264. }
  265. // Applies dynamic defaults to settings not provided with flags
  266. if err := SetInitDynamicDefaults(initcfg); err != nil {
  267. return nil, err
  268. }
  269. // Validates cfg (flags/configs + defaults + dynamic defaults)
  270. if err := validation.ValidateInitConfiguration(initcfg).ToAggregate(); err != nil {
  271. return nil, err
  272. }
  273. return initcfg, nil
  274. }
  275. func defaultedInternalConfig() *kubeadmapi.ClusterConfiguration {
  276. externalcfg := &kubeadmapiv1beta2.ClusterConfiguration{}
  277. internalcfg := &kubeadmapi.ClusterConfiguration{}
  278. kubeadmscheme.Scheme.Default(externalcfg)
  279. kubeadmscheme.Scheme.Convert(externalcfg, internalcfg, nil)
  280. // Default the embedded ComponentConfig structs
  281. componentconfigs.Known.Default(internalcfg)
  282. return internalcfg
  283. }
  284. // MarshalInitConfigurationToBytes marshals the internal InitConfiguration object to bytes. It writes the embedded
  285. // ClusterConfiguration object with ComponentConfigs out as separate YAML documents
  286. func MarshalInitConfigurationToBytes(cfg *kubeadmapi.InitConfiguration, gv schema.GroupVersion) ([]byte, error) {
  287. initbytes, err := kubeadmutil.MarshalToYamlForCodecs(cfg, gv, kubeadmscheme.Codecs)
  288. if err != nil {
  289. return []byte{}, err
  290. }
  291. allFiles := [][]byte{initbytes}
  292. // Exception: If the specified groupversion is targeting the internal type, don't print embedded ClusterConfiguration contents
  293. // This is mostly used for unit testing. In a real scenario the internal version of the API is never marshalled as-is.
  294. if gv.Version != runtime.APIVersionInternal {
  295. clusterbytes, err := MarshalClusterConfigurationToBytes(&cfg.ClusterConfiguration, gv)
  296. if err != nil {
  297. return []byte{}, err
  298. }
  299. allFiles = append(allFiles, clusterbytes)
  300. }
  301. return bytes.Join(allFiles, []byte(kubeadmconstants.YAMLDocumentSeparator)), nil
  302. }
  303. // MarshalClusterConfigurationToBytes marshals the internal ClusterConfiguration object to bytes. It writes the embedded
  304. // ComponentConfiguration objects out as separate YAML documents
  305. func MarshalClusterConfigurationToBytes(clustercfg *kubeadmapi.ClusterConfiguration, gv schema.GroupVersion) ([]byte, error) {
  306. clusterbytes, err := kubeadmutil.MarshalToYamlForCodecs(clustercfg, gv, kubeadmscheme.Codecs)
  307. if err != nil {
  308. return []byte{}, err
  309. }
  310. allFiles := [][]byte{clusterbytes}
  311. componentConfigContent := map[string][]byte{}
  312. defaultedcfg := defaultedInternalConfig()
  313. for kind, registration := range componentconfigs.Known {
  314. // If the ComponentConfig struct for the current registration is nil, skip it when marshalling
  315. realobj, ok := registration.GetFromInternalConfig(clustercfg)
  316. if !ok {
  317. continue
  318. }
  319. defaultedobj, ok := registration.GetFromInternalConfig(defaultedcfg)
  320. // Invalid: The caller asked to not print the componentconfigs if defaulted, but defaultComponentConfigs() wasn't able to create default objects to use for reference
  321. if !ok {
  322. return []byte{}, errors.New("couldn't create a default componentconfig object")
  323. }
  324. // If the real ComponentConfig object differs from the default, print it out. If not, there's no need to print it out, so skip it
  325. if !reflect.DeepEqual(realobj, defaultedobj) {
  326. contentBytes, err := registration.Marshal(realobj)
  327. if err != nil {
  328. return []byte{}, err
  329. }
  330. componentConfigContent[string(kind)] = contentBytes
  331. }
  332. }
  333. // Sort the ComponentConfig files by kind when marshalling
  334. sortedComponentConfigFiles := consistentOrderByteSlice(componentConfigContent)
  335. allFiles = append(allFiles, sortedComponentConfigFiles...)
  336. return bytes.Join(allFiles, []byte(kubeadmconstants.YAMLDocumentSeparator)), nil
  337. }
  338. // consistentOrderByteSlice takes a map of a string key and a byte slice, and returns a byte slice of byte slices
  339. // with consistent ordering, where the keys in the map determine the ordering of the return value. This has to be
  340. // done as the order of a for...range loop over a map in go is undeterministic, and could otherwise lead to flakes
  341. // in e.g. unit tests when marshalling content with a random order
  342. func consistentOrderByteSlice(content map[string][]byte) [][]byte {
  343. keys := []string{}
  344. sortedContent := [][]byte{}
  345. for key := range content {
  346. keys = append(keys, key)
  347. }
  348. sort.Strings(keys)
  349. for _, key := range keys {
  350. sortedContent = append(sortedContent, content[key])
  351. }
  352. return sortedContent
  353. }