Search in sources :

Example 71 with Network

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

the class LoadBalancingRulesManagerImpl method isLbServiceSupportedInNetwork.

@Override
public void isLbServiceSupportedInNetwork(final long networkId, final Scheme scheme) {
    final Network network = _networkDao.findById(networkId);
    // 1) Check if the LB service is supported
    if (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Lb)) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("LB service is not supported in specified network id");
        ex.addProxyObject(network.getUuid(), "networkId");
        throw ex;
    }
    // 2) Check if the Scheme is supported
    final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
    if (scheme == Scheme.Public) {
        if (!off.getPublicLb()) {
            throw new InvalidParameterValueException("Scheme " + scheme + " is not supported by the network offering " + off);
        }
    }
    // 3) Check if the provider supports the scheme
    final LoadBalancingServiceProvider lbProvider = _networkMgr.getLoadBalancingProviderForNetwork(network, scheme);
    if (lbProvider == null) {
        throw new InvalidParameterValueException("Lb rule with scheme " + scheme.toString() + " is not supported by lb providers in network " + network);
    }
}
Also used : InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NetworkOffering(com.cloud.offering.NetworkOffering) Network(com.cloud.legacymodel.network.Network) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider)

Example 72 with Network

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

the class LoadBalancingRulesManagerImpl method createPublicLoadBalancerRule.

@Override
@ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer")
public LoadBalancer createPublicLoadBalancerRule(final String xId, final String name, final String description, final int srcPortStart, final int srcPortEnd, final int defPortStart, final int defPortEnd, final Long ipAddrId, final String protocol, final String algorithm, final long networkId, final long lbOwnerId, final boolean openFirewall, final String lbProtocol, final Boolean forDisplay, Integer clientTimeout, Integer serverTimeout) throws NetworkRuleConflictException, InsufficientAddressCapacityException {
    final Account lbOwner = _accountMgr.getAccount(lbOwnerId);
    if (srcPortStart != srcPortEnd) {
        throw new InvalidParameterValueException("Port ranges are not supported by the load balancer");
    }
    IPAddressVO ipVO = null;
    if (ipAddrId != null) {
        ipVO = _ipAddressDao.findById(ipAddrId);
    }
    final Network network = _networkModel.getNetwork(networkId);
    LoadBalancer result = null;
    if (result == null) {
        IpAddress systemIp = null;
        final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
        if (off.getElasticLb() && ipVO == null && network.getVpcId() == null) {
            systemIp = _ipAddrMgr.assignSystemIp(networkId, lbOwner, true, false);
            if (systemIp != null) {
                ipVO = _ipAddressDao.findById(systemIp.getId());
            }
        }
        // Validate ip address
        if (ipVO == null) {
            throw new InvalidParameterValueException("Unable to create load balance rule; can't find/allocate source IP");
        } else if (ipVO.isOneToOneNat()) {
            throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipVO.getAddress());
        }
        boolean performedIpAssoc = false;
        try {
            if (ipVO.getAssociatedWithNetworkId() == null) {
                final boolean assignToVpcNtwk = network.getVpcId() != null && ipVO.getVpcId() != null && ipVO.getVpcId().longValue() == network.getVpcId();
                if (assignToVpcNtwk) {
                    // set networkId just for verification purposes
                    _networkModel.checkIpForService(ipVO, Service.Lb, networkId);
                    s_logger.debug("The ip is not associated with the VPC network id=" + networkId + " so assigning");
                    ipVO = _ipAddrMgr.associateIPToGuestNetwork(ipAddrId, networkId, false);
                    performedIpAssoc = true;
                }
            } else {
                _networkModel.checkIpForService(ipVO, Service.Lb, null);
            }
            if (ipVO.getAssociatedWithNetworkId() == null) {
                throw new InvalidParameterValueException("Ip address " + ipVO + " is not assigned to the network " + network);
            }
            // Load default values and fallback to hardcoded if not available
            final Integer defaultClientTimeout = NumbersUtil.parseInt(_configDao.getValue(Config.DefaultLoadBalancerClientTimeout.key()), 60000);
            final Integer defaultServerTimeout = NumbersUtil.parseInt(_configDao.getValue(Config.DefaultLoadBalancerServerTimeout.key()), 60000);
            // set timeouts, use defaults if not available
            if (clientTimeout != null) {
                clientTimeout = NumbersUtil.parseInt(clientTimeout.toString(), defaultClientTimeout);
            } else {
                clientTimeout = defaultClientTimeout;
            }
            if (serverTimeout != null) {
                serverTimeout = NumbersUtil.parseInt(serverTimeout.toString(), defaultServerTimeout);
            } else {
                serverTimeout = defaultServerTimeout;
            }
            result = createPublicLoadBalancer(xId, name, description, srcPortStart, defPortStart, ipVO.getId(), protocol, algorithm, openFirewall, CallContext.current(), lbProtocol, forDisplay, clientTimeout, serverTimeout);
        } catch (final Exception ex) {
            s_logger.warn("Failed to create load balancer due to ", ex);
            if (ex instanceof NetworkRuleConflictException) {
                throw (NetworkRuleConflictException) ex;
            }
            if (ex instanceof InvalidParameterValueException) {
                throw (InvalidParameterValueException) ex;
            }
        } finally {
            if (result == null && systemIp != null) {
                s_logger.debug("Releasing system IP address " + systemIp + " as corresponding lb rule failed to create");
                _ipAddrMgr.handleSystemIpRelease(systemIp);
            }
            // release ip address if ipassoc was perfored
            if (performedIpAssoc) {
                ipVO = _ipAddressDao.findById(ipVO.getId());
                _vpcMgr.unassignIPFromVpcNetwork(ipVO.getId(), networkId);
            }
        }
    }
    if (result == null) {
        throw new CloudRuntimeException("Failed to create load balancer rule: " + name);
    }
    return result;
}
Also used : Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NetworkOffering(com.cloud.offering.NetworkOffering) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) LoadBalancer(com.cloud.legacymodel.network.LoadBalancer) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Example 73 with Network

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

