Search in sources :

Example 41 with GuestOSVO

use of com.cloud.storage.GuestOSVO in project cosmic by MissionCriticalCloud.

the class VMSnapshotStrategyTest method testRevertSnapshot.

@Test
public void testRevertSnapshot() throws AgentUnavailableException, OperationTimedoutException {
    final Long hostId = 1L;
    final Long vmId = 1L;
    final Long guestOsId = 1L;
    final HypervisorType hypervisorType = HypervisorType.Any;
    final String hypervisorVersion = "default";
    final String guestOsName = "Other";
    final List<VolumeObjectTO> volumeObjectTOs = new ArrayList<>();
    final VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
    final UserVmVO userVmVO = Mockito.mock(UserVmVO.class);
    Mockito.when(userVmVO.getGuestOSId()).thenReturn(guestOsId);
    Mockito.when(vmSnapshot.getVmId()).thenReturn(vmId);
    Mockito.when(vmSnapshotHelper.pickRunningHost(Matchers.anyLong())).thenReturn(hostId);
    Mockito.when(vmSnapshotHelper.getVolumeTOList(Matchers.anyLong())).thenReturn(volumeObjectTOs);
    Mockito.when(userVmDao.findById(Matchers.anyLong())).thenReturn(userVmVO);
    final GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
    Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
    final GuestOSHypervisorVO guestOSHypervisorVO = Mockito.mock(GuestOSHypervisorVO.class);
    Mockito.when(guestOSHypervisorVO.getGuestOsName()).thenReturn(guestOsName);
    Mockito.when(guestOsHypervisorDao.findById(Matchers.anyLong())).thenReturn(guestOSHypervisorVO);
    Mockito.when(guestOsHypervisorDao.findByOsIdAndHypervisor(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(guestOSHypervisorVO);
    final VMSnapshotTO vmSnapshotTO = Mockito.mock(VMSnapshotTO.class);
    Mockito.when(vmSnapshotHelper.getSnapshotWithParents(Matchers.any(VMSnapshotVO.class))).thenReturn(vmSnapshotTO);
    Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
    Mockito.when(vmSnapshot.getId()).thenReturn(1L);
    Mockito.when(vmSnapshot.getCreated()).thenReturn(new Date());
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
    final HostVO hostVO = Mockito.mock(HostVO.class);
    Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(hostVO);
    Mockito.when(hostVO.getHypervisorType()).thenReturn(hypervisorType);
    Mockito.when(hostVO.getHypervisorVersion()).thenReturn(hypervisorVersion);
    Exception e = null;
    try {
        vmSnapshotStrategy.revertVMSnapshot(vmSnapshot);
    } catch (final CloudRuntimeException e1) {
        e = e1;
    }
    assertNotNull(e);
    final RevertToVMSnapshotAnswer answer = Mockito.mock(RevertToVMSnapshotAnswer.class);
    Mockito.when(answer.getResult()).thenReturn(Boolean.TRUE);
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
    final boolean result = vmSnapshotStrategy.revertVMSnapshot(vmSnapshot);
    assertTrue(result);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) RevertToVMSnapshotAnswer(com.cloud.agent.api.RevertToVMSnapshotAnswer) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VMSnapshotTO(com.cloud.agent.api.VMSnapshotTO) Command(com.cloud.agent.api.Command) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(com.cloud.storage.to.VolumeObjectTO) Test(org.junit.Test)

Example 42 with GuestOSVO

use of com.cloud.storage.GuestOSVO in project cosmic by MissionCriticalCloud.

the class VMSnapshotManagerImpl method createRestoreCommand.

@Override
public RestoreVMSnapshotCommand createRestoreCommand(final UserVmVO userVm, final List<VMSnapshotVO> vmSnapshotVOs) {
    if (!HypervisorType.KVM.equals(userVm.getHypervisorType())) {
        return null;
    }
    final List<VMSnapshotTO> snapshots = new ArrayList<>();
    final Map<Long, VMSnapshotTO> snapshotAndParents = new HashMap<>();
    for (final VMSnapshotVO vmSnapshotVO : vmSnapshotVOs) {
        if (vmSnapshotVO.getType() == VMSnapshot.Type.DiskAndMemory) {
            final VMSnapshotVO snapshot = _vmSnapshotDao.findById(vmSnapshotVO.getId());
            final VMSnapshotTO parent = getSnapshotWithParents(snapshot).getParent();
            final VMSnapshotOptions options = snapshot.getOptions();
            boolean quiescevm = true;
            if (options != null) {
                quiescevm = options.needQuiesceVM();
            }
            final VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(snapshot.getId(), snapshot.getName(), snapshot.getType(), snapshot.getCreated().getTime(), snapshot.getDescription(), snapshot.getCurrent(), parent, quiescevm);
            snapshots.add(vmSnapshotTO);
            snapshotAndParents.put(vmSnapshotVO.getId(), parent);
        }
    }
    if (snapshotAndParents.isEmpty()) {
        return null;
    }
    // prepare RestoreVMSnapshotCommand
    final String vmInstanceName = userVm.getInstanceName();
    final List<VolumeObjectTO> volumeTOs = getVolumeTOList(userVm.getId());
    final GuestOSVO guestOS = _guestOSDao.findById(userVm.getGuestOSId());
    final RestoreVMSnapshotCommand restoreSnapshotCommand = new RestoreVMSnapshotCommand(vmInstanceName, null, volumeTOs, guestOS.getDisplayName());
    restoreSnapshotCommand.setSnapshots(snapshots);
    restoreSnapshotCommand.setSnapshotAndParents(snapshotAndParents);
    return restoreSnapshotCommand;
}
Also used : HashMap(java.util.HashMap) VMSnapshotOptions(com.cloud.engine.subsystem.api.storage.VMSnapshotOptions) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) RestoreVMSnapshotCommand(com.cloud.agent.api.RestoreVMSnapshotCommand) VMSnapshotTO(com.cloud.agent.api.VMSnapshotTO) VolumeObjectTO(com.cloud.storage.to.VolumeObjectTO)

Example 43 with GuestOSVO

use of com.cloud.storage.GuestOSVO in project cosmic by MissionCriticalCloud.

the class TemplateManagerImplTest method testCreatePrivateTemplateRecordForRegionStore.

@Test
public void testCreatePrivateTemplateRecordForRegionStore() throws ResourceAllocationException {
    final CreateTemplateCmd mockCreateCmd = mock(CreateTemplateCmd.class);
    when(mockCreateCmd.getTemplateName()).thenReturn("test");
    when(mockCreateCmd.getTemplateTag()).thenReturn(null);
    when(mockCreateCmd.getBits()).thenReturn(64);
    when(mockCreateCmd.getRequiresHvm()).thenReturn(true);
    when(mockCreateCmd.isPasswordEnabled()).thenReturn(false);
    when(mockCreateCmd.isPublic()).thenReturn(false);
    when(mockCreateCmd.isFeatured()).thenReturn(false);
    when(mockCreateCmd.isDynamicallyScalable()).thenReturn(false);
    when(mockCreateCmd.getVolumeId()).thenReturn(null);
    when(mockCreateCmd.getSnapshotId()).thenReturn(1L);
    when(mockCreateCmd.getOsTypeId()).thenReturn(1L);
    when(mockCreateCmd.getEventDescription()).thenReturn("test");
    when(mockCreateCmd.getDetails()).thenReturn(null);
    final Account mockTemplateOwner = mock(Account.class);
    final SnapshotVO mockSnapshot = mock(SnapshotVO.class);
    when(snapshotDao.findById(anyLong())).thenReturn(mockSnapshot);
    when(mockSnapshot.getVolumeId()).thenReturn(1L);
    when(mockSnapshot.getState()).thenReturn(Snapshot.State.BackedUp);
    when(mockSnapshot.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.XenServer);
    doNothing().when(resourceLimitMgr).checkResourceLimit(any(Account.class), eq(Resource.ResourceType.template));
    doNothing().when(resourceLimitMgr).checkResourceLimit(any(Account.class), eq(Resource.ResourceType.secondary_storage), anyLong());
    final GuestOSVO mockGuestOS = mock(GuestOSVO.class);
    when(guestOSDao.findById(anyLong())).thenReturn(mockGuestOS);
    when(tmpltDao.getNextInSequence(eq(Long.class), eq("id"))).thenReturn(1L);
    final List<ImageStoreVO> mockRegionStores = new ArrayList<>();
    final ImageStoreVO mockRegionStore = mock(ImageStoreVO.class);
    mockRegionStores.add(mockRegionStore);
    when(imgStoreDao.findRegionImageStores()).thenReturn(mockRegionStores);
    when(tmpltDao.persist(any(VMTemplateVO.class))).thenAnswer(new Answer<VMTemplateVO>() {

        @Override
        public VMTemplateVO answer(final InvocationOnMock invocationOnMock) throws Throwable {
            final Object[] args = invocationOnMock.getArguments();
            return (VMTemplateVO) args[0];
        }
    });
    final VMTemplateVO template = templateManager.createPrivateTemplateRecord(mockCreateCmd, mockTemplateOwner);
    assertTrue("Template in a region store should have cross zones set", template.isCrossZones());
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) GuestOSVO(com.cloud.storage.GuestOSVO) SnapshotVO(com.cloud.storage.SnapshotVO) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyLong(org.mockito.Matchers.anyLong) CreateTemplateCmd(com.cloud.api.command.user.template.CreateTemplateCmd) ImageStoreVO(com.cloud.storage.datastore.db.ImageStoreVO) Test(org.junit.Test)

Example 44 with GuestOSVO

use of com.cloud.storage.GuestOSVO in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method prepareIsoForVmProfile.

@Override
public void prepareIsoForVmProfile(final VirtualMachineProfile profile) {
    final UserVmVO vm = _userVmDao.findById(profile.getId());
    if (vm.getIsoId() != null) {
        final TemplateInfo template = prepareIso(vm.getIsoId(), vm.getDataCenterId());
        if (template == null) {
            s_logger.error("Failed to prepare ISO on secondary or cache storage");
            throw new CloudRuntimeException("Failed to prepare ISO on secondary or cache storage");
        }
        if (template.isBootable()) {
            profile.setBootLoaderType(BootloaderType.CD);
        }
        final GuestOSVO guestOS = _guestOSDao.findById(template.getGuestOSId());
        String displayName = null;
        if (guestOS != null) {
            displayName = guestOS.getDisplayName();
        }
        final TemplateObjectTO iso = (TemplateObjectTO) template.getTO();
        iso.setGuestOsType(displayName);
        final DiskTO disk = new DiskTO(iso, 3L, null, Volume.Type.ISO);
        profile.addDisk(disk);
    } else {
        final TemplateObjectTO iso = new TemplateObjectTO();
        iso.setFormat(ImageFormat.ISO);
        final DiskTO disk = new DiskTO(iso, 3L, null, Volume.Type.ISO);
        profile.addDisk(disk);
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) TemplateInfo(com.cloud.engine.subsystem.api.storage.TemplateInfo) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) GuestOSVO(com.cloud.storage.GuestOSVO) TemplateObjectTO(com.cloud.storage.to.TemplateObjectTO) DiskTO(com.cloud.agent.api.to.DiskTO)

Example 45 with GuestOSVO

use of com.cloud.storage.GuestOSVO in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method createPrivateTemplateRecord.

@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true)
public VMTemplateVO createPrivateTemplateRecord(final CreateTemplateCmd cmd, final Account templateOwner) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final boolean isAdmin = _accountMgr.isAdmin(caller.getId());
    _accountMgr.checkAccess(caller, null, true, templateOwner);
    final String name = cmd.getTemplateName();
    if (name == null || name.length() > 32) {
        throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters");
    }
    if (cmd.getTemplateTag() != null) {
        if (!_accountService.isRootAdmin(caller.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    // do some parameter defaulting
    final Integer bits = cmd.getBits();
    final Boolean requiresHvm = cmd.getRequiresHvm();
    final Boolean passwordEnabled = cmd.isPasswordEnabled();
    Boolean isPublic = cmd.isPublic();
    Boolean featured = cmd.isFeatured();
    final int bitsValue = bits == null ? 64 : bits;
    final boolean requiresHvmValue = requiresHvm == null || requiresHvm;
    final boolean passwordEnabledValue = passwordEnabled != null && passwordEnabled;
    if (isPublic == null) {
        isPublic = Boolean.FALSE;
    }
    final boolean isDynamicScalingEnabled = cmd.isDynamicallyScalable();
    // check whether template owner can create public templates
    final boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(templateOwner.getId());
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
        throw new PermissionDeniedException("Failed to create template " + name + ", only private templates can be created.");
    }
    final Long volumeId = cmd.getVolumeId();
    final Long snapshotId = cmd.getSnapshotId();
    if (volumeId == null && snapshotId == null) {
        throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.");
    }
    if (volumeId != null && snapshotId != null) {
        throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")");
    }
    HypervisorType hyperType;
    final VolumeVO volume;
    SnapshotVO snapshot = null;
    final VMTemplateVO privateTemplate;
    if (volumeId != null) {
        // create template from volume
        volume = _volumeDao.findById(volumeId);
        if (volume == null) {
            throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId);
        }
        // check permissions
        _accountMgr.checkAccess(caller, null, true, volume);
        // created
        if (!_volumeMgr.volumeInactive(volume)) {
            final String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is attached to a non-stopped VM, please stop the VM first";
            if (s_logger.isInfoEnabled()) {
                s_logger.info(msg);
            }
            throw new CloudRuntimeException(msg);
        }
        hyperType = _volumeDao.getHypervisorType(volumeId);
    } else {
        // create template from snapshot
        snapshot = _snapshotDao.findById(snapshotId);
        if (snapshot == null) {
            throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId);
        }
        // Volume could be removed so find including removed to record source template id.
        volume = _volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId());
        // check permissions
        _accountMgr.checkAccess(caller, null, true, snapshot);
        if (snapshot.getState() != Snapshot.State.BackedUp) {
            throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for template creation");
        }
        /*
             * // bug #11428. Operation not supported if vmware and snapshots
             * parent volume = ROOT if(snapshot.getHypervisorType() ==
             * HypervisorType.VMware && snapshotVolume.getVolumeType() ==
             * Type.DATADISK){ throw new UnsupportedServiceException(
             * "operation not supported, snapshot with id " + snapshotId +
             * " is created from Data Disk"); }
             */
        hyperType = snapshot.getHypervisorType();
    }
    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.secondary_storage, volume != null ? volume.getSize() : snapshot.getSize());
    if (!isAdmin || featured == null) {
        featured = Boolean.FALSE;
    }
    final Long guestOSId = cmd.getOsTypeId();
    final GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
    if (guestOS == null) {
        throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist.");
    }
    final Long nextTemplateId = _tmpltDao.getNextInSequence(Long.class, "id");
    final String description = cmd.getDisplayText();
    boolean isExtractable = false;
    Long sourceTemplateId = null;
    if (volume != null) {
        final VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
        if (volume.getIsoId() != null && volume.getIsoId() != 0) {
            sourceTemplateId = volume.getIsoId();
        } else if (volume.getTemplateId() != null) {
            sourceTemplateId = volume.getTemplateId();
        }
    }
    final String templateTag = cmd.getTemplateTag();
    if (templateTag != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding template tag: " + templateTag);
        }
    }
    // if specified from the API, use that one
    if (cmd.getHypervisor() != null) {
        hyperType = HypervisorType.getType(cmd.getHypervisor());
    }
    privateTemplate = new VMTemplateVO(nextTemplateId, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, requiresHvmValue, bitsValue, templateOwner.getId(), null, description, passwordEnabledValue, guestOS.getId(), true, hyperType, templateTag, cmd.getDetails(), false, isDynamicScalingEnabled);
    if (sourceTemplateId != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("This template is getting created from other template, setting source template Id to: " + sourceTemplateId);
        }
    }
    // for region wide storage, set cross zones flag
    final List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
    if (!CollectionUtils.isEmpty(stores)) {
        privateTemplate.setCrossZones(true);
    }
    privateTemplate.setSourceTemplateId(sourceTemplateId);
    final VMTemplateVO template = _tmpltDao.persist(privateTemplate);
    // Increment the number of templates
    if (template != null) {
        final Map<String, String> details = new HashMap<>();
        if (volume != null) {
            final Long vmId = volume.getInstanceId();
            if (vmId != null) {
                final UserVmVO userVm = _userVmDao.findById(vmId);
                if (userVm != null) {
                    _userVmDao.loadDetails(userVm);
                    details.putAll(userVm.getDetails());
                }
            }
        }
        if (cmd.getDetails() != null) {
            // new password will be generated during vm deployment from password enabled template
            details.remove("Encrypted.Password");
            details.putAll(cmd.getDetails());
        }
        if (!details.isEmpty()) {
            privateTemplate.setDetails(details);
            _tmpltDao.saveDetails(privateTemplate);
        }
        _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
        _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.secondary_storage, new Long(volume != null ? volume.getSize() : snapshot.getSize()));
    }
    if (template != null) {
        return template;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) GuestOSVO(com.cloud.storage.GuestOSVO) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ImageStoreVO(com.cloud.storage.datastore.db.ImageStoreVO) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

GuestOSVO (com.cloud.storage.GuestOSVO)62 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 GuestOSHypervisorVO (com.cloud.storage.GuestOSHypervisorVO)23 HostVO (com.cloud.host.HostVO)20 UserVmVO (com.cloud.vm.UserVmVO)20 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)17 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)17 VMSnapshotTO (com.cloud.agent.api.VMSnapshotTO)15 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)15 ArrayList (java.util.ArrayList)15 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)12 VolumeObjectTO (org.apache.cloudstack.storage.to.VolumeObjectTO)12 VirtualMachineTO (com.cloud.agent.api.to.VirtualMachineTO)11 Test (org.junit.Test)11 Command (com.cloud.agent.api.Command)9 CreateVMSnapshotAnswer (com.cloud.agent.api.CreateVMSnapshotAnswer)9 IOException (java.io.IOException)9 HashMap (java.util.HashMap)9 RevertToVMSnapshotAnswer (com.cloud.agent.api.RevertToVMSnapshotAnswer)7 VMTemplateVO (com.cloud.storage.VMTemplateVO)7