Search in sources :

Example 21 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method deleteLoadBalancerRule.

@DB
public boolean deleteLoadBalancerRule(final long loadBalancerId, final boolean apply, final Account caller, final long callerUserId, final boolean rollBack) {
    final LoadBalancerVO lb = _lbDao.findById(loadBalancerId);
    final FirewallRule.State backupState = lb.getState();
    // remove any ssl certs associated with this LB rule before trying to delete it.
    final LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(loadBalancerId);
    if (lbCertMap != null) {
        final boolean removeResult = removeCertFromLoadBalancer(loadBalancerId);
        if (!removeResult) {
            throw new CloudRuntimeException("Unable to remove certificate from load balancer rule " + loadBalancerId);
        }
    }
    final List<LoadBalancerVMMapVO> backupMaps = Transaction.execute(new TransactionCallback<List<LoadBalancerVMMapVO>>() {

        @Override
        public List<LoadBalancerVMMapVO> doInTransaction(final TransactionStatus status) {
            if (lb.getState() == FirewallRule.State.Staged) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Found a rule that is still in stage state so just removing it: " + lb);
                }
            } else if (lb.getState() == FirewallRule.State.Add || lb.getState() == FirewallRule.State.Active) {
                lb.setState(FirewallRule.State.Revoke);
                _lbDao.persist(lb);
            }
            final List<LoadBalancerVMMapVO> backupMaps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
            final List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
            if (maps != null) {
                for (final LoadBalancerVMMapVO map : maps) {
                    map.setRevoke(true);
                    _lb2VmMapDao.persist(map);
                    s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + map.getInstanceId());
                }
            }
            final List<LBHealthCheckPolicyVO> hcPolicies = _lb2healthcheckDao.listByLoadBalancerIdAndDisplayFlag(loadBalancerId, null);
            for (final LBHealthCheckPolicyVO lbHealthCheck : hcPolicies) {
                lbHealthCheck.setRevoke(true);
                _lb2healthcheckDao.persist(lbHealthCheck);
            }
            return backupMaps;
        }
    });
    // gather external network usage stats for this lb rule
    final NetworkVO network = _networkDao.findById(lb.getNetworkId());
    if (apply) {
        try {
            if (!applyLoadBalancerConfig(loadBalancerId)) {
                s_logger.warn("Unable to apply the load balancer config");
                return false;
            }
        } catch (final ResourceUnavailableException e) {
            if (rollBack && isRollBackAllowedForProvider(lb)) {
                if (backupMaps != null) {
                    for (final LoadBalancerVMMapVO map : backupMaps) {
                        _lb2VmMapDao.persist(map);
                        s_logger.debug("LB Rollback rule id: " + loadBalancerId + ", vmId " + map.getInstanceId());
                    }
                }
                lb.setState(backupState);
                _lbDao.persist(lb);
                s_logger.debug("LB Rollback rule id: " + loadBalancerId + " while deleting LB rule.");
            } else {
                s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
            }
            return false;
        }
    }
    final FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(lb.getId());
    if (relatedRule != null) {
        s_logger.warn("Unable to remove firewall rule id=" + lb.getId() + " as it has related firewall rule id=" + relatedRule.getId() + "; leaving it in Revoke state");
        return false;
    } else {
        _firewallMgr.removeRule(lb);
    }
    s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully");
    return true;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) LBHealthCheckPolicyVO(com.cloud.network.LBHealthCheckPolicyVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) List(java.util.List) FirewallRule(com.cloud.network.rules.FirewallRule) DB(com.cloud.utils.db.DB)

Example 22 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method getExistingDestinations.

@Override
public List<LbDestination> getExistingDestinations(final long lbId) {
    final List<LbDestination> dstList = new ArrayList<>();
    final List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lbId);
    final LoadBalancerVO lb = _lbDao.findById(lbId);
    String dstIp = null;
    for (final LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
        final UserVm vm = _vmDao.findById(lbVmMap.getInstanceId());
        final Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(lb.getNetworkId(), vm.getId());
        dstIp = lbVmMap.getInstanceIp() == null ? nic.getIPv4Address() : lbVmMap.getInstanceIp();
        final LbDestination lbDst = new LbDestination(lb.getDefaultPortStart(), lb.getDefaultPortEnd(), dstIp, lbVmMap.isRevoke());
        dstList.add(lbDst);
    }
    return dstList;
}
Also used : UserVm(com.cloud.uservm.UserVm) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) Nic(com.cloud.vm.Nic) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination)

