From 508a4291d65841310466c403b617a6ab5a67c6ab Mon Sep 17 00:00:00 2001 From: Brad House Date: Sun, 29 Nov 2026 05:16:27 +0000 Subject: [PATCH] CKS: deploy the Ceph CSI RBD driver when a cluster is created On Ceph-backed zones, a CKS cluster that needs ReadWriteOnce volumes from Ceph gets them only after ceph-csi is installed by hand: its manifests, a config map with the monitors, a secret with the Ceph key and a StorageClass. createKubernetesCluster takes cephcsimonitors, cephcsipool, cephcsiuser and cephcsisecretkey. When they are given, the cluster is created with the ceph-csi RBD driver from the Kubernetes version ISO and a default StorageClass ceph-rbd on that pool. The key is stored encrypted in the cluster's details until the driver is deployed, then removed from them. It is copied to the control node as a file only the login user can read. The file is unlinked as soon as kubectl has it open, and it is applied server-side, so the key is never on a command line, in the node's user data or in a last-applied annotation. The request is marked as sensitive so the async job stores it encrypted. The cluster response returns cephcsipool, so the details tab shows which pool the cluster was created with for the driver; the key is never returned. In the create cluster form, advanced mode has a Ceph RBD storage switch that shows the monitors, pool, user and key (a password field that cannot be revealed). create-kubernetes-binaries-iso.sh adds the ceph-csi manifests and images to the ISO when CEPH_CSI_VERSION is set. Deleting a cluster with ceph-csi first deletes its PVCs with reclaim policy Delete, as for the CloudStack CSI driver. The cleanup now runs once before any node is destroyed (etcd nodes used to go first) and waits up to 120s for those PVs to go, so the driver can remove the backing volumes while the cluster still runs. Signed-off-by: Brad House --- .../apache/cloudstack/api/ApiConstants.java | 4 + .../cluster/KubernetesClusterManagerImpl.java | 43 +++++++++ .../KubernetesClusterActionWorker.java | 60 +++++++++++++ .../KubernetesClusterDestroyWorker.java | 9 +- .../KubernetesClusterStartWorker.java | 3 + .../cluster/CreateKubernetesClusterCmd.java | 36 +++++++- .../response/KubernetesClusterResponse.java | 8 ++ .../src/main/resources/conf/ceph-csi-rbd.yml | 86 ++++++++++++++++++ .../main/resources/conf/k8s-control-node.yml | 4 + .../script/delete-pv-reclaimpolicy-delete | 8 ++ .../KubernetesClusterManagerImplTest.java | 47 ++++++++++ .../KubernetesClusterActionWorkerTest.java | 90 +++++++++++++++++++ .../util/create-kubernetes-binaries-iso.sh | 19 ++++ ui/public/locales/en.json | 6 ++ ui/src/config/section/compute.js | 2 +- .../views/compute/CreateKubernetesCluster.vue | 53 +++++++++++ 16 files changed, 473 insertions(+), 5 deletions(-) create mode 100644 plugins/integrations/kubernetes-service/src/main/resources/conf/ceph-csi-rbd.yml 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 b9468f760d56..83c2dc5bd70e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java @@ -111,6 +111,10 @@ public class ApiConstants { public static final String READINESS_INITIAL_DELAY_SECONDS = "readinessinitialdelayseconds"; public static final String IGNORE_INSTANCE_STATE = "ignoreinstancestate"; public static final String CA_CERTIFICATES = "cacertificates"; + public static final String CEPH_CSI_MONITORS = "cephcsimonitors"; + public static final String CEPH_CSI_POOL = "cephcsipool"; + public static final String CEPH_CSI_SECRET_KEY = "cephcsisecretkey"; + public static final String CEPH_CSI_USER = "cephcsiuser"; public static final String CERTIFICATE = "certificate"; public static final String CERTIFICATE_CHAIN = "certchain"; public static final String CERTIFICATE_FINGERPRINT = "fingerprint"; 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..e7e08b4577f1 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 @@ -42,6 +42,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.inject.Inject; @@ -243,6 +244,7 @@ import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchBuilder; @@ -300,6 +302,10 @@ public class KubernetesClusterManagerImpl extends ManagerBase implements Kuberne ); private static final String PROJECT_KUBERNETES_ACCOUNT_FIRST_NAME = "Kubernetes"; private static final String PROJECT_KUBERNETES_ACCOUNT_LAST_NAME = "Service User"; + // The ceph-csi values are written into Kubernetes manifests, so only characters that cannot break them are accepted + private static final Pattern CEPH_CSI_MONITOR_PATTERN = Pattern.compile("[A-Za-z0-9.:\\[\\]-]+"); + private static final Pattern CEPH_CSI_NAME_PATTERN = Pattern.compile("[A-Za-z0-9._-]+"); + private static final Pattern CEPH_CSI_KEY_PATTERN = Pattern.compile("[A-Za-z0-9+/]+={0,2}"); private static final String DEFAULT_NETWORK_OFFERING_FOR_KUBERNETES_SERVICE_DISPLAY_TEXT = "Network Offering used for CloudStack Kubernetes service"; private static final String DEFAULT_NSX_NETWORK_OFFERING_FOR_KUBERNETES_SERVICE_NAME = "DefaultNSXNetworkOfferingforKubernetesService"; private static final String DEFAULT_NSX_VPC_TIER_NETWORK_OFFERING_FOR_KUBERNETES_SERVICE_NAME = "DefaultNSXVPCNetworkOfferingforKubernetesService"; @@ -961,6 +967,10 @@ public KubernetesClusterResponse createKubernetesClusterResponse(long kubernetes response.setMaxSize(kubernetesCluster.getMaxSize()); response.setClusterType(kubernetesCluster.getClusterType()); response.setCsiEnabled(kubernetesCluster.isCsiEnabled()); + KubernetesClusterDetailsVO cephCsiPool = kubernetesClusterDetailsDao.findDetail(kubernetesCluster.getId(), ApiConstants.CEPH_CSI_POOL); + if (cephCsiPool != null) { + response.setCephCsiPool(cephCsiPool.getValue()); + } response.setCreated(kubernetesCluster.getCreated()); setNodeTypeAffinityGroupResponse(response, kubernetesCluster.getId()); @@ -1178,6 +1188,8 @@ private void validateManagedKubernetesClusterCreateParameters(final CreateKubern validateDockerRegistryParams(dockerRegistryUserName, dockerRegistryPassword, dockerRegistryUrl); + validateCephCsiParams(cmd.getCephCsiMonitors(), cmd.getCephCsiPool(), cmd.getCephCsiUser(), cmd.getCephCsiSecretKey()); + Network network = validateAndGetNetworkForKubernetesCreateParameters(networkId); if (StringUtils.isNotEmpty(externalLoadBalancerIpAddress)) { @@ -1201,6 +1213,32 @@ private void validateManagedKubernetesClusterCreateParameters(final CreateKubern } } + protected void validateCephCsiParams(final String monitors, final String pool, final String user, final String secretKey) { + if (StringUtils.isAllEmpty(monitors, pool, user, secretKey)) { + return; + } + if (StringUtils.isAnyEmpty(monitors, pool, user, secretKey)) { + throw new InvalidParameterValueException(String.format("%s, %s, %s and %s must be given together", + ApiConstants.CEPH_CSI_MONITORS, ApiConstants.CEPH_CSI_POOL, ApiConstants.CEPH_CSI_USER, ApiConstants.CEPH_CSI_SECRET_KEY)); + } + for (String monitor : monitors.split(",", -1)) { + if (!CEPH_CSI_MONITOR_PATTERN.matcher(monitor.trim()).matches()) { + throw new InvalidParameterValueException(String.format("Invalid Ceph monitor address '%s' in %s: give host or host:port, separated by commas", + monitor, ApiConstants.CEPH_CSI_MONITORS)); + } + } + if (user.startsWith("client.")) { + throw new InvalidParameterValueException(String.format("Give %s without the 'client.' prefix", ApiConstants.CEPH_CSI_USER)); + } + if (!CEPH_CSI_NAME_PATTERN.matcher(pool).matches() || !CEPH_CSI_NAME_PATTERN.matcher(user).matches()) { + throw new InvalidParameterValueException(String.format("%s and %s may contain only letters, digits, '.', '_' and '-'", + ApiConstants.CEPH_CSI_POOL, ApiConstants.CEPH_CSI_USER)); + } + if (!CEPH_CSI_KEY_PATTERN.matcher(secretKey).matches()) { + throw new InvalidParameterValueException(String.format("Invalid %s: give the key as printed by 'ceph auth get-key'", ApiConstants.CEPH_CSI_SECRET_KEY)); + } + } + protected void validateServiceOfferingsForNodeTypes(Map map, Long defaultServiceOfferingId, Long etcdNodes, @@ -1320,6 +1358,11 @@ public void doInTransactionWithoutResult(TransactionStatus status) { addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.DOCKER_REGISTRY_URL, dockerRegistryUrl, true); if (kubernetesCluster.getClusterType() == KubernetesCluster.ClusterType.CloudManaged) { details.add(new KubernetesClusterDetailsVO(kubernetesClusterId, "networkCleanup", String.valueOf(networkCleanup), true)); + addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.CEPH_CSI_MONITORS, cmd.getCephCsiMonitors(), true); + addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.CEPH_CSI_POOL, cmd.getCephCsiPool(), true); + addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.CEPH_CSI_USER, cmd.getCephCsiUser(), true); + addKubernetesClusterDetailIfIsNotEmpty(details, kubernetesClusterId, ApiConstants.CEPH_CSI_SECRET_KEY, + DBEncryptionUtil.encrypt(cmd.getCephCsiSecretKey()), false); } kubernetesClusterDetailsDao.saveDetails(details); } diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java index 07c9f12a50e2..eb411766bf0e 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java @@ -21,6 +21,7 @@ import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -57,6 +58,7 @@ import com.cloud.user.SSHKeyPairVO; import com.cloud.user.dao.UserDataDao; import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.TransactionCallbackWithException; import com.cloud.utils.net.Ip; import com.cloud.vm.Nic; @@ -268,6 +270,7 @@ protected String resolveApiPublicIpAddress(Network network) { protected final String deployProviderScriptFilename = "deploy-provider"; protected final String deployCsiDriverScriptFilename = "deploy-csi-driver"; protected final String deletePvScriptFilename = "delete-pv-reclaimpolicy-delete"; + protected final String cephCsiConfigFilename = "ceph-csi-rbd.yml"; protected final String autoscaleScriptFilename = "autoscale-kube-cluster"; protected final String validateNodeScript = "validate-cks-node"; protected final String removeNodeFromClusterScript = "remove-node-from-cluster"; @@ -970,6 +973,63 @@ protected boolean deployCsiDriver() { } } + protected boolean isCephCsiEnabled() { + return kubernetesClusterDetailsDao.findDetail(kubernetesCluster.getId(), ApiConstants.CEPH_CSI_MONITORS) != null; + } + + protected String getCephCsiConfig() throws IOException { + Map details = kubernetesClusterDetailsDao.listDetailsKeyPairs(kubernetesCluster.getId(), List.of( + ApiConstants.CEPH_CSI_MONITORS, ApiConstants.CEPH_CSI_POOL, ApiConstants.CEPH_CSI_USER, ApiConstants.CEPH_CSI_SECRET_KEY)); + String monitors = Arrays.stream(details.get(ApiConstants.CEPH_CSI_MONITORS).split(",")) + .map(monitor -> String.format("\"%s\"", monitor.trim())) + .collect(Collectors.joining(", ")); + return readK8sConfigFile("/conf/" + cephCsiConfigFilename) + .replace("{{ ceph.monitors }}", monitors) + .replace("{{ ceph.pool }}", details.get(ApiConstants.CEPH_CSI_POOL)) + .replace("{{ ceph.user }}", details.get(ApiConstants.CEPH_CSI_USER)) + .replace("{{ ceph.key }}", DBEncryptionUtil.decrypt(details.get(ApiConstants.CEPH_CSI_SECRET_KEY))); + } + + /** + * Applies the ceph-csi manifests that setup-kube-system copied from the ISO, together with the cluster's + * Ceph configuration. The configuration holds the Ceph key, so it is copied as a file readable only by the + * login user rather than passed on a command line, and applied server-side so that kubectl does not copy it + * into a last-applied annotation. Once the cluster holds the key, it is removed from the database. + */ + protected void deployCephCsi() { + File pkFile = getManagementServerSshPublicKeyFile(); + Pair publicIpSshPort = getKubernetesClusterServerIpSshPort(null); + publicIpAddress = publicIpSshPort.first(); + sshPort = publicIpSshPort.second(); + try { + SshHelper.scpTo(publicIpAddress, sshPort, getControlNodeLoginUser(), pkFile, null, "~/", + getCephCsiConfig().getBytes(StandardCharsets.UTF_8), cephCsiConfigFilename, "0600"); + // The file is opened as stdin and unlinked before kubectl runs, so the key does not stay on disk if the session dies + String command = String.format("{ rm -f ~/%1$s; sudo /opt/bin/kubectl apply --server-side -f - -f /opt/ceph-csi/; } < ~/%1$s", + cephCsiConfigFilename); + Pair result = SshHelper.sshExecute(publicIpAddress, sshPort, getControlNodeLoginUser(), + pkFile, null, command, 10000, 10000, 60000); + if (!result.first()) { + throw new CloudRuntimeException(result.second()); + } + } catch (Exception e) { + removeCephCsiConfigFile(pkFile); + logTransitStateAndThrow(Level.ERROR, String.format("Failed to deploy ceph-csi in Kubernetes cluster %s: %s", + kubernetesCluster.getName(), e.getMessage()), + kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed, e); + } + kubernetesClusterDetailsDao.removeDetail(kubernetesCluster.getId(), ApiConstants.CEPH_CSI_SECRET_KEY); + } + + private void removeCephCsiConfigFile(File pkFile) { + try { + SshHelper.sshExecute(publicIpAddress, sshPort, getControlNodeLoginUser(), pkFile, null, + String.format("rm -f ~/%s", cephCsiConfigFilename), 10000, 10000, 10000); + } catch (Exception e) { + logger.warn("Unable to remove {} from the control node of Kubernetes cluster {}", cephCsiConfigFilename, kubernetesCluster, e); + } + } + public void setKeys(String[] keys) { this.keys = keys; } diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterDestroyWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterDestroyWorker.java index ac6a64e2fb0c..9ff1ac58a258 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterDestroyWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterDestroyWorker.java @@ -94,6 +94,12 @@ private void validateClusterSate() { private boolean destroyClusterVMs() { boolean vmDestroyed = true; if (!CollectionUtils.isEmpty(clusterVMs)) { + // Before any node goes: etcd nodes come first in the list, and the CSI driver needs the whole cluster + boolean controlNodeExists = clusterVMs.stream() + .anyMatch(clusterVM -> clusterVM.isControlNode() && userVmDao.findById(clusterVM.getVmId()) != null); + if (controlNodeExists && (kubernetesCluster.isCsiEnabled() || isCephCsiEnabled())) { + deletePVsWithReclaimPolicyDelete(); + } for (KubernetesClusterVmMapVO clusterVM : clusterVMs) { long vmID = clusterVM.getVmId(); @@ -106,9 +112,6 @@ private boolean destroyClusterVMs() { ApiCommandResourceType.VirtualMachine); vmContext.setEventResourceId(vmID); try { - if (clusterVM.isControlNode() && kubernetesCluster.isCsiEnabled()) { - deletePVsWithReclaimPolicyDelete(); - } UserVm vm = userVmService.destroyVm(vmID, true); if (!userVmManager.expunge(userVM)) { logger.warn("Unable to expunge VM {}, destroying Kubernetes cluster will probably fail", vm); 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..a01f1d56508e 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 @@ -894,6 +894,9 @@ public boolean startKubernetesClusterOnCreate(Long domainId, Long accountId, Lon if (kubernetesCluster.isCsiEnabled()) { deployCsiDriver(); } + if (isCephCsiEnabled()) { + deployCephCsi(); + } updateLoginUserDetails(clusterVMs.stream().map(InternalIdentity::getId).collect(Collectors.toList())); stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationSucceeded); return true; 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..c1cb1e6d80ad 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 @@ -71,7 +71,7 @@ responseObject = KubernetesClusterResponse.class, responseView = ResponseView.Restricted, entityType = {KubernetesCluster.class}, - requestHasSensitiveInfo = false, + requestHasSensitiveInfo = true, responseHasSensitiveInfo = true, authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) public class CreateKubernetesClusterCmd extends BaseAsyncCreateCmd { @@ -221,6 +221,24 @@ public class CreateKubernetesClusterCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.ENABLE_CSI, type = CommandType.BOOLEAN, description = "if true, setups up CloudStack CSI driver", since = "4.22.0") private Boolean enableCsi; + @Parameter(name = ApiConstants.CEPH_CSI_MONITORS, type = CommandType.STRING, + description = "Comma-separated Ceph monitor addresses (host or host:port, with the v1 port, 6789 by default). If set, the Ceph CSI RBD driver is deployed " + + "in the cluster with a default StorageClass named ceph-rbd. Needs cephcsipool, cephcsiuser and cephcsisecretkey, " + + "and a Kubernetes version ISO that includes ceph-csi", since = "24.0.0") + private String cephCsiMonitors; + + @Parameter(name = ApiConstants.CEPH_CSI_POOL, type = CommandType.STRING, + description = "Ceph RBD pool in which the Ceph CSI driver creates the cluster's volumes", since = "24.0.0") + private String cephCsiPool; + + @Parameter(name = ApiConstants.CEPH_CSI_USER, type = CommandType.STRING, + description = "Ceph user for the Ceph CSI driver, without the client. prefix", since = "24.0.0") + private String cephCsiUser; + + @Parameter(name = ApiConstants.CEPH_CSI_SECRET_KEY, type = CommandType.STRING, + description = "Key of the Ceph user given in cephcsiuser", since = "24.0.0") + private String cephCsiSecretKey; + @Parameter(name=ApiConstants.AS_NUMBER, type=CommandType.LONG, description="the AS Number of the network") private Long asNumber; @@ -393,6 +411,22 @@ public boolean getEnableCsi() { return Objects.nonNull(enableCsi) ? enableCsi : Boolean.FALSE; } + public String getCephCsiMonitors() { + return cephCsiMonitors; + } + + public String getCephCsiPool() { + return cephCsiPool; + } + + public String getCephCsiUser() { + return cephCsiUser; + } + + public String getCephCsiSecretKey() { + return cephCsiSecretKey; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// 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..0b88b14eae40 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,10 @@ 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.CEPH_CSI_POOL) + @Param(description = "The Ceph RBD pool given for the Ceph CSI driver when the cluster was created", since = "24.0.0") + private String cephCsiPool; + @SerializedName(ApiConstants.CLUSTER_TYPE) @Param(description = "The type of the cluster") private KubernetesCluster.ClusterType clusterType; @@ -560,6 +564,10 @@ public void setCsiEnabled(Boolean csiEnabled) { isCsiEnabled = csiEnabled; } + public void setCephCsiPool(String cephCsiPool) { + this.cephCsiPool = cephCsiPool; + } + public void setControlAffinityGroupIds(String controlAffinityGroupIds) { this.controlAffinityGroupIds = controlAffinityGroupIds; } diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/ceph-csi-rbd.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/ceph-csi-rbd.yml new file mode 100644 index 000000000000..6228ec688e4b --- /dev/null +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/ceph-csi-rbd.yml @@ -0,0 +1,86 @@ +# 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. + +# Cluster-specific configuration for the ceph-csi RBD driver. The driver's own +# manifests come from the Kubernetes version ISO (ceph-csi/ directory). +--- +apiVersion: v1 +kind: Namespace +metadata: + name: ceph-csi-rbd +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: ceph-csi-config + namespace: ceph-csi-rbd +data: + config.json: |- + [{"clusterID": "ceph", "monitors": [{{ ceph.monitors }}]}] +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: ceph-config + namespace: ceph-csi-rbd +data: + ceph.conf: | + [global] + auth_cluster_required = cephx + auth_service_required = cephx + auth_client_required = cephx + keyring: "" +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: ceph-csi-encryption-kms-config + namespace: ceph-csi-rbd +data: + config.json: "{}" +--- +apiVersion: v1 +kind: Secret +metadata: + name: csi-rbd-secret + namespace: ceph-csi-rbd +stringData: + userID: "{{ ceph.user }}" + userKey: "{{ ceph.key }}" +--- +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: ceph-rbd + annotations: + storageclass.kubernetes.io/is-default-class: "true" +provisioner: rbd.csi.ceph.com +parameters: + clusterID: ceph + pool: "{{ ceph.pool }}" + imageFeatures: layering,exclusive-lock,object-map,fast-diff + csi.storage.k8s.io/fstype: ext4 + csi.storage.k8s.io/provisioner-secret-name: csi-rbd-secret + csi.storage.k8s.io/provisioner-secret-namespace: ceph-csi-rbd + csi.storage.k8s.io/controller-expand-secret-name: csi-rbd-secret + csi.storage.k8s.io/controller-expand-secret-namespace: ceph-csi-rbd + csi.storage.k8s.io/node-stage-secret-name: csi-rbd-secret + csi.storage.k8s.io/node-stage-secret-namespace: ceph-csi-rbd +reclaimPolicy: Delete +allowVolumeExpansion: true +mountOptions: + - discard 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..259701bfdd7c 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 @@ -184,6 +184,10 @@ write_files: cp "${BINARIES_DIR}/snapshot-crds.yaml" /opt/csi/snapshot-crds.yaml cp "${BINARIES_DIR}/manifest.yaml" /opt/csi/manifest.yaml fi + if [ -d "${BINARIES_DIR}/ceph-csi" ]; then + mkdir -p /opt/ceph-csi + cp "${BINARIES_DIR}"/ceph-csi/*.yaml /opt/ceph-csi/ + fi PAUSE_IMAGE=`ctr -n k8s.io images ls -q | grep "pause" | sort | tail -n 1` echo $PAUSE_IMAGE diff --git a/plugins/integrations/kubernetes-service/src/main/resources/script/delete-pv-reclaimpolicy-delete b/plugins/integrations/kubernetes-service/src/main/resources/script/delete-pv-reclaimpolicy-delete index 34e07e0bbe30..0f988abe0e8a 100755 --- a/plugins/integrations/kubernetes-service/src/main/resources/script/delete-pv-reclaimpolicy-delete +++ b/plugins/integrations/kubernetes-service/src/main/resources/script/delete-pv-reclaimpolicy-delete @@ -152,6 +152,7 @@ delete_workloads_using_pvc() { } total_pvcs=0 +deleted_pvs="" processed_pvcs=0 echo "$(timestamp) - Scanning for PVCs with associated PVs having reclaimPolicy=Delete..." @@ -167,6 +168,7 @@ while read namespace pvc_name pv_name; do delete_workloads_using_pvc "$namespace" "$pvc_name" echo "$(timestamp) - Deleting PVC $pvc_name in namespace $namespace" /opt/bin/kubectl delete pvc "$pvc_name" -n "$namespace" --ignore-not-found=true + deleted_pvs="$deleted_pvs pv/$pv_name" echo "$(timestamp) - Completed processing PVC $pvc_name" echo "---" @@ -174,5 +176,11 @@ while read namespace pvc_name pv_name; do fi done < <(/opt/bin/kubectl get pvc --all-namespaces --no-headers -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,VOLUME:.spec.volumeName) +# The CSI driver deletes the backing volumes only while the cluster runs, so wait before its nodes go +if [ -n "$deleted_pvs" ]; then + echo "$(timestamp) - Waiting for the PVs to be deleted..." + /opt/bin/kubectl wait --for=delete $deleted_pvs --timeout=120s || echo "$(timestamp) - Some PVs were not deleted after 120s" +fi + echo "$(timestamp) - Script completed successfully!" echo "$(timestamp) - Summary: Processed $processed_pvcs PVC(s) out of $total_pvcs total PVC(s) found" diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImplTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImplTest.java index 1fab5420c3c3..e0f5ec235216 100644 --- a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImplTest.java +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/KubernetesClusterManagerImplTest.java @@ -914,4 +914,51 @@ public void testValidateNodeAffinityGroupsAffinityNoExistingWorkers() { Mockito.verify(kubernetesClusterAffinityGroupMapDao).listAffinityGroupIdsByClusterIdAndNodeType(1L, WORKER.name()); } + + private static final String CEPH_KEY = "AQBzc2VjcmV0a2V5Zm9ydGVzdGluZ29ubHk9PQ=="; + + @Test + public void testValidateCephCsiParamsAcceptsNoCephCsi() { + kubernetesClusterManager.validateCephCsiParams(null, null, null, null); + } + + @Test + public void testValidateCephCsiParamsAcceptsCompleteConfiguration() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1:6789, mon2.example.com,[fd00::1]:6789", "k8s-rbd", "k8s.rbd_user", CEPH_KEY); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsMissingKey() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1:6789", "k8s-rbd", "k8s", null); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsMonitorThatWouldBreakTheManifest() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1:6789\"]", "k8s-rbd", "k8s", CEPH_KEY); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsEmptyMonitorEntry() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1:6789,,10.0.0.2", "k8s-rbd", "k8s", CEPH_KEY); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsMonitorsMadeOfCommasOnly() { + kubernetesClusterManager.validateCephCsiParams(",", "k8s-rbd", "k8s", CEPH_KEY); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsUserWithClientPrefix() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1", "k8s-rbd", "client.k8s", CEPH_KEY); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsPoolWithQuote() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1", "k8s\"rbd", "k8s", CEPH_KEY); + } + + @Test(expected = InvalidParameterValueException.class) + public void testValidateCephCsiParamsRejectsKeyThatIsNotBase64() { + kubernetesClusterManager.validateCephCsiParams("10.0.0.1", "k8s-rbd", "k8s", "not a key"); + } } diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java index a25ec55cc04a..ccc69068a085 100644 --- a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java @@ -16,10 +16,13 @@ // under the License. package com.cloud.kubernetes.cluster.actionworkers; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.UUID; import org.apache.cloudstack.affinity.AffinityGroupVO; @@ -30,6 +33,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @@ -46,6 +50,10 @@ import com.cloud.network.Network; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressVO; +import com.cloud.utils.Pair; +import com.cloud.utils.crypt.DBEncryptionUtil; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.ssh.SshHelper; @RunWith(MockitoJUnitRunner.class) public class KubernetesClusterActionWorkerTest { @@ -229,4 +237,86 @@ public void testGetMergedAffinityGroupIdsExplicitDedicationAlreadyInList() { Assert.assertTrue(result.contains(99L)); Assert.assertTrue(result.contains(2L)); } + + @Test + public void testGetCephCsiConfigFillsTheClusterValuesIntoTheTemplate() throws Exception { + KubernetesClusterActionWorker worker = Mockito.spy(actionWorker); + Mockito.doReturn(Files.readString(Paths.get("src/main/resources/conf/ceph-csi-rbd.yml"))).when(worker).readK8sConfigFile("/conf/ceph-csi-rbd.yml"); + Mockito.when(kubernetesClusterDetailsDao.listDetailsKeyPairs(DEFAULT_ID, List.of(ApiConstants.CEPH_CSI_MONITORS, + ApiConstants.CEPH_CSI_POOL, ApiConstants.CEPH_CSI_USER, ApiConstants.CEPH_CSI_SECRET_KEY))).thenReturn(Map.of( + ApiConstants.CEPH_CSI_MONITORS, "10.0.0.1:6789, 10.0.0.2:6789", + ApiConstants.CEPH_CSI_POOL, "k8s-rbd", + ApiConstants.CEPH_CSI_USER, "k8s", + ApiConstants.CEPH_CSI_SECRET_KEY, "encrypted-key")); + try (MockedStatic encryption = Mockito.mockStatic(DBEncryptionUtil.class)) { + encryption.when(() -> DBEncryptionUtil.decrypt("encrypted-key")).thenReturn("plain-key"); + + String config = worker.getCephCsiConfig(); + + Assert.assertTrue(config.contains("\"monitors\": [\"10.0.0.1:6789\", \"10.0.0.2:6789\"]")); + Assert.assertTrue(config.contains("pool: \"k8s-rbd\"")); + Assert.assertTrue(config.contains("userID: \"k8s\"")); + Assert.assertTrue(config.contains("userKey: \"plain-key\"")); + Assert.assertFalse(config.contains("{{")); + } + } + + private KubernetesClusterActionWorker mockCephCsiDeploy() throws Exception { + KubernetesClusterActionWorker worker = Mockito.spy(actionWorker); + Mockito.doReturn(null).when(worker).getManagementServerSshPublicKeyFile(); + Mockito.doReturn(new Pair<>("192.0.2.10", 2222)).when(worker).getKubernetesClusterServerIpSshPort(null); + Mockito.doReturn("cloud").when(worker).getControlNodeLoginUser(); + Mockito.doReturn("ceph-csi config").when(worker).getCephCsiConfig(); + return worker; + } + + private void mockKubectlApply(MockedStatic sshHelper, boolean success) { + sshHelper.when(() -> SshHelper.sshExecute(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.any(), Mockito.any(), + Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(new Pair<>(success, "kubectl output")); + } + + @Test + public void testDeployCephCsiCopiesTheConfigAsAPrivateFileAndRemovesItBeforeApplying() throws Exception { + KubernetesClusterActionWorker worker = mockCephCsiDeploy(); + try (MockedStatic sshHelper = Mockito.mockStatic(SshHelper.class)) { + mockKubectlApply(sshHelper, true); + + worker.deployCephCsi(); + + sshHelper.verify(() -> SshHelper.scpTo("192.0.2.10", 2222, "cloud", null, null, "~/", + "ceph-csi config".getBytes(), "ceph-csi-rbd.yml", "0600")); + sshHelper.verify(() -> SshHelper.sshExecute("192.0.2.10", 2222, "cloud", null, null, + "{ rm -f ~/ceph-csi-rbd.yml; sudo /opt/bin/kubectl apply --server-side -f - -f /opt/ceph-csi/; } < ~/ceph-csi-rbd.yml", + 10000, 10000, 60000)); + Mockito.verify(kubernetesClusterDetailsDao).removeDetail(DEFAULT_ID, ApiConstants.CEPH_CSI_SECRET_KEY); + } + } + + @Test(expected = CloudRuntimeException.class) + public void testDeployCephCsiFailsTheClusterWhenTheManifestsCannotBeApplied() throws Exception { + KubernetesClusterActionWorker worker = mockCephCsiDeploy(); + Mockito.doReturn(true).when(worker).stateTransitTo(DEFAULT_ID, KubernetesCluster.Event.OperationFailed); + Mockito.doNothing().when(worker).deleteTemplateLaunchPermission(); + try (MockedStatic sshHelper = Mockito.mockStatic(SshHelper.class)) { + mockKubectlApply(sshHelper, false); + + worker.deployCephCsi(); + } finally { + Mockito.verify(kubernetesClusterDetailsDao, Mockito.never()).removeDetail(DEFAULT_ID, ApiConstants.CEPH_CSI_SECRET_KEY); + } + } + + @Test + public void testDeployCephCsiRemovesTheConfigFileWhenTheApplyFails() throws Exception { + KubernetesClusterActionWorker worker = mockCephCsiDeploy(); + Mockito.doReturn(true).when(worker).stateTransitTo(DEFAULT_ID, KubernetesCluster.Event.OperationFailed); + Mockito.doNothing().when(worker).deleteTemplateLaunchPermission(); + try (MockedStatic sshHelper = Mockito.mockStatic(SshHelper.class)) { + mockKubectlApply(sshHelper, false); + + Assert.assertThrows(CloudRuntimeException.class, worker::deployCephCsi); + + sshHelper.verify(() -> SshHelper.sshExecute("192.0.2.10", 2222, "cloud", null, null, "rm -f ~/ceph-csi-rbd.yml", 10000, 10000, 10000)); + } + } } diff --git a/scripts/util/create-kubernetes-binaries-iso.sh b/scripts/util/create-kubernetes-binaries-iso.sh index 00234f205114..1adbca299a96 100755 --- a/scripts/util/create-kubernetes-binaries-iso.sh +++ b/scripts/util/create-kubernetes-binaries-iso.sh @@ -21,6 +21,8 @@ set -e if [ $# -lt 6 ]; then echo "Invalid input. Valid usage: ./create-kubernetes-binaries-iso.sh OUTPUT_PATH KUBERNETES_VERSION CNI_VERSION CRICTL_VERSION WEAVENET_NETWORK_YAML_CONFIG HEADLAMP_DASHBOARD_VERSION BUILD_NAME [ARCH] [ETCD_VERSION]" echo "eg: ./create-kubernetes-binaries-iso.sh ./ 1.11.4 0.7.1 1.11.1 https://github.com/weaveworks/weave/releases/download/latest_release/weave-daemonset-k8s-1.11.yaml 0.40.1 setup-v1.11.4 amd64" + echo "Optional environment variable:" + echo " CEPH_CSI_VERSION include this ceph-csi release (RBD driver), e.g. 3.18.2, for clusters created with cephcsimonitors" exit 1 fi @@ -118,6 +120,18 @@ echo "Including CloudStack CSI Driver manifest" wget https://github.com/cloudstack/cloudstack-csi-driver/releases/download/v3.0.0/snapshot-crds.yaml -O ${working_dir}/snapshot-crds.yaml wget https://github.com/cloudstack/cloudstack-csi-driver/releases/download/v3.0.0/manifest.yaml -O ${csi_conf_file} +if [ -n "${CEPH_CSI_VERSION}" ]; then + CEPH_CSI_VERSION="v${CEPH_CSI_VERSION#v}" + echo "Including ceph-csi ${CEPH_CSI_VERSION} RBD driver manifests" + ceph_csi_dir="${working_dir}/ceph-csi" + mkdir -p "${ceph_csi_dir}" + for manifest in csidriver.yaml csi-provisioner-rbac.yaml csi-nodeplugin-rbac.yaml csi-rbdplugin-provisioner.yaml csi-rbdplugin.yaml; do + curl -fsSL "https://raw.githubusercontent.com/ceph/ceph-csi/${CEPH_CSI_VERSION}/deploy/rbd/kubernetes/${manifest}" -o "${ceph_csi_dir}/${manifest}" + done + # The upstream manifests use the default namespace + sed -i "s/namespace: default/namespace: ceph-csi-rbd/" "${ceph_csi_dir}"/*.yaml +fi + echo "Fetching k8s docker images..." ctr -v if [ $? -ne 0 ]; then @@ -153,6 +167,11 @@ output=`printf "%s\n" ${output} ${provider_image}` csi_images=`grep "image:" "${csi_conf_file}" | cut -d ':' -f2- | tr -d ' ' | tr -d "'"` output=`printf "%s\n%s" "${output}" "${csi_images}"` +if [ -n "${CEPH_CSI_VERSION}" ]; then + ceph_csi_images=`grep -h "image:" "${ceph_csi_dir}"/*.yaml | cut -d ':' -f2- | tr -d ' ' | tr -d "'" | sort -u` + output=`printf "%s\n%s" "${output}" "${ceph_csi_images}"` +fi + while read -r line; do echo "Downloading image $line ---" if [[ $line == kubernetesui* ]] || [[ $line == apache* ]] || [[ $line == weaveworks* ]]; then diff --git a/ui/public/locales/en.json b/ui/public/locales/en.json index a3d3a2285ac4..344300763ebd 100644 --- a/ui/public/locales/en.json +++ b/ui/public/locales/en.json @@ -555,6 +555,11 @@ "label.capacitybytes": "Capacity bytes", "label.capacityiops": "IOPS total", "label.category": "Category", +"label.ceph.csi.rbd": "Ceph RBD storage", +"label.cephcsimonitors": "Ceph monitors", +"label.cephcsipool": "Ceph RBD pool", +"label.cephcsisecretkey": "Ceph key", +"label.cephcsiuser": "Ceph user", "label.certchain": "Chain", "label.certificate": "Certificate", "label.certificate.chain": "Certificate chain", @@ -3450,6 +3455,7 @@ "message.backup.update.existing.schedule": "Updating existing backup schedule for the same interval type", "message.cancel.shutdown": "Please confirm that you would like to cancel the shutdown on this Management Server. It will resume accepting any new Async Jobs.", "message.cancel.maintenance": "Please confirm that you would like to cancel the maintenance on this Management Server. It will resume accepting any new Async Jobs.", +"message.ceph.csi.rbd": "Deploys the Ceph CSI RBD driver with a default StorageClass named ceph-rbd. Needs a Kubernetes version ISO that includes ceph-csi.", "message.certificate.upload.processing": "Certificate upload in progress", "message.change.disk.offering.sharedfs.failed": "Failed to change disk offering for the Shared FileSystem.", "message.change.disk.offering.sharedfs.processing": "Changing disk offering for the Shared FileSystem.", diff --git a/ui/src/config/section/compute.js b/ui/src/config/section/compute.js index df95b01438fb..12cfb570d530 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', 'cephcsipool', 'minsize', 'maxsize', 'size', 'controlnodes', 'controlaffinitygroupnames', 'etcdnodes', 'etcdaffinitygroupnames', 'workeraffinitygroupnames', 'cpunumber', 'memory', 'keypair', 'cniconfigname', 'associatednetworkname', '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..897f95ee51fc 100644 --- a/ui/src/views/compute/CreateKubernetesCluster.vue +++ b/ui/src/views/compute/CreateKubernetesCluster.vue @@ -214,6 +214,48 @@ + + + + +
+ + + + + + + + + + + + + + + + +