Search in sources :

Example 56 with VirtualMachineTemplate

use of com.cloud.template.VirtualMachineTemplate in project cosmic by MissionCriticalCloud.

the class CreateTemplateCmdByAdmin method execute.

@Override
public void execute() {
    CallContext.current().setEventDetails("Template Id: " + getEntityId() + ((getSnapshotId() == null) ? " from volume Id: " + getVolumeId() : " from snapshot Id: " + getSnapshotId()));
    VirtualMachineTemplate template = null;
    template = _templateService.createPrivateTemplate(this);
    if (template != null) {
        final List<TemplateResponse> templateResponses = _responseGenerator.createTemplateResponses(ResponseView.Full, template.getId(), snapshotId, volumeId, false);
        TemplateResponse response = new TemplateResponse();
        if (templateResponses != null && !templateResponses.isEmpty()) {
            response = templateResponses.get(0);
        }
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private template");
    }
}
Also used : VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ServerApiException(com.cloud.api.ServerApiException) TemplateResponse(com.cloud.api.response.TemplateResponse)

Example 57 with VirtualMachineTemplate

use of com.cloud.template.VirtualMachineTemplate in project cosmic by MissionCriticalCloud.

the class RegisterIsoCmdByAdmin method execute.

@Override
public void execute() throws ResourceAllocationException {
    final VirtualMachineTemplate template = _templateService.registerIso(this);
    if (template != null) {
        final ListResponse<TemplateResponse> response = new ListResponse<>();
        final List<TemplateResponse> templateResponses = _responseGenerator.createIsoResponses(ResponseView.Full, template, zoneId, false);
        response.setResponses(templateResponses);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to register iso");
    }
}
Also used : VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ListResponse(com.cloud.api.response.ListResponse) ServerApiException(com.cloud.api.ServerApiException) TemplateResponse(com.cloud.api.response.TemplateResponse)

Example 58 with VirtualMachineTemplate

use of com.cloud.template.VirtualMachineTemplate in project cloudstack by apache.

