From 9914316d1d1195c1736dc90a2a1009dc5bf603b8 Mon Sep 17 00:00:00 2001 From: Brad House Date: Sun, 29 Nov 2026 15:38:45 +0000 Subject: [PATCH] Let CKS set control plane, etcd and kubelet options at create time createKubernetesCluster gains six optional parameters: | parameter | type | used for | |---|---|---| | apiserverargs | map | kube-apiserver flags, e.g. OIDC (oidc-issuer-url, oidc-client-id, ...) | | etcdargs | map | etcd flags, e.g. heartbeat-interval, election-timeout | | controllermanagerargs | map | kube-controller-manager flags, e.g. leader-elect-lease-duration | | schedulerargs | map | kube-scheduler flags, e.g. leader-elect-lease-duration | | kubeletconfig | JSON object | KubeletConfiguration fields, e.g. systemReserved, kubeReserved, evictionHard | | auditpolicy | string | audit Policy document; turns on audit logging | - Stored in kubernetes_cluster_details and returned in the cluster response. No schema change. - Rendered into the kubeadm init config (ClusterConfiguration apiServer, controllerManager, scheduler and etcd.local extraArgs, apiServer extraVolumes, plus a KubeletConfiguration document), not into shell flags. - With external etcd nodes, etcdargs are added to the etcd service on those nodes instead. - kubeadm uploads the ClusterConfiguration and the kubelet config to the cluster, so nodes that join later (scale, HA control nodes) get the same settings. The audit policy file is also written on the extra control nodes. - Audit logs go to /var/log/kubernetes/audit with rotation defaults (maxage 30, maxbackup 3, maxsize 100 MB) that apiserverargs can override. The policy is written gzip+base64 encoded. - kubeadm config is now built in Java for both the external etcd and the stacked case, as kubeadm.k8s.io/v1beta3 (extraArgs as a map), or v1beta4 (extraArgs as a name/value list) for Kubernetes 1.31+. The stacked case keeps the old flag based kubeadm init unless one of the new parameters is set. - Validation: flag names [a-z0-9-], values and kubelet strings limited to a plain character set (no spaces, quotes, braces), flags and kubelet fields CloudStack or kubeadm rely on reserved per component (kube-apiserver secure-port, etcd-servers, anonymous-auth, audit-policy-file, proxy-client-*, requestheader-*; etcd name, initial-cluster, data-dir, wal-dir, the URL and TLS flags; controller-manager and scheduler kubeconfig, bind-address, secure-port, leader-elect, controllers, config; kubelet cgroupDriver, clusterDNS, ...), NodeRestriction kept in enable-admission-plugins, Kubernetes 1.22+, rejected for ExternalManaged clusters, duplicate flags rejected. - kubeadm-config.yaml is now 0600: it holds the bootstrap token and certificate key. - The API server certificate lists the control node's own IP as well as the public IP, and with external etcd the control node advertises its own IP (as kubeadm does for stacked etcd). The public IP stays the controlPlaneEndpoint. - UI: in advanced mode the create cluster form has kube-apiserver, etcd, kube-controller-manager and kube-scheduler arguments (one name=value per line), kubelet configuration and audit policy fields; the cluster details tab shows them. Signed-off-by: Brad House --- .../apache/cloudstack/api/ApiConstants.java | 6 + .../cluster/KubernetesClusterManagerImpl.java | 57 +++ .../KubernetesClusterStartWorker.java | 73 ++-- .../cluster/utils/KubeadmConfigBuilder.java | 384 ++++++++++++++++++ .../cluster/CreateKubernetesClusterCmd.java | 80 ++++ .../response/KubernetesClusterResponse.java | 48 +++ .../src/main/resources/conf/etcd-node.yml | 2 +- .../resources/conf/k8s-control-node-add.yml | 2 + .../main/resources/conf/k8s-control-node.yml | 32 +- .../utils/KubeadmConfigBuilderTest.java | 373 +++++++++++++++++ .../CreateKubernetesClusterCmdTest.java | 62 +++ ui/public/locales/en.json | 11 + ui/src/components/view/DetailsTab.vue | 12 + ui/src/config/section/compute.js | 2 +- .../views/compute/CreateKubernetesCluster.vue | 68 ++++ 15 files changed, 1158 insertions(+), 54 deletions(-) create mode 100644 plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/utils/KubeadmConfigBuilder.java create mode 100644 plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubeadmConfigBuilderTest.java create mode 100644 plugins/integrations/kubernetes-service/src/test/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmdTest.java diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java index 1004d0316254..9d0d129513ad 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java @@ -126,6 +126,7 @@ public class ApiConstants { public static final String COMBINED_CAPACITY_ORDERING = "COMBINED"; public static final String CONTROLLER = "controller"; public static final String CONTROLLER_UNIT = "controllerunit"; + public static final String CONTROLLER_MANAGER_ARGS = "controllermanagerargs"; public static final String CONSOLE_ENDPOINT_CREATOR_ADDRESS = "consoleendpointcreatoraddress"; public static final String COPY_IMAGE_TAGS = "copyimagetags"; public static final String CPU_OVERCOMMIT_RATIO = "cpuOvercommitRatio"; @@ -155,6 +156,8 @@ public class ApiConstants { public static final String CN = "cn"; public static final String COMMAND = "command"; public static final String CMD_EVENT_TYPE = "cmdeventtype"; + public static final String API_SERVER_ARGS = "apiserverargs"; + public static final String AUDIT_POLICY = "auditpolicy"; public static final String CNI_CONFIG = "cniconfig"; public static final String CNI_CONFIG_ID = "cniconfigurationid"; public static final String CNI_CONFIG_DETAILS = "cniconfigdetails"; @@ -185,6 +188,7 @@ public class ApiConstants { public static final String ENCRYPT_FORMAT = "encryptformat"; public static final String ENCRYPT_ROOT = "encryptroot"; public static final String ENCRYPTION_SUPPORTED = "encryptionsupported"; + public static final String ETCD_ARGS = "etcdargs"; public static final String ETCD_IPS = "etcdips"; public static final String MIN_IOPS = "miniops"; public static final String MAX_IOPS = "maxiops"; @@ -450,6 +454,7 @@ public class ApiConstants { public static final String NEW_START_IP = "newstartip"; public static final String NEW_END_IP = "newendip"; public static final String KUBERNETES_NODE_VERSION = "kubernetesnodeversion"; + public static final String KUBELET_CONFIG = "kubeletconfig"; public static final String NUMA_NODE = "numanode"; public static final String NUM_RETRIES = "numretries"; public static final String OFFER_HA = "offerha"; @@ -563,6 +568,7 @@ public class ApiConstants { public static final String QUICK_RESTORE = "quickrestore"; public static final String SCHEDULE = "schedule"; public static final String SCHEDULE_ID = "scheduleid"; + public static final String SCHEDULER_ARGS = "schedulerargs"; public static final String SCOPE = "scope"; public static final String SEARCH_BASE = "searchbase"; public static final String SECONDARY_IP = "secondaryip"; diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImpl.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImpl.java index eb4ebb78ee48..35d5ba85eef6 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImpl.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImpl.java @@ -177,6 +177,7 @@ import com.cloud.kubernetes.cluster.dao.KubernetesClusterDao; import com.cloud.kubernetes.cluster.dao.KubernetesClusterDetailsDao; import com.cloud.kubernetes.cluster.dao.KubernetesClusterVmMapDao; +import com.cloud.kubernetes.cluster.utils.KubeadmConfigBuilder; import com.cloud.kubernetes.version.KubernetesSupportedVersion; import com.cloud.kubernetes.version.KubernetesSupportedVersionVO; import com.cloud.kubernetes.version.KubernetesVersionManagerImpl; @@ -298,6 +299,8 @@ public class KubernetesClusterManagerImpl extends ManagerBase implements Kuberne ListKubernetesClustersCmd.class, ScaleKubernetesClusterCmd.class ); + private static final String NODE_SETTINGS_PARAMETERS = String.join(", ", ApiConstants.API_SERVER_ARGS, ApiConstants.ETCD_ARGS, + ApiConstants.CONTROLLER_MANAGER_ARGS, ApiConstants.SCHEDULER_ARGS, ApiConstants.KUBELET_CONFIG, ApiConstants.AUDIT_POLICY); private static final String PROJECT_KUBERNETES_ACCOUNT_FIRST_NAME = "Kubernetes"; private static final String PROJECT_KUBERNETES_ACCOUNT_LAST_NAME = "Service User"; private static final String DEFAULT_NETWORK_OFFERING_FOR_KUBERNETES_SERVICE_DISPLAY_TEXT = "Network Offering used for CloudStack Kubernetes service"; @@ -962,11 +965,28 @@ public KubernetesClusterResponse createKubernetesClusterResponse(long kubernetes response.setClusterType(kubernetesCluster.getClusterType()); response.setCsiEnabled(kubernetesCluster.isCsiEnabled()); response.setCreated(kubernetesCluster.getCreated()); + setNodeSettingsResponse(response, kubernetesCluster.getId()); setNodeTypeAffinityGroupResponse(response, kubernetesCluster.getId()); return response; } + protected void setNodeSettingsResponse(KubernetesClusterResponse response, long clusterId) { + Map details = kubernetesClusterDetailsDao.listDetailsKeyPairs(clusterId, List.of(ApiConstants.API_SERVER_ARGS, + ApiConstants.ETCD_ARGS, ApiConstants.CONTROLLER_MANAGER_ARGS, ApiConstants.SCHEDULER_ARGS, ApiConstants.KUBELET_CONFIG, ApiConstants.AUDIT_POLICY)); + response.setApiServerArgs(argsDetail(details, ApiConstants.API_SERVER_ARGS)); + response.setEtcdArgs(argsDetail(details, ApiConstants.ETCD_ARGS)); + response.setControllerManagerArgs(argsDetail(details, ApiConstants.CONTROLLER_MANAGER_ARGS)); + response.setSchedulerArgs(argsDetail(details, ApiConstants.SCHEDULER_ARGS)); + response.setKubeletConfig(details.get(ApiConstants.KUBELET_CONFIG)); + response.setAuditPolicy(details.get(ApiConstants.AUDIT_POLICY)); + } + + private Map argsDetail(Map details, String name) { + String args = details.get(name); + return StringUtils.isEmpty(args) ? null : KubeadmConfigBuilder.argsFromJson(args); + } + protected void setNodeTypeAffinityGroupResponse(KubernetesClusterResponse response, long clusterId) { setAffinityGroupResponseForNodeType(response, clusterId, CONTROL.name()); setAffinityGroupResponseForNodeType(response, clusterId, WORKER.name()); @@ -1065,6 +1085,34 @@ private void validateUnmanagedKubernetesClusterCreateParameters(final CreateKube if (StringUtils.isNotEmpty(externalLoadBalancerIpAddress) && (!NetUtils.isValidIp4(externalLoadBalancerIpAddress) && !NetUtils.isValidIp6(externalLoadBalancerIpAddress))) { throw new InvalidParameterValueException("Invalid external load balancer IP address"); } + + if (hasNodeSettings(cmd)) { + throw new InvalidParameterValueException(String.format("%s are not supported for %s clusters", + NODE_SETTINGS_PARAMETERS, KubernetesCluster.ClusterType.ExternalManaged)); + } + } + + private boolean hasNodeSettings(final CreateKubernetesClusterCmd cmd) { + return !cmd.getComponentArgs().isEmpty() || StringUtils.isNotBlank(cmd.getKubeletConfig()) || StringUtils.isNotEmpty(cmd.getAuditPolicy()); + } + + protected void validateNodeSettings(final CreateKubernetesClusterCmd cmd, final KubernetesSupportedVersion clusterKubernetesVersion) { + if (!hasNodeSettings(cmd)) { + return; + } + cmd.getComponentArgs().forEach(KubeadmConfigBuilder::validateArgs); + KubeadmConfigBuilder.normalizeKubeletConfig(cmd.getKubeletConfig()); + KubeadmConfigBuilder.validateAuditPolicy(cmd.getAuditPolicy()); + boolean supported; + try { + supported = KubernetesVersionManagerImpl.compareSemanticVersions(clusterKubernetesVersion.getSemanticVersion(), KubeadmConfigBuilder.MIN_KUBERNETES_VERSION) >= 0; + } catch (IllegalArgumentException e) { + supported = false; + } + if (!supported) { + throw new InvalidParameterValueException(String.format("%s need Kubernetes version %s or above", + NODE_SETTINGS_PARAMETERS, KubeadmConfigBuilder.MIN_KUBERNETES_VERSION)); + } } public boolean isCommandSupported(KubernetesCluster cluster, String cmdName) { @@ -1178,6 +1226,8 @@ private void validateManagedKubernetesClusterCreateParameters(final CreateKubern validateDockerRegistryParams(dockerRegistryUserName, dockerRegistryPassword, dockerRegistryUrl); + validateNodeSettings(cmd, clusterKubernetesVersion); + Network network = validateAndGetNetworkForKubernetesCreateParameters(networkId); if (StringUtils.isNotEmpty(externalLoadBalancerIpAddress)) { @@ -1305,6 +1355,9 @@ private void addKubernetesClusterDetails(final KubernetesCluster kubernetesClust final String dockerRegistryPassword = cmd.getDockerRegistryPassword(); final String dockerRegistryUrl = cmd.getDockerRegistryUrl(); final boolean networkCleanup = cmd.getNetworkId() == null; + final Map> componentArgs = cmd.getComponentArgs(); + final String kubeletConfig = KubeadmConfigBuilder.normalizeKubeletConfig(cmd.getKubeletConfig()); + final String auditPolicy = cmd.getAuditPolicy(); Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { @@ -1318,6 +1371,10 @@ public void doInTransactionWithoutResult(TransactionStatus status) { addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.DOCKER_REGISTRY_USER_NAME, dockerRegistryUserName, true); addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.DOCKER_REGISTRY_PASSWORD, dockerRegistryPassword, false); addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.DOCKER_REGISTRY_URL, dockerRegistryUrl, true); + componentArgs.forEach((component, args) -> + details.add(new KubernetesClusterDetailsVO(kubernetesClusterId, component.getParameter(), KubeadmConfigBuilder.argsToJson(args), true))); + addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.KUBELET_CONFIG, kubeletConfig, true); + addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.AUDIT_POLICY, auditPolicy, true); if (kubernetesCluster.getClusterType() == KubernetesCluster.ClusterType.CloudManaged) { details.add(new KubernetesClusterDetailsVO(kubernetesClusterId, "networkCleanup", String.valueOf(networkCleanup), true)); } diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java index a15086c60d6c..2fa58370fd05 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java @@ -25,6 +25,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -64,6 +65,7 @@ import com.cloud.kubernetes.cluster.KubernetesClusterService; import com.cloud.kubernetes.cluster.KubernetesClusterVO; import com.cloud.kubernetes.cluster.KubernetesClusterVmMapVO; +import com.cloud.kubernetes.cluster.utils.KubeadmConfigBuilder; import com.cloud.kubernetes.cluster.utils.KubernetesClusterUtil; import com.cloud.kubernetes.version.KubernetesSupportedVersion; import com.cloud.kubernetes.version.KubernetesVersionManagerImpl; @@ -176,16 +178,14 @@ private Pair getKubernetesControlNodeConfig(final String control final String caCert = "{{ k8s_control_node.ca.crt }}"; final String sshPubKey = "{{ k8s.ssh.pub.key }}"; final String clusterToken = "{{ k8s_control_node.cluster.token }}"; + final String clusterTokenTtl = "{{ k8s_control_node.cluster.token.ttl }}"; final String clusterInitArgsKey = "{{ k8s_control_node.cluster.initargs }}"; final String ejectIsoKey = "{{ k8s.eject.iso }}"; final String installWaitTime = "{{ k8s.install.wait.time }}"; final String installReattemptsCount = "{{ k8s.install.reattempts.count }}"; - final String externalEtcdNodes = "{{ etcd.unstacked_etcd }}"; - final String etcdEndpointList = "{{ etcd.etcd_endpoint_list }}"; - final String k8sServerIp = "{{ k8s_control.server_ip }}"; - final String k8sApiPort = "{{ k8s.api_server_port }}"; - final String certSans = "{{ k8s_control.server_ips }}"; - final String k8sCertificate = "{{ k8s_control.certificate_key }}"; + final String initWithConfigKey = "{{ k8s_control.init_with_config }}"; + final String kubeadmConfigKey = "{{ k8s_control.kubeadm_config }}"; + final String auditPolicyFileKey = "{{ k8s.audit.policy.file }}"; final String externalCniPlugin = "{{ k8s.external.cni.plugin }}"; final String setupCsiDriver = "{{ k8s.setup.csi.driver }}"; @@ -204,7 +204,10 @@ private Pair getKubernetesControlNodeConfig(final String control final String tlsCaCert = CertUtils.x509CertificatesToPem(certificate.getCaCertificates()); final Long waitTime = KubernetesClusterService.KubernetesControlNodeInstallAttemptWait.value(); final Long reattempts = KubernetesClusterService.KubernetesControlNodeInstallReattempts.value(); - String endpointList = getEtcdEndpointList(etcdIps); + final Map> componentArgs = getComponentArgs(); + final String kubeletConfig = getClusterDetail(ApiConstants.KUBELET_CONFIG); + final String auditPolicy = getClusterDetail(ApiConstants.AUDIT_POLICY); + final boolean initWithConfig = externalEtcd || !componentArgs.isEmpty() || kubeletConfig != null || auditPolicy != null; k8sControlNodeConfig = k8sControlNodeConfig.replace(apiServerCert, tlsClientCert.replace("\n", "\n ")); k8sControlNodeConfig = k8sControlNodeConfig.replace(apiServerKey, tlsPrivateKey.replace("\n", "\n ")); @@ -220,8 +223,10 @@ private Pair getKubernetesControlNodeConfig(final String control k8sControlNodeConfig = k8sControlNodeConfig.replace(installWaitTime, String.valueOf(waitTime)); k8sControlNodeConfig = k8sControlNodeConfig.replace(installReattemptsCount, String.valueOf(reattempts)); k8sControlNodeConfig = k8sControlNodeConfig.replace(sshPubKey, pubKey); + final String tokenTtl = "0"; k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterToken, KubernetesClusterUtil.generateClusterToken(kubernetesCluster)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(externalEtcdNodes, String.valueOf(externalEtcd)); + k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterTokenTtl, tokenTtl); + k8sControlNodeConfig = k8sControlNodeConfig.replace(initWithConfigKey, String.valueOf(initWithConfig)); String initArgs = ""; if (haSupported) { initArgs = String.format("--control-plane-endpoint %s:%d --upload-certs --certificate-key %s ", @@ -229,15 +234,19 @@ private Pair getKubernetesControlNodeConfig(final String control CLUSTER_API_PORT, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster)); } - initArgs += String.format("--apiserver-cert-extra-sans=%s", serverIp); + initArgs += String.format("--apiserver-cert-extra-sans=%s", String.join(",", addresses)); initArgs += String.format(" --kubernetes-version=%s", getKubernetesClusterVersion().getSemanticVersion()); k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterInitArgsKey, initArgs); k8sControlNodeConfig = k8sControlNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(etcdEndpointList, endpointList); - k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sServerIp, serverIp); - k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sApiPort, String.valueOf(CLUSTER_API_PORT)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(certSans, String.format("- %s", serverIp)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sCertificate, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster)); + String kubeadmConfig = ""; + if (initWithConfig) { + kubeadmConfig = KubeadmConfigBuilder.build(getKubernetesClusterVersion().getSemanticVersion(), controlNodeIp, serverIp, CLUSTER_API_PORT, + getEtcdEndpointList(etcdIps), KubernetesClusterUtil.generateClusterToken(kubernetesCluster), tokenTtl, + KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster), haSupported, + componentArgs, auditPolicy != null, kubeletConfig); + } + k8sControlNodeConfig = k8sControlNodeConfig.replace(kubeadmConfigKey, kubeadmConfig.replace("\n", "\n ")); + k8sControlNodeConfig = k8sControlNodeConfig.replace(auditPolicyFileKey, KubeadmConfigBuilder.auditPolicyWriteFile(auditPolicy)); k8sControlNodeConfig = k8sControlNodeConfig.replace(externalCniPlugin, String.valueOf(externalCni)); k8sControlNodeConfig = k8sControlNodeConfig.replace(setupCsiDriver, String.valueOf(setupCsi)); @@ -337,6 +346,7 @@ private String getKubernetesAdditionalControlNodeConfig(final String joinIp, fin final String ejectIsoKey = "{{ k8s.eject.iso }}"; final String installWaitTime = "{{ k8s.install.wait.time }}"; final String installReattemptsCount = "{{ k8s.install.reattempts.count }}"; + final String auditPolicyFileKey = "{{ k8s.audit.policy.file }}"; final Long waitTime = KubernetesClusterService.KubernetesControlNodeInstallAttemptWait.value(); final Long reattempts = KubernetesClusterService.KubernetesControlNodeInstallReattempts.value(); @@ -356,6 +366,7 @@ private String getKubernetesAdditionalControlNodeConfig(final String joinIp, fin k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterTokenKey, KubernetesClusterUtil.generateClusterToken(kubernetesCluster)); k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterHACertificateKey, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster)); k8sControlNodeConfig = k8sControlNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso)); + k8sControlNodeConfig = k8sControlNodeConfig.replace(auditPolicyFileKey, KubeadmConfigBuilder.auditPolicyWriteFile(getClusterDetail(ApiConstants.AUDIT_POLICY))); k8sControlNodeConfig = updateKubeConfigWithRegistryDetails(k8sControlNodeConfig); return k8sControlNodeConfig; @@ -373,22 +384,29 @@ private String getInitialEtcdClusterDetails(List ipAddresses, List ipAddresses) { - StringBuilder endpoints = new StringBuilder(); - for (int i = 0; i < ipAddresses.size(); i++) { - endpoints.append(String.format("- http://%s:%s", ipAddresses.get(i).getIp4Address(), KubernetesClusterActionWorker.ETCD_NODE_CLIENT_REQUEST_PORT)); - if (i < ipAddresses.size()-1) { - endpoints.append("\n "); + private List getEtcdEndpointList(List ipAddresses) { + List endpoints = new ArrayList<>(); + for (Network.IpAddresses ipAddress : ipAddresses) { + endpoints.add(String.format("http://%s:%s", ipAddress.getIp4Address(), KubernetesClusterActionWorker.ETCD_NODE_CLIENT_REQUEST_PORT)); + } + return endpoints; + } + + private Map> getComponentArgs() { + Map> componentArgs = new EnumMap<>(KubeadmConfigBuilder.Component.class); + for (KubeadmConfigBuilder.Component component : KubeadmConfigBuilder.Component.values()) { + Map args = KubeadmConfigBuilder.argsFromJson(getClusterDetail(component.getParameter())); + if (!args.isEmpty()) { + componentArgs.put(component, args); } } - return endpoints.toString(); + return componentArgs; } + private String getClusterDetail(String name) { + KubernetesClusterDetailsVO detail = kubernetesClusterDetailsDao.findDetail(kubernetesCluster.getId(), name); + return detail == null || StringUtils.isEmpty(detail.getValue()) ? null : detail.getValue(); + } private List getEtcdNodeHostnames() { List hostnames = new ArrayList<>(); @@ -409,6 +427,7 @@ private String getEtcdNodeConfig(final List ipAddresses, final List ipAddresses, final List + * The documents are written as JSON, which kubeadm reads as YAML. User values never reach a + * shell, and the character set is limited so they cannot open a cloud-init jinja expression. + */ +public final class KubeadmConfigBuilder { + + public static final String MIN_KUBERNETES_VERSION = "1.22.0"; + private static final String MIN_KUBERNETES_VERSION_V1BETA4 = "1.31.0"; + public static final String AUDIT_POLICY_PATH = "/etc/kubernetes/audit-policy.yaml"; + public static final String AUDIT_LOG_DIR = "/var/log/kubernetes/audit"; + public static final int MAX_KUBELET_CONFIG_LENGTH = 4096; + public static final int MAX_AUDIT_POLICY_LENGTH = 10240; + private static final int MAX_ARGS_LENGTH = 10240; + private static final String KUBELET_API_VERSION = "kubelet.config.k8s.io/v1beta1"; + private static final String CRI_SOCKET = "/run/containerd/containerd.sock"; + private static final int MAX_VALUE_LENGTH = 1024; + private static final Pattern ARG_NAME = Pattern.compile("[a-z0-9][a-z0-9-]*"); + private static final Pattern SAFE_KEY = Pattern.compile("[A-Za-z0-9._/-]+"); + private static final Pattern SAFE_VALUE = Pattern.compile("[A-Za-z0-9._:/%+=,@~*-]*"); + private static final Set MANAGED_KUBELET_FIELDS = Set.of("apiVersion", "kind", + "authentication", "authorization", "cgroupDriver", "clusterDNS", "clusterDomain", "staticPodPath", + "staticPodURL", "providerID", "containerRuntimeEndpoint"); + private static final Map AUDIT_LOG_DEFAULTS = Map.of( + "audit-log-maxage", "30", + "audit-log-maxbackup", "3", + "audit-log-maxsize", "100"); + + /** + * A control plane component that takes extra flags, with the flags CloudStack or kubeadm set and + * a cluster needs as they are. + */ + public enum Component { + API_SERVER("kube-apiserver", ApiConstants.API_SERVER_ARGS, Set.of("audit-policy-file", "audit-log-path", + "advertise-address", "bind-address", "secure-port", "authorization-mode", "service-cluster-ip-range", "client-ca-file", + "tls-cert-file", "tls-private-key-file", "etcd-servers", "etcd-cafile", "etcd-certfile", "etcd-keyfile", + "kubelet-client-certificate", "kubelet-client-key", "service-account-key-file", "service-account-signing-key-file", + "anonymous-auth", "enable-bootstrap-token-auth", "allow-privileged", "disable-admission-plugins", "admission-control", + "proxy-client-cert-file", "proxy-client-key-file")), + ETCD("etcd", ApiConstants.ETCD_ARGS, Set.of("name", "data-dir", "wal-dir", "config-file", "force-new-cluster", + "listen-client-urls", "advertise-client-urls", "listen-peer-urls", "initial-advertise-peer-urls", "listen-metrics-urls", + "initial-cluster", "initial-cluster-state", "initial-cluster-token", "client-cert-auth", "cert-file", "key-file", + "trusted-ca-file", "peer-client-cert-auth", "peer-cert-file", "peer-key-file", "peer-trusted-ca-file")), + CONTROLLER_MANAGER("kube-controller-manager", ApiConstants.CONTROLLER_MANAGER_ARGS, Set.of("kubeconfig", + "authentication-kubeconfig", "authorization-kubeconfig", "bind-address", "secure-port", "client-ca-file", + "cluster-signing-cert-file", "cluster-signing-key-file", "root-ca-file", "service-account-private-key-file", + "use-service-account-credentials", "controllers", "leader-elect", "master", "cluster-name", "service-cluster-ip-range")), + SCHEDULER("kube-scheduler", ApiConstants.SCHEDULER_ARGS, Set.of("kubeconfig", "authentication-kubeconfig", + "authorization-kubeconfig", "bind-address", "secure-port", "config", "leader-elect", "master")); + + private final String program; + private final String parameter; + private final Set managedArgs; + + Component(String program, String parameter, Set managedArgs) { + this.program = program; + this.parameter = parameter; + this.managedArgs = managedArgs; + } + + public String getProgram() { + return program; + } + + public String getParameter() { + return parameter; + } + + private boolean isManaged(String name) { + return managedArgs.contains(name) || name.startsWith("requestheader-"); + } + } + + private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); + + private KubeadmConfigBuilder() { + } + + public static void validateArgs(Component component, Map args) { + if (MapUtils.isEmpty(args)) { + return; + } + for (Map.Entry arg : args.entrySet()) { + String name = arg.getKey(); + if (name == null || !ARG_NAME.matcher(name).matches()) { + throw new InvalidParameterValueException(String.format("Invalid %s argument name: %s. Use the flag name without the leading dashes", component.program, name)); + } + if (component.isManaged(name)) { + throw new InvalidParameterValueException(String.format("%s argument %s is managed by CloudStack", component.program, name)); + } + if (!isSafeValue(arg.getValue())) { + throw new InvalidParameterValueException(String.format("Invalid value for %s argument %s, allowed characters are letters, digits and ._:/%%+=,@~*-", component.program, name)); + } + } + if (argsToJson(args).length() > MAX_ARGS_LENGTH) { + throw new InvalidParameterValueException(String.format("%s arguments can not be longer than %d characters in total", component.program, MAX_ARGS_LENGTH)); + } + } + + public static String argsToJson(Map args) { + return GSON.toJson(new TreeMap<>(args)); + } + + public static Map argsFromJson(String json) { + if (StringUtils.isEmpty(json)) { + return new HashMap<>(); + } + return GSON.fromJson(json, new TypeToken>() { }.getType()); + } + + /** + * @return the kubelet configuration as compact JSON, or null if none was given + */ + public static String normalizeKubeletConfig(String kubeletConfig) { + if (StringUtils.isBlank(kubeletConfig)) { + return null; + } + if (kubeletConfig.length() > MAX_KUBELET_CONFIG_LENGTH) { + throw new InvalidParameterValueException(String.format("Kubelet configuration can not be longer than %d characters", MAX_KUBELET_CONFIG_LENGTH)); + } + JsonElement config; + try (JsonReader reader = new JsonReader(new StringReader(kubeletConfig))) { + config = GSON.getAdapter(JsonElement.class).read(reader); + if (reader.peek() != JsonToken.END_DOCUMENT) { + throw new MalformedJsonException("unexpected data after the JSON object"); + } + } catch (IOException | IllegalStateException | JsonParseException e) { + throw new InvalidParameterValueException("Kubelet configuration must be a JSON object: " + e.getMessage()); + } + if (!config.isJsonObject() || config.getAsJsonObject().size() == 0) { + throw new InvalidParameterValueException("Kubelet configuration must be a non-empty JSON object of KubeletConfiguration fields"); + } + JsonObject object = config.getAsJsonObject(); + for (String field : MANAGED_KUBELET_FIELDS) { + if (object.has(field)) { + throw new InvalidParameterValueException(String.format("Kubelet configuration field %s is managed by CloudStack", field)); + } + } + validateKubeletConfigElement(object); + return GSON.toJson(object); + } + + public static void validateAuditPolicy(String auditPolicy) { + if (auditPolicy == null) { + return; + } + if (StringUtils.isBlank(auditPolicy)) { + throw new InvalidParameterValueException("Audit policy can not be empty"); + } + if (auditPolicy.length() > MAX_AUDIT_POLICY_LENGTH) { + throw new InvalidParameterValueException(String.format("Audit policy can not be longer than %d characters", MAX_AUDIT_POLICY_LENGTH)); + } + if (auditPolicy.codePoints().anyMatch(Character::isSupplementaryCodePoint)) { + throw new InvalidParameterValueException("Audit policy can not contain characters outside the Unicode basic multilingual plane"); + } + } + + /** + * @param controlNodeIp the control node's own IP on the cluster network + * @param serverIp the cluster's API endpoint, e.g. its public IP + * @param etcdEndpoints external etcd client URLs, empty for stacked etcd + * @param componentArgs extra flags per component; etcd flags are left out with external etcd + * @param kubeletConfig normalized kubelet configuration JSON, or null + */ + public static String build(String kubernetesVersion, String controlNodeIp, String serverIp, int apiServerPort, List etcdEndpoints, + String token, String tokenTtl, String certificateKey, boolean haSupported, + Map> componentArgs, boolean auditPolicy, String kubeletConfig) { + boolean externalEtcd = !etcdEndpoints.isEmpty(); + boolean v1beta4; + try { + v1beta4 = KubernetesVersionManagerImpl.compareSemanticVersions(kubernetesVersion, MIN_KUBERNETES_VERSION_V1BETA4) >= 0; + } catch (IllegalArgumentException e) { + v1beta4 = false; + } + String kubeadmApiVersion = v1beta4 ? "kubeadm.k8s.io/v1beta4" : "kubeadm.k8s.io/v1beta3"; + + Map apiServer = new LinkedHashMap<>(); + apiServer.put("certSANs", controlNodeIp.equals(serverIp) ? List.of(serverIp) : List.of(controlNodeIp, serverIp)); + Map extraArgs = new LinkedHashMap<>(); + if (auditPolicy) { + extraArgs.put("audit-policy-file", AUDIT_POLICY_PATH); + extraArgs.put("audit-log-path", AUDIT_LOG_DIR + "/audit.log"); + extraArgs.putAll(new TreeMap<>(AUDIT_LOG_DEFAULTS)); + apiServer.put("extraVolumes", List.of( + hostPathMount("audit-policy", AUDIT_POLICY_PATH, true, "File"), + hostPathMount("audit-log", AUDIT_LOG_DIR, false, "DirectoryOrCreate"))); + } + Map apiServerArgs = componentArgs.get(Component.API_SERVER); + if (MapUtils.isNotEmpty(apiServerArgs)) { + extraArgs.putAll(new TreeMap<>(apiServerArgs)); + String admissionPlugins = extraArgs.get("enable-admission-plugins"); + if (admissionPlugins != null && !List.of(admissionPlugins.split(",")).contains("NodeRestriction")) { + extraArgs.put("enable-admission-plugins", admissionPlugins.isEmpty() ? "NodeRestriction" : admissionPlugins + ",NodeRestriction"); + } + } + if (!extraArgs.isEmpty()) { + apiServer.put("extraArgs", v1beta4 ? toArgList(extraArgs) : extraArgs); + } + + Map clusterConfiguration = document(kubeadmApiVersion, "ClusterConfiguration"); + clusterConfiguration.put("kubernetesVersion", kubernetesVersion); + if (haSupported || externalEtcd) { + clusterConfiguration.put("controlPlaneEndpoint", String.format("%s:%d", serverIp, apiServerPort)); + } + clusterConfiguration.put("apiServer", apiServer); + Map controllerManagerArgs = componentArgs.get(Component.CONTROLLER_MANAGER); + if (MapUtils.isNotEmpty(controllerManagerArgs)) { + clusterConfiguration.put("controllerManager", Map.of("extraArgs", extraArgs(controllerManagerArgs, v1beta4))); + } + Map schedulerArgs = componentArgs.get(Component.SCHEDULER); + if (MapUtils.isNotEmpty(schedulerArgs)) { + clusterConfiguration.put("scheduler", Map.of("extraArgs", extraArgs(schedulerArgs, v1beta4))); + } + Map etcdArgs = componentArgs.get(Component.ETCD); + if (externalEtcd) { + clusterConfiguration.put("etcd", Map.of("external", Map.of("endpoints", etcdEndpoints))); + } else if (MapUtils.isNotEmpty(etcdArgs)) { + clusterConfiguration.put("etcd", Map.of("local", Map.of("extraArgs", extraArgs(etcdArgs, v1beta4)))); + } + + Map initConfiguration = document(kubeadmApiVersion, "InitConfiguration"); + Map bootstrapToken = new LinkedHashMap<>(); + bootstrapToken.put("token", token); + bootstrapToken.put("ttl", tokenTtl); + initConfiguration.put("bootstrapTokens", List.of(bootstrapToken)); + initConfiguration.put("nodeRegistration", Map.of("criSocket", CRI_SOCKET)); + if (externalEtcd) { + Map localApiEndpoint = new LinkedHashMap<>(); + localApiEndpoint.put("advertiseAddress", controlNodeIp); + localApiEndpoint.put("bindPort", apiServerPort); + initConfiguration.put("localAPIEndpoint", localApiEndpoint); + } + initConfiguration.put("certificateKey", certificateKey); + + StringBuilder config = new StringBuilder(); + config.append(GSON.toJson(clusterConfiguration)).append("\n---\n").append(GSON.toJson(initConfiguration)); + if (kubeletConfig != null) { + JsonObject kubelet = new JsonObject(); + kubelet.addProperty("apiVersion", KUBELET_API_VERSION); + kubelet.addProperty("kind", "KubeletConfiguration"); + JsonParser.parseString(kubeletConfig).getAsJsonObject().entrySet().forEach(e -> kubelet.add(e.getKey(), e.getValue())); + config.append("\n---\n").append(GSON.toJson(kubelet)); + } + return config.toString(); + } + + /** + * @return a cloud-config write_files entry for the audit policy, or an empty string + */ + public static String auditPolicyWriteFile(String auditPolicy) { + if (StringUtils.isEmpty(auditPolicy)) { + return ""; + } + byte[] compressed; + try { + compressed = new CompressionUtil().compressString(auditPolicy); + } catch (IOException e) { + throw new CloudRuntimeException("Unable to compress the audit policy", e); + } + return String.format("- path: %s\n permissions: '0600'\n owner: root:root\n encoding: gz+b64\n content: %s", + AUDIT_POLICY_PATH, Base64.getEncoder().encodeToString(compressed)); + } + + /** + * @return the etcd flags as systemd ExecStart continuation lines, or an empty string + */ + public static String etcdServiceArgs(Map etcdArgs) { + StringBuilder lines = new StringBuilder(); + for (Map.Entry arg : new TreeMap<>(etcdArgs).entrySet()) { + lines.append(String.format(" \\\n --%s=%s", arg.getKey(), arg.getValue().replace("%", "%%"))); + } + return lines.toString(); + } + + private static Object extraArgs(Map args, boolean v1beta4) { + Map sortedArgs = new TreeMap<>(args); + return v1beta4 ? toArgList(sortedArgs) : sortedArgs; + } + + private static void validateKubeletConfigElement(JsonElement element) { + if (element.isJsonObject()) { + for (Map.Entry entry : element.getAsJsonObject().entrySet()) { + if (!SAFE_KEY.matcher(entry.getKey()).matches()) { + throw new InvalidParameterValueException(String.format("Invalid kubelet configuration key: %s", entry.getKey())); + } + validateKubeletConfigElement(entry.getValue()); + } + } else if (element.isJsonArray()) { + element.getAsJsonArray().forEach(KubeadmConfigBuilder::validateKubeletConfigElement); + } else if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isString() && !isSafeValue(primitive.getAsString())) { + throw new InvalidParameterValueException(String.format("Invalid kubelet configuration value: %s, allowed characters are letters, digits and ._:/%%+=,@~*-", primitive.getAsString())); + } + } else if (element.isJsonNull()) { + throw new InvalidParameterValueException("Kubelet configuration values can not be null, leave the field out instead"); + } + } + + private static List> toArgList(Map args) { + List> list = new ArrayList<>(); + for (Map.Entry arg : args.entrySet()) { + Map entry = new LinkedHashMap<>(); + entry.put("name", arg.getKey()); + entry.put("value", arg.getValue()); + list.add(entry); + } + return list; + } + + private static boolean isSafeValue(String value) { + return value != null && value.length() <= MAX_VALUE_LENGTH && SAFE_VALUE.matcher(value).matches(); + } + + private static Map document(String apiVersion, String kind) { + Map document = new LinkedHashMap<>(); + document.put("apiVersion", apiVersion); + document.put("kind", kind); + return document; + } + + private static Map hostPathMount(String name, String path, boolean readOnly, String pathType) { + Map mount = new LinkedHashMap<>(); + mount.put("name", name); + mount.put("hostPath", path); + mount.put("mountPath", path); + mount.put("readOnly", readOnly); + mount.put("pathType", pathType); + return mount; + } +} diff --git a/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmd.java b/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmd.java index 8bf0f3625508..e21fb7ab467a 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmd.java +++ b/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmd.java @@ -17,6 +17,8 @@ package org.apache.cloudstack.api.command.user.kubernetes.cluster; import java.security.InvalidParameterException; +import java.util.EnumMap; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -31,6 +33,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.hypervisor.Hypervisor; import com.cloud.kubernetes.cluster.KubernetesServiceHelper; +import com.cloud.kubernetes.cluster.utils.KubeadmConfigBuilder; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; import com.cloud.offering.NetworkOffering; @@ -59,6 +62,7 @@ import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.impl.ConfigurationVO; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import com.cloud.kubernetes.cluster.KubernetesCluster; @@ -224,6 +228,45 @@ public class CreateKubernetesClusterCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.AS_NUMBER, type=CommandType.LONG, description="the AS Number of the network") private Long asNumber; + @Parameter(name = ApiConstants.API_SERVER_ARGS, type = CommandType.MAP, + description = "kube-apiserver arguments, without the leading dashes. Flags that point to a file on the node, other than the audit policy, are not supported. " + + "Example: apiserverargs[0].key=oidc-issuer-url&apiserverargs[0].value=https://idp.example.com&" + + "apiserverargs[1].key=oidc-client-id&apiserverargs[1].value=kubernetes", + since = "24.0.0") + private Map apiServerArgs; + + @Parameter(name = ApiConstants.ETCD_ARGS, type = CommandType.MAP, + description = "etcd arguments, without the leading dashes, for the stacked etcd members on the control nodes or for the etcd nodes. " + + "Example: etcdargs[0].key=heartbeat-interval&etcdargs[0].value=500&etcdargs[1].key=election-timeout&etcdargs[1].value=5000", + since = "24.0.0") + private Map etcdArgs; + + @Parameter(name = ApiConstants.CONTROLLER_MANAGER_ARGS, type = CommandType.MAP, + description = "kube-controller-manager arguments, without the leading dashes. " + + "Example: controllermanagerargs[0].key=leader-elect-lease-duration&controllermanagerargs[0].value=60s", + since = "24.0.0") + private Map controllerManagerArgs; + + @Parameter(name = ApiConstants.SCHEDULER_ARGS, type = CommandType.MAP, + description = "kube-scheduler arguments, without the leading dashes. " + + "Example: schedulerargs[0].key=leader-elect-lease-duration&schedulerargs[0].value=60s", + since = "24.0.0") + private Map schedulerArgs; + + @Parameter(name = ApiConstants.KUBELET_CONFIG, type = CommandType.STRING, length = KubeadmConfigBuilder.MAX_KUBELET_CONFIG_LENGTH, + description = "KubeletConfiguration fields as a JSON object, applied to every node of the cluster. " + + "Example: {\"systemReserved\":{\"cpu\":\"500m\",\"memory\":\"1Gi\"},\"kubeReserved\":{\"cpu\":\"250m\",\"memory\":\"512Mi\"}}. " + + "Note that evictionHard replaces all default thresholds, so list every signal you need", + since = "24.0.0") + private String kubeletConfig; + + @Parameter(name = ApiConstants.AUDIT_POLICY, type = CommandType.STRING, length = KubeadmConfigBuilder.MAX_AUDIT_POLICY_LENGTH, + description = "kube-apiserver audit policy (YAML or JSON). Enables audit logging to /var/log/kubernetes/audit on the control nodes; " + + "retention can be changed with the audit-log-max* apiserverargs. " + + "The policy is part of the control node userdata, a large one may need a higher vm.userdata.max.length", + since = "24.0.0") + private String auditPolicy; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -389,6 +432,43 @@ public Long getCniConfigId() { return cniConfigId; } + /** + * @return the extra flags given for each component, leaving out components without any + */ + public Map> getComponentArgs() { + Map> componentArgs = new EnumMap<>(KubeadmConfigBuilder.Component.class); + putComponentArgs(componentArgs, KubeadmConfigBuilder.Component.API_SERVER, apiServerArgs); + putComponentArgs(componentArgs, KubeadmConfigBuilder.Component.ETCD, etcdArgs); + putComponentArgs(componentArgs, KubeadmConfigBuilder.Component.CONTROLLER_MANAGER, controllerManagerArgs); + putComponentArgs(componentArgs, KubeadmConfigBuilder.Component.SCHEDULER, schedulerArgs); + return componentArgs; + } + + private static void putComponentArgs(Map> componentArgs, + KubeadmConfigBuilder.Component component, Map argsParam) { + if (MapUtils.isEmpty(argsParam)) { + return; + } + Map args = new HashMap<>(); + for (Object arg : argsParam.values()) { + Map entry = (Map) arg; + String name = entry.get(ApiConstants.KEY); + if (args.containsKey(name)) { + throw new InvalidParameterValueException(String.format("%s argument %s is given more than once", component.getProgram(), name)); + } + args.put(name, entry.get(ApiConstants.VALUE)); + } + componentArgs.put(component, args); + } + + public String getKubeletConfig() { + return kubeletConfig; + } + + public String getAuditPolicy() { + return auditPolicy; + } + public boolean getEnableCsi() { return Objects.nonNull(enableCsi) ? enableCsi : Boolean.FALSE; } diff --git a/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/response/KubernetesClusterResponse.java b/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/response/KubernetesClusterResponse.java index 932d722de354..6a68122ff6bd 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/response/KubernetesClusterResponse.java +++ b/plugins/integrations/kubernetes-service/src/main/java/org/apache/cloudstack/api/response/KubernetesClusterResponse.java @@ -212,6 +212,30 @@ public class KubernetesClusterResponse extends BaseResponseWithAnnotations imple @Param(description = "Indicates if the CloudStack CSI driver has been setup in the cluster") private Boolean isCsiEnabled; + @SerializedName(ApiConstants.API_SERVER_ARGS) + @Param(description = "Extra kube-apiserver arguments of the cluster", since = "24.0.0") + private Map apiServerArgs; + + @SerializedName(ApiConstants.ETCD_ARGS) + @Param(description = "Extra etcd arguments of the cluster", since = "24.0.0") + private Map etcdArgs; + + @SerializedName(ApiConstants.CONTROLLER_MANAGER_ARGS) + @Param(description = "Extra kube-controller-manager arguments of the cluster", since = "24.0.0") + private Map controllerManagerArgs; + + @SerializedName(ApiConstants.SCHEDULER_ARGS) + @Param(description = "Extra kube-scheduler arguments of the cluster", since = "24.0.0") + private Map schedulerArgs; + + @SerializedName(ApiConstants.KUBELET_CONFIG) + @Param(description = "KubeletConfiguration fields applied to the cluster nodes", since = "24.0.0") + private String kubeletConfig; + + @SerializedName(ApiConstants.AUDIT_POLICY) + @Param(description = "kube-apiserver audit policy of the cluster", since = "24.0.0") + private String auditPolicy; + @SerializedName(ApiConstants.CLUSTER_TYPE) @Param(description = "The type of the cluster") private KubernetesCluster.ClusterType clusterType; @@ -560,6 +584,30 @@ public void setCsiEnabled(Boolean csiEnabled) { isCsiEnabled = csiEnabled; } + public void setApiServerArgs(Map apiServerArgs) { + this.apiServerArgs = apiServerArgs; + } + + public void setEtcdArgs(Map etcdArgs) { + this.etcdArgs = etcdArgs; + } + + public void setControllerManagerArgs(Map controllerManagerArgs) { + this.controllerManagerArgs = controllerManagerArgs; + } + + public void setSchedulerArgs(Map schedulerArgs) { + this.schedulerArgs = schedulerArgs; + } + + public void setKubeletConfig(String kubeletConfig) { + this.kubeletConfig = kubeletConfig; + } + + public void setAuditPolicy(String auditPolicy) { + this.auditPolicy = auditPolicy; + } + public void setControlAffinityGroupIds(String controlAffinityGroupIds) { this.controlAffinityGroupIds = controlAffinityGroupIds; } diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/etcd-node.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/etcd-node.yml index d455441279dd..52a44b652d91 100644 --- a/plugins/integrations/kubernetes-service/src/main/resources/conf/etcd-node.yml +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/etcd-node.yml @@ -120,7 +120,7 @@ write_files: --listen-client-urls http://{{ etcd.node_ip }}:2379,http://127.0.0.1:2379 \ --initial-cluster-token etcd-cluster-1 \ --initial-cluster {{ etcd.initial_cluster_nodes }} \ - --initial-cluster-state new + --initial-cluster-state new{{ etcd.extra_args }} Restart=on-failure RestartSec=5 diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml index 38f217f403c4..a26d5ce03012 100644 --- a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml @@ -25,6 +25,8 @@ users: {{ k8s.ssh.pub.key }} write_files: + {{ k8s.audit.policy.file }} + - path: /opt/bin/setup-kube-system permissions: '0700' owner: root:root diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml index 4db349ac778a..ad085f3c129c 100644 --- a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml @@ -243,32 +243,12 @@ write_files: fi - path: /etc/kubernetes/kubeadm-config.yaml - permissions: '0644' + permissions: '0600' owner: root:root content: | - apiVersion: kubeadm.k8s.io/v1beta3 - kind: ClusterConfiguration - apiServer: - certSANs: - {{ k8s_control.server_ips }} - controlPlaneEndpoint: {{ k8s_control.server_ip }}:{{ k8s.api_server_port }} - etcd: - external: - endpoints: - {{ etcd.etcd_endpoint_list }} - --- - apiVersion: kubeadm.k8s.io/v1beta3 - kind: InitConfiguration - bootstrapTokens: - - token: "{{ k8s_control_node.cluster.token }}" - ttl: "0" - nodeRegistration: - criSocket: /run/containerd/containerd.sock - localAPIEndpoint: - advertiseAddress: {{ k8s_control.server_ip }} - bindPort: {{ k8s.api_server_port }} - certificateKey: {{ k8s_control.certificate_key }} + {{ k8s_control.kubeadm_config }} + {{ k8s.audit.policy.file }} - path: /opt/bin/deploy-kube-system permissions: '0700' @@ -285,7 +265,7 @@ write_files: export PATH=$PATH:/opt/bin fi - EXTERNAL_ETCD_NODES={{ etcd.unstacked_etcd }} + KUBEADM_INIT_WITH_CONFIG={{ k8s_control.init_with_config }} EXTERNAL_CNI_PLUGIN={{ k8s.external.cni.plugin }} MAX_SETUP_CRUCIAL_CMD_ATTEMPTS=3 crucial_cmd_attempts=1 @@ -296,10 +276,10 @@ write_files: fi retval=0 set +e - if [[ ${EXTERNAL_ETCD_NODES} == true ]]; then + if [[ ${KUBEADM_INIT_WITH_CONFIG} == true ]]; then kubeadm init --config /etc/kubernetes/kubeadm-config.yaml --upload-certs else - kubeadm init --token {{ k8s_control_node.cluster.token }} --token-ttl 0 {{ k8s_control_node.cluster.initargs }} --cri-socket /run/containerd/containerd.sock + kubeadm init --token {{ k8s_control_node.cluster.token }} --token-ttl {{ k8s_control_node.cluster.token.ttl }} {{ k8s_control_node.cluster.initargs }} --cri-socket /run/containerd/containerd.sock fi retval=$? set -e diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubeadmConfigBuilderTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubeadmConfigBuilderTest.java new file mode 100644 index 000000000000..2b24be290f6e --- /dev/null +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubeadmConfigBuilderTest.java @@ -0,0 +1,373 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.kubernetes.cluster.utils; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import org.junit.Assert; +import org.junit.Test; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.kubernetes.cluster.utils.KubeadmConfigBuilder.Component; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class KubeadmConfigBuilderTest { + + private static List parse(String config) { + List documents = new ArrayList<>(); + for (String document : config.split("\n---\n")) { + documents.add(JsonParser.parseString(document).getAsJsonObject()); + } + return documents; + } + + @Test + public void buildStackedWithoutSettings() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "10.1.1.10", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "3600s", "key", false, Collections.emptyMap(), false, null)); + Assert.assertEquals(2, docs.size()); + JsonObject cluster = docs.get(0); + Assert.assertEquals("ClusterConfiguration", cluster.get("kind").getAsString()); + Assert.assertEquals("kubeadm.k8s.io/v1beta3", cluster.get("apiVersion").getAsString()); + Assert.assertEquals("1.30.2", cluster.get("kubernetesVersion").getAsString()); + Assert.assertFalse(cluster.has("controlPlaneEndpoint")); + Assert.assertFalse(cluster.has("etcd")); + Assert.assertEquals(1, cluster.getAsJsonObject("apiServer").getAsJsonArray("certSANs").size()); + Assert.assertEquals("10.1.1.10", cluster.getAsJsonObject("apiServer").getAsJsonArray("certSANs").get(0).getAsString()); + Assert.assertFalse(cluster.getAsJsonObject("apiServer").has("extraArgs")); + JsonObject init = docs.get(1); + Assert.assertEquals("InitConfiguration", init.get("kind").getAsString()); + Assert.assertEquals("abcdef.0123456789abcdef", init.getAsJsonArray("bootstrapTokens").get(0).getAsJsonObject().get("token").getAsString()); + Assert.assertEquals("3600s", init.getAsJsonArray("bootstrapTokens").get(0).getAsJsonObject().get("ttl").getAsString()); + Assert.assertFalse(init.has("localAPIEndpoint")); + } + + @Test + public void buildExternalEtcd() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "10.1.1.10", 6443, List.of("http://10.1.1.20:2379"), + "abcdef.0123456789abcdef", "0", "key", false, Collections.emptyMap(), false, null)); + JsonObject cluster = docs.get(0); + Assert.assertEquals("10.1.1.10:6443", cluster.get("controlPlaneEndpoint").getAsString()); + Assert.assertEquals("http://10.1.1.20:2379", cluster.getAsJsonObject("etcd").getAsJsonObject("external").getAsJsonArray("endpoints").get(0).getAsString()); + JsonObject init = docs.get(1); + Assert.assertEquals("10.1.1.10", init.getAsJsonObject("localAPIEndpoint").get("advertiseAddress").getAsString()); + Assert.assertEquals(6443, init.getAsJsonObject("localAPIEndpoint").get("bindPort").getAsInt()); + Assert.assertEquals("key", init.get("certificateKey").getAsString()); + } + + @Test + public void buildExternalEtcdBehindPublicIp() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "203.0.113.5", 6443, List.of("http://10.1.1.20:2379"), + "abcdef.0123456789abcdef", "0", "key", false, Collections.emptyMap(), false, null)); + JsonObject cluster = docs.get(0); + Assert.assertEquals("203.0.113.5:6443", cluster.get("controlPlaneEndpoint").getAsString()); + JsonArray certSans = cluster.getAsJsonObject("apiServer").getAsJsonArray("certSANs"); + Assert.assertEquals(2, certSans.size()); + Assert.assertEquals("10.1.1.10", certSans.get(0).getAsString()); + Assert.assertEquals("203.0.113.5", certSans.get(1).getAsString()); + Assert.assertEquals("10.1.1.10", docs.get(1).getAsJsonObject("localAPIEndpoint").get("advertiseAddress").getAsString()); + } + + @Test + public void buildStackedWithSettingsBehindPublicIp() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "203.0.113.5", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "0", "key", true, Map.of(Component.API_SERVER, Map.of("oidc-client-id", "kubernetes")), false, null)); + JsonArray certSans = docs.get(0).getAsJsonObject("apiServer").getAsJsonArray("certSANs"); + Assert.assertEquals(2, certSans.size()); + Assert.assertEquals("10.1.1.10", certSans.get(0).getAsString()); + Assert.assertEquals("203.0.113.5", certSans.get(1).getAsString()); + Assert.assertFalse(docs.get(1).has("localAPIEndpoint")); + } + + @Test + public void buildWithSettings() { + String kubelet = KubeadmConfigBuilder.normalizeKubeletConfig("{\"systemReserved\": {\"cpu\": \"500m\"}, \"evictionHard\": {\"memory.available\": \"10%\"}}"); + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "10.1.1.10", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "0", "key", true, + Map.of(Component.API_SERVER, Map.of("oidc-issuer-url", "https://idp.example.com/realms/k8s", "audit-log-maxage", "7")), true, kubelet)); + Assert.assertEquals(3, docs.size()); + JsonObject cluster = docs.get(0); + Assert.assertEquals("10.1.1.10:6443", cluster.get("controlPlaneEndpoint").getAsString()); + JsonObject extraArgs = cluster.getAsJsonObject("apiServer").getAsJsonObject("extraArgs"); + Assert.assertEquals("https://idp.example.com/realms/k8s", extraArgs.get("oidc-issuer-url").getAsString()); + Assert.assertEquals(KubeadmConfigBuilder.AUDIT_POLICY_PATH, extraArgs.get("audit-policy-file").getAsString()); + Assert.assertEquals("7", extraArgs.get("audit-log-maxage").getAsString()); + Assert.assertEquals("100", extraArgs.get("audit-log-maxsize").getAsString()); + Assert.assertEquals(2, cluster.getAsJsonObject("apiServer").getAsJsonArray("extraVolumes").size()); + JsonObject kubeletDoc = docs.get(2); + Assert.assertEquals("KubeletConfiguration", kubeletDoc.get("kind").getAsString()); + Assert.assertEquals("500m", kubeletDoc.getAsJsonObject("systemReserved").get("cpu").getAsString()); + Assert.assertEquals("10%", kubeletDoc.getAsJsonObject("evictionHard").get("memory.available").getAsString()); + } + + @Test + public void buildV1beta4ArgsAsList() { + List docs = parse(KubeadmConfigBuilder.build("1.31.0", "10.1.1.10", "10.1.1.10", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "0", "key", false, Map.of(Component.API_SERVER, Map.of("oidc-client-id", "kubernetes")), false, null)); + Assert.assertEquals("kubeadm.k8s.io/v1beta4", docs.get(0).get("apiVersion").getAsString()); + Assert.assertEquals("kubeadm.k8s.io/v1beta4", docs.get(1).get("apiVersion").getAsString()); + JsonObject arg = docs.get(0).getAsJsonObject("apiServer").getAsJsonArray("extraArgs").get(0).getAsJsonObject(); + Assert.assertEquals("oidc-client-id", arg.get("name").getAsString()); + Assert.assertEquals("kubernetes", arg.get("value").getAsString()); + } + + @Test + public void buildComponentArgsV1beta3() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "10.1.1.10", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "0", "key", true, Map.of( + Component.ETCD, Map.of("heartbeat-interval", "500", "election-timeout", "5000"), + Component.CONTROLLER_MANAGER, Map.of("leader-elect-lease-duration", "60s"), + Component.SCHEDULER, Map.of("leader-elect-retry-period", "5s")), false, null)); + JsonObject cluster = docs.get(0); + JsonObject etcdArgs = cluster.getAsJsonObject("etcd").getAsJsonObject("local").getAsJsonObject("extraArgs"); + Assert.assertEquals("500", etcdArgs.get("heartbeat-interval").getAsString()); + Assert.assertEquals("5000", etcdArgs.get("election-timeout").getAsString()); + Assert.assertEquals("60s", cluster.getAsJsonObject("controllerManager").getAsJsonObject("extraArgs").get("leader-elect-lease-duration").getAsString()); + Assert.assertEquals("5s", cluster.getAsJsonObject("scheduler").getAsJsonObject("extraArgs").get("leader-elect-retry-period").getAsString()); + Assert.assertFalse(cluster.getAsJsonObject("apiServer").has("extraArgs")); + } + + @Test + public void buildComponentArgsV1beta4() { + List docs = parse(KubeadmConfigBuilder.build("1.31.0", "10.1.1.10", "10.1.1.10", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "0", "key", true, Map.of( + Component.ETCD, Map.of("heartbeat-interval", "500"), + Component.SCHEDULER, Map.of("leader-elect-lease-duration", "60s")), false, null)); + JsonObject cluster = docs.get(0); + JsonObject etcdArg = cluster.getAsJsonObject("etcd").getAsJsonObject("local").getAsJsonArray("extraArgs").get(0).getAsJsonObject(); + Assert.assertEquals("heartbeat-interval", etcdArg.get("name").getAsString()); + Assert.assertEquals("500", etcdArg.get("value").getAsString()); + JsonObject schedulerArg = cluster.getAsJsonObject("scheduler").getAsJsonArray("extraArgs").get(0).getAsJsonObject(); + Assert.assertEquals("leader-elect-lease-duration", schedulerArg.get("name").getAsString()); + Assert.assertFalse(cluster.has("controllerManager")); + } + + @Test + public void buildExternalEtcdLeavesOutEtcdArgs() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "10.1.1.10", 6443, List.of("http://10.1.1.20:2379"), + "abcdef.0123456789abcdef", "0", "key", false, Map.of(Component.ETCD, Map.of("heartbeat-interval", "500")), false, null)); + JsonObject etcd = docs.get(0).getAsJsonObject("etcd"); + Assert.assertFalse(etcd.has("local")); + Assert.assertTrue(etcd.has("external")); + } + + @Test + public void etcdServiceArgs() { + Assert.assertEquals("", KubeadmConfigBuilder.etcdServiceArgs(Collections.emptyMap())); + Assert.assertEquals(" \\\n --election-timeout=5000 \\\n --heartbeat-interval=500 \\\n --log-outputs=a%%b", + KubeadmConfigBuilder.etcdServiceArgs(Map.of("heartbeat-interval", "500", "election-timeout", "5000", "log-outputs", "a%b"))); + } + + @Test + public void validComponentArgs() { + KubeadmConfigBuilder.validateArgs(Component.ETCD, Map.of("heartbeat-interval", "500", "election-timeout", "5000")); + KubeadmConfigBuilder.validateArgs(Component.CONTROLLER_MANAGER, Map.of("leader-elect-lease-duration", "60s", + "leader-elect-renew-deadline", "40s", "leader-elect-retry-period", "5s")); + KubeadmConfigBuilder.validateArgs(Component.SCHEDULER, Map.of("leader-elect-lease-duration", "60s")); + } + + @Test(expected = InvalidParameterValueException.class) + public void etcdArgManaged() { + KubeadmConfigBuilder.validateArgs(Component.ETCD, Map.of("initial-cluster", "a=http://10.0.0.1:2380")); + } + + @Test(expected = InvalidParameterValueException.class) + public void etcdArgWithSpace() { + KubeadmConfigBuilder.validateArgs(Component.ETCD, Map.of("heartbeat-interval", "500 --force-new-cluster")); + } + + @Test(expected = InvalidParameterValueException.class) + public void controllerManagerArgManaged() { + KubeadmConfigBuilder.validateArgs(Component.CONTROLLER_MANAGER, Map.of("controllers", "*,-bootstrapsigner")); + } + + @Test(expected = InvalidParameterValueException.class) + public void schedulerArgManaged() { + KubeadmConfigBuilder.validateArgs(Component.SCHEDULER, Map.of("config", "/tmp/scheduler.yaml")); + } + + @Test + public void controlPlaneArgsManaged() { + Map> managed = Map.of( + Component.API_SERVER, List.of("proxy-client-cert-file", "proxy-client-key-file"), + Component.CONTROLLER_MANAGER, List.of("leader-elect", "master", "cluster-name", "service-cluster-ip-range", "controllers"), + Component.SCHEDULER, List.of("leader-elect", "master", "config")); + managed.forEach((component, names) -> names.forEach(name -> Assert.assertThrows(component + " " + name, + InvalidParameterValueException.class, () -> KubeadmConfigBuilder.validateArgs(component, Map.of(name, "x"))))); + } + + @Test(expected = InvalidParameterValueException.class) + public void schedulerArgLeaderElect() { + KubeadmConfigBuilder.validateArgs(Component.SCHEDULER, Map.of("leader-elect", "false")); + } + + @Test(expected = InvalidParameterValueException.class) + public void etcdArgWalDir() { + KubeadmConfigBuilder.validateArgs(Component.ETCD, Map.of("wal-dir", "/var/lib/etcd-wal")); + } + + @Test(expected = InvalidParameterValueException.class) + public void schedulerArgRequestHeader() { + KubeadmConfigBuilder.validateArgs(Component.SCHEDULER, Map.of("requestheader-allowed-names", "foo")); + } + + @Test + public void validApiServerArgs() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("oidc-username-claim", "email", "oidc-username-prefix", "", + "oidc-groups-prefix", "oidc:", "oidc-required-claim", "hd=example.com")); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgWithDashes() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("--oidc-client-id", "kubernetes")); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgWithSpace() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("oidc-client-id", "kubernetes --anonymous-auth=true")); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgWithTemplate() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("oidc-client-id", "{{ds.meta_data}}")); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgManaged() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("audit-log-path", "/tmp/audit.log")); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgRequestHeader() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("requestheader-allowed-names", "foo")); + } + + @Test + public void buildKeepsNodeRestriction() { + List docs = parse(KubeadmConfigBuilder.build("1.30.2", "10.1.1.10", "10.1.1.10", 6443, Collections.emptyList(), + "abcdef.0123456789abcdef", "0", "key", false, Map.of(Component.API_SERVER, Map.of("enable-admission-plugins", "PodNodeSelector")), false, null)); + Assert.assertEquals("PodNodeSelector,NodeRestriction", + docs.get(0).getAsJsonObject("apiServer").getAsJsonObject("extraArgs").get("enable-admission-plugins").getAsString()); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgNeededToJoin() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("anonymous-auth", "false")); + } + + @Test(expected = InvalidParameterValueException.class) + public void apiServerArgSecurePort() { + KubeadmConfigBuilder.validateArgs(Component.API_SERVER, Map.of("secure-port", "7443")); + } + + @Test + public void argsToJsonKeepsEquals() { + Assert.assertEquals("{\"a\":\"x=y\",\"b\":\"1\"}", KubeadmConfigBuilder.argsToJson(Map.of("b", "1", "a", "x=y"))); + } + + @Test + public void argsFromJson() { + Assert.assertTrue(KubeadmConfigBuilder.argsFromJson(null).isEmpty()); + Assert.assertEquals(Map.of("a", "x=y"), KubeadmConfigBuilder.argsFromJson("{\"a\":\"x=y\"}")); + } + + @Test(expected = InvalidParameterValueException.class) + public void kubeletConfigCgroupDriver() { + KubeadmConfigBuilder.normalizeKubeletConfig("{\"cgroupDriver\": \"cgroupfs\"}"); + } + + @Test + public void kubeletConfigBlank() { + Assert.assertNull(KubeadmConfigBuilder.normalizeKubeletConfig(" ")); + } + + @Test(expected = InvalidParameterValueException.class) + public void kubeletConfigNotJson() { + KubeadmConfigBuilder.normalizeKubeletConfig("systemReserved: {cpu: 500m}"); + } + + @Test + public void kubeletConfigNotStrictJson() { + for (String config : new String[] {"{maxPods: 200}", "{'maxPods': '200'}", "{\"maxPods\": 200} {}"}) { + try { + KubeadmConfigBuilder.normalizeKubeletConfig(config); + Assert.fail("accepted " + config); + } catch (InvalidParameterValueException e) { + Assert.assertTrue(e.getMessage().startsWith("Kubelet configuration must be a JSON object")); + } + } + } + + @Test(expected = InvalidParameterValueException.class) + public void kubeletConfigNullValue() { + KubeadmConfigBuilder.normalizeKubeletConfig("{\"evictionHard\": {\"memory.available\": null}}"); + } + + @Test(expected = InvalidParameterValueException.class) + public void kubeletConfigNotObject() { + KubeadmConfigBuilder.normalizeKubeletConfig("[\"a\"]"); + } + + @Test(expected = InvalidParameterValueException.class) + public void kubeletConfigKind() { + KubeadmConfigBuilder.normalizeKubeletConfig("{\"kind\": \"KubeletConfiguration\"}"); + } + + @Test(expected = InvalidParameterValueException.class) + public void kubeletConfigUnsafeValue() { + KubeadmConfigBuilder.normalizeKubeletConfig("{\"systemReserved\": {\"cpu\": \"{% raw %}\"}}"); + } + + @Test + public void kubeletConfigNormalized() { + Assert.assertEquals("{\"maxPods\":200,\"serializeImagePulls\":false}", + KubeadmConfigBuilder.normalizeKubeletConfig("{ \"maxPods\": 200,\n \"serializeImagePulls\": false }")); + } + + @Test(expected = InvalidParameterValueException.class) + public void auditPolicySupplementaryCharacter() { + KubeadmConfigBuilder.validateAuditPolicy("# \uD83D\uDE00\nrules: []\n"); + } + + @Test(expected = InvalidParameterValueException.class) + public void auditPolicyBlank() { + KubeadmConfigBuilder.validateAuditPolicy(" "); + } + + @Test + public void auditPolicyWriteFile() throws IOException { + Assert.assertEquals("", KubeadmConfigBuilder.auditPolicyWriteFile(null)); + String policy = "apiVersion: audit.k8s.io/v1\nkind: Policy\nrules:\n- level: Metadata\n"; + String entry = KubeadmConfigBuilder.auditPolicyWriteFile(policy); + Assert.assertTrue(entry.startsWith("- path: " + KubeadmConfigBuilder.AUDIT_POLICY_PATH + "\n")); + Assert.assertTrue(entry.contains(" encoding: gz+b64\n")); + String content = entry.substring(entry.indexOf("content: ") + "content: ".length()); + try (GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(content)))) { + Assert.assertEquals(policy, new String(gzip.readAllBytes(), StandardCharsets.UTF_8)); + } + } +} diff --git a/plugins/integrations/kubernetes-service/src/test/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmdTest.java b/plugins/integrations/kubernetes-service/src/test/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmdTest.java new file mode 100644 index 000000000000..3cc805830c12 --- /dev/null +++ b/plugins/integrations/kubernetes-service/src/test/java/org/apache/cloudstack/api/command/user/kubernetes/cluster/CreateKubernetesClusterCmdTest.java @@ -0,0 +1,62 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.kubernetes.cluster; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.cloudstack.api.ApiConstants; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.kubernetes.cluster.utils.KubeadmConfigBuilder.Component; + +public class CreateKubernetesClusterCmdTest { + + private static Map> argsParam(String... keyValues) { + Map> param = new HashMap<>(); + for (int i = 0; i < keyValues.length; i += 2) { + param.put(String.valueOf(i / 2), Map.of(ApiConstants.KEY, keyValues[i], ApiConstants.VALUE, keyValues[i + 1])); + } + return param; + } + + @Test + public void getComponentArgs() { + CreateKubernetesClusterCmd cmd = new CreateKubernetesClusterCmd(); + ReflectionTestUtils.setField(cmd, "etcdArgs", argsParam("heartbeat-interval", "500", "election-timeout", "5000")); + ReflectionTestUtils.setField(cmd, "schedulerArgs", argsParam("leader-elect-lease-duration", "60s")); + Map> args = cmd.getComponentArgs(); + Assert.assertEquals(Map.of( + Component.ETCD, Map.of("heartbeat-interval", "500", "election-timeout", "5000"), + Component.SCHEDULER, Map.of("leader-elect-lease-duration", "60s")), args); + } + + @Test + public void getComponentArgsNone() { + Assert.assertTrue(new CreateKubernetesClusterCmd().getComponentArgs().isEmpty()); + } + + @Test(expected = InvalidParameterValueException.class) + public void getComponentArgsDuplicate() { + CreateKubernetesClusterCmd cmd = new CreateKubernetesClusterCmd(); + ReflectionTestUtils.setField(cmd, "controllerManagerArgs", argsParam("leader-elect-retry-period", "5s", "leader-elect-retry-period", "2s")); + cmd.getComponentArgs(); + } +} diff --git a/ui/public/locales/en.json b/ui/public/locales/en.json index a3d3a2285ac4..2e18011bf503 100644 --- a/ui/public/locales/en.json +++ b/ui/public/locales/en.json @@ -431,6 +431,8 @@ "label.apikeypair.name": "Name of the API key pair", "label.apikeypair.startdate": "API key pair valid from", "label.apikeypair.enddate": "API key pair valid until", +"label.apiserverargs": "kube-apiserver arguments", +"label.apiserverargs.tooltip": "kube-apiserver flags, one name=value per line, without the leading dashes. Flags that point to a file on the node, other than the audit policy, are not supported. Example: oidc-issuer-url=https://idp.example.com", "label.app.cookie": "AppCookie", "label.app.name": "CloudStack", "label.application.policy.set": "Application Policy Set", @@ -460,6 +462,7 @@ "label.asyncbackup": "Async backup", "label.attach.vol.to.instance": "Attach the created Volume to an existing Instance", "label.attaching": "Attaching", +"label.auditpolicy": "Audit policy", "label.authentication.method": "Authentication Method", "label.authentication.sshkey": "System SSH Key", "label.authorizeurl": "Authorize URL", @@ -699,6 +702,8 @@ "label.contents": "Contents", "label.continue": "Continue", "label.continue.install": "Continue with installation", +"label.controllermanagerargs": "kube-controller-manager arguments", +"label.controllermanagerargs.tooltip": "kube-controller-manager flags, one name=value per line, without the leading dashes. Example: leader-elect-lease-duration=60s", "label.controlnodes": "Control nodes", "label.conversionhost": "Conversion Host", "label.copied.clipboard": "Copied to clipboard", @@ -1576,6 +1581,7 @@ "label.delete.hsm.profile": "Delete HSM Profile", "label.select.kms.key.optional": "Select KMS Key (optional)", "label.kubeconfig.cluster": "Kubernetes Cluster config", +"label.kubeletconfig": "Kubelet configuration", "label.kubernetes": "Kubernetes", "label.kubernetes.access.details": "The kubernetes nodes can be accessed via ssh using:
ssh -i [ssh_key] -p [port_number] cloud@[public_ip_address]

