Search in sources :

Example 1 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class VpcVirtualRouterElementTest method testApplyVpnUsers.

@Test
public void testApplyVpnUsers() {
    vpcVirtualRouterElement._vpcRouterMgr = _vpcRouterMgr;
    final AdvancedNetworkTopology advancedNetworkTopology = Mockito.mock(AdvancedNetworkTopology.class);
    final BasicNetworkTopology basicNetworkTopology = Mockito.mock(BasicNetworkTopology.class);
    networkTopologyContext.setAdvancedNetworkTopology(advancedNetworkTopology);
    networkTopologyContext.setBasicNetworkTopology(basicNetworkTopology);
    networkTopologyContext.init();
    final Vpc vpc = Mockito.mock(Vpc.class);
    final Zone zone = Mockito.mock(Zone.class);
    final RemoteAccessVpn remoteAccessVpn = Mockito.mock(RemoteAccessVpn.class);
    final DomainRouterVO domainRouterVO1 = Mockito.mock(DomainRouterVO.class);
    final DomainRouterVO domainRouterVO2 = Mockito.mock(DomainRouterVO.class);
    final VpnUser vpnUser1 = Mockito.mock(VpnUser.class);
    final VpnUser vpnUser2 = Mockito.mock(VpnUser.class);
    final List<VpnUser> users = new ArrayList<>();
    users.add(vpnUser1);
    users.add(vpnUser2);
    final List<DomainRouterVO> routers = new ArrayList<>();
    routers.add(domainRouterVO1);
    routers.add(domainRouterVO2);
    final Long vpcId = new Long(1l);
    final Long zoneId = new Long(1l);
    when(remoteAccessVpn.getVpcId()).thenReturn(vpcId);
    when(_vpcRouterMgr.getVpcRouters(vpcId)).thenReturn(routers);
    when(_entityMgr.findById(Vpc.class, vpcId)).thenReturn(vpc);
    when(vpc.getZoneId()).thenReturn(zoneId);
    when(zoneRepository.findOne(zoneId)).thenReturn(zone);
    when(networkTopologyContext.retrieveNetworkTopology(zone)).thenReturn(advancedNetworkTopology);
    try {
        when(advancedNetworkTopology.applyVpnUsers(remoteAccessVpn, users, domainRouterVO1)).thenReturn(new String[] { "user1", "user2" });
        when(advancedNetworkTopology.applyVpnUsers(remoteAccessVpn, users, domainRouterVO2)).thenReturn(new String[] { "user3", "user4" });
    } catch (final ResourceUnavailableException e) {
        fail(e.getMessage());
    }
    try {
        final String[] results = vpcVirtualRouterElement.applyVpnUsers(remoteAccessVpn, users);
        assertNotNull(results);
        assertEquals(results[0], "user1");
        assertEquals(results[1], "user2");
        assertEquals(results[2], "user3");
        assertEquals(results[3], "user4");
    } catch (final ResourceUnavailableException e) {
        fail(e.getMessage());
    }
    verify(remoteAccessVpn, times(1)).getVpcId();
    verify(vpc, times(1)).getZoneId();
    verify(zoneRepository, times(1)).findOne(zoneId);
    verify(networkTopologyContext, times(1)).retrieveNetworkTopology(zone);
}
Also used : BasicNetworkTopology(com.cloud.network.topology.BasicNetworkTopology) Zone(com.cloud.db.model.Zone) Vpc(com.cloud.network.vpc.Vpc) ArrayList(java.util.ArrayList) AdvancedNetworkTopology(com.cloud.network.topology.AdvancedNetworkTopology) VpnUser(com.cloud.network.VpnUser) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) DomainRouterVO(com.cloud.vm.DomainRouterVO) Test(org.junit.Test)

Example 2 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method updateNicIpForVirtualMachine.

