Search in sources :

Example 6 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class CreateTemplateCmd method getEntityOwnerId.

@Override
public long getEntityOwnerId() {
    Long volumeId = getVolumeId();
    Long snapshotId = getSnapshotId();
    Account callingAccount = CallContext.current().getCallingAccount();
    if (volumeId != null) {
        Volume volume = _entityMgr.findById(Volume.class, volumeId);
        if (volume != null) {
            _accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, volume);
        } else {
            throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
        }
    } else {
        Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId);
        if (snapshot != null) {
            _accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, snapshot);
        } else {
            throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId);
        }
    }
    if (projectId != null) {
        final Project project = _projectService.getProject(projectId);
        if (project != null) {
            if (project.getState() == Project.State.Active) {
                Account projectAccount = _accountService.getAccount(project.getProjectAccountId());
                _accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, projectAccount);
                return project.getProjectAccountId();
            } else {
                final PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active");
                ex.addProxyObject(project.getUuid(), "projectId");
                throw ex;
            }
        } else {
            throw new InvalidParameterValueException("Unable to find project by id");
        }
    }
    return callingAccount.getId();
}
Also used : Account(com.cloud.user.Account) Snapshot(com.cloud.storage.Snapshot) Project(com.cloud.projects.Project) Volume(com.cloud.storage.Volume) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 7 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class ApiResponseHelper method createUsageResponse.