where,
ssh_key: points to the ssh private key file corresponding to the key that was associated while creating the Kubernetes Cluster. If no ssh key was provided during Kubernetes cluster creation, use the ssh private key of the management server.
port_number: can be obtained from the Port Forwarding Tab (Public Port column)", "label.kubernetes.cluster.add.nodes.to.cluster": "Add nodes to Kubernetes cluster", @@ -2430,6 +2436,8 @@ "label.scaleup.policies": "ScaleUp policies", "label.scaleup.policy": "ScaleUp policy", "label.scaling": "Scaling", +"label.schedulerargs": "kube-scheduler arguments", +"label.schedulerargs.tooltip": "kube-scheduler flags, one name=value per line, without the leading dashes. Example: leader-elect-lease-duration=60s", "label.schedule": "Schedule", "label.scheduled": "Scheduled", "label.schedule.add": "Add schedule", @@ -3157,6 +3165,8 @@ "label.quotagb": "Quota in GB", "label.edgecluster": "Edge Cluster", "label.encryption": "Encryption", +"label.etcdargs": "etcd arguments", +"label.etcdargs.tooltip": "etcd flags, one name=value per line, without the leading dashes. Applied to the etcd members on the control nodes, or to the etcd nodes. Example: heartbeat-interval=500", "label.etcdnodes": "Number of etcd nodes", "label.controlaffinitygroupnames": "Control Affinity Groups", "label.workeraffinitygroupnames": "Worker Affinity Groups", @@ -4189,6 +4199,7 @@ "message.error.delete.dns.server": "Failed to delete DNS server", "message.error.delete.dns.zone": "Failed to delete DNS zone", "message.success.associate.dns.zone": "Successfully associated DNS zone with network", +"message.error.extra.args": "Each line needs a name and a value as name=value: {0}", "message.error.fetch.dns.zones": "Could not load DNS zones.", "message.success.add.guest.network": "Successfully created guest Network", "message.success.add.gpu.device": "Successfully added GPU device", diff --git a/ui/src/components/view/DetailsTab.vue b/ui/src/components/view/DetailsTab.vue index 9f94bf3a27d4..30a10b2dd8a5 100644 --- a/ui/src/components/view/DetailsTab.vue +++ b/ui/src/components/view/DetailsTab.vue @@ -144,6 +144,11 @@
{{ dataResource.cniconfigname }}
+
+ +
+
{{ formatJson(dataResource[item]) }}
+
{{ dataResource[item] }}
{{ dataResource[item].join(', ') }}
@@ -479,6 +484,13 @@ export default { } }, methods: { + formatJson (value) { + try { + return JSON.stringify(JSON.parse(value), null, 2) + } catch (e) { + return value + } + }, decodeUserData (userdata) { const decodedData = Buffer.from(userdata, 'base64') return decodedData.toString('utf-8') diff --git a/ui/src/config/section/compute.js b/ui/src/config/section/compute.js index 7c2c9f09eae4..e37105d638cc 100644 --- a/ui/src/config/section/compute.js +++ b/ui/src/config/section/compute.js @@ -596,7 +596,7 @@ export default { const filters = ['cloud.managed', 'external.managed'] return filters }, - details: ['name', 'description', 'zonename', 'kubernetesversionname', 'autoscalingenabled', 'csienabled', 'minsize', 'maxsize', 'size', 'controlnodes', 'controlaffinitygroupnames', 'etcdnodes', 'etcdaffinitygroupnames', 'workeraffinitygroupnames', 'cpunumber', 'memory', 'keypair', 'cniconfigname', 'associatednetworkname', 'account', 'domain', 'zonename', 'clustertype', 'created'], + details: ['name', 'description', 'zonename', 'kubernetesversionname', 'autoscalingenabled', 'csienabled', 'minsize', 'maxsize', 'size', 'controlnodes', 'controlaffinitygroupnames', 'etcdnodes', 'etcdaffinitygroupnames', 'workeraffinitygroupnames', 'cpunumber', 'memory', 'keypair', 'cniconfigname', 'associatednetworkname', 'apiserverargs', 'etcdargs', 'controllermanagerargs', 'schedulerargs', 'kubeletconfig', 'auditpolicy', 'account', 'domain', 'zonename', 'clustertype', 'created'], tabs: [ { name: 'k8s', diff --git a/ui/src/views/compute/CreateKubernetesCluster.vue b/ui/src/views/compute/CreateKubernetesCluster.vue index 618e46cb72d9..1107e0bac8f8 100644 --- a/ui/src/views/compute/CreateKubernetesCluster.vue +++ b/ui/src/views/compute/CreateKubernetesCluster.vue @@ -441,6 +441,34 @@ + + + + + + + + +
@@ -507,6 +535,12 @@ export default { props: {}, data () { return { + argFields: [ + { name: 'apiserverargs', placeholder: 'oidc-issuer-url=https://idp.example.com' }, + { name: 'etcdargs', placeholder: 'heartbeat-interval=500\nelection-timeout=5000' }, + { name: 'controllermanagerargs', placeholder: 'leader-elect-lease-duration=60s' }, + { name: 'schedulerargs', placeholder: 'leader-elect-lease-duration=60s' } + ], zones: [], zoneLoading: false, selectedZone: {}, @@ -597,6 +631,10 @@ export default { }, { type: 'number', validator: this.validateNumber } ], + apiserverargs: [{ validator: this.validateArgs }], + etcdargs: [{ validator: this.validateArgs }], + controllermanagerargs: [{ validator: this.validateArgs }], + schedulerargs: [{ validator: this.validateArgs }], dockerregistryusername: [{ required: true, message: this.$t('label.required') }], dockerregistrypassword: [{ required: true, message: this.$t('label.required') }], dockerregistryurl: [{ required: true, message: this.$t('label.required') }], @@ -1063,6 +1101,20 @@ export default { idx++ } } + if (values.advancedmode) { + this.argFields.forEach(field => { + this.parseArgs(values[field.name]).forEach(([name, value], i) => { + params[field.name + '[' + i + '].key'] = name + params[field.name + '[' + i + '].value'] = value + }) + }) + if (values.kubeletconfig?.trim()) { + params.kubeletconfig = values.kubeletconfig + } + if (values.auditpolicy?.trim()) { + params.auditpolicy = values.auditpolicy + } + } if ('asnumber' in values && this.isASNumberRequired()) { params.asnumber = values.asnumber } @@ -1087,6 +1139,22 @@ export default { this.formRef.value.scrollToField(error.errorFields[0].name) }) }, + async validateArgs (rule, value) { + const bad = this.parseArgs(value).find(([name, argValue]) => !name || !argValue) + if (bad) { + return Promise.reject(this.$t('message.error.extra.args', [bad[2]])) + } + return Promise.resolve() + }, + parseArgs (text) { + return (text || '').split('\n').map(line => line.trim()).filter(line => line).map(line => { + const eq = line.indexOf('=') + if (eq < 0) { + return ['', '', line] + } + return [line.substring(0, eq).replace(/^-+/, '').trim(), line.substring(eq + 1).trim(), line] + }) + }, closeAction () { this.$emit('close-action') },