Search in sources :

Example 91 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class XenServer610MigrateWithStorageReceiveCommandWrapper method execute.

@Override
public Answer execute(final MigrateWithStorageReceiveCommand command, final XenServer610Resource xenServer610Resource) {
    final Connection connection = xenServer610Resource.getConnection();
    final VirtualMachineTO vmSpec = command.getVirtualMachine();
    final List<Pair<VolumeTO, StorageFilerTO>> volumeToFiler = command.getVolumeToFiler();
    try {
        // In a cluster management server setup, the migrate with storage receive and send
        // commands and answers may have to be forwarded to another management server. This
        // happens when the host/resource on which the command has to be executed is owned
        // by the second management server. The serialization/deserialization of the command
        // and answers fails as the xapi SR and Network class type isn't understand by the
        // agent attache. Seriliaze the SR and Network objects here to a string and pass in
        // the answer object. It'll be deserialzed and object created in migrate with
        // storage send command execution.
        final Gson gson = new Gson();
        // Get a map of all the SRs to which the vdis will be migrated.
        final List<Pair<VolumeTO, Object>> volumeToSr = new ArrayList<>();
        for (final Pair<VolumeTO, StorageFilerTO> entry : volumeToFiler) {
            final StorageFilerTO storageFiler = entry.second();
            final SR sr = xenServer610Resource.getStorageRepository(connection, storageFiler.getUuid());
            volumeToSr.add(new Pair<>(entry.first(), sr));
        }
        // Get the list of networks to which the vifs will attach.
        final List<Pair<NicTO, Object>> nicToNetwork = new ArrayList<>();
        for (final NicTO nicTo : vmSpec.getNics()) {
            final Network network = xenServer610Resource.getNetwork(connection, nicTo);
            nicToNetwork.add(new Pair<>(nicTo, network));
        }
        final XsLocalNetwork nativeNetworkForTraffic = xenServer610Resource.getNativeNetworkForTraffic(connection, TrafficType.Storage, null);
        final Network network = nativeNetworkForTraffic.getNetwork();
        final XsHost xsHost = xenServer610Resource.getHost();
        final String uuid = xsHost.getUuid();
        final Map<String, String> other = new HashMap<>();
        other.put("live", "true");
        final Host host = Host.getByUuid(connection, uuid);
        final Map<String, String> token = host.migrateReceive(connection, network, other);
        return new MigrateWithStorageReceiveAnswer(command, volumeToSr, nicToNetwork, token);
    } catch (final CloudRuntimeException e) {
        s_logger.error("Migration of vm " + vmSpec.getName() + " with storage failed due to " + e.toString(), e);
        return new MigrateWithStorageReceiveAnswer(command, e);
    } catch (final Exception e) {
        s_logger.error("Migration of vm " + vmSpec.getName() + " with storage failed due to " + e.toString(), e);
        return new MigrateWithStorageReceiveAnswer(command, e);
    }
}
Also used : XsHost(com.cloud.hypervisor.xenserver.resource.XsHost) HashMap(java.util.HashMap) Connection(com.xensource.xenapi.Connection) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) Host(com.xensource.xenapi.Host) XsHost(com.cloud.hypervisor.xenserver.resource.XsHost) StorageFilerTO(com.cloud.legacymodel.to.StorageFilerTO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VolumeTO(com.cloud.legacymodel.to.VolumeTO) MigrateWithStorageReceiveAnswer(com.cloud.legacymodel.communication.answer.MigrateWithStorageReceiveAnswer) XsLocalNetwork(com.cloud.hypervisor.xenserver.resource.XsLocalNetwork) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.xensource.xenapi.Network) XsLocalNetwork(com.cloud.hypervisor.xenserver.resource.XsLocalNetwork) Pair(com.cloud.legacymodel.utils.Pair) SR(com.xensource.xenapi.SR) NicTO(com.cloud.legacymodel.to.NicTO)

Example 92 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class XenServerGuru method getCommandHostDelegation.

