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 @@ -234,6 +234,8 @@ public class KubernetesClusterActionWorker {
* For all other clusters: same value as {@link #publicIpAddress}. */
protected String apiPublicIpAddress;
protected int sshPort;
protected String joinToken;
protected String joinCaCertHash;

/**
* Returns the public IP that Kubernetes nodes should use as the API server cluster endpoint.
Expand Down Expand Up @@ -792,6 +794,51 @@ protected boolean createCloudStackSecret(String[] keys) {
return false;
}

/**
* Creates a bootstrap token on the control node for nodes about to join, and reads the
* cluster CA hash they pin with --discovery-token-ca-cert-hash.
*/
protected void createJoinToken(final long ttlSeconds) {
Pair<String, Integer> publicIpSshPort = getKubernetesClusterServerIpSshPort(null);
String command = String.format("sudo /opt/bin/kubeadm token create --ttl %s --print-join-command", KubernetesClusterUtil.getJoinTokenTtl(ttlSeconds));
Pair<String, String> tokenAndHash = null;
try {
Pair<Boolean, String> result = SshHelper.sshExecute(publicIpSshPort.first(), publicIpSshPort.second(), getControlNodeLoginUser(),
getManagementServerSshPublicKeyFile(), null, command, 10000, 10000, 60000);
if (result.first()) {
tokenAndHash = KubernetesClusterUtil.parseJoinCommand(result.second());
} else {
logger.warn("Failed to create a join token on Kubernetes cluster {}: {}", kubernetesCluster, result.second());
}
} catch (Exception e) {
logger.warn("Failed to create a join token on Kubernetes cluster: {}", kubernetesCluster, e);
}
if (tokenAndHash == null) {
throw new CloudRuntimeException(String.format("Failed to create a join token on Kubernetes cluster: %s", kubernetesCluster.getName()));
}
joinToken = tokenAndHash.first();
joinCaCertHash = tokenAndHash.second();
}

protected void deleteJoinToken() {
if (joinToken == null) {
return;
}
try {
String command = String.format("sudo /opt/bin/kubeadm token delete %s", joinToken.substring(0, 6));
Pair<String, Integer> publicIpSshPort = getKubernetesClusterServerIpSshPort(null);
Pair<Boolean, String> result = SshHelper.sshExecute(publicIpSshPort.first(), publicIpSshPort.second(), getControlNodeLoginUser(),
getManagementServerSshPublicKeyFile(), null, command, 10000, 10000, 60000);
if (!result.first()) {
logger.warn("Failed to delete the join token on Kubernetes cluster {}, it expires on its own: {}", kubernetesCluster, result.second());
}
} catch (Exception e) {
logger.warn("Failed to delete the join token on Kubernetes cluster {}, it expires on its own", kubernetesCluster, e);
}
joinToken = null;
joinCaCertHash = null;
}

protected File retrieveScriptFile(String filename) {
File file = null;
try {
Expand Down Expand Up @@ -1022,6 +1069,7 @@ public String getKubernetesNodeConfig(final String joinIp, final boolean ejectIs
final String sshPubKey = "{{ k8s.ssh.pub.key }}";
final String joinIpKey = "{{ k8s_control_node.join_ip }}";
final String clusterTokenKey = "{{ k8s_control_node.cluster.token }}";
final String caCertHashKey = "{{ k8s_control_node.cluster.ca_cert_hash }}";
final String ejectIsoKey = "{{ k8s.eject.iso }}";
final String routerIpKey = "{{ k8s.vr.iso.mounted.ip }}";
final String installWaitTime = "{{ k8s.install.wait.time }}";
Expand All @@ -1046,7 +1094,8 @@ public String getKubernetesNodeConfig(final String joinIp, final boolean ejectIs
}
k8sNodeConfig = k8sNodeConfig.replace(sshPubKey, pubKey);
k8sNodeConfig = k8sNodeConfig.replace(joinIpKey, joinIp);
k8sNodeConfig = k8sNodeConfig.replace(clusterTokenKey, KubernetesClusterUtil.generateClusterToken(kubernetesCluster));
k8sNodeConfig = k8sNodeConfig.replace(clusterTokenKey, joinToken);
k8sNodeConfig = k8sNodeConfig.replace(caCertHashKey, joinCaCertHash);
k8sNodeConfig = k8sNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso));
k8sNodeConfig = k8sNodeConfig.replace(routerIpKey, routerIp);
k8sNodeConfig = k8sNodeConfig.replace(installWaitTime, String.valueOf(waitTime));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ public boolean addNodesToCluster(List<Long> nodeIds, boolean mountCksIsoOnVr, bo
} catch (ManagementServerException e) {
throw new CloudRuntimeException(String.format("Failed to retrieve public IP for the network: %s ", network.getName()));
}
createJoinToken(KubernetesClusterService.KubernetesClusterAddNodeTimeout.value());
attachCksIsoForNodesAdditionToCluster(nodeIds, kubernetesCluster.getId(), mountCksIsoOnVr);
stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.AddNodeRequested);
String controlNodeGuestIp = getControlVmPrivateIp();
Expand All @@ -97,6 +98,7 @@ public boolean addNodesToCluster(List<Long> nodeIds, boolean mountCksIsoOnVr, bo
logger.info(msg);
detachCksIsoFromNodesAddedToCluster(nodeIds, kubernetesCluster.getId(), mountCksIsoOnVr);
stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed);
deleteUnusedJoinToken();
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), CallContext.current().getCallingAccountId(),
EventVO.LEVEL_ERROR, KubernetesClusterEventTypes.EVENT_KUBERNETES_CLUSTER_NODES_ADD,
msg, kubernetesCluster.getId(), ApiCommandResourceType.KubernetesCluster.toString(), 0);
Expand All @@ -105,6 +107,7 @@ public boolean addNodesToCluster(List<Long> nodeIds, boolean mountCksIsoOnVr, bo
Pair<String, Integer> publicIpSshPort = getKubernetesClusterServerIpSshPort(null);
KubernetesClusterUtil.validateKubernetesClusterReadyNodesCount(kubernetesCluster, publicIpSshPort.first(), publicIpSshPort.second(),
getControlNodeLoginUser(), sshKeyFile, addNodeTimeoutTime, 15000);
deleteJoinToken();
detachCksIsoFromNodesAddedToCluster(nodeIds, kubernetesCluster.getId(), mountCksIsoOnVr);
stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationSucceeded);
String description = String.format("Successfully added %s nodes to Kubernetes Cluster %s", nodesAdded, kubernetesCluster.getUuid());
Expand All @@ -114,10 +117,18 @@ public boolean addNodesToCluster(List<Long> nodeIds, boolean mountCksIsoOnVr, bo
return true;
} catch (Exception e) {
stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed);
deleteUnusedJoinToken();
throw new CloudRuntimeException(e);
}
}

