Search in sources :

Example 96 with ConcurrentOperationException

use of com.cloud.legacymodel.exceptions.ConcurrentOperationException in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method deleteVpcPrivateGateway.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_DELETE, eventDescription = "deleting private gateway")
@DB
public boolean deleteVpcPrivateGateway(final long gatewayId) throws ConcurrentOperationException, ResourceUnavailableException {
    final VpcGatewayVO gatewayVO = _vpcGatewayDao.acquireInLockTable(gatewayId);
    if (gatewayVO == null || gatewayVO.getType() != VpcGateway.Type.Private) {
        throw new ConcurrentOperationException("Unable to lock gateway " + gatewayId);
    }
    try {
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                // don't allow to remove gateway when there are static routes pointing to an ipaddress in the private gateway CIDR.
                final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcIdAndNotRevoked(gatewayVO.getVpcId());
                final NetworkVO network = _ntwkDao.findById(gatewayVO.getNetworkId());
                final List<String> wrongCidrs = new LinkedList<>();
                for (final StaticRoute route : routes) {
                    if (NetUtils.isIpWithtInCidrRange(route.getGwIpAddress(), network.getCidr())) {
                        wrongCidrs.add(route.getCidr());
                    }
                }
                if (!wrongCidrs.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to delete Private Gateway. Please remove these static routes pointing to the private gateway CIDR" + " before attempting to delete the gateway: " + wrongCidrs);
                }
                gatewayVO.setState(VpcGateway.State.Deleting);
                _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO);
                s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Deleting);
            }
        });
        // Delete the gateway on the backend
        final List<Provider> providersToImplement = getVpcProviders(gatewayVO.getVpcId());
        final PrivateGateway gateway = getVpcPrivateGateway(gatewayId);
        for (final VpcProvider provider : getVpcElements()) {
            if (providersToImplement.contains(provider.getProvider())) {
                if (provider.deletePrivateGateway(gateway)) {
                    s_logger.debug("Private gateway " + gateway + " was applied succesfully on the backend");
                } else {
                    s_logger.warn("Private gateway " + gateway + " failed to apply on the backend");
                    gatewayVO.setState(VpcGateway.State.Ready);
                    _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO);
                    s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Ready);
                    return false;
                }
            }
        }
        return deletePrivateGatewayFromTheDB(gateway);
    } finally {
        _vpcGatewayDao.releaseFromLockTable(gatewayId);
    }
}
Also used : StaticRoute(com.cloud.legacymodel.network.vpc.StaticRoute) NetworkVO(com.cloud.network.dao.NetworkVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) VpcProvider(com.cloud.network.element.VpcProvider) Provider(com.cloud.legacymodel.network.Network.Provider) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) VpcProvider(com.cloud.network.element.VpcProvider) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 97 with ConcurrentOperationException

