Search in sources :

Example 41 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project CloudStack-archive by CloudStack-extras.

the class BaseCmd method finalyzeAccountId.

public Long finalyzeAccountId(String accountName, Long domainId, Long projectId, boolean enabledOnly) {
    if (accountName != null) {
        if (domainId == null) {
            throw new InvalidParameterValueException("Account must be specified with domainId parameter");
        }
        Domain domain = _domainService.getDomain(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Unable to find domain by id=" + domainId);
        }
        Account account = _accountService.getActiveAccountByName(accountName, domainId);
        if (account != null && account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            if (!enabledOnly || account.getState() == Account.State.enabled) {
                return account.getId();
            } else {
                throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active");
            }
        } else {
            throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain id=" + domainId);
        }
    }
    if (projectId != null) {
        Project project = _projectService.getProject(projectId);
        if (project != null) {
            if (!enabledOnly || project.getState() == Project.State.Active) {
                return project.getProjectAccountId();
            } else {
                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, projectId, "projectId");
                throw ex;
            }
        } else {
            InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified projectId");
            ex.addProxyObject(project, projectId, "projectId");
            throw ex;
        }
    }
    return null;
}
Also used : Account(com.cloud.user.Account) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Domain(com.cloud.domain.Domain)

Example 42 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project CloudStack-archive by CloudStack-extras.

the class CreateTemplateCmd method getEntityOwnerId.

@Override
public long getEntityOwnerId() {
    Long volumeId = getVolumeId();
    Long snapshotId = getSnapshotId();
    Long accountId = null;
    if (volumeId != null) {
        Volume volume = _entityMgr.findById(Volume.class, volumeId);
        if (volume != null) {
            accountId = volume.getAccountId();
        } else {
            throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
        }
    } else {
        Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId);
        if (snapshot != null) {
            accountId = snapshot.getAccountId();
        } else {
            throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId);
        }
    }
    Account account = _accountService.getAccount(accountId);
    //Can create templates for enabled projects/accounts only
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        Project project = _projectService.findByProjectAccountId(accountId);
        if (project.getState() != Project.State.Active) {
            PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active");
            ex.addProxyObject(project, project.getId(), "projectId");
        }
    } else if (account.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of template is disabled: " + account);
    }
    return accountId;
}
Also used : Snapshot(com.cloud.storage.Snapshot) Account(com.cloud.user.Account) Project(com.cloud.projects.Project) Volume(com.cloud.storage.Volume) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 43 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class QueryManagerImpl method listProjectsInternal.

