Search in sources :

Example 91 with ConcurrentOperationException

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

the class LoadBalanceRuleHandler method deployELBVm.

private DomainRouterVO deployELBVm(Network guestNetwork, final DeployDestination dest, Account owner, final Map<Param, Object> params) throws ConcurrentOperationException, InsufficientCapacityException {
    final long dcId = dest.getDataCenter().getId();
    // lock guest network
    final Long guestNetworkId = guestNetwork.getId();
    guestNetwork = _networkDao.acquireInLockTable(guestNetworkId);
    if (guestNetwork == null) {
        throw new ConcurrentOperationException("Unable to acquire network lock: " + guestNetworkId);
    }
    try {
        if (_networkModel.isNetworkSystem(guestNetwork) || guestNetwork.getGuestType() == Network.GuestType.Shared) {
            owner = _accountService.getSystemAccount();
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Starting a ELB vm for network configurations: " + guestNetwork + " in " + dest);
        }
        assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: " + guestNetwork;
        DataCenterDeployment plan = null;
        DomainRouterVO elbVm = null;
        plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null, null);
        if (elbVm == null) {
            final long id = _routerDao.getNextInSequence(Long.class, "id");
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating the ELB vm " + id);
            }
            final List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork);
            final NetworkOffering controlOffering = offerings.get(0);
            final Network controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0);
            final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(2);
            final NicProfile guestNic = new NicProfile();
            guestNic.setDefaultNic(true);
            networks.put(controlConfig, new ArrayList<NicProfile>());
            networks.put(guestNetwork, new ArrayList<NicProfile>(Arrays.asList(guestNic)));
            final VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId);
            final String typeString = "ElasticLoadBalancerVm";
            final Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork);
            final PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, typeString);
            if (provider == null) {
                throw new CloudRuntimeException("Cannot find service provider " + typeString + " in physical network " + physicalNetworkId);
            }
            final VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm);
            if (vrProvider == null) {
                throw new CloudRuntimeException("Cannot find virtual router provider " + typeString + " as service provider " + provider.getId());
            }
            long userId = CallContext.current().getCallingUserId();
            if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
                List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
                if (!userVOs.isEmpty()) {
                    userId = userVOs.get(0).getId();
                }
            }
            ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.elbVmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId()));
            elbVm = new DomainRouterVO(id, elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, elasticLbVmOffering.getOfferHA(), false, null);
            elbVm.setRole(Role.LB);
            elbVm = _routerDao.persist(elbVm);
            _itMgr.allocate(elbVm.getInstanceName(), template, elasticLbVmOffering, networks, plan, null);
            elbVm = _routerDao.findById(elbVm.getId());
        //TODO: create usage stats
        }
        final State state = elbVm.getState();
        if (state != State.Running) {
            elbVm = start(elbVm, params);
        }
        return elbVm;
    } finally {
        _networkDao.releaseFromLockTable(guestNetworkId);
    }
}
Also used : DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) NetworkOffering(com.cloud.offering.NetworkOffering) VMTemplateVO(com.cloud.storage.VMTemplateVO) PhysicalNetworkServiceProvider(com.cloud.network.PhysicalNetworkServiceProvider) NicProfile(com.cloud.vm.NicProfile) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) UserVO(com.cloud.user.UserVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) State(com.cloud.vm.VirtualMachine.State) RedundantState(com.cloud.network.router.VirtualRouter.RedundantState) Network(com.cloud.network.Network) List(java.util.List) ArrayList(java.util.ArrayList) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 92 with ConcurrentOperationException

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

the class ElasticLoadBalancerManagerImpl method garbageCollectUnusedElbVms.

void garbageCollectUnusedElbVms() {
    List<DomainRouterVO> unusedElbVms = _elbVmMapDao.listUnusedElbVms();
    if (unusedElbVms != null) {
        if (unusedElbVms.size() > 0) {
            s_logger.info("Found " + unusedElbVms.size() + " unused ELB vms");
        }
        Set<Long> currentGcCandidates = new HashSet<Long>();
        for (DomainRouterVO elbVm : unusedElbVms) {
            currentGcCandidates.add(elbVm.getId());
        }
        _gcCandidateElbVmIds.retainAll(currentGcCandidates);
        currentGcCandidates.removeAll(_gcCandidateElbVmIds);
        for (Long elbVmId : _gcCandidateElbVmIds) {
            DomainRouterVO elbVm = _routerDao.findById(elbVmId);
            boolean gceed = false;
            try {
                s_logger.info("Attempting to stop ELB VM: " + elbVm);
                stop(elbVm, true);
                gceed = true;
            } catch (ConcurrentOperationException e) {
                s_logger.warn("Unable to stop unused ELB vm " + elbVm + " due to ", e);
            } catch (ResourceUnavailableException e) {
                s_logger.warn("Unable to stop unused ELB vm " + elbVm + " due to ", e);
                continue;
            }
            if (gceed) {
                try {
                    s_logger.info("Attempting to destroy ELB VM: " + elbVm);
                    _itMgr.expunge(elbVm.getUuid());
                    _routerDao.remove(elbVm.getId());
                } catch (ResourceUnavailableException e) {
                    s_logger.warn("Unable to destroy unused ELB vm " + elbVm + " due to ", e);
                    gceed = false;
                }
            }
            if (!gceed) {
                currentGcCandidates.add(elbVm.getId());
            }
        }
        _gcCandidateElbVmIds = currentGcCandidates;
    }
}
Also used : ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) DomainRouterVO(com.cloud.vm.DomainRouterVO) HashSet(java.util.HashSet)

