Search in sources :

Example 1 with LbSslCert

use of com.cloud.network.lb.LoadBalancingRule.LbSslCert in project cloudstack by apache.

the class VirtualNetworkApplianceManagerImpl method finalizeNetworkRulesForNetwork.

protected void finalizeNetworkRulesForNetwork(final Commands cmds, final DomainRouterVO router, final Provider provider, final Long guestNetworkId) {
    s_logger.debug("Resending ipAssoc, port forwarding, load balancing rules as a part of Virtual router start");
    final ArrayList<? extends PublicIpAddress> publicIps = getPublicIpsToApply(router, provider, guestNetworkId);
    final List<FirewallRule> firewallRulesEgress = new ArrayList<FirewallRule>();
    // Fetch firewall Egress rules.
    if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Firewall, provider)) {
        firewallRulesEgress.addAll(_rulesDao.listByNetworkPurposeTrafficType(guestNetworkId, Purpose.Firewall, FirewallRule.TrafficType.Egress));
        if (firewallRulesEgress.isEmpty()) {
            //create egress default rule for VR
            createDefaultEgressFirewallRule(firewallRulesEgress, guestNetworkId);
        }
    }
    // Re-apply firewall Egress rules
    s_logger.debug("Found " + firewallRulesEgress.size() + " firewall Egress rule(s) to apply as a part of domR " + router + " start.");
    if (!firewallRulesEgress.isEmpty()) {
        _commandSetupHelper.createFirewallRulesCommands(firewallRulesEgress, router, cmds, guestNetworkId);
    }
    if (publicIps != null && !publicIps.isEmpty()) {
        final List<RemoteAccessVpn> vpns = new ArrayList<RemoteAccessVpn>();
        final List<PortForwardingRule> pfRules = new ArrayList<PortForwardingRule>();
        final List<FirewallRule> staticNatFirewallRules = new ArrayList<FirewallRule>();
        final List<StaticNat> staticNats = new ArrayList<StaticNat>();
        final List<FirewallRule> firewallRulesIngress = new ArrayList<FirewallRule>();
        // StaticNatRules; PFVPN to reapply on domR start)
        for (final PublicIpAddress ip : publicIps) {
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.PortForwarding, provider)) {
                pfRules.addAll(_pfRulesDao.listForApplication(ip.getId()));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.StaticNat, provider)) {
                staticNatFirewallRules.addAll(_rulesDao.listByIpAndPurpose(ip.getId(), Purpose.StaticNat));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Firewall, provider)) {
                firewallRulesIngress.addAll(_rulesDao.listByIpAndPurpose(ip.getId(), Purpose.Firewall));
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Vpn, provider)) {
                final RemoteAccessVpn vpn = _vpnDao.findByPublicIpAddress(ip.getId());
                if (vpn != null) {
                    vpns.add(vpn);
                }
            }
            if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.StaticNat, provider)) {
                if (ip.isOneToOneNat()) {
                    boolean revoke = false;
                    if (ip.getState() == IpAddress.State.Releasing) {
                        // for ips got struck in releasing state we need to delete the rule not add.
                        s_logger.debug("Rule revoke set to true for the ip " + ip.getAddress() + " becasue it is in releasing state");
                        revoke = true;
                    }
                    final StaticNatImpl staticNat = new StaticNatImpl(ip.getAccountId(), ip.getDomainId(), guestNetworkId, ip.getId(), ip.getVmIp(), revoke);
                    staticNats.add(staticNat);
                }
            }
        }
        // Re-apply static nats
        s_logger.debug("Found " + staticNats.size() + " static nat(s) to apply as a part of domR " + router + " start.");
        if (!staticNats.isEmpty()) {
            _commandSetupHelper.createApplyStaticNatCommands(staticNats, router, cmds, guestNetworkId);
        }
        // Re-apply firewall Ingress rules
        s_logger.debug("Found " + firewallRulesIngress.size() + " firewall Ingress rule(s) to apply as a part of domR " + router + " start.");
        if (!firewallRulesIngress.isEmpty()) {
            _commandSetupHelper.createFirewallRulesCommands(firewallRulesIngress, router, cmds, guestNetworkId);
        }
        // Re-apply port forwarding rules
        s_logger.debug("Found " + pfRules.size() + " port forwarding rule(s) to apply as a part of domR " + router + " start.");
        if (!pfRules.isEmpty()) {
            _commandSetupHelper.createApplyPortForwardingRulesCommands(pfRules, router, cmds, guestNetworkId);
        }
        // Re-apply static nat rules
        s_logger.debug("Found " + staticNatFirewallRules.size() + " static nat rule(s) to apply as a part of domR " + router + " start.");
        if (!staticNatFirewallRules.isEmpty()) {
            final List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
            for (final FirewallRule rule : staticNatFirewallRules) {
                staticNatRules.add(_rulesMgr.buildStaticNatRule(rule, false));
            }
            _commandSetupHelper.createApplyStaticNatRulesCommands(staticNatRules, router, cmds, guestNetworkId);
        }
        // Re-apply vpn rules
        s_logger.debug("Found " + vpns.size() + " vpn(s) to apply as a part of domR " + router + " start.");
        if (!vpns.isEmpty()) {
            for (final RemoteAccessVpn vpn : vpns) {
                _commandSetupHelper.createApplyVpnCommands(true, vpn, router, cmds);
            }
        }
        final List<LoadBalancerVO> lbs = _loadBalancerDao.listByNetworkIdAndScheme(guestNetworkId, Scheme.Public);
        final List<LoadBalancingRule> lbRules = new ArrayList<LoadBalancingRule>();
        if (_networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Lb, provider)) {
            // Re-apply load balancing rules
            for (final LoadBalancerVO lb : lbs) {
                final List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
                final List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
                final List<LbHealthCheckPolicy> hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId());
                final Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
                final LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId());
                final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
                lbRules.add(loadBalancing);
            }
        }
        s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of domR " + router + " start.");
        if (!lbRules.isEmpty()) {
            _commandSetupHelper.createApplyLoadBalancingRulesCommands(lbRules, router, cmds, guestNetworkId);
        }
    }
    // Reapply dhcp and dns configuration.
    final Network guestNetwork = _networkDao.findById(guestNetworkId);
    if (guestNetwork.getGuestType() == GuestType.Shared && _networkModel.isProviderSupportServiceInNetwork(guestNetworkId, Service.Dhcp, provider)) {
        final Map<Network.Capability, String> dhcpCapabilities = _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(_networkDao.findById(guestNetworkId).getNetworkOfferingId()), Service.Dhcp);
        final String supportsMultipleSubnets = dhcpCapabilities.get(Network.Capability.DhcpAccrossMultipleSubnets);
        if (supportsMultipleSubnets != null && Boolean.valueOf(supportsMultipleSubnets)) {
            final List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(guestNetworkId, NicIpAlias.State.revoked);
            s_logger.debug("Found" + revokedIpAliasVOs.size() + "ip Aliases to revoke on the router as a part of dhcp configuration");
            removeRevokedIpAliasFromDb(revokedIpAliasVOs);
            final List<NicIpAliasVO> aliasVOs = _nicIpAliasDao.listByNetworkIdAndState(guestNetworkId, NicIpAlias.State.active);
            s_logger.debug("Found" + aliasVOs.size() + "ip Aliases to apply on the router as a part of dhcp configuration");
            final List<IpAliasTO> activeIpAliasTOs = new ArrayList<IpAliasTO>();
            for (final NicIpAliasVO aliasVO : aliasVOs) {
                activeIpAliasTOs.add(new IpAliasTO(aliasVO.getIp4Address(), aliasVO.getNetmask(), aliasVO.getAliasCount().toString()));
            }
            if (activeIpAliasTOs.size() != 0) {
                _commandSetupHelper.createIpAlias(router, activeIpAliasTOs, guestNetworkId, cmds);
                _commandSetupHelper.configDnsMasq(router, _networkDao.findById(guestNetworkId), cmds);
            }
        }
    }
}
Also used : LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) PublicIp(com.cloud.network.addr.PublicIp) Ip(com.cloud.utils.net.Ip) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) StaticNatRule(com.cloud.network.rules.StaticNatRule) NicIpAliasVO(com.cloud.vm.dao.NicIpAliasVO) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) PublicIpAddress(com.cloud.network.PublicIpAddress) Network(com.cloud.network.Network) FirewallRule(com.cloud.network.rules.FirewallRule) LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) PortForwardingRule(com.cloud.network.rules.PortForwardingRule) StaticNat(com.cloud.network.rules.StaticNat) StaticNatImpl(com.cloud.network.rules.StaticNatImpl) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy) IpAliasTO(com.cloud.agent.api.routing.IpAliasTO) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn)

