use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class UserVmManagerImpl method createVirtualMachine.
@DB
protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate tmplt, String hostName, String displayName, Account owner, Long diskOfferingId, Long diskSize, List<NetworkVO> networkList, List<Long> securityGroupIdList, String group, HTTPMethod httpmethod, String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean isDisplayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParameters, String customId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
_accountMgr.checkAccess(caller, null, true, owner);
if (owner.getState() == Account.State.disabled) {
throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner);
}
VMTemplateVO template = _templateDao.findById(tmplt.getId());
if (template != null) {
_templateDao.loadDetails(template);
}
long accountId = owner.getId();
assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be specified together";
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId());
}
// check if zone is dedicated
DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
if (dedicatedZone != null) {
DomainVO domain = _domainDao.findById(dedicatedZone.getDomainId());
if (domain == null) {
throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone);
}
// check that caller can operate with domain
_configMgr.checkZoneAccess(caller, zone);
// check that vm owner can create vm in the domain
_configMgr.checkZoneAccess(owner, zone);
}
ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId());
if (offering.isDynamic()) {
offering.setDynamicFlag(true);
validateCustomParameters(offering, customParameters);
offering = _offeringDao.getcomputeOffering(offering, customParameters);
}
// check if account/domain is with in resource limits to create a new vm
boolean isIso = Storage.ImageFormat.ISO == template.getFormat();
// For baremetal, size can be null
Long tmp = _templateDao.findById(template.getId()).getSize();
long size = 0;
if (tmp != null) {
size = tmp;
}
if (diskOfferingId != null) {
DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
if (diskOffering != null && diskOffering.isCustomized()) {
if (diskSize == null) {
throw new InvalidParameterValueException("This disk offering requires a custom size specified");
}
Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
if ((diskSize < customDiskOfferingMinSize) || (diskSize > customDiskOfferingMaxSize)) {
throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
}
size = size + diskSize * (1024 * 1024 * 1024);
}
size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
}
resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso || diskOfferingId == null ? 1 : 2));
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
// verify security group ids
if (securityGroupIdList != null) {
for (Long securityGroupId : securityGroupIdList) {
SecurityGroup sg = _securityGroupDao.findById(securityGroupId);
if (sg == null) {
throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId);
} else {
// verify permissions
_accountMgr.checkAccess(caller, null, true, owner, sg);
}
}
}
// check that the affinity groups exist
if (affinityGroupIdList != null) {
for (Long affinityGroupId : affinityGroupIdList) {
AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
if (ag == null) {
throw new InvalidParameterValueException("Unable to find affinity group " + ag);
} else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {
throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + " , Please try again after removing the affinity group");
} else {
// verify permissions
if (ag.getAclType() == ACLType.Domain) {
_accountMgr.checkAccess(caller, null, false, owner, ag);
// make sure the owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
}
}
} else {
_accountMgr.checkAccess(caller, null, true, owner, ag);
// make sure the owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
if (ag.getAccountId() != owner.getAccountId()) {
throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
}
}
}
}
}
}
HypervisorType hypervisorType = null;
if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) {
if (hypervisor == null || hypervisor == HypervisorType.None) {
throw new InvalidParameterValueException("hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid");
}
hypervisorType = hypervisor;
} else {
if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) {
throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the template");
}
hypervisorType = template.getHypervisorType();
}
if (hypervisorType != HypervisorType.BareMetal) {
// check if we have available pools for vm deployment
long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
if (availablePools < 1) {
throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
}
}
if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
}
List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
}
if (isIso && !template.isBootable()) {
throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
}
// Check templates permissions
_accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
// check if the user data is correct
validateUserData(userData, httpmethod);
// Find an SSH public key corresponding to the key pair name, if one is
// given
String sshPublicKey = null;
if (sshKeyPair != null && !sshKeyPair.equals("")) {
SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
if (pair == null) {
throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.");
}
sshPublicKey = pair.getPublicKey();
}
List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>();
LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<String, NicProfile>();
short defaultNetworkNumber = 0;
boolean securityGroupEnabled = false;
boolean vpcNetwork = false;
for (NetworkVO network : networkList) {
if ((network.getDataCenterId() != zone.getId())) {
if (!network.isStrechedL2Network()) {
throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId());
}
NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
if (physicalNetworkId == null) {
throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
}
String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
}
}
//relax the check if the caller is admin account
if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) {
throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm");
}
}
IpAddresses requestedIpPair = null;
if (requestedIps != null && !requestedIps.isEmpty()) {
requestedIpPair = requestedIps.get(network.getId());
}
if (requestedIpPair == null) {
requestedIpPair = new IpAddresses(null, null);
} else {
_networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address());
}
NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address());
if (defaultNetworkNumber == 0) {
defaultNetworkNumber++;
// if user requested specific ip for default network, add it
if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {
_networkModel.checkRequestedIpAddresses(network.getId(), defaultIps.getIp4Address(), defaultIps.getIp6Address());
profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
}
profile.setDefaultNic(true);
if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {
if ((userData != null) && (!userData.isEmpty())) {
throw new InvalidParameterValueException("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
}
if ((sshPublicKey != null) && (!sshPublicKey.isEmpty())) {
throw new InvalidParameterValueException("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
}
if (template.getEnablePassword()) {
throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
}
}
}
networks.add(new Pair<NetworkVO, NicProfile>(network, profile));
if (_networkModel.isSecurityGroupSupportedInNetwork(network)) {
securityGroupEnabled = true;
}
// vm can't be a part of more than 1 VPC network
if (network.getVpcId() != null) {
if (vpcNetwork) {
throw new InvalidParameterValueException("Vm can't be a part of more than 1 VPC network");
}
vpcNetwork = true;
}
networkNicMap.put(network.getUuid(), profile);
}
if (securityGroupIdList != null && !securityGroupIdList.isEmpty() && !securityGroupEnabled) {
throw new InvalidParameterValueException("Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network");
}
// gateway for the vm
if (defaultNetworkNumber == 0) {
throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm");
} else if (defaultNetworkNumber > 1) {
throw new InvalidParameterValueException("Only 1 default network per vm is supported");
}
long id = _vmDao.getNextInSequence(Long.class, "id");
if (hostName != null) {
// Check is hostName is RFC compliant
checkNameForRFCCompliance(hostName);
}
String instanceName = null;
String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
if (_instanceNameFlag && hypervisor.equals(HypervisorType.VMware)) {
if (hostName == null) {
if (displayName != null) {
hostName = displayName;
} else {
hostName = generateHostName(uuidName);
}
}
// If global config vm.instancename.flag is set to true, then CS will set guest VM's name as it appears on the hypervisor, to its hostname.
// In case of VMware since VM name must be unique within a DC, check if VM with the same hostname already exists in the zone.
VMInstanceVO vmByHostName = _vmInstanceDao.findVMByHostNameInZone(hostName, zone.getId());
if (vmByHostName != null && vmByHostName.getState() != VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("There already exists a VM by the name: " + hostName + ".");
}
} else {
if (hostName == null) {
//Generate name using uuid and instance.name global config
hostName = generateHostName(uuidName);
}
}
if (hostName != null) {
// Check is hostName is RFC compliant
checkNameForRFCCompliance(hostName);
}
instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
// Check if VM with instanceName already exists.
VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);
if (vmObj != null && vmObj.getState() != VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("There already exists a VM by the display name supplied");
}
checkIfHostNameUniqueInNtwkDomain(hostName, networkList);
long userId = CallContext.current().getCallingUserId();
if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
if (!userVOs.isEmpty()) {
userId = userVOs.get(0).getId();
}
}
UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters);
// Assign instance to the group
try {
if (group != null) {
boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
if (!addToGroup) {
throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
}
}
} catch (Exception ex) {
throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
}
_securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
if (affinityGroupIdList != null && !affinityGroupIdList.isEmpty()) {
_affinityGroupVMMapDao.updateMap(vm.getId(), affinityGroupIdList);
}
CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid());
return vm;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class UserVmManagerImpl method startVirtualMachine.
@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams, String deploymentPlannerToUse) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
// Input validation
Account callerAccount = CallContext.current().getCallingAccount();
UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
// if account is removed, return error
if (callerAccount != null && callerAccount.getRemoved() != null) {
throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed");
}
UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
}
_accountMgr.checkAccess(callerAccount, null, true, vm);
Account owner = _accountDao.findById(vm.getAccountId());
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());
}
Host destinationHost = null;
if (hostId != null) {
Account account = CallContext.current().getCallingAccount();
if (!_accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter hostid can only be specified by a Root Admin, permission denied");
}
destinationHost = _hostDao.findById(hostId);
if (destinationHost == null) {
throw new InvalidParameterValueException("Unable to find the host to deploy the VM, host id=" + hostId);
}
}
// check if vm is security group enabled
if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() && !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) && _networkModel.canAddDefaultSecurityGroup()) {
// if vm is not mapped to security group, create a mapping
if (s_logger.isDebugEnabled()) {
s_logger.debug("Vm " + vm + " is security group enabled, but not mapped to default security group; creating the mapping automatically");
}
SecurityGroup defaultSecurityGroup = _securityGroupMgr.getDefaultSecurityGroup(vm.getAccountId());
if (defaultSecurityGroup != null) {
List<Long> groupList = new ArrayList<Long>();
groupList.add(defaultSecurityGroup.getId());
_securityGroupMgr.addInstanceToGroups(vmId, groupList);
}
}
DataCenterDeployment plan = null;
if (destinationHost != null) {
s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
}
// Set parameters
Map<VirtualMachineProfile.Param, Object> params = null;
VMTemplateVO template = null;
if (vm.isUpdateParameters()) {
_vmDao.loadDetails(vm);
// Check that the password was passed in and is valid
template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
String password = "saved_password";
if (template.getEnablePassword()) {
if (vm.getDetail("password") != null) {
password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
} else {
password = _mgr.generateRandomPassword();
}
}
if (!validPassword(password)) {
throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.");
}
// 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);
params = new HashMap<VirtualMachineProfile.Param, Object>();
if (additionalParams != null) {
params.putAll(additionalParams);
}
params.put(VirtualMachineProfile.Param.VmPassword, password);
}
VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
DeploymentPlanner planner = null;
if (deploymentPlannerToUse != null) {
// if set to null, the deployment planner would be later figured out either from global config var, or from
// the service offering
planner = _planningMgr.getDeploymentPlannerByName(deploymentPlannerToUse);
if (planner == null) {
throw new InvalidParameterValueException("Can't find a planner by name " + deploymentPlannerToUse);
}
}
String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params);
Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
if (vm != null && vm.isUpdateParameters()) {
// display purposes
if (template.getEnablePassword()) {
vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
vm.setUpdateParameters(false);
if (vm.getDetail("password") != null) {
_vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
}
_vmDao.update(vm.getId(), vm);
}
}
return vmParamPair;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class UserVmManagerImpl method resetVMPassword.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_RESETPASSWORD, eventDescription = "resetting Vm password", async = true)
public UserVm resetVMPassword(ResetVMPasswordCmd cmd, String password) throws ResourceUnavailableException, InsufficientCapacityException {
Account caller = CallContext.current().getCallingAccount();
Long vmId = cmd.getId();
UserVmVO userVm = _vmDao.findById(cmd.getId());
// Do parameters input validation
if (userVm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + cmd.getId());
}
_vmDao.loadDetails(userVm);
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(userVm.getTemplateId());
if (template == null || !template.getEnablePassword()) {
throw new InvalidParameterValueException("Fail to reset password for the virtual machine, the template is not password enabled");
}
if (userVm.getState() == State.Error || userVm.getState() == State.Expunging) {
s_logger.error("vm is not in the right state: " + vmId);
throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
}
_accountMgr.checkAccess(caller, null, true, userVm);
boolean result = resetVMPasswordInternal(vmId, password);
if (result) {
userVm.setPassword(password);
// 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(userVm, password);
} else {
throw new CloudRuntimeException("Failed to reset password for the virtual machine ");
}
return userVm;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class HypervisorTemplateAdapter method createTemplateAsyncCallBack.
protected Void createTemplateAsyncCallBack(AsyncCallbackDispatcher<HypervisorTemplateAdapter, TemplateApiResult> callback, CreateTemplateContext<TemplateApiResult> context) {
TemplateApiResult result = callback.getResult();
TemplateInfo template = context.template;
if (result.isSuccess()) {
VMTemplateVO tmplt = _tmpltDao.findById(template.getId());
// need to grant permission for public templates
if (tmplt.isPublicTemplate()) {
_messageBus.publish(_name, TemplateManager.MESSAGE_REGISTER_PUBLIC_TEMPLATE_EVENT, PublishScope.LOCAL, tmplt.getId());
}
long accountId = tmplt.getAccountId();
if (template.getSize() != null) {
// publish usage event
String etype = EventTypes.EVENT_TEMPLATE_CREATE;
if (tmplt.getFormat() == ImageFormat.ISO) {
etype = EventTypes.EVENT_ISO_CREATE;
}
// get physical size from template_store_ref table
long physicalSize = 0;
DataStore ds = template.getDataStore();
TemplateDataStoreVO tmpltStore = _tmpltStoreDao.findByStoreTemplate(ds.getId(), template.getId());
if (tmpltStore != null) {
physicalSize = tmpltStore.getPhysicalSize();
} else {
s_logger.warn("No entry found in template_store_ref for template id: " + template.getId() + " and image store id: " + ds.getId() + " at the end of registering template!");
}
Scope dsScope = ds.getScope();
if (dsScope.getScopeType() == ScopeType.ZONE) {
if (dsScope.getScopeId() != null) {
UsageEventUtils.publishUsageEvent(etype, template.getAccountId(), dsScope.getScopeId(), template.getId(), template.getName(), null, null, physicalSize, template.getSize(), VirtualMachineTemplate.class.getName(), template.getUuid());
} else {
s_logger.warn("Zone scope image store " + ds.getId() + " has a null scope id");
}
} else if (dsScope.getScopeType() == ScopeType.REGION) {
// publish usage event for region-wide image store using a -1 zoneId for 4.2, need to revisit post-4.2
UsageEventUtils.publishUsageEvent(etype, template.getAccountId(), -1, template.getId(), template.getName(), null, null, physicalSize, template.getSize(), VirtualMachineTemplate.class.getName(), template.getUuid());
}
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.secondary_storage, template.getSize());
}
}
return null;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class HypervisorTemplateAdapter method delete.
@Override
@DB
public boolean delete(TemplateProfile profile) {
boolean success = true;
VMTemplateVO template = profile.getTemplate();
// find all eligible image stores for this template
List<DataStore> imageStores = templateMgr.getImageStoreByTemplate(template.getId(), profile.getZoneId());
if (imageStores == null || imageStores.size() == 0) {
// already destroyed on image stores
s_logger.info("Unable to find image store still having template: " + template.getName() + ", so just mark the template removed");
} else {
// Make sure the template is downloaded to all found image stores
for (DataStore store : imageStores) {
long storeId = store.getId();
List<TemplateDataStoreVO> templateStores = _tmpltStoreDao.listByTemplateStore(template.getId(), storeId);
for (TemplateDataStoreVO templateStore : templateStores) {
if (templateStore.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
String errorMsg = "Please specify a template that is not currently being downloaded.";
s_logger.debug("Template: " + template.getName() + " is currently being downloaded to secondary storage host: " + store.getName() + "; cant' delete it.");
throw new CloudRuntimeException(errorMsg);
}
}
}
String eventType = "";
if (template.getFormat().equals(ImageFormat.ISO)) {
eventType = EventTypes.EVENT_ISO_DELETE;
} else {
eventType = EventTypes.EVENT_TEMPLATE_DELETE;
}
for (DataStore imageStore : imageStores) {
// publish zone-wide usage event
Long sZoneId = ((ImageStoreEntity) imageStore).getDataCenterId();
if (sZoneId != null) {
UsageEventUtils.publishUsageEvent(eventType, template.getAccountId(), sZoneId, template.getId(), null, VirtualMachineTemplate.class.getName(), template.getUuid());
}
s_logger.info("Delete template from image store: " + imageStore.getName());
AsyncCallFuture<TemplateApiResult> future = imageService.deleteTemplateAsync(imageFactory.getTemplate(template.getId(), imageStore));
try {
TemplateApiResult result = future.get();
success = result.isSuccess();
if (!success) {
s_logger.warn("Failed to delete the template " + template + " from the image store: " + imageStore.getName() + " due to: " + result.getResult());
break;
}
// remove from template_zone_ref
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByZoneTemplate(sZoneId, template.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
//mark all the occurrences of this template in the given store as destroyed.
templateDataStoreDao.removeByTemplateStore(template.getId(), imageStore.getId());
} catch (InterruptedException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
} catch (ExecutionException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
}
}
}
if (success) {
if ((imageStores.size() > 1) && (profile.getZoneId() != null)) {
//if template is stored in more than one image stores, and the zone id is not null, then don't delete other templates.
return success;
}
// delete all cache entries for this template
List<TemplateInfo> cacheTmpls = imageFactory.listTemplateOnCache(template.getId());
for (TemplateInfo tmplOnCache : cacheTmpls) {
s_logger.info("Delete template from image cache store: " + tmplOnCache.getDataStore().getName());
tmplOnCache.delete();
}
// find all eligible image stores for this template
List<DataStore> iStores = templateMgr.getImageStoreByTemplate(template.getId(), null);
if (iStores == null || iStores.size() == 0) {
// Mark template as Inactive.
template.setState(VirtualMachineTemplate.State.Inactive);
_tmpltDao.update(template.getId(), template);
// Decrement the number of templates and total secondary storage
// space used by the account
Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
_resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
_resourceLimitMgr.recalculateResourceCount(template.getAccountId(), account.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// remove its related ACL permission
Pair<Class<?>, Long> tmplt = new Pair<Class<?>, Long>(VirtualMachineTemplate.class, template.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, tmplt);
}
return success;
}
Aggregations