use of com.cloud.legacymodel.exceptions.ConcurrentOperationException in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method createVpcPrivateGateway.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating VPC private gateway", create = true)
public PrivateGateway createVpcPrivateGateway(final long vpcId, final String ipAddress, final String gateway, final String netmask, final long gatewayDomainId, final Long networkId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    // Validate parameters
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
        ex.addProxyObject(String.valueOf(vpcId), "VPC");
        throw ex;
    }
    // permission check on the VPC
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    _accountMgr.checkAccess(caller, null, false, vpc);
    if (gateway != null || netmask != null) {
        throw new InvalidParameterValueException("Gateway/netmask fields are not supported anymore");
    }
    final Network privateNtwk = _ntwkDao.findById(networkId);
    if (privateNtwk == null) {
        throw new InvalidParameterValueException("The private network specified could not be found.");
    }
    if (privateNtwk.getDomainId() != vpc.getDomainId() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new InvalidParameterValueException("VPC '" + vpc.getName() + "' does not have permission to operate on private network '" + privateNtwk.getName() + "' as they need to belong to the same domain.");
    }
    if (NetUtils.isNetworkAWithinNetworkB(privateNtwk.getCidr(), vpc.getCidr())) {
        throw new InvalidParameterValueException("CIDR of the private network to be connected " + privateNtwk.getCidr() + " should be outside of the VPC super CIDR " + vpc.getCidr());
    }
    if (!NetUtils.isIpWithtInCidrRange(ipAddress, privateNtwk.getCidr())) {
        throw new InvalidParameterValueException("The specified ip address for the private network " + ipAddress + " should be within the CIDR of the private network " + privateNtwk.getCidr());
    }
    final SortedSet<Long> availableIps = _ntwkModel.getAvailableIps(privateNtwk, ipAddress);
    if (availableIps == null || availableIps.isEmpty()) {
        throw new InvalidParameterValueException("The requested ip address " + ipAddress + " is not available in private network " + privateNtwk.getName());
    }
    final Long privateNetworkId = privateNtwk.getId();
    final List<PrivateGateway> privateGateways = getVpcPrivateGateways(vpcId);
    for (final PrivateGateway privateGateway : privateGateways) {
        if (privateNetworkId == privateGateway.getNetworkId()) {
            throw new InvalidParameterValueException("VPC with uuid " + vpc.getUuid() + " is already connected to network '" + privateNtwk.getName() + "'");
        }
    }
    final VpcGatewayVO gatewayVO;
    try {
        gatewayVO = Transaction.execute(new TransactionCallbackWithException<VpcGatewayVO, Exception>() {

            @Override
            public VpcGatewayVO doInTransaction(final TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
                // create the nic/ip as createPrivateNetwork doesn't do that work for us now
                s_logger.info("found and using existing network for vpc " + vpc + ": " + privateNtwk.getBroadcastUri());
                final DataCenterVO dc = _dcDao.lockRow(vpc.getZoneId(), true);
                // add entry to private_ip_address table
                PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
                if (privateIp != null) {
                    throw new InvalidParameterValueException("Private IP address " + ipAddress + " already used for private gateway in zone " + _entityMgr.findById(DataCenter.class, vpc.getZoneId()).getName());
                }
                final Long mac = dc.getMacAddress();
                final Long nextMac = mac + 1;
                dc.setMacAddress(nextMac);
                s_logger.info("creating private IP address for VPC (" + ipAddress + ", " + privateNtwk.getId() + ", " + nextMac + ", " + vpcId + ", " + isSourceNat + ")");
                privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, isSourceNat);
                _privateIpDao.persist(privateIp);
                _dcDao.update(dc.getId(), dc);
                long networkAclId = NetworkACL.DEFAULT_DENY;
                if (aclId != null) {
                    final NetworkACLVO aclVO = _networkAclDao.findById(aclId);
                    if (aclVO == null) {
                        throw new InvalidParameterValueException("Invalid network acl id passed ");
                    }
                    if (aclVO.getVpcId() != vpcId && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
                        throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
                    }
                    networkAclId = aclId;
                }
                // 2) create gateway entry
                final VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
                _vpcGatewayDao.persist(gatewayVO);
                s_logger.debug("Created vpc gateway entry " + gatewayVO);
                return gatewayVO;
            }
        });
    } catch (final Exception e) {
        ExceptionUtil.rethrowRuntime(e);
        ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
        ExceptionUtil.rethrow(e, ResourceAllocationException.class);
        throw new IllegalStateException(e);
    }
    CallContext.current().setEventDetails("Private Gateway Id: " + gatewayVO.getId());
    return getVpcPrivateGateway(gatewayVO.getId());
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.legacymodel.user.Account) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) Vpc(com.cloud.legacymodel.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(com.cloud.context.CallContext) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ExecutionException(java.util.concurrent.ExecutionException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ServerApiException(com.cloud.api.ServerApiException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) DataCenter(com.cloud.legacymodel.dc.DataCenter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 98 with ConcurrentOperationException

use of com.cloud.legacymodel.exceptions.ConcurrentOperationException in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method attachVolumeToVM.

public Volume attachVolumeToVM(final Long vmId, final Long volumeId, final Long deviceId) {
    final Account caller = CallContext.current().getCallingAccount();
    // Check that the volume ID is valid
    final VolumeInfo volumeToAttach = this.volFactory.getVolume(volumeId);
    // Check that the volume is a data volume
    if (volumeToAttach == null || !(volumeToAttach.getVolumeType() == VolumeType.DATADISK || volumeToAttach.getVolumeType() == VolumeType.ROOT)) {
        throw new InvalidParameterValueException("Please specify a volume with the valid type: " + VolumeType.ROOT.toString() + " or " + VolumeType.DATADISK.toString());
    }
    // Check that the volume is not currently attached to any VM
    if (volumeToAttach.getInstanceId() != null) {
        throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
    }
    // Check that the volume is not destroyed
    if (volumeToAttach.getState() == Volume.State.Destroy) {
        throw new InvalidParameterValueException("Please specify a volume that is not destroyed.");
    }
    // Check that the virtual machine ID is valid and it's a user vm
    final UserVmVO vm = this._userVmDao.findById(vmId);
    if (vm == null || vm.getType() != VirtualMachineType.User) {
        throw new InvalidParameterValueException("Please specify a valid User VM.");
    }
    // Check that the VM is in the correct state
    if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
        throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
    }
    // Check that the VM and the volume are in the same zone
    if (vm.getDataCenterId() != volumeToAttach.getDataCenterId()) {
        throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.");
    }
    // Check that the device ID is valid
    if (deviceId != null) {
        // validate ROOT volume type
        if (deviceId.longValue() == 0) {
            validateRootVolumeDetachAttach(this._volsDao.findById(volumeToAttach.getId()), vm);
            // vm shouldn't have any volume with deviceId 0
            if (!this._volsDao.findByInstanceAndDeviceId(vm.getId(), 0).isEmpty()) {
                throw new InvalidParameterValueException("Vm already has root volume attached to it");
            }
            // volume can't be in Uploaded state
            if (volumeToAttach.getState() == Volume.State.Uploaded) {
                throw new InvalidParameterValueException("No support for Root volume attach in state " + Volume.State.Uploaded);
            }
        }
    }
    // that supported by hypervisor
    if (deviceId == null || deviceId.longValue() != 0) {
        final List<VolumeVO> existingDataVolumes = this._volsDao.findByInstanceAndType(vmId, VolumeType.DATADISK);
        final int maxDataVolumesSupported = getMaxDataVolumesSupported(vm);
        if (existingDataVolumes.size() >= maxDataVolumesSupported) {
            throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxDataVolumesSupported + "). Please specify another" + " VM.");
        }
    }
    // if target VM has associated VM snapshots
    final List<VMSnapshotVO> vmSnapshots = this._vmSnapshotDao.findByVm(vmId);
    if (vmSnapshots.size() > 0) {
        throw new InvalidParameterValueException("Unable to attach volume, please specify a VM that does not have VM snapshots");
    }
    // permission check
    this._accountMgr.checkAccess(caller, null, true, volumeToAttach, vm);
    if (!(Volume.State.Allocated.equals(volumeToAttach.getState()) || Volume.State.Ready.equals(volumeToAttach.getState()) || Volume.State.Uploaded.equals(volumeToAttach.getState()))) {
        throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state");
    }
    final Account owner = this._accountDao.findById(volumeToAttach.getAccountId());
    if (!(volumeToAttach.getState() == Volume.State.Allocated || volumeToAttach.getState() == Volume.State.Ready)) {
        try {
            this._resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, volumeToAttach.getSize());
        } catch (final ResourceAllocationException e) {
            s_logger.error("primary storage resource limit check failed", e);
            throw new InvalidParameterValueException(e.getMessage());
        }
    }
    final HypervisorType rootDiskHyperType = vm.getHypervisorType();
    final HypervisorType volumeToAttachHyperType = this._volsDao.getHypervisorType(volumeToAttach.getId());
    final StoragePoolVO volumeToAttachStoragePool = this._storagePoolDao.findById(volumeToAttach.getPoolId());
    // only perform this check if the volume's storage pool is not null and not managed
    if (volumeToAttachStoragePool != null && !volumeToAttachStoragePool.isManaged()) {
        if (volumeToAttachHyperType != HypervisorType.None && rootDiskHyperType != volumeToAttachHyperType) {
            throw new InvalidParameterValueException("Can't attach a volume created by: " + volumeToAttachHyperType + " to a " + rootDiskHyperType + " vm");
        }
    }
    final AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (asyncExecutionContext != null) {
        final AsyncJob job = asyncExecutionContext.getJob();
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Trying to attaching volume " + volumeId + " to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
        }
        this._jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
    }
    final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        final VmWorkJobVO placeHolder;
        placeHolder = createPlaceHolderWork(vmId);
        try {
            return orchestrateAttachVolumeToVM(vmId, volumeId, deviceId, volumeToAttach.getDiskController());
        } finally {
            this._workJobDao.expunge(placeHolder.getId());
        }
    } else {
        final Outcome<Volume> outcome = attachVolumeToVmThroughJobQueue(vmId, volumeId, deviceId, volumeToAttach.getDiskController());
        Volume vol = null;
        try {
            outcome.get();
        } catch (final InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (final java.util.concurrent.ExecutionException e) {
            throw new RuntimeException("Execution excetion", e);
        }
        final Object jobResult = this._jobMgr.unmarshallResultObject(outcome.getJob());
        if (jobResult != null) {
            if (jobResult instanceof ConcurrentOperationException) {
                throw (ConcurrentOperationException) jobResult;
            } else if (jobResult instanceof InvalidParameterValueException) {
                throw (InvalidParameterValueException) jobResult;
            } else if (jobResult instanceof RuntimeException) {
                throw (RuntimeException) jobResult;
            } else if (jobResult instanceof Throwable) {
                throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
            } else if (jobResult instanceof Long) {
                vol = this._volsDao.findById((Long) jobResult);
            }
        }
        return vol;
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) AsyncJob(com.cloud.framework.jobs.AsyncJob) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) HypervisorType(com.cloud.model.enumeration.HypervisorType) ExecutionException(java.util.concurrent.ExecutionException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) Volume(com.cloud.legacymodel.storage.Volume) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) VmWorkResizeVolume(com.cloud.vm.VmWorkResizeVolume) VmWorkAttachVolume(com.cloud.vm.VmWorkAttachVolume) VmWorkExtractVolume(com.cloud.vm.VmWorkExtractVolume) DataObject(com.cloud.engine.subsystem.api.storage.DataObject)

