Search in sources :

Example 21 with Service

use of com.cloud.network.Network.Service in project cloudstack by apache.

the class VpcManagerImpl method createVpcOffering.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_OFFERING_CREATE, eventDescription = "creating vpc offering", create = true)
public VpcOffering createVpcOffering(final String name, final String displayText, final List<String> supportedServices, final Map<String, List<String>> serviceProviders, final Map serviceCapabilitystList, final Long serviceOfferingId) {
    final Map<Network.Service, Set<Network.Provider>> svcProviderMap = new HashMap<Network.Service, Set<Network.Provider>>();
    final Set<Network.Provider> defaultProviders = new HashSet<Network.Provider>();
    defaultProviders.add(Provider.VPCVirtualRouter);
    // Just here for 4.1, replaced by commit 836ce6c1 in newer versions
    final Set<Network.Provider> sdnProviders = new HashSet<Network.Provider>();
    sdnProviders.add(Provider.NiciraNvp);
    sdnProviders.add(Provider.JuniperContrailVpcRouter);
    sdnProviders.add(Provider.NuageVsp);
    boolean sourceNatSvc = false;
    boolean firewallSvs = false;
    // populate the services first
    for (final String serviceName : supportedServices) {
        // validate if the service is supported
        final Service service = Network.Service.getService(serviceName);
        if (service == null || nonSupportedServices.contains(service)) {
            throw new InvalidParameterValueException("Service " + serviceName + " is not supported in VPC");
        }
        if (service == Service.Connectivity) {
            s_logger.debug("Applying Connectivity workaround, setting provider to NiciraNvp");
            svcProviderMap.put(service, sdnProviders);
        } else {
            svcProviderMap.put(service, defaultProviders);
        }
        if (service == Service.NetworkACL) {
            firewallSvs = true;
        }
        if (service == Service.SourceNat) {
            sourceNatSvc = true;
        }
    }
    if (!sourceNatSvc) {
        s_logger.debug("Automatically adding source nat service to the list of VPC services");
        svcProviderMap.put(Service.SourceNat, defaultProviders);
    }
    if (!firewallSvs) {
        s_logger.debug("Automatically adding network ACL service to the list of VPC services");
        svcProviderMap.put(Service.NetworkACL, defaultProviders);
    }
    if (serviceProviders != null) {
        for (final Entry<String, List<String>> serviceEntry : serviceProviders.entrySet()) {
            final Network.Service service = Network.Service.getService(serviceEntry.getKey());
            if (svcProviderMap.containsKey(service)) {
                final Set<Provider> providers = new HashSet<Provider>();
                for (final String prvNameStr : serviceEntry.getValue()) {
                    // check if provider is supported
                    final Network.Provider provider = Network.Provider.getProvider(prvNameStr);
                    if (provider == null) {
                        throw new InvalidParameterValueException("Invalid service provider: " + prvNameStr);
                    }
                    providers.add(provider);
                }
                svcProviderMap.put(service, providers);
            } else {
                throw new InvalidParameterValueException("Service " + serviceEntry.getKey() + " is not enabled for the network " + "offering, can't add a provider to it");
            }
        }
    }
    // add gateway provider (if sourceNat provider is enabled)
    final Set<Provider> sourceNatServiceProviders = svcProviderMap.get(Service.SourceNat);
    if (CollectionUtils.isNotEmpty(sourceNatServiceProviders)) {
        svcProviderMap.put(Service.Gateway, sourceNatServiceProviders);
    }
    validateConnectivtyServiceCapabilities(svcProviderMap.get(Service.Connectivity), serviceCapabilitystList);
    final boolean supportsDistributedRouter = isVpcOfferingSupportsDistributedRouter(serviceCapabilitystList);
    final boolean offersRegionLevelVPC = isVpcOfferingForRegionLevelVpc(serviceCapabilitystList);
    final boolean redundantRouter = isVpcOfferingRedundantRouter(serviceCapabilitystList);
    final VpcOffering offering = createVpcOffering(name, displayText, svcProviderMap, false, null, serviceOfferingId, supportsDistributedRouter, offersRegionLevelVPC, redundantRouter);
    CallContext.current().setEventDetails(" Id: " + offering.getId() + " Name: " + name);
    return offering;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NetworkService(com.cloud.network.NetworkService) ResourceLimitService(com.cloud.user.ResourceLimitService) ExecutorService(java.util.concurrent.ExecutorService) Service(com.cloud.network.Network.Service) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) VpcProvider(com.cloud.network.element.VpcProvider) Provider(com.cloud.network.Network.Provider) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Provider(com.cloud.network.Network.Provider) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) ActionEvent(com.cloud.event.ActionEvent)

