Search in sources :

Example 86 with VMInstanceVO

use of com.cloud.vm.VMInstanceVO in project cloudstack by apache.

the class CapacityManagerImpl method updateCapacityForHost.

@DB
@Override
public void updateCapacityForHost(final Host host) {
    // prepare the service offerings
    List<ServiceOfferingVO> offerings = _offeringsDao.listAllIncludingRemoved();
    Map<Long, ServiceOfferingVO> offeringsMap = new HashMap<Long, ServiceOfferingVO>();
    for (ServiceOfferingVO offering : offerings) {
        offeringsMap.put(offering.getId(), offering);
    }
    long usedCpu = 0;
    long usedMemory = 0;
    long reservedMemory = 0;
    long reservedCpu = 0;
    final CapacityState capacityState = (host.getResourceState() == ResourceState.Enabled) ? CapacityState.Enabled : CapacityState.Disabled;
    List<VMInstanceVO> vms = _vmDao.listUpByHostId(host.getId());
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Found " + vms.size() + " VMs on host " + host.getId());
    }
    ClusterVO cluster = _clusterDao.findById(host.getClusterId());
    ClusterDetailsVO clusterDetailCpu = _clusterDetailsDao.findDetail(cluster.getId(), "cpuOvercommitRatio");
    ClusterDetailsVO clusterDetailRam = _clusterDetailsDao.findDetail(cluster.getId(), "memoryOvercommitRatio");
    Float clusterCpuOvercommitRatio = Float.parseFloat(clusterDetailCpu.getValue());
    Float clusterRamOvercommitRatio = Float.parseFloat(clusterDetailRam.getValue());
    Float cpuOvercommitRatio = 1f;
    Float ramOvercommitRatio = 1f;
    for (VMInstanceVO vm : vms) {
        Map<String, String> vmDetails = _userVmDetailsDao.listDetailsKeyPairs(vm.getId());
        String vmDetailCpu = vmDetails.get("cpuOvercommitRatio");
        String vmDetailRam = vmDetails.get("memoryOvercommitRatio");
        if (vmDetailCpu != null) {
            //if vmDetail_cpu is not null it means it is running in a overcommited cluster.
            cpuOvercommitRatio = Float.parseFloat(vmDetailCpu);
            ramOvercommitRatio = Float.parseFloat(vmDetailRam);
        }
        ServiceOffering so = offeringsMap.get(vm.getServiceOfferingId());
        if (so.isDynamic()) {
            usedMemory += ((Integer.parseInt(vmDetails.get(UsageEventVO.DynamicParameters.memory.name())) * 1024L * 1024L) / ramOvercommitRatio) * clusterRamOvercommitRatio;
            usedCpu += ((Integer.parseInt(vmDetails.get(UsageEventVO.DynamicParameters.cpuNumber.name())) * Integer.parseInt(vmDetails.get(UsageEventVO.DynamicParameters.cpuSpeed.name()))) / cpuOvercommitRatio) * clusterCpuOvercommitRatio;
        } else {
            usedMemory += ((so.getRamSize() * 1024L * 1024L) / ramOvercommitRatio) * clusterRamOvercommitRatio;
            usedCpu += ((so.getCpu() * so.getSpeed()) / cpuOvercommitRatio) * clusterCpuOvercommitRatio;
        }
    }
    List<VMInstanceVO> vmsByLastHostId = _vmDao.listByLastHostId(host.getId());
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Found " + vmsByLastHostId.size() + " VM, not running on host " + host.getId());
    }
    for (VMInstanceVO vm : vmsByLastHostId) {
        long secondsSinceLastUpdate = (DateUtil.currentGMTTime().getTime() - vm.getUpdateTime().getTime()) / 1000;
        if (secondsSinceLastUpdate < _vmCapacityReleaseInterval) {
            UserVmDetailVO vmDetailCpu = _userVmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio");
            UserVmDetailVO vmDetailRam = _userVmDetailsDao.findDetail(vm.getId(), "memoryOvercommitRatio");
            if (vmDetailCpu != null) {
                //if vmDetail_cpu is not null it means it is running in a overcommited cluster.
                cpuOvercommitRatio = Float.parseFloat(vmDetailCpu.getValue());
                ramOvercommitRatio = Float.parseFloat(vmDetailRam.getValue());
            }
            ServiceOffering so = offeringsMap.get(vm.getServiceOfferingId());
            Map<String, String> vmDetails = _userVmDetailsDao.listDetailsKeyPairs(vm.getId());
            if (so.isDynamic()) {
                reservedMemory += ((Integer.parseInt(vmDetails.get(UsageEventVO.DynamicParameters.memory.name())) * 1024L * 1024L) / ramOvercommitRatio) * clusterRamOvercommitRatio;
                reservedCpu += ((Integer.parseInt(vmDetails.get(UsageEventVO.DynamicParameters.cpuNumber.name())) * Integer.parseInt(vmDetails.get(UsageEventVO.DynamicParameters.cpuSpeed.name()))) / cpuOvercommitRatio) * clusterCpuOvercommitRatio;
            } else {
                reservedMemory += ((so.getRamSize() * 1024L * 1024L) / ramOvercommitRatio) * clusterRamOvercommitRatio;
                reservedCpu += (so.getCpu() * so.getSpeed() / cpuOvercommitRatio) * clusterCpuOvercommitRatio;
            }
        } else {
            // signal if not done already, that the VM has been stopped for skip.counting.hours,
            // hence capacity will not be reserved anymore.
            UserVmDetailVO messageSentFlag = _userVmDetailsDao.findDetail(vm.getId(), MESSAGE_RESERVED_CAPACITY_FREED_FLAG);
            if (messageSentFlag == null || !Boolean.valueOf(messageSentFlag.getValue())) {
                _messageBus.publish(_name, "VM_ReservedCapacity_Free", PublishScope.LOCAL, vm);
                if (vm.getType() == VirtualMachine.Type.User) {
                    UserVmVO userVM = _userVMDao.findById(vm.getId());
                    _userVMDao.loadDetails(userVM);
                    userVM.setDetail(MESSAGE_RESERVED_CAPACITY_FREED_FLAG, "true");
                    _userVMDao.saveDetails(userVM);
                }
            }
        }
    }
    CapacityVO cpuCap = _capacityDao.findByHostIdType(host.getId(), Capacity.CAPACITY_TYPE_CPU);
    CapacityVO memCap = _capacityDao.findByHostIdType(host.getId(), Capacity.CAPACITY_TYPE_MEMORY);
    if (cpuCap != null && memCap != null) {
        if (host.getTotalMemory() != null) {
            memCap.setTotalCapacity(host.getTotalMemory());
        }
        long hostTotalCpu = host.getCpus().longValue() * host.getSpeed().longValue();
        if (cpuCap.getTotalCapacity() != hostTotalCpu) {
            s_logger.debug("Calibrate total cpu for host: " + host.getId() + " old total CPU:" + cpuCap.getTotalCapacity() + " new total CPU:" + hostTotalCpu);
            cpuCap.setTotalCapacity(hostTotalCpu);
        }
        // Set the capacity state as per the host allocation state.
        if (capacityState != cpuCap.getCapacityState()) {
            s_logger.debug("Calibrate cpu capacity state for host: " + host.getId() + " old capacity state:" + cpuCap.getTotalCapacity() + " new capacity state:" + hostTotalCpu);
            cpuCap.setCapacityState(capacityState);
        }
        memCap.setCapacityState(capacityState);
        if (cpuCap.getUsedCapacity() == usedCpu && cpuCap.getReservedCapacity() == reservedCpu) {
            s_logger.debug("No need to calibrate cpu capacity, host:" + host.getId() + " usedCpu: " + cpuCap.getUsedCapacity() + " reservedCpu: " + cpuCap.getReservedCapacity());
        } else {
            if (cpuCap.getReservedCapacity() != reservedCpu) {
                s_logger.debug("Calibrate reserved cpu for host: " + host.getId() + " old reservedCpu:" + cpuCap.getReservedCapacity() + " new reservedCpu:" + reservedCpu);
                cpuCap.setReservedCapacity(reservedCpu);
            }
            if (cpuCap.getUsedCapacity() != usedCpu) {
                s_logger.debug("Calibrate used cpu for host: " + host.getId() + " old usedCpu:" + cpuCap.getUsedCapacity() + " new usedCpu:" + usedCpu);
                cpuCap.setUsedCapacity(usedCpu);
            }
        }
        if (memCap.getTotalCapacity() != host.getTotalMemory()) {
            s_logger.debug("Calibrate total memory for host: " + host.getId() + " old total memory:" + memCap.getTotalCapacity() + " new total memory:" + host.getTotalMemory());
            memCap.setTotalCapacity(host.getTotalMemory());
        }
        // Set the capacity state as per the host allocation state.
        if (capacityState != memCap.getCapacityState()) {
            s_logger.debug("Calibrate memory capacity state for host: " + host.getId() + " old capacity state:" + memCap.getTotalCapacity() + " new capacity state:" + hostTotalCpu);
            memCap.setCapacityState(capacityState);
        }
        if (memCap.getUsedCapacity() == usedMemory && memCap.getReservedCapacity() == reservedMemory) {
            s_logger.debug("No need to calibrate memory capacity, host:" + host.getId() + " usedMem: " + memCap.getUsedCapacity() + " reservedMem: " + memCap.getReservedCapacity());
        } else {
            if (memCap.getReservedCapacity() != reservedMemory) {
                s_logger.debug("Calibrate reserved memory for host: " + host.getId() + " old reservedMem:" + memCap.getReservedCapacity() + " new reservedMem:" + reservedMemory);
                memCap.setReservedCapacity(reservedMemory);
            }
            if (memCap.getUsedCapacity() != usedMemory) {
                /*
                     * Didn't calibrate for used memory, because VMs can be in
                     * state(starting/migrating) that I don't know on which host
                     * they are allocated
                     */
                s_logger.debug("Calibrate used memory for host: " + host.getId() + " old usedMem: " + memCap.getUsedCapacity() + " new usedMem: " + usedMemory);
                memCap.setUsedCapacity(usedMemory);
            }
        }
        try {
            _capacityDao.update(cpuCap.getId(), cpuCap);
            _capacityDao.update(memCap.getId(), memCap);
        } catch (Exception e) {
            s_logger.error("Caught exception while updating cpu/memory capacity for the host " + host.getId(), e);
        }
    } else {
        final long usedMemoryFinal = usedMemory;
        final long reservedMemoryFinal = reservedMemory;
        final long usedCpuFinal = usedCpu;
        final long reservedCpuFinal = reservedCpu;
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                CapacityVO capacity = new CapacityVO(host.getId(), host.getDataCenterId(), host.getPodId(), host.getClusterId(), usedMemoryFinal, host.getTotalMemory(), Capacity.CAPACITY_TYPE_MEMORY);
                capacity.setReservedCapacity(reservedMemoryFinal);
                capacity.setCapacityState(capacityState);
                _capacityDao.persist(capacity);
                capacity = new CapacityVO(host.getId(), host.getDataCenterId(), host.getPodId(), host.getClusterId(), usedCpuFinal, host.getCpus().longValue() * host.getSpeed().longValue(), Capacity.CAPACITY_TYPE_CPU);
                capacity.setReservedCapacity(reservedCpuFinal);
                capacity.setCapacityState(capacityState);
                _capacityDao.persist(capacity);
            }
        });
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ClusterVO(com.cloud.dc.ClusterVO) HashMap(java.util.HashMap) ServiceOffering(com.cloud.offering.ServiceOffering) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) ConnectionException(com.cloud.exception.ConnectionException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UserVmDetailVO(com.cloud.vm.UserVmDetailVO) ClusterDetailsVO(com.cloud.dc.ClusterDetailsVO) DB(com.cloud.utils.db.DB)

Example 87 with VMInstanceVO

use of com.cloud.vm.VMInstanceVO 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)

