Search in sources :

Example 11 with SecurityGroup

use of com.cloud.network.security.SecurityGroup in project cloudstack by apache.

the class UserVmManagerImpl method createVirtualMachine.

@DB
private 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, Map<String, Map<Integer, String>> dhcpOptionMap, Map<Long, DiskOffering> datadiskTemplateToDiskOfferringMap, Map<String, String> userVmOVFPropertiesMap, boolean dynamicScalingEnabled, String type, Long overrideDiskOfferingId) 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);
    }
    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();
    }
    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);
    } else {
        validateOfferingMaxResource(offering);
    }
    // check if account/domain is with in resource limits to create a new vm
    boolean isIso = Storage.ImageFormat.ISO == template.getFormat();
    Long rootDiskOfferingId = offering.getDiskOfferingId();
    if (isIso) {
        if (diskOfferingId == null) {
            DiskOfferingVO diskOffering = _diskOfferingDao.findById(rootDiskOfferingId);
            if (diskOffering.isComputeOnly()) {
                throw new InvalidParameterValueException("Installing from ISO requires a disk offering to be specified for the root disk.");
            }
        } else {
            rootDiskOfferingId = diskOfferingId;
            diskOfferingId = null;
        }
    }
    if (!offering.getDiskOfferingStrictness() && overrideDiskOfferingId != null) {
        rootDiskOfferingId = overrideDiskOfferingId;
    }
    DiskOfferingVO rootdiskOffering = _diskOfferingDao.findById(rootDiskOfferingId);
    long volumesSize = configureCustomRootDiskSize(customParameters, template, hypervisorType, rootdiskOffering);
    if (!isIso && diskOfferingId != null) {
        DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
        volumesSize += verifyAndGetDiskSize(diskOffering, diskSize);
    }
    if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
        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, volumesSize);
    // 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);
            }
        }
    }
    if (datadiskTemplateToDiskOfferringMap != null && !datadiskTemplateToDiskOfferringMap.isEmpty()) {
        for (Entry<Long, DiskOffering> datadiskTemplateToDiskOffering : datadiskTemplateToDiskOfferringMap.entrySet()) {
            VMTemplateVO dataDiskTemplate = _templateDao.findById(datadiskTemplateToDiskOffering.getKey());
            DiskOffering dataDiskOffering = datadiskTemplateToDiskOffering.getValue();
            if (dataDiskTemplate == null || (!dataDiskTemplate.getTemplateType().equals(TemplateType.DATADISK)) && (dataDiskTemplate.getState().equals(VirtualMachineTemplate.State.Active))) {
                throw new InvalidParameterValueException("Invalid template id specified for Datadisk template" + datadiskTemplateToDiskOffering.getKey());
            }
            long dataDiskTemplateId = datadiskTemplateToDiskOffering.getKey();
            if (!dataDiskTemplate.getParentTemplateId().equals(template.getId())) {
                throw new InvalidParameterValueException("Invalid Datadisk template. Specified Datadisk template" + dataDiskTemplateId + " doesn't belong to template " + template.getId());
            }
            if (dataDiskOffering == null) {
                throw new InvalidParameterValueException("Invalid disk offering id " + datadiskTemplateToDiskOffering.getValue().getId() + " specified for datadisk template " + dataDiskTemplateId);
            }
            if (dataDiskOffering.isCustomized()) {
                throw new InvalidParameterValueException("Invalid disk offering id " + dataDiskOffering.getId() + " specified for datadisk template " + dataDiskTemplateId + ". Custom Disk offerings are not supported for Datadisk templates");
            }
            if (dataDiskOffering.getDiskSize() < dataDiskTemplate.getSize()) {
                throw new InvalidParameterValueException("Invalid disk offering id " + dataDiskOffering.getId() + " specified for datadisk template " + dataDiskTemplateId + ". Disk offering size should be greater than or equal to the template size");
            }
            _templateDao.loadDetails(dataDiskTemplate);
            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, 1);
            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, dataDiskOffering.getDiskSize());
        }
    }
    // 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");
                        }
                    }
                }
            }
        }
    }
    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) && !CKS_NODE.equals(type)) {
        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
    userData = 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();
    }
    LinkedHashMap<String, List<NicProfile>> networkNicMap = new LinkedHashMap<>();
    short defaultNetworkNumber = 0;
    boolean securityGroupEnabled = false;
    int networkIndex = 0;
    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());
            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);
        }
        NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());
        profile.setOrderIndex(networkIndex);
        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);
                profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
            } else if (defaultIps.getMacAddress() != null) {
                profile = new NicProfile(null, null, defaultIps.getMacAddress());
            }
            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.isEnablePassword()) {
                    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());
                }
            }
        }
        if (_networkModel.isSecurityGroupSupportedInNetwork(network)) {
            securityGroupEnabled = true;
        }
        List<NicProfile> profiles = networkNicMap.get(network.getUuid());
        if (CollectionUtils.isEmpty(profiles)) {
            profiles = new ArrayList<>();
        }
        profiles.add(profile);
        networkNicMap.put(network.getUuid(), profiles);
        networkIndex++;
    }
    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 instanceSuffix = _instance;
    String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
    if (_instanceNameFlag && HypervisorType.VMware.equals(hypervisorType)) {
        if (StringUtils.isNotEmpty(hostName)) {
            instanceSuffix = hostName;
        }
        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(), instanceSuffix);
    if (_instanceNameFlag && HypervisorType.VMware.equals(hypervisorType) && !instanceSuffix.equals(_instance)) {
        customParameters.put(VmDetailConstants.NAME_ON_HYPERVISOR, instanceName);
    }
    // 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();
        }
    }
    dynamicScalingEnabled = dynamicScalingEnabled && checkIfDynamicScalingCanBeEnabled(null, offering, template, zone.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, dhcpOptionMap, datadiskTemplateToDiskOfferringMap, userVmOVFPropertiesMap, dynamicScalingEnabled, type, rootDiskOfferingId);
    // 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;
}
Also used : VMTemplateZoneVO(com.cloud.storage.VMTemplateZoneVO) DiskOffering(com.cloud.offering.DiskOffering) VMTemplateVO(com.cloud.storage.VMTemplateVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) AffinityGroupVO(org.apache.cloudstack.affinity.AffinityGroupVO) SSHKeyPair(com.cloud.user.SSHKeyPair) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) AccountService(com.cloud.user.AccountService) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) VolumeOrchestrationService(org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService) QueryService(org.apache.cloudstack.query.QueryService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) OrchestrationService(org.apache.cloudstack.engine.service.api.OrchestrationService) ExecutorService(java.util.concurrent.ExecutorService) VolumeService(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService) TemplateApiService(com.cloud.template.TemplateApiService) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) VolumeApiService(com.cloud.storage.VolumeApiService) AffinityGroupService(org.apache.cloudstack.affinity.AffinityGroupService) AnnotationService(org.apache.cloudstack.annotation.AnnotationService) SecurityGroup(com.cloud.network.security.SecurityGroup) 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) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) IpAddresses(com.cloud.network.Network.IpAddresses) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Example 12 with SecurityGroup