@Override
public Pair<Boolean, Long> getCommandHostDelegation(final long hostId, final Command cmd) {
    LOGGER.debug("getCommandHostDelegation: " + cmd.getClass());
    if (cmd instanceof StorageSubSystemCommand) {
        final StorageSubSystemCommand c = (StorageSubSystemCommand) cmd;
        c.setExecuteInSequence(true);
    }
    if (cmd instanceof CopyCommand) {
        final CopyCommand cpyCommand = (CopyCommand) cmd;
        final DataTO srcData = cpyCommand.getSrcTO();
        final DataTO destData = cpyCommand.getDestTO();
        if (srcData.getHypervisorType() == HypervisorType.XenServer && srcData.getObjectType() == DataObjectType.SNAPSHOT && destData.getObjectType() == DataObjectType.TEMPLATE) {
            final DataStoreTO srcStore = srcData.getDataStore();
            final DataStoreTO destStore = destData.getDataStore();
            if (srcStore instanceof NfsTO && destStore instanceof NfsTO) {
                HostVO host = hostDao.findById(hostId);
                final EndPoint ep = endPointSelector.selectHypervisorHost(new ZoneScope(host.getDataCenterId()));
                host = hostDao.findById(ep.getId());
                hostDao.loadDetails(host);
                final String hypervisorVersion = host.getHypervisorVersion();
                final String snapshotHotFixVersion = host.getDetail(XenserverConfigs.XS620HotFix);
                if (hypervisorVersion != null && !hypervisorVersion.equalsIgnoreCase("6.1.0")) {
                    if (!(hypervisorVersion.equalsIgnoreCase("6.2.0") && !(snapshotHotFixVersion != null && snapshotHotFixVersion.equalsIgnoreCase(XenserverConfigs.XSHotFix62ESP1004)))) {
                        return new Pair<>(Boolean.TRUE, new Long(ep.getId()));
                    }
                }
            }
        }
    }
    return new Pair<>(Boolean.FALSE, new Long(hostId));
}
Also used : ZoneScope(com.cloud.engine.subsystem.api.storage.ZoneScope) DataStoreTO(com.cloud.legacymodel.to.DataStoreTO) StorageSubSystemCommand(com.cloud.legacymodel.communication.command.StorageSubSystemCommand) DataTO(com.cloud.legacymodel.to.DataTO) CopyCommand(com.cloud.legacymodel.communication.command.CopyCommand) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) NfsTO(com.cloud.legacymodel.to.NfsTO) HostVO(com.cloud.host.HostVO) Pair(com.cloud.legacymodel.utils.Pair)

Example 93 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method searchForNetworks.

