Search in sources :

Example 31 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class FirewallManagerImpl method listFirewallRules.

@Override
public Pair<List<? extends FirewallRule>, Integer> listFirewallRules(final IListFirewallRulesCmd cmd) {
    final Long ipId = cmd.getIpAddressId();
    final Long id = cmd.getId();
    final Long networkId = cmd.getNetworkId();
    final Map<String, String> tags = cmd.getTags();
    final FirewallRule.TrafficType trafficType = cmd.getTrafficType();
    final Boolean display = cmd.getDisplay();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    if (ipId != null) {
        final IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
        if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
            throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet");
        }
        _accountMgr.checkAccess(caller, null, true, ipAddressVO);
    }
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), Op.EQ);
    sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
    sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
    sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
    sb.and("display", sb.entity().isDisplay(), Op.EQ);
    if (tags != null && !tags.isEmpty()) {
        final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    final SearchCriteria<FirewallRuleVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.FirewallRule.toString());
        for (final String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (ipId != null) {
        sc.setParameters("ip", ipId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    sc.setParameters("purpose", Purpose.Firewall);
    sc.setParameters("trafficType", trafficType);
    final Pair<List<FirewallRuleVO>, Integer> result = _firewallDao.searchAndCount(sc, filter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) ArrayList(java.util.ArrayList) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) FirewallRule(com.cloud.legacymodel.network.FirewallRule) Pair(com.cloud.legacymodel.utils.Pair) Ternary(com.cloud.legacymodel.utils.Ternary) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 32 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method listTrafficTypes.

@Override
public Pair<List<? extends PhysicalNetworkTrafficType>, Integer> listTrafficTypes(final Long physicalNetworkId) {
    final PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
    if (network == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
        ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
        throw ex;
    }
    final Pair<List<PhysicalNetworkTrafficTypeVO>, Integer> result = _pNTrafficTypeDao.listAndCountBy(physicalNetworkId);
    return new Pair<>(result.first(), result.second());
}
Also used : InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.legacymodel.utils.Pair)

Example 33 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method addOrRemoveVnets.

@DB
private void addOrRemoveVnets(final String[] listOfRanges, final PhysicalNetworkVO network) {
    List<String> addVnets = null;
    List<String> removeVnets = null;
    final HashSet<String> tempVnets = new HashSet<>();
    final HashSet<String> vnetsInDb = new HashSet<>();
    List<Pair<Integer, Integer>> vnetranges = null;
    String comaSeperatedStingOfVnetRanges = null;
    int i = 0;
    if (listOfRanges.length != 0) {
        _physicalNetworkDao.acquireInLockTable(network.getId(), 10);
        vnetranges = validateVlanRange(network, listOfRanges);
        // computing vnets to be removed.
        removeVnets = getVnetsToremove(network, vnetranges);
        // computing vnets to add
        vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId()));
        tempVnets.addAll(vnetsInDb);
        for (final Pair<Integer, Integer> vlan : vnetranges) {
            for (i = vlan.first(); i <= vlan.second(); i++) {
                tempVnets.add(Integer.toString(i));
            }
        }
        tempVnets.removeAll(vnetsInDb);
        // adding and removing vnets from vnetsInDb
        if (removeVnets != null && removeVnets.size() != 0) {
            vnetsInDb.removeAll(removeVnets);
        }
        if (tempVnets.size() != 0) {
            addVnets = new ArrayList<>();
            addVnets.addAll(tempVnets);
            vnetsInDb.addAll(tempVnets);
        }
        // sorting the vnets in Db to generate a coma seperated list of  the vnet string.
        if (vnetsInDb.size() != 0) {
            comaSeperatedStingOfVnetRanges = generateVnetString(new ArrayList<>(vnetsInDb));
        }
        network.setVnet(comaSeperatedStingOfVnetRanges);
        final List<String> addVnetsFinal = addVnets;
        final List<String> removeVnetsFinal = removeVnets;
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                if (addVnetsFinal != null) {
                    s_logger.debug("Adding vnet range " + addVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
                    // add vnet takes a list of strings to be added. each string is a vnet.
                    _dcDao.addVnet(network.getDataCenterId(), network.getId(), addVnetsFinal);
                }
                if (removeVnetsFinal != null) {
                    s_logger.debug("removing vnet range " + removeVnetsFinal.toString() + " for the physicalNetwork id= " + network.getId() + " and zone id=" + network.getDataCenterId() + " as a part of updatePhysicalNetwork call");
                    // deleteVnets  takes a list of strings to be removed. each string is a vnet.
                    _datacneterVnet.deleteVnets(TransactionLegacy.currentTxn(), network.getDataCenterId(), network.getId(), removeVnetsFinal);
                }
                _physicalNetworkDao.update(network.getId(), network);
            }
        });
        _physicalNetworkDao.releaseFromLockTable(network.getId());
    }
}
Also used : ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) HashSet(java.util.HashSet) Pair(com.cloud.legacymodel.utils.Pair) DB(com.cloud.utils.db.DB)

