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
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public interface ApiKeyPairDao extends GenericDao<ApiKeyPairVO, Long> {

ApiKeyPairVO getLastApiKeyCreatedByUser(Long userId);

List<ApiKeyPairVO> listByName(String name);

Pair<List<ApiKeyPairVO>, Integer> listByUserIdsPaginated(List<Long> userIds, ListUserKeysCmd cmd);

}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class ApiKeyPairDaoImpl extends GenericDaoBase<ApiKeyPairVO, Long> implem
private static final String USER_ID = "userId";
private static final String API_KEY = "apiKey";
private static final String SECRET_KEY = "secretKey";
private static final String NAME = "name";

private final SearchBuilder<ApiKeyPairVO> keyPairSearch;

Expand All @@ -44,6 +45,7 @@ public class ApiKeyPairDaoImpl extends GenericDaoBase<ApiKeyPairVO, Long> implem
keyPairSearch.and(SECRET_KEY, keyPairSearch.entity().getSecretKey(), SearchCriteria.Op.EQ);
keyPairSearch.and(ID, keyPairSearch.entity().getId(), SearchCriteria.Op.EQ);
keyPairSearch.and(USER_ID, keyPairSearch.entity().getUserId(), SearchCriteria.Op.IN);
keyPairSearch.and(NAME, keyPairSearch.entity().getName(), SearchCriteria.Op.EQ);
keyPairSearch.done();
}

Expand All @@ -68,6 +70,13 @@ public Pair<List<ApiKeyPairVO>, Integer> listApiKeysByUserOrApiKeyId(Long userId
return searchAndCount(sc, searchFilter);
}

@Override
public List<ApiKeyPairVO> listByName(String name) {
SearchCriteria<ApiKeyPairVO> sc = keyPairSearch.create();
sc.setParameters(NAME, name);
return listBy(sc);
}