Example 23 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method applyLoadBalancerRules.

@DB
protected boolean applyLoadBalancerRules(final List<LoadBalancerVO> lbs, final boolean updateRulesInDB) throws ResourceUnavailableException {
    final List<LoadBalancingRule> rules = new ArrayList<>();
    for (final LoadBalancerVO lb : lbs) {
        rules.add(getLoadBalancerRuleToApply(lb));
    }
    if (!applyLbRules(rules, false)) {
        s_logger.debug("LB rules are not completely applied");
        return false;
    }
    if (updateRulesInDB) {
        for (final LoadBalancerVO lb : lbs) {
            final boolean checkForReleaseElasticIp = Transaction.execute(new TransactionCallback<Boolean>() {

                @Override
                public Boolean doInTransaction(final TransactionStatus status) {
                    boolean checkForReleaseElasticIp = false;
                    if (lb.getState() == FirewallRule.State.Revoke) {
                        removeLBRule(lb);
                        s_logger.debug("LB " + lb.getId() + " is successfully removed");
                        checkForReleaseElasticIp = true;
                    } else if (lb.getState() == FirewallRule.State.Add) {
                        lb.setState(FirewallRule.State.Active);
                        s_logger.debug("LB rule " + lb.getId() + " state is set to Active");
                        _lbDao.persist(lb);
                    }
                    // remove LB-Vm mappings that were state to revoke
                    final List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true);
                    final List<Long> instanceIds = new ArrayList<>();
                    for (final LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
                        instanceIds.add(lbVmMap.getInstanceId());
                        _lb2VmMapDao.remove(lb.getId(), lbVmMap.getInstanceId(), lbVmMap.getInstanceIp(), null);
                        s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vm " + lbVmMap.getInstanceId() + " instance ip " + lbVmMap.getInstanceIp());
                    }
                    if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) {
                        lb.setState(FirewallRule.State.Add);
                        _lbDao.persist(lb);
                        s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings");
                    }
                    // remove LB-Stickiness policy mapping that were state to revoke
                    final List<LBStickinessPolicyVO> stickinesspolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lb.getId(), true);
                    if (!stickinesspolicies.isEmpty()) {
                        _lb2stickinesspoliciesDao.remove(lb.getId(), true);
                        s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies");
                    }
                    // remove LB-HealthCheck policy mapping that were state to
                    // revoke
                    final List<LBHealthCheckPolicyVO> healthCheckpolicies = _lb2healthcheckDao.listByLoadBalancerId(lb.getId(), true);
                    if (!healthCheckpolicies.isEmpty()) {
                        _lb2healthcheckDao.remove(lb.getId(), true);
                        s_logger.debug("Load balancer rule id " + lb.getId() + " is removed health check monitors policies");
                    }
                    final LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(lb.getId());
                    if (lbCertMap != null && lbCertMap.isRevoke()) {
                        _lbCertMapDao.remove(lbCertMap.getId());
                        s_logger.debug("Load balancer rule id " + lb.getId() + " removed certificate mapping");
                    }
                    return checkForReleaseElasticIp;
                }
            });
            if (checkForReleaseElasticIp && lb.getSourceIpAddressId() != null) {
                boolean success = true;
                final long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());
                if (count == 0) {
                    try {
                        success = handleSystemLBIpRelease(lb);
                    } catch (final Exception ex) {
                        s_logger.warn("Failed to release system ip as a part of lb rule " + lb + " deletion due to exception ", ex);
                        success = false;
                    } finally {
                        if (!success) {
                            s_logger.warn("Failed to release system ip as a part of lb rule " + lb + " deletion");
                        }
                    }
                }
            }
            // VPC, unassign it from the network
            if (lb.getSourceIpAddressId() != null) {
                final IpAddress ip = _ipAddressDao.findById(lb.getSourceIpAddressId());
                _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), lb.getNetworkId());
            }
        }
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) IpAddress(com.cloud.network.IpAddress) DB(com.cloud.utils.db.DB)

