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 @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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<Pair<String, String>> getAddonApplyCommands() {
List<Pair<String, String>> 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<String, String> addon : getAddonApplyCommands()) {
boolean applied = false;
String output = null;
for (int retry = KubernetesClusterService.KubernetesClusterUpgradeRetries.value(); retry >= 0; retry--) {
try {
Pair<Boolean, String> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;

Expand All @@ -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<SshHelper> mockSsh(Pair<Boolean, String> result) {
MockedStatic<SshHelper> 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<SshHelper> 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<SshHelper> 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<SshHelper> 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<SshHelper> 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<SshHelper> 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<SshHelper> 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<SshHelper> 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
Expand Down
Loading