Search in sources :

Example 26 with Nic

use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method assignToLoadBalancer.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true)
public boolean assignToLoadBalancer(final long loadBalancerId, final List<Long> instanceIds, Map<Long, List<String>> vmIdIpMap) {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
        throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found.");
    }
    if (instanceIds == null && vmIdIpMap.isEmpty()) {
        throw new InvalidParameterValueException("Both instanceids and vmidipmap  can't be null");
    }
    // instanceIds and vmIdipmap is passed
    if (instanceIds != null && !vmIdIpMap.isEmpty()) {
        for (final long instanceId : instanceIds) {
            if (!vmIdIpMap.containsKey(instanceId)) {
                vmIdIpMap.put(instanceId, null);
            }
        }
    }
    // only instanceids list passed
    if (instanceIds != null && vmIdIpMap.isEmpty()) {
        vmIdIpMap = new HashMap<>();
        for (final long instanceId : instanceIds) {
            vmIdIpMap.put(instanceId, null);
        }
    }
    final List<LoadBalancerVMMapVO> mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
    final Set<Long> mappedInstanceIds = new HashSet<>();
    for (final LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
    }
    final Map<Long, List<String>> existingVmIdIps = new HashMap<>();
    // now get the ips of vm and add it to map
    for (final LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        List<String> ipsList = null;
        if (existingVmIdIps.containsKey(mappedInstance.getInstanceId())) {
            ipsList = existingVmIdIps.get(mappedInstance.getInstanceId());
        } else {
            ipsList = new ArrayList<>();
        }
        ipsList.add(mappedInstance.getInstanceIp());
        existingVmIdIps.put(mappedInstance.getInstanceId(), ipsList);
    }
    final List<UserVm> vmsToAdd = new ArrayList<>();
    // check for conflict
    final Set<Long> passedInstanceIds = vmIdIpMap.keySet();
    for (final Long instanceId : passedInstanceIds) {
        final UserVm vm = _vmDao.findById(instanceId);
        if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Invalid instance id specified");
            if (vm == null) {
                ex.addProxyObject(instanceId.toString(), "instanceId");
            } else {
                ex.addProxyObject(vm.getUuid(), "instanceId");
            }
            throw ex;
        }
        _rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller);
        if (vm.getAccountId() != loadBalancer.getAccountId()) {
            throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner.");
        }
        // Let's check to make sure the vm has a nic in the same network as
        // the load balancing rule.
        final List<? extends Nic> nics = _networkModel.getNics(vm.getId());
        Nic nicInSameNetwork = null;
        for (final Nic nic : nics) {
            if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
                nicInSameNetwork = nic;
                break;
            }
        }
        if (nicInSameNetwork == null) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("VM with id specified cannot be added because it doesn't belong in the same network.");
            ex.addProxyObject(vm.getUuid(), "instanceId");
            throw ex;
        }
        final String priIp = nicInSameNetwork.getIPv4Address();
        if (existingVmIdIps.containsKey(instanceId)) {
            // now check for ip address
            final List<String> mappedIps = existingVmIdIps.get(instanceId);
            List<String> newIps = vmIdIpMap.get(instanceId);
            if (newIps == null) {
                newIps = new ArrayList<>();
                newIps.add(priIp);
            }
            for (final String newIp : newIps) {
                if (mappedIps.contains(newIp)) {
                    throw new InvalidParameterValueException("VM " + instanceId + " with " + newIp + " is already mapped to load balancer.");
                }
            }
        }
        List<String> vmIpsList = vmIdIpMap.get(instanceId);
        final String vmLbIp = null;
        if (vmIpsList != null) {
            // check if the ips belongs to nic secondary ip
            for (final String ip : vmIpsList) {
                // skip the primary ip from vm secondary ip comparisions
                if (ip.equals(priIp)) {
                    continue;
                }
                if (_nicSecondaryIpDao.findByIp4AddressAndNicId(ip, nicInSameNetwork.getId()) == null) {
                    throw new InvalidParameterValueException("VM ip " + ip + " specified does not belong to " + "nic in network " + nicInSameNetwork.getNetworkId());
                }
            }
        } else {
            vmIpsList = new ArrayList<>();
            vmIpsList.add(priIp);
        }
        // assign for primary ip and ip passed in vmidipmap
        if (instanceIds != null) {
            if (instanceIds.contains(instanceId)) {
                vmIpsList.add(priIp);
            }
        }
        vmIdIpMap.put(instanceId, vmIpsList);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding " + vm + " to the load balancer pool");
        }
        vmsToAdd.add(vm);
    }
    final Set<Long> vmIds = vmIdIpMap.keySet();
    final Map<Long, List<String>> newMap = vmIdIpMap;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            for (final Long vmId : vmIds) {
                final Set<String> lbVmIps = new HashSet<>(newMap.get(vmId));
                for (final String vmIp : lbVmIps) {
                    LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vmId, vmIp, false);
                    map = _lb2VmMapDao.persist(map);
                }
            }
        }
    });
    boolean success = false;
    final FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        applyLoadBalancerConfig(loadBalancerId);
        success = true;
    } catch (final ResourceUnavailableException e) {
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
        success = false;
    } finally {
        if (!success) {
            final List<Long> vmInstanceIds = new ArrayList<>();
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    for (final Long vmId : vmIds) {
                        vmInstanceIds.add(vmId);
                    }
                }
            });
            if (!vmInstanceIds.isEmpty()) {
                _lb2VmMapDao.remove(loadBalancer.getId(), vmInstanceIds, null);
                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while attaching VM: " + vmInstanceIds);
            }
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            final CloudRuntimeException ex = new CloudRuntimeException("Failed to add specified loadbalancerruleid for vms " + vmInstanceIds);
            ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
            // right VO object or table name.
            throw ex;
        }
    }
    return success;
}
Also used : Account(com.cloud.legacymodel.user.Account) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) List(java.util.List) FirewallRule(com.cloud.legacymodel.network.FirewallRule) HashSet(java.util.HashSet) Nic(com.cloud.legacymodel.network.Nic) CallContext(com.cloud.context.CallContext) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 27 with Nic