the class LoadBalancingRulesManagerImpl method updateLBHealthChecks.

// This method will check the status of services which has monitors created
// by CloudStack and update them in lbvmmap table
@DB
@Override
public void updateLBHealthChecks(final Scheme scheme) throws ResourceUnavailableException {
    List<LoadBalancerVO> rules = _lbDao.listAll();
    final List<NetworkVO> networks = _networkDao.listAll();
    List<LoadBalancerTO> stateRules = null;
    boolean isHandled = false;
    for (final NetworkVO ntwk : networks) {
        final Network network = _networkDao.findById(ntwk.getId());
        final String capability = getLBCapability(network.getId(), Capability.HealthCheckPolicy.getName());
        if (capability != null && capability.equalsIgnoreCase("true")) {
            /*
                 * s_logger.debug(
                 * "HealthCheck Manager :: LB Provider in the Network has the Healthcheck policy capability :: "
                 * + provider.get(0).getName());
                 */
            rules = _lbDao.listByNetworkIdAndScheme(network.getId(), scheme);
            if (rules != null && rules.size() > 0) {
                final List<LoadBalancingRule> lbrules = new ArrayList<>();
                for (final LoadBalancerVO lb : rules) {
                    final List<LbDestination> dstList = getExistingDestinations(lb.getId());
                    final List<LbHealthCheckPolicy> hcPolicyList = getHealthCheckPolicies(lb.getId());
                    // hashealtChecks
                    if (hcPolicyList != null && hcPolicyList.size() > 0) {
                        final Ip sourceIp = getSourceIp(lb);
                        final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, null, hcPolicyList, sourceIp, null, lb.getLbProtocol());
                        lbrules.add(loadBalancing);
                    }
                }
                if (lbrules.size() > 0) {
                    isHandled = false;
                    for (final LoadBalancingServiceProvider lbElement : _lbProviders) {
                        stateRules = lbElement.updateHealthChecks(network, lbrules);
                        if (stateRules != null && stateRules.size() > 0) {
                            for (final LoadBalancerTO lbto : stateRules) {
                                final LoadBalancerVO ulb = _lbDao.findByUuid(lbto.getUuid());
                                final List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(ulb.getId());
                                for (final LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
                                    final UserVm vm = _vmDao.findById(lbVmMap.getInstanceId());
                                    final Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(ulb.getNetworkId(), vm.getId());
                                    final String dstIp = lbVmMap.getInstanceIp() == null ? nic.getIPv4Address() : lbVmMap.getInstanceIp();
                                    for (int i = 0; i < lbto.getDestinations().length; i++) {
                                        final LoadBalancerTO.DestinationTO des = lbto.getDestinations()[i];
                                        if (dstIp.equalsIgnoreCase(lbto.getDestinations()[i].getDestIp())) {
                                            lbVmMap.setState(des.getMonitorState());
                                            _lb2VmMapDao.persist(lbVmMap);
                                            s_logger.debug("Updating the LB VM Map table with the service state");
                                        }
                                    }
                                }
                            }
                            isHandled = true;
                        }
                        if (isHandled) {
                            break;
                        }
                    }
                }
            }
        } else {
        // s_logger.debug("HealthCheck Manager :: LB Provider in the Network DNOT the Healthcheck policy capability ");
        }
    }
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) LoadBalancingRule(com.cloud.legacymodel.network.LoadBalancingRule) Ip(com.cloud.legacymodel.network.Ip) PublicIp(com.cloud.network.addr.PublicIp) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) Nic(com.cloud.legacymodel.network.Nic) LoadBalancerTO(com.cloud.legacymodel.to.LoadBalancerTO) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) LbDestination(com.cloud.legacymodel.network.LoadBalancingRule.LbDestination) UserVm(com.cloud.uservm.UserVm) Network(com.cloud.legacymodel.network.Network) LbHealthCheckPolicy(com.cloud.legacymodel.network.LoadBalancingRule.LbHealthCheckPolicy) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) DB(com.cloud.utils.db.DB)

