Search in sources :

Example 21 with TemplateDataStoreVO

use of com.cloud.storage.datastore.db.TemplateDataStoreVO in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method copy.

@Override
@DB
public boolean copy(final long userId, final VMTemplateVO template, final DataStore srcSecStore, final DataCenterVO dstZone) throws StorageUnavailableException, ResourceAllocationException {
    final long tmpltId = template.getId();
    final long dstZoneId = dstZone.getId();
    // find all eligible image stores for the destination zone
    final List<DataStore> dstSecStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(dstZoneId));
    if (dstSecStores == null || dstSecStores.isEmpty()) {
        throw new StorageUnavailableException("Destination zone is not ready, no image store associated", DataCenter.class, dstZone.getId());
    }
    final AccountVO account = _accountDao.findById(template.getAccountId());
    // find the size of the template to be copied
    final TemplateDataStoreVO srcTmpltStore = _tmplStoreDao.findByStoreTemplate(srcSecStore.getId(), tmpltId);
    _resourceLimitMgr.checkResourceLimit(account, ResourceType.template);
    _resourceLimitMgr.checkResourceLimit(account, ResourceType.secondary_storage, new Long(srcTmpltStore.getSize()).longValue());
    // Event details
    final String copyEventType;
    if (template.getFormat().equals(ImageFormat.ISO)) {
        copyEventType = EventTypes.EVENT_ISO_COPY;
    } else {
        copyEventType = EventTypes.EVENT_TEMPLATE_COPY;
    }
    final TemplateInfo srcTemplate = _tmplFactory.getTemplate(template.getId(), srcSecStore);
    // for that zone
    for (final DataStore dstSecStore : dstSecStores) {
        final TemplateDataStoreVO dstTmpltStore = _tmplStoreDao.findByStoreTemplate(dstSecStore.getId(), tmpltId);
        if (dstTmpltStore != null && dstTmpltStore.getDownloadState() == Status.DOWNLOADED) {
            // already downloaded on this image store
            return true;
        }
        if (dstTmpltStore != null && dstTmpltStore.getDownloadState() != Status.DOWNLOAD_IN_PROGRESS) {
            _tmplStoreDao.removeByTemplateStore(tmpltId, dstSecStore.getId());
        }
        final AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.copyTemplate(srcTemplate, dstSecStore);
        try {
            final TemplateApiResult result = future.get();
            if (result.isFailed()) {
                s_logger.debug("copy template failed for image store " + dstSecStore.getName() + ":" + result.getResult());
                // try next image store
                continue;
            }
            _tmpltDao.addTemplateToZone(template, dstZoneId);
            return true;
        } catch (final Exception ex) {
            s_logger.debug("failed to copy template to image store:" + dstSecStore.getName() + " ,will try next one");
        }
    }
    return false;
}
Also used : TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO) AccountVO(com.cloud.user.AccountVO) TemplateApiResult(com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) MalformedURLException(java.net.MalformedURLException) ZoneScope(com.cloud.engine.subsystem.api.storage.ZoneScope) TemplateInfo(com.cloud.engine.subsystem.api.storage.TemplateInfo) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) DB(com.cloud.utils.db.DB)

Example 22 with TemplateDataStoreVO

use of com.cloud.storage.datastore.db.TemplateDataStoreVO in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method restoreVMInternal.