Example 93 with ConcurrentOperationException

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

the class AutoScaleManagerImpl method doScaleDown.

@Override
public void doScaleDown(final long groupId) {
    AutoScaleVmGroupVO asGroup = _autoScaleVmGroupDao.findById(groupId);
    if (asGroup == null) {
        s_logger.error("Can not find the groupid " + groupId + " for scaling up");
        return;
    }
    if (!checkConditionDown(asGroup)) {
        return;
    }
    final long vmId = removeLBrule(asGroup);
    if (vmId != -1) {
        long profileId = asGroup.getProfileId();
        // update group-vm mapping
        _autoScaleVmGroupVmMapDao.remove(groupId, vmId);
        // update last_quiettime
        List<AutoScaleVmGroupPolicyMapVO> GroupPolicyVOs = _autoScaleVmGroupPolicyMapDao.listByVmGroupId(groupId);
        for (AutoScaleVmGroupPolicyMapVO GroupPolicyVO : GroupPolicyVOs) {
            AutoScalePolicyVO vo = _autoScalePolicyDao.findById(GroupPolicyVO.getPolicyId());
            if (vo.getAction().equals("scaledown")) {
                vo.setLastQuiteTime(new Date());
                _autoScalePolicyDao.persist(vo);
                break;
            }
        }
        // get destroyvmgrace param
        AutoScaleVmProfileVO asProfile = _autoScaleVmProfileDao.findById(profileId);
        Integer destroyVmGracePeriod = asProfile.getDestroyVmGraceperiod();
        if (destroyVmGracePeriod >= 0) {
            _executor.schedule(new Runnable() {

                @Override
                public void run() {
                    try {
                        _userVmManager.destroyVm(vmId, false);
                    } catch (ResourceUnavailableException e) {
                        e.printStackTrace();
                    } catch (ConcurrentOperationException e) {
                        e.printStackTrace();
                    }
                }
            }, destroyVmGracePeriod, TimeUnit.SECONDS);
        }
    } else {
        s_logger.error("Can not remove LB rule for the VM being destroyed. Do nothing more.");
    }
}
Also used : ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) Date(java.util.Date)

Example 94 with ConcurrentOperationException

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

the class AutoScaleManagerImpl method startNewVM.

private boolean startNewVM(long vmId) {
    try {
        CallContext.current().setEventDetails("Vm Id: " + vmId);
        _userVmManager.startVirtualMachine(vmId, null, null, null);
    } catch (final ResourceUnavailableException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ConcurrentOperationException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    } catch (InsufficientCapacityException ex) {
        StringBuilder message = new StringBuilder(ex.getMessage());
        if (ex instanceof InsufficientServerCapacityException) {
            if (((InsufficientServerCapacityException) ex).isAffinityApplied()) {
                message.append(", Please check the affinity groups provided, there may not be sufficient capacity to follow them");
            }
        }
        s_logger.info(ex);
        s_logger.info(message.toString(), ex);
        throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, message.toString());
    }
    return true;
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException)

Example 95 with ConcurrentOperationException

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

