Package org.jvnet.glassfish.comms.clb.core.sip

Source Code of org.jvnet.glassfish.comms.clb.core.sip.SipLoadBalancerManagerBackEnd

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) Ericsson AB, 2004-2008. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.jvnet.glassfish.comms.clb.core.sip;

import com.ericsson.ssa.container.NetworkManager;
import com.ericsson.ssa.container.reporter.Reporter;
import com.ericsson.ssa.container.reporter.ReporterResolver;
import com.ericsson.ssa.sip.Layer;
import com.ericsson.ssa.sip.LayerHelper;
import com.ericsson.ssa.sip.SipServletMessageImpl.RetryPolicy;
import com.ericsson.ssa.sip.SipServletRequestImpl;
import com.ericsson.ssa.sip.SipServletResponseImpl;
import com.ericsson.ssa.sip.dns.SipTransports;
import com.ericsson.ssa.sip.dns.TargetTuple;

import org.apache.catalina.core.StandardContext;

import org.jvnet.glassfish.comms.clb.core.ConvergedLoadBalancerFactory;
import org.jvnet.glassfish.comms.clb.core.util.LoadbalancerUtil;
import org.jvnet.glassfish.comms.util.LogUtil;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.jvnet.glassfish.comms.clb.admin.CLBConfigurator;
import org.jvnet.glassfish.comms.clb.core.CLBRuntimeException;
import org.jvnet.glassfish.comms.clb.core.monitor.CLBMonitoringManager;


/**
* This is the LoadBalancingManagerBackEnd that together with
* {@link SipLoadBalancerManager} is the entry point of the Converged Load
* Balancer.
* <p>
* This part of the CLB is responsible for handling outgoing requests/responses
* on a back-end.
*
* It is a singleton and will be inserted into the SIP chain by the
* {@link org.jvnet.glassfish.comms.startup.SipServiceListener} and
* {@link com.ericsson.ssa.config.LayerHandler} at start-up. Note, it should be
* placed "above" the {@link SipLoadBalancerManager} to achieve the best
* performance.
*
* It is this class that is responsible for reading the configuration and
* creating all the runtime objects for the back-end parts.
*/
public class SipLoadBalancerManagerBackEnd implements Layer {
    private static final Logger logger = LogUtil.CLB_LOGGER.getLogger();
    private static SipLoadBalancerManagerBackEnd instance; // The singleton
                                                           // instance
    private static final CLBMonitoringManager clbMonitoringManager =
            CLBMonitoringManager.getInstance();
   
    private Layer nextLayer; // The next layer above
    private SipLoadBalancerBackend sipLoadBalancerBackend;
    private Reporter reporter;

    /**
     * Create the instance
     */
    private SipLoadBalancerManagerBackEnd() {
    }

    /**
     * Gets the singleton instance. Used by the
     * {@link com.ericsson.ssa.config.LayerHandler} (via reflection) when
     * setting up the SIP and HTTP processing chains at start-up.
     *
     * @return the singleton instance
     */
    public static synchronized SipLoadBalancerManagerBackEnd getInstance() {
       
        if (instance != null) {
            return instance;
        }
       
        if (ConvergedLoadBalancerFactory.isLayerActive() ||
                ConvergedLoadBalancerFactory.isInstanceFrontEndedByCLB()) {
            instance = new SipLoadBalancerManagerBackEnd();
            clbMonitoringManager.register();
            clbMonitoringManager.enableBackendStats();
        } else {
            // There is no CLB F-E on this server instance and there is no CLB F-E
            // on another server instance fronting this server instance do not activate
            // the SIP CLB B-E.
            logger.info("clb.sip.info.sip_lb_be_not_activated");
        }
       
        return instance;
    }