Example 2 with LbSslCert

use of com.cloud.network.lb.LoadBalancingRule.LbSslCert in project cloudstack by apache.

the class FirewallRules method accept.

@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
    _router = router;
    _purpose = _rules.get(0).getPurpose();
    if (_purpose == Purpose.LoadBalancing) {
        LoadBalancerDao loadBalancerDao = visitor.getVirtualNetworkApplianceFactory().getLoadBalancerDao();
        // for load balancer we have to resend all lb rules for the network
        final List<LoadBalancerVO> lbs = loadBalancerDao.listByNetworkIdAndScheme(_network.getId(), Scheme.Public);
        _loadbalancingRules = new ArrayList<LoadBalancingRule>();
        LoadBalancingRulesManager lbMgr = visitor.getVirtualNetworkApplianceFactory().getLbMgr();
        NetworkModel networkModel = visitor.getVirtualNetworkApplianceFactory().getNetworkModel();
        for (final LoadBalancerVO lb : lbs) {
            final List<LbDestination> dstList = lbMgr.getExistingDestinations(lb.getId());
            final List<LbStickinessPolicy> policyList = lbMgr.getStickinessPolicies(lb.getId());
            final List<LbHealthCheckPolicy> hcPolicyList = lbMgr.getHealthCheckPolicies(lb.getId());
            final LbSslCert sslCert = lbMgr.getLbSslCert(lb.getId());
            final Ip sourceIp = networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
            final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
            _loadbalancingRules.add(loadBalancing);
        }
    }
    return visitor.visit(this);
}
Also used : LoadBalancerDao(com.cloud.network.dao.LoadBalancerDao) LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) LoadBalancingRulesManager(com.cloud.network.lb.LoadBalancingRulesManager) Ip(com.cloud.utils.net.Ip) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) NetworkModel(com.cloud.network.NetworkModel) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy)