use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.

the class DirectNetworkGuru method trash.

@Override
@DB
public boolean trash(final Network network, final NetworkOffering offering) {
    // Have to remove all placeholder nics
    try {
        final long id = network.getId();
        final List<NicVO> nics = _nicDao.listPlaceholderNicsByNetworkId(id);
        if (nics != null) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    for (final Nic nic : nics) {
                        if (nic.getIPv4Address() != null) {
                            s_logger.debug("Releasing ip " + nic.getIPv4Address() + " of placeholder nic " + nic);
                            final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIPv4Address());
                            if (ip != null) {
                                _ipAddrMgr.markIpAsUnavailable(ip.getId());
                                _ipAddressDao.unassignIpAddress(ip.getId());
                                s_logger.debug("Removing placeholder nic " + nic);
                                _nicDao.remove(nic.getId());
                            }
                        }
                    }
                }
            });
        }
        return true;
    } catch (final Exception e) {
        s_logger.error("trash. Exception:" + e.getMessage());
        throw new CloudRuntimeException("trash. Exception:" + e.getMessage(), e);
    }
}
Also used : CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) Nic(com.cloud.legacymodel.network.Nic) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) IPAddressVO(com.cloud.network.dao.IPAddressVO) NicVO(com.cloud.vm.NicVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.legacymodel.exceptions.InsufficientVirtualNetworkCapacityException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) DB(com.cloud.utils.db.DB)

Example 28 with Nic

use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.

the class VirtualNetworkApplianceManagerImpl method prepareStop.