Example 22 with Service

use of com.cloud.network.Network.Service in project cloudstack by apache.

the class UserVmManagerImpl method createVirtualMachine.

@DB
protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate tmplt, String hostName, String displayName, Account owner, Long diskOfferingId, Long diskSize, List<NetworkVO> networkList, List<Long> securityGroupIdList, String group, HTTPMethod httpmethod, String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean isDisplayVm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParameters, String customId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
    _accountMgr.checkAccess(caller, null, true, owner);
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner);
    }
    VMTemplateVO template = _templateDao.findById(tmplt.getId());
    if (template != null) {
        _templateDao.loadDetails(template);
    }
    long accountId = owner.getId();
    assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be specified together";
    if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId());
    }
    // check if zone is dedicated
    DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
    if (dedicatedZone != null) {
        DomainVO domain = _domainDao.findById(dedicatedZone.getDomainId());
        if (domain == null) {
            throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone);
        }
        // check that caller can operate with domain
        _configMgr.checkZoneAccess(caller, zone);
        // check that vm owner can create vm in the domain
        _configMgr.checkZoneAccess(owner, zone);
    }
    ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId());
    if (offering.isDynamic()) {
        offering.setDynamicFlag(true);
        validateCustomParameters(offering, customParameters);
        offering = _offeringDao.getcomputeOffering(offering, customParameters);
    }
    // check if account/domain is with in resource limits to create a new vm
    boolean isIso = Storage.ImageFormat.ISO == template.getFormat();
    // For baremetal, size can be null
    Long tmp = _templateDao.findById(template.getId()).getSize();
    long size = 0;
    if (tmp != null) {
        size = tmp;
    }
    if (diskOfferingId != null) {
        DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
        if (diskOffering != null && diskOffering.isCustomized()) {
            if (diskSize == null) {
                throw new InvalidParameterValueException("This disk offering requires a custom size specified");
            }
            Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
            Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
            if ((diskSize < customDiskOfferingMinSize) || (diskSize > customDiskOfferingMaxSize)) {
                throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
            }
            size = size + diskSize * (1024 * 1024 * 1024);
        }
        size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
    }
    resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso || diskOfferingId == null ? 1 : 2));
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
    // verify security group ids
    if (securityGroupIdList != null) {
        for (Long securityGroupId : securityGroupIdList) {
            SecurityGroup sg = _securityGroupDao.findById(securityGroupId);
            if (sg == null) {
                throw new InvalidParameterValueException("Unable to find security group by id " + securityGroupId);
            } else {
                // verify permissions
                _accountMgr.checkAccess(caller, null, true, owner, sg);
            }
        }
    }
    // check that the affinity groups exist
    if (affinityGroupIdList != null) {
        for (Long affinityGroupId : affinityGroupIdList) {
            AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
            if (ag == null) {
                throw new InvalidParameterValueException("Unable to find affinity group " + ag);
            } else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {
                throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + " , Please try again after removing the affinity group");
            } else {
                // verify permissions
                if (ag.getAclType() == ACLType.Domain) {
                    _accountMgr.checkAccess(caller, null, false, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                } else {
                    _accountMgr.checkAccess(caller, null, true, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (ag.getAccountId() != owner.getAccountId()) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
                        }
                    }
                }
            }
        }
    }
    HypervisorType hypervisorType = null;
    if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) {
        if (hypervisor == null || hypervisor == HypervisorType.None) {
            throw new InvalidParameterValueException("hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid");
        }
        hypervisorType = hypervisor;
    } else {
        if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) {
            throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the template");
        }
        hypervisorType = template.getHypervisorType();
    }
    if (hypervisorType != HypervisorType.BareMetal) {
        // check if we have available pools for vm deployment
        long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
        if (availablePools < 1) {
            throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
        }
    }
    if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
        throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
    }
    List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
    if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
        throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
    }
    if (isIso && !template.isBootable()) {
        throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
    }
    // Check templates permissions
    _accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
    // check if the user data is correct
    validateUserData(userData, httpmethod);
    // Find an SSH public key corresponding to the key pair name, if one is
    // given
    String sshPublicKey = null;
    if (sshKeyPair != null && !sshKeyPair.equals("")) {
        SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
        if (pair == null) {
            throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.");
        }
        sshPublicKey = pair.getPublicKey();
    }
    List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>();
    LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<String, NicProfile>();
    short defaultNetworkNumber = 0;
    boolean securityGroupEnabled = false;
    boolean vpcNetwork = false;
    for (NetworkVO network : networkList) {
        if ((network.getDataCenterId() != zone.getId())) {
            if (!network.isStrechedL2Network()) {
                throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId());
            }
            NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
            Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
            if (physicalNetworkId == null) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
            String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
            if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
        }
        //relax the check if the caller is admin account
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) {
                throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm");
            }
        }
        IpAddresses requestedIpPair = null;
        if (requestedIps != null && !requestedIps.isEmpty()) {
            requestedIpPair = requestedIps.get(network.getId());
        }
        if (requestedIpPair == null) {
            requestedIpPair = new IpAddresses(null, null);
        } else {
            _networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address());
        }
        NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address());
        if (defaultNetworkNumber == 0) {
            defaultNetworkNumber++;
            // if user requested specific ip for default network, add it
            if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {
                _networkModel.checkRequestedIpAddresses(network.getId(), defaultIps.getIp4Address(), defaultIps.getIp6Address());
                profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
            }
            profile.setDefaultNic(true);
            if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {
                if ((userData != null) && (!userData.isEmpty())) {
                    throw new InvalidParameterValueException("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if ((sshPublicKey != null) && (!sshPublicKey.isEmpty())) {
                    throw new InvalidParameterValueException("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (template.getEnablePassword()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
            }
        }
        networks.add(new Pair<NetworkVO, NicProfile>(network, profile));
        if (_networkModel.isSecurityGroupSupportedInNetwork(network)) {
            securityGroupEnabled = true;
        }
        // vm can't be a part of more than 1 VPC network
        if (network.getVpcId() != null) {
            if (vpcNetwork) {
                throw new InvalidParameterValueException("Vm can't be a part of more than 1 VPC network");
            }
            vpcNetwork = true;
        }
        networkNicMap.put(network.getUuid(), profile);
    }
    if (securityGroupIdList != null && !securityGroupIdList.isEmpty() && !securityGroupEnabled) {
        throw new InvalidParameterValueException("Unable to deploy vm with security groups as SecurityGroup service is not enabled for the vm's network");
    }
    // gateway for the vm
    if (defaultNetworkNumber == 0) {
        throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm");
    } else if (defaultNetworkNumber > 1) {
        throw new InvalidParameterValueException("Only 1 default network per vm is supported");
    }
    long id = _vmDao.getNextInSequence(Long.class, "id");
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    String instanceName = null;
    String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
    if (_instanceNameFlag && hypervisor.equals(HypervisorType.VMware)) {
        if (hostName == null) {
            if (displayName != null) {
                hostName = displayName;
            } else {
                hostName = generateHostName(uuidName);
            }
        }
        // If global config vm.instancename.flag is set to true, then CS will set guest VM's name as it appears on the hypervisor, to its hostname.
        // In case of VMware since VM name must be unique within a DC, check if VM with the same hostname already exists in the zone.
        VMInstanceVO vmByHostName = _vmInstanceDao.findVMByHostNameInZone(hostName, zone.getId());
        if (vmByHostName != null && vmByHostName.getState() != VirtualMachine.State.Expunging) {
            throw new InvalidParameterValueException("There already exists a VM by the name: " + hostName + ".");
        }
    } else {
        if (hostName == null) {
            //Generate name using uuid and instance.name global config
            hostName = generateHostName(uuidName);
        }
    }
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
    // Check if VM with instanceName already exists.
    VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);
    if (vmObj != null && vmObj.getState() != VirtualMachine.State.Expunging) {
        throw new InvalidParameterValueException("There already exists a VM by the display name supplied");
    }
    checkIfHostNameUniqueInNtwkDomain(hostName, networkList);
    long userId = CallContext.current().getCallingUserId();
    if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
        List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
        if (!userVOs.isEmpty()) {
            userId = userVOs.get(0).getId();
        }
    }
    UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters);
    // Assign instance to the group
    try {
        if (group != null) {
            boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
            if (!addToGroup) {
                throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
            }
        }
    } catch (Exception ex) {
        throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
    }
    _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
    if (affinityGroupIdList != null && !affinityGroupIdList.isEmpty()) {
        _affinityGroupVMMapDao.updateMap(vm.getId(), affinityGroupIdList);
    }
    CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid());
    return vm;
}
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.exception.StorageUnavailableException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair) 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) 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) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) VolumeApiService(com.cloud.storage.VolumeApiService) AffinityGroupService(org.apache.cloudstack.affinity.AffinityGroupService) SecurityGroup(com.cloud.network.security.SecurityGroup) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) 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) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) 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 23 with Service