Example 3 with LbSslCert

use of com.cloud.network.lb.LoadBalancingRule.LbSslCert in project cloudstack by apache.

the class NetscalerResource method execute.

private synchronized Answer execute(final LoadBalancerConfigCommand cmd, final int numRetries) {
    try {
        if (_isSdx) {
            return Answer.createUnsupportedCommandAnswer(cmd);
        }
        final LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers();
        if (loadBalancers == null) {
            return new Answer(cmd);
        }
        for (final LoadBalancerTO loadBalancer : loadBalancers) {
            final String srcIp = loadBalancer.getSrcIp();
            final int srcPort = loadBalancer.getSrcPort();
            final String lbProtocol = getNetScalerProtocol(loadBalancer);
            final String lbAlgorithm = loadBalancer.getAlgorithm();
            final String nsVirtualServerName = generateNSVirtualServerName(srcIp, srcPort);
            final String nsMonitorName = generateNSMonitorName(srcIp, srcPort);
            final LbSslCert sslCert = loadBalancer.getSslCert();
            if (loadBalancer.isAutoScaleVmGroupTO()) {
                applyAutoScaleConfig(loadBalancer);
                // Continue to process all the rules.
                continue;
            }
            boolean hasMonitor = false;
            boolean deleteMonitor = false;
            boolean destinationsToAdd = false;
            boolean deleteCert = false;
            for (final DestinationTO destination : loadBalancer.getDestinations()) {
                if (!destination.isRevoked()) {
                    destinationsToAdd = true;
                    break;
                }
            }
            if (!loadBalancer.isRevoked() && destinationsToAdd) {
                // create a load balancing virtual server
                addLBVirtualServer(nsVirtualServerName, srcIp, srcPort, lbAlgorithm, lbProtocol, loadBalancer.getStickinessPolicies(), null);
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Created load balancing virtual server " + nsVirtualServerName + " on the Netscaler device");
                }
                // create a new monitor
                final HealthCheckPolicyTO[] healthCheckPolicies = loadBalancer.getHealthCheckPolicies();
                if (healthCheckPolicies != null && healthCheckPolicies.length > 0 && healthCheckPolicies[0] != null) {
                    for (final HealthCheckPolicyTO healthCheckPolicyTO : healthCheckPolicies) {
                        if (!healthCheckPolicyTO.isRevoked()) {
                            addLBMonitor(nsMonitorName, lbProtocol, healthCheckPolicyTO);
                            hasMonitor = true;
                        } else {
                            deleteMonitor = true;
                            hasMonitor = false;
                        }
                    }
                }
                for (final DestinationTO destination : loadBalancer.getDestinations()) {
                    final String nsServerName = generateNSServerName(destination.getDestIp());
                    final String nsServiceName = generateNSServiceName(destination.getDestIp(), destination.getDestPort());
                    if (!destination.isRevoked()) {
                        // add a new server
                        if (!nsServerExists(nsServerName)) {
                            final com.citrix.netscaler.nitro.resource.config.basic.server nsServer = new com.citrix.netscaler.nitro.resource.config.basic.server();
                            nsServer.set_name(nsServerName);
                            nsServer.set_ipaddress(destination.getDestIp());
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.add(_netscalerService, nsServer);
                            if (apiCallResult.errorcode != 0 && apiCallResult.errorcode != NitroError.NS_RESOURCE_EXISTS) {
                                throw new ExecutionException("Failed to add server " + destination.getDestIp() + " due to" + apiCallResult.message);
                            }
                        }
                        // create a new service using the server added
                        if (!nsServiceExists(nsServiceName)) {
                            final com.citrix.netscaler.nitro.resource.config.basic.service newService = new com.citrix.netscaler.nitro.resource.config.basic.service();
                            newService.set_name(nsServiceName);
                            newService.set_port(destination.getDestPort());
                            newService.set_servername(nsServerName);
                            newService.set_state("ENABLED");
                            if (lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) {
                                newService.set_servicetype(NetUtils.HTTP_PROTO);
                            } else {
                                newService.set_servicetype(lbProtocol);
                            }
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.add(_netscalerService, newService);
                            if (apiCallResult.errorcode != 0) {
                                throw new ExecutionException("Failed to create service " + nsServiceName + " using server " + nsServerName + " due to" + apiCallResult.message);
                            }
                        }
                        //bind service to load balancing virtual server
                        if (!nsServiceBindingExists(nsVirtualServerName, nsServiceName)) {
                            final com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding svcBinding = new com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding();
                            svcBinding.set_name(nsVirtualServerName);
                            svcBinding.set_servicename(nsServiceName);
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.add(_netscalerService, svcBinding);
                            if (apiCallResult.errorcode != 0) {
                                throw new ExecutionException("Failed to bind service: " + nsServiceName + " to the lb virtual server: " + nsVirtualServerName + " on Netscaler device");
                            }
                        }
                        // service.
                        if (hasMonitor) {
                            if (!isServiceBoundToMonitor(nsServiceName, nsMonitorName)) {
                                bindServiceToMonitor(nsServiceName, nsMonitorName);
                            }
                        } else {
                            // delete it.
                            if (nsMonitorExist(nsMonitorName)) {
                                // unbind the service from the monitor and
                                // delete the monitor
                                unBindServiceToMonitor(nsServiceName, nsMonitorName);
                                deleteMonitor = true;
                            }
                        }
                        if (sslCert != null && lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) {
                            if (sslCert.isRevoked()) {
                                deleteCert = true;
                            } else {
                                // If there is a chain, that should go first to the NS
                                String previousCertKeyName = null;
                                if (sslCert.getChain() != null) {
                                    final List<Certificate> chainList = CertificateHelper.parseChain(sslCert.getChain());
                                    // go from ROOT to intermediate CAs
                                    for (final Certificate intermediateCert : Lists.reverse(chainList)) {
                                        final String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert);
                                        final String intermediateCertKeyName = generateSslCertKeyName(fingerPrint);
                                        final String intermediateCertFileName = intermediateCertKeyName + ".pem";
                                        if (!SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName)) {
                                            final PemObject pemObject = new PemObject(intermediateCert.getType(), intermediateCert.getEncoded());
                                            final StringWriter textWriter = new StringWriter();
                                            try (final PemWriter pemWriter = new PemWriter(textWriter)) {
                                                pemWriter.writeObject(pemObject);
                                                pemWriter.flush();
                                            } catch (final IOException e) {
                                                if (s_logger.isDebugEnabled()) {
                                                    s_logger.debug("couldn't write PEM to a string", e);
                                                }
                                            // else just close the certDataStream
                                            }
                                            SSL.uploadCert(_ip, _username, _password, intermediateCertFileName, textWriter.toString().getBytes());
                                            SSL.createSslCertKey(_netscalerService, intermediateCertFileName, null, intermediateCertKeyName, null);
                                        }
                                        if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService, intermediateCertKeyName, previousCertKeyName)) {
                                            SSL.linkCerts(_netscalerService, intermediateCertKeyName, previousCertKeyName);
                                        }
                                        previousCertKeyName = intermediateCertKeyName;
                                    }
                                }
                                //netscaler uses ".pem" format for "bundle" files
                                final String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem";
                                //netscaler uses ".pem" format for "bundle" files
                                final String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem";
                                final String certKeyName = generateSslCertKeyName(sslCert.getFingerprint());
                                try (final ByteArrayOutputStream certDataStream = new ByteArrayOutputStream()) {
                                    certDataStream.write(sslCert.getCert().getBytes());
                                    if (!SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) {
                                        SSL.uploadCert(_ip, _username, _password, certFilename, certDataStream.toByteArray());
                                        SSL.uploadKey(_ip, _username, _password, keyFilename, sslCert.getKey().getBytes());
                                        SSL.createSslCertKey(_netscalerService, certFilename, keyFilename, certKeyName, sslCert.getPassword());
                                    }
                                } catch (final IOException e) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("couldn't open buffer for certificate", e);
                                    }
                                // else just close the certDataStream
                                }
                                if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService, certKeyName, previousCertKeyName)) {
                                    SSL.linkCerts(_netscalerService, certKeyName, previousCertKeyName);
                                }
                                SSL.bindCertKeyToVserver(_netscalerService, certKeyName, nsVirtualServerName);
                            }
                        }
                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Successfully added LB destination: " + destination.getDestIp() + ":" + destination.getDestPort() + " to load balancer " + srcIp + ":" + srcPort);
                        }
                    } else {
                        // remove a destination from the deployed load balancing rule
                        final com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, nsVirtualServerName);
                        if (serviceBindings != null) {
                            for (final com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
                                if (nsServiceName.equalsIgnoreCase(binding.get_servicename())) {
                                    // delete the binding
                                    apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(_netscalerService, binding);
                                    if (apiCallResult.errorcode != 0) {
                                        throw new ExecutionException("Failed to delete the binding between the virtual server: " + nsVirtualServerName + " and service:" + nsServiceName + " due to" + apiCallResult.message);
                                    }
                                    // check if service is bound to any other virtual server
                                    if (!isServiceBoundToVirtualServer(nsServiceName)) {
                                        // no lb virtual servers are bound to this service so delete it
                                        apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, nsServiceName);
                                        if (apiCallResult.errorcode != 0) {
                                            throw new ExecutionException("Failed to delete service: " + nsServiceName + " due to " + apiCallResult.message);
                                        }
                                    }
                                    // delete the server if there is no associated services
                                    final server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName);
                                    if (services == null || services.length == 0) {
                                        apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, nsServerName);
                                        if (apiCallResult.errorcode != 0) {
                                            throw new ExecutionException("Failed to remove server:" + nsServerName + " due to " + apiCallResult.message);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // delete the implemented load balancing rule and its destinations
                final lbvserver lbserver = getVirtualServerIfExisits(nsVirtualServerName);
                if (lbserver != null) {
                    //unbind the all services associated with this virtual server
                    final com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, nsVirtualServerName);
                    if (serviceBindings != null) {
                        for (final com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
                            final String serviceName = binding.get_servicename();
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.delete(_netscalerService, binding);
                            if (apiCallResult.errorcode != 0) {
                                throw new ExecutionException("Failed to unbind service from the lb virtual server: " + nsVirtualServerName + " due to " + apiCallResult.message);
                            }
                            final com.citrix.netscaler.nitro.resource.config.basic.service svc = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName);
                            final String nsServerName = svc.get_servername();
                            // check if service is bound to any other virtual server
                            if (!isServiceBoundToVirtualServer(serviceName)) {
                                // no lb virtual servers are bound to this service so delete it
                                apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service.delete(_netscalerService, serviceName);
                                if (apiCallResult.errorcode != 0) {
                                    throw new ExecutionException("Failed to delete service: " + serviceName + " due to " + apiCallResult.message);
                                }
                            }
                            //delete the server if no more services attached
                            final server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName);
                            if (services == null || services.length == 0) {
                                apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server.delete(_netscalerService, nsServerName);
                                if (apiCallResult.errorcode != 0) {
                                    throw new ExecutionException("Failed to remove server:" + nsServerName + " due to " + apiCallResult.message);
                                }
                            }
                        }
                    }
                    removeLBVirtualServer(nsVirtualServerName);
                    deleteMonitor = true;
                    deleteCert = true;
                }
            }
            if (deleteMonitor) {
                removeLBMonitor(nsMonitorName);
            }
            if (sslCert != null && deleteCert) {
                //netscaler uses ".pem" format for "bundle" files
                final String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem";
                //netscaler uses ".pem" format for "bundle" files
                final String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem";
                final String certKeyName = generateSslCertKeyName(sslCert.getFingerprint());
                // unbind before deleting
                if (nsVirtualServerExists(nsVirtualServerName) && SSL.isSslCertKeyPresent(_netscalerService, certKeyName) && SSL.isBoundToVserver(_netscalerService, certKeyName, nsVirtualServerName)) {
                    SSL.unbindCertKeyFromVserver(_netscalerService, certKeyName, nsVirtualServerName);
                }
                if (SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) {
                    SSL.deleteSslCertKey(_netscalerService, certKeyName);
                    SSL.deleteCertFile(_ip, _username, _password, certFilename);
                    SSL.deleteKeyFile(_ip, _username, _password, keyFilename);
                }
                if (sslCert.getChain() != null) {
                    final List<Certificate> chainList = CertificateHelper.parseChain(sslCert.getChain());
                    //go from intermediate CAs to ROOT
                    for (final Certificate intermediateCert : chainList) {
                        final String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert);
                        final String intermediateCertKeyName = generateSslCertKeyName(fingerPrint);
                        final String intermediateCertFileName = intermediateCertKeyName + ".pem";
                        if (SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName) && !SSL.isCaforCerts(_netscalerService, intermediateCertKeyName)) {
                            SSL.deleteSslCertKey(_netscalerService, intermediateCertKeyName);
                            SSL.deleteCertFile(_ip, _username, _password, intermediateCertFileName);
                        } else {
                            // if this cert has another certificate as a child then stop at this point because we need the whole chain
                            break;
                        }
                    }
                }
            }
        }
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Successfully executed resource LoadBalancerConfigCommand: " + _gson.toJson(cmd));
        }
        saveConfiguration();
        return new Answer(cmd);
    } catch (final ExecutionException e) {
        s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e);
        if (shouldRetry(numRetries)) {
            return retry(cmd, numRetries);
        } else {
            return new Answer(cmd, e);
        }
    } catch (final Exception e) {
        s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e);
        if (shouldRetry(numRetries)) {
            return retry(cmd, numRetries);
        } else {
            return new Answer(cmd, e);
        }
    }
}
Also used : com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver(com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver) com.citrix.netscaler.nitro.resource.config.lb.lbvserver(com.citrix.netscaler.nitro.resource.config.lb.lbvserver) com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding(com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding) com.citrix.netscaler.nitro.resource.config.basic.server_service_binding(com.citrix.netscaler.nitro.resource.config.basic.server_service_binding) LoadBalancerTO(com.cloud.agent.api.to.LoadBalancerTO) DestinationTO(com.cloud.agent.api.to.LoadBalancerTO.DestinationTO) StringWriter(java.io.StringWriter) ExecutionException(com.cloud.utils.exception.ExecutionException) LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) PemWriter(org.bouncycastle.util.io.pem.PemWriter) IOException(java.io.IOException) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) ExecutionException(com.cloud.utils.exception.ExecutionException) IOException(java.io.IOException) ConfigurationException(javax.naming.ConfigurationException) com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver(com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver) com.citrix.netscaler.nitro.resource.config.lb.lbvserver(com.citrix.netscaler.nitro.resource.config.lb.lbvserver) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) GlobalLoadBalancerConfigAnswer(com.cloud.agent.api.routing.GlobalLoadBalancerConfigAnswer) Answer(com.cloud.agent.api.Answer) SetStaticNatRulesAnswer(com.cloud.agent.api.routing.SetStaticNatRulesAnswer) HealthCheckLBConfigAnswer(com.cloud.agent.api.routing.HealthCheckLBConfigAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) ReadyAnswer(com.cloud.agent.api.ReadyAnswer) ExternalNetworkResourceUsageAnswer(com.cloud.agent.api.ExternalNetworkResourceUsageAnswer) PemObject(org.bouncycastle.util.io.pem.PemObject) HealthCheckPolicyTO(com.cloud.agent.api.to.LoadBalancerTO.HealthCheckPolicyTO) com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding(com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding) com.citrix.netscaler.nitro.service.nitro_service(com.citrix.netscaler.nitro.service.nitro_service) com.citrix.netscaler.nitro.resource.config.gslb.gslbservice(com.citrix.netscaler.nitro.resource.config.gslb.gslbservice) com.citrix.netscaler.nitro.resource.config.ns.nsconfig(com.citrix.netscaler.nitro.resource.config.ns.nsconfig) com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding(com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding) Certificate(java.security.cert.Certificate)