@Override
public void prepareStop(final VirtualMachineProfile profile) {
    // Collect network usage before stopping Vm
    final DomainRouterVO router = _routerDao.findById(profile.getVirtualMachine().getId());
    if (router == null) {
        return;
    }
    final String privateIP = router.getPrivateIpAddress();
    if (privateIP != null) {
        final boolean forVpc = router.getVpcId() != null;
        final List<? extends Nic> routerNics = _nicDao.listByVmId(router.getId());
        for (final Nic routerNic : routerNics) {
            final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
            // VR
            if (network == null) {
                s_logger.error("Could not find a network with ID => " + routerNic.getNetworkId() + ".");
                continue;
            }
            if (forVpc && network.getTrafficType() == TrafficType.Public || !forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == GuestType.Isolated) {
                final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(), forVpc, routerNic.getIPv4Address());
                final String routerType = router.getType().toString();
                final UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(), router.getDataCenterId(), network.getId(), forVpc ? routerNic.getIPv4Address() : null, router.getId(), routerType);
                NetworkUsageAnswer answer = null;
                try {
                    answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd);
                } catch (final Exception e) {
                    s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId(), e);
                    continue;
                }
                if (answer != null) {
                    if (!answer.getResult()) {
                        s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails());
                        continue;
                    }
                    try {
                        if (answer.getBytesReceived() == 0 && answer.getBytesSent() == 0) {
                            s_logger.debug("Recieved and Sent bytes are both 0. Not updating user_statistics");
                            continue;
                        }
                        final NetworkUsageAnswer answerFinal = answer;
                        Transaction.execute(new TransactionCallbackNoReturn() {

                            @Override
                            public void doInTransactionWithoutResult(final TransactionStatus status) {
                                final UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(), router.getDataCenterId(), network.getId(), forVpc ? routerNic.getIPv4Address() : null, router.getId(), routerType);
                                if (stats == null) {
                                    s_logger.warn("unable to find stats for account: " + router.getAccountId());
                                    return;
                                }
                                if (previousStats != null && (previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived() || previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent())) {
                                    s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " + "Ignoring current answer. Router: " + answerFinal.getRouterName() + " Rcvd: " + answerFinal.getBytesReceived() + "Sent: " + answerFinal.getBytesSent());
                                    return;
                                }
                                if (stats.getCurrentBytesReceived() > answerFinal.getBytesReceived()) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("Received # of bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Router: " + answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesReceived() + " Stored: " + stats.getCurrentBytesReceived());
                                    }
                                    stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
                                }
                                stats.setCurrentBytesReceived(answerFinal.getBytesReceived());
                                if (stats.getCurrentBytesSent() > answerFinal.getBytesSent()) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("Received # of bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Router: " + answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesSent() + " Stored: " + stats.getCurrentBytesSent());
                                    }
                                    stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
                                }
                                stats.setCurrentBytesSent(answerFinal.getBytesSent());
                                if (!_dailyOrHourly) {
                                    // update agg bytes
                                    stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
                                    stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
                                }
                                _userStatsDao.update(stats.getId(), stats);
                            }
                        });
                    } catch (final Exception e) {
                        s_logger.warn("Unable to update user statistics for account: " + router.getAccountId() + " Rx: " + answer.getBytesReceived() + "; Tx: " + answer.getBytesSent());
                    }
                }
            }
        }
    }
}
Also used : Nic(com.cloud.legacymodel.network.Nic) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkUsageCommand(com.cloud.legacymodel.communication.command.NetworkUsageCommand) ConnectionException(com.cloud.legacymodel.exceptions.ConnectionException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) NetworkUsageAnswer(com.cloud.legacymodel.communication.answer.NetworkUsageAnswer) DomainRouterVO(com.cloud.vm.DomainRouterVO) UserStatisticsVO(com.cloud.user.UserStatisticsVO)

Example 29 with Nic

use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.

the class RulesManagerImpl method createStaticNatForIp.

protected List<StaticNat> createStaticNatForIp(final IpAddress sourceIp, final Account caller, final boolean forRevoke) {
    final List<StaticNat> staticNats = new ArrayList<>();
    if (!sourceIp.isOneToOneNat()) {
        s_logger.debug("Source ip id=" + sourceIp + " is not one to one nat");
        return staticNats;
    }
    final Long networkId = sourceIp.getAssociatedWithNetworkId();
    if (networkId == null) {
        throw new CloudRuntimeException("Ip address is not associated with any network");
    }
    final VMInstanceVO vm = _vmInstanceDao.findByIdIncludingRemoved(sourceIp.getAssociatedWithVmId());
    final Network network = _networkModel.getNetwork(networkId);
    if (network == null) {
        final CloudRuntimeException ex = new CloudRuntimeException("Unable to find an ip address to map to specified vm id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (caller != null) {
        _accountMgr.checkAccess(caller, null, true, sourceIp);
    }
    // create new static nat rule
    // Get nic IP4 address
    final Nic guestNic = _networkModel.getNicInNetworkIncludingRemoved(vm.getId(), networkId);
    if (guestNic == null) {
        throw new InvalidParameterValueException("Vm doesn't belong to the network with specified id");
    }
    final String dstIp;
    dstIp = sourceIp.getVmIp();
    if (dstIp == null) {
        throw new InvalidParameterValueException("Vm ip is not set as dnat ip for this public ip");
    }
    String srcMac = null;
    try {
        srcMac = _networkModel.getNextAvailableMacAddressInNetwork(networkId);
    } catch (final InsufficientAddressCapacityException e) {
        throw new CloudRuntimeException("Insufficient MAC address for static NAT instantiation.");
    }
    final StaticNatImpl staticNat = new StaticNatImpl(sourceIp.getAllocatedToAccountId(), sourceIp.getAllocatedInDomainId(), networkId, sourceIp.getId(), dstIp, srcMac, forRevoke);
    staticNats.add(staticNat);
    return staticNats;
}
Also used : InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) ArrayList(java.util.ArrayList) VMInstanceVO(com.cloud.vm.VMInstanceVO) Nic(com.cloud.legacymodel.network.Nic)