@Override
public Pair<List<? extends Network>, Integer> searchForNetworks(final ListNetworksCmd cmd) {
    final Long id = cmd.getId();
    final String keyword = cmd.getKeyword();
    final Long zoneId = cmd.getZoneId();
    final Account caller = CallContext.current().getCallingAccount();
    Long domainId = cmd.getDomainId();
    final String accountName = cmd.getAccountName();
    final String guestIpType = cmd.getGuestIpType();
    final String trafficType = cmd.getTrafficType();
    Boolean isSystem = cmd.getIsSystem();
    final String aclType = cmd.getAclType();
    final Long projectId = cmd.getProjectId();
    final List<Long> permittedAccounts = new ArrayList<>();
    String path = null;
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    final List<String> supportedServicesStr = cmd.getSupportedServices();
    final Boolean restartRequired = cmd.getRestartRequired();
    final boolean listAll = cmd.listAll();
    boolean isRecursive = cmd.isRecursive();
    final Boolean specifyIpRanges = cmd.getSpecifyIpRanges();
    final Long vpcId = cmd.getVpcId();
    final Boolean canUseForDeploy = cmd.canUseForDeploy();
    final Map<String, String> tags = cmd.getTags();
    final Boolean forVpc = cmd.getForVpc();
    final Boolean display = cmd.getDisplay();
    // 2) reset parameter to false if it's specified by the regular user
    if ((isSystem == null || _accountMgr.isNormalUser(caller.getId())) && id == null) {
        isSystem = false;
    }
    // Account/domainId parameters and isSystem are mutually exclusive
    if (isSystem != null && isSystem && (accountName != null || domainId != null)) {
        throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified");
    }
    if (domainId != null) {
        final DomainVO domain = _domainDao.findById(domainId);
        if (domain == null) {
            // see DomainVO.java
            throw new InvalidParameterValueException("Specified domain id doesn't exist in the system");
        }
        _accountMgr.checkAccess(caller, domain);
        if (accountName != null) {
            final Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
            if (owner == null) {
                // see DomainVO.java
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");
            }
            _accountMgr.checkAccess(caller, null, true, owner);
            permittedAccounts.add(owner.getId());
        }
    }
    if (!_accountMgr.isAdmin(caller.getId()) || projectId != null && projectId.longValue() != -1 && domainId == null) {
        permittedAccounts.add(caller.getId());
        domainId = caller.getDomainId();
    }
    // set project information
    boolean skipProjectNetworks = true;
    if (projectId != null) {
        if (projectId.longValue() == -1) {
            if (!_accountMgr.isAdmin(caller.getId())) {
                permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
            }
        } else {
            permittedAccounts.clear();
            final Project project = _projectMgr.getProject(projectId);
            if (project == null) {
                throw new InvalidParameterValueException("Unable to find project by specified id");
            }
            if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
                // getProject() returns type ProjectVO.
                final InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id");
                ex.addProxyObject(project.getUuid(), "projectId");
                throw ex;
            }
            // add project account
            permittedAccounts.add(project.getProjectAccountId());
            // add caller account (if admin)
            if (_accountMgr.isAdmin(caller.getId())) {
                permittedAccounts.add(caller.getId());
            }
        }
        skipProjectNetworks = false;
    }
    if (domainId != null) {
        path = _domainDao.findById(domainId).getPath();
    } else {
        path = _domainDao.findById(caller.getDomainId()).getPath();
    }
    if (listAll && domainId == null) {
        isRecursive = true;
    }
    final Filter searchFilter = new Filter(NetworkVO.class, "id", false, null, null);
    final SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
    if (forVpc != null) {
        if (forVpc) {
            sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
        } else {
            sb.and("vpc", sb.entity().getVpcId(), Op.NULL);
        }
    }
    // Don't display networks created of system network offerings
    final SearchBuilder<NetworkOfferingVO> networkOfferingSearch = _networkOfferingDao.createSearchBuilder();
    networkOfferingSearch.and("systemOnly", networkOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
    if (isSystem != null && isSystem) {
        networkOfferingSearch.and("trafficType", networkOfferingSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
    }
    sb.join("networkOfferingSearch", networkOfferingSearch, sb.entity().getNetworkOfferingId(), networkOfferingSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    final SearchBuilder<DataCenterVO> zoneSearch = _dcDao.createSearchBuilder();
    zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ);
    sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    sb.and("removed", sb.entity().getRemoved(), Op.NULL);
    if (tags != null && !tags.isEmpty()) {
        final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    if (permittedAccounts.isEmpty()) {
        final SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
        domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
        sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    }
    final SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
    accountSearch.and("typeNEQ", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
    accountSearch.and("typeEQ", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
    sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    List<NetworkVO> networksToReturn = new ArrayList<>();
    if (isSystem == null || !isSystem) {
        if (!permittedAccounts.isEmpty()) {
            // get account level networks
            networksToReturn.addAll(listAccountSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, permittedAccounts));
            // get domain level networks
            if (domainId != null) {
                networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, domainId, false));
            }
        } else {
            // add account specific networks
            networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
            // add domain specific networks of domain + parent domains
            networksToReturn.addAll(listDomainSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
            // add networks of subdomains
            if (domainId == null) {
                networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, caller.getDomainId(), true));
            }
        }
    } else {
        networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter);
    }
    if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) {
        final List<NetworkVO> supportedNetworks = new ArrayList<>();
        final Service[] suppportedServices = new Service[supportedServicesStr.size()];
        int i = 0;
        for (final String supportedServiceStr : supportedServicesStr) {
            final Service service = Service.getService(supportedServiceStr);
            if (service == null) {
                throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
            } else {
                suppportedServices[i] = service;
            }
            i++;
        }
        for (final NetworkVO network : networksToReturn) {
            if (areServicesSupportedInNetwork(network.getId(), suppportedServices)) {
                supportedNetworks.add(network);
            }
        }
        networksToReturn = supportedNetworks;
    }
    if (canUseForDeploy != null) {
        final List<NetworkVO> networksForDeploy = new ArrayList<>();
        for (final NetworkVO network : networksToReturn) {
            if (_networkModel.canUseForDeploy(network) == canUseForDeploy) {
                networksForDeploy.add(network);
            }
        }
        networksToReturn = networksForDeploy;
    }
    // Now apply pagination
    final List<? extends Network> wPagination = StringUtils.applyPagination(networksToReturn, cmd.getStartIndex(), cmd.getPageSizeVal());
    if (wPagination != null) {
        final Pair<List<? extends Network>, Integer> listWPagination = new Pair<>(wPagination, networksToReturn.size());
        return listWPagination;
    }
    return new Pair<>(networksToReturn, networksToReturn.size());
}
Also used : Account(com.cloud.legacymodel.user.Account) ArrayList(java.util.ArrayList) AccountVO(com.cloud.user.AccountVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Network(com.cloud.legacymodel.network.Network) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.legacymodel.utils.Pair) DataCenterVO(com.cloud.dc.DataCenterVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) LoadBalancingRulesService(com.cloud.network.lb.LoadBalancingRulesService) Service(com.cloud.legacymodel.network.Network.Service) ResourceLimitService(com.cloud.user.ResourceLimitService) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) DomainVO(com.cloud.domain.DomainVO) Project(com.cloud.projects.Project) Filter(com.cloud.utils.db.Filter) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO)

