Search in sources :

Example 56 with Provider

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

the class NetworkOrchestrator method prepareAllNicsForMigration.

/*
    Prepare All Nics for migration including the nics dynamically created and not stored in DB
    This is a temporary workaround work KVM migration
    Once clean fix is added by stored dynamically nics is DB, this workaround won't be needed
     */
@Override
public void prepareAllNicsForMigration(final VirtualMachineProfile vm, final DeployDestination dest) {
    final List<NicVO> nics = _nicDao.listByVmId(vm.getId());
    final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), null, null);
    Long guestNetworkId = null;
    for (final NicVO nic : nics) {
        final NetworkVO network = _networksDao.findById(nic.getNetworkId());
        if (network.getTrafficType().equals(TrafficType.Guest) && network.getGuestType().equals(GuestType.Isolated)) {
            guestNetworkId = network.getId();
        }
        final Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
        final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
        final NicProfile profile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network));
        if (guru instanceof NetworkMigrationResponder) {
            if (!((NetworkMigrationResponder) guru).prepareMigration(profile, network, vm, dest, context)) {
                // XXX: Transaction error
                s_logger.error("NetworkGuru " + guru + " prepareForMigration failed.");
            }
        }
        final List<Provider> providersToImplement = getNetworkProviders(network.getId());
        for (final NetworkElement element : networkElements) {
            if (providersToImplement.contains(element.getProvider())) {
                if (!_networkModel.isProviderEnabledInPhysicalNetwork(_networkModel.getPhysicalNetworkId(network), element.getProvider().getName())) {
                    throw new CloudRuntimeException("Service provider " + element.getProvider().getName() + " either doesn't exist or is not enabled in physical network id: " + network.getPhysicalNetworkId());
                }
                if (element instanceof NetworkMigrationResponder) {
                    if (!((NetworkMigrationResponder) element).prepareMigration(profile, network, vm, dest, context)) {
                        // XXX: Transaction error
                        s_logger.error("NetworkElement " + element + " prepareForMigration failed.");
                    }
                }
            }
        }
        guru.updateNicProfile(profile, network);
        vm.addNic(profile);
    }
    final List<String> addedURIs = new ArrayList<String>();
    if (guestNetworkId != null) {
        final List<IPAddressVO> publicIps = _ipAddressDao.listByAssociatedNetwork(guestNetworkId, null);
        for (final IPAddressVO userIp : publicIps) {
            final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
            final URI broadcastUri = BroadcastDomainType.Vlan.toUri(publicIp.getVlanTag());
            final long ntwkId = publicIp.getNetworkId();
            final Nic nic = _nicDao.findByNetworkIdInstanceIdAndBroadcastUri(ntwkId, vm.getId(), broadcastUri.toString());
            if (nic == null && !addedURIs.contains(broadcastUri.toString())) {
                //Nic details are not available in DB
                //Create nic profile for migration
                s_logger.debug("Creating nic profile for migration. BroadcastUri: " + broadcastUri.toString() + " NetworkId: " + ntwkId + " Vm: " + vm.getId());
                final NetworkVO network = _networksDao.findById(ntwkId);
                _networkModel.getNetworkRate(network.getId(), vm.getId());
                final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
                final NicProfile profile = new NicProfile();
                //dummyId
                profile.setDeviceId(255);
                profile.setIPv4Address(userIp.getAddress().toString());
                profile.setIPv4Netmask(publicIp.getNetmask());
                profile.setIPv4Gateway(publicIp.getGateway());
                profile.setMacAddress(publicIp.getMacAddress());
                profile.setBroadcastType(network.getBroadcastDomainType());
                profile.setTrafficType(network.getTrafficType());
                profile.setBroadcastUri(broadcastUri);
                profile.setIsolationUri(Networks.IsolationType.Vlan.toUri(publicIp.getVlanTag()));
                profile.setSecurityGroupEnabled(_networkModel.isSecurityGroupSupportedInNetwork(network));
                profile.setName(_networkModel.getNetworkTag(vm.getHypervisorType(), network));
                profile.setNetworId(network.getId());
                guru.updateNicProfile(profile, network);
                vm.addNic(profile);
                addedURIs.add(broadcastUri.toString());
            }
        }
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkMigrationResponder(com.cloud.network.NetworkMigrationResponder) PublicIp(com.cloud.network.addr.PublicIp) NetworkGuru(com.cloud.network.guru.NetworkGuru) ArrayList(java.util.ArrayList) Nic(com.cloud.vm.Nic) NicProfile(com.cloud.vm.NicProfile) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) URI(java.net.URI) ReservationContext(com.cloud.vm.ReservationContext) 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) NetworkElement(com.cloud.network.element.NetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) NicVO(com.cloud.vm.NicVO)

Example 57 with Provider

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

the class NetworkOrchestrator method getResourceCount.