Example 34 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class LdapAuthenticator method authenticate.

@Override
public Pair<Boolean, ActionOnFailedAuthentication> authenticate(final String username, final String password, final Long domainId, final Map<String, Object[]> requestParameters) {
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        s_logger.debug("Username or Password cannot be empty");
        return new Pair<>(false, null);
    }
    boolean result = false;
    ActionOnFailedAuthentication action = null;
    if (_ldapManager.isLdapEnabled()) {
        final UserAccount user = _userAccountDao.getUserAccount(username, domainId);
        final LdapTrustMapVO ldapTrustMapVO = _ldapManager.getDomainLinkedToLdap(domainId);
        if (ldapTrustMapVO != null) {
            ldapGroupName = DistinguishedNameParser.parseLeafName(ldapTrustMapVO.getName());
            try {
                final LdapUser ldapUser = _ldapManager.getUser(username, ldapTrustMapVO.getType().toString(), ldapTrustMapVO.getName());
                if (!ldapUser.isDisabled()) {
                    result = _ldapManager.canAuthenticate(ldapUser.getPrincipal(), password);
                    if (result) {
                        if (user == null) {
                            // import user to cloudstack
                            createCloudStackUserAccount(ldapUser, domainId, ldapTrustMapVO.getAccountType());
                        } else {
                            enableUserInCloudStack(user);
                        }
                    }
                } else {
                    // disable user in cloudstack
                    disableUserInCloudStack(user);
                }
            } catch (final NoLdapUserMatchingQueryException e) {
                s_logger.debug(e.getMessage());
            }
        } else {
            // domain is not linked to ldap follow normal authentication
            if (user != null) {
                try {
                    final LdapUser ldapUser = _ldapManager.getUser(username);
                    if (!ldapUser.isDisabled()) {
                        result = _ldapManager.canAuthenticate(ldapUser.getPrincipal(), password);
                    } else {
                        s_logger.debug("user with principal " + ldapUser.getPrincipal() + " is disabled in ldap");
                    }
                } catch (final NoLdapUserMatchingQueryException e) {
                    s_logger.debug(e.getMessage());
                }
            }
        }
        if (!result && user != null) {
            action = ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT;
        }
    }
    return new Pair<>(result, action);
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Pair(com.cloud.legacymodel.utils.Pair)

Example 35 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method createVirtualMachine.