Example 88 with VMInstanceVO

use of com.cloud.vm.VMInstanceVO in project cloudstack by apache.

the class VolumeApiServiceImpl method allocSnapshotForVm.

@Override
public Snapshot allocSnapshotForVm(Long vmId, Long volumeId, String snapshotName) throws ResourceAllocationException {
    Account caller = CallContext.current().getCallingAccount();
    VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to vm:" + vmId + " doesn't exist");
    }
    _accountMgr.checkAccess(caller, null, true, vm);
    VolumeInfo volume = volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
    }
    _accountMgr.checkAccess(caller, null, true, volume);
    VirtualMachine attachVM = volume.getAttachedVM();
    if (attachVM == null || attachVM.getId() != vm.getId()) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't attach to vm :" + vm);
    }
    DataCenter zone = _dcDao.findById(volume.getDataCenterId());
    if (zone == null) {
        throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
    }
    if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
    }
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
    }
    if (volume.getTemplateId() != null) {
        VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
        if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
            throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
        }
    }
    StoragePool storagePool = (StoragePool) volume.getDataStore();
    if (storagePool == null) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
    }
    return snapshotMgr.allocSnapshot(volumeId, Snapshot.MANUAL_POLICY_ID, snapshotName, null);
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 89 with VMInstanceVO