private Pair<List<ProjectJoinVO>, Integer> listProjectsInternal(ListProjectsCmd cmd) {
    Long id = cmd.getId();
    String name = cmd.getName();
    String displayText = cmd.getDisplayText();
    String state = cmd.getState();
    String accountName = cmd.getAccountName();
    Long domainId = cmd.getDomainId();
    String keyword = cmd.getKeyword();
    Long startIndex = cmd.getStartIndex();
    Long pageSize = cmd.getPageSizeVal();
    boolean listAll = cmd.listAll();
    boolean isRecursive = cmd.isRecursive();
    cmd.getTags();
    Account caller = CallContext.current().getCallingAccount();
    Long accountId = null;
    String path = null;
    Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize);
    SearchBuilder<ProjectJoinVO> sb = _projectJoinDao.createSearchBuilder();
    // select distinct
    sb.select(null, Func.DISTINCT, sb.entity().getId());
    if (_accountMgr.isAdmin(caller.getId())) {
        if (domainId != null) {
            DomainVO domain = _domainDao.findById(domainId);
            if (domain == null) {
                throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system");
            }
            _accountMgr.checkAccess(caller, domain);
            if (accountName != null) {
                Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
                if (owner == null) {
                    throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
                }
                accountId = owner.getId();
            }
        } else {
            // domainId == null
            if (accountName != null) {
                throw new InvalidParameterValueException("could not find account " + accountName + " because domain is not specified");
            }
        }
    } else {
        if (accountName != null && !accountName.equals(caller.getAccountName())) {
            throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized");
        }
        if (domainId != null && !domainId.equals(caller.getDomainId())) {
            throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized");
        }
        accountId = caller.getId();
    }
    if (domainId == null && accountId == null && (_accountMgr.isNormalUser(caller.getId()) || !listAll)) {
        accountId = caller.getId();
    } else if (_accountMgr.isDomainAdmin(caller.getId()) || (isRecursive && !listAll)) {
        DomainVO domain = _domainDao.findById(caller.getDomainId());
        path = domain.getPath();
    }
    if (path != null) {
        sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
    }
    if (accountId != null) {
        sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
    }
    SearchCriteria<ProjectJoinVO> sc = sb.create();
    if (id != null) {
        sc.addAnd("id", Op.EQ, id);
    }
    if (domainId != null && !isRecursive) {
        sc.addAnd("domainId", Op.EQ, domainId);
    }
    if (name != null) {
        sc.addAnd("name", Op.EQ, name);
    }
    if (displayText != null) {
        sc.addAnd("displayText", Op.EQ, displayText);
    }
    if (accountId != null) {
        sc.setParameters("accountId", accountId);
    }
    if (state != null) {
        sc.addAnd("state", Op.EQ, state);
    }
    if (keyword != null) {
        SearchCriteria<ProjectJoinVO> ssc = _projectJoinDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (path != null) {
        sc.setParameters("domainPath", path);
    }
    // search distinct projects to get count
    Pair<List<ProjectJoinVO>, Integer> uniquePrjPair = _projectJoinDao.searchAndCount(sc, searchFilter);
    Integer count = uniquePrjPair.second();
    if (count.intValue() == 0) {
        // handle empty result cases
        return uniquePrjPair;
    }
    List<ProjectJoinVO> uniquePrjs = uniquePrjPair.first();
    Long[] prjIds = new Long[uniquePrjs.size()];
    int i = 0;
    for (ProjectJoinVO v : uniquePrjs) {
        prjIds[i++] = v.getId();
    }
    List<ProjectJoinVO> prjs = _projectJoinDao.searchByIds(prjIds);
    return new Pair<List<ProjectJoinVO>, Integer>(prjs, count);
}
Also used : Account(com.cloud.user.Account) ProjectJoinVO(com.cloud.api.query.vo.ProjectJoinVO) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair)

Example 44 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class QueryManagerImpl method searchForServiceOfferingsInternal.