@DB
private UserVm createVirtualMachine(final Zone zone, final ServiceOffering serviceOffering, final VirtualMachineTemplate tmplt, String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final List<NetworkVO> networkList, final String group, final HTTPMethod httpmethod, final String userData, final String sshKeyPair, final HypervisorType hypervisor, final Account caller, final Map<Long, IpAddresses> requestedIps, final IpAddresses defaultIps, final Boolean isDisplayVm, final String keyboard, final List<Long> affinityGroupIdList, final Map<String, String> customParameters, final String customId, final DiskControllerType diskControllerType, final Long bootMenuTimeout, MaintenancePolicy maintenancePolicy, OptimiseFor optimiseFor, String manufacturerString, String bootOrder) 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);
    }
    final VMTemplateVO template = _templateDao.findById(tmplt.getId());
    if (template != null) {
        _templateDao.loadDetails(template);
    }
    if (optimiseFor == null) {
        if (template.getOptimiseFor() != null) {
            optimiseFor = template.getOptimiseFor();
        } else {
            optimiseFor = OptimiseFor.Generic;
        }
    }
    if (manufacturerString == null) {
        manufacturerString = template.getManufacturerString();
    }
    if (maintenancePolicy == null) {
        maintenancePolicy = template.getMaintenancePolicy();
    }
    Boolean macLarning = template.getMacLearning();
    String cpuFlags = template.getCpuFlags();
    final long accountId = owner.getId();
    assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be " + "specified together";
    if (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
    final DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
    if (dedicatedZone != null) {
        final 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());
    // check if account/domain is with in resource limits to create a new vm
    final boolean isIso = ImageFormat.ISO == template.getFormat();
    long size = 0;
    // custom root disk size, resizes base template to larger size
    if (customParameters.containsKey("rootdisksize")) {
        final Long rootDiskSize = NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1);
        if (rootDiskSize <= 0) {
            throw new InvalidParameterValueException("Root disk size should be a positive number.");
        }
        size = rootDiskSize * GB_TO_BYTES;
    }
    if (diskOfferingId != null) {
        final DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
        if (diskOffering != null && diskOffering.isCustomized()) {
            if (diskSize == null) {
                throw new InvalidParameterValueException("This disk offering requires a custom size specified");
            }
            final Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
            final Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
            if (diskSize < customDiskOfferingMinSize || diskSize > customDiskOfferingMaxSize) {
                throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
            }
            size += diskSize * GB_TO_BYTES;
        }
        size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
    }
    resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, isIso || diskOfferingId == null ? 1 : 2);
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
    // check that the affinity groups exist
    if (affinityGroupIdList != null) {
        for (final Long affinityGroupId : affinityGroupIdList) {
            final 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.getDomainId() != owner.getDomainId()) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                }
            }
        }
    }
    final HypervisorType hypervisorType;
    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();
    }
    // check if we have available pools for vm deployment
    final long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
    if (availablePools < 1) {
        throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
    }
    if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
        throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
    }
    final List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
    if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
        throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
    }
    if (isIso && !template.isBootable()) {
        throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
    }
    // Check templates permissions
    _accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
    // check if the user data is correct
    validateUserData(userData, httpmethod);
    // Find an SSH public key corresponding to the key pair name, if one is
    // given
    String sshPublicKey = null;
    if (sshKeyPair != null && !sshKeyPair.equals("")) {
        final 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();
    }
    final List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<>();
    final LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<>();
    short defaultNetworkNumber = 0;
    boolean vpcNetwork = false;
    for (final 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());
            }
            final NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
            final Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
            if (physicalNetworkId == null) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
            final 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() == 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());
        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.getEnablePassword()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
            }
        }
        networks.add(new Pair<>(network, profile));
        networkNicMap.put(network.getUuid(), profile);
    }
    // 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");
    }
    final long id = _vmDao.getNextInSequence(Long.class, "id");
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    final String instanceName;
    final String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
    if (hostName == null) {
        // Generate name using uuid and instance.name global config
        hostName = generateHostName(uuidName);
    }
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
    // Check if VM with instanceName already exists.
    final 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()) {
        final List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
        if (!userVOs.isEmpty()) {
            userId = userVOs.get(0).getId();
        }
    }
    final 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, diskControllerType, manufacturerString, optimiseFor, macLarning, cpuFlags, maintenancePolicy, bootMenuTimeout, bootOrder);
    // Assign instance to the group
    try {
        if (group != null) {
            final boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
            if (!addToGroup) {
                throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
            }
        }
    } catch (final Exception ex) {
        throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
    }
    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) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) Pair(com.cloud.legacymodel.utils.Pair) AffinityGroupVO(com.cloud.affinity.AffinityGroupVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) AccountService(com.cloud.user.AccountService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(com.cloud.legacymodel.network.Network.Service) OrchestrationService(com.cloud.engine.service.api.OrchestrationService) ExecutorService(java.util.concurrent.ExecutorService) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) VolumeApiService(com.cloud.storage.VolumeApiService) AffinityGroupService(com.cloud.affinity.AffinityGroupService) VolumeOrchestrationService(com.cloud.engine.orchestration.service.VolumeOrchestrationService) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) CloudException(com.cloud.legacymodel.exceptions.CloudException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ManagementServerException(com.cloud.legacymodel.exceptions.ManagementServerException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) IpAddresses(com.cloud.legacymodel.network.Network.IpAddresses) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Aggregations

Pair (com.cloud.legacymodel.utils.Pair)139 ArrayList (java.util.ArrayList)87 List (java.util.List)64 Account (com.cloud.legacymodel.user.Account)49 Filter (com.cloud.utils.db.Filter)48 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)38 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)27 HashMap (java.util.HashMap)27 Ternary (com.cloud.legacymodel.utils.Ternary)23 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)22 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)20 SSHKeyPair (com.cloud.legacymodel.user.SSHKeyPair)16 TemplateFilter (com.cloud.legacymodel.storage.VirtualMachineTemplate.TemplateFilter)13 Map (java.util.Map)13 DB (com.cloud.utils.db.DB)11 DomainVO (com.cloud.domain.DomainVO)10 VolumeVO (com.cloud.storage.VolumeVO)10 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)9 Network (com.cloud.legacymodel.network.Network)9 ResourceTagVO (com.cloud.tags.ResourceTagVO)9