use of com.cloud.network.Network.Service in project cloudstack by apache.

the class VpcVirtualRouterElement method applyIps.

@Override
public boolean applyIps(final Network network, final List<? extends PublicIpAddress> ipAddress, final Set<Service> services) throws ResourceUnavailableException {
    boolean canHandle = true;
    for (final Service service : services) {
        if (!canHandle(network, service)) {
            canHandle = false;
            break;
        }
    }
    boolean result = true;
    if (canHandle) {
        final List<DomainRouterVO> routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER);
        if (routers == null || routers.isEmpty()) {
            s_logger.debug(getName() + " element doesn't need to associate ip addresses on the backend; VPC virtual " + "router doesn't exist in the network " + network.getId());
            return false;
        }
        final DataCenterVO dcVO = _dcDao.findById(network.getDataCenterId());
        final NetworkTopology networkTopology = networkTopologyContext.retrieveNetworkTopology(dcVO);
        for (final DomainRouterVO domainRouterVO : routers) {
            result = result && networkTopology.associatePublicIP(network, ipAddress, domainRouterVO);
        }
    }
    return result;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) NetworkTopology(org.apache.cloudstack.network.topology.NetworkTopology) Service(com.cloud.network.Network.Service) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 24 with Service

use of com.cloud.network.Network.Service in project cloudstack by apache.