@Override
public UserVm updateNicIpForVirtualMachine(final UpdateVmNicIpCmd cmd) {
    final Long nicId = cmd.getNicId();
    String ipaddr = cmd.getIpaddress();
    final Account caller = CallContext.current().getCallingAccount();
    // check whether the nic belongs to user vm.
    final NicVO nicVO = _nicDao.findById(nicId);
    if (nicVO == null) {
        throw new InvalidParameterValueException("There is no nic for the " + nicId);
    }
    if (nicVO.getVmType() != VirtualMachine.Type.User) {
        throw new InvalidParameterValueException("The nic is not belongs to user vm");
    }
    final UserVm vm = _vmDao.findById(nicVO.getInstanceId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm with the nic");
    }
    final Network network = _networkDao.findById(nicVO.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("There is no network with the nic");
    }
    // Don't allow to update vm nic ip if network is not in Implemented/Setup/Allocated state
    if (!(network.getState() == Network.State.Allocated || network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
        throw new InvalidParameterValueException("Network is not in the right state to update vm nic ip. Correct states are: " + Network.State.Allocated + ", " + Network.State.Implemented + ", " + Network.State.Setup);
    }
    final NetworkOfferingVO offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
    if (offering == null) {
        throw new InvalidParameterValueException("There is no network offering with the network");
    }
    if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && vm.getState() != State.Stopped) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to update the vm nic having the specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    // verify permissions
    _accountMgr.checkAccess(caller, null, true, vm);
    final Account ipOwner = _accountDao.findByIdIncludingRemoved(vm.getAccountId());
    // verify ip address
    s_logger.debug("Calling the ip allocation ...");
    final Zone zone = zoneRepository.findOne(network.getDataCenterId());
    if (zone == null) {
        throw new InvalidParameterValueException("There is no dc with the nic");
    }
    if (zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
        try {
            ipaddr = _ipAddrMgr.allocateGuestIP(network, ipaddr);
        } catch (final InsufficientAddressCapacityException e) {
            throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
        }
        if (ipaddr == null) {
            throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
        }
        if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
            final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
            if (oldIP != null) {
                oldIP.setVmIp(ipaddr);
                _ipAddressDao.persist(oldIP);
            }
        }
        // implementing the network elements and resources as a part of vm nic ip update if network has services and it is in Implemented state
        if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && network.getState() == Network.State.Implemented) {
            final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
            final ReservationContext context = new ReservationContextImpl(null, null, callerUser, caller);
            final DeployDestination dest = new DeployDestination(zoneRepository.findOne(network.getDataCenterId()), null, null, null);
            s_logger.debug("Implementing the network " + network + " elements and resources as a part of vm nic ip update");
            try {
                // implement the network elements and rules again
                _networkMgr.implementNetworkElementsAndResources(dest, context, network, offering);
            } catch (final Exception ex) {
                s_logger.warn("Failed to implement network " + network + " elements and resources as a part of vm nic ip update due to ", ex);
                final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of vm nic ip " + "update");
                e.addProxyObject(network.getUuid(), "networkId");
                // restore to old ip address
                if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
                    final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
                    if (oldIP != null) {
                        oldIP.setVmIp(nicVO.getIPv4Address());
                        _ipAddressDao.persist(oldIP);
                    }
                }
                throw e;
            }
        }
    } else if (zone.getNetworkType() == NetworkType.Basic || network.getGuestType() == Network.GuestType.Shared) {
        // handle the basic networks here
        // for basic zone, need to provide the podId to ensure proper ip alloation
        Long podId = null;
        if (zone.getNetworkType() == NetworkType.Basic) {
            podId = vm.getPodIdToDeployIn();
            if (podId == null) {
                throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
            }
        }
        try {
            ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, ipaddr);
            if (ipaddr == null) {
                throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
            }
            final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nicVO.getNetworkId(), nicVO.getIPv4Address());
            if (ip != null) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(final TransactionStatus status) {
                        _ipAddrMgr.markIpAsUnavailable(ip.getId());
                        _ipAddressDao.unassignIpAddress(ip.getId());
                    }
                });
            }
        } catch (final InsufficientAddressCapacityException e) {
            s_logger.error("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
            return null;
        }
    } else {
        s_logger.error("UpdateVmNicIpCmd is not supported in this network...");
        return null;
    }
    // update nic ipaddress
    nicVO.setIPv4Address(ipaddr);
    _nicDao.persist(nicVO);
    return vm;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) Zone(com.cloud.db.model.Zone) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 3 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method migrateVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(final Long vmId, final Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    // access check - only root admin can migrate VM
    final Account caller = CallContext.current().getCallingAccount();
    if (!_accountMgr.isRootAdmin(caller.getId())) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
        }
        throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!");
    }
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId);
    }
    // business logic
    if (vm.getState() != State.Running) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
        }
        final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Running, unable to migrate the vm with specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
        throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
    }
    if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.KVM)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(vm + " is not XenServer/KVM, cannot migrate this VM.");
        }
        throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/KVM only");
    }
    if (isVMUsingLocalStorage(vm)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(vm + " is using Local Storage, cannot migrate this VM.");
        }
        throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate");
    }
    // check if migrating to same host
    final long srcHostId = vm.getHostId();
    if (destinationHost.getId() == srcHostId) {
        throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM");
    }
    // check if host is UP
    if (destinationHost.getState() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
        throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
    }
    if (vm.getType() != VirtualMachine.Type.User) {
        // for System VMs check that the destination host is within the same
        // cluster
        final HostVO srcHost = _hostDao.findById(srcHostId);
        if (srcHost != null && srcHost.getClusterId() != null && destinationHost.getClusterId() != null) {
            if (srcHost.getClusterId().longValue() != destinationHost.getClusterId().longValue()) {
                throw new InvalidParameterValueException("Cannot migrate the VM, destination host is not in the same cluster as current host of the VM");
            }
        }
    }
    checkHostsDedication(vm, srcHostId, destinationHost.getId());
    // call to core process
    final Zone zone = zoneRepository.findOne(destinationHost.getDataCenterId());
    final HostPodVO pod = _podDao.findById(destinationHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destinationHost.getClusterId());
    final DeployDestination dest = new DeployDestination(zone, pod, cluster, destinationHost);
    // check max guest vm limit for the destinationHost
    final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
    if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Host name: " + destinationHost.getName() + ": " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
        }
        throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
    }
    // Check host tags
    final ServiceOffering serviceOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId());
    if (serviceOffering != null) {
        final String requiredHostTag = serviceOffering.getHostTag();
        final List<String> hostTags = _hostTagsDao.gethostTags(destinationHost.getId());
        boolean foundRequiredHostTag = false;
        for (final String hostTag : hostTags) {
            if (hostTag.equals(requiredHostTag)) {
                foundRequiredHostTag = true;
                break;
            }
        }
        if (!foundRequiredHostTag && requiredHostTag != null) {
            throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " does not have required host tag " + requiredHostTag);
        }
    }
    final UserVmVO uservm = _vmDao.findById(vmId);
    if (uservm != null) {
        collectVmDiskStatistics(uservm);
    }
    _itMgr.migrate(vm.getUuid(), srcHostId, dest);
    final VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
    if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
        return _vmDao.findById(vmId);
    } else {
        return vmInstance;
    }
}
Also used : Account(com.cloud.user.Account) ServiceOffering(com.cloud.offering.ServiceOffering) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.org.Cluster) HostPodVO(com.cloud.dc.HostPodVO) HostVO(com.cloud.host.HostVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) ActionEvent(com.cloud.event.ActionEvent)