Example 94 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method listNetworkServiceProviders.

@Override
public Pair<List<? extends PhysicalNetworkServiceProvider>, Integer> listNetworkServiceProviders(final Long physicalNetworkId, final String name, final String state, final Long startIndex, final Long pageSize) {
    final Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize);
    final SearchBuilder<PhysicalNetworkServiceProviderVO> sb = _pNSPDao.createSearchBuilder();
    final SearchCriteria<PhysicalNetworkServiceProviderVO> sc = sb.create();
    if (physicalNetworkId != null) {
        sc.addAnd("physicalNetworkId", Op.EQ, physicalNetworkId);
    }
    if (name != null) {
        sc.addAnd("providerName", Op.EQ, name);
    }
    if (state != null) {
        sc.addAnd("state", Op.EQ, state);
    }
    final Pair<List<PhysicalNetworkServiceProviderVO>, Integer> result = _pNSPDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Filter(com.cloud.utils.db.Filter) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.legacymodel.utils.Pair)

Example 95 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method dedicateGuestVlanRange.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_GUEST_VLAN_RANGE_DEDICATE, eventDescription = "dedicating guest vlan range", async = false)
public GuestVlan dedicateGuestVlanRange(final DedicateGuestVlanRangeCmd cmd) {
    final String vlan = cmd.getVlan();
    final String accountName = cmd.getAccountName();
    final Long domainId = cmd.getDomainId();
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    final Long projectId = cmd.getProjectId();
    final int startVlan;
    final int endVlan;
    String updatedVlanRange = null;
    long guestVlanMapId = 0;
    long guestVlanMapAccountId = 0;
    long vlanOwnerId = 0;
    // Verify account is valid
    Account vlanOwner = null;
    if (projectId != null) {
        if (accountName != null) {
            throw new InvalidParameterValueException("accountName and projectId are mutually exclusive");
        }
        final Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            throw new InvalidParameterValueException("Unable to find project by id " + projectId);
        }
        vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
    }
    if (accountName != null && domainId != null) {
        vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
    }
    if (vlanOwner == null) {
        throw new InvalidParameterValueException("Unable to find account by name " + accountName);
    }
    vlanOwnerId = vlanOwner.getAccountId();
    // Verify physical network isolation type is VLAN
    final PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Unable to find physical network by id " + physicalNetworkId);
    } else if (!physicalNetwork.getIsolationMethods().isEmpty() && !physicalNetwork.getIsolationMethods().contains("VLAN")) {
        throw new InvalidParameterValueException("Cannot dedicate guest vlan range. " + "Physical isolation type of network " + physicalNetworkId + " is not VLAN");
    }
    // Get the start and end vlan
    final String[] vlanRange = vlan.split("-");
    if (vlanRange.length != 2) {
        throw new InvalidParameterValueException("Invalid format for parameter value vlan " + vlan + " .Vlan should be specified as 'startvlan-endvlan'");
    }
    try {
        startVlan = Integer.parseInt(vlanRange[0]);
        endVlan = Integer.parseInt(vlanRange[1]);
    } catch (final NumberFormatException e) {
        s_logger.warn("Unable to parse guest vlan range:", e);
        throw new InvalidParameterValueException("Please provide valid guest vlan range");
    }
    // Verify guest vlan range exists in the system
    final List<Pair<Integer, Integer>> existingRanges = physicalNetwork.getVnet();
    Boolean exists = false;
    if (!existingRanges.isEmpty()) {
        for (int i = 0; i < existingRanges.size(); i++) {
            final int existingStartVlan = existingRanges.get(i).first();
            final int existingEndVlan = existingRanges.get(i).second();
            if (startVlan <= endVlan && startVlan >= existingStartVlan && endVlan <= existingEndVlan) {
                exists = true;
                break;
            }
        }
        if (!exists) {
            throw new InvalidParameterValueException("Unable to find guest vlan by range " + vlan);
        }
    }
    // Verify guest vlans in the range don't belong to a network of a different account
    for (int i = startVlan; i <= endVlan; i++) {
        final List<DataCenterVnetVO> allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
        if (allocatedVlans != null && !allocatedVlans.isEmpty()) {
            for (final DataCenterVnetVO allocatedVlan : allocatedVlans) {
                if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) {
                    throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account." + " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account ");
                }
            }
        }
    }
    final List<AccountGuestVlanMapVO> guestVlanMaps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(physicalNetworkId);
    // Verify if vlan range is already dedicated
    for (final AccountGuestVlanMapVO guestVlanMap : guestVlanMaps) {
        final List<Integer> vlanTokens = getVlanFromRange(guestVlanMap.getGuestVlanRange());
        final int dedicatedStartVlan = vlanTokens.get(0).intValue();
        final int dedicatedEndVlan = vlanTokens.get(1).intValue();
        if (startVlan < dedicatedStartVlan & endVlan >= dedicatedStartVlan || startVlan >= dedicatedStartVlan & startVlan <= dedicatedEndVlan) {
            throw new InvalidParameterValueException("Vlan range is already dedicated. Cannot" + " dedicate guest vlan range " + vlan);
        }
    }
    // Sort the existing dedicated vlan ranges
    Collections.sort(guestVlanMaps, new Comparator<AccountGuestVlanMapVO>() {

        @Override
        public int compare(final AccountGuestVlanMapVO obj1, final AccountGuestVlanMapVO obj2) {
            final List<Integer> vlanTokens1 = getVlanFromRange(obj1.getGuestVlanRange());
            final List<Integer> vlanTokens2 = getVlanFromRange(obj2.getGuestVlanRange());
            return vlanTokens1.get(0).compareTo(vlanTokens2.get(0));
        }
    });
    // Verify if vlan range extends an already dedicated range
    for (int i = 0; i < guestVlanMaps.size(); i++) {
        guestVlanMapId = guestVlanMaps.get(i).getId();
        guestVlanMapAccountId = guestVlanMaps.get(i).getAccountId();
        final List<Integer> vlanTokens1 = getVlanFromRange(guestVlanMaps.get(i).getGuestVlanRange());
        // Range extends a dedicated vlan range to the left
        if (endVlan == vlanTokens1.get(0).intValue() - 1) {
            if (guestVlanMapAccountId == vlanOwnerId) {
                updatedVlanRange = startVlan + "-" + vlanTokens1.get(1).intValue();
            }
            break;
        }
        // Range extends a dedicated vlan range to the right
        if (startVlan == vlanTokens1.get(1).intValue() + 1 & guestVlanMapAccountId == vlanOwnerId) {
            if (i != guestVlanMaps.size() - 1) {
                final List<Integer> vlanTokens2 = getVlanFromRange(guestVlanMaps.get(i + 1).getGuestVlanRange());
                // Range extends 2 vlan ranges, both to the right and left
                if (endVlan == vlanTokens2.get(0).intValue() - 1 && guestVlanMaps.get(i + 1).getAccountId() == vlanOwnerId) {
                    _datacneterVnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i + 1).getId());
                    _accountGuestVlanMapDao.remove(guestVlanMaps.get(i + 1).getId());
                    updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + vlanTokens2.get(1).intValue();
                    break;
                }
            }
            updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + endVlan;
            break;
        }
    }
    // Dedicate vlan range
    final AccountGuestVlanMapVO accountGuestVlanMapVO;
    if (updatedVlanRange != null) {
        accountGuestVlanMapVO = _accountGuestVlanMapDao.findById(guestVlanMapId);
        accountGuestVlanMapVO.setGuestVlanRange(updatedVlanRange);
        _accountGuestVlanMapDao.update(guestVlanMapId, accountGuestVlanMapVO);
    } else {
        accountGuestVlanMapVO = new AccountGuestVlanMapVO(vlanOwner.getAccountId(), physicalNetworkId);
        accountGuestVlanMapVO.setGuestVlanRange(startVlan + "-" + endVlan);
        _accountGuestVlanMapDao.persist(accountGuestVlanMapVO);
    }
    // For every guest vlan set the corresponding account guest vlan map id
    final List<Integer> finaVlanTokens = getVlanFromRange(accountGuestVlanMapVO.getGuestVlanRange());
    for (int i = finaVlanTokens.get(0).intValue(); i <= finaVlanTokens.get(1).intValue(); i++) {
        final List<DataCenterVnetVO> dataCenterVnet = _datacneterVnet.findVnet(physicalNetwork.getDataCenterId(), physicalNetworkId, Integer.toString(i));
        dataCenterVnet.get(0).setAccountGuestVlanMapId(accountGuestVlanMapVO.getId());
        _datacneterVnet.update(dataCenterVnet.get(0).getId(), dataCenterVnet.get(0));
    }
    return accountGuestVlanMapVO;
}
Also used : Account(com.cloud.legacymodel.user.Account) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) Project(com.cloud.projects.Project) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.legacymodel.utils.Pair) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

Pair (com.cloud.legacymodel.utils.Pair)139 ArrayList (java.util.ArrayList)87 List (java.util.List)64 Account (com.cloud.legacymodel.user.Account)49 Filter (com.cloud.utils.db.Filter)48 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)38 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)27 HashMap (java.util.HashMap)27 Ternary (com.cloud.legacymodel.utils.Ternary)23 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)22 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)20 SSHKeyPair (com.cloud.legacymodel.user.SSHKeyPair)16 TemplateFilter (com.cloud.legacymodel.storage.VirtualMachineTemplate.TemplateFilter)13 Map (java.util.Map)13 DB (com.cloud.utils.db.DB)11 DomainVO (com.cloud.domain.DomainVO)10 VolumeVO (com.cloud.storage.VolumeVO)10 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)9 Network (com.cloud.legacymodel.network.Network)9 ResourceTagVO (com.cloud.tags.ResourceTagVO)9