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 @@ -31,6 +31,7 @@ public class AffinityProcessorBase extends AdapterBase implements AffinityGroupP

public static final String AFFINITY_TYPE_HOST = "host affinity";
public static final String AFFINITY_TYPE_HOST_ANTI = "host anti-affinity";
public static final String AFFINITY_TYPE_NON_STRICT_HOST_ANTI = "non-strict host anti-affinity";

protected String _type;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.acl.Rule;
import org.apache.cloudstack.acl.SecurityChecker;
import org.apache.cloudstack.affinity.AffinityGroupService;
import org.apache.cloudstack.affinity.AffinityGroupVO;
import org.apache.cloudstack.affinity.AffinityProcessorBase;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
Expand Down Expand Up @@ -311,6 +312,8 @@ public class KubernetesClusterManagerImpl extends ManagerBase implements Kuberne
protected StateMachine2<KubernetesCluster.State, KubernetesCluster.Event, KubernetesCluster> _stateMachine = KubernetesCluster.State.getStateMachine();

protected final static List<String> CLUSTER_NODES_TYPES_LIST = Arrays.asList(WORKER.name(), CONTROL.name(), ETCD.name());
private static final Set<VirtualMachine.State> GONE_VM_STATES = EnumSet.of(VirtualMachine.State.Destroyed,
VirtualMachine.State.Expunging, VirtualMachine.State.Error);

ScheduledExecutorService _gcExecutor;
ScheduledExecutorService _stateScanner;
Expand Down Expand Up @@ -340,6 +343,8 @@ public class KubernetesClusterManagerImpl extends ManagerBase implements Kuberne
@Inject
protected AffinityGroupVMMapDao affinityGroupVMMapDao;
@Inject
protected AffinityGroupService affinityGroupService;
@Inject
protected ServiceOfferingDao serviceOfferingDao;
@Inject
protected UserDataDao userDataDao;
Expand Down Expand Up @@ -1299,6 +1304,68 @@ private void persistAffinityGroupMappings(long clusterId, Map<String, List<Long>
}
}

protected String getDefaultAntiAffinityGroupName(KubernetesCluster kubernetesCluster, String nodeType) {
return String.format("cks-%s-%s", kubernetesCluster.getUuid(), nodeType.toLowerCase());
}

protected Map<String, List<Long>> addDefaultAntiAffinityGroups(KubernetesClusterVO kubernetesCluster, Account owner,
Map<String, Long> nodeTypeCount, Map<String, List<Long>> affinityGroupNodeTypeMap) {
Map<String, List<Long>> result = MapUtils.isEmpty(affinityGroupNodeTypeMap) ? new HashMap<>() : new HashMap<>(affinityGroupNodeTypeMap);
if (!KubernetesClusterDefaultAntiAffinityEnabled.valueIn(owner.getId())) {
return result;
}
if (!affinityGroupService.isAffinityGroupProcessorAvailable(AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI)) {
logger.warn("Not adding default anti-affinity groups for Kubernetes cluster {}: affinity group type '{}' is not available",
kubernetesCluster, AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI);
return result;
}
for (String nodeType : CLUSTER_NODES_TYPES_LIST) {
// Only worker nodes can be scaled later, so a single control or etcd node has nothing to spread from.
long minNodes = WORKER.name().equals(nodeType) ? 1 : 2;
if (nodeTypeCount.getOrDefault(nodeType, 0L) < minNodes || CollectionUtils.isNotEmpty(result.get(nodeType))) {
continue;
}
AffinityGroupVO group = affinityGroupDao.persist(new AffinityGroupVO(getDefaultAntiAffinityGroupName(kubernetesCluster, nodeType),
AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI,
String.format("Spreads %s nodes of Kubernetes cluster %s across hosts", nodeType.toLowerCase(), kubernetesCluster.getName()),
owner.getDomainId(), owner.getId(), ControlledEntity.ACLType.Account));
result.put(nodeType, List.of(group.getId()));
}
return result;
}

private boolean isVmLive(long vmId) {
VMInstanceVO vm = vmInstanceDao.findById(vmId);
return vm != null && !GONE_VM_STATES.contains(vm.getState());
}