the class VolumeApiServiceImpl method migrateVolume.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_MIGRATE, eventDescription = "migrating volume", async = true)
public Volume migrateVolume(MigrateVolumeCmd cmd) {
    Long volumeId = cmd.getVolumeId();
    Long storagePoolId = cmd.getStoragePoolId();
    VolumeVO vol = _volsDao.findById(volumeId);
    if (vol == null) {
        throw new InvalidParameterValueException("Failed to find the volume id: " + volumeId);
    }
    if (vol.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("Volume must be in ready state");
    }
    boolean liveMigrateVolume = false;
    Long instanceId = vol.getInstanceId();
    Long srcClusterId = null;
    VMInstanceVO vm = null;
    if (instanceId != null) {
        vm = _vmInstanceDao.findById(instanceId);
    }
    // Check that Vm to which this volume is attached does not have VM Snapshots
    if (vm != null && _vmSnapshotDao.findByVm(vm.getId()).size() > 0) {
        throw new InvalidParameterValueException("Volume cannot be migrated, please remove all VM snapshots for VM to which this volume is attached");
    }
    if (vm != null && vm.getState() == State.Running) {
        // Check if the VM is GPU enabled.
        if (_serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
            throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
        }
        // Check if the underlying hypervisor supports storage motion.
        Long hostId = vm.getHostId();
        if (hostId != null) {
            HostVO host = _hostDao.findById(hostId);
            HypervisorCapabilitiesVO capabilities = null;
            if (host != null) {
                capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(host.getHypervisorType(), host.getHypervisorVersion());
                srcClusterId = host.getClusterId();
            }
            if (capabilities != null) {
                liveMigrateVolume = capabilities.isStorageMotionSupported();
            }
        }
        // If vm is running, and hypervisor doesn't support live migration, then return error
        if (!liveMigrateVolume) {
            throw new InvalidParameterValueException("Volume needs to be detached from VM");
        }
    }
    if (liveMigrateVolume && !cmd.isLiveMigrate()) {
        throw new InvalidParameterValueException("The volume " + vol + "is attached to a vm and for migrating it " + "the parameter livemigrate should be specified");
    }
    StoragePool destPool = (StoragePool) dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary);
    if (destPool == null) {
        throw new InvalidParameterValueException("Failed to find the destination storage pool: " + storagePoolId);
    } else if (destPool.isInMaintenance()) {
        throw new InvalidParameterValueException("Cannot migrate volume " + vol + "to the destination storage pool " + destPool.getName() + " as the storage pool is in maintenance mode.");
    }
    if (_volumeMgr.volumeOnSharedStoragePool(vol)) {
        if (destPool.isLocal()) {
            throw new InvalidParameterValueException("Migration of volume from shared to local storage pool is not supported");
        } else {
            // to make sure that the destination storage pool is in the same cluster as the vm.
            if (liveMigrateVolume && destPool.getClusterId() != null && srcClusterId != null) {
                if (!srcClusterId.equals(destPool.getClusterId())) {
                    throw new InvalidParameterValueException("Cannot migrate a volume of a virtual machine to a storage pool in a different cluster");
                }
            }
            // In case of VMware, if ROOT volume is being cold-migrated, then ensure destination storage pool is in the same Datacenter as the VM.
            if (vm != null && vm.getHypervisorType().equals(HypervisorType.VMware)) {
                if (!liveMigrateVolume && vol.volumeType.equals(Volume.Type.ROOT)) {
                    Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
                    HostVO host = _hostDao.findById(hostId);
                    if (host != null)
                        srcClusterId = host.getClusterId();
                    if (srcClusterId != null && destPool.getClusterId() != null && !srcClusterId.equals(destPool.getClusterId())) {
                        String srcDcName = _clusterDetailsDao.getVmwareDcName(srcClusterId);
                        String destDcName = _clusterDetailsDao.getVmwareDcName(destPool.getClusterId());
                        if (srcDcName != null && destDcName != null && !srcDcName.equals(destDcName)) {
                            throw new InvalidParameterValueException("Cannot migrate ROOT volume of a stopped VM to a storage pool in a different VMware datacenter");
                        }
                    }
                    updateMissingRootDiskController(vm, vol.getChainInfo());
                }
            }
        }
    } else {
        throw new InvalidParameterValueException("Migration of volume from local storage pool is not supported");
    }
    if (vm != null) {
        // serialize VM operation
        AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
        if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
            // avoid re-entrance
            VmWorkJobVO placeHolder = null;
            placeHolder = createPlaceHolderWork(vm.getId());
            try {
                return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume);
            } finally {
                _workJobDao.expunge(placeHolder.getId());
            }
        } else {
            Outcome<Volume> outcome = migrateVolumeThroughJobQueue(vm.getId(), vol.getId(), destPool.getId(), liveMigrateVolume);
            try {
                outcome.get();
            } catch (InterruptedException e) {
                throw new RuntimeException("Operation is interrupted", e);
            } catch (java.util.concurrent.ExecutionException e) {
                throw new RuntimeException("Execution excetion", e);
            }
            Object jobResult = _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 migrated new volume from job result
            if (jobResult != null && jobResult instanceof Long) {
                return _entityMgr.findById(VolumeVO.class, ((Long) jobResult));
            }
            return null;
        }
    }
    return orchestrateMigrateVolume(vol.getId(), destPool.getId(), liveMigrateVolume);
}
Also used : HypervisorCapabilitiesVO(com.cloud.hypervisor.HypervisorCapabilitiesVO) AsyncJobExecutionContext(org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext) VMInstanceVO(com.cloud.vm.VMInstanceVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) HostVO(com.cloud.host.HostVO) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO) ExecutionException(java.util.concurrent.ExecutionException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) 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(org.apache.cloudstack.engine.subsystem.api.storage.DataObject) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)153 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)96 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)80 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)71 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)46 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)43 ServerApiException (org.apache.cloudstack.api.ServerApiException)32 Account (com.cloud.user.Account)24 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)23 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)21 DB (com.cloud.utils.db.DB)21 AsyncJobExecutionContext (org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext)20 VmWorkJobVO (org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)20 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)17 ConfigurationException (javax.naming.ConfigurationException)17 ArrayList (java.util.ArrayList)16 ActionEvent (com.cloud.event.ActionEvent)14 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)14 UserVm (com.cloud.uservm.UserVm)14 ManagementServerException (com.cloud.exception.ManagementServerException)13