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 @@ -28,11 +28,11 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
Expand Down Expand Up @@ -2307,7 +2307,7 @@ public boolean addNodesToKubernetesCluster(AddNodesToKubernetesClusterCmd cmd) {
KubernetesClusterVO kubernetesCluster = validateCluster(cmd.getClusterId());
long networkId = kubernetesCluster.getNetworkId();
NetworkVO networkVO = networkDao.findById(networkId);
List<Long> validNodeIds = validateNodes(cmd.getNodeIds(), networkId, networkVO.getName(), kubernetesCluster, false);
List<Long> validNodeIds = validateNodes(cmd.getNodeIds(), networkId, networkVO.getName(), false);
if (validNodeIds.isEmpty()) {
throw new CloudRuntimeException("No valid nodes found to be added to the Kubernetes cluster");
}
Expand All @@ -2322,7 +2322,7 @@ public boolean removeNodesFromKubernetesCluster(RemoveNodesFromKubernetesCluster
logAndThrow(Level.ERROR, "Kubernetes Service plugin is disabled");
}
KubernetesClusterVO kubernetesCluster = validateCluster(cmd.getClusterId());
List<Long> validNodeIds = validateNodes(cmd.getNodeIds(), null, null, kubernetesCluster, true);
List<Long> validNodeIds = validateNodes(cmd.getNodeIds(), null, null, true);
if (validNodeIds.isEmpty()) {
throw new CloudRuntimeException("No valid nodes found to be removed from the Kubernetes cluster");
}
Expand All @@ -2341,10 +2341,10 @@ private KubernetesClusterVO validateCluster(long clusterId) {
return kubernetesCluster;
}

private List<Long> validateNodes(List<Long> nodeIds, Long networkId, String networkName, KubernetesCluster cluster, boolean removeNodes) {
protected List<Long> validateNodes(List<Long> nodeIds, Long networkId, String networkName, boolean removeNodes) {
Account caller = CallContext.current().getCallingAccount();
List<Long> validNodeIds = new ArrayList<>(nodeIds);
for (Long id : nodeIds) {
List<Long> validNodeIds = new ArrayList<>(new LinkedHashSet<>(nodeIds));
for (Long id : new ArrayList<>(validNodeIds)) {
VMInstanceVO node = vmInstanceDao.findById(id);
if (Objects.isNull(node)) {
logger.error(String.format("Failed to find node (physical or virtual machine) with ID: %s", id));
Expand All @@ -2366,10 +2366,13 @@ private List<Long> validateNodes(List<Long> nodeIds, Long networkId, String netw
logger.error(String.format("Node: %s does not have its default NIC in the kubernetes cluster network: %s", node.getId(), networkName));
validNodeIds.remove(id);
}
List<KubernetesClusterVmMapVO> clusterVmMapVO = kubernetesClusterVmMapDao.listByClusterIdAndVmIdsIn(cluster.getId(), Collections.singletonList(id));
if (Objects.nonNull(clusterVmMapVO) && !clusterVmMapVO.isEmpty()) {
logger.warn(String.format("Node: %s is already part of the cluster %s", node.getId(), cluster.getName()));
validNodeIds.remove(id);
for (KubernetesClusterVmMapVO clusterVmMapVO : kubernetesClusterVmMapDao.listByVmId(id)) {
KubernetesClusterVO mappedCluster = kubernetesClusterDao.findById(clusterVmMapVO.getClusterId());
if (Objects.nonNull(mappedCluster)) {
logger.warn(String.format("Node: %s is already part of the Kubernetes cluster %s", node.getId(), mappedCluster.getUuid()));
validNodeIds.remove(id);
break;
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ private Pair<Boolean, Integer> validateAndSetupNode(Network network, IpAddress p
userVmManager.updateVirtualMachine(nodeId, null, null, null, null,
null, null, base64UserData, null, null, null,
BaseCmd.HTTPMethod.POST, null, null, null, null, null);
resetNodeProvisioningState(userVmDao.findById(nodeId), publicIp, sshKeyFile, sshStartPort);

RebootVMCmd rebootVMCmd = new RebootVMCmd();
Field idField = rebootVMCmd.getClass().getDeclaredField("id");
Expand Down Expand Up @@ -292,21 +293,32 @@ private boolean validateNodeCompatibility(IpAddress publicIp, long nodeId, int n
logger.error(String.format("Failed to validate node with ID: %s", nodeId), e);
return false;
}
UserVmVO userVm = userVmDao.findById(nodeId);
cleanupCloudInitSemFolder(userVm, publicIp, pkFile, nodeSshPort);
return true;
}

private void cleanupCloudInitSemFolder(UserVm userVm, IpAddress publicIp, File pkFile, int nodeSshPort) {
/**
* Clears the previous user data run, and any earlier cluster join: a VM removed from a cluster keeps
* /home/cloud/success, which makes the join scripts exit early, and kubeadm state if it wasn't reset.
*/
protected String getNodeProvisioningResetCommand(UserVm userVm) {
return String.format("sudo rm -rf /var/lib/cloud/instances/%s/sem/* && sudo rm -f /home/cloud/success && " +
"{ sudo systemctl stop deploy-kube-system 2>/dev/null; " +
"sudo umount /mnt/k8sdisk 2>/dev/null; mountpoint -q /mnt/k8sdisk || sudo rm -rf /mnt/k8sdisk; sudo rm -rf /aux-dwnld; " +
"sudo systemctl disable --now kubelet 2>/dev/null; " +
"if PATH=$PATH:/opt/bin command -v kubeadm >/dev/null; then " +
"sudo env PATH=$PATH:/opt/bin kubeadm reset -f; fi; }", userVm.getUuid());
}

protected void resetNodeProvisioningState(UserVm userVm, IpAddress publicIp, File pkFile, int nodeSshPort) {
try {
String command = String.format("sudo rm -rf /var/lib/cloud/instances/%s/sem/*", userVm.getUuid());
Pair<Boolean, String> result = SshHelper.sshExecute(publicIp.getAddress().addr(), nodeSshPort, getControlNodeLoginUser(),
pkFile, null, command, 10000, 10000, 10 * 60 * 1000);
pkFile, null, getNodeProvisioningResetCommand(userVm), 10000, 10000, 10 * 60 * 1000);
if (Boolean.FALSE.equals(result.first())) {
logger.error(String.format("Failed to cleanup previous applied userdata on node: %s; This may hamper to addition of the node to the cluster ", userVm.getName()));
logger.error(String.format("Failed to reset previous provisioning on node: %s; this may prevent it from joining the cluster: %s",
userVm.getName(), result.second()));
}
} catch (Exception e) {
logger.error(String.format("Failed to cleanup previous applied userdata on node: %s; This may hamper to addition of the node to the cluster ", userVm.getName()), e);
logger.error(String.format("Failed to reset previous provisioning on node: %s; this may prevent it from joining the cluster", userVm.getName()), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public interface KubernetesClusterVmMapDao extends GenericDao<KubernetesClusterV
public List<KubernetesClusterVmMapVO> listByClusterId(long clusterId);

public KubernetesClusterVmMapVO getClusterMapFromVmId(long vmId);

List<KubernetesClusterVmMapVO> listByVmId(long vmId);

public List<KubernetesClusterVmMapVO> listByClusterIdAndVmIdsIn(long clusterId, List<Long> vmIds);

int removeByClusterIdAndVmIdsIn(long clusterId, List<Long> vmIds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ public KubernetesClusterVmMapVO getClusterMapFromVmId(long vmId) {
return findOneBy(sc);
}

@Override
public List<KubernetesClusterVmMapVO> listByVmId(long vmId) {
SearchCriteria<KubernetesClusterVmMapVO> sc = vmIdSearch.create();
sc.setParameters("vmId", vmId);
return listBy(sc);
}

@Override
public List<KubernetesClusterVmMapVO> listByClusterIdAndVmIdsIn(long clusterId, List<Long> vmIds) {
SearchCriteria<KubernetesClusterVmMapVO> sc = clusterIdSearch.create();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@
import com.cloud.user.User;
import com.cloud.utils.Pair;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.NicVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.VMInstanceDao;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.AddVirtualMachinesToKubernetesClusterCmd;
Expand Down Expand Up @@ -103,6 +105,9 @@ public class KubernetesClusterManagerImplTest {
@Mock
private ServiceOfferingDao serviceOfferingDao;

@Mock
private NicDao nicDao;

@Spy
@InjectMocks
KubernetesClusterManagerImpl kubernetesClusterManager;
Expand Down Expand Up @@ -297,6 +302,65 @@ public void addVmsToCluster() {
Assert.assertTrue(kubernetesClusterManager.addVmsToCluster(cmd));
}

private void mockNodeForAdd(long vmId, long networkId) {
VMInstanceVO vm = Mockito.mock(VMInstanceVO.class);
VMTemplateVO template = Mockito.mock(VMTemplateVO.class);
NicVO nic = Mockito.mock(NicVO.class);
Mockito.when(vm.getTemplateId()).thenReturn(10L);
Mockito.when(template.isForCks()).thenReturn(true);
Mockito.when(nic.getNetworkId()).thenReturn(networkId);
Mockito.when(vmInstanceDao.findById(vmId)).thenReturn(vm);
Mockito.when(templateDao.findById(10L)).thenReturn(template);
Mockito.when(nicDao.findDefaultNicForVM(vmId)).thenReturn(nic);
}

@Test
public void validateNodesAcceptsNodeNotInAnyCluster() {
mockNodeForAdd(1L, 5L);
Mockito.when(kubernetesClusterVmMapDao.listByVmId(1L)).thenReturn(Collections.emptyList());
Assert.assertEquals(List.of(1L), kubernetesClusterManager.validateNodes(List.of(1L), 5L, "net", false));
}

@Test
public void validateNodesRejectsNodeInAnotherCluster() {
mockNodeForAdd(1L, 5L);
KubernetesClusterVmMapVO map = Mockito.mock(KubernetesClusterVmMapVO.class);
Mockito.when(map.getClusterId()).thenReturn(7L);
Mockito.when(kubernetesClusterVmMapDao.listByVmId(1L)).thenReturn(List.of(map));
Mockito.when(kubernetesClusterDao.findById(7L)).thenReturn(Mockito.mock(KubernetesClusterVO.class));
Assert.assertTrue(kubernetesClusterManager.validateNodes(List.of(1L), 5L, "net", false).isEmpty());
}

@Test
public void validateNodesAcceptsNodeMappedToRemovedCluster() {
mockNodeForAdd(1L, 5L);
KubernetesClusterVmMapVO map = Mockito.mock(KubernetesClusterVmMapVO.class);
Mockito.when(map.getClusterId()).thenReturn(7L);
Mockito.when(kubernetesClusterVmMapDao.listByVmId(1L)).thenReturn(List.of(map));
Mockito.when(kubernetesClusterDao.findById(7L)).thenReturn(null);
Assert.assertEquals(List.of(1L), kubernetesClusterManager.validateNodes(List.of(1L), 5L, "net", false));
}

@Test
public void validateNodesRejectsNodeWithLiveMappingBehindStaleOne() {
mockNodeForAdd(1L, 5L);
KubernetesClusterVmMapVO stale = Mockito.mock(KubernetesClusterVmMapVO.class);
KubernetesClusterVmMapVO live = Mockito.mock(KubernetesClusterVmMapVO.class);
Mockito.when(stale.getClusterId()).thenReturn(7L);
Mockito.when(live.getClusterId()).thenReturn(8L);
Mockito.when(kubernetesClusterVmMapDao.listByVmId(1L)).thenReturn(List.of(stale, live));
Mockito.when(kubernetesClusterDao.findById(7L)).thenReturn(null);
Mockito.when(kubernetesClusterDao.findById(8L)).thenReturn(Mockito.mock(KubernetesClusterVO.class));
Assert.assertTrue(kubernetesClusterManager.validateNodes(List.of(1L), 5L, "net", false).isEmpty());
}

@Test
public void validateNodesDropsDuplicateIds() {
mockNodeForAdd(1L, 5L);
Mockito.when(kubernetesClusterVmMapDao.listByVmId(1L)).thenReturn(Collections.emptyList());
Assert.assertEquals(List.of(1L), kubernetesClusterManager.validateNodes(Arrays.asList(1L, 1L), 5L, "net", false));
}

@Test
public void removeVmsFromCluster() {
KubernetesClusterVO cluster = Mockito.mock(KubernetesClusterVO.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.kubernetes.cluster.actionworkers;

import com.cloud.kubernetes.cluster.KubernetesCluster;
import com.cloud.kubernetes.cluster.KubernetesClusterManagerImpl;
import com.cloud.network.IpAddress;
import com.cloud.utils.Pair;
import com.cloud.utils.net.Ip;
import com.cloud.utils.ssh.SshHelper;
import com.cloud.uservm.UserVm;
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;

import java.io.File;

@RunWith(MockitoJUnitRunner.class)
public class KubernetesClusterAddWorkerTest {

@Mock
private KubernetesCluster kubernetesCluster;
@Mock
private KubernetesClusterManagerImpl clusterManager;
@Mock
private UserVm userVm;
@Mock
private IpAddress publicIp;

private final File pkFile = new File("/dev/null");
private KubernetesClusterAddWorker worker;

@Before
public void setUp() {
worker = Mockito.spy(new KubernetesClusterAddWorker(kubernetesCluster, clusterManager));
Mockito.doReturn("cloud").when(worker).getControlNodeLoginUser();
Mockito.when(publicIp.getAddress()).thenReturn(new Ip("10.1.1.1"));
Mockito.when(userVm.getUuid()).thenReturn("vm-uuid");
}

@Test
public void getNodeProvisioningResetCommandClearsMarkerAndKubeadmState() {
Assert.assertEquals("sudo rm -rf /var/lib/cloud/instances/vm-uuid/sem/* && sudo rm -f /home/cloud/success && " +
"{ sudo systemctl stop deploy-kube-system 2>/dev/null; " +
"sudo umount /mnt/k8sdisk 2>/dev/null; mountpoint -q /mnt/k8sdisk || sudo rm -rf /mnt/k8sdisk; sudo rm -rf /aux-dwnld; " +
"sudo systemctl disable --now kubelet 2>/dev/null; " +
"if PATH=$PATH:/opt/bin command -v kubeadm >/dev/null; then " +
"sudo env PATH=$PATH:/opt/bin kubeadm reset -f; fi; }",
worker.getNodeProvisioningResetCommand(userVm));
}

private MockedStatic<SshHelper> mockSsh() {
return Mockito.mockStatic(SshHelper.class);
}

private void verifyResetCommandRun(MockedStatic<SshHelper> sshHelper) {
String command = worker.getNodeProvisioningResetCommand(userVm);
sshHelper.verify(() -> SshHelper.sshExecute(ArgumentMatchers.eq("10.1.1.1"), ArgumentMatchers.eq(2222),
ArgumentMatchers.eq("cloud"), ArgumentMatchers.eq(pkFile), ArgumentMatchers.isNull(),
ArgumentMatchers.eq(command),
ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()));
}

@Test
public void resetNodeProvisioningStateRunsResetCommand() {
try (MockedStatic<SshHelper> sshHelper = mockSsh()) {
sshHelper.when(() -> SshHelper.sshExecute(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(),
ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(new Pair<>(true, ""));
worker.resetNodeProvisioningState(userVm, publicIp, pkFile, 2222);
verifyResetCommandRun(sshHelper);
}
}

@Test
public void resetNodeProvisioningStateToleratesUnreachableNode() {
try (MockedStatic<SshHelper> sshHelper = mockSsh()) {
sshHelper.when(() -> SshHelper.sshExecute(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(),
ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenThrow(new RuntimeException("unreachable"));
worker.resetNodeProvisioningState(userVm, publicIp, pkFile, 2222);
verifyResetCommandRun(sshHelper);
}
}

@Test
public void resetNodeProvisioningStateToleratesCommandFailure() {
try (MockedStatic<SshHelper> sshHelper = mockSsh()) {
sshHelper.when(() -> SshHelper.sshExecute(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(),
ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyString(),
ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(new Pair<>(false, "kubeadm failed"));
worker.resetNodeProvisioningState(userVm, publicIp, pkFile, 2222);
verifyResetCommandRun(sshHelper);
}
}
}
Loading