Search in sources :

Example 6 with LoadBalancerTO

use of com.cloud.agent.api.to.LoadBalancerTO 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 7 with LoadBalancerTO

use of com.cloud.agent.api.to.LoadBalancerTO in project cloudstack by apache.

the class NetscalerElement method applyElasticLoadBalancerRules.

public boolean applyElasticLoadBalancerRules(Network network, List<LoadBalancingRule> loadBalancingRules) throws ResourceUnavailableException {
    if (loadBalancingRules == null || loadBalancingRules.isEmpty()) {
        return true;
    }
    String errMsg = null;
    ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
    if (lbDeviceVO == null) {
        try {
            lbDeviceVO = allocateLoadBalancerForNetwork(network);
        } catch (Exception e) {
            errMsg = "Could not allocate a NetSclaer load balancer for configuring elastic load balancer rules due to " + e.getMessage();
            s_logger.error(errMsg);
            throw new ResourceUnavailableException(errMsg, this.getClass(), 0);
        }
    }
    if (!isNetscalerDevice(lbDeviceVO.getDeviceName())) {
        errMsg = "There are no NetScaler load balancer assigned for this network. So NetScaler element can not be handle elastic load balancer rules.";
        s_logger.error(errMsg);
        throw new ResourceUnavailableException(errMsg, this.getClass(), 0);
    }
    List<LoadBalancerTO> loadBalancersToApply = new ArrayList<LoadBalancerTO>();
    for (int i = 0; i < loadBalancingRules.size(); i++) {
        LoadBalancingRule rule = loadBalancingRules.get(i);
        boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke));
        String protocol = rule.getProtocol();
        String algorithm = rule.getAlgorithm();
        String lbUuid = rule.getUuid();
        String srcIp = rule.getSourceIp().addr();
        int srcPort = rule.getSourcePortStart();
        List<LbDestination> destinations = rule.getDestinations();
        if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) {
            LoadBalancerTO loadBalancer = new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies(), rule.getLbSslCert(), rule.getLbProtocol());
            if (rule.isAutoScaleConfig()) {
                loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup());
            }
            loadBalancersToApply.add(loadBalancer);
        }
    }
    if (loadBalancersToApply.size() > 0) {
        int numLoadBalancersForCommand = loadBalancersToApply.size();
        LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
        LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(loadBalancersForCommand, null);
        HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
        Answer answer = _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
        if (answer == null || !answer.getResult()) {
            String details = (answer != null) ? answer.getDetails() : "details unavailable";
            String msg = "Unable to apply elastic load balancer rules to the external load balancer appliance in zone " + network.getDataCenterId() + " due to: " + details + ".";
            s_logger.error(msg);
            throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId());
        }
    }
    return true;
}
Also used : LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) ArrayList(java.util.ArrayList) LoadBalancerTO(com.cloud.agent.api.to.LoadBalancerTO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InsufficientNetworkCapacityException(com.cloud.exception.InsufficientNetworkCapacityException) HostVO(com.cloud.host.HostVO) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) ExternalLoadBalancerDeviceVO(com.cloud.network.dao.ExternalLoadBalancerDeviceVO) Answer(com.cloud.agent.api.Answer) SetStaticNatRulesAnswer(com.cloud.agent.api.routing.SetStaticNatRulesAnswer) HealthCheckLBConfigAnswer(com.cloud.agent.api.routing.HealthCheckLBConfigAnswer) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) GlobalLoadBalancerConfigCommand(com.cloud.agent.api.routing.GlobalLoadBalancerConfigCommand) LoadBalancerConfigCommand(com.cloud.agent.api.routing.LoadBalancerConfigCommand)

Example 8 with LoadBalancerTO

use of com.cloud.agent.api.to.LoadBalancerTO in project cloudstack by apache.

the class NetscalerResource method execute.