use of com.cloud.network.security.SecurityGroup in project cloudstack by apache.

the class UserVmManagerImpl method startVirtualMachine.

@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long podId, Long clusterId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams, String deploymentPlannerToUse, boolean isExplicitHost) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException {
    // Input validation
    final 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);
    }
    if (vm.getState() == State.Running) {
        throw new InvalidParameterValueException("The virtual machine " + vm.getUuid() + " (" + vm.getDisplayName() + ") is already running");
    }
    _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());
    }
    if (VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
        // check if account/domain is with in resource limits to start a new vm
        ServiceOfferingVO offering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
        resourceLimitCheck(owner, vm.isDisplayVm(), Long.valueOf(offering.getCpu()), Long.valueOf(offering.getRamSize()));
    }
    // 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);
        }
    }
    // Choose deployment planner
    // Host takes 1st preference, Cluster takes 2nd preference and Pod takes 3rd
    // Default behaviour is invoked when host, cluster or pod are not specified
    boolean isRootAdmin = _accountService.isRootAdmin(callerAccount.getId());
    Pod destinationPod = getDestinationPod(podId, isRootAdmin);
    Cluster destinationCluster = getDestinationCluster(clusterId, isRootAdmin);
    Host destinationHost = getDestinationHost(hostId, isRootAdmin, isExplicitHost);
    DataCenterDeployment plan = null;
    boolean deployOnGivenHost = false;
    if (destinationHost != null) {
        s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        final ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
        Pair<Boolean, Boolean> cpuCapabilityAndCapacity = _capacityMgr.checkIfHostHasCpuCapabilityAndCapacity(destinationHost, offering, false);
        if (!cpuCapabilityAndCapacity.first() || !cpuCapabilityAndCapacity.second()) {
            String errorMsg = "Cannot deploy the VM to specified host " + hostId + "; host has cpu capability? " + cpuCapabilityAndCapacity.first() + ", host has capacity? " + cpuCapabilityAndCapacity.second();
            s_logger.info(errorMsg);
            if (!AllowDeployVmIfGivenHostFails.value()) {
                throw new InvalidParameterValueException(errorMsg);
            }
            ;
        } else {
            plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
            if (!AllowDeployVmIfGivenHostFails.value()) {
                deployOnGivenHost = true;
            }
        }
    } else if (destinationCluster != null) {
        s_logger.debug("Destination Cluster to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationCluster.getPodId(), destinationCluster.getId(), null, null, null);
        if (!AllowDeployVmIfGivenHostFails.value()) {
            deployOnGivenHost = true;
        }
    } else if (destinationPod != null) {
        s_logger.debug("Destination Pod to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationPod.getId(), null, null, null, null);
        if (!AllowDeployVmIfGivenHostFails.value()) {
            deployOnGivenHost = true;
        }
    }
    // 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.isEnablePassword()) {
            if (vm.getDetail("password") != null) {
                password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
            } else {
                password = _mgr.generateRandomPassword();
                vm.setPassword(password);
            }
        }
        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 = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.VmPassword, password);
    }
    if (null != additionalParams && additionalParams.containsKey(VirtualMachineProfile.Param.BootIntoSetup)) {
        if (!HypervisorType.VMware.equals(vm.getHypervisorType())) {
            throw new InvalidParameterValueException(ApiConstants.BOOT_INTO_SETUP + " makes no sense for " + vm.getHypervisorType());
        }
        Object paramValue = additionalParams.get(VirtualMachineProfile.Param.BootIntoSetup);
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("It was specified whether to enter setup mode: " + paramValue.toString());
        }
        params = createParameterInParameterMap(params, additionalParams, VirtualMachineProfile.Param.BootIntoSetup, paramValue);
    }
    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);
        }
    }
    vmEntity.setParamsToEntity(additionalParams);
    String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
    vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params, deployOnGivenHost);
    Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
    if (vm != null && vm.isUpdateParameters()) {
        // display purposes
        if (template.isEnablePassword()) {
            if (vm.getDetail(VmDetailConstants.PASSWORD) != null) {
                userVmDetailsDao.removeDetail(vm.getId(), VmDetailConstants.PASSWORD);
            }
            vm.setUpdateParameters(false);
            _vmDao.update(vm.getId(), vm);
        }
    }
    return vmParamPair;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) Pod(com.cloud.dc.Pod) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) Cluster(com.cloud.org.Cluster) Host(com.cloud.host.Host) SecurityGroup(com.cloud.network.security.SecurityGroup) UserVO(com.cloud.user.UserVO) DeploymentPlanner(com.cloud.deploy.DeploymentPlanner) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 13 with SecurityGroup