Example 30 with Nic

use of com.cloud.legacymodel.network.Nic in project cosmic by MissionCriticalCloud.

the class VpcVirtualNetworkApplianceManagerImpl method finalizeCommandsOnStart.

@Override
public boolean finalizeCommandsOnStart(final Commands cmds, final VirtualMachineProfile profile) {
    final DomainRouterVO domainRouterVO = _routerDao.findById(profile.getId());
    final boolean isVpc = domainRouterVO.getVpcId() != null;
    if (!isVpc) {
        return super.finalizeCommandsOnStart(cmds, profile);
    }
    if (domainRouterVO.getState() == State.Starting || domainRouterVO.getState() == State.Running) {
        final List<Nic> nicsToExclude = new ArrayList<>();
        final List<Ip> ipsToExclude = new ArrayList<>();
        final List<StaticRouteProfile> staticRoutesToExclude = new ArrayList<>();
        // 1) FORM SSH CHECK COMMAND
        final NicProfile controlNic = getControlNic(profile);
        if (controlNic == null) {
            s_logger.error("Control network doesn't exist for the router " + domainRouterVO);
            return false;
        }
        finalizeSshAndVersionAndNetworkUsageOnStart(cmds, profile, domainRouterVO, controlNic);
        // 2) FORM PLUG NIC COMMANDS
        final List<Pair<Nic, Network>> syncNics = new ArrayList<>();
        final List<Pair<Nic, Network>> guestNics = new ArrayList<>();
        final List<Pair<Nic, Network>> publicNics = new ArrayList<>();
        final List<? extends Nic> routerNics = _nicDao.listByVmId(profile.getId());
        for (final Nic routerNic : routerNics) {
            final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
            if (network.getTrafficType() == TrafficType.Guest) {
                final Pair<Nic, Network> guestNic = new Pair<>(routerNic, network);
                if (GuestType.Sync.equals(network.getGuestType())) {
                    syncNics.add(guestNic);
                } else {
                    guestNics.add(guestNic);
                }
            } else if (network.getTrafficType() == TrafficType.Public) {
                final Pair<Nic, Network> publicNic = new Pair<>(routerNic, network);
                publicNics.add(publicNic);
            }
        }
        final List<Command> usageCmds = new ArrayList<>();
        // 3) PREPARE PLUG NIC COMMANDS
        try {
            // add VPC router to sync networks
            for (final Pair<Nic, Network> nicNtwk : syncNics) {
                final Nic syncNic = nicNtwk.first();
                // plug sync nic
                final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, syncNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType());
                cmds.addCommand(plugNicCmd);
            }
            // add VPC router to public networks
            final List<PublicIp> sourceNat = new ArrayList<>(1);
            for (final Pair<Nic, Network> nicNtwk : publicNics) {
                final Nic publicNic = nicNtwk.first();
                final Network publicNtwk = nicNtwk.second();
                final IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(publicNtwk.getId(), publicNic.getIPv4Address());
                if (userIp.isSourceNat()) {
                    final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
                    sourceNat.add(publicIp);
                    if (domainRouterVO.getPublicIpAddress() == null) {
                        final DomainRouterVO routerVO = _routerDao.findById(domainRouterVO.getId());
                        routerVO.setPublicIpAddress(publicNic.getIPv4Address());
                        routerVO.setPublicNetmask(publicNic.getIPv4Netmask());
                        routerVO.setPublicMacAddress(publicNic.getMacAddress());
                        _routerDao.update(routerVO.getId(), routerVO);
                    }
                }
                final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, publicNic.getNetworkId(), publicNic.getBroadcastUri().toString()), domainRouterVO.getInstanceName(), domainRouterVO.getType());
                cmds.addCommand(plugNicCmd);
                final VpcVO vpc = _vpcDao.findById(domainRouterVO.getVpcId());
                final NetworkUsageCommand netUsageCmd = new NetworkUsageCommand(domainRouterVO.getPrivateIpAddress(), domainRouterVO.getInstanceName(), true, publicNic.getIPv4Address(), vpc.getCidr());
                usageCmds.add(netUsageCmd);
                UserStatisticsVO stats = _userStatsDao.findBy(domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNtwk.getId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString());
                if (stats == null) {
                    stats = new UserStatisticsVO(domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString(), publicNtwk.getId());
                    _userStatsDao.persist(stats);
                }
                _commandSetupHelper.createPublicIpACLsCommands(domainRouterVO, cmds);
            }
            // create ip assoc for source nat
            if (!sourceNat.isEmpty()) {
                _commandSetupHelper.findIpsToExclude(sourceNat, ipsToExclude);
            }
            // add VPC router to guest networks
            for (final Pair<Nic, Network> nicNtwk : guestNics) {
                final Nic guestNic = nicNtwk.first();
                // plug guest nic
                final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, guestNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType());
                cmds.addCommand(plugNicCmd);
                if (_networkModel.isPrivateGateway(guestNic.getNetworkId())) {
                    // set private network
                    final PrivateIpVO ipVO = _privateIpDao.findByIpAndSourceNetworkId(guestNic.getNetworkId(), guestNic.getIPv4Address());
                    final Long privateGwAclId = _vpcGatewayDao.getNetworkAclIdForPrivateIp(ipVO.getVpcId(), ipVO.getNetworkId(), ipVO.getIpAddress());
                    if (privateGwAclId != null) {
                        // set network acl on private gateway
                        final List<NetworkACLItemVO> networkACLs = _networkACLItemDao.listByACL(privateGwAclId);
                        s_logger.debug("Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + domainRouterVO + " start for private gateway ip = " + ipVO.getIpAddress());
                        _commandSetupHelper.createNetworkACLsCommands(networkACLs, domainRouterVO, cmds, ipVO.getNetworkId(), true);
                    }
                }
            }
        } catch (final Exception ex) {
            s_logger.warn("Failed to add router " + domainRouterVO + " to network due to exception ", ex);
            return false;
        }
        // 4) REPROGRAM GUEST NETWORK
        boolean reprogramGuestNtwks = profile.getParameter(Param.ReProgramGuestNetworks) == null || (Boolean) profile.getParameter(Param.ReProgramGuestNetworks);
        final VirtualRouterProvider vrProvider = _vrProviderDao.findById(domainRouterVO.getElementId());
        if (vrProvider == null) {
            throw new CloudRuntimeException("Cannot find related virtual router provider of router: " + domainRouterVO.getHostName());
        }
        final Provider provider = Provider.getProvider(vrProvider.getType().toString());
        if (provider == null) {
            throw new CloudRuntimeException("Cannot find related provider of virtual router provider: " + vrProvider.getType().toString());
        }
        boolean isDhcpSupported = false;
        for (final Pair<Nic, Network> nicNtwk : guestNics) {
            final Nic guestNic = nicNtwk.first();
            final AggregationControlCommand startCmd = new AggregationControlCommand(Action.Start, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNic.getNetworkId(), domainRouterVO.getId()));
            cmds.addCommand(startCmd);
            if (reprogramGuestNtwks) {
                finalizeIpAssocForNetwork(domainRouterVO, provider, guestNic.getNetworkId(), ipsToExclude);
                finalizeNetworkRulesForNetwork(cmds, domainRouterVO, provider, guestNic.getNetworkId());
            }
            isDhcpSupported = isDhcpSupported || _networkModel.isProviderSupportServiceInNetwork(guestNic.getNetworkId(), Service.Dhcp, provider);
            final AggregationControlCommand finishCmd = new AggregationControlCommand(Action.Finish, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNic.getNetworkId(), domainRouterVO.getId()));
            cmds.addCommand(finishCmd);
        }
        final NetworkOverviewTO networkOverview = _commandSetupHelper.createNetworkOverviewFromRouter(domainRouterVO, nicsToExclude, ipsToExclude, staticRoutesToExclude, null, null, null);
        final UpdateNetworkOverviewCommand updateNetworkOverviewCommand = _commandSetupHelper.createUpdateNetworkOverviewCommand(domainRouterVO, networkOverview);
        updateNetworkOverviewCommand.setPlugNics(true);
        cmds.addCommand(updateNetworkOverviewCommand);
        if (isDhcpSupported) {
            final VMOverviewTO vmOverview = _commandSetupHelper.createVmOverviewFromRouter(domainRouterVO);
            final UpdateVmOverviewCommand updateVmOverviewCommand = _commandSetupHelper.createUpdateVmOverviewCommand(domainRouterVO, vmOverview);
            cmds.addCommand(updateVmOverviewCommand);
        }
        // 5) RE-APPLY VR Configuration
        final Vpc vpc = _vpcDao.findById(domainRouterVO.getVpcId());
        _commandSetupHelper.createVRConfigCommands(vpc, domainRouterVO, cmds);
        // Add network usage commands
        cmds.addCommands(usageCmds);
    }
    return true;
}
Also used : Ip(com.cloud.legacymodel.network.Ip) PublicIp(com.cloud.network.addr.PublicIp) ArrayList(java.util.ArrayList) Vpc(com.cloud.legacymodel.network.vpc.Vpc) PrivateIpVO(com.cloud.network.vpc.PrivateIpVO) NetworkACLItemVO(com.cloud.network.vpc.NetworkACLItemVO) StaticRouteProfile(com.cloud.legacymodel.network.vpc.StaticRouteProfile) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) AggregationControlCommand(com.cloud.legacymodel.communication.command.AggregationControlCommand) VMOverviewTO(com.cloud.legacymodel.to.VMOverviewTO) NetworkOverviewTO(com.cloud.legacymodel.to.NetworkOverviewTO) PlugNicCommand(com.cloud.legacymodel.communication.command.PlugNicCommand) Pair(com.cloud.legacymodel.utils.Pair) PublicIp(com.cloud.network.addr.PublicIp) Nic(com.cloud.legacymodel.network.Nic) NetworkUsageCommand(com.cloud.legacymodel.communication.command.NetworkUsageCommand) UpdateNetworkOverviewCommand(com.cloud.legacymodel.communication.command.UpdateNetworkOverviewCommand) NicProfile(com.cloud.vm.NicProfile) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Provider(com.cloud.legacymodel.network.Network.Provider) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) VpcVO(com.cloud.network.vpc.VpcVO) PlugNicCommand(com.cloud.legacymodel.communication.command.PlugNicCommand) Command(com.cloud.legacymodel.communication.command.Command) NetworkUsageCommand(com.cloud.legacymodel.communication.command.NetworkUsageCommand) AggregationControlCommand(com.cloud.legacymodel.communication.command.AggregationControlCommand) UpdateVmOverviewCommand(com.cloud.legacymodel.communication.command.UpdateVmOverviewCommand) UpdateNetworkOverviewCommand(com.cloud.legacymodel.communication.command.UpdateNetworkOverviewCommand) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) IPAddressVO(com.cloud.network.dao.IPAddressVO) DomainRouterVO(com.cloud.vm.DomainRouterVO) UserStatisticsVO(com.cloud.user.UserStatisticsVO) UpdateVmOverviewCommand(com.cloud.legacymodel.communication.command.UpdateVmOverviewCommand)

Aggregations

Nic (com.cloud.legacymodel.network.Nic)37 Network (com.cloud.legacymodel.network.Network)19 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)17 ArrayList (java.util.ArrayList)13 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)11 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)11 NicProfile (com.cloud.vm.NicProfile)8 IPAddressVO (com.cloud.network.dao.IPAddressVO)7 DB (com.cloud.utils.db.DB)7 Zone (com.cloud.db.model.Zone)5 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)5 InsufficientAddressCapacityException (com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException)5 Ip (com.cloud.legacymodel.network.Ip)5 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)5 UserVm (com.cloud.uservm.UserVm)5 DomainRouterVO (com.cloud.vm.DomainRouterVO)5 CallContext (com.cloud.context.CallContext)4 IpAddress (com.cloud.network.IpAddress)4 PublicIp (com.cloud.network.addr.PublicIp)4 NetworkVO (com.cloud.network.dao.NetworkVO)4