Example 4 with LbSslCert

use of com.cloud.network.lb.LoadBalancingRule.LbSslCert in project cloudstack by apache.

the class LoadBalancingRules method accept.

@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
    _router = router;
    LoadBalancerDao loadBalancerDao = visitor.getVirtualNetworkApplianceFactory().getLoadBalancerDao();
    // For load balancer we have to resend all lb rules for the network
    final List<LoadBalancerVO> lbs = loadBalancerDao.listByNetworkIdAndScheme(_network.getId(), Scheme.Public);
    // We are cleaning it before because all the rules have to be sent to the router.
    _rules.clear();
    LoadBalancingRulesManager lbMgr = visitor.getVirtualNetworkApplianceFactory().getLbMgr();
    NetworkModel networkModel = visitor.getVirtualNetworkApplianceFactory().getNetworkModel();
    for (final LoadBalancerVO lb : lbs) {
        final List<LbDestination> dstList = lbMgr.getExistingDestinations(lb.getId());
        final List<LbStickinessPolicy> policyList = lbMgr.getStickinessPolicies(lb.getId());
        final List<LbHealthCheckPolicy> hcPolicyList = lbMgr.getHealthCheckPolicies(lb.getId());
        final LbSslCert sslCert = lbMgr.getLbSslCert(lb.getId());
        final Ip sourceIp = networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress();
        final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol());
        _rules.add(loadBalancing);
    }
    return visitor.visit(this);
}
Also used : LoadBalancerDao(com.cloud.network.dao.LoadBalancerDao) LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) LoadBalancingRulesManager(com.cloud.network.lb.LoadBalancingRulesManager) Ip(com.cloud.utils.net.Ip) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) NetworkModel(com.cloud.network.NetworkModel) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy)