Example 4 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method updateDefaultNicForVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_UPDATE, eventDescription = "Creating Nic", async = true)
public UserVm updateDefaultNicForVirtualMachine(final UpdateDefaultNicForVMCmd cmd) throws InvalidParameterValueException, CloudRuntimeException {
    final Long vmId = cmd.getVmId();
    final Long nicId = cmd.getNicId();
    final Account caller = CallContext.current().getCallingAccount();
    final UserVmVO vmInstance = _vmDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("NIC cannot be updated for VM with VM Snapshots");
    }
    NicVO nic = _nicDao.findById(nicId);
    if (nic == null) {
        throw new InvalidParameterValueException("unable to find a nic with id " + nicId);
    }
    final NetworkVO network = _networkDao.findById(nic.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("unable to find a network with id " + nic.getNetworkId());
    }
    // Perform permission check on VM
    _accountMgr.checkAccess(caller, null, true, vmInstance);
    // Verify that zone is not Basic
    final Zone zone = zoneRepository.findOne(vmInstance.getDataCenterId());
    if (zone.getNetworkType() == NetworkType.Basic) {
        throw new CloudRuntimeException("Zone " + vmInstance.getDataCenterId() + ", has a NetworkType of Basic. Can't change default NIC on a Basic Network");
    }
    // no need to check permissions for network, we'll enumerate the ones they already have access to
    final Network existingdefaultnet = _networkModel.getDefaultNetworkForVm(vmId);
    // check to see if nic is attached to VM
    if (nic.getInstanceId() != vmId) {
        throw new InvalidParameterValueException(nic + " is not a nic on  " + vmInstance);
    }
    // if current default equals chosen new default, Throw an exception
    if (nic.isDefaultNic()) {
        throw new CloudRuntimeException("refusing to set default nic because chosen nic is already the default");
    }
    // make sure the VM is Running or Stopped
    if (vmInstance.getState() != State.Running && vmInstance.getState() != State.Stopped) {
        throw new CloudRuntimeException("refusing to set default " + vmInstance + " is not Running or Stopped");
    }
    NicProfile existing = null;
    final List<NicProfile> nicProfiles = _networkMgr.getNicProfiles(vmInstance);
    for (final NicProfile nicProfile : nicProfiles) {
        if (nicProfile.isDefaultNic() && existingdefaultnet != null && nicProfile.getNetworkId() == existingdefaultnet.getId()) {
            existing = nicProfile;
        }
    }
    if (existing == null) {
        s_logger.warn("Failed to update default nic, no nic profile found for existing default network");
        throw new CloudRuntimeException("Failed to find a nic profile for the existing default network. This is bad and probably means some sort of configuration corruption");
    }
    NicVO existingVO = _nicDao.findById(existing.id);
    nic.setDefaultNic(true);
    existingVO.setDefaultNic(false);
    nic = _nicDao.persist(nic);
    existingVO = _nicDao.persist(existingVO);
    Network newdefault = _networkModel.getDefaultNetworkForVm(vmId);
    if (newdefault == null) {
        nic.setDefaultNic(false);
        existingVO.setDefaultNic(true);
        nic = _nicDao.persist(nic);
        _nicDao.persist(existingVO);
        newdefault = _networkModel.getDefaultNetworkForVm(vmId);
        if (newdefault.getId() == existingdefaultnet.getId()) {
            throw new CloudRuntimeException("Setting a default nic failed, and we had no default nic, but we were able to set it back to the original");
        }
        throw new CloudRuntimeException("Failed to change default nic to " + nic + " and now we have no default");
    } else if (newdefault.getId() == nic.getNetworkId()) {
        s_logger.debug("successfully set default network to " + network + " for " + vmInstance);
        return _vmDao.findById(vmInstance.getId());
    }
    throw new CloudRuntimeException("something strange happened, new default network(" + newdefault.getId() + ") is not null, and is not equal to the network(" + nic.getNetworkId() + ") of the chosen nic");
}
Also used : Account(com.cloud.user.Account) NetworkVO(com.cloud.network.dao.NetworkVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) Zone(com.cloud.db.model.Zone) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ActionEvent(com.cloud.event.ActionEvent)