@Override
public int getResourceCount(Network network) {
    List<Provider> providers = getNetworkProviders(network.getId());
    int resourceCount = 0;
    for (NetworkElement element : networkElements) {
        if (providers.contains(element.getProvider())) {
            //currently only one element implements the redundant resource interface
            if (element instanceof RedundantResource) {
                resourceCount = ((RedundantResource) element).getResourceCount(network);
                break;
            }
        }
    }
    return resourceCount;
}
Also used : NetworkElement(com.cloud.network.element.NetworkElement) RedundantResource(com.cloud.network.element.RedundantResource) 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)

Example 58 with Provider

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

the class NetworkOrchestrator method canUpdateInSequence.

@Override
public boolean canUpdateInSequence(Network network, boolean forced) {
    List<Provider> providers = getNetworkProviders(network.getId());
    //check if the there are no service provider other than virtualrouter.
    for (Provider provider : providers) {
        if (provider != Provider.VirtualRouter)
            throw new UnsupportedOperationException("Cannot update the network resources in sequence when providers other than virtualrouter are used");
    }
    //check if routers are in correct state before proceeding with the update
    List<DomainRouterVO> routers = _rotuerDao.listByNetworkAndRole(network.getId(), VirtualRouter.Role.VIRTUAL_ROUTER);
    for (DomainRouterVO router : routers) {
        if (router.getRedundantState() == VirtualRouter.RedundantState.UNKNOWN) {
            if (!forced) {
                throw new CloudRuntimeException("Domain router: " + router.getInstanceName() + " is in unknown state, Cannot update network. set parameter forced to true for forcing an update");
            }
        }
    }
    return true;
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DomainRouterVO(com.cloud.vm.DomainRouterVO) 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)

Example 59 with Provider

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

the class NetworkOrchestrator method shutdownNetworkElementsAndResources.

@Override
public boolean shutdownNetworkElementsAndResources(final ReservationContext context, final boolean cleanupElements, final Network network) {
    // get providers to shutdown
    final List<Provider> providersToShutdown = getNetworkProviders(network.getId());
    // 1) Cleanup all the rules for the network. If it fails, just log the failure and proceed with shutting down
    // the elements
    boolean cleanupResult = true;
    boolean cleanupNeeded = false;
    try {
        for (final Provider provider : providersToShutdown) {
            if (provider.cleanupNeededOnShutdown()) {
                cleanupNeeded = true;
                break;
            }
        }
        if (cleanupNeeded) {
            cleanupResult = shutdownNetworkResources(network.getId(), context.getAccount(), context.getCaller().getId());
        }
    } catch (final Exception ex) {
        s_logger.warn("shutdownNetworkRules failed during the network " + network + " shutdown due to ", ex);
    } finally {
        // just warn the administrator that the network elements failed to shutdown
        if (!cleanupResult) {
            s_logger.warn("Failed to cleanup network id=" + network.getId() + " resources as a part of shutdownNetwork");
        }
    }
    // 2) Shutdown all the network elements
    boolean success = true;
    for (final NetworkElement element : networkElements) {
        if (providersToShutdown.contains(element.getProvider())) {
            try {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Sending network shutdown to " + element.getName());
                }
                if (!element.shutdown(network, context, cleanupElements)) {
                    s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName());
                    success = false;
                }
            } catch (final ResourceUnavailableException e) {
                s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName(), e);
                success = false;
            } catch (final ConcurrentOperationException e) {
                s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName(), e);
                success = false;
            } catch (final Exception e) {
                s_logger.warn("Unable to complete shutdown of the network elements due to element: " + element.getName(), e);
                success = false;
            }
        }
    }
    return success;
}
Also used : NetworkElement(com.cloud.network.element.NetworkElement) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) 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)

Example 60 with Provider

use of com.cloud.network.Network.Provider 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

Provider (com.cloud.network.Network.Provider)66 Service (com.cloud.network.Network.Service)35 HashSet (java.util.HashSet)31 HashMap (java.util.HashMap)28 Set (java.util.Set)27 StaticNatServiceProvider (com.cloud.network.element.StaticNatServiceProvider)25 UserDataServiceProvider (com.cloud.network.element.UserDataServiceProvider)25 NetworkElement (com.cloud.network.element.NetworkElement)22 ArrayList (java.util.ArrayList)19 LoadBalancingServiceProvider (com.cloud.network.element.LoadBalancingServiceProvider)18 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)18 Network (com.cloud.network.Network)17 DhcpServiceProvider (com.cloud.network.element.DhcpServiceProvider)15 DnsServiceProvider (com.cloud.network.element.DnsServiceProvider)15 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)12 NetworkOfferingVO (com.cloud.offerings.NetworkOfferingVO)12 Map (java.util.Map)12 ResourceLimitService (com.cloud.user.ResourceLimitService)11 NetworkOrchestrationService (org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService)11 NicProfile (com.cloud.vm.NicProfile)10