public UserVm restoreVMInternal(final Account caller, UserVmVO vm, final Long newTemplateId) throws InsufficientCapacityException, ResourceUnavailableException {
    final Long userId = caller.getId();
    final Account owner = _accountDao.findById(vm.getAccountId());
    _userDao.findById(userId);
    final long vmId = vm.getId();
    boolean needRestart = false;
    // Input validation
    if (owner == null) {
        throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId());
    }
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId());
    }
    if (vm.getState() != VirtualMachine.State.Running && vm.getState() != VirtualMachine.State.Stopped) {
        throw new CloudRuntimeException("Vm " + vm.getUuid() + " currently in " + vm.getState() + " state, restore vm can only execute when VM in Running or Stopped");
    }
    if (vm.getState() == VirtualMachine.State.Running) {
        needRestart = true;
    }
    final List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT);
    if (rootVols.isEmpty()) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vm.getUuid());
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (rootVols.size() > 1) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("There are " + rootVols.size() + " root volumes for VM " + vm.getUuid());
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    final VolumeVO root = rootVols.get(0);
    if (!Volume.State.Allocated.equals(root.getState()) || newTemplateId != null) {
        Long templateId = root.getTemplateId();
        boolean isISO = false;
        if (templateId == null) {
            // Assuming that for a vm deployed using ISO, template ID is set to NULL
            isISO = true;
            templateId = vm.getIsoId();
        }
        // If target VM has associated VM snapshots then don't allow restore of VM
        final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
        if (vmSnapshots.size() > 0) {
            throw new InvalidParameterValueException("Unable to restore VM, please remove VM snapshots before restoring VM");
        }
        final VMTemplateVO template;
        // newTemplateId can be either template or ISO id. In the following snippet based on the vm deployment (from template or ISO) it is handled accordingly
        if (newTemplateId != null) {
            template = _templateDao.findById(newTemplateId);
            _accountMgr.checkAccess(caller, null, true, template);
            if (isISO) {
                if (!template.getFormat().equals(ImageFormat.ISO)) {
                    throw new InvalidParameterValueException("Invalid ISO id provided to restore the VM ");
                }
            } else {
                if (template.getFormat().equals(ImageFormat.ISO)) {
                    throw new InvalidParameterValueException("Invalid template id provided to restore the VM ");
                }
            }
        } else {
            if (isISO && templateId == null) {
                throw new CloudRuntimeException("Cannot restore the VM since there is no ISO attached to VM");
            }
            template = _templateDao.findById(templateId);
            if (template == null) {
                final InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template/ISO for specified volumeid and vmId");
                ex.addProxyObject(vm.getUuid(), "vmId");
                ex.addProxyObject(root.getUuid(), "volumeId");
                throw ex;
            }
        }
        final TemplateDataStoreVO tmplStore = _templateStoreDao.findByTemplateZoneReady(template.getId(), vm.getDataCenterId());
        if (tmplStore == null) {
            throw new InvalidParameterValueException("Cannot restore the vm as the template " + template.getUuid() + " isn't available in the zone");
        }
        if (needRestart) {
            try {
                _itMgr.stop(vm.getUuid());
            } catch (final ResourceUnavailableException e) {
                s_logger.debug("Stop vm " + vm.getUuid() + " failed", e);
                final CloudRuntimeException ex = new CloudRuntimeException("Stop vm failed for specified vmId");
                ex.addProxyObject(vm.getUuid(), "vmId");
                throw ex;
            }
        }
        /* If new template/ISO is provided allocate a new volume from new template/ISO otherwise allocate new volume from original template/ISO */
        final Volume newVol;
        if (newTemplateId != null) {
            if (isISO) {
                newVol = volumeMgr.allocateDuplicateVolume(root, null);
                vm.setIsoId(newTemplateId);
                vm.setGuestOSId(template.getGuestOSId());
                vm.setTemplateId(newTemplateId);
                _vmDao.update(vmId, vm);
            } else {
                newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
                vm.setGuestOSId(template.getGuestOSId());
                vm.setTemplateId(newTemplateId);
                _vmDao.update(vmId, vm);
            }
        } else {
            newVol = volumeMgr.allocateDuplicateVolume(root, null);
        }
        // 1. Save usage event and update resource count for user vm volumes
        _resourceLimitMgr.incrementResourceCount(newVol.getAccountId(), ResourceType.volume, newVol.isDisplay());
        _resourceLimitMgr.incrementResourceCount(newVol.getAccountId(), ResourceType.primary_storage, newVol.isDisplay(), new Long(newVol.getSize()));
        handleManagedStorage(vm, root);
        _volsDao.attachVolume(newVol.getId(), vmId, newVol.getDeviceId());
        // Detach, destroy and create the usage event for the old root volume.
        _volsDao.detachVolume(root.getId());
        volumeMgr.destroyVolume(root);
        Map<VirtualMachineProfile.Param, Object> params = null;
        String password = null;
        if (template.getEnablePassword()) {
            password = _mgr.generateRandomPassword();
            final boolean result = resetVMPasswordInternal(vmId, password);
            if (result) {
                vm.setPassword(password);
                _vmDao.loadDetails(vm);
                // update the password in vm_details table too
                // Check if an SSH key pair was selected for the instance and if so
                // use it to encrypt & save the vm password
                encryptAndStorePassword(vm, password);
            } else {
                throw new CloudRuntimeException("VM reset is completed but failed to reset password for the virtual machine ");
            }
        }
        if (needRestart) {
            try {
                if (vm.getDetail("password") != null) {
                    params = new HashMap<>();
                    params.put(VirtualMachineProfile.Param.VmPassword, password);
                }
                _itMgr.start(vm.getUuid(), params);
                vm = _vmDao.findById(vmId);
                if (template.getEnablePassword()) {
                    // this value is not being sent to the backend; need only for api
                    // display purposes
                    vm.setPassword(password);
                    if (vm.isUpdateParameters()) {
                        vm.setUpdateParameters(false);
                        _vmDao.loadDetails(vm);
                        if (vm.getDetail("password") != null) {
                            _vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
                        }
                        _vmDao.update(vm.getId(), vm);
                    }
                }
            } catch (final Exception e) {
                s_logger.debug("Unable to start VM " + vm.getUuid(), e);
                final CloudRuntimeException ex = new CloudRuntimeException("Unable to start VM with specified id" + e.getMessage());
                ex.addProxyObject(vm.getUuid(), "vmId");
                throw ex;
            }
        }
    }
    s_logger.debug("Restore VM " + vmId + " done successfully");
    return vm;
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO) 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) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) Volume(com.cloud.storage.Volume) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 23 with TemplateDataStoreVO