Example 5 with Zone

use of com.cloud.db.model.Zone in project cosmic by MissionCriticalCloud.

the class FirstFitPlannerTest method initializeForTest.

private void initializeForTest(final VirtualMachineProfileImpl vmProfile, final DataCenterDeployment plan, final ExcludeList avoids) {
    final Zone zone = mock(Zone.class);
    final VMInstanceVO vm = mock(VMInstanceVO.class);
    final UserVmVO userVm = mock(UserVmVO.class);
    final ServiceOfferingVO offering = mock(ServiceOfferingVO.class);
    final AccountVO account = mock(AccountVO.class);
    when(account.getId()).thenReturn(accountId);
    when(account.getAccountId()).thenReturn(accountId);
    when(vmProfile.getOwner()).thenReturn(account);
    when(vmProfile.getVirtualMachine()).thenReturn(vm);
    when(vmProfile.getId()).thenReturn(12L);
    when(vmDao.findById(12L)).thenReturn(userVm);
    when(userVm.getAccountId()).thenReturn(accountId);
    when(vm.getDataCenterId()).thenReturn(dataCenterId);
    when(zoneRepository.findOne(1L)).thenReturn(zone);
    when(avoids.shouldAvoid(zone)).thenReturn(false);
    when(plan.getDataCenterId()).thenReturn(dataCenterId);
    when(plan.getClusterId()).thenReturn(null);
    when(plan.getPodId()).thenReturn(null);
    // Mock offering details.
    when(vmProfile.getServiceOffering()).thenReturn(offering);
    when(offering.getId()).thenReturn(offeringId);
    when(vmProfile.getServiceOfferingId()).thenReturn(offeringId);
    when(offering.getCpu()).thenReturn(noOfCpusInOffering);
    when(offering.getRamSize()).thenReturn(ramInOffering);
    final List<Long> clustersWithEnoughCapacity = new ArrayList<>();
    clustersWithEnoughCapacity.add(1L);
    clustersWithEnoughCapacity.add(2L);
    clustersWithEnoughCapacity.add(3L);
    clustersWithEnoughCapacity.add(4L);
    clustersWithEnoughCapacity.add(5L);
    clustersWithEnoughCapacity.add(6L);
    when(capacityDao.listClustersInZoneOrPodByHostCapacities(dataCenterId, noOfCpusInOffering, ramInOffering * 1024L * 1024L, Capacity.CAPACITY_TYPE_CPU, true)).thenReturn(clustersWithEnoughCapacity);
    final Map<Long, Double> clusterCapacityMap = new HashMap<>();
    clusterCapacityMap.put(1L, 2048D);
    clusterCapacityMap.put(2L, 2048D);
    clusterCapacityMap.put(3L, 2048D);
    clusterCapacityMap.put(4L, 2048D);
    clusterCapacityMap.put(5L, 2048D);
    clusterCapacityMap.put(6L, 2048D);
    final Pair<List<Long>, Map<Long, Double>> clustersOrderedByCapacity = new Pair<>(clustersWithEnoughCapacity, clusterCapacityMap);
    when(capacityDao.orderClustersByAggregateCapacity(dataCenterId, Capacity.CAPACITY_TYPE_CPU, true)).thenReturn(clustersOrderedByCapacity);
    final List<Long> disabledClusters = new ArrayList<>();
    final List<Long> clustersWithDisabledPods = new ArrayList<>();
    when(clusterDao.listDisabledClusters(dataCenterId, null)).thenReturn(disabledClusters);
    when(clusterDao.listClustersWithDisabledPods(dataCenterId)).thenReturn(clustersWithDisabledPods);
    final List<Long> hostList0 = new ArrayList<>();
    final List<Long> hostList1 = new ArrayList<>();
    final List<Long> hostList2 = new ArrayList<>();
    final List<Long> hostList3 = new ArrayList<>();
    final List<Long> hostList4 = new ArrayList<>();
    final List<Long> hostList5 = new ArrayList<>();
    final List<Long> hostList6 = new ArrayList<>();
    hostList0.add(new Long(1));
    hostList1.add(new Long(10));
    hostList2.add(new Long(11));
    hostList3.add(new Long(12));
    hostList4.add(new Long(13));
    hostList5.add(new Long(14));
    hostList6.add(new Long(15));
    final String[] implicitHostTags = { "GPU" };
    final int ramInBytes = ramInOffering * 1024 * 1024;
    when(serviceOfferingDetailsDao.findDetail(Matchers.anyLong(), anyString())).thenReturn(null);
    when(hostGpuGroupsDao.listHostIds()).thenReturn(hostList0);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(1), Host.Type.Routing.toString())).thenReturn(hostList1);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(2), Host.Type.Routing.toString())).thenReturn(hostList2);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(3), Host.Type.Routing.toString())).thenReturn(hostList3);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(4), Host.Type.Routing.toString())).thenReturn(hostList4);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(5), Host.Type.Routing.toString())).thenReturn(hostList5);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(6), Host.Type.Routing.toString())).thenReturn(hostList6);
    when(hostTagsDao.getDistinctImplicitHostTags(hostList1, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList2, implicitHostTags)).thenReturn(Arrays.asList("abc", "123", "pqr", "456", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList3, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList4, implicitHostTags)).thenReturn(Arrays.asList("abc"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList5, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList6, implicitHostTags)).thenReturn(Arrays.asList("abc", "123", "pqr", "xyz"));
}
Also used : HashMap(java.util.HashMap) Zone(com.cloud.db.model.Zone) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) AccountVO(com.cloud.user.AccountVO) List(java.util.List) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Map(java.util.Map) HashMap(java.util.HashMap) Pair(com.cloud.utils.Pair)

Aggregations

Zone (com.cloud.db.model.Zone)106 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)34 ArrayList (java.util.ArrayList)32 DomainRouterVO (com.cloud.vm.DomainRouterVO)28 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)26 Network (com.cloud.network.Network)23 NetworkTopology (com.cloud.network.topology.NetworkTopology)23 Account (com.cloud.user.Account)23 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)23 NetworkVO (com.cloud.network.dao.NetworkVO)22 DeployDestination (com.cloud.deploy.DeployDestination)18 NicProfile (com.cloud.vm.NicProfile)16 List (java.util.List)16 HostPodVO (com.cloud.dc.HostPodVO)15 HostVO (com.cloud.host.HostVO)15 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)14 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)14 DB (com.cloud.utils.db.DB)14 TransactionStatus (com.cloud.utils.db.TransactionStatus)12 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)11