public ApiKeyPairVO getLastApiKeyCreatedByUser(Long userId) {
final SearchCriteria<ApiKeyPairVO> sc = keyPairSearch.create();
sc.setParametersIfNotNull(USER_ID, userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class KubernetesClusterEventTypes {
public static final String EVENT_KUBERNETES_CLUSTER_STOP = "KUBERNETES.CLUSTER.STOP";
public static final String EVENT_KUBERNETES_CLUSTER_SCALE = "KUBERNETES.CLUSTER.SCALE";
public static final String EVENT_KUBERNETES_CLUSTER_UPGRADE = "KUBERNETES.CLUSTER.UPGRADE";
public static final String EVENT_KUBERNETES_CLUSTER_KEYS_ROTATE = "KUBERNETES.CLUSTER.KEYS.ROTATE";
public static final String EVENT_KUBERNETES_CLUSTER_NODES_ADD = "KUBERNETES.CLUSTER.NODES.ADD";
public static final String EVENT_KUBERNETES_CLUSTER_NODES_REMOVE = "KUBERNETES.CLUSTER.NODES.REMOVE";
public static final String EVENT_KUBERNETES_CLUSTER_AFFINITY_UPDATE = "KUBERNETES.CLUSTER.AFFINITY.UPDATE";
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.apache.cloudstack.api.command.user.kubernetes.cluster.ListKubernetesClustersCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.RemoveNodesFromKubernetesClusterCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.RemoveVirtualMachinesFromKubernetesClusterCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.RotateKubernetesClusterKeysCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.ScaleKubernetesClusterCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.StartKubernetesClusterCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.StopKubernetesClusterCmd;
Expand Down Expand Up @@ -158,6 +159,8 @@ public interface KubernetesClusterService extends PluggableService, Configurable

boolean stopKubernetesCluster(StopKubernetesClusterCmd cmd) throws CloudRuntimeException;

void rotateKubernetesClusterKeys(RotateKubernetesClusterKeysCmd cmd) throws CloudRuntimeException;

boolean deleteKubernetesCluster(DeleteKubernetesClusterCmd cmd) throws CloudRuntimeException;

boolean isCommandSupported(KubernetesCluster cluster, String cmdName);
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 All @@ -33,6 +34,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -265,6 +267,10 @@ protected String resolveApiPublicIpAddress(Network network) {


protected final String deploySecretsScriptFilename = "deploy-cloudstack-secret";
protected final String cloudConfigFilename = "cloud-config";
public static final String SECRET_STORED = "cloudstack-secret stored";
public static final String SECRET_EXISTS = "cloudstack-secret exists";
public static final String COMPONENTS_RESTARTED = "CloudStack components restarted";
protected final String deployProviderScriptFilename = "deploy-provider";
protected final String deployCsiDriverScriptFilename = "deploy-csi-driver";
protected final String deletePvScriptFilename = "delete-pv-reclaimpolicy-delete";
Expand All @@ -280,7 +286,7 @@ protected String resolveApiPublicIpAddress(Network network) {
protected KubernetesClusterManagerImpl manager;
protected String[] keys;

protected KubernetesClusterActionWorker(final KubernetesCluster kubernetesCluster, final KubernetesClusterManagerImpl clusterManager) {
public KubernetesClusterActionWorker(final KubernetesCluster kubernetesCluster, final KubernetesClusterManagerImpl clusterManager) {
this.kubernetesCluster = kubernetesCluster;
this.kubernetesClusterDao = clusterManager.kubernetesClusterDao;
this.kubernetesClusterDetailsDao = clusterManager.kubernetesClusterDetailsDao;
Expand Down Expand Up @@ -782,27 +788,82 @@ protected boolean stateTransitTo(long kubernetesClusterId, KubernetesCluster.Eve
}

protected boolean createCloudStackSecret(String[] keys) {
if (keys == null) {
logger.debug("Kubernetes cluster {} has no API key pair of its own, its cloudstack-secret is left as it is", kubernetesCluster);
return true;
}
return storeCloudStackSecret(keys, false) != null;
}

/**
* Stores the keys in the cluster's cloudstack-secret. Without restart, an existing secret is left as it is. With
* restart, only the keys in an existing secret are replaced and the components that read it are restarted.
* @return the output of the secret script, or null if the secret is not in place
*/
protected String storeCloudStackSecret(String[] keys, boolean restart) {
File pkFile = getManagementServerSshPublicKeyFile();
Pair<String, Integer> publicIpSshPort = getKubernetesClusterServerIpSshPort(null);
publicIpAddress = publicIpSshPort.first();
sshPort = publicIpSshPort.second();
// A name of its own, so that another operation on the cluster cannot replace the file before it is read
String configFile = String.format("%s-%s", cloudConfigFilename, UUID.randomUUID());
boolean configFileLeft = false;

try {
String command = String.format("sudo %s/%s -u '%s' -k '%s' -s '%s'",
scriptPath, deploySecretsScriptFilename, ApiServiceConfiguration.getApiServletPathValue(), keys[0], keys[1]);
Account account = accountDao.findById(kubernetesCluster.getAccountId());
if (account != null && account.getType() == Account.Type.PROJECT) {
String projectId = projectService.findByProjectAccountId(account.getId()).getUuid();
command = String.format("%s -p '%s'", command, projectId);
}
SshHelper.scpTo(publicIpAddress, sshPort, getControlNodeLoginUser(), pkFile, null, "~/",
getCloudConfig(keys).getBytes(StandardCharsets.UTF_8), configFile, "0600");
configFileLeft = true;
// The file is opened as stdin and unlinked before the script runs, so the keys do not stay on disk
String command = String.format("{ rm -f ~/%1$s; sudo %2$s/%3$s%4$s; } < ~/%1$s",
configFile, scriptPath, deploySecretsScriptFilename, restart ? " --restart" : "");
// With restart, the script waits for the components it restarts, at most 24 minutes in all
Pair<Boolean, String> result = SshHelper.sshExecute(publicIpAddress, sshPort, getControlNodeLoginUser(),
pkFile, null, command, 10000, 10000, 60000);
return result.first();
pkFile, null, command, 10000, 10000, restart ? 30 * 60 * 1000 : 60000);
configFileLeft = false;
String output = StringUtils.defaultString(result.second());
if (!result.first()) {
logger.warn("Storing cloudstack-secret in Kubernetes cluster {}: {}", kubernetesCluster, output);
}
// Checked in the output rather than the exit status, so that an older script that is still in place counts as failed
if (output.contains(SECRET_STORED) || (!restart && output.contains(SECRET_EXISTS))) {
return output;
}
} catch (Exception e) {
String msg = String.format("Failed to add cloudstack-secret to Kubernetes cluster: %s", kubernetesCluster.getName());
logger.warn(msg, e);
}
return false;
// The command removes the file as it starts, unless it failed to run
if (configFileLeft) {
try {
SshHelper.sshExecute(publicIpAddress, sshPort, getControlNodeLoginUser(), pkFile, null,
String.format("rm -f ~/%s", configFile), 10000, 10000, 60000);
} catch (Exception e) {
logger.warn("Failed to remove {} from the control node of Kubernetes cluster {}", configFile, kubernetesCluster, e);
}
}
return null;
}

protected String getCloudConfig(String[] keys) {
StringBuilder config = new StringBuilder(String.format("[Global]\napi-url = %s\napi-key = %s\nsecret-key = %s\n",
ApiServiceConfiguration.getApiServletPathValue(), keys[0], keys[1]));
Account account = accountDao.findById(kubernetesCluster.getAccountId());
if (account != null && account.getType() == Account.Type.PROJECT) {
config.append(String.format("project-id = %s\n", projectService.findByProjectAccountId(account.getId()).getUuid()));
}
return config.toString();
}

/**
* Stores the keys in the cluster's cloudstack-secret and restarts the components that read it. The secret
* script is copied first, as the cluster may have been created with an older one.
* @return the output of the secret script, or null if the secret was not stored
*/
public String updateCloudStackSecret(String[] keys) {
Pair<String, Integer> publicIpSshPort = getKubernetesClusterServerIpSshPort(null);
copyScriptFile(publicIpSshPort.first(), publicIpSshPort.second(), retrieveScriptFile(deploySecretsScriptFilename),
deploySecretsScriptFilename);
return storeCloudStackSecret(keys, true);
}

protected File retrieveScriptFile(String filename) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,11 @@ public boolean destroy() throws CloudRuntimeException {
}
stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationSucceeded);
annotationDao.removeByEntityType(AnnotationService.EntityType.KUBERNETES_CLUSTER.name(), kubernetesCluster.getUuid());
try {
manager.deleteKubernetesClusterKeyPairs(kubernetesCluster, null);
} catch (Exception e) {
logger.warn("Failed to delete the API key pairs of Kubernetes cluster {}", kubernetesCluster, e);
}
kubernetesClusterDetailsDao.removeDetails(kubernetesCluster.getId());
kubernetesClusterAffinityGroupMapDao.removeByClusterId(kubernetesCluster.getId());
boolean deleted = kubernetesClusterDao.remove(kubernetesCluster.getId());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// 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 javax.inject.Inject;

import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandResourceType;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.KubernetesClusterResponse;
import org.apache.cloudstack.api.response.SuccessResponse;
import org.apache.cloudstack.context.CallContext;

import com.cloud.kubernetes.cluster.KubernetesCluster;
import com.cloud.kubernetes.cluster.KubernetesClusterEventTypes;
import com.cloud.kubernetes.cluster.KubernetesClusterService;
import com.cloud.utils.exception.CloudRuntimeException;

@APICommand(name = "rotateKubernetesClusterKeys",
description = "Replaces the API key pair used by the CloudStack components of a Kubernetes cluster with a new one, " +
"updates the cloudstack-secret in the cluster, restarts the components that read it and deletes the cluster's old key pairs. " +
"A key pair shared with other clusters, as used by clusters created before 24.0.0, is not deleted. " +
"Only the API keys in the secret are replaced, its other settings are kept. The cluster must be Running with every node up, " +
"as the rotation waits for the components on each node to restart",
responseObject = SuccessResponse.class,
entityType = {KubernetesCluster.class},
requestHasSensitiveInfo = false,
responseHasSensitiveInfo = false,
since = "24.0.0",
authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User})
public class RotateKubernetesClusterKeysCmd extends BaseAsyncCmd {

@Inject
public KubernetesClusterService kubernetesClusterService;

@Parameter(name = ApiConstants.ID, type = CommandType.UUID,
entityType = KubernetesClusterResponse.class, required = true,
description = "The ID of the Kubernetes cluster")
private Long id;

public Long getId() {
return id;
}

@Override
public String getEventType() {
return KubernetesClusterEventTypes.EVENT_KUBERNETES_CLUSTER_KEYS_ROTATE;
}

@Override
public String getEventDescription() {
KubernetesCluster cluster = _entityMgr.findById(KubernetesCluster.class, getId());
return String.format("Rotating API keys of Kubernetes cluster ID: %s", cluster != null ? cluster.getUuid() : getId());
}

@Override
public long getEntityOwnerId() {
return CallContext.current().getCallingAccount().getId();
}

@Override
public Long getApiResourceId() {
return getId();
}

// Rotations of one cluster run one at a time, so the key pair recorded is the one in its secret
@Override
public String getSyncObjType() {
return "kubernetescluster";
}

@Override
public Long getSyncObjId() {
return getId();
}

@Override
public ApiCommandResourceType getApiResourceType() {
return ApiCommandResourceType.KubernetesCluster;
}

@Override
public void execute() throws ServerApiException {
try {
kubernetesClusterService.rotateKubernetesClusterKeys(this);
setResponseObject(new SuccessResponse(getCommandName()));
} catch (CloudRuntimeException ex) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
}
}
}
Loading
Loading