the class UserVmManagerImpl method moveVMToUser.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false)
public UserVm moveVMToUser(final AssignVMCmd cmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    // VERIFICATIONS and VALIDATIONS
    // VV 1: verify the two users
    Account caller = CallContext.current().getCallingAccount();
    if (!_accountMgr.isRootAdmin(caller.getId()) && !_accountMgr.isDomainAdmin(caller.getId())) {
        // VMs
        throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType());
    }
    // get and check the valid VM
    final UserVmVO vm = _vmDao.findById(cmd.getVmId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm by that id " + cmd.getVmId());
    } else if (vm.getState() == State.Running) {
        // running
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is Running, unable to move the vm " + vm);
        }
        InvalidParameterValueException ex = new InvalidParameterValueException("VM is Running, unable to move the vm with specified vmId");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    final Account oldAccount = _accountService.getActiveAccountById(vm.getAccountId());
    if (oldAccount == null) {
        throw new InvalidParameterValueException("Invalid account for VM " + vm.getAccountId() + " in domain.");
    }
    final Account newAccount = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
    if (newAccount == null) {
        throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId());
    }
    if (newAccount.getState() == Account.State.disabled) {
        throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled.");
    }
    if (cmd.getProjectId() != null && cmd.getDomainId() == null) {
        throw new InvalidParameterValueException("Please provide a valid domain ID; cannot assign VM to a project if domain ID is NULL.");
    }
    // check caller has access to both the old and new account
    _accountMgr.checkAccess(caller, null, true, oldAccount);
    _accountMgr.checkAccess(caller, null, true, newAccount);
    // make sure the accounts are not same
    if (oldAccount.getAccountId() == newAccount.getAccountId()) {
        throw new InvalidParameterValueException("The new account is the same as the old account. Account id =" + oldAccount.getAccountId());
    }
    // don't allow to move the vm if there are existing PF/LB/Static Nat
    // rules, or vm is assigned to static Nat ip
    List<PortForwardingRuleVO> pfrules = _portForwardingDao.listByVm(cmd.getVmId());
    if (pfrules != null && pfrules.size() > 0) {
        throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user.");
    }
    List<FirewallRuleVO> snrules = _rulesDao.listStaticNatByVmId(vm.getId());
    if (snrules != null && snrules.size() > 0) {
        throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user.");
    }
    List<LoadBalancerVMMapVO> maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId());
    if (maps != null && maps.size() > 0) {
        throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user.");
    }
    // check for one on one nat
    List<IPAddressVO> ips = _ipAddressDao.findAllByAssociatedVmId(cmd.getVmId());
    for (IPAddressVO ip : ips) {
        if (ip.isOneToOneNat()) {
            throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString());
        }
    }
    final List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
    for (VolumeVO volume : volumes) {
        List<SnapshotVO> snapshots = _snapshotDao.listByStatusNotIn(volume.getId(), Snapshot.State.Destroyed, Snapshot.State.Error);
        if (snapshots != null && snapshots.size() > 0) {
            throw new InvalidParameterValueException("Snapshots exists for volume: " + volume.getName() + ", Detach volume or remove snapshots for volume before assigning VM to another user.");
        }
    }
    DataCenterVO zone = _dcDao.findById(vm.getDataCenterId());
    // Get serviceOffering and Volumes for Virtual Machine
    final ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
    // Remove vm from instance group
    removeInstanceFromInstanceGroup(cmd.getVmId());
    // VV 2: check if account/domain is with in resource limits to create a new vm
    if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
        resourceLimitCheck(newAccount, vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
    }
    // VV 3: check if volumes and primary storage space are with in resource limits
    _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, _volsDao.findByInstance(cmd.getVmId()).size());
    Long totalVolumesSize = (long) 0;
    for (VolumeVO volume : volumes) {
        totalVolumesSize += volume.getSize();
    }
    _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.primary_storage, totalVolumesSize);
    // VV 4: Check if new owner can use the vm template
    VirtualMachineTemplate template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
    if (template == null) {
        throw new InvalidParameterValueException(String.format("Template for VM: %s cannot be found", vm.getUuid()));
    }
    if (!template.isPublicTemplate()) {
        Account templateOwner = _accountMgr.getAccount(template.getAccountId());
        _accountMgr.checkAccess(newAccount, null, true, templateOwner);
    }
    // VV 5: check the new account can create vm in the domain
    DomainVO domain = _domainDao.findById(cmd.getDomainId());
    _accountMgr.checkAccess(newAccount, domain);
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // generate destroy vm event for usage
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());
            // update resource counts for old account
            resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
            // OWNERSHIP STEP 1: update the vm owner
            vm.setAccountId(newAccount.getAccountId());
            vm.setDomainId(cmd.getDomainId());
            _vmDao.persist(vm);
            // OS 2: update volume
            for (VolumeVO volume : volumes) {
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
                _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
                _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
                volume.setAccountId(newAccount.getAccountId());
                volume.setDomainId(newAccount.getDomainId());
                _volsDao.persist(volume);
                _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
                _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
            }
            // update resource count of new account
            if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
                resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
            }
            // generate usage events to account for this change
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());
        }
    });
    VirtualMachine vmoi = _itMgr.findById(vm.getId());
    VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);
    // OS 3: update the network
    List<Long> networkIdList = cmd.getNetworkIds();
    List<Long> securityGroupIdList = cmd.getSecurityGroupIdList();
    if (zone.getNetworkType() == NetworkType.Basic) {
        if (networkIdList != null && !networkIdList.isEmpty()) {
            throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM");
        }
        // cleanup the old security groups
        _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId());
        // cleanup the network for the oldOwner
        _networkMgr.cleanupNics(vmOldProfile);
        _networkMgr.removeNics(vmOldProfile);
        // security groups will be recreated for the new account, when the
        // VM is started
        List<NetworkVO> networkList = new ArrayList<NetworkVO>();
        // Get default guest network in Basic zone
        Network defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId());
        if (defaultNetwork == null) {
            throw new InvalidParameterValueException("Unable to find a default network to start a vm");
        } else {
            networkList.add(_networkDao.findById(defaultNetwork.getId()));
        }
        boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware);
        if (securityGroupIdList != null && isVmWare) {
            throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
        } else if (!isVmWare && _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkModel.canAddDefaultSecurityGroup()) {
            if (securityGroupIdList == null) {
                securityGroupIdList = new ArrayList<Long>();
            }
            SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccount.getId());
            if (defaultGroup != null) {
                // check if security group id list already contains Default
                // security group, and if not - add it
                boolean defaultGroupPresent = false;
                for (Long securityGroupId : securityGroupIdList) {
                    if (securityGroupId.longValue() == defaultGroup.getId()) {
                        defaultGroupPresent = true;
                        break;
                    }
                }
                if (!defaultGroupPresent) {
                    securityGroupIdList.add(defaultGroup.getId());
                }
            } else {
                // create default security group for the account
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one");
                }
                defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName());
                securityGroupIdList.add(defaultGroup.getId());
            }
        }
        LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
        NicProfile profile = new NicProfile();
        profile.setDefaultNic(true);
        networks.put(networkList.get(0), new ArrayList<NicProfile>(Arrays.asList(profile)));
        VirtualMachine vmi = _itMgr.findById(vm.getId());
        VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
        _networkMgr.allocate(vmProfile, networks, null);
        _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
        s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
    } else {
        Set<NetworkVO> applicableNetworks = new LinkedHashSet<>();
        Map<Long, String> requestedIPv4ForNics = new HashMap<>();
        Map<Long, String> requestedIPv6ForNics = new HashMap<>();
        if (zone.isSecurityGroupEnabled()) {
            // advanced zone with security groups
            // cleanup the old security groups
            _securityGroupMgr.removeInstanceFromGroups(cmd.getVmId());
            // if networkIdList is null and the first network of vm is shared network, then keep it if possible
            if (networkIdList == null || networkIdList.isEmpty()) {
                NicVO defaultNicOld = _nicDao.findDefaultNicForVM(vm.getId());
                if (defaultNicOld != null) {
                    NetworkVO defaultNetworkOld = _networkDao.findById(defaultNicOld.getNetworkId());
                    if (canAccountUseNetwork(newAccount, defaultNetworkOld)) {
                        applicableNetworks.add(defaultNetworkOld);
                        requestedIPv4ForNics.put(defaultNetworkOld.getId(), defaultNicOld.getIPv4Address());
                        requestedIPv6ForNics.put(defaultNetworkOld.getId(), defaultNicOld.getIPv6Address());
                        s_logger.debug("AssignVM: use old shared network " + defaultNetworkOld.getName() + " with old ip " + defaultNicOld.getIPv4Address() + " on default nic of vm:" + vm.getInstanceName());
                    }
                }
            }
            if (networkIdList != null && !networkIdList.isEmpty()) {
                // add any additional networks
                for (Long networkId : networkIdList) {
                    NetworkVO network = _networkDao.findById(networkId);
                    if (network == null) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
                        ex.addProxyObject(networkId.toString(), "networkId");
                        throw ex;
                    }
                    _networkModel.checkNetworkPermissions(newAccount, network);
                    // don't allow to use system networks
                    NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
                    if (networkOffering.isSystemOnly()) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
                        ex.addProxyObject(network.getUuid(), "networkId");
                        throw ex;
                    }
                    if (network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) {
                        NicVO nicOld = _nicDao.findByNtwkIdAndInstanceId(network.getId(), vm.getId());
                        if (nicOld != null) {
                            requestedIPv4ForNics.put(network.getId(), nicOld.getIPv4Address());
                            requestedIPv6ForNics.put(network.getId(), nicOld.getIPv6Address());
                            s_logger.debug("AssignVM: use old shared network " + network.getName() + " with old ip " + nicOld.getIPv4Address() + " on nic of vm:" + vm.getInstanceName());
                        }
                    }
                    s_logger.debug("AssignVM: Added network " + network.getName() + " to vm " + vm.getId());
                    applicableNetworks.add(network);
                }
            }
            // cleanup the network for the oldOwner
            _networkMgr.cleanupNics(vmOldProfile);
            _networkMgr.removeNics(vmOldProfile);
            // add the new nics
            LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
            int toggle = 0;
            NetworkVO defaultNetwork = null;
            for (NetworkVO appNet : applicableNetworks) {
                NicProfile defaultNic = new NicProfile();
                if (toggle == 0) {
                    defaultNic.setDefaultNic(true);
                    defaultNetwork = appNet;
                    toggle++;
                }
                defaultNic.setRequestedIPv4(requestedIPv4ForNics.get(appNet.getId()));
                defaultNic.setRequestedIPv6(requestedIPv6ForNics.get(appNet.getId()));
                networks.put(appNet, new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
            }
            boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware);
            if (securityGroupIdList != null && isVmWare) {
                throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
            } else if (!isVmWare && (defaultNetwork == null || _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork)) && _networkModel.canAddDefaultSecurityGroup()) {
                if (securityGroupIdList == null) {
                    securityGroupIdList = new ArrayList<Long>();
                }
                SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccount.getId());
                if (defaultGroup != null) {
                    // check if security group id list already contains Default
                    // security group, and if not - add it
                    boolean defaultGroupPresent = false;
                    for (Long securityGroupId : securityGroupIdList) {
                        if (securityGroupId.longValue() == defaultGroup.getId()) {
                            defaultGroupPresent = true;
                            break;
                        }
                    }
                    if (!defaultGroupPresent) {
                        securityGroupIdList.add(defaultGroup.getId());
                    }
                } else {
                    // create default security group for the account
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one");
                    }
                    defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName());
                    securityGroupIdList.add(defaultGroup.getId());
                }
            }
            VirtualMachine vmi = _itMgr.findById(vm.getId());
            VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
            if (applicableNetworks.isEmpty()) {
                throw new InvalidParameterValueException("No network is specified, please specify one when you move the vm. For now, please add a network to VM on NICs tab.");
            } else {
                _networkMgr.allocate(vmProfile, networks, null);
            }
            _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
            s_logger.debug("AssignVM: Advanced zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
        } else {
            if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) {
                throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone");
            }
            // if networkIdList is null and the first network of vm is shared network, then keep it if possible
            if (networkIdList == null || networkIdList.isEmpty()) {
                NicVO defaultNicOld = _nicDao.findDefaultNicForVM(vm.getId());
                if (defaultNicOld != null) {
                    NetworkVO defaultNetworkOld = _networkDao.findById(defaultNicOld.getNetworkId());
                    if (canAccountUseNetwork(newAccount, defaultNetworkOld)) {
                        applicableNetworks.add(defaultNetworkOld);
                        requestedIPv4ForNics.put(defaultNetworkOld.getId(), defaultNicOld.getIPv4Address());
                        requestedIPv6ForNics.put(defaultNetworkOld.getId(), defaultNicOld.getIPv6Address());
                        s_logger.debug("AssignVM: use old shared network " + defaultNetworkOld.getName() + " with old ip " + defaultNicOld.getIPv4Address() + " on default nic of vm:" + vm.getInstanceName());
                    }
                }
            }
            if (networkIdList != null && !networkIdList.isEmpty()) {
                // add any additional networks
                for (Long networkId : networkIdList) {
                    NetworkVO network = _networkDao.findById(networkId);
                    if (network == null) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
                        ex.addProxyObject(networkId.toString(), "networkId");
                        throw ex;
                    }
                    _networkModel.checkNetworkPermissions(newAccount, network);
                    // don't allow to use system networks
                    NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
                    if (networkOffering.isSystemOnly()) {
                        InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
                        ex.addProxyObject(network.getUuid(), "networkId");
                        throw ex;
                    }
                    if (network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) {
                        NicVO nicOld = _nicDao.findByNtwkIdAndInstanceId(network.getId(), vm.getId());
                        if (nicOld != null) {
                            requestedIPv4ForNics.put(network.getId(), nicOld.getIPv4Address());
                            requestedIPv6ForNics.put(network.getId(), nicOld.getIPv6Address());
                            s_logger.debug("AssignVM: use old shared network " + network.getName() + " with old ip " + nicOld.getIPv4Address() + " on nic of vm:" + vm.getInstanceName());
                        }
                    }
                    s_logger.debug("AssignVM: Added network " + network.getName() + " to vm " + vm.getId());
                    applicableNetworks.add(network);
                }
            } else if (applicableNetworks.isEmpty()) {
                NetworkVO defaultNetwork = null;
                List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
                if (requiredOfferings.size() < 1) {
                    throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation");
                }
                if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
                    // get Virtual networks
                    List<? extends Network> virtualNetworks = _networkModel.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated);
                    if (virtualNetworks.isEmpty()) {
                        long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
                        // Validate physical network
                        PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
                        if (physicalNetwork == null) {
                            throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + requiredOfferings.get(0).getTags());
                        }
                        s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process");
                        Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, false, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null, null, null, null, null);
                        // if the network offering has persistent set to true, implement the network
                        if (requiredOfferings.get(0).isPersistent()) {
                            DeployDestination dest = new DeployDestination(zone, null, null, null);
                            UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
                            Journal journal = new Journal.LogJournal("Implementing " + newNetwork, s_logger);
                            ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
                            s_logger.debug("Implementing the network for account" + newNetwork + " as a part of" + " network provision for persistent networks");
                            try {
                                Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(newNetwork.getId(), dest, context);
                                if (implementedNetwork == null || implementedNetwork.first() == null) {
                                    s_logger.warn("Failed to implement the network " + newNetwork);
                                }
                                newNetwork = implementedNetwork.second();
                            } catch (Exception ex) {
                                s_logger.warn("Failed to implement network " + newNetwork + " elements and" + " resources as a part of network provision for persistent network due to ", ex);
                                CloudRuntimeException e = new CloudRuntimeException("Failed to implement network" + " (with specified id) elements and resources as a part of network provision");
                                e.addProxyObject(newNetwork.getUuid(), "networkId");
                                throw e;
                            }
                        }
                        defaultNetwork = _networkDao.findById(newNetwork.getId());
                    } else if (virtualNetworks.size() > 1) {
                        throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + "; please specify networkIds");
                    } else {
                        defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
                    }
                } else {
                    throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
                }
                applicableNetworks.add(defaultNetwork);
            }
            // cleanup the network for the oldOwner
            _networkMgr.cleanupNics(vmOldProfile);
            _networkMgr.removeNics(vmOldProfile);
            // add the new nics
            LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
            int toggle = 0;
            for (NetworkVO appNet : applicableNetworks) {
                NicProfile defaultNic = new NicProfile();
                if (toggle == 0) {
                    defaultNic.setDefaultNic(true);
                    toggle++;
                }
                defaultNic.setRequestedIPv4(requestedIPv4ForNics.get(appNet.getId()));
                defaultNic.setRequestedIPv6(requestedIPv6ForNics.get(appNet.getId()));
                networks.put(appNet, new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
            }
            VirtualMachine vmi = _itMgr.findById(vm.getId());
            VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
            _networkMgr.allocate(vmProfile, networks, null);
            s_logger.debug("AssignVM: Advance virtual, adding networks no " + networks.size() + " to " + vm.getInstanceName());
        }
    // END IF NON SEC GRP ENABLED
    }
    // END IF ADVANCED
    s_logger.info("AssignVM: vm " + vm.getInstanceName() + " now belongs to account " + newAccount.getAccountName());
    return vm;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Account(com.cloud.user.Account) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) Journal(com.cloud.utils.Journal) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) LinkedHashMap(java.util.LinkedHashMap) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) DataCenterVO(com.cloud.dc.DataCenterVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) NetworkVO(com.cloud.network.dao.NetworkVO) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) SecurityGroup(com.cloud.network.security.SecurityGroup) DomainVO(com.cloud.domain.DomainVO) DeployDestination(com.cloud.deploy.DeployDestination) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair) NetworkOffering(com.cloud.offering.NetworkOffering) NetworkGuru(com.cloud.network.guru.NetworkGuru) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) IOException(java.io.IOException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) 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) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) AffinityConflictException(com.cloud.exception.AffinityConflictException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) UserVO(com.cloud.user.UserVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 59 with VirtualMachineTemplate

use of com.cloud.template.VirtualMachineTemplate in project cloudstack by apache.

the class UserVmManagerImpl method createVirtualMachine.

@Override
public UserVm createVirtualMachine(DeployVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
    // Verify that all objects exist before passing them to the service
    Account owner = _accountService.getActiveAccountById(cmd.getEntityOwnerId());
    verifyDetails(cmd.getDetails());
    Long zoneId = cmd.getZoneId();
    DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId);
    }
    Long serviceOfferingId = cmd.getServiceOfferingId();
    Long overrideDiskOfferingId = cmd.getOverrideDiskOfferingId();
    ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
    if (serviceOffering == null) {
        throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
    }
    if (serviceOffering.getDiskOfferingStrictness() && overrideDiskOfferingId != null) {
        throw new InvalidParameterValueException(String.format("Cannot override disk offering id %d since provided service offering is strictly mapped to its disk offering", overrideDiskOfferingId));
    }
    if (!serviceOffering.isDynamic()) {
        for (String detail : cmd.getDetails().keySet()) {
            if (detail.equalsIgnoreCase(VmDetailConstants.CPU_NUMBER) || detail.equalsIgnoreCase(VmDetailConstants.CPU_SPEED) || detail.equalsIgnoreCase(VmDetailConstants.MEMORY)) {
                throw new InvalidParameterValueException("cpuNumber or cpuSpeed or memory should not be specified for static service offering");
            }
        }
    }
    Long templateId = cmd.getTemplateId();
    boolean dynamicScalingEnabled = cmd.isDynamicScalingEnabled();
    VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId);
    // Make sure a valid template ID was specified
    if (template == null) {
        throw new InvalidParameterValueException("Unable to use template " + templateId);
    }
    ServiceOfferingJoinVO svcOffering = serviceOfferingJoinDao.findById(serviceOfferingId);
    if (template.isDeployAsIs()) {
        if (svcOffering != null && svcOffering.getRootDiskSize() != null && svcOffering.getRootDiskSize() > 0) {
            throw new InvalidParameterValueException("Failed to deploy Virtual Machine as a service offering with root disk size specified cannot be used with a deploy as-is template");
        }
        if (cmd.getDetails().get("rootdisksize") != null) {
            throw new InvalidParameterValueException("Overriding root disk size isn't supported for VMs deployed from deploy as-is templates");
        }
        // Bootmode and boottype are not supported on VMWare dpeloy-as-is templates (since 4.15)
        if ((cmd.getBootMode() != null || cmd.getBootType() != null)) {
            throw new InvalidParameterValueException("Boot type and boot mode are not supported on VMware, as we honour what is defined in the template.");
        }
    }
    Long diskOfferingId = cmd.getDiskOfferingId();
    DiskOffering diskOffering = null;
    if (diskOfferingId != null) {
        diskOffering = _entityMgr.findById(DiskOffering.class, diskOfferingId);
        if (diskOffering == null) {
            throw new InvalidParameterValueException("Unable to find disk offering " + diskOfferingId);
        }
        if (diskOffering.isComputeOnly()) {
            throw new InvalidParameterValueException(String.format("The disk offering id %d provided is directly mapped to a service offering, please provide an individual disk offering", diskOfferingId));
        }
    }
    if (!zone.isLocalStorageEnabled()) {
        DiskOffering diskOfferingMappedInServiceOffering = _entityMgr.findById(DiskOffering.class, serviceOffering.getDiskOfferingId());
        if (diskOfferingMappedInServiceOffering.isUseLocalStorage()) {
            throw new InvalidParameterValueException("Zone is not configured to use local storage but disk offering " + diskOfferingMappedInServiceOffering.getName() + " mapped in service offering uses it");
        }
        if (diskOffering != null && diskOffering.isUseLocalStorage()) {
            throw new InvalidParameterValueException("Zone is not configured to use local storage but disk offering " + diskOffering.getName() + " uses it");
        }
    }
    List<Long> networkIds = cmd.getNetworkIds();
    LinkedHashMap<Integer, Long> userVmNetworkMap = getVmOvfNetworkMapping(zone, owner, template, cmd.getVmNetworkMap());
    if (MapUtils.isNotEmpty(userVmNetworkMap)) {
        networkIds = new ArrayList<>(userVmNetworkMap.values());
    }
    Account caller = CallContext.current().getCallingAccount();
    Long callerId = caller.getId();
    boolean isRootAdmin = _accountService.isRootAdmin(callerId);
    Long hostId = cmd.getHostId();
    getDestinationHost(hostId, isRootAdmin, true);
    String ipAddress = cmd.getIpAddress();
    String ip6Address = cmd.getIp6Address();
    String macAddress = cmd.getMacAddress();
    String name = cmd.getName();
    String displayName = cmd.getDisplayName();
    UserVm vm = null;
    IpAddresses addrs = new IpAddresses(ipAddress, ip6Address, macAddress);
    Long size = cmd.getSize();
    String group = cmd.getGroup();
    String userData = cmd.getUserData();
    String sshKeyPairName = cmd.getSSHKeyPairName();
    Boolean displayVm = cmd.isDisplayVm();
    String keyboard = cmd.getKeyboard();
    Map<Long, DiskOffering> dataDiskTemplateToDiskOfferingMap = cmd.getDataDiskTemplateToDiskOfferingMap();
    Map<String, String> userVmOVFProperties = cmd.getVmProperties();
    if (zone.getNetworkType() == NetworkType.Basic) {
        if (networkIds != null) {
            throw new InvalidParameterValueException("Can't specify network Ids in Basic zone");
        } else {
            vm = createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, getSecurityGroupIdList(cmd), owner, name, displayName, diskOfferingId, size, group, cmd.getHypervisor(), cmd.getHttpMethod(), userData, sshKeyPairName, cmd.getIpToNetworkMap(), addrs, displayVm, keyboard, cmd.getAffinityGroupIdList(), cmd.getDetails(), cmd.getCustomId(), cmd.getDhcpOptionsMap(), dataDiskTemplateToDiskOfferingMap, userVmOVFProperties, dynamicScalingEnabled, overrideDiskOfferingId);
        }
    } else {
        if (zone.isSecurityGroupEnabled()) {
            vm = createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, networkIds, getSecurityGroupIdList(cmd), owner, name, displayName, diskOfferingId, size, group, cmd.getHypervisor(), cmd.getHttpMethod(), userData, sshKeyPairName, cmd.getIpToNetworkMap(), addrs, displayVm, keyboard, cmd.getAffinityGroupIdList(), cmd.getDetails(), cmd.getCustomId(), cmd.getDhcpOptionsMap(), dataDiskTemplateToDiskOfferingMap, userVmOVFProperties, dynamicScalingEnabled, overrideDiskOfferingId);
        } else {
            if (cmd.getSecurityGroupIdList() != null && !cmd.getSecurityGroupIdList().isEmpty()) {
                throw new InvalidParameterValueException("Can't create vm with security groups; security group feature is not enabled per zone");
            }
            vm = createAdvancedVirtualMachine(zone, serviceOffering, template, networkIds, owner, name, displayName, diskOfferingId, size, group, cmd.getHypervisor(), cmd.getHttpMethod(), userData, sshKeyPairName, cmd.getIpToNetworkMap(), addrs, displayVm, keyboard, cmd.getAffinityGroupIdList(), cmd.getDetails(), cmd.getCustomId(), cmd.getDhcpOptionsMap(), dataDiskTemplateToDiskOfferingMap, userVmOVFProperties, dynamicScalingEnabled, null, overrideDiskOfferingId);
        }
    }
    // check if this templateId has a child ISO
    List<VMTemplateVO> child_templates = _templateDao.listByParentTemplatetId(templateId);
    for (VMTemplateVO tmpl : child_templates) {
        if (tmpl.getFormat() == Storage.ImageFormat.ISO) {
            s_logger.info("MDOV trying to attach disk to the VM " + tmpl.getId() + " vmid=" + vm.getId());
            _tmplService.attachIso(tmpl.getId(), vm.getId(), true);
        }
    }
    // Add extraConfig to user_vm_details table
    String extraConfig = cmd.getExtraConfig();
    if (StringUtils.isNotBlank(extraConfig)) {
        if (EnableAdditionalVmConfig.valueIn(callerId)) {
            s_logger.info("Adding extra configuration to user vm: " + vm.getUuid());
            addExtraConfig(vm, extraConfig);
        } else {
            throw new InvalidParameterValueException("attempted setting extraconfig but enable.additional.vm.configuration is disabled");
        }
    }
    if (cmd.getCopyImageTags()) {
        VMTemplateVO templateOrIso = _templateDao.findById(templateId);
        if (templateOrIso != null) {
            final ResourceTag.ResourceObjectType templateType = (templateOrIso.getFormat() == ImageFormat.ISO) ? ResourceTag.ResourceObjectType.ISO : ResourceTag.ResourceObjectType.Template;
            final List<? extends ResourceTag> resourceTags = resourceTagDao.listBy(templateId, templateType);
            for (ResourceTag resourceTag : resourceTags) {
                final ResourceTagVO copyTag = new ResourceTagVO(resourceTag.getKey(), resourceTag.getValue(), resourceTag.getAccountId(), resourceTag.getDomainId(), vm.getId(), ResourceTag.ResourceObjectType.UserVm, resourceTag.getCustomer(), vm.getUuid());
                resourceTagDao.persist(copyTag);
            }
        }
    }
    return vm;
}
Also used : Account(com.cloud.user.Account) DiskOffering(com.cloud.offering.DiskOffering) VMTemplateVO(com.cloud.storage.VMTemplateVO) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ServiceOfferingJoinVO(com.cloud.api.query.vo.ServiceOfferingJoinVO) ServiceOffering(com.cloud.offering.ServiceOffering) IpAddresses(com.cloud.network.Network.IpAddresses) DataCenter(com.cloud.dc.DataCenter) ResourceTag(com.cloud.server.ResourceTag)

