manifests.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. Copyright 2016 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 controlplane
  14. import (
  15. "fmt"
  16. "net"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "github.com/pkg/errors"
  21. v1 "k8s.io/api/core/v1"
  22. "k8s.io/klog"
  23. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  24. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  25. "k8s.io/kubernetes/cmd/kubeadm/app/features"
  26. "k8s.io/kubernetes/cmd/kubeadm/app/images"
  27. certphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/certs"
  28. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  29. staticpodutil "k8s.io/kubernetes/cmd/kubeadm/app/util/staticpod"
  30. utilsnet "k8s.io/utils/net"
  31. )
  32. // CreateInitStaticPodManifestFiles will write all static pod manifest files needed to bring up the control plane.
  33. func CreateInitStaticPodManifestFiles(manifestDir, kustomizeDir string, cfg *kubeadmapi.InitConfiguration) error {
  34. klog.V(1).Infoln("[control-plane] creating static Pod files")
  35. return CreateStaticPodFiles(manifestDir, kustomizeDir, &cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint, kubeadmconstants.KubeAPIServer, kubeadmconstants.KubeControllerManager, kubeadmconstants.KubeScheduler)
  36. }
  37. // GetStaticPodSpecs returns all staticPodSpecs actualized to the context of the current configuration
  38. // NB. this methods holds the information about how kubeadm creates static pod manifests.
  39. func GetStaticPodSpecs(cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint) map[string]v1.Pod {
  40. // Get the required hostpath mounts
  41. mounts := getHostPathVolumesForTheControlPlane(cfg)
  42. // Prepare static pod specs
  43. staticPodSpecs := map[string]v1.Pod{
  44. kubeadmconstants.KubeAPIServer: staticpodutil.ComponentPod(v1.Container{
  45. Name: kubeadmconstants.KubeAPIServer,
  46. Image: images.GetKubernetesImage(kubeadmconstants.KubeAPIServer, cfg),
  47. ImagePullPolicy: v1.PullIfNotPresent,
  48. Command: getAPIServerCommand(cfg, endpoint),
  49. VolumeMounts: staticpodutil.VolumeMountMapToSlice(mounts.GetVolumeMounts(kubeadmconstants.KubeAPIServer)),
  50. LivenessProbe: staticpodutil.LivenessProbe(staticpodutil.GetAPIServerProbeAddress(endpoint), "/healthz", int(endpoint.BindPort), v1.URISchemeHTTPS),
  51. Resources: staticpodutil.ComponentResources("250m"),
  52. Env: kubeadmutil.GetProxyEnvVars(),
  53. }, mounts.GetVolumes(kubeadmconstants.KubeAPIServer),
  54. map[string]string{kubeadmconstants.KubeAPIServerAdvertiseAddressEndpointAnnotationKey: endpoint.String()}),
  55. kubeadmconstants.KubeControllerManager: staticpodutil.ComponentPod(v1.Container{
  56. Name: kubeadmconstants.KubeControllerManager,
  57. Image: images.GetKubernetesImage(kubeadmconstants.KubeControllerManager, cfg),
  58. ImagePullPolicy: v1.PullIfNotPresent,
  59. Command: getControllerManagerCommand(cfg),
  60. VolumeMounts: staticpodutil.VolumeMountMapToSlice(mounts.GetVolumeMounts(kubeadmconstants.KubeControllerManager)),
  61. LivenessProbe: staticpodutil.LivenessProbe(staticpodutil.GetControllerManagerProbeAddress(cfg), "/healthz", kubeadmconstants.KubeControllerManagerPort, v1.URISchemeHTTPS),
  62. Resources: staticpodutil.ComponentResources("200m"),
  63. Env: kubeadmutil.GetProxyEnvVars(),
  64. }, mounts.GetVolumes(kubeadmconstants.KubeControllerManager), nil),
  65. kubeadmconstants.KubeScheduler: staticpodutil.ComponentPod(v1.Container{
  66. Name: kubeadmconstants.KubeScheduler,
  67. Image: images.GetKubernetesImage(kubeadmconstants.KubeScheduler, cfg),
  68. ImagePullPolicy: v1.PullIfNotPresent,
  69. Command: getSchedulerCommand(cfg),
  70. VolumeMounts: staticpodutil.VolumeMountMapToSlice(mounts.GetVolumeMounts(kubeadmconstants.KubeScheduler)),
  71. LivenessProbe: staticpodutil.LivenessProbe(staticpodutil.GetSchedulerProbeAddress(cfg), "/healthz", kubeadmconstants.KubeSchedulerPort, v1.URISchemeHTTPS),
  72. Resources: staticpodutil.ComponentResources("100m"),
  73. Env: kubeadmutil.GetProxyEnvVars(),
  74. }, mounts.GetVolumes(kubeadmconstants.KubeScheduler), nil),
  75. }
  76. return staticPodSpecs
  77. }
  78. // CreateStaticPodFiles creates all the requested static pod files.
  79. func CreateStaticPodFiles(manifestDir, kustomizeDir string, cfg *kubeadmapi.ClusterConfiguration, endpoint *kubeadmapi.APIEndpoint, componentNames ...string) error {
  80. // gets the StaticPodSpecs, actualized for the current ClusterConfiguration
  81. klog.V(1).Infoln("[control-plane] getting StaticPodSpecs")
  82. specs := GetStaticPodSpecs(cfg, endpoint)
  83. // creates required static pod specs
  84. for _, componentName := range componentNames {
  85. // retrieves the StaticPodSpec for given component
  86. spec, exists := specs[componentName]
  87. if !exists {
  88. return errors.Errorf("couldn't retrieve StaticPodSpec for %q", componentName)
  89. }
  90. // print all volumes that are mounted
  91. for _, v := range spec.Spec.Volumes {
  92. klog.V(2).Infof("[control-plane] adding volume %q for component %q", v.Name, componentName)
  93. }
  94. // if kustomizeDir is defined, customize the static pod manifest
  95. if kustomizeDir != "" {
  96. kustomizedSpec, err := staticpodutil.KustomizeStaticPod(&spec, kustomizeDir)
  97. if err != nil {
  98. return errors.Wrapf(err, "failed to kustomize static pod manifest file for %q", componentName)
  99. }
  100. spec = *kustomizedSpec
  101. }
  102. // writes the StaticPodSpec to disk
  103. if err := staticpodutil.WriteStaticPodToDisk(componentName, manifestDir, spec); err != nil {
  104. return errors.Wrapf(err, "failed to create static pod manifest file for %q", componentName)
  105. }
  106. klog.V(1).Infof("[control-plane] wrote static Pod manifest for component %q to %q\n", componentName, kubeadmconstants.GetStaticPodFilepath(componentName, manifestDir))
  107. }
  108. return nil
  109. }
  110. // getAPIServerCommand builds the right API server command from the given config object and version
  111. func getAPIServerCommand(cfg *kubeadmapi.ClusterConfiguration, localAPIEndpoint *kubeadmapi.APIEndpoint) []string {
  112. defaultArguments := map[string]string{
  113. "advertise-address": localAPIEndpoint.AdvertiseAddress,
  114. "insecure-port": "0",
  115. "enable-admission-plugins": "NodeRestriction",
  116. "service-cluster-ip-range": cfg.Networking.ServiceSubnet,
  117. "service-account-key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPublicKeyName),
  118. "client-ca-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.CACertName),
  119. "tls-cert-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerCertName),
  120. "tls-private-key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKeyName),
  121. "kubelet-client-certificate": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientCertName),
  122. "kubelet-client-key": filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientKeyName),
  123. "enable-bootstrap-token-auth": "true",
  124. "secure-port": fmt.Sprintf("%d", localAPIEndpoint.BindPort),
  125. "allow-privileged": "true",
  126. "kubelet-preferred-address-types": "InternalIP,ExternalIP,Hostname",
  127. // add options to configure the front proxy. Without the generated client cert, this will never be useable
  128. // so add it unconditionally with recommended values
  129. "requestheader-username-headers": "X-Remote-User",
  130. "requestheader-group-headers": "X-Remote-Group",
  131. "requestheader-extra-headers-prefix": "X-Remote-Extra-",
  132. "requestheader-client-ca-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertName),
  133. "requestheader-allowed-names": "front-proxy-client",
  134. "proxy-client-cert-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientCertName),
  135. "proxy-client-key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientKeyName),
  136. }
  137. command := []string{"kube-apiserver"}
  138. // If the user set endpoints for an external etcd cluster
  139. if cfg.Etcd.External != nil {
  140. defaultArguments["etcd-servers"] = strings.Join(cfg.Etcd.External.Endpoints, ",")
  141. // Use any user supplied etcd certificates
  142. if cfg.Etcd.External.CAFile != "" {
  143. defaultArguments["etcd-cafile"] = cfg.Etcd.External.CAFile
  144. }
  145. if cfg.Etcd.External.CertFile != "" && cfg.Etcd.External.KeyFile != "" {
  146. defaultArguments["etcd-certfile"] = cfg.Etcd.External.CertFile
  147. defaultArguments["etcd-keyfile"] = cfg.Etcd.External.KeyFile
  148. }
  149. } else {
  150. // Default to etcd static pod on localhost
  151. // localhost IP family should be the same that the AdvertiseAddress
  152. etcdLocalhostAddress := "127.0.0.1"
  153. if utilsnet.IsIPv6String(localAPIEndpoint.AdvertiseAddress) {
  154. etcdLocalhostAddress = "::1"
  155. }
  156. defaultArguments["etcd-servers"] = fmt.Sprintf("https://%s", net.JoinHostPort(etcdLocalhostAddress, strconv.Itoa(kubeadmconstants.EtcdListenClientPort)))
  157. defaultArguments["etcd-cafile"] = filepath.Join(cfg.CertificatesDir, kubeadmconstants.EtcdCACertName)
  158. defaultArguments["etcd-certfile"] = filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerEtcdClientCertName)
  159. defaultArguments["etcd-keyfile"] = filepath.Join(cfg.CertificatesDir, kubeadmconstants.APIServerEtcdClientKeyName)
  160. // Apply user configurations for local etcd
  161. if cfg.Etcd.Local != nil {
  162. if value, ok := cfg.Etcd.Local.ExtraArgs["advertise-client-urls"]; ok {
  163. defaultArguments["etcd-servers"] = value
  164. }
  165. }
  166. }
  167. // TODO: The following code should be removed after dual-stack is GA.
  168. // Note: The user still retains the ability to explicitly set feature-gates and that value will overwrite this base value.
  169. if enabled, present := cfg.FeatureGates[features.IPv6DualStack]; present {
  170. defaultArguments["feature-gates"] = fmt.Sprintf("%s=%t", features.IPv6DualStack, enabled)
  171. }
  172. if cfg.APIServer.ExtraArgs == nil {
  173. cfg.APIServer.ExtraArgs = map[string]string{}
  174. }
  175. cfg.APIServer.ExtraArgs["authorization-mode"] = getAuthzModes(cfg.APIServer.ExtraArgs["authorization-mode"])
  176. command = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.APIServer.ExtraArgs)...)
  177. return command
  178. }
  179. // getAuthzModes gets the authorization-related parameters to the api server
  180. // Node,RBAC is the default mode if nothing is passed to kubeadm. User provided modes override
  181. // the default.
  182. func getAuthzModes(authzModeExtraArgs string) string {
  183. defaultMode := []string{
  184. kubeadmconstants.ModeNode,
  185. kubeadmconstants.ModeRBAC,
  186. }
  187. if len(authzModeExtraArgs) > 0 {
  188. mode := []string{}
  189. for _, requested := range strings.Split(authzModeExtraArgs, ",") {
  190. if isValidAuthzMode(requested) {
  191. mode = append(mode, requested)
  192. } else {
  193. klog.Warningf("ignoring unknown kube-apiserver authorization-mode %q", requested)
  194. }
  195. }
  196. // only return the user provided mode if at least one was valid
  197. if len(mode) > 0 {
  198. klog.Warningf("the default kube-apiserver authorization-mode is %q; using %q",
  199. strings.Join(defaultMode, ","),
  200. strings.Join(mode, ","),
  201. )
  202. return strings.Join(mode, ",")
  203. }
  204. }
  205. return strings.Join(defaultMode, ",")
  206. }
  207. func isValidAuthzMode(authzMode string) bool {
  208. allModes := []string{
  209. kubeadmconstants.ModeNode,
  210. kubeadmconstants.ModeRBAC,
  211. kubeadmconstants.ModeWebhook,
  212. kubeadmconstants.ModeABAC,
  213. kubeadmconstants.ModeAlwaysAllow,
  214. kubeadmconstants.ModeAlwaysDeny,
  215. }
  216. for _, mode := range allModes {
  217. if authzMode == mode {
  218. return true
  219. }
  220. }
  221. return false
  222. }
  223. // calcNodeCidrSize determines the size of the subnets used on each node, based
  224. // on the pod subnet provided. For IPv4, we assume that the pod subnet will
  225. // be /16 and use /24. If the pod subnet cannot be parsed, the IPv4 value will
  226. // be used (/24).
  227. //
  228. // For IPv6, the algorithm will do two three. First, the node CIDR will be set
  229. // to a multiple of 8, using the available bits for easier readability by user.
  230. // Second, the number of nodes will be 512 to 64K to attempt to maximize the
  231. // number of nodes (see NOTE below). Third, pod networks of /113 and larger will
  232. // be rejected, as the amount of bits available is too small.
  233. //
  234. // A special case is when the pod network size is /112, where /120 will be used,
  235. // only allowing 256 nodes and 256 pods.
  236. //
  237. // If the pod network size is /113 or larger, the node CIDR will be set to the same
  238. // size and this will be rejected later in validation.
  239. //
  240. // NOTE: Currently, the design allows a maximum of 64K nodes. This algorithm splits
  241. // the available bits to maximize the number used for nodes, but still have the node
  242. // CIDR be a multiple of eight.
  243. //
  244. func calcNodeCidrSize(podSubnet string) (string, bool) {
  245. maskSize := "24"
  246. isIPv6 := false
  247. if ip, podCidr, err := net.ParseCIDR(podSubnet); err == nil {
  248. if utilsnet.IsIPv6(ip) {
  249. var nodeCidrSize int
  250. isIPv6 = true
  251. podNetSize, totalBits := podCidr.Mask.Size()
  252. switch {
  253. case podNetSize == 112:
  254. // Special case, allows 256 nodes, 256 pods/node
  255. nodeCidrSize = 120
  256. case podNetSize < 112:
  257. // Use multiple of 8 for node CIDR, with 512 to 64K nodes
  258. nodeCidrSize = totalBits - ((totalBits-podNetSize-1)/8-1)*8
  259. default:
  260. // Not enough bits, will fail later, when validate
  261. nodeCidrSize = podNetSize
  262. }
  263. maskSize = strconv.Itoa(nodeCidrSize)
  264. }
  265. }
  266. return maskSize, isIPv6
  267. }
  268. // getControllerManagerCommand builds the right controller manager command from the given config object and version
  269. func getControllerManagerCommand(cfg *kubeadmapi.ClusterConfiguration) []string {
  270. kubeconfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ControllerManagerKubeConfigFileName)
  271. caFile := filepath.Join(cfg.CertificatesDir, kubeadmconstants.CACertName)
  272. defaultArguments := map[string]string{
  273. "bind-address": "127.0.0.1",
  274. "leader-elect": "true",
  275. "kubeconfig": kubeconfigFile,
  276. "authentication-kubeconfig": kubeconfigFile,
  277. "authorization-kubeconfig": kubeconfigFile,
  278. "client-ca-file": caFile,
  279. "requestheader-client-ca-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertName),
  280. "root-ca-file": caFile,
  281. "service-account-private-key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPrivateKeyName),
  282. "cluster-signing-cert-file": caFile,
  283. "cluster-signing-key-file": filepath.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName),
  284. "use-service-account-credentials": "true",
  285. "controllers": "*,bootstrapsigner,tokencleaner",
  286. }
  287. // If using external CA, pass empty string to controller manager instead of ca.key/ca.crt path,
  288. // so that the csrsigning controller fails to start
  289. if res, _ := certphase.UsingExternalCA(cfg); res {
  290. defaultArguments["cluster-signing-key-file"] = ""
  291. defaultArguments["cluster-signing-cert-file"] = ""
  292. }
  293. // Let the controller-manager allocate Node CIDRs for the Pod network.
  294. // Each node will get a subspace of the address CIDR provided with --pod-network-cidr.
  295. if cfg.Networking.PodSubnet != "" {
  296. defaultArguments["allocate-node-cidrs"] = "true"
  297. defaultArguments["cluster-cidr"] = cfg.Networking.PodSubnet
  298. if cfg.Networking.ServiceSubnet != "" {
  299. defaultArguments["service-cluster-ip-range"] = cfg.Networking.ServiceSubnet
  300. }
  301. }
  302. // Set cluster name
  303. if cfg.ClusterName != "" {
  304. defaultArguments["cluster-name"] = cfg.ClusterName
  305. }
  306. // TODO: The following code should be remvoved after dual-stack is GA.
  307. // Note: The user still retains the ability to explicitly set feature-gates and that value will overwrite this base value.
  308. enabled, present := cfg.FeatureGates[features.IPv6DualStack]
  309. if present {
  310. defaultArguments["feature-gates"] = fmt.Sprintf("%s=%t", features.IPv6DualStack, enabled)
  311. }
  312. if cfg.Networking.PodSubnet != "" {
  313. if enabled {
  314. // any errors will be caught during validation
  315. subnets := strings.Split(cfg.Networking.PodSubnet, ",")
  316. for _, podSubnet := range subnets {
  317. if maskSize, isIPv6 := calcNodeCidrSize(podSubnet); isIPv6 {
  318. defaultArguments["node-cidr-mask-size-ipv6"] = maskSize
  319. } else {
  320. defaultArguments["node-cidr-mask-size-ipv4"] = maskSize
  321. }
  322. }
  323. } else {
  324. maskSize, _ := calcNodeCidrSize(cfg.Networking.PodSubnet)
  325. defaultArguments["node-cidr-mask-size"] = maskSize
  326. }
  327. }
  328. command := []string{"kube-controller-manager"}
  329. command = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.ControllerManager.ExtraArgs)...)
  330. return command
  331. }
  332. // getSchedulerCommand builds the right scheduler command from the given config object and version
  333. func getSchedulerCommand(cfg *kubeadmapi.ClusterConfiguration) []string {
  334. kubeconfigFile := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.SchedulerKubeConfigFileName)
  335. defaultArguments := map[string]string{
  336. "bind-address": "127.0.0.1",
  337. "leader-elect": "true",
  338. "kubeconfig": kubeconfigFile,
  339. "authentication-kubeconfig": kubeconfigFile,
  340. "authorization-kubeconfig": kubeconfigFile,
  341. }
  342. // TODO: The following code should be remvoved after dual-stack is GA.
  343. // Note: The user still retains the ability to explicitly set feature-gates and that value will overwrite this base value.
  344. if enabled, present := cfg.FeatureGates[features.IPv6DualStack]; present {
  345. defaultArguments["feature-gates"] = fmt.Sprintf("%s=%t", features.IPv6DualStack, enabled)
  346. }
  347. command := []string{"kube-scheduler"}
  348. command = append(command, kubeadmutil.BuildArgumentListFromMap(defaultArguments, cfg.Scheduler.ExtraArgs)...)
  349. return command
  350. }