private Answer execute(final HealthCheckLBConfigCommand cmd, final int numRetries) {
    final List<LoadBalancerTO> hcLB = new ArrayList<LoadBalancerTO>();
    try {
        if (_isSdx) {
            return Answer.createUnsupportedCommandAnswer(cmd);
        }
        final LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers();
        if (loadBalancers == null) {
            return new HealthCheckLBConfigAnswer(hcLB);
        }
        for (final LoadBalancerTO loadBalancer : loadBalancers) {
            final HealthCheckPolicyTO[] healthCheckPolicies = loadBalancer.getHealthCheckPolicies();
            if (healthCheckPolicies != null && healthCheckPolicies.length > 0 && healthCheckPolicies[0] != null) {
                final String nsVirtualServerName = generateNSVirtualServerName(loadBalancer.getSrcIp(), loadBalancer.getSrcPort());
                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 DestinationTO destination : loadBalancer.getDestinations()) {
                        final String nsServiceName = generateNSServiceName(destination.getDestIp(), destination.getDestPort());
                        for (final com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
                            if (nsServiceName.equalsIgnoreCase(binding.get_servicename())) {
                                destination.setMonitorState(binding.get_curstate());
                                break;
                            }
                        }
                    }
                    hcLB.add(loadBalancer);
                }
            }
        }
    } catch (final ExecutionException e) {
        s_logger.error("Failed to execute HealthCheckLBConfigCommand due to ", e);
        if (shouldRetry(numRetries)) {
            return retry(cmd, numRetries);
        } else {
            return new HealthCheckLBConfigAnswer(hcLB);
        }
    } catch (final Exception e) {
        s_logger.error("Failed to execute HealthCheckLBConfigCommand due to ", e);
        if (shouldRetry(numRetries)) {
            return retry(cmd, numRetries);
        } else {
            return new HealthCheckLBConfigAnswer(hcLB);
        }
    }
    return new HealthCheckLBConfigAnswer(hcLB);
}
Also used : ArrayList(java.util.ArrayList) LoadBalancerTO(com.cloud.agent.api.to.LoadBalancerTO) DestinationTO(com.cloud.agent.api.to.LoadBalancerTO.DestinationTO) ExecutionException(com.cloud.utils.exception.ExecutionException) IOException(java.io.IOException) ConfigurationException(javax.naming.ConfigurationException) 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) HealthCheckLBConfigAnswer(com.cloud.agent.api.routing.HealthCheckLBConfigAnswer) ExecutionException(com.cloud.utils.exception.ExecutionException) 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)

Example 9 with LoadBalancerTO

