From bd86a4ff3a8c6d4beab0eafa7f466acbe29c4f06 Mon Sep 17 00:00:00 2001 From: Brad House Date: Mon, 30 Nov 2026 14:31:35 +0000 Subject: [PATCH] CKS: apply the provider and CSI driver of the new version on upgrade upgradeKubernetesCluster copies the provider manifest of the new binaries ISO to the nodes, and calls deployProvider() before each node, but deploy-provider exits as soon as a cloud-controller-manager pod exists. The CSI driver manifests of the ISO are not copied at all. So an upgraded cluster keeps the provider and CSI driver it was created with, whatever the ISO of the new version holds. The CNI and dashboard manifests are already applied by the upgrade script. - upgrade-kubernetes.sh copies the CSI driver manifests of the ISO to /opt/csi, as the control node setup does at create, with the same fix for the document separator of the v3.0.0 manifest. - Once every node is upgraded, and before the version of the cluster is recorded, kubectl apply the provider (but on a shared network) and the CSI driver (when the cluster has it) on the control node, and wait for their rollout. The snapshot CRDs are shared, so only created when missing. Each is tried cloud.kubernetes.cluster.upgrade.retries + 1 times, within the upgrade timeout. If it still fails, the upgrade fails, so that upgrading to the same version again applies them again. Applying an unchanged manifest changes nothing, so a cluster whose ISO has the same add-ons sees no restart. Signed-off-by: Brad House --- .../KubernetesClusterUpgradeWorker.java | 80 +++++++++++++++- .../resources/script/upgrade-kubernetes.sh | 10 ++ .../KubernetesClusterUpgradeWorkerTest.java | 95 +++++++++++++++++++ 3 files changed, 184 insertions(+), 1 deletion(-) diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorker.java index 4c2725fc2a2f..e62ce516210d 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorker.java @@ -36,6 +36,7 @@ import com.cloud.kubernetes.cluster.utils.KubernetesClusterUtil; import com.cloud.kubernetes.version.KubernetesSupportedVersion; import com.cloud.kubernetes.version.KubernetesVersionManagerImpl; +import com.cloud.network.Network; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; @@ -47,7 +48,25 @@ public class KubernetesClusterUpgradeWorker extends KubernetesClusterActionWorke private KubernetesSupportedVersion upgradeVersion; private final String upgradeScriptFilename = "upgrade-kubernetes.sh"; private File upgradeScriptFile; - private long upgradeTimeoutTime; + protected long upgradeTimeoutTime; + protected long addonApplyRetrySleepMs = 10000; + + protected static final String KUBECTL = "/opt/bin/kubectl "; + protected static final int ADDON_APPLY_TIMEOUT_MS = 12 * 60 * 1000; + protected static final String APPLY_PROVIDER_COMMAND = "sudo sh -c '" + KUBECTL + "apply -f /opt/provider/provider.yaml && " + + KUBECTL + "-n kube-system rollout status deployment/cloud-controller-manager --timeout=300s'"; + /** + * The snapshot CRDs are shared with anything else that takes snapshots, so they are only created when missing. Only the + * first control node gets the manifests at create, and an ISO built before the CSI driver was added has none. + */ + protected static final String APPLY_CSI_DRIVER_COMMAND = "sudo sh -c '" + + "[ -e /opt/csi/manifest.yaml ] || { echo No CSI driver manifest on this node, not applied; exit 0; }; " + + "if ! err=$(" + KUBECTL + "get crd volumesnapshotclasses.snapshot.storage.k8s.io volumesnapshotcontents.snapshot.storage.k8s.io " + + "volumesnapshots.snapshot.storage.k8s.io 2>&1 >/dev/null); then echo \"$err\"; echo \"$err\" | grep -q NotFound || exit 1; " + + KUBECTL + "apply -f /opt/csi/snapshot-crds.yaml && " + KUBECTL + "wait --for condition=established --timeout=60s -f /opt/csi/snapshot-crds.yaml || exit 1; fi; " + + KUBECTL + "apply -f /opt/csi/manifest.yaml && " + + KUBECTL + "-n kube-system rollout status deployment/cloudstack-csi-controller --timeout=300s && " + + KUBECTL + "-n kube-system rollout status daemonset/cloudstack-csi-node --timeout=300s'"; public KubernetesClusterUpgradeWorker(final KubernetesCluster kubernetesCluster, final KubernetesSupportedVersion upgradeVersion, @@ -178,6 +197,12 @@ public boolean upgradeCluster() throws CloudRuntimeException { attachIsoKubernetesVMs(clusterVMs, upgradeVersion); upgradeKubernetesClusterNodes(); detachIsoKubernetesVMs(clusterVMs); + // Before the version is recorded, so that upgrading to it again applies them again + String error = applyAddons(); + if (error != null) { + logTransitStateAndThrow(Level.ERROR, String.format("Failed to upgrade Kubernetes cluster : %s, %s", kubernetesCluster.getName(), error), + kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed); + } KubernetesClusterVO kubernetesClusterVO = kubernetesClusterDao.findById(kubernetesCluster.getId()); kubernetesClusterVO.setKubernetesVersionId(upgradeVersion.getId()); boolean updated = kubernetesClusterDao.update(kubernetesCluster.getId(), kubernetesClusterVO); @@ -189,6 +214,59 @@ public boolean upgradeCluster() throws CloudRuntimeException { return updated; } + /** + * The provider (but on a shared network) and the CSI driver, which CloudStack deployed when the cluster was created. + * The upgrade script copied the manifests of the new binaries ISO to the control node; they are applied once every + * node has imported the images of the ISO. + */ + protected List> getAddonApplyCommands() { + List> commands = new ArrayList<>(); + Network network = networkDao.findById(kubernetesCluster.getNetworkId()); + if (network != null && !manager.isDirectAccess(network)) { + commands.add(new Pair<>("provider", APPLY_PROVIDER_COMMAND)); + } + if (kubernetesCluster.isCsiEnabled()) { + commands.add(new Pair<>("CSI driver", APPLY_CSI_DRIVER_COMMAND)); + } + return commands; + } + + /** Applies the add-ons and waits for their pods; returns why it failed, or null */ + protected String applyAddons() { + for (Pair addon : getAddonApplyCommands()) { + boolean applied = false; + String output = null; + for (int retry = KubernetesClusterService.KubernetesClusterUpgradeRetries.value(); retry >= 0; retry--) { + try { + Pair result = SshHelper.sshExecute(publicIpAddress, sshPort, getControlNodeLoginUser(), sshKeyFile, null, + addon.second(), 10000, 10000, ADDON_APPLY_TIMEOUT_MS); + applied = result.first(); + output = result.second(); + } catch (Exception e) { + output = String.valueOf(e); + } + if (applied) { + logger.info("Applied the {} of Kubernetes version {} to Kubernetes cluster {}: {}", addon.first(), upgradeVersion.getSemanticVersion(), kubernetesCluster, output); + break; + } + if (retry == 0 || System.currentTimeMillis() >= upgradeTimeoutTime) { + break; + } + logger.warn("Unable to apply the {} to Kubernetes cluster {}, retries left: {}: {}", addon.first(), kubernetesCluster, retry, output); + try { + Thread.sleep(addonApplyRetrySleepMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return String.format("interrupted while applying the %s", addon.first()); + } + } + if (!applied) { + return String.format("unable to apply the %s of Kubernetes version %s: %s", addon.first(), upgradeVersion.getSemanticVersion(), output); + } + } + return null; + } + protected void filterOutManualUpgradeNodesFromClusterUpgrade() { if (CollectionUtils.isEmpty(clusterVMs)) { return; diff --git a/plugins/integrations/kubernetes-service/src/main/resources/script/upgrade-kubernetes.sh b/plugins/integrations/kubernetes-service/src/main/resources/script/upgrade-kubernetes.sh index a947d508436e..3a6d0b30476f 100755 --- a/plugins/integrations/kubernetes-service/src/main/resources/script/upgrade-kubernetes.sh +++ b/plugins/integrations/kubernetes-service/src/main/resources/script/upgrade-kubernetes.sh @@ -114,6 +114,16 @@ if [ -d "$BINARIES_DIR" ]; then cp "${BINARIES_DIR}/autoscaler.yaml" /opt/autoscaler/autoscaler_tmpl.yaml fi + if [ -e "${BINARIES_DIR}/snapshot-crds.yaml" ] && [ -e "${BINARIES_DIR}/manifest.yaml" ]; then + mkdir -p /opt/csi + cp "${BINARIES_DIR}/snapshot-crds.yaml" /opt/csi/snapshot-crds.yaml + cp "${BINARIES_DIR}/manifest.yaml" /opt/csi/manifest.yaml + fi + if [ -e /opt/csi/manifest.yaml ]; then + # The CSI driver v3.0.0 manifest ends a line with its document separator, which merges two documents + sed -i '/^[[:space:]]*#/!s/^\(.*[^-[:space:]]\)---$/\1\n---/' /opt/csi/manifest.yaml + fi + PAUSE_IMAGE=`ctr -n k8s.io images ls -q | grep "pause" | sort | tail -n 1` echo $PAUSE_IMAGE if [ -n "$PAUSE_IMAGE" ]; then diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorkerTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorkerTest.java index ff8f875d06e1..0b8178e1508c 100644 --- a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorkerTest.java +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterUpgradeWorkerTest.java @@ -18,15 +18,22 @@ import com.cloud.kubernetes.cluster.KubernetesCluster; import com.cloud.kubernetes.cluster.KubernetesClusterManagerImpl; +import com.cloud.kubernetes.cluster.KubernetesClusterService; import com.cloud.kubernetes.cluster.KubernetesClusterVmMapVO; import com.cloud.kubernetes.cluster.dao.KubernetesClusterVmMapDao; import com.cloud.kubernetes.version.KubernetesSupportedVersion; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkVO; import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; +import com.cloud.utils.ssh.SshHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @@ -45,6 +52,10 @@ public class KubernetesClusterUpgradeWorkerTest { private KubernetesClusterManagerImpl clusterManager; @Mock private KubernetesClusterVmMapDao kubernetesClusterVmMapDao; + @Mock + private NetworkDao networkDao; + @Mock + private NetworkVO network; private KubernetesClusterUpgradeWorker worker; @@ -53,6 +64,90 @@ public void setUp() { String[] keys = {}; worker = new KubernetesClusterUpgradeWorker(kubernetesCluster, kubernetesSupportedVersion, clusterManager, keys); worker.kubernetesClusterVmMapDao = kubernetesClusterVmMapDao; + worker.networkDao = networkDao; + worker.addonApplyRetrySleepMs = 0; + worker.upgradeTimeoutTime = Long.MAX_VALUE; + } + + private void mockAddons(boolean isolated, boolean csi) { + Mockito.when(kubernetesCluster.getNetworkId()).thenReturn(10L); + Mockito.when(networkDao.findById(10L)).thenReturn(network); + Mockito.when(clusterManager.isDirectAccess(network)).thenReturn(!isolated); + Mockito.when(kubernetesCluster.isCsiEnabled()).thenReturn(csi); + } + + private MockedStatic mockSsh(Pair result) { + MockedStatic ssh = Mockito.mockStatic(SshHelper.class); + ssh.when(() -> SshHelper.sshExecute(Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), + Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(result); + return ssh; + } + + private void verifyApplied(MockedStatic ssh, String command, int times) { + ssh.verify(() -> SshHelper.sshExecute(Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any(), Mockito.any(), + ArgumentMatchers.eq(command), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt()), Mockito.times(times)); + } + + @Test + public void applyAddonsAppliesTheProviderAndTheCsiDriver() { + mockAddons(true, true); + try (MockedStatic ssh = mockSsh(new Pair<>(true, "deployment \"cloud-controller-manager\" successfully rolled out"))) { + Assert.assertNull(worker.applyAddons()); + verifyApplied(ssh, KubernetesClusterUpgradeWorker.APPLY_PROVIDER_COMMAND, 1); + verifyApplied(ssh, KubernetesClusterUpgradeWorker.APPLY_CSI_DRIVER_COMMAND, 1); + } + } + + @Test + public void applyAddonsSkipsTheProviderOnASharedNetworkAndTheCsiDriverWhenNotEnabled() { + mockAddons(false, false); + try (MockedStatic ssh = mockSsh(new Pair<>(true, ""))) { + Assert.assertNull(worker.applyAddons()); + ssh.verifyNoInteractions(); + } + } + + @Test + public void applyAddonsRetriesThenReportsTheFailure() { + mockAddons(true, false); + Mockito.when(kubernetesSupportedVersion.getSemanticVersion()).thenReturn("1.34.7"); + try (MockedStatic ssh = mockSsh(new Pair<>(false, "error: timed out waiting for the condition"))) { + String error = worker.applyAddons(); + Assert.assertNotNull(error); + Assert.assertTrue(error, error.contains("provider") && error.contains("1.34.7") && error.contains("timed out waiting")); + verifyApplied(ssh, KubernetesClusterUpgradeWorker.APPLY_PROVIDER_COMMAND, KubernetesClusterService.KubernetesClusterUpgradeRetries.value() + 1); + } + } + + @Test + public void applyAddonsReportsAFailureWhoseExceptionHasNoMessage() { + mockAddons(true, false); + try (MockedStatic ssh = Mockito.mockStatic(SshHelper.class)) { + ssh.when(() -> SshHelper.sshExecute(Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), + Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenThrow(new NullPointerException()); + Assert.assertNotNull(worker.applyAddons()); + } + } + + @Test + public void applyAddonsStopsRetryingOnceTheUpgradeTimedOut() { + mockAddons(true, false); + worker.upgradeTimeoutTime = 0; + try (MockedStatic ssh = mockSsh(new Pair<>(false, "error"))) { + Assert.assertNotNull(worker.applyAddons()); + verifyApplied(ssh, KubernetesClusterUpgradeWorker.APPLY_PROVIDER_COMMAND, 1); + } + } + + @Test + public void applyAddonsRetriesAfterAFailure() { + mockAddons(true, false); + try (MockedStatic ssh = Mockito.mockStatic(SshHelper.class)) { + ssh.when(() -> SshHelper.sshExecute(Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.anyString(), + Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenThrow(new RuntimeException("connection refused")).thenReturn(new Pair<>(true, "")); + Assert.assertNull(worker.applyAddons()); + verifyApplied(ssh, KubernetesClusterUpgradeWorker.APPLY_PROVIDER_COMMAND, 2); + } } @Test