    /**
     * Called by {@link org.jvnet.glassfish.comms.startup.SipServiceListener} at
     * Lifecycle.AFTER_START_EVENT.
     */
    public void start() {
        logger.info("clb.sip.info.starting_sip_lb_be");

        //create admin event listeners to listen for dcr file update events
        CLBConfigurator.registerAdminEventListeners();
       
        createBackend(null);

        DataCentricUtilImpl.install();

        // Register response processor, so that proxy-bekey and proxy-beroute
        // header values will be added as cookies to http responses (whose
        // corresponding requests have been load-balanced by the CLB) or
        // rewritten URLs (if cookies have been disabled)
        StandardContext.setResponseProcessor(CLBHttpResponseProcessor.getInstance());

        logger.info("clb.info.sip.sip_lb_be_started");
    }

    public void dcrReconfig(String dcrFileName) {
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE,
                "clb.sip.fine.sip_lb_be_reconfig_with_dcr_file",
                new Object[]{dcrFileName});
        }
        createBackend(dcrFileName);
    }
   
    private void createBackend(String dcrFileName) {
        try {
            sipLoadBalancerBackend = new SipLoadBalancerBackend(
                    LoadbalancerUtil.generateInstanceID(),
                    LoadbalancerUtil.getLocalSocket(SipTransports.TCP_PROT));
        } catch (CLBRuntimeException ex) {
            logger.log(Level.SEVERE, "clb.sip.severe.failed_to_create_sip_loadbalancer_backend");
            if (logger.isLoggable(Level.FINE)) {
                // Log stack trace with FINE
                logger.log(Level.FINE, "clb.caught_an_exception", ex);
            }
        }
    }

    public void stop() {
        DataCentricUtilImpl.deinstall();
        StandardContext.setResponseProcessor(null);
    }

    // --------------- Layer interface ----------------
    /**
     * No handling of incoming requests (handled by
     * {@link SipLoadBalancerManager}).
     *
     * @param req the received request
     * @see com.ericsson.ssa.sip.Layer#next(com.ericsson.ssa.sip.SipServletRequestImpl)
     */
    public void next(SipServletRequestImpl request) {
        if(clbMonitoringManager.isCLBMonitoringEnabled()){
            clbMonitoringManager.getCLBStatsUpdater().
                    incrementTotalIncomingSipRequestsBE();
        }
        try {
            sipLoadBalancerBackend.handleIncomingRequest(request);
            request.pushTransactionDispatcher(this);
            request.pushApplicationDispatcher(this);
            LayerHelper.next(request, this, nextLayer);
        } catch (SipRoutingException ex) {
            logger.log(Level.WARNING,
                    "clb.sip.failed_to_route_incoming_request_BE",
                    ex.getMessage());
            if (logger.isLoggable(Level.FINE)) {
                // Log stack trace with FINE
                logger.log(Level.FINE, "clb.caught_an_exception", ex);
            }
            SipServletResponseImpl errorResponse = request.createTerminatingResponse(503);
            if (errorResponse != null) {
                errorResponse.popDispatcher().dispatch(errorResponse);
            }
        }
    }

    /**
     * No handling of incoming responses (handled by
     * {@link SipLoadBalancerManager}).
     *
     * @param resp the received request
     * @see com.ericsson.ssa.sip.Layer#next(com.ericsson.ssa.sip.SipServletResponseImpl)
     */
    public void next(SipServletResponseImpl resp) {
        if(clbMonitoringManager.isCLBMonitoringEnabled()){
            clbMonitoringManager.getCLBStatsUpdater().
                    incrementTotalIncomingSipResponsesBE();
        }
        try {
            sipLoadBalancerBackend.handleIncomingResponse(resp);
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER,
                        "An incoming response, pass it on.");
            }
            LayerHelper.next(resp, this, nextLayer);
        } catch (SipRoutingException ex) {
            logger.log(Level.WARNING,
                    "clb.sip.failed_to_route_incoming_response_BE",
                    ex.getMessage());
            if (logger.isLoggable(Level.FINE)) {
                // Log stack trace with FINE
                logger.log(Level.FINE, "clb.caught_an_exception", ex);
            }
        }
    }

    /**
     * Handle an outgoing request.
     *
     * @param req the request to be sent
     * @see com.ericsson.ssa.sip.Dispatcher#dispatch(com.ericsson.ssa.sip.SipServletRequestImpl)
     */
    public void dispatch(SipServletRequestImpl req) {
        if(clbMonitoringManager.isCLBMonitoringEnabled()){
            clbMonitoringManager.getCLBStatsUpdater().
                    incrementTotalOutgoingSipRequestsBE();
        }
        Connection connection;

        try {
            connection = sipLoadBalancerBackend.handleOutgoingRequest(req);

            if (connection != null) {
                assert false : "Should never happen!!! Original connection set by ResolverManager shall always be used";
            } else {
                // Dispatch the request
                req.popDispatcher().dispatch(req);
            }
        } catch (SipRoutingException e) {
            logger.log(Level.WARNING, "clb.sip.failed_to_route_outgoing_req_BE",
                    e.getMessage());
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "clb.caught_an_exception", e);
            }

            SipServletResponseImpl errorResponse = req.createTerminatingResponse(503);

            if (errorResponse != null) {
                LayerHelper.next(errorResponse, this, nextLayer);
            }
        }
    }

    /**
     * Handle an outgoing response.
     *
     * @param resp the response to be sent
     * @see com.ericsson.ssa.sip.Dispatcher#dispatch(com.ericsson.ssa.sip.SipServletResponseImpl)
     */
    public void dispatch(SipServletResponseImpl response) {
        if(clbMonitoringManager.isCLBMonitoringEnabled()){
            clbMonitoringManager.getCLBStatsUpdater().
                    incrementTotalOutgoingSipResponsesBE();
        }
        Connection connection;

        try {
            connection = sipLoadBalancerBackend.handleOutgoingResponse(response);

            if (connection != null) {
                // Alter connection and dispatch
                if (logger.isLoggable(Level.FINER)) {
                    logger.log(Level.FINER, "Alter connection: " +
                        connection);
                }
                if (connection.getTransport() == SipTransports.UDP_PROT &&
                        LoadbalancerUtil.isAsymmetric()){
                    LayerHelper.resetResponseDispatcher(response);
                } else {
                    LayerHelper.resetDispatcher(response,
                            NetworkManager.getInstance());
                }
                TargetTuple tt = new TargetTuple(connection.getTransport(),
                        connection.getRemoteEndpoint().getHostName(),
                        connection.getRemoteEndpoint().getPort());
                tt.setCLBEndpoint(true);
                response.setRemote(tt);              
            }

            response.popDispatcher().dispatch(response);
        } catch (SipRoutingException e) {
            logger.log(Level.WARNING,
                    "clb.sip.failed_to_route_outgoing_resp_BE",
                    e.getMessage());
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "clb.caught_an_exception", e);
            }

            // Drop the response
        }
    }

    /**
     * Register the next layer (used by
     * {@link com.ericsson.ssa.config.LayerHandler})
     *
     * @see com.ericsson.ssa.sip.Layer#registerNext(com.ericsson.ssa.sip.Layer)
     */
    public void registerNext(Layer layer) {
        nextLayer = layer;
    }

    public void setReporters(String reporters) {
        reporter = ReporterResolver.getInstance().getReporter(reporters);
    }

    public Reporter getReporter() {
        return reporter;
    }
   
    /**
     * This method is used to determine whether sip load-balancer back-end layer is active
     * in this instance.
     *
     * @return true if sip load-balancer back-end layer is active
     */
    public static boolean isLayerActive(){
        if(instance == null)
            return false;
        return true;
    }
}
TOP

Related Classes of org.jvnet.glassfish.comms.clb.core.sip.SipLoadBalancerManagerBackEnd

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.