Search in sources :

Example 1 with MaintenancePolicy

use of com.cloud.model.enumeration.MaintenancePolicy in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method updateVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_UPDATE, eventDescription = "updating Vm")
public UserVm updateVirtualMachine(final UpdateVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException {
    final String displayName = cmd.getDisplayName();
    final String group = cmd.getGroup();
    final Boolean ha = cmd.getHaEnable();
    final Boolean isDisplayVm = cmd.getDisplayVm();
    final Long id = cmd.getId();
    final Long osTypeId = cmd.getOsTypeId();
    final String userData = cmd.getUserData();
    final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
    final String hostName = cmd.getHostName();
    final Map<String, String> details = cmd.getDetails();
    final Account caller = CallContext.current().getCallingAccount();
    final OptimiseFor optimiseFor = cmd.getOptimiseFor();
    final String manufacturerString = cmd.getManufacturerString();
    final Boolean requiresRestart = cmd.getRequiresRestart();
    final MaintenancePolicy maintenancePolicy = cmd.getMaintenancePolicy();
    final Long bootMenuTimeout = cmd.getBootMenuTimeout();
    final String bootOrder = cmd.getBootOrder();
    final ComplianceStatus complianceStatus = cmd.getComplianceStatus();
    // Input validation and permission checks
    final UserVmVO vmInstance = _vmDao.findById(id);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("unable to find virtual machine with id " + id);
    }
    _accountMgr.checkAccess(caller, null, true, vmInstance);
    // If the flag is specified and is changed
    if (isDisplayVm != null && isDisplayVm != vmInstance.isDisplayVm()) {
        // update vm
        vmInstance.setDisplayVm(isDisplayVm);
        // Resource limit changes
        final ServiceOffering offering = _serviceOfferingDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId());
        _resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.user_vm, isDisplayVm);
        _resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.cpu, isDisplayVm, new Long(offering.getCpu()));
        _resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.memory, isDisplayVm, new Long(offering.getRamSize()));
        // take care of the root volume as well.
        final List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(id, VolumeType.ROOT);
        if (!rootVols.isEmpty()) {
            _volumeService.updateDisplay(rootVols.get(0), isDisplayVm);
        }
        // take care of the data volumes as well.
        final List<VolumeVO> dataVols = _volsDao.findByInstanceAndType(id, VolumeType.DATADISK);
        for (final Volume dataVol : dataVols) {
            _volumeService.updateDisplay(dataVol, isDisplayVm);
        }
    }
    if (details != null && !details.isEmpty()) {
        _vmDao.loadDetails(vmInstance);
        for (final Map.Entry<String, String> entry : details.entrySet()) {
            if (entry instanceof Map.Entry) {
                vmInstance.setDetail(entry.getKey(), entry.getValue());
            }
        }
        _vmDao.saveDetails(vmInstance);
    }
    return updateVirtualMachine(id, displayName, group, ha, isDisplayVm, osTypeId, userData, isDynamicallyScalable, cmd.getHttpMethod(), cmd.getCustomId(), hostName, cmd.getInstanceName(), manufacturerString, optimiseFor, requiresRestart, maintenancePolicy, bootMenuTimeout, bootOrder, complianceStatus);
}
Also used : Account(com.cloud.legacymodel.user.Account) ComplianceStatus(com.cloud.model.enumeration.ComplianceStatus) ServiceOffering(com.cloud.offering.ServiceOffering) OptimiseFor(com.cloud.model.enumeration.OptimiseFor) Entry(java.util.Map.Entry) VmDiskStatsEntry(com.cloud.legacymodel.storage.VmDiskStatsEntry) VmStatsEntry(com.cloud.legacymodel.vm.VmStatsEntry) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Volume(com.cloud.legacymodel.storage.Volume) MaintenancePolicy(com.cloud.model.enumeration.MaintenancePolicy) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent)

Example 2 with MaintenancePolicy