use of com.cloud.storage.datastore.db.TemplateDataStoreVO in project cosmic by MissionCriticalCloud.

the class TemplateManagerImplTest method testPrepareTemplateNoHostConnectedToPool.

@Test(expected = CloudRuntimeException.class)
public void testPrepareTemplateNoHostConnectedToPool() {
    final VMTemplateVO mockTemplate = mock(VMTemplateVO.class);
    when(mockTemplate.getId()).thenReturn(202l);
    final StoragePoolVO mockPool = mock(StoragePoolVO.class);
    when(mockPool.getId()).thenReturn(2l);
    final PrimaryDataStore mockPrimaryDataStore = mock(PrimaryDataStore.class);
    when(mockPrimaryDataStore.getId()).thenReturn(2l);
    when(mockPrimaryDataStore.getDataCenterId()).thenReturn(1l);
    final TemplateDataStoreVO mockTemplateDataStore = mock(TemplateDataStoreVO.class);
    when(dataStoreManager.getPrimaryDataStore(anyLong())).thenReturn(mockPrimaryDataStore);
    when(vmTemplateDao.findById(anyLong(), anyBoolean())).thenReturn(mockTemplate);
    when(vmTemplatePoolDao.findByPoolTemplate(anyLong(), anyLong())).thenReturn(null);
    when(templateDataStoreDao.findByTemplateZoneDownloadStatus(202l, 1l, VMTemplateStorageResourceAssoc.Status.DOWNLOADED)).thenReturn(mockTemplateDataStore);
    when(storagePoolHostDao.listByHostStatus(2l, Status.Up)).thenReturn(null);
    templateManager.prepareTemplateForCreate(mockTemplate, (StoragePool) mockPrimaryDataStore);
}
Also used : VMTemplateVO(com.cloud.storage.VMTemplateVO) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) VMTemplateStoragePoolVO(com.cloud.storage.VMTemplateStoragePoolVO) TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO) PrimaryDataStore(com.cloud.engine.subsystem.api.storage.PrimaryDataStore) Test(org.junit.Test)

Example 24 with TemplateDataStoreVO

use of com.cloud.storage.datastore.db.TemplateDataStoreVO in project cosmic by MissionCriticalCloud.

the class TemplateObject method processEvent.