use of com.cloud.vm.VMInstanceVO in project cloudstack by apache.

the class VolumeApiServiceImpl method orchestrateDetachVolumeFromVM.

private Volume orchestrateDetachVolumeFromVM(long vmId, long volumeId) {
    Volume volume = _volsDao.findById(volumeId);
    VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    String errorMsg = "Failed to detach volume " + volume.getName() + " from VM " + vm.getHostName();
    boolean sendCommand = vm.getState() == State.Running;
    Long hostId = vm.getHostId();
    if (hostId == null) {
        hostId = vm.getLastHostId();
        HostVO host = _hostDao.findById(hostId);
        if (host != null && host.getHypervisorType() == HypervisorType.VMware) {
            sendCommand = true;
        }
    }
    HostVO host = null;
    StoragePoolVO volumePool = _storagePoolDao.findByIdIncludingRemoved(volume.getPoolId());
    if (hostId != null) {
        host = _hostDao.findById(hostId);
        if (host != null && host.getHypervisorType() == HypervisorType.XenServer && volumePool != null && volumePool.isManaged()) {
            sendCommand = true;
        }
    }
    Answer answer = null;
    if (sendCommand) {
        DataTO volTO = volFactory.getVolume(volume.getId()).getTO();
        DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType());
        DettachCommand cmd = new DettachCommand(disk, vm.getInstanceName());
        cmd.setManaged(volumePool.isManaged());
        cmd.setStorageHost(volumePool.getHostAddress());
        cmd.setStoragePort(volumePool.getPort());
        cmd.set_iScsiName(volume.get_iScsiName());
        try {
            answer = _agentMgr.send(hostId, cmd);
        } catch (Exception e) {
            throw new CloudRuntimeException(errorMsg + " due to: " + e.getMessage());
        }
    }
    if (!sendCommand || (answer != null && answer.getResult())) {
        // Mark the volume as detached
        _volsDao.detachVolume(volume.getId());
        // volume.getPoolId() should be null if the VM we are detaching the disk from has never been started before
        DataStore dataStore = volume.getPoolId() != null ? dataStoreMgr.getDataStore(volume.getPoolId(), DataStoreRole.Primary) : null;
        volService.revokeAccess(volFactory.getVolume(volume.getId()), host, dataStore);
        return _volsDao.findById(volumeId);
    } else {
        if (answer != null) {
            String details = answer.getDetails();
            if (details != null && !details.isEmpty()) {
                errorMsg += "; " + details;
            }
        }
        throw new CloudRuntimeException(errorMsg);
    }
}
Also used : VMInstanceVO(com.cloud.vm.VMInstanceVO) HostVO(com.cloud.host.HostVO) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) JsonParseException(com.google.gson.JsonParseException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) MalformedURLException(java.net.MalformedURLException) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) Answer(com.cloud.agent.api.Answer) DataTO(com.cloud.agent.api.to.DataTO) 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) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) DettachCommand(org.apache.cloudstack.storage.command.DettachCommand) DiskTO(com.cloud.agent.api.to.DiskTO)

