Search in sources :

Example 1 with VpnUserVO

use of com.cloud.network.VpnUserVO in project cloudstack by apache.

the class UsageServiceImpl method getUsageRecords.

@Override
public Pair<List<? extends Usage>, Integer> getUsageRecords(GetUsageRecordsCmd cmd) {
    Long accountId = cmd.getAccountId();
    Long domainId = cmd.getDomainId();
    String accountName = cmd.getAccountName();
    Account userAccount = null;
    Account caller = CallContext.current().getCallingAccount();
    Long usageType = cmd.getUsageType();
    Long projectId = cmd.getProjectId();
    String usageId = cmd.getUsageId();
    if (projectId != null) {
        if (accountId != null) {
            throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
        }
        Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            throw new InvalidParameterValueException("Unable to find project by id " + projectId);
        }
        accountId = project.getProjectAccountId();
    }
    //if accountId is not specified, use accountName and domainId
    if ((accountId == null) && (accountName != null) && (domainId != null)) {
        if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
            Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
            List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
            if (accounts.size() > 0) {
                userAccount = accounts.get(0);
            }
            if (userAccount != null) {
                accountId = userAccount.getId();
            } else {
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
            }
        } else {
            throw new PermissionDeniedException("Invalid Domain Id or Account");
        }
    }
    boolean isAdmin = false;
    boolean isDomainAdmin = false;
    //If accountId couldn't be found using accountName and domainId, get it from userContext
    if (accountId == null) {
        accountId = caller.getId();
        //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
        if (_accountService.isRootAdmin(caller.getId())) {
            isAdmin = true;
        } else if (_accountService.isDomainAdmin(caller.getId())) {
            isDomainAdmin = true;
        }
        s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
    }
    Date startDate = cmd.getStartDate();
    Date endDate = cmd.getEndDate();
    if (startDate.after(endDate)) {
        throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
    }
    TimeZone usageTZ = getUsageTimezone();
    Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ);
    Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
    }
    Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
    if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) {
        sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
    }
    if (isDomainAdmin) {
        SearchCriteria<DomainVO> sdc = _domainDao.createSearchCriteria();
        sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
        List<DomainVO> domains = _domainDao.search(sdc, null);
        List<Long> domainIds = new ArrayList<Long>();
        for (DomainVO domain : domains) domainIds.add(domain.getId());
        sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray());
    }
    if (domainId != null) {
        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
    }
    if (usageType != null) {
        sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
    }
    if (usageId != null) {
        if (usageType == null) {
            throw new InvalidParameterValueException("Usageid must be specified together with usageType");
        }
        Long usageDbId = null;
        switch(usageType.intValue()) {
            case UsageTypes.NETWORK_BYTES_RECEIVED:
            case UsageTypes.NETWORK_BYTES_SENT:
            case UsageTypes.RUNNING_VM:
            case UsageTypes.ALLOCATED_VM:
            case UsageTypes.VM_SNAPSHOT:
                VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId);
                if (vm != null) {
                    usageDbId = vm.getId();
                }
                if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) {
                    HostVO host = _hostDao.findByUuidIncludingRemoved(usageId);
                    if (host != null) {
                        usageDbId = host.getId();
                    }
                }
                break;
            case UsageTypes.SNAPSHOT:
                SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId);
                if (snap != null) {
                    usageDbId = snap.getId();
                }
                break;
            case UsageTypes.TEMPLATE:
            case UsageTypes.ISO:
                VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId);
                if (tmpl != null) {
                    usageDbId = tmpl.getId();
                }
                break;
            case UsageTypes.LOAD_BALANCER_POLICY:
                LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId);
                if (lb != null) {
                    usageDbId = lb.getId();
                }
                break;
            case UsageTypes.PORT_FORWARDING_RULE:
                PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId);
                if (pf != null) {
                    usageDbId = pf.getId();
                }
                break;
            case UsageTypes.VOLUME:
            case UsageTypes.VM_DISK_IO_READ:
            case UsageTypes.VM_DISK_IO_WRITE:
            case UsageTypes.VM_DISK_BYTES_READ:
            case UsageTypes.VM_DISK_BYTES_WRITE:
                VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId);
                if (volume != null) {
                    usageDbId = volume.getId();
                }
                break;
            case UsageTypes.VPN_USERS:
                VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId);
                if (vpnUser != null) {
                    usageDbId = vpnUser.getId();
                }
                break;
            case UsageTypes.SECURITY_GROUP:
                SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId);
                if (sg != null) {
                    usageDbId = sg.getId();
                }
                break;
            case UsageTypes.IP_ADDRESS:
                IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId);
                if (ip != null) {
                    usageDbId = ip.getId();
                }
                break;
            default:
                break;
        }
        if (usageDbId != null) {
            sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId);
        } else {
            // return an empty list if usageId was not found
            return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
        }
    }
    if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
        sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
        sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
    } else {
        // return an empty list if we fail to validate the dates
        return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
    }
    Pair<List<UsageVO>, Integer> usageRecords = null;
    TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
    try {
        usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter);
    } finally {
        txn.close();
        // switch back to VMOPS_DB
        TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
        swap.close();
    }
    return new Pair<List<? extends Usage>, Integer>(usageRecords.first(), usageRecords.second());
}
Also used : Account(com.cloud.user.Account) VpnUserVO(com.cloud.network.VpnUserVO) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) AccountVO(com.cloud.user.AccountVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) Usage(org.apache.cloudstack.usage.Usage) SecurityGroupVO(com.cloud.network.security.SecurityGroupVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) Project(com.cloud.projects.Project) DomainVO(com.cloud.domain.DomainVO) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) TimeZone(java.util.TimeZone) SnapshotVO(com.cloud.storage.SnapshotVO) Filter(com.cloud.utils.db.Filter) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 2 with VpnUserVO

