Search in sources :

Example 11 with NetworkElement

use of com.cloud.network.element.NetworkElement in project cloudstack by apache.

the class NetworkServiceImpl method updateNetworkServiceProvider.

@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_UPDATE, eventDescription = "Updating physical network ServiceProvider", async = true)
public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String stateStr, List<String> enabledServices) {
    PhysicalNetworkServiceProviderVO provider = _pNSPDao.findById(id);
    if (provider == null) {
        throw new InvalidParameterValueException("Network Service Provider id=" + id + "doesn't exist in the system");
    }
    NetworkElement element = _networkModel.getElementImplementingProvider(provider.getProviderName());
    if (element == null) {
        throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + provider.getProviderName() + "'");
    }
    PhysicalNetworkServiceProvider.State state = null;
    if (stateStr != null && !stateStr.isEmpty()) {
        try {
            state = PhysicalNetworkServiceProvider.State.valueOf(stateStr);
        } catch (IllegalArgumentException ex) {
            throw new InvalidParameterValueException("Unable to resolve state '" + stateStr + "' to a supported value {Enabled or Disabled}");
        }
    }
    boolean update = false;
    if (state != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("trying to update the state of the service provider id=" + id + " on physical network: " + provider.getPhysicalNetworkId() + " to state: " + stateStr);
        }
        switch(state) {
            case Enabled:
                if (element != null && element.isReady(provider)) {
                    provider.setState(PhysicalNetworkServiceProvider.State.Enabled);
                    update = true;
                } else {
                    throw new CloudRuntimeException("Provider is not ready, cannot Enable the provider, please configure the provider first");
                }
                break;
            case Disabled:
                // do we need to do anything for the provider instances before disabling?
                provider.setState(PhysicalNetworkServiceProvider.State.Disabled);
                update = true;
                break;
            case Shutdown:
                throw new InvalidParameterValueException("Updating the provider state to 'Shutdown' is not supported");
        }
    }
    if (enabledServices != null) {
        // check if services can be turned of
        if (!element.canEnableIndividualServices()) {
            throw new InvalidParameterValueException("Cannot update set of Services for this Service Provider '" + provider.getProviderName() + "'");
        }
        // validate Services
        List<Service> services = new ArrayList<Service>();
        for (String serviceName : enabledServices) {
            Network.Service service = Network.Service.getService(serviceName);
            if (service == null) {
                throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName);
            }
            services.add(service);
        }
        // set enabled services
        provider.setEnabledServices(services);
        update = true;
    }
    if (update) {
        _pNSPDao.update(id, provider);
    }
    return provider;
}
Also used : ArrayList(java.util.ArrayList) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) LoadBalancingRulesService(com.cloud.network.lb.LoadBalancingRulesService) SecurityGroupService(com.cloud.network.security.SecurityGroupService) ResourceLimitService(com.cloud.user.ResourceLimitService) InternalLoadBalancerElementService(org.apache.cloudstack.network.element.InternalLoadBalancerElementService) Service(com.cloud.network.Network.Service) NetworkElement(com.cloud.network.element.NetworkElement) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Example 12 with NetworkElement

use of com.cloud.network.element.NetworkElement in project cloudstack by apache.