the class NetworkOfferingServiceMapDaoImpl method areServicesSupportedByNetworkOffering.

@Override
public boolean areServicesSupportedByNetworkOffering(long networkOfferingId, Service... services) {
    SearchCriteria<NetworkOfferingServiceMapVO> sc = MultipleServicesSearch.create();
    sc.setParameters("networkOfferingId", networkOfferingId);
    if (services != null) {
        String[] servicesStr = new String[services.length];
        int i = 0;
        for (Service service : services) {
            servicesStr[i] = service.getName();
            i++;
        }
        sc.setParameters("service", (Object[]) servicesStr);
    }
    List<NetworkOfferingServiceMapVO> offeringServices = listBy(sc);
    if (services != null) {
        if (offeringServices.size() == services.length) {
            return true;
        }
    } else if (!offeringServices.isEmpty()) {
        return true;
    }
    return false;
}
Also used : NetworkOfferingServiceMapVO(com.cloud.offerings.NetworkOfferingServiceMapVO) Service(com.cloud.network.Network.Service)

Example 25 with Service

use of com.cloud.network.Network.Service in project cloudstack by apache.

the class NetscalerElement method getCapabilities.

@Override
public Map<Service, Map<Capability, String>> getCapabilities() {
    Map<Service, Map<Capability, String>> capabilities = new HashMap<Service, Map<Capability, String>>();
    // Set capabilities for LB service
    Map<Capability, String> lbCapabilities = new HashMap<Capability, String>();
    // Specifies that the RoundRobin and Leastconn algorithms are supported for load balancing rules
    lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin, leastconn, source");
    // specifies that Netscaler network element can provided both shared and isolation modes
    lbCapabilities.put(Capability.SupportedLBIsolation, "dedicated, shared");
    // Specifies that load balancing rules can be made for either TCP or UDP traffic
    lbCapabilities.put(Capability.SupportedProtocols, "tcp,udp");
    // Specifies that this element can measure network usage on a per public IP basis
    lbCapabilities.put(Capability.TrafficStatistics, "per public ip");
    // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs
    lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional");
    // Supports only Public load balancing
    lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString());
    // Specifies that load balancing rules can support autoscaling and the list of counters it supports
    AutoScaleCounter counter;
    List<AutoScaleCounter> counterList = new ArrayList<AutoScaleCounter>();
    counter = new AutoScaleCounter(AutoScaleCounterSnmp);
    counterList.add(counter);
    counter.addParam("snmpcommunity", true, "the community string that has to be used to do a SNMP GET on the AutoScaled Vm", false);
    counter.addParam("snmpport", false, "the port at which SNMP agent is running on the AutoScaled Vm", false);
    counter = new AutoScaleCounter(AutoScaleCounterNetscaler);
    counterList.add(counter);
    Gson gson = new Gson();
    String autoScaleCounterList = gson.toJson(counterList);
    lbCapabilities.put(Capability.AutoScaleCounters, autoScaleCounterList);
    LbStickinessMethod method;
    List<LbStickinessMethod> methodList = new ArrayList<LbStickinessMethod>();
    method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http");
    methodList.add(method);
    method.addParam("holdtime", false, "time period in minutes for which persistence is in effect.", false);
    method = new LbStickinessMethod(StickinessMethodType.AppCookieBased, "This is app session based sticky method, can be used only for http");
    methodList.add(method);
    method.addParam("name", true, "cookie name passed in http header by apllication to the client", false);
    method = new LbStickinessMethod(StickinessMethodType.SourceBased, "This is source based sticky method, can be used for any type of protocol.");
    methodList.add(method);
    method.addParam("holdtime", false, "time period for which persistence is in effect.", false);
    String stickyMethodList = gson.toJson(methodList);
    lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList);
    lbCapabilities.put(Capability.ElasticLb, "true");
    //Setting HealthCheck Capability to True for Netscaler element
    lbCapabilities.put(Capability.HealthCheckPolicy, "true");
    capabilities.put(Service.Lb, lbCapabilities);
    Map<Capability, String> staticNatCapabilities = new HashMap<Capability, String>();
    staticNatCapabilities.put(Capability.ElasticIp, "true");
    capabilities.put(Service.StaticNat, staticNatCapabilities);
    // Supports SSL offloading
    lbCapabilities.put(Capability.SslTermination, "true");
    // TODO - Murali, please put correct capabilities here
    Map<Capability, String> firewallCapabilities = new HashMap<Capability, String>();
    firewallCapabilities.put(Capability.TrafficStatistics, "per public ip");
    firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp");
    firewallCapabilities.put(Capability.MultipleIps, "true");
    capabilities.put(Service.Firewall, firewallCapabilities);
    return capabilities;
}
Also used : AutoScaleCounter(com.cloud.network.as.AutoScaleCounter) Capability(com.cloud.network.Network.Capability) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Service(com.cloud.network.Network.Service) Gson(com.google.gson.Gson) LbStickinessMethod(com.cloud.network.rules.LbStickinessMethod) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Service (com.cloud.network.Network.Service)76 HashMap (java.util.HashMap)40 ArrayList (java.util.ArrayList)37 Provider (com.cloud.network.Network.Provider)36 HashSet (java.util.HashSet)36 NetworkOrchestrationService (org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService)31 Set (java.util.Set)30 ResourceLimitService (com.cloud.user.ResourceLimitService)28 Map (java.util.Map)22 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 Network (com.cloud.network.Network)18 Capability (com.cloud.network.Network.Capability)17 NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)15 NetworkElement (com.cloud.network.element.NetworkElement)14 Test (org.junit.Test)13 UserDataServiceProvider (com.cloud.network.element.UserDataServiceProvider)12 NetworkService (com.cloud.network.NetworkService)11 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)11 NetworkOffering (com.cloud.offering.NetworkOffering)10 Account (com.cloud.user.Account)10