use of com.cloud.network.VpnUserVO 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 3 with VpnUserVO

use of com.cloud.network.VpnUserVO in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method searchForVpnUsers.

@Override
public Pair<List<? extends VpnUser>, Integer> searchForVpnUsers(final ListVpnUsersCmd cmd) {
    final String username = cmd.getUsername();
    final Long id = cmd.getId();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(VpnUserVO.class, "username", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<VpnUserVO> sb = _vpnUsersDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ);
    sb.and("state", sb.entity().getState(), Op.IN);
    final SearchCriteria<VpnUserVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    // list only active users
    sc.setParameters("state", State.Active, State.Add);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (username != null) {
        sc.setParameters("username", username);
    }
    final Pair<List<VpnUserVO>, Integer> result = _vpnUsersDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) VpnUserVO(com.cloud.network.VpnUserVO) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair)

Example 4 with VpnUserVO

use of com.cloud.network.VpnUserVO in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method applyVpnUsers.

@DB
@Override
public boolean applyVpnUsers(final long vpnOwnerId, final String userName) {
    final Account caller = CallContext.current().getCallingAccount();
    final Account owner = _accountDao.findById(vpnOwnerId);
    _accountMgr.checkAccess(caller, null, true, owner);
    s_logger.debug("Applying vpn users for " + owner);
    final List<RemoteAccessVpnVO> vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId);
    if (vpns.size() == 0) {
        throw new InvalidParameterValueException("No Remote Access VPN configuration can be found for account " + owner.getAccountName());
    }
    final List<VpnUserVO> users = _vpnUsersDao.listByAccount(vpnOwnerId);
    // If user is in Active state, we still have to resend them therefore their status has to be Add
    for (final VpnUserVO user : users) {
        if (user.getState() == State.Active) {
            user.setState(State.Add);
            _vpnUsersDao.update(user.getId(), user);
        }
    }
    boolean success = true;
    final Boolean[] finals = new Boolean[users.size()];
    for (final RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
        s_logger.debug("Applying vpn access to " + element.getName());
        for (final RemoteAccessVpnVO vpn : vpns) {
            try {
                final String[] results = element.applyVpnUsers(vpn, users);
                if (results != null) {
                    int indexUser = -1;
                    for (int i = 0; i < results.length; i++) {
                        indexUser++;
                        if (indexUser == users.size()) {
                            // results on multiple VPC routers are combined in commit 13eb789, reset user index if one VR is done.
                            indexUser = 0;
                        }
                        s_logger.debug("VPN User " + users.get(indexUser) + (results[i] == null ? " is set on " : (" couldn't be set due to " + results[i]) + " on ") + vpn.getUuid());
                        if (results[i] == null) {
                            if (finals[indexUser] == null) {
                                finals[indexUser] = true;
                            }
                        } else {
                            finals[indexUser] = false;
                            success = false;
                        }
                    }
                }
            } catch (final Exception e) {
                s_logger.warn("Unable to apply vpn users ", e);
                success = false;
                for (int i = 0; i < finals.length; i++) {
                    finals[i] = false;
                }
            }
        }
    }
    for (int i = 0; i < finals.length; i++) {
        final VpnUserVO user = users.get(i);
        if (finals[i]) {
            if (user.getState() == State.Add) {
                user.setState(State.Active);
                _vpnUsersDao.update(user.getId(), user);
            } else if (user.getState() == State.Revoke) {
                _vpnUsersDao.remove(user.getId());
            }
        } else {
            if (user.getState() == State.Add && (user.getUsername()).equals(userName)) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(final TransactionStatus status) {
                        _vpnUsersDao.remove(user.getId());
                    }
                });
            }
            s_logger.warn("Failed to apply vpn for user " + user.getUsername() + ", accountId=" + user.getAccountId());
        }
    }
    return success;
}
Also used : Account(com.cloud.user.Account) RemoteAccessVPNServiceProvider(com.cloud.network.element.RemoteAccessVPNServiceProvider) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) VpnUserVO(com.cloud.network.VpnUserVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) AccountLimitException(com.cloud.exception.AccountLimitException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DB(com.cloud.utils.db.DB)

Example 5 with VpnUserVO

use of com.cloud.network.VpnUserVO in project cloudstack by apache.

the class ApiResponseHelper method createUsageResponse.

@Override
public UsageRecordResponse createUsageResponse(Usage usageRecord, Map<String, Set<ResourceTagResponse>> resourceTagResponseMap, boolean oldFormat) {
    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());
    VMInstanceVO vmInstance = null;
    if (usageRecord.getVmInstanceId() != null) {
        vmInstance = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
        if (vmInstance != null) {
            usageRecResponse.setVirtualMachineId(vmInstance.getUuid());
        }
    }
    usageRecResponse.setResourceName(usageRecord.getVmName());
    VMTemplateVO template = null;
    if (usageRecord.getTemplateId() != null) {
        template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
        if (template != null) {
            usageRecResponse.setTemplateId(template.getUuid());
        }
    }
    ResourceTag.ResourceObjectType resourceType = null;
    Long resourceId = null;
    if (usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM) {
        ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
        // Service Offering Id
        if (svcOffering != null) {
            usageRecResponse.setOfferingId(svcOffering.getUuid());
        }
        // VM Instance ID
        VMInstanceVO vm = null;
        if (usageRecord.getUsageId() != null && usageRecord.getUsageId().equals(usageRecord.getVmInstanceId())) {
            vm = vmInstance;
        } else {
            vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
        }
        if (vm != null) {
            resourceType = ResourceTag.ResourceObjectType.UserVm;
            usageRecResponse.setUsageId(vm.getUuid());
            resourceId = vm.getId();
            final GuestOS guestOS = _guestOsDao.findById(vm.getGuestOSId());
            if (guestOS != null) {
                usageRecResponse.setOsTypeId(guestOS.getUuid());
                usageRecResponse.setOsDisplayName(guestOS.getDisplayName());
                final GuestOsCategory guestOsCategory = _guestOsCategoryDao.findById(guestOS.getCategoryId());
                if (guestOsCategory != null) {
                    usageRecResponse.setOsCategoryId(guestOsCategory.getUuid());
                    usageRecResponse.setOsCategoryName(guestOsCategory.getName());
                }
            }
        }
        // Hypervisor Type
        usageRecResponse.setType(usageRecord.getType());
        // Dynamic compute offerings details
        if (usageRecord.getCpuCores() != null) {
            usageRecResponse.setCpuNumber(usageRecord.getCpuCores());
        } else if (svcOffering.getCpu() != null) {
            usageRecResponse.setCpuNumber(svcOffering.getCpu().longValue());
        }
        if (usageRecord.getCpuSpeed() != null) {
            usageRecResponse.setCpuSpeed(usageRecord.getCpuSpeed());
        } else if (svcOffering.getSpeed() != null) {
            usageRecResponse.setCpuSpeed(svcOffering.getSpeed().longValue());
        }
        if (usageRecord.getMemory() != null) {
            usageRecResponse.setMemory(usageRecord.getMemory());
        } else if (svcOffering.getRamSize() != null) {
            usageRecResponse.setMemory(svcOffering.getRamSize().longValue());
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            if (usageRecord.getUsageType() == UsageTypes.RUNNING_VM) {
                builder.append("Running VM usage ");
            } else if (usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM) {
                builder.append("Allocated VM usage ");
            }
            if (vm != null) {
                builder.append("for ").append(vm.getHostName()).append(" (").append(vm.getInstanceName()).append(") (").append(vm.getUuid()).append(") ");
            }
            if (svcOffering != null) {
                builder.append("using service offering ").append(svcOffering.getName()).append(" (").append(svcOffering.getUuid()).append(") ");
            }
            if (template != null) {
                builder.append("and template ").append(template.getName()).append(" (").append(template.getUuid()).append(")");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.IP_ADDRESS) {
        // IP Address ID
        IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
        if (ip != null) {
            Long networkId = ip.getAssociatedWithNetworkId();
            if (networkId == null) {
                networkId = ip.getSourceNetworkId();
            }
            resourceType = ResourceObjectType.PublicIpAddress;
            resourceId = ip.getId();
            usageRecResponse.setUsageId(ip.getUuid());
        }
        // isSourceNAT
        usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat")) ? true : false);
        // isSystem
        usageRecResponse.setSystem((usageRecord.getSize() == 1) ? true : false);
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED) {
        // Device Type
        resourceType = ResourceObjectType.UserVm;
        usageRecResponse.setType(usageRecord.getType());
        VMInstanceVO vm = null;
        HostVO host = null;
        if (usageRecord.getType().equals("DomainRouter") || usageRecord.getType().equals("UserVm")) {
            // Domain Router Id
            vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
            if (vm != null) {
                resourceId = vm.getId();
                usageRecResponse.setUsageId(vm.getUuid());
            }
        } else {
            // External Device Host Id
            host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
            if (host != null) {
                usageRecResponse.setUsageId(host.getUuid());
            }
        }
        // Network ID
        NetworkVO network = null;
        if ((usageRecord.getNetworkId() != null) && (usageRecord.getNetworkId() != 0)) {
            network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
            if (network != null) {
                resourceType = ResourceObjectType.Network;
                if (network.getTrafficType() == TrafficType.Public) {
                    VirtualRouter router = ApiDBUtils.findDomainRouterById(usageRecord.getUsageId());
                    Vpc vpc = ApiDBUtils.findVpcByIdIncludingRemoved(router.getVpcId());
                    usageRecResponse.setVpcId(vpc.getUuid());
                    resourceId = vpc.getId();
                } else {
                    usageRecResponse.setNetworkId(network.getUuid());
                    resourceId = network.getId();
                }
                usageRecResponse.setResourceName(network.getName());
            }
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT) {
                builder.append("Bytes sent by network ");
            } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED) {
                builder.append("Bytes received by network ");
            }
            if (network != null) {
                if (network.getName() != null) {
                    builder.append(network.getName());
                }
                if (network.getUuid() != null) {
                    builder.append(" (").append(network.getUuid()).append(") ");
                }
                builder.append(" " + toHumanReadableSize(usageRecord.getRawUsage().longValue()) + " ");
            }
            if (vm != null) {
                builder.append("using router ").append(vm.getInstanceName()).append(" (").append(vm.getUuid()).append(")");
            } else if (host != null) {
                builder.append("using host ").append(host.getName()).append(" (").append(host.getUuid()).append(")");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } 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());
        resourceType = ResourceObjectType.Volume;
        // Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
            resourceId = volume.getId();
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ) {
                builder.append("Disk I/O read requests");
            } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE) {
                builder.append("Disk I/O write requests");
            } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ) {
                builder.append("Disk I/O read bytes");
            } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) {
                builder.append("Disk I/O write bytes");
            }
            if (vmInstance != null) {
                builder.append(" for VM ").append(vmInstance.getHostName()).append(" (").append(vmInstance.getUuid()).append(")");
            }
            if (volume != null) {
                builder.append(" and volume ").append(volume.getName()).append(" (").append(volume.getUuid()).append(")");
            }
            if (usageRecord.getRawUsage() != null) {
                builder.append(" " + toHumanReadableSize(usageRecord.getRawUsage().longValue()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VOLUME) {
        // Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        resourceType = ResourceObjectType.Volume;
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
            resourceId = volume.getId();
        }
        // Volume Size
        usageRecResponse.setSize(usageRecord.getSize());
        // Disk Offering Id
        DiskOfferingVO diskOff = null;
        if (usageRecord.getOfferingId() != null) {
            diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
            usageRecResponse.setOfferingId(diskOff.getUuid());
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Volume usage ");
            if (volume != null) {
                builder.append("for ").append(volume.getName()).append(" (").append(volume.getUuid()).append(")");
            }
            if (diskOff != null) {
                builder.append(" with disk offering ").append(diskOff.getName()).append(" (").append(diskOff.getUuid()).append(")");
            }
            if (template != null) {
                builder.append(" and template ").append(template.getName()).append(" (").append(template.getUuid()).append(")");
            }
            if (usageRecord.getSize() != null) {
                builder.append(" and size " + toHumanReadableSize(usageRecord.getSize()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } 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());
            resourceId = tmpl.getId();
        }
        // Template/ISO Size
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getUsageType() == UsageTypes.ISO) {
            usageRecResponse.setVirtualSize(usageRecord.getSize());
            resourceType = ResourceObjectType.ISO;
        } else {
            usageRecResponse.setVirtualSize(usageRecord.getVirtualSize());
            resourceType = ResourceObjectType.Template;
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            if (usageRecord.getUsageType() == UsageTypes.TEMPLATE) {
                builder.append("Template usage");
            } else if (usageRecord.getUsageType() == UsageTypes.ISO) {
                builder.append("ISO usage");
            }
            if (tmpl != null) {
                builder.append(" for ").append(tmpl.getName()).append(" (").append(tmpl.getUuid()).append(") ").append("with size ").append(toHumanReadableSize(usageRecord.getSize())).append(" and virtual size ").append(toHumanReadableSize(usageRecord.getVirtualSize()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SNAPSHOT) {
        // Snapshot ID
        SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
        resourceType = ResourceObjectType.Snapshot;
        if (snap != null) {
            usageRecResponse.setUsageId(snap.getUuid());
            resourceId = snap.getId();
        }
        // Snapshot Size
        usageRecResponse.setSize(usageRecord.getSize());
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Snapshot usage ");
            if (snap != null) {
                builder.append("for ").append(snap.getName()).append(" (").append(snap.getUuid()).append(") ").append("with size ").append(toHumanReadableSize(usageRecord.getSize()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY) {
        // Load Balancer Policy ID
        LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
        resourceType = ResourceObjectType.LoadBalancer;
        if (lb != null) {
            usageRecResponse.setUsageId(lb.getUuid());
            resourceId = lb.getId();
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Loadbalancer policy usage ");
            if (lb != null) {
                builder.append(lb.getName()).append(" (").append(lb.getUuid()).append(")");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE) {
        // Port Forwarding Rule ID
        PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
        resourceType = ResourceObjectType.PortForwardingRule;
        if (pf != null) {
            usageRecResponse.setUsageId(pf.getUuid());
            resourceId = pf.getId();
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Port forwarding rule usage");
            if (pf != null) {
                builder.append(" (").append(pf.getUuid()).append(")");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } 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);
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Network offering ");
            if (netOff != null) {
                builder.append(netOff.getName()).append(" (").append(netOff.getUuid()).append(") usage ");
            }
            if (vmInstance != null) {
                builder.append("for VM ").append(vmInstance.getHostName()).append(" (").append(vmInstance.getUuid()).append(") ");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } 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());
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("VPN usage ");
            if (vpnUser != null) {
                builder.append("for user ").append(vpnUser.getUsername()).append(" (").append(vpnUser.getUuid()).append(")");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP) {
        // Security Group Id
        SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
        resourceType = ResourceObjectType.SecurityGroup;
        if (sg != null) {
            resourceId = sg.getId();
            usageRecResponse.setUsageId(sg.getUuid());
        }
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Security group");
            if (sg != null) {
                builder.append(" ").append(sg.getName()).append(" (").append(sg.getUuid()).append(") usage");
            }
            if (vmInstance != null) {
                builder.append(" for VM ").append(vmInstance.getHostName()).append(" (").append(vmInstance.getUuid()).append(")");
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.BACKUP) {
        resourceType = ResourceObjectType.Backup;
        final StringBuilder builder = new StringBuilder();
        builder.append("Backup usage of size ").append(usageRecord.getUsageDisplay());
        if (vmInstance != null) {
            resourceId = vmInstance.getId();
            usageRecResponse.setResourceName(vmInstance.getInstanceName());
            usageRecResponse.setUsageId(vmInstance.getUuid());
            builder.append(" for VM ").append(vmInstance.getHostName()).append(" (").append(vmInstance.getUuid()).append(")");
            final BackupOffering backupOffering = backupOfferingDao.findByIdIncludingRemoved(usageRecord.getOfferingId());
            if (backupOffering != null) {
                builder.append(" and backup offering ").append(backupOffering.getName()).append(" (").append(backupOffering.getUuid()).append(", user ad-hoc/scheduled backup allowed: ").append(backupOffering.isUserDrivenBackupAllowed()).append(")");
            }
        }
        usageRecResponse.setDescription(builder.toString());
    } else if (usageRecord.getUsageType() == UsageTypes.VM_SNAPSHOT) {
        resourceType = ResourceObjectType.VMSnapshot;
        VMSnapshotVO vmSnapshotVO = null;
        if (usageRecord.getUsageId() != null) {
            vmSnapshotVO = vmSnapshotDao.findByIdIncludingRemoved(usageRecord.getUsageId());
            if (vmSnapshotVO != null) {
                resourceId = vmSnapshotVO.getId();
                usageRecResponse.setResourceName(vmSnapshotVO.getDisplayName());
                usageRecResponse.setUsageId(vmSnapshotVO.getUuid());
            }
        }
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getVirtualSize() != null) {
            usageRecResponse.setVirtualSize(usageRecord.getVirtualSize());
        }
        if (usageRecord.getOfferingId() != null) {
            usageRecResponse.setOfferingId(usageRecord.getOfferingId().toString());
        }
        if (!oldFormat) {
            VolumeVO volume = null;
            if (vmSnapshotVO == null && usageRecord.getUsageId() != null) {
                volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
            }
            DiskOfferingVO diskOff = null;
            if (usageRecord.getOfferingId() != null) {
                diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId());
            }
            final StringBuilder builder = new StringBuilder();
            builder.append("VMSnapshot usage");
            if (vmSnapshotVO != null) {
                builder.append(" Id: ").append(vmSnapshotVO.getUuid());
            }
            if (vmInstance != null) {
                builder.append(" for VM ").append(vmInstance.getHostName()).append(" (").append(vmInstance.getUuid()).append(")");
            }
            if (volume != null) {
                builder.append(" with volume ").append(volume.getName()).append(" (").append(volume.getUuid()).append(")");
            }
            if (diskOff != null) {
                builder.append(" using disk offering ").append(diskOff.getName()).append(" (").append(diskOff.getUuid()).append(")");
            }
            if (usageRecord.getSize() != null) {
                builder.append(" and size " + toHumanReadableSize(usageRecord.getSize()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VOLUME_SECONDARY) {
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Volume on secondary storage usage");
            if (volume != null) {
                builder.append(" for ").append(volume.getName()).append(" (").append(volume.getUuid()).append(") ").append("with size ").append(toHumanReadableSize(usageRecord.getSize()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_SNAPSHOT_ON_PRIMARY) {
        resourceType = ResourceObjectType.VMSnapshot;
        VMSnapshotVO vmSnapshotVO = null;
        if (usageRecord.getUsageId() != null) {
            vmSnapshotVO = vmSnapshotDao.findByIdIncludingRemoved(usageRecord.getUsageId());
            if (vmSnapshotVO != null) {
                resourceId = vmSnapshotVO.getId();
                usageRecResponse.setResourceName(vmSnapshotVO.getDisplayName());
                usageRecResponse.setUsageId(vmSnapshotVO.getUuid());
            }
        }
        usageRecResponse.setSize(usageRecord.getVirtualSize());
        if (!oldFormat) {
            final StringBuilder builder = new StringBuilder();
            builder.append("VMSnapshot on primary storage usage");
            if (vmSnapshotVO != null) {
                builder.append(" Id: ").append(vmSnapshotVO.getUuid());
            }
            if (vmInstance != null) {
                builder.append(" for VM ").append(vmInstance.getHostName()).append(" (").append(vmInstance.getUuid()).append(") ").append("with size ").append(toHumanReadableSize(usageRecord.getVirtualSize()));
            }
            usageRecResponse.setDescription(builder.toString());
        }
    }
    if (resourceTagResponseMap != null && resourceTagResponseMap.get(resourceId + ":" + resourceType) != null) {
        usageRecResponse.setTags(resourceTagResponseMap.get(resourceId + ":" + resourceType));
    }
    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) GuestOsCategory(com.cloud.storage.GuestOsCategory) VpnUserVO(com.cloud.network.VpnUserVO) DecimalFormat(java.text.DecimalFormat) VMTemplateVO(com.cloud.storage.VMTemplateVO) Vpc(com.cloud.network.vpc.Vpc) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VolumeVO(com.cloud.storage.VolumeVO) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) GuestOS(com.cloud.storage.GuestOS) BackupOffering(org.apache.cloudstack.backup.BackupOffering) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) SecurityGroupVO(com.cloud.network.security.SecurityGroupVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) HostVO(com.cloud.host.HostVO) VirtualRouter(com.cloud.network.router.VirtualRouter) Project(com.cloud.projects.Project) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) DataCenter(com.cloud.dc.DataCenter) ResourceTag(com.cloud.server.ResourceTag) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) Domain(com.cloud.domain.Domain)

Aggregations

VpnUserVO (com.cloud.network.VpnUserVO)16 Account (com.cloud.user.Account)10 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)7 RemoteAccessVpnVO (com.cloud.network.dao.RemoteAccessVpnVO)7 DB (com.cloud.utils.db.DB)7 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)7 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)6 VMTemplateVO (com.cloud.storage.VMTemplateVO)6 VolumeVO (com.cloud.storage.VolumeVO)6 RemoteAccessVPNServiceProvider (com.cloud.network.element.RemoteAccessVPNServiceProvider)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 ConfigurationException (javax.naming.ConfigurationException)5 HostVO (com.cloud.host.HostVO)4 NetworkVO (com.cloud.network.dao.NetworkVO)4 AccountLimitException (com.cloud.exception.AccountLimitException)3 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)3 IpAddress (com.cloud.network.IpAddress)3 IPAddressVO (com.cloud.network.dao.IPAddressVO)3