Example 74 with Network

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

the class CommandSetupHelper method configureInterfacesAndIps.

private void configureInterfacesAndIps(final VirtualRouter router, final List<Nic> nicsToExclude, final List<Ip> ipsToExclude, final NetworkOverviewTO networkOverviewTO, final List<NetworkOverviewTO.InterfaceTO> interfacesTO, final List<NetworkOverviewTO.ServiceTO.ServiceSourceNatTO> serviceSourceNatsTO) {
    final List<NicVO> nics = _nicDao.listByVmId(router.getId());
    nics.stream().filter(nic -> !nicsToExclude.contains(nic)).forEach(nic -> {
        final NetworkOverviewTO.InterfaceTO interfaceTO = new NetworkOverviewTO.InterfaceTO();
        interfaceTO.setMacAddress(nic.getMacAddress());
        final List<NetworkOverviewTO.InterfaceTO.IPv4AddressTO> ipv4Addresses = new ArrayList<>();
        if (StringUtils.isNotBlank(nic.getIPv4Address()) && StringUtils.isNotBlank(nic.getIPv4Netmask())) {
            ipv4Addresses.add(new NetworkOverviewTO.InterfaceTO.IPv4AddressTO(NetUtils.getIpv4AddressWithCidrSize(nic.getIPv4Address(), nic.getIPv4Netmask()), nic.getIPv4Gateway()));
        }
        final NetworkVO network = _networkDao.findById(nic.getNetworkId());
        if (network != null) {
            final TrafficType trafficType = network.getTrafficType();
            if (TrafficType.Public.equals(trafficType)) {
                ipv4Addresses.addAll(_ipAddressDao.listByVpc(router.getVpcId(), false).stream().filter(ipAddressVO -> !ipsToExclude.contains(ipAddressVO.getAddress()) && ipAddressVO.getAssociatedWithNetworkId() != null).map(ipAddressVO -> {
                    final Ip ip = ipAddressVO.getAddress();
                    final VlanVO vlanVO = _vlanDao.findById(ipAddressVO.getVlanId());
                    return new NetworkOverviewTO.InterfaceTO.IPv4AddressTO(NetUtils.getIpv4AddressWithCidrSize(ip.addr(), vlanVO.getVlanNetmask()), nic.getIPv4Gateway());
                }).collect(Collectors.toList()));
                serviceSourceNatsTO.addAll(_ipAddressDao.listByVpc(router.getVpcId(), true).stream().map(IPAddressVO::getAddress).filter(ip -> !ipsToExclude.contains(ip)).map(Ip::addr).map(ip -> new NetworkOverviewTO.ServiceTO.ServiceSourceNatTO(ip, nic.getIPv4Gateway())).collect(Collectors.toList()));
            }
            interfaceTO.setMetadata(new NetworkOverviewTO.InterfaceTO.MetadataTO(network));
        }
        interfaceTO.setIpv4Addresses(ipv4Addresses.toArray(new NetworkOverviewTO.InterfaceTO.IPv4AddressTO[ipv4Addresses.size()]));
        interfacesTO.add(interfaceTO);
    });
    networkOverviewTO.setInterfaces(interfacesTO.toArray(new NetworkOverviewTO.InterfaceTO[interfacesTO.size()]));
}
Also used : LbStickinessPolicy(com.cloud.legacymodel.network.LoadBalancingRule.LbStickinessPolicy) NetworkModel(com.cloud.network.NetworkModel) VpnUser(com.cloud.legacymodel.network.VpnUser) Nic(com.cloud.legacymodel.network.Nic) StaticRouteProfile(com.cloud.legacymodel.network.vpc.StaticRouteProfile) NetworkACLTO(com.cloud.legacymodel.to.NetworkACLTO) ServiceOfferingDao(com.cloud.service.dao.ServiceOfferingDao) VlanDao(com.cloud.dc.dao.VlanDao) Map(java.util.Map) ZoneRepository(com.cloud.db.repository.ZoneRepository) LoadBalancerVMMapDao(com.cloud.network.dao.LoadBalancerVMMapDao) FirewallRule(com.cloud.legacymodel.network.FirewallRule) NetworkACLItemVO(com.cloud.network.vpc.NetworkACLItemVO) NicTO(com.cloud.legacymodel.to.NicTO) LoadBalancingRule(com.cloud.legacymodel.network.LoadBalancingRule) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) SetPublicIpACLCommand(com.cloud.legacymodel.communication.command.SetPublicIpACLCommand) VpcGateway(com.cloud.legacymodel.network.vpc.VpcGateway) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) SetStaticNatRulesCommand(com.cloud.legacymodel.communication.command.SetStaticNatRulesCommand) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) VpnUserDao(com.cloud.network.dao.VpnUserDao) NumbersUtil(com.cloud.utils.NumbersUtil) VirtualMachine(com.cloud.legacymodel.vm.VirtualMachine) Ip(com.cloud.legacymodel.network.Ip) Zone(com.cloud.db.model.Zone) UpdateVmOverviewCommand(com.cloud.legacymodel.communication.command.UpdateVmOverviewCommand) NicProfile(com.cloud.vm.NicProfile) ArrayList(java.util.ArrayList) Purpose(com.cloud.legacymodel.network.FirewallRule.Purpose) VlanVO(com.cloud.dc.VlanVO) ConfigurationDao(com.cloud.framework.config.dao.ConfigurationDao) DomainRouterVO(com.cloud.vm.DomainRouterVO) UpdateNetworkOverviewCommand(com.cloud.legacymodel.communication.command.UpdateNetworkOverviewCommand) BroadcastDomainType(com.cloud.model.enumeration.BroadcastDomainType) Site2SiteVpnConnection(com.cloud.network.Site2SiteVpnConnection) PortForwardingRule(com.cloud.legacymodel.network.PortForwardingRule) DomainRouterDao(com.cloud.vm.dao.DomainRouterDao) SavePasswordCommand(com.cloud.legacymodel.communication.command.SavePasswordCommand) LbDestination(com.cloud.legacymodel.network.LoadBalancingRule.LbDestination) PublicIpACLTO(com.cloud.legacymodel.to.PublicIpACLTO) Site2SiteVpnConnectionDao(com.cloud.network.dao.Site2SiteVpnConnectionDao) Site2SiteVpnConnectionVO(com.cloud.network.dao.Site2SiteVpnConnectionVO) UserVmDao(com.cloud.vm.dao.UserVmDao) NetworkElementCommand(com.cloud.legacymodel.communication.command.NetworkElementCommand) NicDao(com.cloud.vm.dao.NicDao) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) Site2SiteCustomerGatewayDao(com.cloud.network.dao.Site2SiteCustomerGatewayDao) StaticRouteDao(com.cloud.network.vpc.dao.StaticRouteDao) SetPortForwardingRulesVpcCommand(com.cloud.legacymodel.communication.command.SetPortForwardingRulesVpcCommand) FirewallRuleTO(com.cloud.legacymodel.to.FirewallRuleTO) PortForwardingRuleTO(com.cloud.legacymodel.to.PortForwardingRuleTO) SetPortForwardingRulesCommand(com.cloud.legacymodel.communication.command.SetPortForwardingRulesCommand) Site2SiteVpnGatewayDao(com.cloud.network.dao.Site2SiteVpnGatewayDao) Site2SiteVpnGatewayVO(com.cloud.network.dao.Site2SiteVpnGatewayVO) StaticNatRuleTO(com.cloud.legacymodel.to.StaticNatRuleTO) URI(java.net.URI) Config(com.cloud.configuration.Config) SetFirewallRulesCommand(com.cloud.legacymodel.communication.command.SetFirewallRulesCommand) StringUtils(com.cloud.utils.StringUtils) SetNetworkACLCommand(com.cloud.legacymodel.communication.command.SetNetworkACLCommand) TrafficType(com.cloud.model.enumeration.TrafficType) LBStickinessPolicyDao(com.cloud.network.dao.LBStickinessPolicyDao) Commands(com.cloud.agent.manager.Commands) IpAddress(com.cloud.network.IpAddress) LoadBalancerDao(com.cloud.network.dao.LoadBalancerDao) NicVO(com.cloud.vm.NicVO) Site2SiteCustomerGatewayVO(com.cloud.network.dao.Site2SiteCustomerGatewayVO) Collectors(java.util.stream.Collectors) NetworkOverviewTO(com.cloud.legacymodel.to.NetworkOverviewTO) List(java.util.List) LoadBalancerTO(com.cloud.legacymodel.to.LoadBalancerTO) NetworkACLItem(com.cloud.legacymodel.network.vpc.NetworkACLItem) RemoteAccessVpnDao(com.cloud.network.dao.RemoteAccessVpnDao) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) Optional(java.util.Optional) NetUtils(com.cloud.utils.net.NetUtils) LoadBalancerConfigCommand(com.cloud.legacymodel.communication.command.LoadBalancerConfigCommand) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) StaticNat(com.cloud.network.rules.StaticNat) VirtualRouter(com.cloud.legacymodel.network.VirtualRouter) HashMap(java.util.HashMap) NetworkDao(com.cloud.network.dao.NetworkDao) Inject(javax.inject.Inject) IPAddressVO(com.cloud.network.dao.IPAddressVO) NetworkVO(com.cloud.network.dao.NetworkVO) Qualifier(org.springframework.beans.factory.annotation.Qualifier) IPAddressDao(com.cloud.network.dao.IPAddressDao) VMOverviewTO(com.cloud.legacymodel.to.VMOverviewTO) GuestType(com.cloud.model.enumeration.GuestType) FirewallRulesDao(com.cloud.network.dao.FirewallRulesDao) Network(com.cloud.legacymodel.network.Network) NetworkACLItemDao(com.cloud.network.vpc.NetworkACLItemDao) SetupVRCommand(com.cloud.legacymodel.communication.command.SetupVRCommand) PublicIpAddress(com.cloud.network.PublicIpAddress) NetworkOffering(com.cloud.offering.NetworkOffering) UserVmVO(com.cloud.vm.UserVmVO) VpcDao(com.cloud.network.vpc.dao.VpcDao) NetworkOfferingDao(com.cloud.offerings.dao.NetworkOfferingDao) LoadBalancer(com.cloud.legacymodel.network.LoadBalancer) Vpc(com.cloud.legacymodel.network.vpc.Vpc) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) NetworkVO(com.cloud.network.dao.NetworkVO) Ip(com.cloud.legacymodel.network.Ip) ArrayList(java.util.ArrayList) NetworkOverviewTO(com.cloud.legacymodel.to.NetworkOverviewTO) VlanVO(com.cloud.dc.VlanVO) NicVO(com.cloud.vm.NicVO) TrafficType(com.cloud.model.enumeration.TrafficType)