Example 24 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method moveVMToUser.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false)
public UserVm moveVMToUser(final AssignVMCmd cmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    // VERIFICATIONS and VALIDATIONS
    // VV 1: verify the two users
    final Account caller = CallContext.current().getCallingAccount();
    if (!_accountMgr.isRootAdmin(caller.getId()) && !_accountMgr.isDomainAdmin(caller.getId())) {
        // VMs
        throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType());
    }
    // get and check the valid VM
    final UserVmVO vm = _vmDao.findById(cmd.getVmId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm by that id " + cmd.getVmId());
    } else if (vm.getState() == State.Running) {
        // running
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is Running, unable to move the vm " + vm);
        }
        final InvalidParameterValueException ex = new InvalidParameterValueException("VM is Running, unable to move the vm with specified vmId");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    final Account oldAccount = _accountService.getActiveAccountById(vm.getAccountId());
    if (oldAccount == null) {
        throw new InvalidParameterValueException("Invalid account for VM " + vm.getAccountId() + " in domain.");
    }
    // don't allow to move the vm from the project
    if (oldAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Specified Vm id belongs to the project and can't be moved");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    final Account newAccount = _accountService.getActiveAccountByName(cmd.getAccountName(), cmd.getDomainId());
    if (newAccount == null || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId());
    }
    if (newAccount.getState() == Account.State.disabled) {
        throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled.");
    }
    // check caller has access to both the old and new account
    _accountMgr.checkAccess(caller, null, true, oldAccount);
    _accountMgr.checkAccess(caller, null, true, newAccount);
    // make sure the accounts are not same
    if (oldAccount.getAccountId() == newAccount.getAccountId()) {
        throw new InvalidParameterValueException("The new account is the same as the old account. Account id =" + oldAccount.getAccountId());
    }
    // don't allow to move the vm if there are existing PF/LB/Static Nat
    // rules, or vm is assigned to static Nat ip
    final List<PortForwardingRuleVO> pfrules = _portForwardingDao.listByVm(cmd.getVmId());
    if (pfrules != null && pfrules.size() > 0) {
        throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user.");
    }
    final List<FirewallRuleVO> snrules = _rulesDao.listStaticNatByVmId(vm.getId());
    if (snrules != null && snrules.size() > 0) {
        throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user.");
    }
    final List<LoadBalancerVMMapVO> maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId());
    if (maps != null && maps.size() > 0) {
        throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user.");
    }
    // check for one on one nat
    final List<IPAddressVO> ips = _ipAddressDao.findAllByAssociatedVmId(cmd.getVmId());
    for (final IPAddressVO ip : ips) {
        if (ip.isOneToOneNat()) {
            throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString());
        }
    }
    final Zone zone = zoneRepository.findOne(vm.getDataCenterId());
    // Get serviceOffering and Volumes for Virtual Machine
    final ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
    final List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
    // Remove vm from instance group
    removeInstanceFromInstanceGroup(cmd.getVmId());
    // VV 2: check if account/domain is with in resource limits to create a new vm
    resourceLimitCheck(newAccount, vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
    // VV 3: check if volumes and primary storage space are with in resource limits
    _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, _volsDao.findByInstance(cmd.getVmId()).size());
    Long totalVolumesSize = (long) 0;
    for (final VolumeVO volume : volumes) {
        totalVolumesSize += volume.getSize();
    }
    _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.primary_storage, totalVolumesSize);
    // VV 4: Check if new owner can use the vm template
    final VirtualMachineTemplate template = _templateDao.findById(vm.getTemplateId());
    if (!template.isPublicTemplate()) {
        final Account templateOwner = _accountMgr.getAccount(template.getAccountId());
        _accountMgr.checkAccess(newAccount, null, true, templateOwner);
    }
    // VV 5: check the new account can create vm in the domain
    final DomainVO domain = _domainDao.findById(cmd.getDomainId());
    _accountMgr.checkAccess(newAccount, domain);
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            // update resource counts for old account
            resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
            // OWNERSHIP STEP 1: update the vm owner
            vm.setAccountId(newAccount.getAccountId());
            vm.setDomainId(cmd.getDomainId());
            _vmDao.persist(vm);
            // OS 2: update volume
            for (final VolumeVO volume : volumes) {
                _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
                _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
                volume.setAccountId(newAccount.getAccountId());
                volume.setDomainId(newAccount.getDomainId());
                _volsDao.persist(volume);
                _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
                _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
                // snapshots: mark these removed in db
                final List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
                for (final SnapshotVO snapshot : snapshots) {
                    _snapshotDao.remove(snapshot.getId());
                }
            }
            // update resource count of new account
            resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
        }
    });
    final VirtualMachine vmoi = _itMgr.findById(vm.getId());
    final VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);
    // OS 3: update the network
    final List<Long> networkIdList = cmd.getNetworkIds();
    if (zone.getNetworkType() == NetworkType.Basic) {
        if (networkIdList != null && !networkIdList.isEmpty()) {
            throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM");
        }
        // cleanup the network for the oldOwner
        _networkMgr.cleanupNics(vmOldProfile);
        _networkMgr.expungeNics(vmOldProfile);
        // security groups will be recreated for the new account, when the
        // VM is started
        final List<NetworkVO> networkList = new ArrayList<>();
        // Get default guest network in Basic zone
        final Network defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId());
        if (defaultNetwork == null) {
            throw new InvalidParameterValueException("Unable to find a default network to start a vm");
        } else {
            networkList.add(_networkDao.findById(defaultNetwork.getId()));
        }
        final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>();
        final NicProfile profile = new NicProfile();
        profile.setDefaultNic(true);
        networks.put(networkList.get(0), new ArrayList<>(Arrays.asList(profile)));
        final VirtualMachine vmi = _itMgr.findById(vm.getId());
        final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
        _networkMgr.allocate(vmProfile, networks);
    } else {
        // cleanup the network for the oldOwner
        _networkMgr.cleanupNics(vmOldProfile);
        _networkMgr.expungeNics(vmOldProfile);
        final Set<NetworkVO> applicableNetworks = new HashSet<>();
        if (networkIdList != null && !networkIdList.isEmpty()) {
            // add any additional networks
            for (final Long networkId : networkIdList) {
                final NetworkVO network = _networkDao.findById(networkId);
                if (network == null) {
                    final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
                    ex.addProxyObject(networkId.toString(), "networkId");
                    throw ex;
                }
                _networkModel.checkNetworkPermissions(newAccount, network);
                // don't allow to use system networks
                final NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
                if (networkOffering.isSystemOnly()) {
                    final InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
                    ex.addProxyObject(network.getUuid(), "networkId");
                    throw ex;
                }
                applicableNetworks.add(network);
            }
        } else {
            final NetworkVO defaultNetwork;
            final List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
            if (requiredOfferings.size() < 1) {
                throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation");
            }
            if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
                // get Virtual networks
                final List<? extends Network> virtualNetworks = _networkModel.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated);
                if (virtualNetworks.isEmpty()) {
                    final long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
                    // Validate physical network
                    final PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
                    if (physicalNetwork == null) {
                        throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + requiredOfferings.get(0).getTags());
                    }
                    s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process");
                    Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null, null, null, null);
                    // if the network offering has persistent set to true, implement the network
                    if (requiredOfferings.get(0).getIsPersistent()) {
                        final DeployDestination dest = new DeployDestination(zone, null, null, null);
                        final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
                        final Journal journal = new Journal.LogJournal("Implementing " + newNetwork, s_logger);
                        final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
                        s_logger.debug("Implementing the network for account" + newNetwork + " as a part of" + " network provision for persistent networks");
                        try {
                            final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(newNetwork.getId(), dest, context);
                            if (implementedNetwork == null || implementedNetwork.first() == null) {
                                s_logger.warn("Failed to implement the network " + newNetwork);
                            }
                            newNetwork = implementedNetwork.second();
                        } catch (final Exception ex) {
                            s_logger.warn("Failed to implement network " + newNetwork + " elements and" + " resources as a part of network provision for persistent network due to ", ex);
                            final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network" + " (with specified id) elements and resources as a part of network provision");
                            e.addProxyObject(newNetwork.getUuid(), "networkId");
                            throw e;
                        }
                    }
                    defaultNetwork = _networkDao.findById(newNetwork.getId());
                } else if (virtualNetworks.size() > 1) {
                    throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + "; please specify networkIds");
                } else {
                    defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
                }
            } else {
                throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
            }
            applicableNetworks.add(defaultNetwork);
        }
        // add the new nics
        final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>();
        int toggle = 0;
        for (final NetworkVO appNet : applicableNetworks) {
            final NicProfile defaultNic = new NicProfile();
            if (toggle == 0) {
                defaultNic.setDefaultNic(true);
                toggle++;
            }
            networks.put(appNet, new ArrayList<>(Arrays.asList(defaultNic)));
        }
        final VirtualMachine vmi = _itMgr.findById(vm.getId());
        final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
        _networkMgr.allocate(vmProfile, networks);
        s_logger.debug("AssignVM: Advance virtual, adding networks no " + networks.size() + " to " + vm.getInstanceName());
    }
    // END IF ADVANCED
    s_logger.info("AssignVM: vm " + vm.getInstanceName() + " now belongs to account " + cmd.getAccountName());
    return vm;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) Journal(com.cloud.utils.Journal) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) LinkedHashMap(java.util.LinkedHashMap) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) HashSet(java.util.HashSet) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) NetworkVO(com.cloud.network.dao.NetworkVO) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) DomainVO(com.cloud.domain.DomainVO) DeployDestination(com.cloud.deploy.DeployDestination) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkOffering(com.cloud.offering.NetworkOffering) Zone(com.cloud.db.model.Zone) 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) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) UserVO(com.cloud.user.UserVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 25 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cosmic by MissionCriticalCloud.

the class AssignLoadBalancerTest method testVmIdAlreadyExist.

@Test(expected = InvalidParameterValueException.class)
public void testVmIdAlreadyExist() throws ResourceAllocationException, ResourceUnavailableException, InsufficientCapacityException {
    final AssignToLoadBalancerRuleCmd assignLbRuleCmd = Mockito.mock(AssignToLoadBalancerRuleCmd.class);
    final Map<Long, List<String>> vmIdIpMap = new HashMap<>();
    final List<String> secIp = new ArrayList<>();
    secIp.add("10.1.1.175");
    vmIdIpMap.put(1L, secIp);
    final List<Long> vmIds = new ArrayList<>();
    vmIds.add(2L);
    final LoadBalancerVO lbVO = new LoadBalancerVO("1", "L1", "Lbrule", 1, 22, 22, "rb", 204, 0, 0, "tcp", 60000, 60000);
    final LoadBalancerDao lbDao = Mockito.mock(LoadBalancerDao.class);
    final LoadBalancerVMMapDao lb2VmMapDao = Mockito.mock(LoadBalancerVMMapDao.class);
    final UserVmDao userVmDao = Mockito.mock(UserVmDao.class);
    final NicSecondaryIpDao nicSecIpDao = Mockito.mock(NicSecondaryIpDao.class);
    final LoadBalancerVMMapVO lbVmMapVO = new LoadBalancerVMMapVO(1L, 1L, "10.1.1.175", false);
    _lbMgr._lbDao = lbDao;
    _lbMgr._lb2VmMapDao = lb2VmMapDao;
    _lbMgr._vmDao = userVmDao;
    _lbMgr._nicSecondaryIpDao = nicSecIpDao;
    _lbvmMapList = new ArrayList<>();
    _lbvmMapList.add(lbVmMapVO);
    _lbMgr._rulesMgr = _rulesMgr;
    _lbMgr._networkModel = _networkModel;
    when(lbDao.findById(anyLong())).thenReturn(lbVO);
    when(userVmDao.findById(anyLong())).thenReturn(Mockito.mock(UserVmVO.class));
    when(lb2VmMapDao.listByLoadBalancerId(anyLong(), anyBoolean())).thenReturn(_lbvmMapList);
    when(nicSecIpDao.findByIp4AddressAndNicId(anyString(), anyLong())).thenReturn(null);
    _lbMgr.assignToLoadBalancer(1L, null, vmIdIpMap);
}
Also used : LoadBalancerDao(com.cloud.network.dao.LoadBalancerDao) UserVmVO(com.cloud.vm.UserVmVO) NicSecondaryIpDao(com.cloud.vm.dao.NicSecondaryIpDao) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) Matchers.anyString(org.mockito.Matchers.anyString) AssignToLoadBalancerRuleCmd(com.cloud.api.command.user.loadbalancer.AssignToLoadBalancerRuleCmd) Matchers.anyLong(org.mockito.Matchers.anyLong) LoadBalancerVMMapDao(com.cloud.network.dao.LoadBalancerVMMapDao) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) UserVmDao(com.cloud.vm.dao.UserVmDao) Test(org.junit.Test)

Aggregations

LoadBalancerVMMapVO (com.cloud.network.dao.LoadBalancerVMMapVO)34 ArrayList (java.util.ArrayList)28 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)23 List (java.util.List)18 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)14 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)12 DB (com.cloud.utils.db.DB)12 HashMap (java.util.HashMap)11 TransactionStatus (com.cloud.utils.db.TransactionStatus)10 FirewallRule (com.cloud.network.rules.FirewallRule)8 Account (com.cloud.user.Account)8 UserVm (com.cloud.uservm.UserVm)8 Nic (com.cloud.vm.Nic)8 ActionEvent (com.cloud.event.ActionEvent)6 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)6 NetworkVO (com.cloud.network.dao.NetworkVO)6 FirewallRuleVO (com.cloud.network.rules.FirewallRuleVO)6 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)6 Network (com.cloud.network.Network)5 Pair (com.cloud.utils.Pair)5