@Override
public UsageRecordResponse createUsageResponse(Usage usageRecord) {
    UsageRecordResponse usageRecResponse = new UsageRecordResponse();
    Account account = ApiDBUtils.findAccountById(usageRecord.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        //find the project
        Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
        if (project != null) {
            usageRecResponse.setProjectId(project.getUuid());
            usageRecResponse.setProjectName(project.getName());
        }
    } else {
        usageRecResponse.setAccountId(account.getUuid());
        usageRecResponse.setAccountName(account.getAccountName());
    }
    Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
    if (domain != null) {
        usageRecResponse.setDomainId(domain.getUuid());
        usageRecResponse.setDomainName(domain.getName());
    }
    if (usageRecord.getZoneId() != null) {
        DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
        if (zone != null) {
            usageRecResponse.setZoneId(zone.getUuid());
        }
    }
    usageRecResponse.setDescription(usageRecord.getDescription());
    usageRecResponse.setUsage(usageRecord.getUsageDisplay());
    usageRecResponse.setUsageType(usageRecord.getUsageType());
    if (usageRecord.getVmInstanceId() != null) {
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
        if (vm != null) {
            usageRecResponse.setVirtualMachineId(vm.getUuid());
        }
    }
    usageRecResponse.setVmName(usageRecord.getVmName());
    if (usageRecord.getTemplateId() != null) {
        VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
        if (template != null) {
            usageRecResponse.setTemplateId(template.getUuid());
        }
    }
    if (usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM) {
        ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
        //Service Offering Id
        usageRecResponse.setOfferingId(svcOffering.getUuid());
        //VM Instance ID
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
        if (vm != null) {
            usageRecResponse.setUsageId(vm.getUuid());
        }
        //Hypervisor Type
        usageRecResponse.setType(usageRecord.getType());
        //Dynamic compute offerings details
        usageRecResponse.setCpuNumber(usageRecord.getCpuCores());
        usageRecResponse.setCpuSpeed(usageRecord.getCpuSpeed());
        usageRecResponse.setMemory(usageRecord.getMemory());
    } else if (usageRecord.getUsageType() == UsageTypes.IP_ADDRESS) {
        //isSourceNAT
        usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat")) ? true : false);
        //isSystem
        usageRecResponse.setSystem((usageRecord.getSize() == 1) ? true : false);
        //IP Address ID
        IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
        if (ip != null) {
            usageRecResponse.setUsageId(ip.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED) {
        //Device Type
        usageRecResponse.setType(usageRecord.getType());
        if (usageRecord.getType().equals("DomainRouter")) {
            //Domain Router Id
            VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
            if (vm != null) {
                usageRecResponse.setUsageId(vm.getUuid());
            }
        } else {
            //External Device Host Id
            HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
            if (host != null) {
                usageRecResponse.setUsageId(host.getUuid());
            }
        }
        //Network ID
        if ((usageRecord.getNetworkId() != null) && (usageRecord.getNetworkId() != 0)) {
            NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
            if (network != null) {
                usageRecResponse.setNetworkId(network.getUuid());
            }
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) {
        //Device Type
        usageRecResponse.setType(usageRecord.getType());
        //VM Instance Id
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
        if (vm != null) {
            usageRecResponse.setVirtualMachineId(vm.getUuid());
        }
        //Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VOLUME) {
        //Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
        }
        //Volume Size
        usageRecResponse.setSize(usageRecord.getSize());
        //Disk Offering Id
        if (usageRecord.getOfferingId() != null) {
            DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
            usageRecResponse.setOfferingId(diskOff.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO) {
        //Template/ISO ID
        VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
        if (tmpl != null) {
            usageRecResponse.setUsageId(tmpl.getUuid());
        }
        //Template/ISO Size
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getUsageType() == UsageTypes.ISO) {
            usageRecResponse.setVirtualSize(usageRecord.getSize());
        } else {
            usageRecResponse.setVirtualSize(usageRecord.getVirtualSize());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SNAPSHOT) {
        //Snapshot ID
        SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
        if (snap != null) {
            usageRecResponse.setUsageId(snap.getUuid());
        }
        //Snapshot Size
        usageRecResponse.setSize(usageRecord.getSize());
    } else if (usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY) {
        //Load Balancer Policy ID
        LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
        if (lb != null) {
            usageRecResponse.setUsageId(lb.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE) {
        //Port Forwarding Rule ID
        PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
        if (pf != null) {
            usageRecResponse.setUsageId(pf.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING) {
        //Network Offering Id
        NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
        usageRecResponse.setOfferingId(netOff.getUuid());
        //is Default
        usageRecResponse.setDefault((usageRecord.getUsageId() == 1) ? true : false);
    } else if (usageRecord.getUsageType() == UsageTypes.VPN_USERS) {
        //VPN User ID
        VpnUserVO vpnUser = _entityMgr.findByIdIncludingRemoved(VpnUserVO.class, usageRecord.getUsageId().toString());
        if (vpnUser != null) {
            usageRecResponse.setUsageId(vpnUser.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP) {
        //Security Group Id
        SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
        if (sg != null) {
            usageRecResponse.setUsageId(sg.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_SNAPSHOT) {
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
        if (vm != null) {
            usageRecResponse.setVmName(vm.getInstanceName());
            usageRecResponse.setUsageId(vm.getUuid());
        }
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getOfferingId() != null) {
            usageRecResponse.setOfferingId(usageRecord.getOfferingId().toString());
        }
    }
    if (usageRecord.getRawUsage() != null) {
        DecimalFormat decimalFormat = new DecimalFormat("###########.######");
        usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
    }
    if (usageRecord.getStartDate() != null) {
        usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
    }
    if (usageRecord.getEndDate() != null) {
        usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
    }
    return usageRecResponse;
}
Also used : UsageRecordResponse(org.apache.cloudstack.api.response.UsageRecordResponse) ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) SecurityGroupVO(com.cloud.network.security.SecurityGroupVO) VpnUserVO(com.cloud.network.VpnUserVO) DecimalFormat(java.text.DecimalFormat) VMTemplateVO(com.cloud.storage.VMTemplateVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) HostVO(com.cloud.host.HostVO) Project(com.cloud.projects.Project) DataCenter(com.cloud.dc.DataCenter) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) Domain(com.cloud.domain.Domain)

Example 8 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class ApiResponseHelper method createTemplatePermissionsResponse.

@Override
public TemplatePermissionsResponse createTemplatePermissionsResponse(ResponseView view, List<String> accountNames, Long id) {
    Long templateOwnerDomain = null;
    VirtualMachineTemplate template = ApiDBUtils.findTemplateById(id);
    Account templateOwner = ApiDBUtils.findAccountById(template.getAccountId());
    if (view == ResponseView.Full) {
        // from that
        if (templateOwner != null) {
            templateOwnerDomain = templateOwner.getDomainId();
        }
    }
    TemplatePermissionsResponse response = new TemplatePermissionsResponse();
    response.setId(template.getUuid());
    response.setPublicTemplate(template.isPublicTemplate());
    if ((view == ResponseView.Full) && (templateOwnerDomain != null)) {
        Domain domain = ApiDBUtils.findDomainById(templateOwnerDomain);
        if (domain != null) {
            response.setDomainId(domain.getUuid());
        }
    }
    // Set accounts
    List<String> projectIds = new ArrayList<String>();
    List<String> regularAccounts = new ArrayList<String>();
    for (String accountName : accountNames) {
        Account account = ApiDBUtils.findAccountByNameDomain(accountName, templateOwner.getDomainId());
        if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            regularAccounts.add(accountName);
        } else {
            // convert account to projectIds
            Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
            if (project.getUuid() != null && !project.getUuid().isEmpty()) {
                projectIds.add(project.getUuid());
            } else {
                projectIds.add(String.valueOf(project.getId()));
            }
        }
    }
    if (!projectIds.isEmpty()) {
        response.setProjectIds(projectIds);
    }
    if (!regularAccounts.isEmpty()) {
        response.setAccountNames(regularAccounts);
    }
    response.setObjectName("templatepermission");
    return response;
}
Also used : ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) Project(com.cloud.projects.Project) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ArrayList(java.util.ArrayList) Domain(com.cloud.domain.Domain) TemplatePermissionsResponse(org.apache.cloudstack.api.response.TemplatePermissionsResponse)

Example 9 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class NetworkServiceImpl method listDedicatedGuestVlanRanges.

@Override
public Pair<List<? extends GuestVlan>, Integer> listDedicatedGuestVlanRanges(ListDedicatedGuestVlanRangesCmd cmd) {
    Long id = cmd.getId();
    String accountName = cmd.getAccountName();
    Long domainId = cmd.getDomainId();
    Long projectId = cmd.getProjectId();
    String guestVlanRange = cmd.getGuestVlanRange();
    Long physicalNetworkId = cmd.getPhysicalNetworkId();
    Long zoneId = cmd.getZoneId();
    Long accountId = null;
    if (accountName != null && domainId != null) {
        if (projectId != null) {
            throw new InvalidParameterValueException("Account and projectId can't be specified together");
        }
        Account account = _accountDao.findActiveAccount(accountName, domainId);
        if (account == null) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName);
            DomainVO domain = ApiDBUtils.findDomainById(domainId);
            String domainUuid = domainId.toString();
            if (domain != null) {
                domainUuid = domain.getUuid();
            }
            ex.addProxyObject(domainUuid, "domainId");
            throw ex;
        } else {
            accountId = account.getId();
        }
    }
    // set project information
    if (projectId != null) {
        Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project by id " + projectId);
            ex.addProxyObject(projectId.toString(), "projectId");
            throw ex;
        }
        accountId = project.getProjectAccountId();
    }
    SearchBuilder<AccountGuestVlanMapVO> sb = _accountGuestVlanMapDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
    sb.and("guestVlanRange", sb.entity().getGuestVlanRange(), SearchCriteria.Op.EQ);
    sb.and("physicalNetworkId", sb.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
    if (zoneId != null) {
        SearchBuilder<PhysicalNetworkVO> physicalnetworkSearch = _physicalNetworkDao.createSearchBuilder();
        physicalnetworkSearch.and("zoneId", physicalnetworkSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
        sb.join("physicalnetworkSearch", physicalnetworkSearch, sb.entity().getPhysicalNetworkId(), physicalnetworkSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    }
    SearchCriteria<AccountGuestVlanMapVO> sc = sb.create();
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (accountId != null) {
        sc.setParameters("accountId", accountId);
    }
    if (guestVlanRange != null) {
        sc.setParameters("guestVlanRange", guestVlanRange);
    }
    if (physicalNetworkId != null) {
        sc.setParameters("physicalNetworkId", physicalNetworkId);
    }
    if (zoneId != null) {
        sc.setJoinParameters("physicalnetworkSearch", "zoneId", zoneId);
    }
    Filter searchFilter = new Filter(AccountGuestVlanMapVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    Pair<List<AccountGuestVlanMapVO>, Integer> result = _accountGuestVlanMapDao.searchAndCount(sc, searchFilter);
    return new Pair<List<? extends GuestVlan>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) DomainVO(com.cloud.domain.DomainVO) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair)

Example 10 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

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(DedicateGuestVlanRangeCmd cmd) {
    String vlan = cmd.getVlan();
    String accountName = cmd.getAccountName();
    Long domainId = cmd.getDomainId();
    Long physicalNetworkId = cmd.getPhysicalNetworkId();
    Long projectId = cmd.getProjectId();
    int startVlan, 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");
        }
        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
    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
    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 (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
    List<Pair<Integer, Integer>> existingRanges = physicalNetwork.getVnet();
    Boolean exists = false;
    if (!existingRanges.isEmpty()) {
        for (int i = 0; i < existingRanges.size(); i++) {
            int existingStartVlan = existingRanges.get(i).first();
            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++) {
        List<DataCenterVnetVO> allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
        if (allocatedVlans != null && !allocatedVlans.isEmpty()) {
            for (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 ");
                }
            }
        }
    }
    List<AccountGuestVlanMapVO> guestVlanMaps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(physicalNetworkId);
    // Verify if vlan range is already dedicated
    for (AccountGuestVlanMapVO guestVlanMap : guestVlanMaps) {
        List<Integer> vlanTokens = getVlanFromRange(guestVlanMap.getGuestVlanRange());
        int dedicatedStartVlan = vlanTokens.get(0).intValue();
        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(AccountGuestVlanMapVO obj1, AccountGuestVlanMapVO obj2) {
            List<Integer> vlanTokens1 = getVlanFromRange(obj1.getGuestVlanRange());
            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();
        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)) {
                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
    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
    List<Integer> finaVlanTokens = getVlanFromRange(accountGuestVlanMapVO.getGuestVlanRange());
    for (int i = finaVlanTokens.get(0).intValue(); i <= finaVlanTokens.get(1).intValue(); i++) {
        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.user.Account) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) Project(com.cloud.projects.Project) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

Project (com.cloud.projects.Project)48 Account (com.cloud.user.Account)30 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)25 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)16 Domain (com.cloud.domain.Domain)10 ArrayList (java.util.ArrayList)10 DomainVO (com.cloud.domain.DomainVO)7 Volume (com.cloud.storage.Volume)7 Pair (com.cloud.utils.Pair)6 List (java.util.List)6 ServerApiException (com.cloud.api.ServerApiException)5 ProjectResponse (com.cloud.api.response.ProjectResponse)5 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)5 ProjectAccount (com.cloud.projects.ProjectAccount)5 UserAccount (com.cloud.user.UserAccount)5 ServerApiException (org.apache.cloudstack.api.ServerApiException)5 DataCenterVO (com.cloud.dc.DataCenterVO)4 DB (com.cloud.utils.db.DB)4 Filter (com.cloud.utils.db.Filter)4 VlanVO (com.cloud.dc.VlanVO)3