constants.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*
  2. Copyright 2019 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 constants
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "net"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "strings"
  22. "time"
  23. "github.com/pkg/errors"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/util/version"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. bootstrapapi "k8s.io/cluster-bootstrap/token/api"
  28. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  29. utilnet "k8s.io/utils/net"
  30. )
  31. const (
  32. // KubernetesDir is the directory Kubernetes owns for storing various configuration files
  33. KubernetesDir = "/etc/kubernetes"
  34. // ManifestsSubDirName defines directory name to store manifests
  35. ManifestsSubDirName = "manifests"
  36. // TempDirForKubeadm defines temporary directory for kubeadm
  37. // should be joined with KubernetesDir.
  38. TempDirForKubeadm = "tmp"
  39. // CertificateValidity defines the validity for all the signed certificates generated by kubeadm
  40. CertificateValidity = time.Hour * 24 * 365
  41. // CACertAndKeyBaseName defines certificate authority base name
  42. CACertAndKeyBaseName = "ca"
  43. // CACertName defines certificate name
  44. CACertName = "ca.crt"
  45. // CAKeyName defines certificate name
  46. CAKeyName = "ca.key"
  47. // APIServerCertAndKeyBaseName defines API's server certificate and key base name
  48. APIServerCertAndKeyBaseName = "apiserver"
  49. // APIServerCertName defines API's server certificate name
  50. APIServerCertName = "apiserver.crt"
  51. // APIServerKeyName defines API's server key name
  52. APIServerKeyName = "apiserver.key"
  53. // APIServerCertCommonName defines API's server certificate common name (CN)
  54. APIServerCertCommonName = "kube-apiserver"
  55. // APIServerKubeletClientCertAndKeyBaseName defines kubelet client certificate and key base name
  56. APIServerKubeletClientCertAndKeyBaseName = "apiserver-kubelet-client"
  57. // APIServerKubeletClientCertName defines kubelet client certificate name
  58. APIServerKubeletClientCertName = "apiserver-kubelet-client.crt"
  59. // APIServerKubeletClientKeyName defines kubelet client key name
  60. APIServerKubeletClientKeyName = "apiserver-kubelet-client.key"
  61. // APIServerKubeletClientCertCommonName defines kubelet client certificate common name (CN)
  62. APIServerKubeletClientCertCommonName = "kube-apiserver-kubelet-client"
  63. // EtcdCACertAndKeyBaseName defines etcd's CA certificate and key base name
  64. EtcdCACertAndKeyBaseName = "etcd/ca"
  65. // EtcdCACertName defines etcd's CA certificate name
  66. EtcdCACertName = "etcd/ca.crt"
  67. // EtcdCAKeyName defines etcd's CA key name
  68. EtcdCAKeyName = "etcd/ca.key"
  69. // EtcdServerCertAndKeyBaseName defines etcd's server certificate and key base name
  70. EtcdServerCertAndKeyBaseName = "etcd/server"
  71. // EtcdServerCertName defines etcd's server certificate name
  72. EtcdServerCertName = "etcd/server.crt"
  73. // EtcdServerKeyName defines etcd's server key name
  74. EtcdServerKeyName = "etcd/server.key"
  75. // EtcdListenClientPort defines the port etcd listen on for client traffic
  76. EtcdListenClientPort = 2379
  77. // EtcdMetricsPort is the port at which to obtain etcd metrics and health status
  78. EtcdMetricsPort = 2381
  79. // EtcdPeerCertAndKeyBaseName defines etcd's peer certificate and key base name
  80. EtcdPeerCertAndKeyBaseName = "etcd/peer"
  81. // EtcdPeerCertName defines etcd's peer certificate name
  82. EtcdPeerCertName = "etcd/peer.crt"
  83. // EtcdPeerKeyName defines etcd's peer key name
  84. EtcdPeerKeyName = "etcd/peer.key"
  85. // EtcdListenPeerPort defines the port etcd listen on for peer traffic
  86. EtcdListenPeerPort = 2380
  87. // EtcdHealthcheckClientCertAndKeyBaseName defines etcd's healthcheck client certificate and key base name
  88. EtcdHealthcheckClientCertAndKeyBaseName = "etcd/healthcheck-client"
  89. // EtcdHealthcheckClientCertName defines etcd's healthcheck client certificate name
  90. EtcdHealthcheckClientCertName = "etcd/healthcheck-client.crt"
  91. // EtcdHealthcheckClientKeyName defines etcd's healthcheck client key name
  92. EtcdHealthcheckClientKeyName = "etcd/healthcheck-client.key"
  93. // EtcdHealthcheckClientCertCommonName defines etcd's healthcheck client certificate common name (CN)
  94. EtcdHealthcheckClientCertCommonName = "kube-etcd-healthcheck-client"
  95. // APIServerEtcdClientCertAndKeyBaseName defines apiserver's etcd client certificate and key base name
  96. APIServerEtcdClientCertAndKeyBaseName = "apiserver-etcd-client"
  97. // APIServerEtcdClientCertName defines apiserver's etcd client certificate name
  98. APIServerEtcdClientCertName = "apiserver-etcd-client.crt"
  99. // APIServerEtcdClientKeyName defines apiserver's etcd client key name
  100. APIServerEtcdClientKeyName = "apiserver-etcd-client.key"
  101. // APIServerEtcdClientCertCommonName defines apiserver's etcd client certificate common name (CN)
  102. APIServerEtcdClientCertCommonName = "kube-apiserver-etcd-client"
  103. // ServiceAccountKeyBaseName defines SA key base name
  104. ServiceAccountKeyBaseName = "sa"
  105. // ServiceAccountPublicKeyName defines SA public key base name
  106. ServiceAccountPublicKeyName = "sa.pub"
  107. // ServiceAccountPrivateKeyName defines SA private key base name
  108. ServiceAccountPrivateKeyName = "sa.key"
  109. // FrontProxyCACertAndKeyBaseName defines front proxy CA certificate and key base name
  110. FrontProxyCACertAndKeyBaseName = "front-proxy-ca"
  111. // FrontProxyCACertName defines front proxy CA certificate name
  112. FrontProxyCACertName = "front-proxy-ca.crt"
  113. // FrontProxyCAKeyName defines front proxy CA key name
  114. FrontProxyCAKeyName = "front-proxy-ca.key"
  115. // FrontProxyClientCertAndKeyBaseName defines front proxy certificate and key base name
  116. FrontProxyClientCertAndKeyBaseName = "front-proxy-client"
  117. // FrontProxyClientCertName defines front proxy certificate name
  118. FrontProxyClientCertName = "front-proxy-client.crt"
  119. // FrontProxyClientKeyName defines front proxy key name
  120. FrontProxyClientKeyName = "front-proxy-client.key"
  121. // FrontProxyClientCertCommonName defines front proxy certificate common name
  122. FrontProxyClientCertCommonName = "front-proxy-client" //used as subject.commonname attribute (CN)
  123. // AdminKubeConfigFileName defines name for the kubeconfig aimed to be used by the superuser/admin of the cluster
  124. AdminKubeConfigFileName = "admin.conf"
  125. // KubeletBootstrapKubeConfigFileName defines the file name for the kubeconfig that the kubelet will use to do
  126. // the TLS bootstrap to get itself an unique credential
  127. KubeletBootstrapKubeConfigFileName = "bootstrap-kubelet.conf"
  128. // KubeletKubeConfigFileName defines the file name for the kubeconfig that the control-plane kubelet will use for talking
  129. // to the API server
  130. KubeletKubeConfigFileName = "kubelet.conf"
  131. // ControllerManagerKubeConfigFileName defines the file name for the controller manager's kubeconfig file
  132. ControllerManagerKubeConfigFileName = "controller-manager.conf"
  133. // SchedulerKubeConfigFileName defines the file name for the scheduler's kubeconfig file
  134. SchedulerKubeConfigFileName = "scheduler.conf"
  135. // Some well-known users and groups in the core Kubernetes authorization system
  136. // ControllerManagerUser defines the well-known user the controller-manager should be authenticated as
  137. ControllerManagerUser = "system:kube-controller-manager"
  138. // SchedulerUser defines the well-known user the scheduler should be authenticated as
  139. SchedulerUser = "system:kube-scheduler"
  140. // SystemPrivilegedGroup defines the well-known group for the apiservers. This group is also superuser by default
  141. // (i.e. bound to the cluster-admin ClusterRole)
  142. SystemPrivilegedGroup = "system:masters"
  143. // NodesGroup defines the well-known group for all nodes.
  144. NodesGroup = "system:nodes"
  145. // NodesUserPrefix defines the user name prefix as requested by the Node authorizer.
  146. NodesUserPrefix = "system:node:"
  147. // NodesClusterRoleBinding defines the well-known ClusterRoleBinding which binds the too permissive system:node
  148. // ClusterRole to the system:nodes group. Since kubeadm is using the Node Authorizer, this ClusterRoleBinding's
  149. // system:nodes group subject is removed if present.
  150. NodesClusterRoleBinding = "system:node"
  151. // APICallRetryInterval defines how long kubeadm should wait before retrying a failed API operation
  152. APICallRetryInterval = 500 * time.Millisecond
  153. // DiscoveryRetryInterval specifies how long kubeadm should wait before retrying to connect to the control-plane when doing discovery
  154. DiscoveryRetryInterval = 5 * time.Second
  155. // PatchNodeTimeout specifies how long kubeadm should wait for applying the label and taint on the control-plane before timing out
  156. PatchNodeTimeout = 2 * time.Minute
  157. // TLSBootstrapTimeout specifies how long kubeadm should wait for the kubelet to perform the TLS Bootstrap
  158. TLSBootstrapTimeout = 2 * time.Minute
  159. // PullImageRetry specifies how many times ContainerRuntime retries when pulling image failed
  160. PullImageRetry = 5
  161. // PrepullImagesInParallelTimeout specifies how long kubeadm should wait for prepulling images in parallel before timing out
  162. PrepullImagesInParallelTimeout = 10 * time.Second
  163. // DefaultControlPlaneTimeout specifies the default control plane (actually API Server) timeout for use by kubeadm
  164. DefaultControlPlaneTimeout = 4 * time.Minute
  165. // MinimumAddressesInServiceSubnet defines minimum amount of nodes the Service subnet should allow.
  166. // We need at least ten, because the DNS service is always at the tenth cluster clusterIP
  167. MinimumAddressesInServiceSubnet = 10
  168. // DefaultTokenDuration specifies the default amount of time that a bootstrap token will be valid
  169. // Default behaviour is 24 hours
  170. DefaultTokenDuration = 24 * time.Hour
  171. // DefaultCertTokenDuration specifies the default amount of time that the token used by upload certs will be valid
  172. // Default behaviour is 2 hours
  173. DefaultCertTokenDuration = 2 * time.Hour
  174. // CertificateKeySize specifies the size of the key used to encrypt certificates on uploadcerts phase
  175. CertificateKeySize = 32
  176. // LabelNodeRoleMaster specifies that a node is a control-plane
  177. // This is a duplicate definition of the constant in pkg/controller/service/controller.go
  178. LabelNodeRoleMaster = "node-role.kubernetes.io/master"
  179. // AnnotationKubeadmCRISocket specifies the annotation kubeadm uses to preserve the crisocket information given to kubeadm at
  180. // init/join time for use later. kubeadm annotates the node object with this information
  181. AnnotationKubeadmCRISocket = "kubeadm.alpha.kubernetes.io/cri-socket"
  182. // KubeadmConfigConfigMap specifies in what ConfigMap in the kube-system namespace the `kubeadm init` configuration should be stored
  183. KubeadmConfigConfigMap = "kubeadm-config"
  184. // ClusterConfigurationConfigMapKey specifies in what ConfigMap key the cluster configuration should be stored
  185. ClusterConfigurationConfigMapKey = "ClusterConfiguration"
  186. // ClusterStatusConfigMapKey specifies in what ConfigMap key the cluster status should be stored
  187. ClusterStatusConfigMapKey = "ClusterStatus"
  188. // KubeProxyConfigMap specifies in what ConfigMap in the kube-system namespace the kube-proxy configuration should be stored
  189. KubeProxyConfigMap = "kube-proxy"
  190. // KubeProxyConfigMapKey specifies in what ConfigMap key the component config of kube-proxy should be stored
  191. KubeProxyConfigMapKey = "config.conf"
  192. // KubeletBaseConfigurationConfigMapPrefix specifies in what ConfigMap in the kube-system namespace the initial remote configuration of kubelet should be stored
  193. KubeletBaseConfigurationConfigMapPrefix = "kubelet-config-"
  194. // KubeletBaseConfigurationConfigMapKey specifies in what ConfigMap key the initial remote configuration of kubelet should be stored
  195. KubeletBaseConfigurationConfigMapKey = "kubelet"
  196. // KubeletBaseConfigMapRolePrefix defines the base kubelet configuration ConfigMap.
  197. KubeletBaseConfigMapRolePrefix = "kubeadm:kubelet-config-"
  198. // KubeletRunDirectory specifies the directory where the kubelet runtime information is stored.
  199. KubeletRunDirectory = "/var/lib/kubelet"
  200. // KubeletConfigurationFileName specifies the file name on the node which stores initial remote configuration of kubelet
  201. // This file should exist under KubeletRunDirectory
  202. KubeletConfigurationFileName = "config.yaml"
  203. // DynamicKubeletConfigurationDirectoryName specifies the directory which stores the dynamic configuration checkpoints for the kubelet
  204. // This directory should exist under KubeletRunDirectory
  205. DynamicKubeletConfigurationDirectoryName = "dynamic-config"
  206. // KubeletEnvFileName is a file "kubeadm init" writes at runtime. Using that interface, kubeadm can customize certain
  207. // kubelet flags conditionally based on the environment at runtime. Also, parameters given to the configuration file
  208. // might be passed through this file. "kubeadm init" writes one variable, with the name ${KubeletEnvFileVariableName}.
  209. // This file should exist under KubeletRunDirectory
  210. KubeletEnvFileName = "kubeadm-flags.env"
  211. // KubeletEnvFileVariableName specifies the shell script variable name "kubeadm init" should write a value to in KubeletEnvFile
  212. KubeletEnvFileVariableName = "KUBELET_KUBEADM_ARGS"
  213. // KubeletHealthzPort is the port of the kubelet healthz endpoint
  214. KubeletHealthzPort = 10248
  215. // MinExternalEtcdVersion indicates minimum external etcd version which kubeadm supports
  216. MinExternalEtcdVersion = "3.2.18"
  217. // DefaultEtcdVersion indicates the default etcd version that kubeadm uses
  218. DefaultEtcdVersion = "3.4.3-0"
  219. // PauseVersion indicates the default pause image version for kubeadm
  220. PauseVersion = "3.2"
  221. // Etcd defines variable used internally when referring to etcd component
  222. Etcd = "etcd"
  223. // KubeAPIServer defines variable used internally when referring to kube-apiserver component
  224. KubeAPIServer = "kube-apiserver"
  225. // KubeControllerManager defines variable used internally when referring to kube-controller-manager component
  226. KubeControllerManager = "kube-controller-manager"
  227. // KubeScheduler defines variable used internally when referring to kube-scheduler component
  228. KubeScheduler = "kube-scheduler"
  229. // KubeProxy defines variable used internally when referring to kube-proxy component
  230. KubeProxy = "kube-proxy"
  231. // HyperKube defines variable used internally when referring to the hyperkube image
  232. HyperKube = "hyperkube"
  233. // SelfHostingPrefix describes the prefix workloads that are self-hosted by kubeadm has
  234. SelfHostingPrefix = "self-hosted-"
  235. // KubeCertificatesVolumeName specifies the name for the Volume that is used for injecting certificates to control plane components (can be both a hostPath volume or a projected, all-in-one volume)
  236. KubeCertificatesVolumeName = "k8s-certs"
  237. // KubeConfigVolumeName specifies the name for the Volume that is used for injecting the kubeconfig to talk securely to the api server for a control plane component if applicable
  238. KubeConfigVolumeName = "kubeconfig"
  239. // NodeBootstrapTokenAuthGroup specifies which group a Node Bootstrap Token should be authenticated in
  240. NodeBootstrapTokenAuthGroup = "system:bootstrappers:kubeadm:default-node-token"
  241. // DefaultCIImageRepository points to image registry where CI uploads images from ci-cross build job
  242. DefaultCIImageRepository = "gcr.io/kubernetes-ci-images"
  243. // CoreDNSConfigMap specifies in what ConfigMap in the kube-system namespace the CoreDNS config should be stored
  244. CoreDNSConfigMap = "coredns"
  245. // CoreDNSDeploymentName specifies the name of the Deployment for CoreDNS add-on
  246. CoreDNSDeploymentName = "coredns"
  247. // CoreDNSImageName specifies the name of the image for CoreDNS add-on
  248. CoreDNSImageName = "coredns"
  249. // KubeDNSConfigMap specifies in what ConfigMap in the kube-system namespace the kube-dns config should be stored
  250. KubeDNSConfigMap = "kube-dns"
  251. // KubeDNSDeploymentName specifies the name of the Deployment for kube-dns add-on
  252. KubeDNSDeploymentName = "kube-dns"
  253. // KubeDNSKubeDNSImageName specifies the name of the image for the kubedns container in the kube-dns add-on
  254. KubeDNSKubeDNSImageName = "k8s-dns-kube-dns"
  255. // KubeDNSSidecarImageName specifies the name of the image for the sidecar container in the kube-dns add-on
  256. KubeDNSSidecarImageName = "k8s-dns-sidecar"
  257. // KubeDNSDnsMasqNannyImageName specifies the name of the image for the dnsmasq container in the kube-dns add-on
  258. KubeDNSDnsMasqNannyImageName = "k8s-dns-dnsmasq-nanny"
  259. // AuditPolicyDir is the directory that will contain the audit policy
  260. AuditPolicyDir = "audit"
  261. // AuditPolicyFile is the name of the audit policy file itself
  262. AuditPolicyFile = "audit.yaml"
  263. // StaticPodAuditPolicyLogDir is the name of the directory in the static pod that will have the audit logs
  264. StaticPodAuditPolicyLogDir = "/var/log/kubernetes/audit"
  265. // LeaseEndpointReconcilerType will select a storage based reconciler
  266. // Copied from pkg/master/reconcilers to avoid pulling extra dependencies
  267. // TODO: Import this constant from a consts only package, that does not pull any further dependencies.
  268. LeaseEndpointReconcilerType = "lease"
  269. // KubeDNSVersion is the version of kube-dns to be deployed if it is used
  270. KubeDNSVersion = "1.14.13"
  271. // CoreDNSVersion is the version of CoreDNS to be deployed if it is used
  272. CoreDNSVersion = "1.6.7"
  273. // ClusterConfigurationKind is the string kind value for the ClusterConfiguration struct
  274. ClusterConfigurationKind = "ClusterConfiguration"
  275. // InitConfigurationKind is the string kind value for the InitConfiguration struct
  276. InitConfigurationKind = "InitConfiguration"
  277. // JoinConfigurationKind is the string kind value for the JoinConfiguration struct
  278. JoinConfigurationKind = "JoinConfiguration"
  279. // YAMLDocumentSeparator is the separator for YAML documents
  280. // TODO: Find a better place for this constant
  281. YAMLDocumentSeparator = "---\n"
  282. // DefaultAPIServerBindAddress is the default bind address for the API Server
  283. DefaultAPIServerBindAddress = "0.0.0.0"
  284. // ControlPlaneNumCPU is the number of CPUs required on control-plane
  285. ControlPlaneNumCPU = 2
  286. // KubeadmCertsSecret specifies in what Secret in the kube-system namespace the certificates should be stored
  287. KubeadmCertsSecret = "kubeadm-certs"
  288. // KubeletPort is the default port for the kubelet server on each host machine.
  289. // May be overridden by a flag at startup.
  290. KubeletPort = 10250
  291. // KubeSchedulerPort is the default port for the scheduler status server.
  292. // May be overridden by a flag at startup.
  293. KubeSchedulerPort = 10259
  294. // KubeControllerManagerPort is the default port for the controller manager status server.
  295. // May be overridden by a flag at startup.
  296. KubeControllerManagerPort = 10257
  297. // EtcdAdvertiseClientUrlsAnnotationKey is the annotation key on every etcd pod, describing the
  298. // advertise client URLs
  299. EtcdAdvertiseClientUrlsAnnotationKey = "kubeadm.kubernetes.io/etcd.advertise-client-urls"
  300. // KubeAPIServerAdvertiseAddressEndpointAnnotationKey is the annotation key on every apiserver pod,
  301. // describing the API endpoint (advertise address and bind port of the api server)
  302. KubeAPIServerAdvertiseAddressEndpointAnnotationKey = "kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint"
  303. // ControlPlaneTier is the value used in the tier label to identify control plane components
  304. ControlPlaneTier = "control-plane"
  305. // Mode* constants were copied from pkg/kubeapiserver/authorizer/modes
  306. // to avoid kubeadm dependency on the internal module
  307. // TODO: share Mode* constants in component config
  308. // ModeAlwaysAllow is the mode to set all requests as authorized
  309. ModeAlwaysAllow string = "AlwaysAllow"
  310. // ModeAlwaysDeny is the mode to set no requests as authorized
  311. ModeAlwaysDeny string = "AlwaysDeny"
  312. // ModeABAC is the mode to use Attribute Based Access Control to authorize
  313. ModeABAC string = "ABAC"
  314. // ModeWebhook is the mode to make an external webhook call to authorize
  315. ModeWebhook string = "Webhook"
  316. // ModeRBAC is the mode to use Role Based Access Control to authorize
  317. ModeRBAC string = "RBAC"
  318. // ModeNode is an authorization mode that authorizes API requests made by kubelets.
  319. ModeNode string = "Node"
  320. )
  321. var (
  322. // ControlPlaneTaint is the taint to apply on the PodSpec for being able to run that Pod on the control-plane
  323. ControlPlaneTaint = v1.Taint{
  324. Key: LabelNodeRoleMaster,
  325. Effect: v1.TaintEffectNoSchedule,
  326. }
  327. // ControlPlaneToleration is the toleration to apply on the PodSpec for being able to run that Pod on the control-plane
  328. ControlPlaneToleration = v1.Toleration{
  329. Key: LabelNodeRoleMaster,
  330. Effect: v1.TaintEffectNoSchedule,
  331. }
  332. // DefaultTokenUsages specifies the default functions a token will get
  333. DefaultTokenUsages = bootstrapapi.KnownTokenUsages
  334. // DefaultTokenGroups specifies the default groups that this token will authenticate as when used for authentication
  335. DefaultTokenGroups = []string{NodeBootstrapTokenAuthGroup}
  336. // ControlPlaneComponents defines the control-plane component names
  337. ControlPlaneComponents = []string{KubeAPIServer, KubeControllerManager, KubeScheduler}
  338. // MinimumControlPlaneVersion specifies the minimum control plane version kubeadm can deploy
  339. MinimumControlPlaneVersion = version.MustParseSemantic("v1.17.0")
  340. // MinimumKubeletVersion specifies the minimum version of kubelet which kubeadm supports
  341. MinimumKubeletVersion = version.MustParseSemantic("v1.17.0")
  342. // CurrentKubernetesVersion specifies current Kubernetes version supported by kubeadm
  343. CurrentKubernetesVersion = version.MustParseSemantic("v1.18.0")
  344. // SupportedEtcdVersion lists officially supported etcd versions with corresponding Kubernetes releases
  345. SupportedEtcdVersion = map[uint8]string{
  346. 13: "3.2.24",
  347. 14: "3.3.10",
  348. 15: "3.3.10",
  349. 16: "3.3.17-0",
  350. 17: "3.4.3-0",
  351. 18: "3.4.3-0",
  352. 19: "3.4.3-0",
  353. }
  354. // KubeadmCertsClusterRoleName sets the name for the ClusterRole that allows
  355. // the bootstrap tokens to access the kubeadm-certs Secret during the join of a new control-plane
  356. KubeadmCertsClusterRoleName = fmt.Sprintf("kubeadm:%s", KubeadmCertsSecret)
  357. // StaticPodMirroringDefaultRetry is used a backoff strategy for
  358. // waiting for static pods to be mirrored to the apiserver.
  359. StaticPodMirroringDefaultRetry = wait.Backoff{
  360. Steps: 30,
  361. Duration: 1 * time.Second,
  362. Factor: 1.0,
  363. Jitter: 0.1,
  364. }
  365. )
  366. // EtcdSupportedVersion returns officially supported version of etcd for a specific Kubernetes release
  367. // If passed version is not in the given list, the function returns the nearest version with a warning
  368. func EtcdSupportedVersion(supportedEtcdVersion map[uint8]string, versionString string) (etcdVersion *version.Version, warning, err error) {
  369. kubernetesVersion, err := version.ParseSemantic(versionString)
  370. if err != nil {
  371. return nil, nil, err
  372. }
  373. desiredVersion, etcdStringVersion := uint8(kubernetesVersion.Minor()), ""
  374. min, max := ^uint8(0), uint8(0)
  375. for k, v := range supportedEtcdVersion {
  376. if desiredVersion == k {
  377. etcdStringVersion = v
  378. break
  379. }
  380. if k < min {
  381. min = k
  382. }
  383. if k > max {
  384. max = k
  385. }
  386. }
  387. if len(etcdStringVersion) == 0 {
  388. if desiredVersion < min {
  389. etcdStringVersion = supportedEtcdVersion[min]
  390. }
  391. if desiredVersion > max {
  392. etcdStringVersion = supportedEtcdVersion[max]
  393. }
  394. warning = fmt.Errorf("could not find officially supported version of etcd for Kubernetes %s, falling back to the nearest etcd version (%s)",
  395. versionString, etcdStringVersion)
  396. }
  397. etcdVersion, err = version.ParseSemantic(etcdStringVersion)
  398. if err != nil {
  399. return nil, nil, err
  400. }
  401. return etcdVersion, warning, nil
  402. }
  403. // GetStaticPodDirectory returns the location on the disk where the Static Pod should be present
  404. func GetStaticPodDirectory() string {
  405. return filepath.Join(KubernetesDir, ManifestsSubDirName)
  406. }
  407. // GetStaticPodFilepath returns the location on the disk where the Static Pod should be present
  408. func GetStaticPodFilepath(componentName, manifestsDir string) string {
  409. return filepath.Join(manifestsDir, componentName+".yaml")
  410. }
  411. // GetAdminKubeConfigPath returns the location on the disk where admin kubeconfig is located by default
  412. func GetAdminKubeConfigPath() string {
  413. return filepath.Join(KubernetesDir, AdminKubeConfigFileName)
  414. }
  415. // GetBootstrapKubeletKubeConfigPath returns the location on the disk where bootstrap kubelet kubeconfig is located by default
  416. func GetBootstrapKubeletKubeConfigPath() string {
  417. return filepath.Join(KubernetesDir, KubeletBootstrapKubeConfigFileName)
  418. }
  419. // GetKubeletKubeConfigPath returns the location on the disk where kubelet kubeconfig is located by default
  420. func GetKubeletKubeConfigPath() string {
  421. return filepath.Join(KubernetesDir, KubeletKubeConfigFileName)
  422. }
  423. // AddSelfHostedPrefix adds the self-hosted- prefix to the component name
  424. func AddSelfHostedPrefix(componentName string) string {
  425. return fmt.Sprintf("%s%s", SelfHostingPrefix, componentName)
  426. }
  427. // CreateTempDirForKubeadm is a function that creates a temporary directory under /etc/kubernetes/tmp (not using /tmp as that would potentially be dangerous)
  428. func CreateTempDirForKubeadm(kubernetesDir, dirName string) (string, error) {
  429. tempDir := path.Join(KubernetesDir, TempDirForKubeadm)
  430. if len(kubernetesDir) != 0 {
  431. tempDir = path.Join(kubernetesDir, TempDirForKubeadm)
  432. }
  433. // creates target folder if not already exists
  434. if err := os.MkdirAll(tempDir, 0700); err != nil {
  435. return "", errors.Wrapf(err, "failed to create directory %q", tempDir)
  436. }
  437. tempDir, err := ioutil.TempDir(tempDir, dirName)
  438. if err != nil {
  439. return "", errors.Wrap(err, "couldn't create a temporary directory")
  440. }
  441. return tempDir, nil
  442. }
  443. // CreateTimestampDirForKubeadm is a function that creates a temporary directory under /etc/kubernetes/tmp formatted with the current date
  444. func CreateTimestampDirForKubeadm(kubernetesDir, dirName string) (string, error) {
  445. tempDir := path.Join(KubernetesDir, TempDirForKubeadm)
  446. if len(kubernetesDir) != 0 {
  447. tempDir = path.Join(kubernetesDir, TempDirForKubeadm)
  448. }
  449. // creates target folder if not already exists
  450. if err := os.MkdirAll(tempDir, 0700); err != nil {
  451. return "", errors.Wrapf(err, "failed to create directory %q", tempDir)
  452. }
  453. timestampDirName := fmt.Sprintf("%s-%s", dirName, time.Now().Format("2006-01-02-15-04-05"))
  454. timestampDir := path.Join(tempDir, timestampDirName)
  455. if err := os.Mkdir(timestampDir, 0700); err != nil {
  456. return "", errors.Wrap(err, "could not create timestamp directory")
  457. }
  458. return timestampDir, nil
  459. }
  460. // GetDNSIP returns a dnsIP, which is 10th IP in svcSubnet CIDR range
  461. func GetDNSIP(svcSubnetList string, isDualStack bool) (net.IP, error) {
  462. // Get the service subnet CIDR
  463. svcSubnetCIDR, err := GetKubernetesServiceCIDR(svcSubnetList, isDualStack)
  464. if err != nil {
  465. return nil, errors.Wrapf(err, "unable to get internal Kubernetes Service IP from the given service CIDR (%s)", svcSubnetList)
  466. }
  467. // Selects the 10th IP in service subnet CIDR range as dnsIP
  468. dnsIP, err := utilnet.GetIndexedIP(svcSubnetCIDR, 10)
  469. if err != nil {
  470. return nil, errors.Wrap(err, "unable to get internal Kubernetes Service IP from the given service CIDR")
  471. }
  472. return dnsIP, nil
  473. }
  474. // GetKubernetesServiceCIDR returns the default Service CIDR for the Kubernetes internal service
  475. func GetKubernetesServiceCIDR(svcSubnetList string, isDualStack bool) (*net.IPNet, error) {
  476. if isDualStack {
  477. // The default service address family for the cluster is the address family of the first
  478. // service cluster IP range configured via the `--service-cluster-ip-range` flag
  479. // of the kube-controller-manager and kube-apiserver.
  480. svcSubnets, err := utilnet.ParseCIDRs(strings.Split(svcSubnetList, ","))
  481. if err != nil {
  482. return nil, errors.Wrapf(err, "unable to parse ServiceSubnet %v", svcSubnetList)
  483. }
  484. if len(svcSubnets) == 0 {
  485. return nil, errors.New("received empty ServiceSubnet for dual-stack")
  486. }
  487. return svcSubnets[0], nil
  488. }
  489. // internal IP address for the API server
  490. _, svcSubnet, err := net.ParseCIDR(svcSubnetList)
  491. if err != nil {
  492. return nil, errors.Wrapf(err, "unable to parse ServiceSubnet %v", svcSubnetList)
  493. }
  494. return svcSubnet, nil
  495. }
  496. // GetAPIServerVirtualIP returns the IP of the internal Kubernetes API service
  497. func GetAPIServerVirtualIP(svcSubnetList string, isDualStack bool) (net.IP, error) {
  498. svcSubnet, err := GetKubernetesServiceCIDR(svcSubnetList, isDualStack)
  499. if err != nil {
  500. return nil, errors.Wrap(err, "unable to get internal Kubernetes Service IP from the given service CIDR")
  501. }
  502. internalAPIServerVirtualIP, err := utilnet.GetIndexedIP(svcSubnet, 1)
  503. if err != nil {
  504. return nil, errors.Wrapf(err, "unable to get the first IP address from the given CIDR: %s", svcSubnet.String())
  505. }
  506. return internalAPIServerVirtualIP, nil
  507. }
  508. // GetStaticPodAuditPolicyFile returns the path to the audit policy file within a static pod
  509. func GetStaticPodAuditPolicyFile() string {
  510. return filepath.Join(KubernetesDir, AuditPolicyDir, AuditPolicyFile)
  511. }
  512. // GetDNSVersion is a handy function that returns the DNS version by DNS type
  513. func GetDNSVersion(dnsType kubeadmapi.DNSAddOnType) string {
  514. switch dnsType {
  515. case kubeadmapi.KubeDNS:
  516. return KubeDNSVersion
  517. default:
  518. return CoreDNSVersion
  519. }
  520. }
  521. // GetKubeletConfigMapName returns the right ConfigMap name for the right branch of k8s
  522. func GetKubeletConfigMapName(k8sVersion *version.Version) string {
  523. return fmt.Sprintf("%s%d.%d", KubeletBaseConfigurationConfigMapPrefix, k8sVersion.Major(), k8sVersion.Minor())
  524. }