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 @@ -42,6 +42,7 @@ public class ApiConstants {
public static final String ANNOTATION = "annotation";
public static final String API_KEY = "apikey";
public static final String API_KEY_ACCESS = "apikeyaccess";
public static final String API_SERVER_SANS = "apiserversans";
public static final String ARCHIVED = "archived";
public static final String ARCH = "arch";
public static final String AS_NUMBER = "asnumber";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.KubernetesClusterUtil;
import com.cloud.kubernetes.version.KubernetesSupportedVersion;
import com.cloud.kubernetes.version.KubernetesSupportedVersionVO;
import com.cloud.kubernetes.version.KubernetesVersionManagerImpl;
Expand Down Expand Up @@ -961,6 +962,10 @@ public KubernetesClusterResponse createKubernetesClusterResponse(long kubernetes
response.setMaxSize(kubernetesCluster.getMaxSize());
response.setClusterType(kubernetesCluster.getClusterType());
response.setCsiEnabled(kubernetesCluster.isCsiEnabled());
KubernetesClusterDetailsVO apiServerSans = kubernetesClusterDetailsDao.findDetail(kubernetesCluster.getId(), ApiConstants.API_SERVER_SANS);
if (apiServerSans != null) {
response.setApiServerSans(Arrays.asList(apiServerSans.getValue().split(",")));
}
response.setCreated(kubernetesCluster.getCreated());
setNodeTypeAffinityGroupResponse(response, kubernetesCluster.getId());

Expand Down Expand Up @@ -1035,7 +1040,12 @@ private Network validateAndGetNetworkForKubernetesCreateParameters(Long networkI
return network;
}

private void validateUnmanagedKubernetesClusterCreateParameters(final CreateKubernetesClusterCmd cmd) throws CloudRuntimeException {
protected void validateUnmanagedKubernetesClusterCreateParameters(final CreateKubernetesClusterCmd cmd) throws CloudRuntimeException {
if (CollectionUtils.isNotEmpty(cmd.getApiServerSans())) {
throw new InvalidParameterValueException(String.format("%s is not supported for %s clusters, whose certificates CloudStack does not issue",
ApiConstants.API_SERVER_SANS, KubernetesCluster.ClusterType.ExternalManaged));
}

final String name = cmd.getName();
final Long zoneId = cmd.getZoneId();
final Account owner = accountService.getActiveAccountById(cmd.getEntityOwnerId());
Expand Down Expand Up @@ -1177,6 +1187,7 @@ private void validateManagedKubernetesClusterCreateParameters(final CreateKubern
}

validateDockerRegistryParams(dockerRegistryUserName, dockerRegistryPassword, dockerRegistryUrl);
KubernetesClusterUtil.normalizeApiServerSans(cmd.getApiServerSans());

Network network = validateAndGetNetworkForKubernetesCreateParameters(networkId);

Expand Down Expand Up @@ -1305,6 +1316,7 @@ private void addKubernetesClusterDetails(final KubernetesCluster kubernetesClust
final String dockerRegistryPassword = cmd.getDockerRegistryPassword();
final String dockerRegistryUrl = cmd.getDockerRegistryUrl();
final boolean networkCleanup = cmd.getNetworkId() == null;
final List<String> apiServerSans = KubernetesClusterUtil.normalizeApiServerSans(cmd.getApiServerSans());
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
Expand All @@ -1320,6 +1332,7 @@ 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.API_SERVER_SANS, String.join(",", apiServerSans), true);
}
kubernetesClusterDetailsDao.saveDetails(details);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ private boolean isKubernetesVersionSupportsHA() {
return haSupported;
}

private Pair<String, String> getKubernetesControlNodeConfig(final String controlNodeIp, final String serverIp,
protected Pair<String, String> getKubernetesControlNodeConfig(final String controlNodeIp, final String serverIp,
final List<Network.IpAddresses> etcdIps, final String hostName, final boolean haSupported,
final boolean ejectIso, final boolean externalCni, final boolean setupCsi) throws IOException {
String k8sControlNodeConfig = readK8sConfigFile("/conf/k8s-control-node.yml");
Expand All @@ -184,7 +184,7 @@ private Pair<String, String> getKubernetesControlNodeConfig(final String control
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 certSansKey = "{{ k8s_control.server_ips }}";
final String k8sCertificate = "{{ k8s_control.certificate_key }}";
final String externalCniPlugin = "{{ k8s.external.cni.plugin }}";
final String setupCsiDriver = "{{ k8s.setup.csi.driver }}";
Expand Down Expand Up @@ -229,14 +229,16 @@ private Pair<String, String> getKubernetesControlNodeConfig(final String control
CLUSTER_API_PORT,
KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster));
}
initArgs += String.format("--apiserver-cert-extra-sans=%s", serverIp);
final List<String> certSans = getApiServerCertSans(serverIp);
initArgs += String.format("--apiserver-cert-extra-sans=%s", String.join(",", certSans));
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(certSansKey, certSans.stream()
.map(san -> String.format("- \"%s\"", san)).collect(Collectors.joining("\n ")));
k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sCertificate, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster));
k8sControlNodeConfig = k8sControlNodeConfig.replace(externalCniPlugin, String.valueOf(externalCni));
k8sControlNodeConfig = k8sControlNodeConfig.replace(setupCsiDriver, String.valueOf(setupCsi));
Expand All @@ -246,6 +248,19 @@ private Pair<String, String> getKubernetesControlNodeConfig(final String control
return new Pair<>(k8sControlNodeConfig, controlNodeIp);
}

/**
* @return the cluster's API endpoint followed by the extra SANs given at creation
*/
protected List<String> getApiServerCertSans(String serverIp) {
List<String> sans = new ArrayList<>();
sans.add(serverIp);
KubernetesClusterDetailsVO extraSans = kubernetesClusterDetailsDao.findDetail(kubernetesCluster.getId(), ApiConstants.API_SERVER_SANS);
if (extraSans != null) {
sans.addAll(Arrays.asList(extraSans.getValue().split(",")));
}
return sans;
}

private Pair<UserVm,String> createKubernetesControlNode(final Network network, String serverIp, List<Network.IpAddresses> etcdIps, Long domainId, Long accountId, Long asNumber) throws ManagementServerException,
ResourceUnavailableException, InsufficientCapacityException {
UserVm controlVm = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
import java.net.Socket;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.net.ssl.HttpsURLConnection;
Expand All @@ -33,14 +37,17 @@

import com.cloud.kubernetes.cluster.KubernetesClusterVmMapVO;
import com.cloud.kubernetes.cluster.dao.KubernetesClusterVmMapDao;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.utils.security.SSLUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import com.cloud.exception.InvalidParameterValueException;
import com.cloud.kubernetes.cluster.KubernetesCluster;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.nio.TrustAllManager;
import com.cloud.utils.ssh.SshHelper;

Expand All @@ -50,6 +57,9 @@ public class KubernetesClusterUtil {

public static final String CLUSTER_NODE_READY_COMMAND = "sudo /opt/bin/kubectl get nodes | awk '{if ($1 == \"%s\" && $2 == \"Ready\") print $1}'";
public static final String CLUSTER_NODE_VERSION_COMMAND = "sudo /opt/bin/kubectl get nodes | awk '{if ($1 == \"%s\") print $5}'";
// The DNS-1123 subdomain kubeadm requires of a certSANs entry that is not an IP address
private static final Pattern DNS_SUBDOMAIN_PATTERN = Pattern.compile("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*");
private static final int DNS_SUBDOMAIN_MAX_LENGTH = 253;

public static boolean isKubernetesClusterNodeReady(final KubernetesCluster kubernetesCluster, String ipAddress, int port,
String user, File sshKeyFile, String nodeName) throws Exception {
Expand Down Expand Up @@ -384,4 +394,31 @@ protected static Pair<Boolean, String> clusterNodeVersionMatches(final Pair<Bool
String response = result.second();
return new Pair<>(response.contains(String.format("v%s", version)), response);
}

/**
* @return the extra API server certificate SANs, trimmed and in lower case
* @throws InvalidParameterValueException for an entry that is neither an IP address nor a DNS name
*/
public static List<String> normalizeApiServerSans(List<String> sans) {
List<String> normalized = new ArrayList<>();
if (sans == null) {
return normalized;
}
for (String san : sans) {
String value = san.trim().toLowerCase(Locale.ROOT);
if (!NetUtils.isValidIp4(value) && !NetUtils.isValidIp6(value) && !isDnsName(value)) {
throw new InvalidParameterValueException(String.format("Invalid %s entry '%s': give a DNS name or an IP address",
ApiConstants.API_SERVER_SANS, san));
}
normalized.add(value);
}
return normalized;
}

private static boolean isDnsName(String value) {
// No top-level domain is all digits, so such a name is a mistyped IP address
String lastLabel = value.substring(value.lastIndexOf('.') + 1);
return value.length() <= DNS_SUBDOMAIN_MAX_LENGTH && DNS_SUBDOMAIN_PATTERN.matcher(value).matches()
&& !lastLabel.chars().allMatch(Character::isDigit);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,13 @@ 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_SANS, type = CommandType.LIST, collectionType = CommandType.STRING,
description = "Comma-separated DNS names and IP addresses to add to the API server certificate, " +
"for clients that reach the cluster through a name or address CloudStack does not know, " +
"such as a DNS name in front of the load balancer or a NAT address. They can not be changed later.",
since = "24.0.0")
private List<String> apiServerSans;

/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
Expand Down Expand Up @@ -302,6 +309,10 @@ public String getDockerRegistryPassword() {
return dockerRegistryPassword;
}

public List<String> getApiServerSans() {
return apiServerSans;
}

public String getDockerRegistryUrl() {
return dockerRegistryUrl;
}
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.API_SERVER_SANS)
@Param(description = "The DNS names and IP addresses added to the API server certificate", since = "24.0.0")
private List<String> apiServerSans;

@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 setApiServerSans(List<String> apiServerSans) {
this.apiServerSans = apiServerSans;
}

public void setControlAffinityGroupIds(String controlAffinityGroupIds) {
this.controlAffinityGroupIds = controlAffinityGroupIds;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.CreateKubernetesClusterCmd;
import org.apache.cloudstack.affinity.AffinityGroupVO;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.api.BaseCmd;
Expand Down Expand Up @@ -914,4 +915,10 @@ public void testValidateNodeAffinityGroupsAffinityNoExistingWorkers() {
Mockito.verify(kubernetesClusterAffinityGroupMapDao).listAffinityGroupIdsByClusterIdAndNodeType(1L, WORKER.name());
}

@Test(expected = InvalidParameterValueException.class)
public void testValidateUnmanagedClusterCreateRefusesApiServerSans() {
CreateKubernetesClusterCmd cmd = Mockito.mock(CreateKubernetesClusterCmd.class);
Mockito.when(cmd.getApiServerSans()).thenReturn(List.of("k8s.example.com"));
kubernetesClusterManager.validateUnmanagedKubernetesClusterCreateParameters(cmd);
}
}
Loading
Loading