the class NetworkServiceImpl method addProviderToPhysicalNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_PROVIDER_CREATE, eventDescription = "Creating Physical Network ServiceProvider", create = true)
public PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, List<String> enabledServices) {
    // verify input parameters
    PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId);
    if (network == null) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
        ex.addProxyObject(physicalNetworkId.toString(), "physicalNetworkId");
        throw ex;
    }
    // verify input parameters
    if (destinationPhysicalNetworkId != null) {
        PhysicalNetworkVO destNetwork = _physicalNetworkDao.findById(destinationPhysicalNetworkId);
        if (destNetwork == null) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Destination Physical Network with specified id doesn't exist in the system");
            ex.addProxyObject(destinationPhysicalNetworkId.toString(), "destinationPhysicalNetworkId");
            throw ex;
        }
    }
    if (providerName != null) {
        Provider provider = Network.Provider.getProvider(providerName);
        if (provider == null) {
            throw new InvalidParameterValueException("Invalid Network Service Provider=" + providerName);
        }
    }
    if (_pNSPDao.findByServiceProvider(physicalNetworkId, providerName) != null) {
        // TBD: send uuid instead of physicalNetworkId.
        throw new CloudRuntimeException("The '" + providerName + "' provider already exists on physical network : " + physicalNetworkId);
    }
    // check if services can be turned off
    NetworkElement element = _networkModel.getElementImplementingProvider(providerName);
    if (element == null) {
        throw new InvalidParameterValueException("Unable to find the Network Element implementing the Service Provider '" + providerName + "'");
    }
    List<Service> services = new ArrayList<Service>();
    if (enabledServices != null) {
        if (!element.canEnableIndividualServices()) {
            if (enabledServices.size() != element.getCapabilities().keySet().size()) {
                throw new InvalidParameterValueException("Cannot enable subset of Services, Please specify the complete list of Services for this Service Provider '" + providerName + "'");
            }
        }
        // validate Services
        boolean addGatewayService = false;
        for (String serviceName : enabledServices) {
            Network.Service service = Network.Service.getService(serviceName);
            if (service == null || service == Service.Gateway) {
                throw new InvalidParameterValueException("Invalid Network Service specified=" + serviceName);
            } else if (service == Service.SourceNat) {
                addGatewayService = true;
            }
            // check if the service is provided by this Provider
            if (!element.getCapabilities().containsKey(service)) {
                throw new InvalidParameterValueException(providerName + " Provider cannot provide this Service specified=" + serviceName);
            }
            services.add(service);
        }
        if (addGatewayService) {
            services.add(Service.Gateway);
        }
    } else {
        // enable all the default services supported by this element.
        services = new ArrayList<Service>(element.getCapabilities().keySet());
    }
    try {
        // Create the new physical network in the database
        PhysicalNetworkServiceProviderVO nsp = new PhysicalNetworkServiceProviderVO(physicalNetworkId, providerName);
        // set enabled services
        nsp.setEnabledServices(services);
        if (destinationPhysicalNetworkId != null) {
            nsp.setDestinationPhysicalNetworkId(destinationPhysicalNetworkId);
        }
        nsp = _pNSPDao.persist(nsp);
        return nsp;
    } catch (Exception ex) {
        s_logger.warn("Exception: ", ex);
        throw new CloudRuntimeException("Fail to add a provider to physical network");
    }
}
Also used : ArrayList(java.util.ArrayList) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) LoadBalancingRulesService(com.cloud.network.lb.LoadBalancingRulesService) SecurityGroupService(com.cloud.network.security.SecurityGroupService) ResourceLimitService(com.cloud.user.ResourceLimitService) InternalLoadBalancerElementService(org.apache.cloudstack.network.element.InternalLoadBalancerElementService) Service(com.cloud.network.Network.Service) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) UnknownHostException(java.net.UnknownHostException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Provider(com.cloud.network.Network.Provider) NetworkElement(com.cloud.network.element.NetworkElement) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 13 with NetworkElement

use of com.cloud.network.element.NetworkElement in project cloudstack by apache.

the class NetworkServiceImpl method addDefaultVpcVirtualRouterToPhysicalNetwork.

protected PhysicalNetworkServiceProvider addDefaultVpcVirtualRouterToPhysicalNetwork(long physicalNetworkId) {
    PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VPCVirtualRouter.getName(), null, null);
    NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
    if (networkElement == null) {
        throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider");
    }
    VpcVirtualRouterElement element = (VpcVirtualRouterElement) networkElement;
    element.addElement(nsp.getId(), Type.VPCVirtualRouter);
    return nsp;
}
Also used : NetworkElement(com.cloud.network.element.NetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VpcVirtualRouterElement(com.cloud.network.element.VpcVirtualRouterElement)

Example 14 with NetworkElement

use of com.cloud.network.element.NetworkElement in project cloudstack by apache.

the class NetworkModelTest method testCapabilityForProvider.

@Test
public void testCapabilityForProvider() {
    NetworkModelImpl modelImpl = spy(NetworkModelImpl.class);
    Set<Provider> providers = new HashSet<>();
    providers.add(Provider.NuageVsp);
    NetworkElement nuageVspElement = mock(NetworkElement.class);
    HashMap<Network.Service, Map<Network.Capability, String>> nuageVspCap = new HashMap<Network.Service, Map<Network.Capability, String>>();
    HashMap<Network.Capability, String> nuageVspConnectivity = new HashMap<Network.Capability, String>();
    nuageVspConnectivity.put(Network.Capability.NoVlan, "FindMe");
    nuageVspConnectivity.put(Network.Capability.PublicAccess, "");
    nuageVspCap.put(Network.Service.Connectivity, nuageVspConnectivity);
    when(nuageVspElement.getName()).thenReturn("NuageVsp");
    doReturn(nuageVspCap).when(nuageVspElement).getCapabilities();
    doReturn(nuageVspElement).when(modelImpl).getElementImplementingProvider("NuageVsp");
    try {
        modelImpl.checkCapabilityForProvider(providers, Network.Service.UserData, null, null);
        Assert.fail();
    } catch (UnsupportedServiceException e) {
        Assert.assertEquals(e.getMessage(), "Service " + Network.Service.UserData.getName() + " is not supported by the element=NuageVsp implementing Provider=" + Provider.NuageVsp.getName());
    }
    try {
        modelImpl.checkCapabilityForProvider(providers, Network.Service.Connectivity, Network.Capability.ElasticIp, null);
        Assert.fail();
    } catch (UnsupportedServiceException e) {
        Assert.assertEquals(e.getMessage(), "Service " + Network.Service.Connectivity.getName() + " doesn't have capability " + Network.Capability.ElasticIp.getName() + " for element=NuageVsp implementing Provider=" + Provider.NuageVsp.getName());
    }
    try {
        modelImpl.checkCapabilityForProvider(providers, Network.Service.Connectivity, Network.Capability.PublicAccess, "NonExistingVal");
        Assert.fail();
    } catch (UnsupportedServiceException e) {
        Assert.assertEquals(e.getMessage(), "Service Connectivity doesn't have capability PublicAccess for element=NuageVsp implementing Provider=NuageVsp");
    }
    modelImpl.checkCapabilityForProvider(providers, Network.Service.Connectivity, Network.Capability.NoVlan, "FindMe");
    NetworkElement nuageVspElement2 = mock(NetworkElement.class);
    doReturn(null).when(nuageVspElement).getCapabilities();
    try {
        modelImpl.checkCapabilityForProvider(providers, Network.Service.Connectivity, Network.Capability.PublicAccess, "");
        Assert.fail();
    } catch (UnsupportedServiceException e) {
        Assert.assertEquals(e.getMessage(), "Service Connectivity is not supported by the element=NuageVsp implementing Provider=NuageVsp");
    }
}
Also used : HashMap(java.util.HashMap) Provider(com.cloud.network.Network.Provider) NetworkElement(com.cloud.network.element.NetworkElement) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 15 with NetworkElement

use of com.cloud.network.element.NetworkElement in project cloudstack by apache.

the class NetworkOrchestrator method destroyNetwork.

@Override
@DB
public boolean destroyNetwork(final long networkId, final ReservationContext context, final boolean forced) {
    final Account callerAccount = context.getAccount();
    NetworkVO network = _networksDao.findById(networkId);
    if (network == null) {
        s_logger.debug("Unable to find network with id: " + networkId);
        return false;
    }
    // Make sure that there are no user vms in the network that are not Expunged/Error
    final List<UserVmVO> userVms = _userVmDao.listByNetworkIdAndStates(networkId);
    for (final UserVmVO vm : userVms) {
        if (!(vm.getState() == VirtualMachine.State.Expunging && vm.getRemoved() != null)) {
            s_logger.warn("Can't delete the network, not all user vms are expunged. Vm " + vm + " is in " + vm.getState() + " state");
            return false;
        }
    }
    // Don't allow to delete network via api call when it has vms assigned to it
    final int nicCount = getActiveNicsInNetwork(networkId);
    if (nicCount > 0) {
        s_logger.debug("The network id=" + networkId + " has active Nics, but shouldn't.");
        // at this point we have already determined that there are no active user vms in network
        // if the op_networks table shows active nics, it's a bug in releasing nics updating op_networks
        _networksDao.changeActiveNicsBy(networkId, -1 * nicCount);
    }
    //In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network
    final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
    if (zone.getNetworkType() == NetworkType.Basic) {
        final List<VMInstanceVO> systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), Type.ConsoleProxy, Type.SecondaryStorageVm);
        if (systemVms != null && !systemVms.isEmpty()) {
            s_logger.warn("Can't delete the network, not all consoleProxy/secondaryStorage vms are expunged");
            return false;
        }
    }
    // Shutdown network first
    shutdownNetwork(networkId, context, false);
    // get updated state for the network
    network = _networksDao.findById(networkId);
    if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup && !forced) {
        s_logger.debug("Network is not not in the correct state to be destroyed: " + network.getState());
        return false;
    }
    boolean success = true;
    if (!cleanupNetworkResources(networkId, callerAccount, context.getCaller().getId())) {
        s_logger.warn("Unable to delete network id=" + networkId + ": failed to cleanup network resources");
        return false;
    }
    // get providers to destroy
    final List<Provider> providersToDestroy = getNetworkProviders(network.getId());
    for (final NetworkElement element : networkElements) {
        if (providersToDestroy.contains(element.getProvider())) {
            try {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Sending destroy to " + element);
                }
                if (!element.destroy(network, context)) {
                    success = false;
                    s_logger.warn("Unable to complete destroy of the network: failed to destroy network element " + element.getName());
                }
            } catch (final ResourceUnavailableException e) {
                s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
                success = false;
            } catch (final ConcurrentOperationException e) {
                s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
                success = false;
            } catch (final Exception e) {
                s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
                success = false;
            }
        }
    }
    if (success) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Network id=" + networkId + " is destroyed successfully, cleaning up corresponding resources now.");
        }
        final NetworkVO networkFinal = network;
        try {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
                    guru.trash(networkFinal, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId()));
                    if (!deleteVlansInNetwork(networkFinal.getId(), context.getCaller().getId(), callerAccount)) {
                        s_logger.warn("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
                        throw new CloudRuntimeException("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
                    } else {
                        // commit transaction only when ips and vlans for the network are released successfully
                        try {
                            stateTransitTo(networkFinal, Event.DestroyNetwork);
                        } catch (final NoTransitionException e) {
                            s_logger.debug(e.getMessage());
                        }
                        if (_networksDao.remove(networkFinal.getId())) {
                            final NetworkDomainVO networkDomain = _networkDomainDao.getDomainNetworkMapByNetworkId(networkFinal.getId());
                            if (networkDomain != null) {
                                _networkDomainDao.remove(networkDomain.getId());
                            }
                            final NetworkAccountVO networkAccount = _networkAccountDao.getAccountNetworkMapByNetworkId(networkFinal.getId());
                            if (networkAccount != null) {
                                _networkAccountDao.remove(networkAccount.getId());
                            }
                        }
                        final NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, networkFinal.getNetworkOfferingId());
                        final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, networkFinal.getAclType());
                        if (updateResourceCount) {
                            _resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network, networkFinal.getDisplayNetwork());
                        }
                    }
                }
            });
            if (_networksDao.findById(network.getId()) == null) {
                // remove its related ACL permission
                final Pair<Class<?>, Long> networkMsg = new Pair<Class<?>, Long>(Network.class, networkFinal.getId());
                _messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg);
            }
            return true;
        } catch (final CloudRuntimeException e) {
            s_logger.error("Failed to delete network", e);
            return false;
        }
    }
    return success;
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkElement(com.cloud.network.element.NetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) Pair(com.cloud.utils.Pair) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) NetworkGuru(com.cloud.network.guru.NetworkGuru) VMInstanceVO(com.cloud.vm.VMInstanceVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConnectionException(com.cloud.exception.ConnectionException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) ConfigurationException(javax.naming.ConfigurationException) DnsServiceProvider(com.cloud.network.element.DnsServiceProvider) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) Provider(com.cloud.network.Network.Provider) DataCenter(com.cloud.dc.DataCenter) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NetworkAccountVO(com.cloud.network.dao.NetworkAccountVO) DB(com.cloud.utils.db.DB)

Aggregations

NetworkElement (com.cloud.network.element.NetworkElement)36 Provider (com.cloud.network.Network.Provider)23 UserDataServiceProvider (com.cloud.network.element.UserDataServiceProvider)17 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)17 StaticNatServiceProvider (com.cloud.network.element.StaticNatServiceProvider)15 Service (com.cloud.network.Network.Service)14 DhcpServiceProvider (com.cloud.network.element.DhcpServiceProvider)13 LoadBalancingServiceProvider (com.cloud.network.element.LoadBalancingServiceProvider)13 DnsServiceProvider (com.cloud.network.element.DnsServiceProvider)12 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)11 UnsupportedServiceException (com.cloud.exception.UnsupportedServiceException)11 HashMap (java.util.HashMap)10 Map (java.util.Map)10 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)9 Capability (com.cloud.network.Network.Capability)8 NetworkVO (com.cloud.network.dao.NetworkVO)8 NetworkGuru (com.cloud.network.guru.NetworkGuru)8 ArrayList (java.util.ArrayList)8 NicProfile (com.cloud.vm.NicProfile)7 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)6