Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions api/src/main/java/org/apache/cloudstack/api/ApiConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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());

Expand Down Expand Up @@ -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)) {
Expand All @@ -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<String, Long> map,
Long defaultServiceOfferingId,
Long etcdNodes,
Expand Down Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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<String, String> 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<String, Integer> 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<Boolean, String> 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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///////////////////
/////////////////////////////////////////////////////
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading