Search in sources :

Example 11 with NetworkGuru

use of com.cloud.network.guru.NetworkGuru in project cloudstack by apache.

the class NetworkOrchestrator method setupNetwork.

@Override
@DB
public List<? extends Network> setupNetwork(final Account owner, final NetworkOffering offering, final Network predefined, final DeploymentPlan plan, final String name, final String displayText, final boolean errorIfAlreadySetup, final Long domainId, final ACLType aclType, final Boolean subdomainAccess, final Long vpcId, final Boolean isDisplayNetworkEnabled) throws ConcurrentOperationException {
    final Account locked = _accountDao.acquireInLockTable(owner.getId());
    if (locked == null) {
        throw new ConcurrentOperationException("Unable to acquire lock on " + owner);
    }
    try {
        if (predefined == null || offering.getTrafficType() != TrafficType.Guest && predefined.getCidr() == null && predefined.getBroadcastUri() == null && !(predefined.getBroadcastDomainType() == BroadcastDomainType.Vlan || predefined.getBroadcastDomainType() == BroadcastDomainType.Lswitch || predefined.getBroadcastDomainType() == BroadcastDomainType.Vxlan)) {
            final List<NetworkVO> configs = _networksDao.listBy(owner.getId(), offering.getId(), plan.getDataCenterId());
            if (configs.size() > 0) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Found existing network configuration for offering " + offering + ": " + configs.get(0));
                }
                if (errorIfAlreadySetup) {
                    final InvalidParameterValueException ex = new InvalidParameterValueException("Found existing network configuration (with specified id) for offering (with specified id)");
                    ex.addProxyObject(offering.getUuid(), "offeringId");
                    ex.addProxyObject(configs.get(0).getUuid(), "networkConfigId");
                    throw ex;
                } else {
                    return configs;
                }
            }
        }
        final List<NetworkVO> networks = new ArrayList<NetworkVO>();
        long related = -1;
        for (final NetworkGuru guru : networkGurus) {
            final Network network = guru.design(offering, plan, predefined, owner);
            if (network == null) {
                continue;
            }
            if (network.getId() != -1) {
                if (network instanceof NetworkVO) {
                    networks.add((NetworkVO) network);
                } else {
                    networks.add(_networksDao.findById(network.getId()));
                }
                continue;
            }
            final long id = _networksDao.getNextInSequence(Long.class, "id");
            if (related == -1) {
                related = id;
            }
            final long relatedFile = related;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    final NetworkVO vo = new NetworkVO(id, network, offering.getId(), guru.getName(), owner.getDomainId(), owner.getId(), relatedFile, name, displayText, predefined.getNetworkDomain(), offering.getGuestType(), plan.getDataCenterId(), plan.getPhysicalNetworkId(), aclType, offering.getSpecifyIpRanges(), vpcId, offering.getRedundantRouter());
                    vo.setDisplayNetwork(isDisplayNetworkEnabled == null ? true : isDisplayNetworkEnabled);
                    vo.setStrechedL2Network(offering.getSupportsStrechedL2());
                    final NetworkVO networkPersisted = _networksDao.persist(vo, vo.getGuestType() == Network.GuestType.Isolated, finalizeServicesAndProvidersForNetwork(offering, plan.getPhysicalNetworkId()));
                    networks.add(networkPersisted);
                    if (predefined instanceof NetworkVO && guru instanceof NetworkGuruAdditionalFunctions) {
                        final NetworkGuruAdditionalFunctions functions = (NetworkGuruAdditionalFunctions) guru;
                        functions.finalizeNetworkDesign(networkPersisted.getId(), ((NetworkVO) predefined).getVlanIdAsUUID());
                    }
                    if (domainId != null && aclType == ACLType.Domain) {
                        _networksDao.addDomainToNetwork(id, domainId, subdomainAccess == null ? true : subdomainAccess);
                    }
                }
            });
        }
        if (networks.size() < 1) {
            // see networkOfferingVO.java
            final CloudRuntimeException ex = new CloudRuntimeException("Unable to convert network offering with specified id to network profile");
            ex.addProxyObject(offering.getUuid(), "offeringId");
            throw ex;
        }
        return networks;
    } finally {
        s_logger.debug("Releasing lock for " + locked);
        _accountDao.releaseFromLockTable(locked.getId());
    }
}
Also used : Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkGuru(com.cloud.network.guru.NetworkGuru) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) NetworkGuruAdditionalFunctions(com.cloud.network.guru.NetworkGuruAdditionalFunctions) DB(com.cloud.utils.db.DB)

Example 12 with NetworkGuru

use of com.cloud.network.guru.NetworkGuru in project cloudstack by apache.

the class NetworkOrchestrator method getNicProfiles.

@Override
public List<NicProfile> getNicProfiles(final VirtualMachine vm) {
    final List<NicVO> nics = _nicDao.listByVmId(vm.getId());
    final List<NicProfile> profiles = new ArrayList<NicProfile>();
    if (nics != null) {
        for (final Nic nic : nics) {
            final NetworkVO network = _networksDao.findById(nic.getNetworkId());
            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));
            guru.updateNicProfile(profile, network);
            profiles.add(profile);
        }
    }
    return profiles;
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkGuru(com.cloud.network.guru.NetworkGuru) ArrayList(java.util.ArrayList) Nic(com.cloud.vm.Nic) NicProfile(com.cloud.vm.NicProfile) NicVO(com.cloud.vm.NicVO)

Example 13 with NetworkGuru

use of com.cloud.network.guru.NetworkGuru in project cloudstack by apache.

the class NetworkOrchestrator method createNicForVm.

@Override
public NicProfile createNicForVm(final Network network, final NicProfile requested, final ReservationContext context, final VirtualMachineProfile vmProfile, final boolean prepare) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
    final VirtualMachine vm = vmProfile.getVirtualMachine();
    final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
    final Host host = _hostDao.findById(vm.getHostId());
    final DeployDestination dest = new DeployDestination(dc, null, null, host);
    NicProfile nic = getNicProfileForVm(network, requested, vm);
    //1) allocate nic (if needed) Always allocate if it is a user vm
    if (nic == null || vmProfile.getType() == VirtualMachine.Type.User) {
        final int deviceId = _nicDao.getFreeDeviceId(vm.getId());
        nic = allocateNic(requested, network, false, deviceId, vmProfile).first();
        if (nic == null) {
            throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
        }
        //Update vm_network_map table
        if (vmProfile.getType() == VirtualMachine.Type.User) {
            final VMNetworkMapVO vno = new VMNetworkMapVO(vm.getId(), network.getId());
            _vmNetworkMapDao.persist(vno);
        }
        s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network);
    }
    //2) prepare nic
    if (prepare) {
        final Pair<NetworkGuru, NetworkVO> implemented = implementNetwork(nic.getNetworkId(), dest, context, vmProfile.getVirtualMachine().getType() == Type.DomainRouter);
        if (implemented == null || implemented.first() == null) {
            s_logger.warn("Failed to implement network id=" + nic.getNetworkId() + " as a part of preparing nic id=" + nic.getId());
            throw new CloudRuntimeException("Failed to implement network id=" + nic.getNetworkId() + " as a part preparing nic id=" + nic.getId());
        }
        nic = prepareNic(vmProfile, dest, context, nic.getId(), implemented.second());
        s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
    }
    return nic;
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) DataCenter(com.cloud.dc.DataCenter) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkGuru(com.cloud.network.guru.NetworkGuru) VMNetworkMapVO(org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO) Host(com.cloud.host.Host) NicProfile(com.cloud.vm.NicProfile) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 14 with NetworkGuru

use of com.cloud.network.guru.NetworkGuru in project cloudstack by apache.

the class NetworkOrchestrator method prepare.

@Override
public void prepare(final VirtualMachineProfile vmProfile, final DeployDestination dest, final ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
    final List<NicVO> nics = _nicDao.listByVmId(vmProfile.getId());
    // we have to implement default nics first - to ensure that default network elements start up first in multiple
    //nics case
    // (need for setting DNS on Dhcp to domR's Ip4 address)
    Collections.sort(nics, new Comparator<NicVO>() {

        @Override
        public int compare(final NicVO nic1, final NicVO nic2) {
            final boolean isDefault1 = nic1.isDefaultNic();
            final boolean isDefault2 = nic2.isDefaultNic();
            return isDefault1 ^ isDefault2 ? isDefault1 ^ true ? 1 : -1 : 0;
        }
    });
    for (final NicVO nic : nics) {
        final Pair<NetworkGuru, NetworkVO> implemented = implementNetwork(nic.getNetworkId(), dest, context, vmProfile.getVirtualMachine().getType() == Type.DomainRouter);
        if (implemented == null || implemented.first() == null) {
            s_logger.warn("Failed to implement network id=" + nic.getNetworkId() + " as a part of preparing nic id=" + nic.getId());
            throw new CloudRuntimeException("Failed to implement network id=" + nic.getNetworkId() + " as a part preparing nic id=" + nic.getId());
        }
        final NetworkVO network = implemented.second();
        final NicProfile profile = prepareNic(vmProfile, dest, context, nic.getId(), network);
        vmProfile.addNic(profile);
    }
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkGuru(com.cloud.network.guru.NetworkGuru) NicProfile(com.cloud.vm.NicProfile) NicVO(com.cloud.vm.NicVO)

Example 15 with NetworkGuru

use of com.cloud.network.guru.NetworkGuru 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

NetworkGuru (com.cloud.network.guru.NetworkGuru)22 NetworkVO (com.cloud.network.dao.NetworkVO)19 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)18 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)12 NicProfile (com.cloud.vm.NicProfile)11 DhcpServiceProvider (com.cloud.network.element.DhcpServiceProvider)9 NicVO (com.cloud.vm.NicVO)9 Provider (com.cloud.network.Network.Provider)8 DnsServiceProvider (com.cloud.network.element.DnsServiceProvider)8 LoadBalancingServiceProvider (com.cloud.network.element.LoadBalancingServiceProvider)8 NetworkElement (com.cloud.network.element.NetworkElement)8 StaticNatServiceProvider (com.cloud.network.element.StaticNatServiceProvider)8 UserDataServiceProvider (com.cloud.network.element.UserDataServiceProvider)8 DB (com.cloud.utils.db.DB)7 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)6 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)6 Pair (com.cloud.utils.Pair)6 ArrayList (java.util.ArrayList)6 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)5 Network (com.cloud.network.Network)5