k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/cmd/kubeadm/app/constants/constants.go (about)

     1  /*
     2  Copyright 2019 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package constants
    18  
    19  import (
    20  	"fmt"
    21  	"net"
    22  	"os"
    23  	"path/filepath"
    24  	"strings"
    25  	"time"
    26  
    27  	"github.com/pkg/errors"
    28  
    29  	v1 "k8s.io/api/core/v1"
    30  	"k8s.io/apimachinery/pkg/util/version"
    31  	apimachineryversion "k8s.io/apimachinery/pkg/version"
    32  	componentversion "k8s.io/component-base/version"
    33  	netutils "k8s.io/utils/net"
    34  )
    35  
    36  const (
    37  	// KubernetesDir is the directory Kubernetes owns for storing various configuration files
    38  	KubernetesDir = "/etc/kubernetes"
    39  	// ManifestsSubDirName defines directory name to store manifests
    40  	ManifestsSubDirName = "manifests"
    41  	// TempDirForKubeadm defines temporary directory for kubeadm
    42  	// should be joined with KubernetesDir.
    43  	TempDirForKubeadm = "tmp"
    44  
    45  	// CertificateBackdate defines the offset applied to notBefore for CA certificates generated by kubeadm
    46  	CertificateBackdate = time.Minute * 5
    47  	// CertificateValidityPeriod defines the validity period for all the signed certificates generated by kubeadm
    48  	CertificateValidityPeriod = time.Hour * 24 * 365
    49  	// CACertificateValidityPeriod defines the validity period for all the signed CA certificates generated by kubeadm
    50  	CACertificateValidityPeriod = time.Hour * 24 * 365 * 10
    51  
    52  	// DefaultCertificateDir defines default certificate directory
    53  	DefaultCertificateDir = "pki"
    54  
    55  	// CACertAndKeyBaseName defines certificate authority base name
    56  	CACertAndKeyBaseName = "ca"
    57  	// CACertName defines certificate name
    58  	CACertName = "ca.crt"
    59  	// CAKeyName defines certificate name
    60  	CAKeyName = "ca.key"
    61  
    62  	// APIServerCertAndKeyBaseName defines API's server certificate and key base name
    63  	APIServerCertAndKeyBaseName = "apiserver"
    64  	// APIServerCertName defines API's server certificate name
    65  	APIServerCertName = "apiserver.crt"
    66  	// APIServerKeyName defines API's server key name
    67  	APIServerKeyName = "apiserver.key"
    68  	// APIServerCertCommonName defines API's server certificate common name (CN)
    69  	APIServerCertCommonName = "kube-apiserver"
    70  
    71  	// APIServerKubeletClientCertAndKeyBaseName defines kubelet client certificate and key base name
    72  	APIServerKubeletClientCertAndKeyBaseName = "apiserver-kubelet-client"
    73  	// APIServerKubeletClientCertName defines kubelet client certificate name
    74  	APIServerKubeletClientCertName = "apiserver-kubelet-client.crt"
    75  	// APIServerKubeletClientKeyName defines kubelet client key name
    76  	APIServerKubeletClientKeyName = "apiserver-kubelet-client.key"
    77  	// APIServerKubeletClientCertCommonName defines kubelet client certificate common name (CN)
    78  	APIServerKubeletClientCertCommonName = "kube-apiserver-kubelet-client"
    79  
    80  	// EtcdCACertAndKeyBaseName defines etcd's CA certificate and key base name
    81  	EtcdCACertAndKeyBaseName = "etcd/ca"
    82  	// EtcdCACertName defines etcd's CA certificate name
    83  	EtcdCACertName = "etcd/ca.crt"
    84  	// EtcdCAKeyName defines etcd's CA key name
    85  	EtcdCAKeyName = "etcd/ca.key"
    86  
    87  	// EtcdServerCertAndKeyBaseName defines etcd's server certificate and key base name
    88  	EtcdServerCertAndKeyBaseName = "etcd/server"
    89  	// EtcdServerCertName defines etcd's server certificate name
    90  	EtcdServerCertName = "etcd/server.crt"
    91  	// EtcdServerKeyName defines etcd's server key name
    92  	EtcdServerKeyName = "etcd/server.key"
    93  
    94  	// EtcdListenClientPort defines the port etcd listen on for client traffic
    95  	EtcdListenClientPort = 2379
    96  	// EtcdMetricsPort is the port at which to obtain etcd metrics and health status
    97  	EtcdMetricsPort = 2381
    98  
    99  	// EtcdPeerCertAndKeyBaseName defines etcd's peer certificate and key base name
   100  	EtcdPeerCertAndKeyBaseName = "etcd/peer"
   101  	// EtcdPeerCertName defines etcd's peer certificate name
   102  	EtcdPeerCertName = "etcd/peer.crt"
   103  	// EtcdPeerKeyName defines etcd's peer key name
   104  	EtcdPeerKeyName = "etcd/peer.key"
   105  
   106  	// EtcdListenPeerPort defines the port etcd listen on for peer traffic
   107  	EtcdListenPeerPort = 2380
   108  
   109  	// EtcdHealthcheckClientCertAndKeyBaseName defines etcd's healthcheck client certificate and key base name
   110  	EtcdHealthcheckClientCertAndKeyBaseName = "etcd/healthcheck-client"
   111  	// EtcdHealthcheckClientCertName defines etcd's healthcheck client certificate name
   112  	EtcdHealthcheckClientCertName = "etcd/healthcheck-client.crt"
   113  	// EtcdHealthcheckClientKeyName defines etcd's healthcheck client key name
   114  	EtcdHealthcheckClientKeyName = "etcd/healthcheck-client.key"
   115  	// EtcdHealthcheckClientCertCommonName defines etcd's healthcheck client certificate common name (CN)
   116  	EtcdHealthcheckClientCertCommonName = "kube-etcd-healthcheck-client"
   117  
   118  	// APIServerEtcdClientCertAndKeyBaseName defines apiserver's etcd client certificate and key base name
   119  	APIServerEtcdClientCertAndKeyBaseName = "apiserver-etcd-client"
   120  	// APIServerEtcdClientCertName defines apiserver's etcd client certificate name
   121  	APIServerEtcdClientCertName = "apiserver-etcd-client.crt"
   122  	// APIServerEtcdClientKeyName defines apiserver's etcd client key name
   123  	APIServerEtcdClientKeyName = "apiserver-etcd-client.key"
   124  	// APIServerEtcdClientCertCommonName defines apiserver's etcd client certificate common name (CN)
   125  	APIServerEtcdClientCertCommonName = "kube-apiserver-etcd-client"
   126  
   127  	// ServiceAccountKeyBaseName defines SA key base name
   128  	ServiceAccountKeyBaseName = "sa"
   129  	// ServiceAccountPublicKeyName defines SA public key base name
   130  	ServiceAccountPublicKeyName = "sa.pub"
   131  	// ServiceAccountPrivateKeyName defines SA private key base name
   132  	ServiceAccountPrivateKeyName = "sa.key"
   133  
   134  	// FrontProxyCACertAndKeyBaseName defines front proxy CA certificate and key base name
   135  	FrontProxyCACertAndKeyBaseName = "front-proxy-ca"
   136  	// FrontProxyCACertName defines front proxy CA certificate name
   137  	FrontProxyCACertName = "front-proxy-ca.crt"
   138  	// FrontProxyCAKeyName defines front proxy CA key name
   139  	FrontProxyCAKeyName = "front-proxy-ca.key"
   140  
   141  	// FrontProxyClientCertAndKeyBaseName defines front proxy certificate and key base name
   142  	FrontProxyClientCertAndKeyBaseName = "front-proxy-client"
   143  	// FrontProxyClientCertName defines front proxy certificate name
   144  	FrontProxyClientCertName = "front-proxy-client.crt"
   145  	// FrontProxyClientKeyName defines front proxy key name
   146  	FrontProxyClientKeyName = "front-proxy-client.key"
   147  	// FrontProxyClientCertCommonName defines front proxy certificate common name
   148  	FrontProxyClientCertCommonName = "front-proxy-client" //used as subject.commonname attribute (CN)
   149  
   150  	// AdminKubeConfigFileName defines name for the kubeconfig aimed to be used by the admin of the cluster
   151  	AdminKubeConfigFileName = "admin.conf"
   152  	// SuperAdminKubeConfigFileName defines name for the kubeconfig aimed to be used by the super-admin of the cluster
   153  	SuperAdminKubeConfigFileName = "super-admin.conf"
   154  
   155  	// KubeletBootstrapKubeConfigFileName defines the file name for the kubeconfig that the kubelet will use to do
   156  	// the TLS bootstrap to get itself an unique credential
   157  	KubeletBootstrapKubeConfigFileName = "bootstrap-kubelet.conf"
   158  
   159  	// KubeletKubeConfigFileName defines the file name for the kubeconfig that the control-plane kubelet will use for talking
   160  	// to the API server
   161  	KubeletKubeConfigFileName = "kubelet.conf"
   162  	// ControllerManagerKubeConfigFileName defines the file name for the controller manager's kubeconfig file
   163  	ControllerManagerKubeConfigFileName = "controller-manager.conf"
   164  	// SchedulerKubeConfigFileName defines the file name for the scheduler's kubeconfig file
   165  	SchedulerKubeConfigFileName = "scheduler.conf"
   166  
   167  	// Some well-known users, groups, roles and clusterrolebindings in the core Kubernetes authorization system
   168  
   169  	// ControllerManagerUser defines the well-known user the controller-manager should be authenticated as
   170  	ControllerManagerUser = "system:kube-controller-manager"
   171  	// SchedulerUser defines the well-known user the scheduler should be authenticated as
   172  	SchedulerUser = "system:kube-scheduler"
   173  	// NodesUserPrefix defines the user name prefix as requested by the Node authorizer.
   174  	NodesUserPrefix = "system:node:"
   175  	// SystemPrivilegedGroup defines the well-known group for the apiservers. This group is also superuser by default
   176  	// (i.e. bound to the cluster-admin ClusterRole)
   177  	SystemPrivilegedGroup = "system:masters"
   178  	// NodesGroup defines the well-known group for all nodes.
   179  	NodesGroup = "system:nodes"
   180  	// NodeBootstrapTokenAuthGroup specifies which group a Node Bootstrap Token should be authenticated in
   181  	NodeBootstrapTokenAuthGroup = "system:bootstrappers:kubeadm:default-node-token"
   182  	// KubeProxyClusterRoleName sets the name for the kube-proxy ClusterRole
   183  	KubeProxyClusterRoleName = "system:node-proxier"
   184  	// NodeBootstrapperClusterRoleName defines the name of the auto-bootstrapped ClusterRole for letting someone post a CSR
   185  	NodeBootstrapperClusterRoleName = "system:node-bootstrapper"
   186  	// CSRAutoApprovalClusterRoleName defines the name of the auto-bootstrapped ClusterRole for making the csrapprover controller auto-approve the CSR
   187  	// Starting from v1.8, CSRAutoApprovalClusterRoleName is automatically created by the API server on startup
   188  	CSRAutoApprovalClusterRoleName = "system:certificates.k8s.io:certificatesigningrequests:nodeclient"
   189  	// NodeSelfCSRAutoApprovalClusterRoleName is a role defined in default 1.8 RBAC policies for automatic CSR approvals for automatically rotated node certificates
   190  	NodeSelfCSRAutoApprovalClusterRoleName = "system:certificates.k8s.io:certificatesigningrequests:selfnodeclient"
   191  	// NodesClusterRoleBinding defines the well-known ClusterRoleBinding which binds the too permissive system:node
   192  	// ClusterRole to the system:nodes group. Since kubeadm is using the Node Authorizer, this ClusterRoleBinding's
   193  	// system:nodes group subject is removed if present.
   194  	NodesClusterRoleBinding = "system:node"
   195  
   196  	// KubeletBaseConfigMapRole defines the base kubelet configuration ConfigMap.
   197  	KubeletBaseConfigMapRole = "kubeadm:kubelet-config"
   198  	// KubeProxyClusterRoleBindingName sets the name for the kube-proxy CluterRoleBinding
   199  	KubeProxyClusterRoleBindingName = "kubeadm:node-proxier"
   200  	// NodeKubeletBootstrap defines the name of the ClusterRoleBinding that lets kubelets post CSRs
   201  	NodeKubeletBootstrap = "kubeadm:kubelet-bootstrap"
   202  	// GetNodesClusterRoleName defines the name of the ClusterRole and ClusterRoleBinding to get nodes
   203  	GetNodesClusterRoleName = "kubeadm:get-nodes"
   204  	// NodeAutoApproveBootstrapClusterRoleBinding defines the name of the ClusterRoleBinding that makes the csrapprover approve node CSRs
   205  	NodeAutoApproveBootstrapClusterRoleBinding = "kubeadm:node-autoapprove-bootstrap"
   206  	// NodeAutoApproveCertificateRotationClusterRoleBinding defines name of the ClusterRoleBinding that makes the csrapprover approve node auto rotated CSRs
   207  	NodeAutoApproveCertificateRotationClusterRoleBinding = "kubeadm:node-autoapprove-certificate-rotation"
   208  	// ClusterAdminsGroupAndClusterRoleBinding is the name of the Group used for kubeadm generated cluster
   209  	// admin credentials and the name of the ClusterRoleBinding that binds the same Group to the "cluster-admin"
   210  	// built-in ClusterRole.
   211  	ClusterAdminsGroupAndClusterRoleBinding = "kubeadm:cluster-admins"
   212  
   213  	// KubernetesAPICallTimeout specifies how long kubeadm should wait for API calls
   214  	KubernetesAPICallTimeout = 1 * time.Minute
   215  	// KubernetesAPICallRetryInterval defines how long kubeadm should wait before retrying a failed API operation
   216  	KubernetesAPICallRetryInterval = 500 * time.Millisecond
   217  
   218  	// DiscoveryTimeout specifies the default discovery timeout for kubeadm (used unless one is specified in the JoinConfiguration)
   219  	DiscoveryTimeout = 5 * time.Minute
   220  	// DiscoveryRetryInterval specifies how long kubeadm should wait before retrying to connect to the control-plane when doing discovery
   221  	DiscoveryRetryInterval = 5 * time.Second
   222  
   223  	// TLSBootstrapTimeout specifies how long kubeadm should wait for the kubelet to perform the TLS Bootstrap
   224  	TLSBootstrapTimeout = 5 * time.Minute
   225  	// TLSBootstrapRetryInterval specifies how long kubeadm should wait before retrying the TLS Bootstrap check
   226  	TLSBootstrapRetryInterval = 1 * time.Second
   227  
   228  	// EtcdAPICallTimeout specifies how much time to wait for completion of requests against the etcd API.
   229  	EtcdAPICallTimeout = 2 * time.Minute
   230  	// EtcdAPICallRetryInterval specifies how frequently to retry requests against the etcd API.
   231  	EtcdAPICallRetryInterval = 500 * time.Millisecond
   232  
   233  	// ControlPlaneComponentHealthCheckTimeout specifies the default control plane component health check timeout
   234  	ControlPlaneComponentHealthCheckTimeout = 4 * time.Minute
   235  
   236  	// KubeletHealthCheckTimeout specifies the default kubelet timeout
   237  	KubeletHealthCheckTimeout = 4 * time.Minute
   238  
   239  	// UpgradeManifestsTimeout specifies the default timeout for upgradring static Pod manifests
   240  	UpgradeManifestsTimeout = 5 * time.Minute
   241  
   242  	// PullImageRetry specifies how many times ContainerRuntime retries when pulling image failed
   243  	PullImageRetry = 5
   244  	// RemoveContainerRetry specifies how many times ContainerRuntime retries when removing container failed
   245  	RemoveContainerRetry = 5
   246  
   247  	// MinimumAddressesInServiceSubnet defines minimum amount of nodes the Service subnet should allow.
   248  	// We need at least ten, because the DNS service is always at the tenth cluster clusterIP
   249  	MinimumAddressesInServiceSubnet = 10
   250  
   251  	// MaximumBitsForServiceSubnet defines maximum possible size of the service subnet in terms of bits.
   252  	// For example, if the value is 20, then the largest supported service subnet is /12 for IPv4 and /108 for IPv6.
   253  	// Note however that anything in between /108 and /112 will be clamped to /112 due to the limitations of the underlying allocation logic.
   254  	// TODO: https://github.com/kubernetes/enhancements/pull/1881
   255  	MaximumBitsForServiceSubnet = 20
   256  
   257  	// MinimumAddressesInPodSubnet defines minimum amount of pods in the cluster.
   258  	// We need at least more than services, an IPv4 /28 or IPv6 /128 subnet means 14 util addresses
   259  	MinimumAddressesInPodSubnet = 14
   260  
   261  	// PodSubnetNodeMaskMaxDiff is limited to 16 due to an issue with uncompressed IP bitmap in core:
   262  	// xref: #44918
   263  	// The node subnet mask size must be no more than the pod subnet mask size + 16
   264  	PodSubnetNodeMaskMaxDiff = 16
   265  
   266  	// DefaultCertTokenDuration specifies the default amount of time that the token used by upload certs will be valid
   267  	// Default behaviour is 2 hours
   268  	DefaultCertTokenDuration = 2 * time.Hour
   269  
   270  	// CertificateKeySize specifies the size of the key used to encrypt certificates on uploadcerts phase
   271  	CertificateKeySize = 32
   272  
   273  	// LabelNodeRoleControlPlane specifies that a node hosts control-plane components
   274  	LabelNodeRoleControlPlane = "node-role.kubernetes.io/control-plane"
   275  
   276  	// LabelExcludeFromExternalLB can be set on a node to exclude it from external load balancers.
   277  	// This is added to control plane nodes to preserve backwards compatibility with a legacy behavior.
   278  	LabelExcludeFromExternalLB = "node.kubernetes.io/exclude-from-external-load-balancers"
   279  
   280  	// AnnotationKubeadmCRISocket specifies the annotation kubeadm uses to preserve the crisocket information given to kubeadm at
   281  	// init/join time for use later. kubeadm annotates the node object with this information
   282  	AnnotationKubeadmCRISocket = "kubeadm.alpha.kubernetes.io/cri-socket"
   283  
   284  	// KubeadmConfigConfigMap specifies in what ConfigMap in the kube-system namespace the `kubeadm init` configuration should be stored
   285  	KubeadmConfigConfigMap = "kubeadm-config"
   286  
   287  	// ClusterConfigurationConfigMapKey specifies in what ConfigMap key the cluster configuration should be stored
   288  	ClusterConfigurationConfigMapKey = "ClusterConfiguration"
   289  
   290  	// KubeProxyConfigMap specifies in what ConfigMap in the kube-system namespace the kube-proxy configuration should be stored
   291  	KubeProxyConfigMap = "kube-proxy"
   292  
   293  	// KubeProxyConfigMapKey specifies in what ConfigMap key the component config of kube-proxy should be stored
   294  	KubeProxyConfigMapKey = "config.conf"
   295  
   296  	// KubeletBaseConfigurationConfigMap specifies in what ConfigMap in the kube-system namespace the initial remote configuration of kubelet should be stored
   297  	KubeletBaseConfigurationConfigMap = "kubelet-config"
   298  
   299  	// KubeletBaseConfigurationConfigMapKey specifies in what ConfigMap key the initial remote configuration of kubelet should be stored
   300  	KubeletBaseConfigurationConfigMapKey = "kubelet"
   301  
   302  	// KubeletRunDirectory specifies the directory where the kubelet runtime information is stored.
   303  	KubeletRunDirectory = "/var/lib/kubelet"
   304  
   305  	// KubeletConfigurationFileName specifies the file name on the node which stores initial remote configuration of kubelet
   306  	// This file should exist under KubeletRunDirectory
   307  	KubeletConfigurationFileName = "config.yaml"
   308  
   309  	// KubeletEnvFileName is a file "kubeadm init" writes at runtime. Using that interface, kubeadm can customize certain
   310  	// kubelet flags conditionally based on the environment at runtime. Also, parameters given to the configuration file
   311  	// might be passed through this file. "kubeadm init" writes one variable, with the name ${KubeletEnvFileVariableName}.
   312  	// This file should exist under KubeletRunDirectory
   313  	KubeletEnvFileName = "kubeadm-flags.env"
   314  
   315  	// KubeletEnvFileVariableName specifies the shell script variable name "kubeadm init" should write a value to in KubeletEnvFile
   316  	KubeletEnvFileVariableName = "KUBELET_KUBEADM_ARGS"
   317  
   318  	// KubeletHealthzPort is the port of the kubelet healthz endpoint
   319  	KubeletHealthzPort = 10248
   320  
   321  	// MinExternalEtcdVersion indicates minimum external etcd version which kubeadm supports
   322  	MinExternalEtcdVersion = "3.4.13-4"
   323  
   324  	// DefaultEtcdVersion indicates the default etcd version that kubeadm uses
   325  	DefaultEtcdVersion = "3.5.13-0"
   326  
   327  	// Etcd defines variable used internally when referring to etcd component
   328  	Etcd = "etcd"
   329  	// KubeAPIServer defines variable used internally when referring to kube-apiserver component
   330  	KubeAPIServer = "kube-apiserver"
   331  	// KubeControllerManager defines variable used internally when referring to kube-controller-manager component
   332  	KubeControllerManager = "kube-controller-manager"
   333  	// KubeScheduler defines variable used internally when referring to kube-scheduler component
   334  	KubeScheduler = "kube-scheduler"
   335  	// KubeProxy defines variable used internally when referring to kube-proxy component
   336  	KubeProxy = "kube-proxy"
   337  	// CoreDNS defines variable used internally when referring to the CoreDNS component
   338  	CoreDNS = "CoreDNS"
   339  	// Kubelet defines variable used internally when referring to the Kubelet
   340  	Kubelet = "kubelet"
   341  	// Kubeadm defines variable used internally when referring to the kubeadm component
   342  	Kubeadm = "kubeadm"
   343  
   344  	// 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)
   345  	KubeCertificatesVolumeName = "k8s-certs"
   346  
   347  	// 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
   348  	KubeConfigVolumeName = "kubeconfig"
   349  
   350  	// DefaultCIImageRepository points to image registry where CI uploads images from ci build job
   351  	DefaultCIImageRepository = "gcr.io/k8s-staging-ci-images"
   352  
   353  	// CoreDNSConfigMap specifies in what ConfigMap in the kube-system namespace the CoreDNS config should be stored
   354  	CoreDNSConfigMap = "coredns"
   355  
   356  	// CoreDNSDeploymentName specifies the name of the Deployment for CoreDNS add-on
   357  	CoreDNSDeploymentName = "coredns"
   358  
   359  	// CoreDNSImageName specifies the name of the image for CoreDNS add-on
   360  	CoreDNSImageName = "coredns"
   361  
   362  	// CoreDNSVersion is the version of CoreDNS to be deployed if it is used
   363  	CoreDNSVersion = "v1.11.1"
   364  
   365  	// ClusterConfigurationKind is the string kind value for the ClusterConfiguration struct
   366  	ClusterConfigurationKind = "ClusterConfiguration"
   367  
   368  	// InitConfigurationKind is the string kind value for the InitConfiguration struct
   369  	InitConfigurationKind = "InitConfiguration"
   370  
   371  	// JoinConfigurationKind is the string kind value for the JoinConfiguration struct
   372  	JoinConfigurationKind = "JoinConfiguration"
   373  
   374  	// ResetConfigurationKind is the string kind value for the ResetConfiguration struct
   375  	ResetConfigurationKind = "ResetConfiguration"
   376  
   377  	// YAMLDocumentSeparator is the separator for YAML documents
   378  	// TODO: Find a better place for this constant
   379  	YAMLDocumentSeparator = "---\n"
   380  
   381  	// CIKubernetesVersionPrefix is the prefix for CI Kubernetes version
   382  	CIKubernetesVersionPrefix = "ci/"
   383  
   384  	// DefaultAPIServerBindAddress is the default bind address for the API Server
   385  	DefaultAPIServerBindAddress = "0.0.0.0"
   386  
   387  	// ControlPlaneNumCPU is the number of CPUs required on control-plane
   388  	ControlPlaneNumCPU = 2
   389  
   390  	// ControlPlaneMem is the number of megabytes of memory required on the control-plane
   391  	// Below that amount of RAM running a stable control plane would be difficult.
   392  	ControlPlaneMem = 1700
   393  
   394  	// KubeadmCertsSecret specifies in what Secret in the kube-system namespace the certificates should be stored
   395  	KubeadmCertsSecret = "kubeadm-certs"
   396  
   397  	// KubeletPort is the default port for the kubelet server on each host machine.
   398  	// May be overridden by a flag at startup.
   399  	KubeletPort = 10250
   400  	// KubeSchedulerPort is the default port for the scheduler status server.
   401  	// May be overridden by a flag at startup.
   402  	KubeSchedulerPort = 10259
   403  	// KubeControllerManagerPort is the default port for the controller manager status server.
   404  	// May be overridden by a flag at startup.
   405  	KubeControllerManagerPort = 10257
   406  
   407  	// EtcdAdvertiseClientUrlsAnnotationKey is the annotation key on every etcd pod, describing the
   408  	// advertise client URLs
   409  	EtcdAdvertiseClientUrlsAnnotationKey = "kubeadm.kubernetes.io/etcd.advertise-client-urls"
   410  	// KubeAPIServerAdvertiseAddressEndpointAnnotationKey is the annotation key on every apiserver pod,
   411  	// describing the API endpoint (advertise address and bind port of the api server)
   412  	KubeAPIServerAdvertiseAddressEndpointAnnotationKey = "kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint"
   413  	// ComponentConfigHashAnnotationKey holds the config map annotation key that kubeadm uses to store
   414  	// a SHA256 sum to check for user changes
   415  	ComponentConfigHashAnnotationKey = "kubeadm.kubernetes.io/component-config.hash"
   416  
   417  	// ControlPlaneTier is the value used in the tier label to identify control plane components
   418  	ControlPlaneTier = "control-plane"
   419  
   420  	// Mode* constants were copied from pkg/kubeapiserver/authorizer/modes
   421  	// to avoid kubeadm dependency on the internal module
   422  	// TODO: share Mode* constants in component config
   423  
   424  	// ModeAlwaysAllow is the mode to set all requests as authorized
   425  	ModeAlwaysAllow string = "AlwaysAllow"
   426  	// ModeAlwaysDeny is the mode to set no requests as authorized
   427  	ModeAlwaysDeny string = "AlwaysDeny"
   428  	// ModeABAC is the mode to use Attribute Based Access Control to authorize
   429  	ModeABAC string = "ABAC"
   430  	// ModeWebhook is the mode to make an external webhook call to authorize
   431  	ModeWebhook string = "Webhook"
   432  	// ModeRBAC is the mode to use Role Based Access Control to authorize
   433  	ModeRBAC string = "RBAC"
   434  	// ModeNode is an authorization mode that authorizes API requests made by kubelets.
   435  	ModeNode string = "Node"
   436  
   437  	// PauseVersion indicates the default pause image version for kubeadm
   438  	PauseVersion = "3.9"
   439  
   440  	// CgroupDriverSystemd holds the systemd driver type
   441  	CgroupDriverSystemd = "systemd"
   442  
   443  	// KubeControllerManagerUserName is the username of the user that kube-controller-manager runs as.
   444  	KubeControllerManagerUserName string = "kubeadm-kcm"
   445  	// KubeAPIServerUserName is the username of the user that kube-apiserver runs as.
   446  	KubeAPIServerUserName string = "kubeadm-kas"
   447  	// KubeSchedulerUserName is the username of the user that kube-scheduler runs as.
   448  	KubeSchedulerUserName string = "kubeadm-ks"
   449  	// EtcdUserName is the username of the user that etcd runs as.
   450  	EtcdUserName string = "kubeadm-etcd"
   451  	// ServiceAccountKeyReadersGroupName is the group of users that are allowed to read the service account private key.
   452  	ServiceAccountKeyReadersGroupName string = "kubeadm-sa-key-readers"
   453  	// UpgradeConfigurationKind is the string kind value for the UpgradeConfiguration struct
   454  	UpgradeConfigurationKind = "UpgradeConfiguration"
   455  )
   456  
   457  var (
   458  	// ControlPlaneTaint is the taint to apply on the PodSpec for being able to run that Pod on the control-plane
   459  	ControlPlaneTaint = v1.Taint{
   460  		Key:    LabelNodeRoleControlPlane,
   461  		Effect: v1.TaintEffectNoSchedule,
   462  	}
   463  
   464  	// ControlPlaneToleration is the toleration to apply on the PodSpec for being able to run that Pod on the control-plane
   465  	ControlPlaneToleration = v1.Toleration{
   466  		Key:    LabelNodeRoleControlPlane,
   467  		Effect: v1.TaintEffectNoSchedule,
   468  	}
   469  
   470  	// ControlPlaneComponents defines the control-plane component names
   471  	ControlPlaneComponents = []string{KubeAPIServer, KubeControllerManager, KubeScheduler}
   472  
   473  	// MinimumControlPlaneVersion specifies the minimum control plane version kubeadm can deploy
   474  	MinimumControlPlaneVersion = getSkewedKubernetesVersion(-1)
   475  
   476  	// MinimumKubeletVersion specifies the minimum version of kubelet which kubeadm supports
   477  	MinimumKubeletVersion = getSkewedKubernetesVersion(-3)
   478  
   479  	// CurrentKubernetesVersion specifies current Kubernetes version supported by kubeadm
   480  	CurrentKubernetesVersion = getSkewedKubernetesVersion(0)
   481  
   482  	// SupportedEtcdVersion lists officially supported etcd versions with corresponding Kubernetes releases
   483  	SupportedEtcdVersion = map[uint8]string{
   484  		22: "3.5.13-0",
   485  		23: "3.5.13-0",
   486  		24: "3.5.13-0",
   487  		25: "3.5.13-0",
   488  		26: "3.5.13-0",
   489  		27: "3.5.13-0",
   490  		28: "3.5.13-0",
   491  		29: "3.5.13-0",
   492  		30: "3.5.13-0",
   493  		31: "3.5.13-0",
   494  	}
   495  
   496  	// KubeadmCertsClusterRoleName sets the name for the ClusterRole that allows
   497  	// the bootstrap tokens to access the kubeadm-certs Secret during the join of a new control-plane
   498  	KubeadmCertsClusterRoleName = fmt.Sprintf("kubeadm:%s", KubeadmCertsSecret)
   499  
   500  	// DefaultKubernetesPlaceholderVersion is a placeholder version in case the component-base
   501  	// version was not populated during build.
   502  	DefaultKubernetesPlaceholderVersion = version.MustParseSemantic("v1.0.0-placeholder-version")
   503  )
   504  
   505  // getSkewedKubernetesVersion returns the current MAJOR.(MINOR+n).0 Kubernetes version with a skew of 'n'
   506  // It uses the kubeadm version provided by the 'component-base/version' package. This version must be populated
   507  // by passing linker flags during the kubeadm build process. If the version is empty, assume that kubeadm
   508  // was either build incorrectly or this code is running in unit tests.
   509  func getSkewedKubernetesVersion(n int) *version.Version {
   510  	versionInfo := componentversion.Get()
   511  	return getSkewedKubernetesVersionImpl(&versionInfo, n)
   512  }
   513  
   514  func getSkewedKubernetesVersionImpl(versionInfo *apimachineryversion.Info, n int) *version.Version {
   515  	// TODO: update if the kubeadm version gets decoupled from the Kubernetes version.
   516  	// This would require keeping track of the supported skew in a table.
   517  	// More changes would be required if the kubelet version one day decouples from that of Kubernetes.
   518  	var ver *version.Version
   519  	if len(versionInfo.Major) == 0 {
   520  		return DefaultKubernetesPlaceholderVersion
   521  	}
   522  	ver = version.MustParseSemantic(versionInfo.GitVersion)
   523  	// Append the MINOR version skew.
   524  	// TODO: handle the case of Kubernetes moving to v2.0 or having MAJOR version updates in the future.
   525  	// This would require keeping track (in a table) of the last MINOR for a particular MAJOR.
   526  	minor := uint(int(ver.Minor()) + n)
   527  	return version.MustParseSemantic(fmt.Sprintf("v%d.%d.0", ver.Major(), minor))
   528  }
   529  
   530  // EtcdSupportedVersion returns officially supported version of etcd for a specific Kubernetes release
   531  // If passed version is not in the given list, the function returns the nearest version with a warning
   532  func EtcdSupportedVersion(supportedEtcdVersion map[uint8]string, versionString string) (etcdVersion *version.Version, warning, err error) {
   533  	kubernetesVersion, err := version.ParseSemantic(versionString)
   534  	if err != nil {
   535  		return nil, nil, err
   536  	}
   537  	desiredVersion, etcdStringVersion := uint8(kubernetesVersion.Minor()), ""
   538  
   539  	min, max := ^uint8(0), uint8(0)
   540  	for k, v := range supportedEtcdVersion {
   541  		if desiredVersion == k {
   542  			etcdStringVersion = v
   543  			break
   544  		}
   545  		if k < min {
   546  			min = k
   547  		}
   548  		if k > max {
   549  			max = k
   550  		}
   551  	}
   552  
   553  	if len(etcdStringVersion) == 0 {
   554  		if desiredVersion < min {
   555  			etcdStringVersion = supportedEtcdVersion[min]
   556  		}
   557  		if desiredVersion > max {
   558  			etcdStringVersion = supportedEtcdVersion[max]
   559  		}
   560  		warning = errors.Errorf("could not find officially supported version of etcd for Kubernetes %s, falling back to the nearest etcd version (%s)",
   561  			versionString, etcdStringVersion)
   562  	}
   563  
   564  	etcdVersion, err = version.ParseSemantic(etcdStringVersion)
   565  	if err != nil {
   566  		return nil, nil, err
   567  	}
   568  
   569  	return etcdVersion, warning, nil
   570  }
   571  
   572  // GetStaticPodDirectory returns the location on the disk where the Static Pod should be present
   573  func GetStaticPodDirectory() string {
   574  	return filepath.Join(KubernetesDir, ManifestsSubDirName)
   575  }
   576  
   577  // GetStaticPodFilepath returns the location on the disk where the Static Pod should be present
   578  func GetStaticPodFilepath(componentName, manifestsDir string) string {
   579  	return filepath.Join(manifestsDir, componentName+".yaml")
   580  }
   581  
   582  // GetAdminKubeConfigPath returns the location on the disk where admin kubeconfig is located by default
   583  func GetAdminKubeConfigPath() string {
   584  	return filepath.Join(KubernetesDir, AdminKubeConfigFileName)
   585  }
   586  
   587  // GetSuperAdminKubeConfigPath returns the location on the disk where admin kubeconfig is located by default
   588  func GetSuperAdminKubeConfigPath() string {
   589  	return filepath.Join(KubernetesDir, SuperAdminKubeConfigFileName)
   590  }
   591  
   592  // GetBootstrapKubeletKubeConfigPath returns the location on the disk where bootstrap kubelet kubeconfig is located by default
   593  func GetBootstrapKubeletKubeConfigPath() string {
   594  	return filepath.Join(KubernetesDir, KubeletBootstrapKubeConfigFileName)
   595  }
   596  
   597  // GetKubeletKubeConfigPath returns the location on the disk where kubelet kubeconfig is located by default
   598  func GetKubeletKubeConfigPath() string {
   599  	return filepath.Join(KubernetesDir, KubeletKubeConfigFileName)
   600  }
   601  
   602  // CreateTempDirForKubeadm is a function that creates a temporary directory under /etc/kubernetes/tmp (not using /tmp as that would potentially be dangerous)
   603  func CreateTempDirForKubeadm(kubernetesDir, dirName string) (string, error) {
   604  	tempDir := filepath.Join(KubernetesDir, TempDirForKubeadm)
   605  	if len(kubernetesDir) != 0 {
   606  		tempDir = filepath.Join(kubernetesDir, TempDirForKubeadm)
   607  	}
   608  
   609  	// creates target folder if not already exists
   610  	if err := os.MkdirAll(tempDir, 0700); err != nil {
   611  		return "", errors.Wrapf(err, "failed to create directory %q", tempDir)
   612  	}
   613  
   614  	tempDir, err := os.MkdirTemp(tempDir, dirName)
   615  	if err != nil {
   616  		return "", errors.Wrap(err, "couldn't create a temporary directory")
   617  	}
   618  	return tempDir, nil
   619  }
   620  
   621  // CreateTimestampDirForKubeadm is a function that creates a temporary directory under /etc/kubernetes/tmp formatted with the current date
   622  func CreateTimestampDirForKubeadm(kubernetesDir, dirName string) (string, error) {
   623  	tempDir := filepath.Join(KubernetesDir, TempDirForKubeadm)
   624  	if len(kubernetesDir) != 0 {
   625  		tempDir = filepath.Join(kubernetesDir, TempDirForKubeadm)
   626  	}
   627  
   628  	// creates target folder if not already exists
   629  	if err := os.MkdirAll(tempDir, 0700); err != nil {
   630  		return "", errors.Wrapf(err, "failed to create directory %q", tempDir)
   631  	}
   632  
   633  	timestampDirName := fmt.Sprintf("%s-%s", dirName, time.Now().Format("2006-01-02-15-04-05"))
   634  	timestampDir := filepath.Join(tempDir, timestampDirName)
   635  	if err := os.Mkdir(timestampDir, 0700); err != nil {
   636  		return "", errors.Wrap(err, "could not create timestamp directory")
   637  	}
   638  
   639  	return timestampDir, nil
   640  }
   641  
   642  // GetDNSIP returns a dnsIP, which is 10th IP in svcSubnet CIDR range
   643  func GetDNSIP(svcSubnetList string) (net.IP, error) {
   644  	// Get the service subnet CIDR
   645  	svcSubnetCIDR, err := GetKubernetesServiceCIDR(svcSubnetList)
   646  	if err != nil {
   647  		return nil, errors.Wrapf(err, "unable to get internal Kubernetes Service IP from the given service CIDR (%s)", svcSubnetList)
   648  	}
   649  
   650  	// Selects the 10th IP in service subnet CIDR range as dnsIP
   651  	dnsIP, err := netutils.GetIndexedIP(svcSubnetCIDR, 10)
   652  	if err != nil {
   653  		return nil, errors.Wrap(err, "unable to get internal Kubernetes Service IP from the given service CIDR")
   654  	}
   655  
   656  	return dnsIP, nil
   657  }
   658  
   659  // GetKubernetesServiceCIDR returns the default Service CIDR for the Kubernetes internal service
   660  func GetKubernetesServiceCIDR(svcSubnetList string) (*net.IPNet, error) {
   661  	// The default service address family for the cluster is the address family of the first
   662  	// service cluster IP range configured via the `--service-cluster-ip-range` flag
   663  	// of the kube-controller-manager and kube-apiserver.
   664  	svcSubnets, err := netutils.ParseCIDRs(strings.Split(svcSubnetList, ","))
   665  	if err != nil {
   666  		return nil, errors.Wrapf(err, "unable to parse ServiceSubnet %v", svcSubnetList)
   667  	}
   668  	if len(svcSubnets) == 0 {
   669  		return nil, errors.New("received empty ServiceSubnet")
   670  	}
   671  	return svcSubnets[0], nil
   672  }
   673  
   674  // GetAPIServerVirtualIP returns the IP of the internal Kubernetes API service
   675  func GetAPIServerVirtualIP(svcSubnetList string) (net.IP, error) {
   676  	svcSubnet, err := GetKubernetesServiceCIDR(svcSubnetList)
   677  	if err != nil {
   678  		return nil, errors.Wrap(err, "unable to get internal Kubernetes Service IP from the given service CIDR")
   679  	}
   680  	internalAPIServerVirtualIP, err := netutils.GetIndexedIP(svcSubnet, 1)
   681  	if err != nil {
   682  		return nil, errors.Wrapf(err, "unable to get the first IP address from the given CIDR: %s", svcSubnet.String())
   683  	}
   684  	return internalAPIServerVirtualIP, nil
   685  }