Example 5 with LbSslCert

use of com.cloud.network.lb.LoadBalancingRule.LbSslCert in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method getLoadBalancerRuleToApply.

private LoadBalancingRule getLoadBalancerRuleToApply(LoadBalancerVO lb) {
    List<LbStickinessPolicy> policyList = getStickinessPolicies(lb.getId());
    Ip sourceIp = getSourceIp(lb);
    LbSslCert sslCert = getLbSslCert(lb.getId());
    LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, null, policyList, null, sourceIp, sslCert, lb.getLbProtocol());
    if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(lb.getId())) {
        // Get the associated VmGroup
        AutoScaleVmGroupVO vmGroup = _autoScaleVmGroupDao.listByAll(lb.getId(), null).get(0);
        LbAutoScaleVmGroup lbAutoScaleVmGroup = getLbAutoScaleVmGroup(vmGroup, vmGroup.getState(), lb);
        loadBalancing.setAutoScaleVmGroup(lbAutoScaleVmGroup);
    } else {
        List<LbDestination> dstList = getExistingDestinations(lb.getId());
        loadBalancing.setDestinations(dstList);
        List<LbHealthCheckPolicy> hcPolicyList = getHealthCheckPolicies(lb.getId());
        loadBalancing.setHealthCheckPolicies(hcPolicyList);
    }
    return loadBalancing;
}
Also used : LbSslCert(com.cloud.network.lb.LoadBalancingRule.LbSslCert) AutoScaleVmGroupVO(com.cloud.network.as.AutoScaleVmGroupVO) Ip(com.cloud.utils.net.Ip) PublicIp(com.cloud.network.addr.PublicIp) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) LbAutoScaleVmGroup(com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination)