Example 60 with VirtualMachineTemplate

use of com.cloud.template.VirtualMachineTemplate in project cloudstack by apache.

the class SwiftImageStoreDriverImpl method createAsync.

@Override
public void createAsync(DataStore dataStore, DataObject data, AsyncCompletionCallback<CreateCmdResult> callback) {
    Long maxTemplateSizeInBytes = getMaxTemplateSizeInBytes();
    VirtualMachineTemplate tmpl = _templateDao.findById(data.getId());
    DataStore cacheStore = cacheManager.getCacheStorage(dataStore.getScope());
    DownloadCommand dcmd = new DownloadCommand((TemplateObjectTO) (data.getTO()), maxTemplateSizeInBytes);
    dcmd.setCacheStore(cacheStore.getTO());
    dcmd.setProxy(getHttpProxy());
    EndPoint ep = _epSelector.select(data);
    if (ep == null) {
        String errMsg = "No remote endpoint to send command, check if host or ssvm is down?";
        s_logger.error(errMsg);
        throw new CloudRuntimeException(errMsg);
    }
    CreateContext<CreateCmdResult> context = new CreateContext<CreateCmdResult>(callback, data);
    AsyncCallbackDispatcher<SwiftImageStoreDriverImpl, DownloadAnswer> caller = AsyncCallbackDispatcher.create(this);
    caller.setContext(context);
    if (data.getType() == DataObjectType.TEMPLATE) {
        caller.setCallback(caller.getTarget().createTemplateAsyncCallback(null, null));
    } else if (data.getType() == DataObjectType.VOLUME) {
        caller.setCallback(caller.getTarget().createVolumeAsyncCallback(null, null));
    }
    ep.sendMessageAsync(dcmd, caller);
}
Also used : VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) DownloadCommand(org.apache.cloudstack.storage.command.DownloadCommand) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) CreateCmdResult(org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult) DownloadAnswer(com.cloud.agent.api.storage.DownloadAnswer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore)

Aggregations

VirtualMachineTemplate (com.cloud.template.VirtualMachineTemplate)65 ServerApiException (com.cloud.api.ServerApiException)22 TemplateResponse (com.cloud.api.response.TemplateResponse)20 Account (com.cloud.user.Account)16 ServerApiException (org.apache.cloudstack.api.ServerApiException)15 TemplateResponse (org.apache.cloudstack.api.response.TemplateResponse)13 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)10 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)9 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)9 ArrayList (java.util.ArrayList)9 ListResponse (com.cloud.api.response.ListResponse)8 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)8 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)8 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)8 StorageUnavailableException (com.cloud.exception.StorageUnavailableException)8 DiskOffering (com.cloud.offering.DiskOffering)8 DataCenter (com.cloud.dc.DataCenter)7 Network (com.cloud.network.Network)7 VolumeVO (com.cloud.storage.VolumeVO)7 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)7