public void deleteDefaultAntiAffinityGroups(KubernetesCluster kubernetesCluster) {
String[] names = CLUSTER_NODES_TYPES_LIST.stream()
.map(nodeType -> getDefaultAntiAffinityGroupName(kubernetesCluster, nodeType)).toArray(String[]::new);
List<AffinityGroupVO> groups;
try {
groups = affinityGroupDao.findByAccountAndNames(kubernetesCluster.getAccountId(), names);
} catch (Exception e) {
logger.warn("Failed to look up the default affinity groups of Kubernetes cluster {}", kubernetesCluster, e);
return;
}
for (AffinityGroupVO group : groups) {
try {
if (!AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI.equals(group.getType())) {
continue;
}
if (CollectionUtils.isNotEmpty(kubernetesClusterAffinityGroupMapDao.listByAffinityGroupId(group.getId())) ||
affinityGroupVMMapDao.listVmIdsByAffinityGroup(group.getId()).stream().anyMatch(this::isVmLive)) {
logger.info("Keeping affinity group {} of Kubernetes cluster {}: it is still in use", group, kubernetesCluster);
continue;
}
affinityGroupService.deleteAffinityGroup(group.getId(), null, null, null, null);
} catch (Exception e) {
logger.warn("Failed to delete affinity group {} of Kubernetes cluster {}", group, kubernetesCluster, e);
}
}
}

private void addKubernetesClusterDetails(final KubernetesCluster kubernetesCluster, final Network network, final CreateKubernetesClusterCmd cmd) {
final String externalLoadBalancerIpAddress = cmd.getExternalLoadBalancerIpAddress();
final String dockerRegistryUserName = cmd.getDockerRegistryUserName();
Expand Down Expand Up @@ -1784,7 +1851,8 @@ public KubernetesClusterVO doInTransaction(TransactionStatus status) {
}
newCluster.setCsiEnabled(cmd.getEnableCsi());
kubernetesClusterDao.persist(newCluster);
persistAffinityGroupMappings(newCluster.getId(), affinityGroupNodeTypeMap);
persistAffinityGroupMappings(newCluster.getId(),
addDefaultAntiAffinityGroups(newCluster, owner, nodeTypeCount, affinityGroupNodeTypeMap));
addKubernetesClusterDetails(newCluster, defaultNetwork, cmd);
return newCluster;
}
Expand Down Expand Up @@ -3089,7 +3157,8 @@ public ConfigKey<?>[] getConfigKeys() {
KubernetesControlNodeInstallReattempts,
KubernetesWorkerNodeInstallAttemptWait,
KubernetesWorkerNodeInstallReattempts,
KubernetesEtcdNodeStartPort
KubernetesEtcdNodeStartPort,
KubernetesClusterDefaultAntiAffinityEnabled
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,14 @@ public interface KubernetesClusterService extends PluggableService, Configurable
"Start port for Port forwarding rules for etcd nodes",
true,
KubernetesServiceEnabled.key());
static final ConfigKey<Boolean> KubernetesClusterDefaultAntiAffinityEnabled = new ConfigKey<Boolean>("Advanced", Boolean.class,
"cloud.kubernetes.cluster.default.anti.affinity.enabled",
"true",
"When creating a Kubernetes cluster, place the worker nodes, and the control and etcd nodes when there is more than one of them, " +
"in a non-strict host anti-affinity group per node type so they prefer different hosts. Node types given affinity groups by the user are left alone",
true,
ConfigKey.Scope.Account,
KubernetesServiceEnabled.key());