/** A node rebooted with join userdata may still be joining; otherwise the token is no longer needed */
private void deleteUnusedJoinToken() {
if (finalNodeIds.isEmpty()) {
deleteJoinToken();
}
}

private void detachCksIsoFromNodesAddedToCluster(List<Long> nodeIds, long kubernetesClusterId, boolean mountCksIsoOnVr) {
if (mountCksIsoOnVr) {
detachIsoOnVirtualRouter(kubernetesClusterId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,11 @@ private void scaleUpKubernetesClusterSize(final long newVmCount) throws CloudRun
LaunchPermissionVO launchPermission = new LaunchPermissionVO(clusterTemplate.getId(), owner.getId());
launchPermissionDao.persist(launchPermission);
}
try {
createJoinToken(KubernetesClusterService.KubernetesClusterScaleTimeout.value());
} catch (CloudRuntimeException e) {
logTransitStateToFailedIfNeededAndThrow(Level.ERROR, String.format("Scaling failed for Kubernetes cluster : %s, unable to create a join token", kubernetesCluster.getName()), e);
}
try {
clusterVMs = provisionKubernetesClusterNodeVms((int)(newVmCount + kubernetesCluster.getNodeCount()), (int)kubernetesCluster.getNodeCount(), apiPublicIpAddress, kubernetesCluster.getDomainId(), kubernetesCluster.getAccountId());
updateLoginUserDetails(clusterVMs.stream().map(InternalIdentity::getId).collect(Collectors.toList()));
Expand All @@ -517,6 +522,7 @@ private void scaleUpKubernetesClusterSize(final long newVmCount) throws CloudRun
boolean readyNodesCountValid = KubernetesClusterUtil.validateKubernetesClusterReadyNodesCount(kubernetesClusterVO, publicIpAddress, sshPort,
getControlNodeLoginUser(), sshKeyFile, scaleTimeoutTime, 15000);
detachIsoKubernetesVMs(clusterVMs);
deleteJoinToken();
deleteTemplateLaunchPermission();
if (!readyNodesCountValid) { // Scaling failed
logTransitStateToFailedIfNeededAndThrow(Level.ERROR, String.format("Scaling unsuccessful for Kubernetes cluster : %s as it does not have desired number of nodes in ready state", kubernetesCluster.getName()));
Expand Down
Loading
Loading