private Pair<List<ServiceOfferingJoinVO>, Integer> searchForServiceOfferingsInternal(ListServiceOfferingsCmd cmd) {
    // Note
    // The filteredOfferings method for offerings is being modified in accordance with
    // discussion with Will/Kevin
    // For now, we will be listing the following based on the usertype
    // 1. For root, we will filteredOfferings all offerings
    // 2. For domainAdmin and regular users, we will filteredOfferings everything in
    // their domains+parent domains ... all the way
    // till
    // root
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = (isAscending == null ? true : isAscending);
    Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
    Account caller = CallContext.current().getCallingAccount();
    Object name = cmd.getServiceOfferingName();
    Object id = cmd.getId();
    Object keyword = cmd.getKeyword();
    Long vmId = cmd.getVirtualMachineId();
    Long domainId = cmd.getDomainId();
    Boolean isSystem = cmd.getIsSystem();
    String vmTypeStr = cmd.getSystemVmType();
    ServiceOfferingVO currentVmOffering = null;
    Boolean isRecursive = cmd.isRecursive();
    SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
    if (!_accountMgr.isRootAdmin(caller.getId()) && isSystem) {
        throw new InvalidParameterValueException("Only ROOT admins can access system's offering");
    }
    // domain
    if (domainId != null && !_accountMgr.isRootAdmin(caller.getId())) {
        // child of so's domain
        if (!isPermissible(caller.getDomainId(), domainId)) {
            throw new PermissionDeniedException("The account:" + caller.getAccountName() + " does not fall in the same domain hierarchy as the service offering");
        }
    }
    if (vmId != null) {
        VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
        if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
            InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id");
            ex.addProxyObject(vmId.toString(), "vmId");
            throw ex;
        }
        _accountMgr.checkAccess(caller, null, true, vmInstance);
        currentVmOffering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
        sc.addAnd("id", SearchCriteria.Op.NEQ, currentVmOffering.getId());
        // 1. Only return offerings with the same storage type
        sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, currentVmOffering.getUseLocalStorage());
        // 2.In case vm is running return only offerings greater than equal to current offering compute.
        if (vmInstance.getState() == VirtualMachine.State.Running) {
            sc.addAnd("cpu", Op.GTEQ, currentVmOffering.getCpu());
            sc.addAnd("speed", Op.GTEQ, currentVmOffering.getSpeed());
            sc.addAnd("ramSize", Op.GTEQ, currentVmOffering.getRamSize());
        }
    }
    // boolean includePublicOfferings = false;
    if ((_accountMgr.isNormalUser(caller.getId()) || _accountMgr.isDomainAdmin(caller.getId())) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
        // For non-root users.
        if (isSystem) {
            throw new InvalidParameterValueException("Only root admins can access system's offering");
        }
        if (isRecursive) {
            // domain + all sub-domains
            if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL)
                throw new InvalidParameterValueException("Only ROOT admins and Domain admins can list service offerings with isrecursive=true");
            DomainVO domainRecord = _domainDao.findById(caller.getDomainId());
            sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domainRecord.getPath() + "%");
        } else {
            // domain + all ancestors
            // find all domain Id up to root domain for this account
            List<Long> domainIds = new ArrayList<Long>();
            DomainVO domainRecord;
            if (vmId != null) {
                UserVmVO vmInstance = _userVmDao.findById(vmId);
                domainRecord = _domainDao.findById(vmInstance.getDomainId());
                if (domainRecord == null) {
                    s_logger.error("Could not find the domainId for vmId:" + vmId);
                    throw new CloudAuthenticationException("Could not find the domainId for vmId:" + vmId);
                }
            } else {
                domainRecord = _domainDao.findById(caller.getDomainId());
                if (domainRecord == null) {
                    s_logger.error("Could not find the domainId for account:" + caller.getAccountName());
                    throw new CloudAuthenticationException("Could not find the domainId for account:" + caller.getAccountName());
                }
            }
            domainIds.add(domainRecord.getId());
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            SearchCriteria<ServiceOfferingJoinVO> spc = _srvOfferingJoinDao.createSearchCriteria();
            spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            // include public offering as well
            spc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
        }
    } else {
        // for root users
        if (caller.getDomainId() != 1 && isSystem) {
            // NON ROOT admin
            throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering");
        }
        if (domainId != null) {
            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
        }
    }
    if (keyword != null) {
        SearchCriteria<ServiceOfferingJoinVO> ssc = _srvOfferingJoinDao.createSearchCriteria();
        ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    }
    if (isSystem != null) {
        // note that for non-root users, isSystem is always false when
        // control comes to here
        sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem);
    }
    if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.EQ, name);
    }
    if (vmTypeStr != null) {
        sc.addAnd("vmType", SearchCriteria.Op.EQ, vmTypeStr);
    }
    Pair<List<ServiceOfferingJoinVO>, Integer> result = _srvOfferingJoinDao.searchAndCount(sc, searchFilter);
    //Couldn't figure out a smart way to filter offerings based on tags in sql so doing it in Java.
    List<ServiceOfferingJoinVO> filteredOfferings = filterOfferingsOnCurrentTags(result.first(), currentVmOffering);
    return new Pair<>(filteredOfferings, result.second());
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) ServiceOfferingJoinVO(com.cloud.api.query.vo.ServiceOfferingJoinVO) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) ArrayList(java.util.ArrayList) VMInstanceVO(com.cloud.vm.VMInstanceVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair)