KubernetesCluster findById(final Long id);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@ public boolean destroy() throws CloudRuntimeException {
updateKubernetesClusterEntryForGC();
return false;
}
manager.deleteDefaultAntiAffinityGroups(kubernetesCluster);
if (logger.isInfoEnabled()) {
logger.info("Kubernetes cluster: {} is successfully deleted", kubernetesCluster);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,6 @@ public interface KubernetesClusterAffinityGroupMapDao extends GenericDao<Kuberne
List<Long> listAffinityGroupIdsByClusterIdAndNodeType(long clusterId, String nodeType);

int removeByClusterId(long clusterId);

List<KubernetesClusterAffinityGroupMapVO> listByAffinityGroupId(long affinityGroupId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public class KubernetesClusterAffinityGroupMapDaoImpl extends GenericDaoBase<Kub

private final SearchBuilder<KubernetesClusterAffinityGroupMapVO> clusterIdAndNodeTypeSearch;
private final SearchBuilder<KubernetesClusterAffinityGroupMapVO> clusterIdSearch;
private final SearchBuilder<KubernetesClusterAffinityGroupMapVO> affinityGroupIdSearch;

public KubernetesClusterAffinityGroupMapDaoImpl() {
clusterIdAndNodeTypeSearch = createSearchBuilder();
Expand All @@ -44,6 +45,10 @@ public KubernetesClusterAffinityGroupMapDaoImpl() {
clusterIdSearch = createSearchBuilder();
clusterIdSearch.and("clusterId", clusterIdSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
clusterIdSearch.done();

affinityGroupIdSearch = createSearchBuilder();
affinityGroupIdSearch.and("affinityGroupId", affinityGroupIdSearch.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
affinityGroupIdSearch.done();
}

@Override
Expand All @@ -69,4 +74,11 @@ public int removeByClusterId(long clusterId) {
sc.setParameters("clusterId", clusterId);
return remove(sc);
}

@Override
public List<KubernetesClusterAffinityGroupMapVO> listByAffinityGroupId(long affinityGroupId) {
SearchCriteria<KubernetesClusterAffinityGroupMapVO> sc = affinityGroupIdSearch.create();
sc.setParameters("affinityGroupId", affinityGroupId);
return listBy(sc);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,15 @@
import com.cloud.utils.Pair;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import org.apache.cloudstack.affinity.AffinityGroupService;
import org.apache.cloudstack.affinity.AffinityGroupVO;
import org.apache.cloudstack.affinity.AffinityProcessorBase;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.AddVirtualMachinesToKubernetesClusterCmd;
import org.apache.cloudstack.api.command.user.kubernetes.cluster.RemoveVirtualMachinesFromKubernetesClusterCmd;
Expand Down Expand Up @@ -118,6 +122,12 @@ public class KubernetesClusterManagerImplTest {
@Mock
private HostDao hostDao;

@Mock
private AffinityGroupService affinityGroupService;

@Mock
private AffinityGroupVMMapDao affinityGroupVMMapDao;

@Spy
@InjectMocks
KubernetesClusterManagerImpl kubernetesClusterManager;
Expand Down Expand Up @@ -914,4 +924,157 @@ public void testValidateNodeAffinityGroupsAffinityNoExistingWorkers() {
Mockito.verify(kubernetesClusterAffinityGroupMapDao).listAffinityGroupIdsByClusterIdAndNodeType(1L, WORKER.name());
}


private KubernetesClusterVO mockClusterForDefaultAntiAffinity() {
KubernetesClusterVO cluster = Mockito.mock(KubernetesClusterVO.class);
Mockito.when(cluster.getUuid()).thenReturn("abc");
return cluster;
}

private Account mockOwnerForDefaultAntiAffinity() {
Account owner = Mockito.mock(Account.class);
Mockito.when(owner.getId()).thenReturn(5L);
return owner;
}

private void mockPersistedAffinityGroups() {
Mockito.when(affinityGroupService.isAffinityGroupProcessorAvailable(AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI)).thenReturn(true);
Mockito.when(affinityGroupDao.persist(Mockito.any(AffinityGroupVO.class))).thenAnswer(invocation -> {
AffinityGroupVO group = Mockito.spy((AffinityGroupVO) invocation.getArgument(0));
Mockito.doReturn(group.getName().endsWith("-control") ? 10L : 20L).when(group).getId();
return group;
});
}

@Test
public void addDefaultAntiAffinityGroupsCreatesNonStrictGroupPerNodeType() {
KubernetesClusterVO cluster = mockClusterForDefaultAntiAffinity();
Account owner = mockOwnerForDefaultAntiAffinity();
mockPersistedAffinityGroups();

Map<String, List<Long>> result = kubernetesClusterManager.addDefaultAntiAffinityGroups(cluster, owner,
Map.of(CONTROL.name(), 3L, WORKER.name(), 2L, ETCD.name(), 0L), new HashMap<>());

Assert.assertEquals(List.of(10L), result.get(CONTROL.name()));
Assert.assertEquals(List.of(20L), result.get(WORKER.name()));
Assert.assertFalse(result.containsKey(ETCD.name()));
Mockito.verify(affinityGroupDao).persist(Mockito.argThat((AffinityGroupVO g) ->
"cks-abc-control".equals(g.getName()) && AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI.equals(g.getType()) && g.getAccountId() == 5L));
Mockito.verify(affinityGroupDao).persist(Mockito.argThat((AffinityGroupVO g) -> "cks-abc-worker".equals(g.getName())));
}

@Test
public void addDefaultAntiAffinityGroupsKeepsUserGroups() {
KubernetesClusterVO cluster = mockClusterForDefaultAntiAffinity();
Account owner = mockOwnerForDefaultAntiAffinity();
mockPersistedAffinityGroups();
Map<String, List<Long>> userMap = new HashMap<>();
userMap.put(WORKER.name(), List.of(99L));

Map<String, List<Long>> result = kubernetesClusterManager.addDefaultAntiAffinityGroups(cluster, owner,
Map.of(CONTROL.name(), 3L, WORKER.name(), 2L, ETCD.name(), 0L), userMap);

Assert.assertEquals(List.of(99L), result.get(WORKER.name()));
Assert.assertEquals(List.of(10L), result.get(CONTROL.name()));
Mockito.verify(affinityGroupDao, Mockito.times(1)).persist(Mockito.any(AffinityGroupVO.class));
}

@Test
public void addDefaultAntiAffinityGroupsSkipsSingleControlAndEtcdNode() {
KubernetesClusterVO cluster = mockClusterForDefaultAntiAffinity();
Account owner = mockOwnerForDefaultAntiAffinity();
mockPersistedAffinityGroups();

Map<String, List<Long>> result = kubernetesClusterManager.addDefaultAntiAffinityGroups(cluster, owner,
Map.of(CONTROL.name(), 1L, WORKER.name(), 1L, ETCD.name(), 1L), null);

Assert.assertEquals(Map.of(WORKER.name(), List.of(20L)), result);
}

@Test
public void addDefaultAntiAffinityGroupsSkippedWhenProcessorUnavailable() {
KubernetesClusterVO cluster = Mockito.mock(KubernetesClusterVO.class);
Account owner = Mockito.mock(Account.class);
Mockito.when(affinityGroupService.isAffinityGroupProcessorAvailable(AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI)).thenReturn(false);

Map<String, List<Long>> result = kubernetesClusterManager.addDefaultAntiAffinityGroups(cluster, owner,
Map.of(CONTROL.name(), 1L, WORKER.name(), 1L, ETCD.name(), 0L), null);

Assert.assertTrue(result.isEmpty());
Mockito.verify(affinityGroupDao, Mockito.never()).persist(Mockito.any(AffinityGroupVO.class));
}

@Test
public void addDefaultAntiAffinityGroupsSkippedWhenDisabled() throws Exception {
overrideDefaultConfigValue(KubernetesClusterService.KubernetesClusterDefaultAntiAffinityEnabled, "_defaultValue", "false");
overrideDefaultConfigValue(KubernetesClusterService.KubernetesClusterDefaultAntiAffinityEnabled, "_value", null);
try {
Map<String, List<Long>> result = kubernetesClusterManager.addDefaultAntiAffinityGroups(
Mockito.mock(KubernetesClusterVO.class), Mockito.mock(Account.class),
Map.of(CONTROL.name(), 1L, WORKER.name(), 1L, ETCD.name(), 0L), null);
Assert.assertTrue(result.isEmpty());
Mockito.verifyNoInteractions(affinityGroupService);
} finally {
overrideDefaultConfigValue(KubernetesClusterService.KubernetesClusterDefaultAntiAffinityEnabled, "_defaultValue", "true");
overrideDefaultConfigValue(KubernetesClusterService.KubernetesClusterDefaultAntiAffinityEnabled, "_value", null);
}
}

@Test
public void deleteDefaultAntiAffinityGroupsDeletesOnlyCksGroups() {
KubernetesClusterVO cluster = mockClusterForDefaultAntiAffinity();
Mockito.when(cluster.getAccountId()).thenReturn(5L);
AffinityGroupVO control = Mockito.mock(AffinityGroupVO.class);
Mockito.when(control.getId()).thenReturn(10L);
Mockito.when(control.getType()).thenReturn(AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI);
AffinityGroupVO worker = Mockito.mock(AffinityGroupVO.class);
Mockito.when(worker.getType()).thenReturn("host affinity");
Mockito.when(affinityGroupDao.findByAccountAndNames(5L, "cks-abc-worker", "cks-abc-control", "cks-abc-etcd"))
.thenReturn(List.of(control, worker));
Mockito.when(affinityGroupVMMapDao.listVmIdsByAffinityGroup(10L)).thenReturn(List.of(7L, 8L));
VMInstanceVO destroyedVm = Mockito.mock(VMInstanceVO.class);
Mockito.when(destroyedVm.getState()).thenReturn(VirtualMachine.State.Destroyed);
Mockito.when(vmInstanceDao.findById(8L)).thenReturn(destroyedVm);

kubernetesClusterManager.deleteDefaultAntiAffinityGroups(cluster);

Mockito.verify(affinityGroupService).deleteAffinityGroup(10L, null, null, null, null);
Mockito.verifyNoMoreInteractions(affinityGroupService);
}

@Test
public void deleteDefaultAntiAffinityGroupsKeepsGroupWithLiveVms() {
KubernetesClusterVO cluster = mockClusterForDefaultAntiAffinity();
Mockito.when(cluster.getAccountId()).thenReturn(5L);
AffinityGroupVO control = Mockito.mock(AffinityGroupVO.class);
Mockito.when(control.getId()).thenReturn(10L);
Mockito.when(control.getType()).thenReturn(AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI);
Mockito.when(affinityGroupDao.findByAccountAndNames(5L, "cks-abc-worker", "cks-abc-control", "cks-abc-etcd"))
.thenReturn(List.of(control));
Mockito.when(affinityGroupVMMapDao.listVmIdsByAffinityGroup(10L)).thenReturn(List.of(7L));
VMInstanceVO vm = Mockito.mock(VMInstanceVO.class);
Mockito.when(vm.getState()).thenReturn(VirtualMachine.State.Stopped);
Mockito.when(vmInstanceDao.findById(7L)).thenReturn(vm);

kubernetesClusterManager.deleteDefaultAntiAffinityGroups(cluster);

Mockito.verifyNoInteractions(affinityGroupService);
}

@Test
public void deleteDefaultAntiAffinityGroupsKeepsGroupUsedByAnotherCluster() {
KubernetesClusterVO cluster = mockClusterForDefaultAntiAffinity();
Mockito.when(cluster.getAccountId()).thenReturn(5L);
AffinityGroupVO worker = Mockito.mock(AffinityGroupVO.class);
Mockito.when(worker.getId()).thenReturn(20L);
Mockito.when(worker.getType()).thenReturn(AffinityProcessorBase.AFFINITY_TYPE_NON_STRICT_HOST_ANTI);
Mockito.when(affinityGroupDao.findByAccountAndNames(5L, "cks-abc-worker", "cks-abc-control", "cks-abc-etcd"))
.thenReturn(List.of(worker));
Mockito.when(kubernetesClusterAffinityGroupMapDao.listByAffinityGroupId(20L))
.thenReturn(List.of(new KubernetesClusterAffinityGroupMapVO(2L, WORKER.name(), 20L)));

kubernetesClusterManager.deleteDefaultAntiAffinityGroups(cluster);

Mockito.verifyNoInteractions(affinityGroupService);
}
}
Loading