Pearl1594 commented on code in PR #14611:
URL: https://github.com/apache/cloudstack/pull/14611#discussion_r4684227717


##########
plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterScaleWorker.java:
##########
@@ -287,46 +291,89 @@ protected Pair<Long, Long> 
calculateNodesCapacity(ServiceOffering offering, long
         return new Pair<>(offering.getCpu() * nodeCount, offering.getRamSize() 
* nodeCount);
     }
 
+    /**
+     * Deletes the Kubernetes node object of a VM that is being removed from 
the cluster. The node has been drained
+     * already, see {@link #drainNodesToRemove(List)}. A failed attempt is 
retried after waiting.
+     */
     private boolean removeKubernetesClusterNode(final String ipAddress, final 
int port, final UserVm userVm, final int retries, final int waitDuration) {
-        File pkFile = getManagementServerSshPublicKeyFile();
-        int retryCounter = 0;
-        String hostName = userVm.getHostName();
-        if (StringUtils.isNotEmpty(hostName)) {
-            hostName = hostName.toLowerCase();
-        }
-        while (retryCounter < retries) {
-            retryCounter++;
+        final String hostName = getNodeName(userVm);
+        for (int attempt = 1; attempt <= retries; attempt++) {
+            if (attempt > 1 && !sleepBeforeRetry(waitDuration)) {
+                break;
+            }
             try {
-                Pair<Boolean, String> result = SshHelper.sshExecute(ipAddress, 
port, getControlNodeLoginUser(),
-                        pkFile, null, String.format("sudo /opt/bin/kubectl 
drain %s --ignore-daemonsets --delete-emptydir-data", hostName),
-                        10000, 10000, 60000);
-                if (!result.first()) {
-                    logger.warn("Draining node: {} on VM: {} in Kubernetes 
cluster: {} unsuccessful", hostName, userVm, kubernetesCluster);
-                } else {
-                    result = SshHelper.sshExecute(ipAddress, port, 
getControlNodeLoginUser(),
-                            pkFile, null, String.format("sudo /opt/bin/kubectl 
delete node %s", hostName),
-                            10000, 10000, 30000);
-                    if (result.first()) {
-                        return true;
-                    } else {
-                        logger.warn("Deleting node: {} on VM: {} in Kubernetes 
cluster: {} unsuccessful", hostName, userVm, kubernetesCluster);
-                    }
+                Pair<Boolean, String> result = executeSshCommand(ipAddress, 
port,
+                        String.format("sudo /opt/bin/kubectl delete node %s 
--ignore-not-found", hostName), 10000, 10000, 30000);
+                if (result.first()) {
+                    return true;
                 }
-                break;
+                logger.warn("Deleting node: {} on VM: {} in Kubernetes 
cluster: {} unsuccessful: {}", hostName, userVm, kubernetesCluster, 
result.second());
             } catch (Exception e) {
-                String msg = String.format("Failed to remove Kubernetes 
cluster: %s node: %s on VM: %s", kubernetesCluster, hostName, userVm);
-                logger.warn(msg, e);
+                logger.warn("Failed to remove Kubernetes cluster: {} node: {} 
on VM: {}", kubernetesCluster, hostName, userVm, e);
             }
+        }
+        return false;
+    }
+
+    /**
+     * Drains the nodes that are being removed, before any of them is removed. 
All of them are cordoned first, so
+     * that the pods evicted from one are not moved to another one that is 
going away. If a node can't be drained,
+     * all of them are uncordoned and the scale-down stops with nothing 
removed: the nodes are still working members
+     * of the cluster, so the cluster goes back to the state it was in, rather 
than to Alert.
+     *
+     * @return the nodes that were cordoned here, as opposed to the ones that 
were cordoned already
+     */
+    protected List<UserVmVO> drainNodesToRemove(final List<UserVmVO> vms) 
throws CloudRuntimeException {
+        List<UserVmVO> cordoned = new ArrayList<>();
+        String failure = null;
+        for (UserVmVO vm : vms) {
+            // A node cordoned by someone else has to stay cordoned if the 
scale-down is rolled back
+            final boolean cordonedAlready = isNodeCordoned(vm);
+            String output;
             try {
-                Thread.sleep(waitDuration);
-            } catch (InterruptedException ie) {
-                logger.error("Error while waiting for Kubernetes cluster: {} 
node: {} on VM: {} removal", kubernetesCluster, hostName, userVm, ie);
+                Pair<Boolean, String> result = 
executeSshCommand(publicIpAddress, sshPort,
+                        String.format("sudo /opt/bin/kubectl cordon %s", 
getNodeName(vm)), 10000, 10000, 30000);
+                if (result.first()) {
+                    if (!cordonedAlready) {
+                        cordoned.add(vm);
+                    }
+                    continue;
+                }
+                output = result.second();
+            } catch (Exception e) {
+                output = e.getMessage();
+            }
+            failure = String.format("unable to cordon Kubernetes node: %s on 
VM: %s: %s", getNodeName(vm), vm, output);
+            break;
+        }
+        if (failure == null) {
+            for (UserVmVO vm : vms) {
+                if (System.currentTimeMillis() > scaleTimeoutTime) {
+                    failure = String.format("scaling action timed out before 
Kubernetes node: %s on VM: %s was drained", getNodeName(vm), vm);
+                    break;
+                }
+                Pair<Boolean, String> drained = 
drainKubernetesClusterNode(publicIpAddress, sshPort, vm, 
SCALE_DOWN_DRAIN_ATTEMPTS, DRAIN_RETRY_WAIT, scaleTimeoutTime);
+                if (!drained.first()) {
+                    failure = String.format("unable to drain Kubernetes node: 
%s on VM: %s: %s", getNodeName(vm), vm, drained.second());
+                    break;
+                }
             }
-            retryCounter++;
         }
-        return false;
+        if (failure == null) {
+            return cordoned;
+        }
+        uncordonNodes(cordoned);
+        String message = String.format("Scaling failed for Kubernetes cluster 
%s, %s. No node was removed", kubernetesCluster, failure);
+        logger.error(message);
+        // Nothing has changed, so the cluster goes back to the state it was 
in: Scaling goes back to Running (and
+        // ScalingStoppedCluster to Stopped) on OperationSucceeded. Scaling a 
cluster in Alert is not allowed today,
+        // but if it is, such a cluster has to go back to Alert, not to 
Running.
+        stateTransitTo(kubernetesCluster.getId(), 
KubernetesCluster.State.Alert.equals(originalState) ?
+                KubernetesCluster.Event.OperationFailed : 
KubernetesCluster.Event.OperationSucceeded);

Review Comment:
   This branch predates #12386, which changed Scaling + OperationFailed to 
Running on main. After rebasing, OperationFailed gives the same state as 
OperationSucceeded, so please use OperationFailed here, drop the Alert ternary, 
and update the comment above it.



##########
plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterScaleWorker.java:
##########
@@ -411,48 +458,225 @@ private void 
scaleKubernetesClusterOffering(KubernetesClusterNodeType nodeType,
         kubernetesCluster = updateKubernetesClusterEntryForNodeType(null, 
nodeType, serviceOffering, updateNodeOffering, updateClusterOffering);
     }
 
-    private void removeNodesFromCluster(List<KubernetesClusterVmMapVO> vmMaps) 
throws CloudRuntimeException {
-        for (KubernetesClusterVmMapVO vmMapVO : vmMaps) {
-            UserVmVO userVM = userVmDao.findById(vmMapVO.getVmId());
-            logger.info("Removing vm {} from cluster {}", userVM, 
kubernetesCluster);
-            if (!removeKubernetesClusterNode(publicIpAddress, sshPort, userVM, 
3, 30000)) {
-                logTransitStateAndThrow(Level.ERROR, String.format("Scaling 
failed for Kubernetes" +
-                        " cluster %s, failed to remove Kubernetes node: %s 
running on VM : %s",
-                        kubernetesCluster, userVM.getHostName(), userVM), 
kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed);
+    protected void removeNodesFromCluster(List<KubernetesClusterVmMapVO> 
vmMaps) throws CloudRuntimeException {
+        List<UserVmVO> vms = vmMaps.stream().map(vmMapVO -> 
userVmDao.findById(vmMapVO.getVmId())).collect(Collectors.toList());
+        List<UserVmVO> cordoned = drainNodesToRemove(vms);
+        // Index of the first VM whose Kubernetes node is still in the cluster
+        int firstInCluster = 0;
+        // VMs taken out of the cluster's VM map so far
+        List<UserVmVO> removed = new ArrayList<>();
+        boolean completed = false;
+        try {
+            for (int i = 0; i < vmMaps.size(); i++) {
+                // No timeout check here: the nodes are drained, and stopping 
part way would leave the cluster
+                // with some of them removed and the node count not updated
+                UserVmVO userVM = vms.get(i);
+                KubernetesClusterVmMapVO vmMapVO = vmMaps.get(i);
+                logger.info("Removing vm {} from cluster {}", userVM, 
kubernetesCluster);
+                if (!removeKubernetesClusterNode(publicIpAddress, sshPort, 
userVM, 3, 30000)) {
+                    logTransitStateAndThrow(Level.ERROR, 
String.format("Scaling failed for Kubernetes" +
+                            " cluster %s, failed to remove Kubernetes node: %s 
running on VM : %s",
+                            kubernetesCluster, userVM.getHostName(), userVM), 
kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed);
+                }
+                firstInCluster = i + 1;
+                try {
+                    destroyRemovedNodeVm(userVM);
+                } finally {
+                    // The node has left the Kubernetes cluster, so its VM 
leaves the cluster's VM map, whatever
+                    // happened to the VM. A map entry kept for it would never 
match a Kubernetes node again: the
+                    // state scanner would hold the cluster in Alert, which 
blocks the next scale, and the node count
+                    // and the next scale-down's choice of nodes would be 
worked out from a VM that is gone. The
+                    // entry is deleted only now as the VM's expunge looks it 
up (to leave alone the port-forwarding
+                    // rules of a CKS node in an NSX zone).
+                    kubernetesClusterVmMapDao.expunge(vmMapVO.getId());
+                    removed.add(userVM);
+                }
             }
-            CallContext vmContext = CallContext.register(CallContext.current(),
-                    ApiCommandResourceType.VirtualMachine);
-            vmContext.setEventResourceId(userVM.getId());
+
+            // Scale network rules to update firewall rule
             try {
-                UserVm vm = userVmService.destroyVm(userVM.getId(), true);
-                if (!userVmManager.expunge(userVM)) {
-                    logTransitStateAndThrow(Level.ERROR, 
String.format("Scaling Kubernetes cluster %s failed, unable to expunge VM '%s'."
-                            , kubernetesCluster, vm), 
kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed);
+                List<Long> clusterVMIds = getKubernetesClusterVMMaps()
+                        .stream()
+                        .filter(x -> !x.isEtcdNode())
+                        
.map(KubernetesClusterVmMapVO::getVmId).collect(Collectors.toList());
+                scaleKubernetesClusterNetworkRules(clusterVMIds);
+            } catch (ManagementServerException e) {
+                logTransitStateAndThrow(Level.ERROR, String.format("Scaling 
failed for Kubernetes " +
+                        "cluster %s, unable to update network rules", 
kubernetesCluster),
+                        kubernetesCluster.getId(), 
KubernetesCluster.Event.OperationFailed, e);
+            }
+            completed = true;
+        } finally {
+            if (!completed) {
+                // The nodes that are still in the cluster were drained above 
and would stay unschedulable
+                updateKubernetesClusterEntryForRemovedNodes(removed);
+                List<UserVmVO> inCluster = vms.subList(firstInCluster, 
vms.size());
+                
uncordonNodes(cordoned.stream().filter(inCluster::contains).collect(Collectors.toList()));
+            }
+        }
+    }
+
+    /**
+     * Destroys and expunges the VM of a node that has been deleted from the 
Kubernetes cluster. The caller then takes
+     * the VM out of the cluster's VM map, whether this succeeds or not.
+     * <ul>
+     * <li>If the VM can't be destroyed, the scale fails: the VM may still be 
running, though it is no longer a
+     * Kubernetes node nor a member of the cluster, and has to be destroyed by 
hand.</li>
+     * <li>If the destroyed VM can't be expunged, the scale goes on, with a 
warning event that names the VM and its
+     * state. The expunge task retries VMs left Destroyed, Expunging or in 
Error.</li>
+     * </ul>
+     */
+    protected void destroyRemovedNodeVm(final UserVmVO userVM) throws 
CloudRuntimeException {

Review Comment:
   The nested try/catch with found/vm/leftBehind, plus the same 
findByIdIncludingRemoved lookup again at line 584, is hard to follow.  Could 
you pleases extract one lookup helper and cut the flags.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to