use of com.cloud.agent.api.to.LoadBalancerTO in project cloudstack by apache.

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(Scheme scheme) throws ResourceUnavailableException {
    List<LoadBalancerVO> rules = _lbDao.listAll();
    List<NetworkVO> networks = _networkDao.listAll();
    List<LoadBalancerTO> stateRules = null;
    boolean isHandled = false;
    for (NetworkVO ntwk : networks) {
        Network network = _networkDao.findById(ntwk.getId());
        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) {
                List<LoadBalancingRule> lbrules = new ArrayList<LoadBalancingRule>();
                for (LoadBalancerVO lb : rules) {
                    List<LbDestination> dstList = getExistingDestinations(lb.getId());
                    List<LbHealthCheckPolicy> hcPolicyList = getHealthCheckPolicies(lb.getId());
                    // hashealtChecks
                    if (hcPolicyList != null && hcPolicyList.size() > 0) {
                        Ip sourceIp = getSourceIp(lb);
                        LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, null, hcPolicyList, sourceIp, null, lb.getLbProtocol());
                        lbrules.add(loadBalancing);
                    }
                }
                if (lbrules.size() > 0) {
                    isHandled = false;
                    for (LoadBalancingServiceProvider lbElement : _lbProviders) {
                        stateRules = lbElement.updateHealthChecks(network, lbrules);
                        if (stateRules != null && stateRules.size() > 0) {
                            for (LoadBalancerTO lbto : stateRules) {
                                LoadBalancerVO ulb = _lbDao.findByUuid(lbto.getUuid());
                                List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(ulb.getId());
                                for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
                                    UserVm vm = _vmDao.findById(lbVmMap.getInstanceId());
                                    Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(ulb.getNetworkId(), vm.getId());
                                    String dstIp = lbVmMap.getInstanceIp() == null ? nic.getIPv4Address() : lbVmMap.getInstanceIp();
                                    for (int i = 0; i < lbto.getDestinations().length; i++) {
                                        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) Ip(com.cloud.utils.net.Ip) PublicIp(com.cloud.network.addr.PublicIp) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) Nic(com.cloud.vm.Nic) LoadBalancerTO(com.cloud.agent.api.to.LoadBalancerTO) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) UserVm(com.cloud.uservm.UserVm) Network(com.cloud.network.Network) LbHealthCheckPolicy(com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) DB(com.cloud.utils.db.DB)

Example 10 with LoadBalancerTO

use of com.cloud.agent.api.to.LoadBalancerTO in project cloudstack by apache.

the class CommandSetupHelper method createApplyLoadBalancingRulesCommands.

public void createApplyLoadBalancingRulesCommands(final List<LoadBalancingRule> rules, final VirtualRouter router, final Commands cmds, final long guestNetworkId) {
    final LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()];
    int i = 0;
    // We don't support VR to be inline currently
    final boolean inline = false;
    for (final LoadBalancingRule rule : rules) {
        final boolean revoked = rule.getState().equals(FirewallRule.State.Revoke);
        final String protocol = rule.getProtocol();
        final String lb_protocol = rule.getLbProtocol();
        final String algorithm = rule.getAlgorithm();
        final String uuid = rule.getUuid();
        final String srcIp = rule.getSourceIp().addr();
        final int srcPort = rule.getSourcePortStart();
        final List<LbDestination> destinations = rule.getDestinations();
        final List<LbStickinessPolicy> stickinessPolicies = rule.getStickinessPolicies();
        final LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, stickinessPolicies);
        lb.setLbProtocol(lb_protocol);
        lbs[i++] = lb;
    }
    String routerPublicIp = null;
    if (router instanceof DomainRouterVO) {
        final DomainRouterVO domr = _routerDao.findById(router.getId());
        routerPublicIp = domr.getPublicIpAddress();
        if (routerPublicIp == null) {
            routerPublicIp = router.getPublicIpAddress();
        }
    }
    final Network guestNetwork = _networkModel.getNetwork(guestNetworkId);
    final Nic nic = _nicDao.findByNtwkIdAndInstanceId(guestNetwork.getId(), router.getId());
    final NicProfile nicProfile = new NicProfile(nic, guestNetwork, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(guestNetwork.getId(), router.getId()), _networkModel.isSecurityGroupSupportedInNetwork(guestNetwork), _networkModel.getNetworkTag(router.getHypervisorType(), guestNetwork));
    final NetworkOffering offering = _networkOfferingDao.findById(guestNetwork.getNetworkOfferingId());
    String maxconn = null;
    if (offering.getConcurrentConnections() == null) {
        maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key());
    } else {
        maxconn = offering.getConcurrentConnections().toString();
    }
    final LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs, routerPublicIp, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()), router.getPrivateIpAddress(), _itMgr.toNicTO(nicProfile, router.getHypervisorType()), router.getVpcId(), maxconn, offering.isKeepAliveEnabled());
    cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key());
    cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key());
    cmd.lbStatsAuth = _configDao.getValue(Config.NetworkLBHaproxyStatsAuth.key());
    cmd.lbStatsPort = _configDao.getValue(Config.NetworkLBHaproxyStatsPort.key());
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(guestNetworkId, router.getId()));
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
    final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
    cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
    cmds.addCommand(cmd);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) LoadBalancingRule(com.cloud.network.lb.LoadBalancingRule) NetworkOffering(com.cloud.offering.NetworkOffering) Nic(com.cloud.vm.Nic) LoadBalancerTO(com.cloud.agent.api.to.LoadBalancerTO) LbStickinessPolicy(com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy) NicProfile(com.cloud.vm.NicProfile) LbDestination(com.cloud.network.lb.LoadBalancingRule.LbDestination) Network(com.cloud.network.Network) DomainRouterVO(com.cloud.vm.DomainRouterVO) LoadBalancerConfigCommand(com.cloud.agent.api.routing.LoadBalancerConfigCommand)

Aggregations

LoadBalancerTO (com.cloud.agent.api.to.LoadBalancerTO)19 LbDestination (com.cloud.network.lb.LoadBalancingRule.LbDestination)12 ArrayList (java.util.ArrayList)12 LoadBalancerConfigCommand (com.cloud.agent.api.routing.LoadBalancerConfigCommand)10 LoadBalancingRule (com.cloud.network.lb.LoadBalancingRule)7 HealthCheckLBConfigAnswer (com.cloud.agent.api.routing.HealthCheckLBConfigAnswer)6 Nic (com.cloud.vm.Nic)5 Answer (com.cloud.agent.api.Answer)4 DataCenterVO (com.cloud.dc.DataCenterVO)4 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)4 HostVO (com.cloud.host.HostVO)4 ExternalLoadBalancerDeviceVO (com.cloud.network.dao.ExternalLoadBalancerDeviceVO)4 ConfigurationException (javax.naming.ConfigurationException)4 DestinationTO (com.cloud.agent.api.to.LoadBalancerTO.DestinationTO)3 NicTO (com.cloud.agent.api.to.NicTO)3 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)3 InsufficientNetworkCapacityException (com.cloud.exception.InsufficientNetworkCapacityException)3 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)3 Network (com.cloud.network.Network)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3