Aggregations

LbSslCert (com.cloud.network.lb.LoadBalancingRule.LbSslCert)7 LbDestination (com.cloud.network.lb.LoadBalancingRule.LbDestination)5 LbHealthCheckPolicy (com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy)5 LbStickinessPolicy (com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy)5 Ip (com.cloud.utils.net.Ip)5 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)4 LoadBalancingRule (com.cloud.network.lb.LoadBalancingRule)3 NetworkModel (com.cloud.network.NetworkModel)2 PublicIp (com.cloud.network.addr.PublicIp)2 LoadBalancerDao (com.cloud.network.dao.LoadBalancerDao)2 LoadBalancingRulesManager (com.cloud.network.lb.LoadBalancingRulesManager)2 com.citrix.netscaler.nitro.resource.config.basic.server_service_binding (com.citrix.netscaler.nitro.resource.config.basic.server_service_binding)1 com.citrix.netscaler.nitro.resource.config.gslb.gslbservice (com.citrix.netscaler.nitro.resource.config.gslb.gslbservice)1 com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver (com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver)1 com.citrix.netscaler.nitro.resource.config.lb.lbvserver (com.citrix.netscaler.nitro.resource.config.lb.lbvserver)1 com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding)1 com.citrix.netscaler.nitro.resource.config.ns.nsconfig (com.citrix.netscaler.nitro.resource.config.ns.nsconfig)1 com.citrix.netscaler.nitro.service.nitro_service (com.citrix.netscaler.nitro.service.nitro_service)1 Answer (com.cloud.agent.api.Answer)1 ExternalNetworkResourceUsageAnswer (com.cloud.agent.api.ExternalNetworkResourceUsageAnswer)1