Example 75 with Network

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

the class CommandSetupHelper method createVmOverviewFromRouter.

public VMOverviewTO createVmOverviewFromRouter(final VirtualRouter router) {
    final VMOverviewTO vmOverviewTO = new VMOverviewTO();
    final Map<UserVmVO, List<NicVO>> vmsAndNicsMap = new HashMap<>();
    final List<NicVO> routerNics = _nicDao.listByVmId(router.getId());
    for (final NicVO routerNic : routerNics) {
        final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
        if (TrafficType.Guest.equals(network.getTrafficType()) && !GuestType.Sync.equals(network.getGuestType())) {
            _userVmDao.listByNetworkIdAndStates(network.getId(), VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Paused, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping).forEach(vm -> {
                final NicVO nic = _nicDao.findByNtwkIdAndInstanceId(network.getId(), vm.getId());
                if (nic != null) {
                    if (!vmsAndNicsMap.containsKey(vm)) {
                        vmsAndNicsMap.put(vm, new ArrayList<NicVO>() {

                            {
                                add(nic);
                            }
                        });
                    } else {
                        vmsAndNicsMap.get(vm).add(nic);
                    }
                }
            });
        }
    }
    final List<VMOverviewTO.VMTO> vmsTO = new ArrayList<>();
    vmsAndNicsMap.forEach((vm, nics) -> {
        _userVmDao.loadDetails(vm);
        final VMOverviewTO.VMTO vmTO = new VMOverviewTO.VMTO(vm.getHostName());
        final List<VMOverviewTO.VMTO.InterfaceTO> interfacesTO = new ArrayList<>();
        final ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
        final Zone zone = zoneRepository.findById(router.getDataCenterId()).orElse(null);
        nics.forEach(nic -> {
            final VMOverviewTO.VMTO.InterfaceTO interfaceTO = new VMOverviewTO.VMTO.InterfaceTO(nic.getIPv4Address(), nic.getMacAddress(), nic.isDefaultNic());
            final NetworkVO networkVO = _networkDao.findById(nic.getNetworkId());
            final String vmNameFQDN = networkVO != null ? vm.getHostName() + "." + networkVO.getNetworkDomain() : vm.getHostName();
            final Map<String, String> metadata = interfaceTO.getMetadata();
            metadata.put("service-offering", StringUtils.unicodeEscape(serviceOffering.getDisplayText()));
            metadata.put("availability-zone", StringUtils.unicodeEscape(zone.getName()));
            metadata.put("local-ipv4", nic.getIPv4Address());
            metadata.put("local-hostname", StringUtils.unicodeEscape(vmNameFQDN));
            metadata.put("public-ipv4", router.getPublicIpAddress() != null ? router.getPublicIpAddress() : nic.getIPv4Address());
            metadata.put("public-hostname", router.getPublicIpAddress());
            metadata.put("instance-id", vm.getUuid() != null ? vm.getUuid() : vm.getInstanceName());
            metadata.put("vm-id", vm.getUuid() != null ? vm.getUuid() : String.valueOf(vm.getId()));
            metadata.put("public-keys", vm.getDetail("SSH.PublicKey"));
            final String cloudIdentifier = _configDao.getValue("cloud.identifier");
            metadata.put("cloud-identifier", cloudIdentifier != null ? "CloudStack-{" + cloudIdentifier + "}" : "");
            final Map<String, String> userData = interfaceTO.getUserData();
            userData.put("user-data", vm.getUserData());
            interfacesTO.add(interfaceTO);
        });
        vmTO.setInterfaces(interfacesTO.toArray(new VMOverviewTO.VMTO.InterfaceTO[interfacesTO.size()]));
        vmsTO.add(vmTO);
    });
    vmOverviewTO.setVms(vmsTO.toArray(new VMOverviewTO.VMTO[vmsTO.size()]));
    return vmOverviewTO;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) NetworkVO(com.cloud.network.dao.NetworkVO) HashMap(java.util.HashMap) Zone(com.cloud.db.model.Zone) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VMOverviewTO(com.cloud.legacymodel.to.VMOverviewTO) Network(com.cloud.legacymodel.network.Network) ArrayList(java.util.ArrayList) List(java.util.List) NicVO(com.cloud.vm.NicVO)

Aggregations

Network (com.cloud.legacymodel.network.Network)160 ArrayList (java.util.ArrayList)57 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)56 Account (com.cloud.legacymodel.user.Account)46 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)42 NetworkOffering (com.cloud.offering.NetworkOffering)36 PhysicalNetwork (com.cloud.network.PhysicalNetwork)34 IPAddressVO (com.cloud.network.dao.IPAddressVO)32 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)30 NetworkVO (com.cloud.network.dao.NetworkVO)28 List (java.util.List)28 Zone (com.cloud.db.model.Zone)27 DB (com.cloud.utils.db.DB)27 NicProfile (com.cloud.vm.NicProfile)26 Nic (com.cloud.legacymodel.network.Nic)21 DataCenter (com.cloud.legacymodel.dc.DataCenter)20 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)20 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)19 DomainRouterVO (com.cloud.vm.DomainRouterVO)18 ActionEvent (com.cloud.event.ActionEvent)17