Example 45 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method moveVMToUser.

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

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            //generate destroy vm event for usage
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());
            // update resource counts for old account
            resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
            // OWNERSHIP STEP 1: update the vm owner
            vm.setAccountId(newAccount.getAccountId());
            vm.setDomainId(cmd.getDomainId());
            _vmDao.persist(vm);
            // OS 2: update volume
            for (VolumeVO volume : volumes) {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
                _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
                _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
                volume.setAccountId(newAccount.getAccountId());
                volume.setDomainId(newAccount.getDomainId());
                _volsDao.persist(volume);
                _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
                _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
                //snapshots: mark these removed in db
                List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
                for (SnapshotVO snapshot : snapshots) {
                    _snapshotDao.remove(snapshot.getId());
                }
            }
            //update resource count of new account
            resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
            //generate usage events to account for this change
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());
        }
    });
    VirtualMachine vmoi = _itMgr.findById(vm.getId());
    VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);
    // OS 3: update the network
    List<Long> networkIdList = cmd.getNetworkIds();
    List<Long> securityGroupIdList = cmd.getSecurityGroupIdList();
    if (zone.getNetworkType() == NetworkType.Basic) {
        if (networkIdList != null && !networkIdList.isEmpty()) {
            throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM");
        }
        // cleanup the old security groups
        _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId());
        // cleanup the network for the oldOwner
        _networkMgr.cleanupNics(vmOldProfile);
        _networkMgr.expungeNics(vmOldProfile);
        // security groups will be recreated for the new account, when the
        // VM is started
        List<NetworkVO> networkList = new ArrayList<NetworkVO>();
        // Get default guest network in Basic zone
        Network defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId());
        if (defaultNetwork == null) {
            throw new InvalidParameterValueException("Unable to find a default network to start a vm");
        } else {
            networkList.add(_networkDao.findById(defaultNetwork.getId()));
        }
        boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware);
        if (securityGroupIdList != null && isVmWare) {
            throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
        } else if (!isVmWare && _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkModel.canAddDefaultSecurityGroup()) {
            if (securityGroupIdList == null) {
                securityGroupIdList = new ArrayList<Long>();
            }
            SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccount.getId());
            if (defaultGroup != null) {
                // check if security group id list already contains Default
                // security group, and if not - add it
                boolean defaultGroupPresent = false;
                for (Long securityGroupId : securityGroupIdList) {
                    if (securityGroupId.longValue() == defaultGroup.getId()) {
                        defaultGroupPresent = true;
                        break;
                    }
                }
                if (!defaultGroupPresent) {
                    securityGroupIdList.add(defaultGroup.getId());
                }
            } else {
                // create default security group for the account
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one");
                }
                defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName());
                securityGroupIdList.add(defaultGroup.getId());
            }
        }
        LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
        NicProfile profile = new NicProfile();
        profile.setDefaultNic(true);
        networks.put(networkList.get(0), new ArrayList<NicProfile>(Arrays.asList(profile)));
        VirtualMachine vmi = _itMgr.findById(vm.getId());
        VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
        _networkMgr.allocate(vmProfile, networks);
        _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
        s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
    } else {
        if (zone.isSecurityGroupEnabled()) {
            // advanced zone with security groups
            // cleanup the old security groups
            _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId());
            Set<NetworkVO> applicableNetworks = new HashSet<NetworkVO>();
            String requestedIPv4ForDefaultNic = null;
            String requestedIPv6ForDefaultNic = null;
            // if networkIdList is null and the first network of vm is shared network, then keep it if possible
            if (networkIdList == null || networkIdList.isEmpty()) {
                NicVO defaultNicOld = _nicDao.findDefaultNicForVM(vm.getId());
                if (defaultNicOld != null) {
                    NetworkVO defaultNetworkOld = _networkDao.findById(defaultNicOld.getNetworkId());
                    if (defaultNetworkOld != null && defaultNetworkOld.getGuestType() == Network.GuestType.Shared && defaultNetworkOld.getAclType() == ACLType.Domain) {
                        try {
                            _networkModel.checkNetworkPermissions(newAccount, defaultNetworkOld);
                            applicableNetworks.add(defaultNetworkOld);
                            requestedIPv4ForDefaultNic = defaultNicOld.getIPv4Address();
                            requestedIPv6ForDefaultNic = defaultNicOld.getIPv6Address();
                            s_logger.debug("AssignVM: use old shared network " + defaultNetworkOld.getName() + " with old ip " + requestedIPv4ForDefaultNic + " on default nic of vm:" + vm.getInstanceName());
                        } catch (PermissionDeniedException e) {
                            s_logger.debug("AssignVM: the shared network on old default nic can not be applied to new account");
                        }
                    }
                }
            }
            // cleanup the network for the oldOwner
            _networkMgr.cleanupNics(vmOldProfile);
            _networkMgr.expungeNics(vmOldProfile);
            if (networkIdList != null && !networkIdList.isEmpty()) {
                // add any additional networks
                for (Long networkId : networkIdList) {
                    NetworkVO network = _networkDao.findById(networkId);
                    if (network == null) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
                        ex.addProxyObject(networkId.toString(), "networkId");
                        throw ex;
                    }
                    _networkModel.checkNetworkPermissions(newAccount, network);
                    // don't allow to use system networks
                    NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
                    if (networkOffering.isSystemOnly()) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
                        ex.addProxyObject(network.getUuid(), "networkId");
                        throw ex;
                    }
                    applicableNetworks.add(network);
                }
            }
            // add the new nics
            LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
            int toggle = 0;
            NetworkVO defaultNetwork = null;
            for (NetworkVO appNet : applicableNetworks) {
                NicProfile defaultNic = new NicProfile();
                if (toggle == 0) {
                    defaultNic.setDefaultNic(true);
                    defaultNic.setRequestedIPv4(requestedIPv4ForDefaultNic);
                    defaultNic.setRequestedIPv6(requestedIPv6ForDefaultNic);
                    defaultNetwork = appNet;
                    toggle++;
                }
                networks.put(appNet, new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
            }
            boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware);
            if (securityGroupIdList != null && isVmWare) {
                throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
            } else if (!isVmWare && (defaultNetwork == null || _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork)) && _networkModel.canAddDefaultSecurityGroup()) {
                if (securityGroupIdList == null) {
                    securityGroupIdList = new ArrayList<Long>();
                }
                SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccount.getId());
                if (defaultGroup != null) {
                    // check if security group id list already contains Default
                    // security group, and if not - add it
                    boolean defaultGroupPresent = false;
                    for (Long securityGroupId : securityGroupIdList) {
                        if (securityGroupId.longValue() == defaultGroup.getId()) {
                            defaultGroupPresent = true;
                            break;
                        }
                    }
                    if (!defaultGroupPresent) {
                        securityGroupIdList.add(defaultGroup.getId());
                    }
                } else {
                    // create default security group for the account
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one");
                    }
                    defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName());
                    securityGroupIdList.add(defaultGroup.getId());
                }
            }
            VirtualMachine vmi = _itMgr.findById(vm.getId());
            VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
            if (applicableNetworks.isEmpty()) {
                throw new InvalidParameterValueException("No network is specified, please specify one when you move the vm. For now, please add a network to VM on NICs tab.");
            } else {
                _networkMgr.allocate(vmProfile, networks);
            }
            _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
            s_logger.debug("AssignVM: Advanced zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
        } else {
            if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) {
                throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone");
            }
            Set<NetworkVO> applicableNetworks = new HashSet<NetworkVO>();
            // if networkIdList is null and the first network of vm is shared network, then keep it if possible
            if (networkIdList == null || networkIdList.isEmpty()) {
                NicVO defaultNicOld = _nicDao.findDefaultNicForVM(vm.getId());
                if (defaultNicOld != null) {
                    NetworkVO defaultNetworkOld = _networkDao.findById(defaultNicOld.getNetworkId());
                    if (defaultNetworkOld != null && defaultNetworkOld.getGuestType() == Network.GuestType.Shared && defaultNetworkOld.getAclType() == ACLType.Domain) {
                        try {
                            _networkModel.checkNetworkPermissions(newAccount, defaultNetworkOld);
                            applicableNetworks.add(defaultNetworkOld);
                        } catch (PermissionDeniedException e) {
                            s_logger.debug("AssignVM: the shared network on old default nic can not be applied to new account");
                        }
                    }
                }
            }
            // cleanup the network for the oldOwner
            _networkMgr.cleanupNics(vmOldProfile);
            _networkMgr.expungeNics(vmOldProfile);
            if (networkIdList != null && !networkIdList.isEmpty()) {
                // add any additional networks
                for (Long networkId : networkIdList) {
                    NetworkVO network = _networkDao.findById(networkId);
                    if (network == null) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
                        ex.addProxyObject(networkId.toString(), "networkId");
                        throw ex;
                    }
                    _networkModel.checkNetworkPermissions(newAccount, network);
                    // don't allow to use system networks
                    NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
                    if (networkOffering.isSystemOnly()) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
                        ex.addProxyObject(network.getUuid(), "networkId");
                        throw ex;
                    }
                    applicableNetworks.add(network);
                }
            } else if (applicableNetworks.isEmpty()) {
                NetworkVO defaultNetwork = null;
                List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
                if (requiredOfferings.size() < 1) {
                    throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation");
                }
                if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
                    // get Virtual networks
                    List<? extends Network> virtualNetworks = _networkModel.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated);
                    if (virtualNetworks.isEmpty()) {
                        long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
                        // Validate physical network
                        PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
                        if (physicalNetwork == null) {
                            throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + requiredOfferings.get(0).getTags());
                        }
                        s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process");
                        Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null);
                        // if the network offering has persistent set to true, implement the network
                        if (requiredOfferings.get(0).getIsPersistent()) {
                            DeployDestination dest = new DeployDestination(zone, null, null, null);
                            UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
                            Journal journal = new Journal.LogJournal("Implementing " + newNetwork, s_logger);
                            ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
                            s_logger.debug("Implementing the network for account" + newNetwork + " as a part of" + " network provision for persistent networks");
                            try {
                                Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(newNetwork.getId(), dest, context);
                                if (implementedNetwork == null || implementedNetwork.first() == null) {
                                    s_logger.warn("Failed to implement the network " + newNetwork);
                                }
                                newNetwork = implementedNetwork.second();
                            } catch (Exception ex) {
                                s_logger.warn("Failed to implement network " + newNetwork + " elements and" + " resources as a part of network provision for persistent network due to ", ex);
                                CloudRuntimeException e = new CloudRuntimeException("Failed to implement network" + " (with specified id) elements and resources as a part of network provision");
                                e.addProxyObject(newNetwork.getUuid(), "networkId");
                                throw e;
                            }
                        }
                        defaultNetwork = _networkDao.findById(newNetwork.getId());
                    } else if (virtualNetworks.size() > 1) {
                        throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + "; please specify networkIds");
                    } else {
                        defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
                    }
                } else {
                    throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
                }
                applicableNetworks.add(defaultNetwork);
            }
            // add the new nics
            LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
            int toggle = 0;
            for (NetworkVO appNet : applicableNetworks) {
                NicProfile defaultNic = new NicProfile();
                if (toggle == 0) {
                    defaultNic.setDefaultNic(true);
                    toggle++;
                }
                networks.put(appNet, new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
            }
            VirtualMachine vmi = _itMgr.findById(vm.getId());
            VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
            _networkMgr.allocate(vmProfile, networks);
            s_logger.debug("AssignVM: Advance virtual, adding networks no " + networks.size() + " to " + vm.getInstanceName());
        }
    // END IF NON SEC GRP ENABLED
    }
    // END IF ADVANCED
    s_logger.info("AssignVM: vm " + vm.getInstanceName() + " now belongs to account " + newAccount.getAccountName());
    return vm;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) Journal(com.cloud.utils.Journal) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) LinkedHashMap(java.util.LinkedHashMap) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) HashSet(java.util.HashSet) DataCenterVO(com.cloud.dc.DataCenterVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) NetworkVO(com.cloud.network.dao.NetworkVO) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) SecurityGroup(com.cloud.network.security.SecurityGroup) DomainVO(com.cloud.domain.DomainVO) DeployDestination(com.cloud.deploy.DeployDestination) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair) NetworkOffering(com.cloud.offering.NetworkOffering) NetworkGuru(com.cloud.network.guru.NetworkGuru) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) UserVO(com.cloud.user.UserVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

PermissionDeniedException (com.cloud.exception.PermissionDeniedException)82 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)70 Account (com.cloud.user.Account)69 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 ActionEvent (com.cloud.event.ActionEvent)23 ArrayList (java.util.ArrayList)22 Project (com.cloud.projects.Project)16 DB (com.cloud.utils.db.DB)15 HashMap (java.util.HashMap)15 DataCenterVO (com.cloud.dc.DataCenterVO)13 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)13 ConfigurationException (javax.naming.ConfigurationException)13 DomainVO (com.cloud.domain.DomainVO)11 Pair (com.cloud.utils.Pair)11 List (java.util.List)11 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)10 VolumeVO (com.cloud.storage.VolumeVO)10 TransactionStatus (com.cloud.utils.db.TransactionStatus)10 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)8