use of com.cloud.network.security.SecurityGroup in project cloudstack by apache.

the class SecurityGroupResultObject method transposeNetworkGroups.

public static List<SecurityGroupResultObject> transposeNetworkGroups(List<? extends SecurityGroupRules> groups) {
    List<SecurityGroupResultObject> resultObjects = new ArrayList<SecurityGroupResultObject>();
    Map<Long, SecurityGroup> allowedSecurityGroups = new HashMap<Long, SecurityGroup>();
    Map<Long, Account> accounts = new HashMap<Long, Account>();
    if ((groups != null) && !groups.isEmpty()) {
        List<SecurityGroupRuleResultObject> securityGroupRuleDataList = new ArrayList<SecurityGroupRuleResultObject>();
        SecurityGroupResultObject currentGroup = null;
        List<Long> processedGroups = new ArrayList<Long>();
        for (SecurityGroupRules netGroupRule : groups) {
            Long groupId = netGroupRule.getId();
            if (!processedGroups.contains(groupId)) {
                processedGroups.add(groupId);
                if (currentGroup != null) {
                    if (!securityGroupRuleDataList.isEmpty()) {
                        currentGroup.setSecurityGroupRules(securityGroupRuleDataList);
                        securityGroupRuleDataList = new ArrayList<SecurityGroupRuleResultObject>();
                    }
                    resultObjects.add(currentGroup);
                }
                // start a new group
                SecurityGroupResultObject groupResult = new SecurityGroupResultObject();
                groupResult.setId(netGroupRule.getId());
                groupResult.setName(netGroupRule.getName());
                groupResult.setDescription(netGroupRule.getDescription());
                groupResult.setDomainId(netGroupRule.getDomainId());
                Account account = accounts.get(netGroupRule.getAccountId());
                if (account == null) {
                    account = ApiDBUtils.findAccountById(netGroupRule.getAccountId());
                    accounts.put(account.getId(), account);
                }
                groupResult.setAccountId(account.getId());
                groupResult.setAccountName(account.getAccountName());
                currentGroup = groupResult;
            }
            if (netGroupRule.getRuleId() != null) {
                // there's at least one securitygroup rule for this network group, add the securitygroup rule data
                SecurityGroupRuleResultObject securityGroupRuleData = new SecurityGroupRuleResultObject();
                securityGroupRuleData.setEndPort(netGroupRule.getEndPort());
                securityGroupRuleData.setStartPort(netGroupRule.getStartPort());
                securityGroupRuleData.setId(netGroupRule.getRuleId());
                securityGroupRuleData.setProtocol(netGroupRule.getProtocol());
                securityGroupRuleData.setRuleType(netGroupRule.getRuleType());
                Long allowedSecurityGroupId = netGroupRule.getAllowedNetworkId();
                if (allowedSecurityGroupId != null) {
                    SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId);
                    if (allowedSecurityGroup == null) {
                        allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId);
                        allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup);
                    }
                    securityGroupRuleData.setAllowedSecurityGroup(allowedSecurityGroup.getName());
                    Account allowedAccount = accounts.get(allowedSecurityGroup.getAccountId());
                    if (allowedAccount == null) {
                        allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId());
                        accounts.put(allowedAccount.getId(), allowedAccount);
                    }
                    securityGroupRuleData.setAllowedSecGroupAcct(allowedAccount.getAccountName());
                } else if (netGroupRule.getAllowedSourceIpCidr() != null) {
                    securityGroupRuleData.setAllowedSourceIpCidr(netGroupRule.getAllowedSourceIpCidr());
                }
                securityGroupRuleDataList.add(securityGroupRuleData);
            }
        }
        // all rules have been processed, add the final data into the list
        if (currentGroup != null) {
            if (!securityGroupRuleDataList.isEmpty()) {
                currentGroup.setSecurityGroupRules(securityGroupRuleDataList);
            }
            resultObjects.add(currentGroup);
        }
    }
    return resultObjects;
}
Also used : Account(com.cloud.user.Account) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SecurityGroup(com.cloud.network.security.SecurityGroup) SecurityGroupRules(com.cloud.network.security.SecurityGroupRules)