Example 99 with ConcurrentOperationException

use of com.cloud.legacymodel.exceptions.ConcurrentOperationException in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method extractVolume.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
public String extractVolume(final ExtractVolumeCmd cmd) {
    final Long volumeId = cmd.getId();
    final Long zoneId = cmd.getZoneId();
    final String mode = cmd.getMode();
    final Account account = CallContext.current().getCallingAccount();
    if (!this._accountMgr.isRootAdmin(account.getId()) && ApiDBUtils.isExtractionDisabled()) {
        throw new PermissionDeniedException("Extraction has been disabled by admin");
    }
    final VolumeVO volume = this._volsDao.findById(volumeId);
    if (volume == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
        ex.addProxyObject(volumeId.toString(), "volumeId");
        throw ex;
    }
    // perform permission check
    this._accountMgr.checkAccess(account, null, true, volume);
    if (this._dcDao.findById(zoneId) == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    if (volume.getPoolId() == null) {
        throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
    }
    // instance is stopped
    if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
        s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state.");
        final PermissionDeniedException ex = new PermissionDeniedException("Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
        ex.addProxyObject(volume.getUuid(), "volumeId");
        throw ex;
    }
    if (volume.getVolumeType() != VolumeType.DATADISK) {
        // Datadisk dont have any template dependence.
        final VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        if (template != null) {
            // For ISO based volumes template = null and
            // we allow extraction of all ISO based
            // volumes
            final boolean isExtractable = template.isExtractable() && template.getTemplateType() != TemplateType.SYSTEM;
            if (!isExtractable && account != null && !this._accountMgr.isRootAdmin(account.getId())) {
                // Global admins are always allowed to extract
                final PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
                ex.addProxyObject(volume.getUuid(), "volumeId");
                throw ex;
            }
        }
    }
    if (mode == null || !mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString())) {
        throw new InvalidParameterValueException("Please specify a valid extract Mode ");
    }
    // Check if the url already exists
    final VolumeDataStoreVO volumeStoreRef = this._volumeStoreDao.findByVolume(volumeId);
    if (volumeStoreRef != null && volumeStoreRef.getExtractUrl() != null) {
        return volumeStoreRef.getExtractUrl();
    }
    VMInstanceVO vm = null;
    if (volume.getInstanceId() != null) {
        vm = this._vmInstanceDao.findById(volume.getInstanceId());
    }
    if (vm != null) {
        // serialize VM operation
        final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
        if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
            // avoid re-entrance
            final VmWorkJobVO placeHolder;
            placeHolder = createPlaceHolderWork(vm.getId());
            try {
                return orchestrateExtractVolume(volume.getId(), zoneId);
            } finally {
                this._workJobDao.expunge(placeHolder.getId());
            }
        } else {
            final Outcome<String> outcome = extractVolumeThroughJobQueue(vm.getId(), volume.getId(), zoneId);
            try {
                outcome.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException("Operation is interrupted", e);
            } catch (final java.util.concurrent.ExecutionException e) {
                throw new RuntimeException("Execution excetion", e);
            }
            final Object jobResult = this._jobMgr.unmarshallResultObject(outcome.getJob());
            if (jobResult != null) {
                if (jobResult instanceof ConcurrentOperationException) {
                    throw (ConcurrentOperationException) jobResult;
                } else if (jobResult instanceof RuntimeException) {
                    throw (RuntimeException) jobResult;
                } else if (jobResult instanceof Throwable) {
                    throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
                }
            }
            // retrieve the entity url from job result
            if (jobResult != null && jobResult instanceof String) {
                return (String) jobResult;
            }
            return null;
        }
    }
    return orchestrateExtractVolume(volume.getId(), zoneId);
}
Also used : Account(com.cloud.legacymodel.user.Account) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) VMInstanceVO(com.cloud.vm.VMInstanceVO) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) ExecutionException(java.util.concurrent.ExecutionException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) VolumeDataStoreVO(com.cloud.storage.datastore.db.VolumeDataStoreVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DataObject(com.cloud.engine.subsystem.api.storage.DataObject) ActionEvent(com.cloud.event.ActionEvent)

Example 100 with ConcurrentOperationException

use of com.cloud.legacymodel.exceptions.ConcurrentOperationException in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method detachVolumeFromVM.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_DETACH, eventDescription = "detaching volume", async = true)
public Volume detachVolumeFromVM(final DetachVolumeCmd cmmd) {
    final Account caller = CallContext.current().getCallingAccount();
    if (cmmd.getId() == null && cmmd.getDeviceId() == null && cmmd.getVirtualMachineId() == null || cmmd.getId() != null && (cmmd.getDeviceId() != null || cmmd.getVirtualMachineId() != null) || cmmd.getId() == null && (cmmd.getDeviceId() == null || cmmd.getVirtualMachineId() == null)) {
        throw new InvalidParameterValueException("Please provide either a volume id, or a tuple(device id, instance id)");
    }
    final Long volumeId = cmmd.getId();
    final VolumeVO volume;
    if (volumeId != null) {
        volume = this._volsDao.findById(volumeId);
    } else {
        volume = this._volsDao.findByInstanceAndDeviceId(cmmd.getVirtualMachineId(), cmmd.getDeviceId()).get(0);
    }
    // Check that the volume ID is valid
    if (volume == null) {
        throw new InvalidParameterValueException("Unable to find volume with ID: " + volumeId);
    }
    final Long vmId;
    if (cmmd.getVirtualMachineId() == null) {
        vmId = volume.getInstanceId();
    } else {
        vmId = cmmd.getVirtualMachineId();
    }
    // Permissions check
    this._accountMgr.checkAccess(caller, null, true, volume);
    // Check that the volume is currently attached to a VM
    if (vmId == null) {
        throw new InvalidParameterValueException("The specified volume is not attached to a VM.");
    }
    // Check that the VM is in the correct state
    final UserVmVO vm = this._userVmDao.findById(vmId);
    if (vm.getState() != State.Running && vm.getState() != State.Stopped && vm.getState() != State.Destroyed) {
        throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
    }
    // Check that the volume is a data/root volume
    if (!(volume.getVolumeType() == VolumeType.ROOT || volume.getVolumeType() == VolumeType.DATADISK)) {
        throw new InvalidParameterValueException("Please specify volume of type " + VolumeType.DATADISK.toString() + " or " + VolumeType.ROOT.toString());
    }
    // Root volume detach is allowed for following hypervisors: Xen/KVM/VmWare
    if (volume.getVolumeType() == VolumeType.ROOT) {
        validateRootVolumeDetachAttach(volume, vm);
    }
    // Don't allow detach if target VM has associated VM snapshots
    final List<VMSnapshotVO> vmSnapshots = this._vmSnapshotDao.findByVm(vmId);
    if (vmSnapshots.size() > 0) {
        throw new InvalidParameterValueException("Unable to detach volume, please specify a VM that does not have VM snapshots");
    }
    final AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (asyncExecutionContext != null) {
        final AsyncJob job = asyncExecutionContext.getJob();
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Trying to attaching volume " + volumeId + "to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
        }
        this._jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
    }
    final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        final VmWorkJobVO placeHolder;
        placeHolder = createPlaceHolderWork(vmId);
        try {
            return orchestrateDetachVolumeFromVM(vmId, volumeId);
        } finally {
            this._workJobDao.expunge(placeHolder.getId());
        }
    } else {
        final Outcome<Volume> outcome = detachVolumeFromVmThroughJobQueue(vmId, volumeId);
        Volume vol = null;
        try {
            outcome.get();
        } catch (final InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (final java.util.concurrent.ExecutionException e) {
            throw new RuntimeException("Execution excetion", e);
        }
        final Object jobResult = this._jobMgr.unmarshallResultObject(outcome.getJob());
        if (jobResult != null) {
            if (jobResult instanceof ConcurrentOperationException) {
                throw (ConcurrentOperationException) jobResult;
            } else if (jobResult instanceof RuntimeException) {
                throw (RuntimeException) jobResult;
            } else if (jobResult instanceof Throwable) {
                throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
            } else if (jobResult instanceof Long) {
                vol = this._volsDao.findById((Long) jobResult);
            }
        }
        return vol;
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) AsyncJob(com.cloud.framework.jobs.AsyncJob) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) ExecutionException(java.util.concurrent.ExecutionException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Volume(com.cloud.legacymodel.storage.Volume) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) VmWorkResizeVolume(com.cloud.vm.VmWorkResizeVolume) VmWorkAttachVolume(com.cloud.vm.VmWorkAttachVolume) VmWorkExtractVolume(com.cloud.vm.VmWorkExtractVolume) DataObject(com.cloud.engine.subsystem.api.storage.DataObject) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)101 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)63 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)58 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)50 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)37 ServerApiException (com.cloud.api.ServerApiException)30 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)28 Account (com.cloud.legacymodel.user.Account)23 AsyncJobExecutionContext (com.cloud.framework.jobs.AsyncJobExecutionContext)20 VmWorkJobVO (com.cloud.framework.jobs.impl.VmWorkJobVO)20 VirtualMachine (com.cloud.legacymodel.vm.VirtualMachine)20 DB (com.cloud.utils.db.DB)19 InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)17 NoTransitionException (com.cloud.legacymodel.exceptions.NoTransitionException)17 ConfigurationException (javax.naming.ConfigurationException)16 OperationTimedoutException (com.cloud.legacymodel.exceptions.OperationTimedoutException)14 Network (com.cloud.legacymodel.network.Network)14 ActionEvent (com.cloud.event.ActionEvent)13 NetworkVO (com.cloud.network.dao.NetworkVO)13 VirtualMachineMigrationException (com.cloud.legacymodel.exceptions.VirtualMachineMigrationException)12