use of com.cloud.model.enumeration.MaintenancePolicy in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method createPrivateTemplate.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true)
public VirtualMachineTemplate createPrivateTemplate(final CreateTemplateCmd command) throws CloudRuntimeException {
    final long templateId = command.getEntityId();
    Long volumeId = command.getVolumeId();
    final Long snapshotId = command.getSnapshotId();
    VMTemplateVO privateTemplate = null;
    final Long accountId = CallContext.current().getCallingAccountId();
    SnapshotVO snapshot = null;
    VolumeVO volume = null;
    OptimiseFor optimiseFor = command.getOptimiseFor();
    String manufacturerString = command.getManufacturerString();
    String cpuFlags = command.getCpuFlags();
    Boolean macLearning = command.getMacLearning();
    MaintenancePolicy maintenancePolicy = command.getMaintenancePolicy();
    try {
        final TemplateInfo tmplInfo = this._tmplFactory.getTemplate(templateId, DataStoreRole.Image);
        long zoneId = 0;
        if (snapshotId != null) {
            snapshot = this._snapshotDao.findById(snapshotId);
            zoneId = snapshot.getDataCenterId();
        } else if (volumeId != null) {
            volume = this._volumeDao.findById(volumeId);
            zoneId = volume.getDataCenterId();
        }
        DataStore store = this._dataStoreMgr.getImageStore(zoneId);
        if (store == null) {
            throw new CloudRuntimeException("cannot find an image store for zone " + zoneId);
        }
        final AsyncCallFuture<TemplateApiResult> future;
        if (snapshotId != null) {
            final DataStoreRole dataStoreRole = ApiResponseHelper.getDataStoreRole(snapshot, this._snapshotStoreDao, this._dataStoreMgr);
            SnapshotInfo snapInfo = this._snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
            if (dataStoreRole == DataStoreRole.Image) {
                if (snapInfo == null) {
                    snapInfo = this._snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
                    if (snapInfo == null) {
                        throw new CloudRuntimeException("Cannot find snapshot " + snapshotId);
                    }
                    if (volumeId == null) {
                        volumeId = snapInfo.getVolumeId();
                    }
                    // We need to copy the snapshot onto secondary.
                    final SnapshotStrategy snapshotStrategy = this._storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.BACKUP);
                    snapshotStrategy.backupSnapshot(snapInfo);
                    // Attempt to grab it again.
                    snapInfo = this._snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
                    if (snapInfo == null) {
                        throw new CloudRuntimeException("Cannot find snapshot " + snapshotId + " on secondary and could not create backup");
                    }
                }
                final DataStore snapStore = snapInfo.getDataStore();
                if (snapStore != null) {
                    // pick snapshot image store to create template
                    store = snapStore;
                }
            }
            future = this._tmpltSvr.createTemplateFromSnapshotAsync(snapInfo, tmplInfo, store);
        } else if (volumeId != null) {
            final VolumeInfo volInfo = this._volFactory.getVolume(volumeId);
            future = this._tmpltSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store);
        } else {
            throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId");
        }
        if (volume != null) {
            final VMInstanceVO vm = this._vmInstanceDao.findById(volume.getInstanceId());
            if (vm != null) {
                if (optimiseFor == null) {
                    optimiseFor = vm.getOptimiseFor();
                }
                if (manufacturerString == null) {
                    manufacturerString = vm.getManufacturerString();
                }
                if (cpuFlags == null) {
                    cpuFlags = vm.getCpuFlags();
                }
                if (macLearning == null) {
                    macLearning = vm.getMacLearning();
                }
                if (maintenancePolicy == null) {
                    maintenancePolicy = vm.getMaintenancePolicy();
                }
            }
        }
        final CommandResult result;
        try {
            result = future.get();
            if (result.isFailed()) {
                s_logger.debug("Failed to create template" + result.getResult());
                throw new CloudRuntimeException("Failed to create template" + result.getResult());
            }
            // create entries in template_zone_ref table
            if (this._dataStoreMgr.isRegionStore(store)) {
                // template created on region store
                this._tmpltSvr.associateTemplateToZone(templateId, null);
            } else {
                final VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
                this._tmpltZoneDao.persist(templateZone);
            }
            if (optimiseFor == null) {
                optimiseFor = OptimiseFor.Generic;
            }
            if (maintenancePolicy == null) {
                maintenancePolicy = MaintenancePolicy.LiveMigrate;
            }
            privateTemplate = this._tmpltDao.findById(templateId);
            privateTemplate.setCpuFlags(cpuFlags);
            privateTemplate.setMacLearning(macLearning);
            privateTemplate.setManufacturerString(manufacturerString);
            privateTemplate.setOptimiseFor(optimiseFor);
            privateTemplate.setMaintenancePolicy(maintenancePolicy);
            this._tmpltDao.persist(privateTemplate);
        } catch (final InterruptedException | ExecutionException e) {
            s_logger.debug("Failed to create template", e);
            throw new CloudRuntimeException("Failed to create template", e);
        }
    } finally {
        if (privateTemplate == null) {
            final VolumeVO volumeFinal = volume;
            final SnapshotVO snapshotFinal = snapshot;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    // template_store_ref entries should have been removed using our
                    // DataObject.processEvent command in case of failure, but clean
                    // it up here to avoid
                    // some leftovers which will cause removing template from
                    // vm_template table fail.
                    TemplateManagerImpl.this._tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
                    // Remove the template_zone_ref record
                    TemplateManagerImpl.this._tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
                    // Remove the template record
                    TemplateManagerImpl.this._tmpltDao.expunge(templateId);
                    // decrement resource count
                    if (accountId != null) {
                        TemplateManagerImpl.this._resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
                        TemplateManagerImpl.this._resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volumeFinal != null ? volumeFinal.getSize() : snapshotFinal.getSize()));
                    }
                }
            });
        }
    }
    if (privateTemplate != null) {
        return privateTemplate;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
Also used : VMTemplateZoneVO(com.cloud.storage.VMTemplateZoneVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) OptimiseFor(com.cloud.model.enumeration.OptimiseFor) DataStoreRole(com.cloud.model.enumeration.DataStoreRole) VolumeVO(com.cloud.storage.VolumeVO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) MaintenancePolicy(com.cloud.model.enumeration.MaintenancePolicy) ExecutionException(java.util.concurrent.ExecutionException) SnapshotStrategy(com.cloud.engine.subsystem.api.storage.SnapshotStrategy) VMInstanceVO(com.cloud.vm.VMInstanceVO) TemplateApiResult(com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult) Date(java.util.Date) CommandResult(com.cloud.storage.command.CommandResult) TemplateInfo(com.cloud.engine.subsystem.api.storage.TemplateInfo) SnapshotInfo(com.cloud.engine.subsystem.api.storage.SnapshotInfo) SnapshotVO(com.cloud.storage.SnapshotVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 3 with MaintenancePolicy

use of com.cloud.model.enumeration.MaintenancePolicy in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method updateTemplateOrIso.

private VMTemplateVO updateTemplateOrIso(final BaseUpdateTemplateOrIsoCmd cmd) {
    final Long id = cmd.getId();
    final String name = cmd.getTemplateName();
    final String displayText = cmd.getDisplayText();
    final String format = cmd.getFormat();
    final Long guestOSId = cmd.getOsTypeId();
    final Boolean passwordEnabled = cmd.getPasswordEnabled();
    final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
    final Boolean isRoutingTemplate = cmd.isRoutingType();
    final Boolean bootable = cmd.getBootable();
    final Integer sortKey = cmd.getSortKey();
    final Map details = cmd.getDetails();
    final Account account = CallContext.current().getCallingAccount();
    final String url = cmd.getUrl();
    final OptimiseFor optimiseFor = cmd.getOptimiseFor();
    final String manufacturerString = cmd.getManufacturerString();
    final String cpuFlags = cmd.getCpuFlags();
    final Boolean macLearning = cmd.getMacLearning();
    final MaintenancePolicy maintenancePolicy = cmd.getMaintenancePolicy();
    final Boolean isRemoteGatewayTemplate = cmd.getIsRemoteGatewayTemplate();
    // verify that template exists
    VMTemplateVO template = this._tmpltDao.findById(id);
    if (template == null || template.getRemoved() != null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
        ex.addProxyObject(String.valueOf(id), "templateId");
        throw ex;
    }
    verifyTemplateId(id);
    // do a permission check
    this._accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
    if (cmd.isRoutingType() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
        }
    }
    // update is needed if any of the fields below got filled by the user
    final boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && optimiseFor == null && manufacturerString == null && isRemoteGatewayTemplate == null && cpuFlags == null && macLearning == null && passwordEnabled == null && bootable == null && sortKey == null && isDynamicallyScalable == null && isRoutingTemplate == null && url == null && details == null);
    if (!updateNeeded) {
        return template;
    }
    template = this._tmpltDao.createForUpdate(id);
    if (name != null) {
        template.setName(name);
    }
    if (displayText != null) {
        template.setDisplayText(displayText);
    }
    if (sortKey != null) {
        template.setSortKey(sortKey);
    }
    if (optimiseFor != null) {
        template.setOptimiseFor(optimiseFor);
    }
    if (manufacturerString != null) {
        template.setManufacturerString(manufacturerString);
    }
    if (cpuFlags != null) {
        template.setCpuFlags(cpuFlags);
    }
    if (macLearning != null) {
        template.setMacLearning(macLearning);
    }
    if (maintenancePolicy != null) {
        template.setMaintenancePolicy(maintenancePolicy);
    }
    if (isRemoteGatewayTemplate != null) {
        template.setRemoteGatewayTemplate(isRemoteGatewayTemplate);
    }
    final ImageFormat imageFormat;
    if (format != null) {
        try {
            imageFormat = ImageFormat.valueOf(format.toUpperCase());
        } catch (final IllegalArgumentException e) {
            throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
        }
        template.setFormat(imageFormat);
    }
    if (guestOSId != null) {
        final long oldGuestOSId = template.getGuestOSId();
        final GuestOSVO guestOS = this._guestOSDao.findById(guestOSId);
        if (guestOS == null) {
            throw new InvalidParameterValueException("Please specify a valid guest OS ID.");
        } else {
            template.setGuestOSId(guestOSId);
        }
        if (guestOSId != oldGuestOSId) {
            // vm guest os type need to be updated if template guest os id changes.
            final SearchCriteria<VMInstanceVO> sc = this._vmInstanceDao.createSearchCriteria();
            sc.addAnd("templateId", SearchCriteria.Op.EQ, id);
            sc.addAnd("state", SearchCriteria.Op.NEQ, State.Expunging);
            final List<VMInstanceVO> vms = this._vmInstanceDao.search(sc, null);
            if (vms != null && !vms.isEmpty()) {
                for (final VMInstanceVO vm : vms) {
                    vm.setGuestOSId(guestOSId);
                    this._vmInstanceDao.update(vm.getId(), vm);
                }
            }
        }
    }
    if (passwordEnabled != null) {
        template.setEnablePassword(passwordEnabled);
    }
    if (bootable != null) {
        template.setBootable(bootable);
    }
    if (isDynamicallyScalable != null) {
        template.setDynamicallyScalable(isDynamicallyScalable);
    }
    if (url != null) {
        template.setUrl(url);
    }
    if (isRoutingTemplate != null) {
        if (isRoutingTemplate) {
            template.setTemplateType(TemplateType.ROUTING);
        } else {
            template.setTemplateType(TemplateType.USER);
        }
    }
    if (details != null && !details.isEmpty()) {
        template.setDetails(details);
        this._tmpltDao.saveDetails(template);
    }
    this._tmpltDao.update(id, template);
    return this._tmpltDao.findById(id);
}
Also used : Account(com.cloud.legacymodel.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) GuestOSVO(com.cloud.storage.GuestOSVO) OptimiseFor(com.cloud.model.enumeration.OptimiseFor) ImageFormat(com.cloud.model.enumeration.ImageFormat) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) MaintenancePolicy(com.cloud.model.enumeration.MaintenancePolicy) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

MaintenancePolicy (com.cloud.model.enumeration.MaintenancePolicy)3 OptimiseFor (com.cloud.model.enumeration.OptimiseFor)3 ActionEvent (com.cloud.event.ActionEvent)2 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)2 Account (com.cloud.legacymodel.user.Account)2 VMTemplateVO (com.cloud.storage.VMTemplateVO)2 VolumeVO (com.cloud.storage.VolumeVO)2 VMInstanceVO (com.cloud.vm.VMInstanceVO)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 DataStore (com.cloud.engine.subsystem.api.storage.DataStore)1 SnapshotInfo (com.cloud.engine.subsystem.api.storage.SnapshotInfo)1 SnapshotStrategy (com.cloud.engine.subsystem.api.storage.SnapshotStrategy)1 TemplateInfo (com.cloud.engine.subsystem.api.storage.TemplateInfo)1 TemplateApiResult (com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult)1 VolumeInfo (com.cloud.engine.subsystem.api.storage.VolumeInfo)1 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)1 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)1 VmDiskStatsEntry (com.cloud.legacymodel.storage.VmDiskStatsEntry)1 Volume (com.cloud.legacymodel.storage.Volume)1