@Override
public void processEvent(final ObjectInDataStoreStateMachine.Event event, final Answer answer) {
    try {
        if (getDataStore().getRole() == DataStoreRole.Primary) {
            if (answer instanceof CopyCmdAnswer) {
                final CopyCmdAnswer cpyAnswer = (CopyCmdAnswer) answer;
                final TemplateObjectTO newTemplate = (TemplateObjectTO) cpyAnswer.getNewData();
                final VMTemplateStoragePoolVO templatePoolRef = templatePoolDao.findByPoolTemplate(getDataStore().getId(), getId());
                templatePoolRef.setDownloadPercent(100);
                if (newTemplate.getSize() != null) {
                    templatePoolRef.setTemplateSize(newTemplate.getSize());
                }
                templatePoolRef.setDownloadState(Status.DOWNLOADED);
                templatePoolRef.setLocalDownloadPath(newTemplate.getPath());
                templatePoolRef.setInstallPath(newTemplate.getPath());
                templatePoolDao.update(templatePoolRef.getId(), templatePoolRef);
            }
        } else if (getDataStore().getRole() == DataStoreRole.Image || getDataStore().getRole() == DataStoreRole.ImageCache) {
            if (answer instanceof CopyCmdAnswer) {
                final CopyCmdAnswer cpyAnswer = (CopyCmdAnswer) answer;
                final TemplateObjectTO newTemplate = (TemplateObjectTO) cpyAnswer.getNewData();
                final TemplateDataStoreVO templateStoreRef = templateStoreDao.findByStoreTemplate(getDataStore().getId(), getId());
                templateStoreRef.setInstallPath(newTemplate.getPath());
                templateStoreRef.setDownloadPercent(100);
                templateStoreRef.setDownloadState(Status.DOWNLOADED);
                templateStoreRef.setSize(newTemplate.getSize());
                if (newTemplate.getPhysicalSize() != null) {
                    templateStoreRef.setPhysicalSize(newTemplate.getPhysicalSize());
                }
                templateStoreDao.update(templateStoreRef.getId(), templateStoreRef);
                if (getDataStore().getRole() == DataStoreRole.Image) {
                    final VMTemplateVO templateVO = imageDao.findById(getId());
                    if (newTemplate.getFormat() != null) {
                        templateVO.setFormat(newTemplate.getFormat());
                    }
                    if (newTemplate.getName() != null) {
                        // For template created from snapshot, template name is determine by resource code.
                        templateVO.setUniqueName(newTemplate.getName());
                    }
                    if (newTemplate.getHypervisorType() != null) {
                        templateVO.setHypervisorType(newTemplate.getHypervisorType());
                    }
                    templateVO.setSize(newTemplate.getSize());
                    imageDao.update(templateVO.getId(), templateVO);
                }
            }
        }
        objectInStoreMgr.update(this, event);
    } catch (final NoTransitionException e) {
        s_logger.debug("failed to update state", e);
        throw new CloudRuntimeException("Failed to update state" + e.toString());
    } catch (final Exception ex) {
        s_logger.debug("failed to process event and answer", ex);
        objectInStoreMgr.delete(this);
        throw new CloudRuntimeException("Failed to process event", ex);
    } finally {
        // in case of OperationFailed, expunge the entry
        if (event == ObjectInDataStoreStateMachine.Event.OperationFailed) {
            objectInStoreMgr.deleteIfNotReady(this);
        }
    }
}
Also used : VMTemplateStoragePoolVO(com.cloud.storage.VMTemplateStoragePoolVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) VMTemplateVO(com.cloud.storage.VMTemplateVO) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO) TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO) CopyCmdAnswer(com.cloud.storage.command.CopyCmdAnswer) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException)

Example 25 with TemplateDataStoreVO

use of com.cloud.storage.datastore.db.TemplateDataStoreVO in project cosmic by MissionCriticalCloud.

the class TemplateObject method decRefCount.

@Override
public void decRefCount() {
    if (dataStore == null) {
        return;
    }
    if (dataStore.getRole() == DataStoreRole.Image || dataStore.getRole() == DataStoreRole.ImageCache) {
        final TemplateDataStoreVO store = templateStoreDao.findByStoreTemplate(dataStore.getId(), getId());
        store.decrRefCnt();
        store.setLastUpdated(new Date());
        templateStoreDao.update(store.getId(), store);
    }
}
Also used : TemplateDataStoreVO(com.cloud.storage.datastore.db.TemplateDataStoreVO) Date(java.util.Date)

Aggregations

TemplateDataStoreVO (com.cloud.storage.datastore.db.TemplateDataStoreVO)39 DataStore (com.cloud.engine.subsystem.api.storage.DataStore)17 VMTemplateVO (com.cloud.storage.VMTemplateVO)15 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)13 TemplateInfo (com.cloud.engine.subsystem.api.storage.TemplateInfo)11 Date (java.util.Date)9 VolumeDataStoreVO (com.cloud.storage.datastore.db.VolumeDataStoreVO)7 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)7 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)6 VMTemplateStoragePoolVO (com.cloud.storage.VMTemplateStoragePoolVO)6 SnapshotDataStoreVO (com.cloud.storage.datastore.db.SnapshotDataStoreVO)6 TemplateApiResult (com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult)5 ZoneScope (com.cloud.engine.subsystem.api.storage.ZoneScope)5 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)5 StorageUnavailableException (com.cloud.exception.StorageUnavailableException)5 URISyntaxException (java.net.URISyntaxException)5 ExecutionException (java.util.concurrent.ExecutionException)5 ConfigurationException (javax.naming.ConfigurationException)5 EndPoint (com.cloud.engine.subsystem.api.storage.EndPoint)4 CreateCmdResult (com.cloud.engine.subsystem.api.storage.CreateCmdResult)3