Example 14 with SecurityGroup

use of com.cloud.network.security.SecurityGroup in project cloudstack by apache.

the class ApiDBUtils method findJobInstanceUuid.

public static String findJobInstanceUuid(AsyncJob job) {
    if (job == null) {
        return null;
    }
    String jobInstanceId = null;
    ApiCommandJobType jobInstanceType = EnumUtils.fromString(ApiCommandJobType.class, job.getInstanceType(), ApiCommandJobType.None);
    if (job.getInstanceId() == null) {
        // when assert is hit, implement 'getInstanceId' of BaseAsyncCmd and return appropriate instance id
        assert (false);
        return null;
    }
    if (jobInstanceType == ApiCommandJobType.Volume) {
        VolumeVO volume = ApiDBUtils.findVolumeById(job.getInstanceId());
        if (volume != null) {
            jobInstanceId = volume.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Template || jobInstanceType == ApiCommandJobType.Iso) {
        VMTemplateVO template = ApiDBUtils.findTemplateById(job.getInstanceId());
        if (template != null) {
            jobInstanceId = template.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.VirtualMachine || jobInstanceType == ApiCommandJobType.ConsoleProxy || jobInstanceType == ApiCommandJobType.SystemVm || jobInstanceType == ApiCommandJobType.DomainRouter) {
        VMInstanceVO vm = ApiDBUtils.findVMInstanceById(job.getInstanceId());
        if (vm != null) {
            jobInstanceId = vm.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Snapshot) {
        Snapshot snapshot = ApiDBUtils.findSnapshotById(job.getInstanceId());
        if (snapshot != null) {
            jobInstanceId = snapshot.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Host) {
        Host host = ApiDBUtils.findHostById(job.getInstanceId());
        if (host != null) {
            jobInstanceId = host.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.StoragePool) {
        StoragePoolVO spool = ApiDBUtils.findStoragePoolById(job.getInstanceId());
        if (spool != null) {
            jobInstanceId = spool.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.IpAddress) {
        IPAddressVO ip = ApiDBUtils.findIpAddressById(job.getInstanceId());
        if (ip != null) {
            jobInstanceId = ip.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.SecurityGroup) {
        SecurityGroup sg = ApiDBUtils.findSecurityGroupById(job.getInstanceId());
        if (sg != null) {
            jobInstanceId = sg.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.PhysicalNetwork) {
        PhysicalNetworkVO pnet = ApiDBUtils.findPhysicalNetworkById(job.getInstanceId());
        if (pnet != null) {
            jobInstanceId = pnet.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.TrafficType) {
        PhysicalNetworkTrafficTypeVO trafficType = ApiDBUtils.findPhysicalNetworkTrafficTypeById(job.getInstanceId());
        if (trafficType != null) {
            jobInstanceId = trafficType.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.PhysicalNetworkServiceProvider) {
        PhysicalNetworkServiceProvider sp = ApiDBUtils.findPhysicalNetworkServiceProviderById(job.getInstanceId());
        if (sp != null) {
            jobInstanceId = sp.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.FirewallRule) {
        FirewallRuleVO fw = ApiDBUtils.findFirewallRuleById(job.getInstanceId());
        if (fw != null) {
            jobInstanceId = fw.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Account) {
        Account acct = ApiDBUtils.findAccountById(job.getInstanceId());
        if (acct != null) {
            jobInstanceId = acct.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.User) {
        User usr = ApiDBUtils.findUserById(job.getInstanceId());
        if (usr != null) {
            jobInstanceId = usr.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.StaticRoute) {
        StaticRouteVO route = ApiDBUtils.findStaticRouteById(job.getInstanceId());
        if (route != null) {
            jobInstanceId = route.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.PrivateGateway) {
        VpcGatewayVO gateway = ApiDBUtils.findVpcGatewayById(job.getInstanceId());
        if (gateway != null) {
            jobInstanceId = gateway.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Counter) {
        CounterVO counter = ApiDBUtils.getCounter(job.getInstanceId());
        if (counter != null) {
            jobInstanceId = counter.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Condition) {
        ConditionVO condition = ApiDBUtils.findConditionById(job.getInstanceId());
        if (condition != null) {
            jobInstanceId = condition.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.AutoScalePolicy) {
        AutoScalePolicyVO policy = ApiDBUtils.findAutoScalePolicyById(job.getInstanceId());
        if (policy != null) {
            jobInstanceId = policy.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.AutoScaleVmProfile) {
        AutoScaleVmProfileVO profile = ApiDBUtils.findAutoScaleVmProfileById(job.getInstanceId());
        if (profile != null) {
            jobInstanceId = profile.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.AutoScaleVmGroup) {
        AutoScaleVmGroupVO group = ApiDBUtils.findAutoScaleVmGroupById(job.getInstanceId());
        if (group != null) {
            jobInstanceId = group.getUuid();
        }
    } else if (jobInstanceType == ApiCommandJobType.Network) {
        NetworkVO networkVO = ApiDBUtils.findNetworkById(job.getInstanceId());
        if (networkVO != null) {
            jobInstanceId = networkVO.getUuid();
        }
    } else if (jobInstanceType != ApiCommandJobType.None) {
        // entity table mapping
        assert (false);
    }
    return jobInstanceId;
}
Also used : ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) AutoScalePolicyVO(com.cloud.network.as.AutoScalePolicyVO) VpcGatewayVO(com.cloud.network.vpc.VpcGatewayVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) ApiCommandJobType(org.apache.cloudstack.api.ApiCommandJobType) User(com.cloud.user.User) VMTemplateVO(com.cloud.storage.VMTemplateVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) Host(com.cloud.host.Host) PhysicalNetworkTrafficTypeVO(com.cloud.network.dao.PhysicalNetworkTrafficTypeVO) PhysicalNetworkServiceProvider(com.cloud.network.PhysicalNetworkServiceProvider) StaticRouteVO(com.cloud.network.vpc.StaticRouteVO) SecurityGroup(com.cloud.network.security.SecurityGroup) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) VMSnapshot(com.cloud.vm.snapshot.VMSnapshot) Snapshot(com.cloud.storage.Snapshot) AutoScaleVmProfileVO(com.cloud.network.as.AutoScaleVmProfileVO) AutoScaleVmGroupVO(com.cloud.network.as.AutoScaleVmGroupVO) VolumeVO(com.cloud.storage.VolumeVO) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ConditionVO(com.cloud.network.as.ConditionVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) CounterVO(com.cloud.network.as.CounterVO)

Aggregations

SecurityGroup (com.cloud.network.security.SecurityGroup)14 ArrayList (java.util.ArrayList)10 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)9 Account (com.cloud.user.Account)9 NetworkVO (com.cloud.network.dao.NetworkVO)8 ActionEvent (com.cloud.event.ActionEvent)5 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)5 Network (com.cloud.network.Network)5 PhysicalNetwork (com.cloud.network.PhysicalNetwork)5 VMTemplateVO (com.cloud.storage.VMTemplateVO)5 SSHKeyPair (com.cloud.user.SSHKeyPair)5 UserVO (com.cloud.user.UserVO)5 LinkedHashMap (java.util.LinkedHashMap)5 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)4 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)4 Pair (com.cloud.utils.Pair)4 DomainVO (com.cloud.domain.DomainVO)3 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)3 CloudException (com.cloud.exception.CloudException)3 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)3