Example 90 with VMInstanceVO

use of com.cloud.vm.VMInstanceVO in project cloudstack by apache.

the class SnapshotManagerImpl method allocSnapshot.

@Override
public Snapshot allocSnapshot(Long volumeId, Long policyId, String snapshotName, Snapshot.LocationType locationType) throws ResourceAllocationException {
    Account caller = CallContext.current().getCallingAccount();
    VolumeInfo volume = volFactory.getVolume(volumeId);
    supportedByHypervisor(volume);
    // Verify permissions
    _accountMgr.checkAccess(caller, null, true, volume);
    Type snapshotType = getSnapshotType(policyId);
    Account owner = _accountMgr.getAccount(volume.getAccountId());
    try {
        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize()).longValue());
    } catch (ResourceAllocationException e) {
        if (snapshotType != Type.MANUAL) {
            String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots";
            s_logger.warn(msg);
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit");
        }
        throw e;
    }
    // Determine the name for this snapshot
    // Snapshot Name: VMInstancename + volumeName + timeString
    String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT);
    VMInstanceVO vmInstance = _vmDao.findById(volume.getInstanceId());
    String vmDisplayName = "detached";
    if (vmInstance != null) {
        vmDisplayName = vmInstance.getHostName();
    }
    if (snapshotName == null)
        snapshotName = vmDisplayName + "_" + volume.getName() + "_" + timeString;
    HypervisorType hypervisorType = HypervisorType.None;
    StoragePoolVO storagePool = _storagePoolDao.findById(volume.getDataStore().getId());
    if (storagePool.getScope() == ScopeType.ZONE) {
        hypervisorType = storagePool.getHypervisor();
        // at the time being, managed storage only supports XenServer, ESX(i), and KVM (i.e. not Hyper-V), so the VHD file type can be mapped to XenServer
        if (storagePool.isManaged() && HypervisorType.Any.equals(hypervisorType) && ImageFormat.VHD.equals(volume.getFormat())) {
            hypervisorType = HypervisorType.XenServer;
        }
    } else {
        hypervisorType = volume.getHypervisorType();
    }
    SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), snapshotName, (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), volume.getMinIops(), volume.getMaxIops(), hypervisorType, locationType);
    SnapshotVO snapshot = _snapshotDao.persist(snapshotVO);
    if (snapshot == null) {
        throw new CloudRuntimeException("Failed to create snapshot for volume: " + volume.getId());
    }
    _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.snapshot);
    _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, new Long(volume.getSize()));
    return snapshot;
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Account(com.cloud.user.Account) ScopeType(com.cloud.storage.ScopeType) Type(com.cloud.storage.Snapshot.Type) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ResourceType(com.cloud.configuration.Resource.ResourceType) IntervalType(com.cloud.utils.DateUtil.IntervalType) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Date(java.util.Date)

Aggregations

VMInstanceVO (com.cloud.vm.VMInstanceVO)131 ArrayList (java.util.ArrayList)40 HostVO (com.cloud.host.HostVO)34 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)30 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)28 Account (com.cloud.user.Account)28 VolumeVO (com.cloud.storage.VolumeVO)24 Test (org.junit.Test)24 HostPodVO (com.cloud.dc.HostPodVO)15 HashMap (java.util.HashMap)14 NetworkVO (com.cloud.network.dao.NetworkVO)13 User (com.cloud.user.User)13 NicVO (com.cloud.vm.NicVO)13 VmWorkJobVO (org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)13 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)12 StoragePoolVO (org.apache.cloudstack.storage.datastore.db.StoragePoolVO)12 ActionEvent (com.cloud.event.ActionEvent)11 Random (java.util.Random)11 Answer (com.cloud.agent.api.Answer)10 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)10