Package org.jvnet.glassfish.comms.clb.proxy

Source Code of org.jvnet.glassfish.comms.clb.proxy.HttpProxy

/*
* 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.proxy;

import com.sun.enterprise.admin.event.AdminEventListenerRegistry;
import com.sun.enterprise.admin.event.http.HSKeepAliveEvent;
import com.sun.enterprise.web.connector.grizzly.SelectorThread;

import com.sun.grizzly.ConnectorHandler;
import org.jvnet.glassfish.comms.clb.proxy.config.ProxyConfig;
import org.jvnet.glassfish.comms.clb.proxy.outbound.ConnectionManager;
import org.jvnet.glassfish.comms.clb.proxy.util.Reader;
import org.jvnet.glassfish.comms.httplayers.HttpLayer;

import java.io.IOException;

import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jvnet.glassfish.comms.clb.proxy.config.HttpReconfigListener;


/**
* This is a singleton class that is responsible for proxying a Http
* request to a remote instances.
*
* @author rampsarathy
*/
public class HttpProxy {
    /**
     * Singleton object.
     */
    private static HttpProxy _thisInstance = null;
   
    /**
     * Manages the outbound connections
     */
    private ConnectionManager connectionManager;
   
    /**
     * Logger.
     */
    private Logger _logger;
   
    /**
     * The pluggable layer framework handler
     */
    private ProxyLayerHandler layerHandler = null;
   
    /**
     * Flag that indicates if proxy functionality
     * has to be enabled in the grzzly connector.
     */
    private boolean proxyDisabled = false;
   
    private static final int RETRY_ATTEMPTS = 5;

    private int retryAttempts = RETRY_ATTEMPTS;

    public void setRetryAttempts(int retryAttempts) {
        this.retryAttempts = retryAttempts;
    }
    /**
     * Creates a new instance of HttpProxy
     */
    private HttpProxy() {
        connectionManager = new ConnectionManager();
        connectionManager.createConnectionHandlerPool();
        layerHandler = new ProxyLayerHandler();
        _logger = ProxyConfig.getInstance().getLogger();
        retryAttempts = ProxyConfig.getInstance().getSendRetryCount();
        AdminEventListenerRegistry.addEventListener(
                                    HSKeepAliveEvent.eventType,
                                    new HttpReconfigListener(connectionManager));
        if (_logger.isLoggable(Level.FINEST)){
            _logger.log(Level.FINEST, "clb.proxy.httpproxy_constructor_called");
        }
        registerProxy();
    }

    /**
     * Sets the logger
     */
    public void setLogger(Logger logger) {
        this._logger = logger;
    }

    /**
     * Getter for proxy status.
     */
    public boolean proxyDisabled() {
        return proxyDisabled;
    }

    /**
     * Enables the proxy functionality in the connector.
     */
    private void registerProxy() {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    System.setProperty(ProxyConfig.PIPELINE_CLASS_PROPERTY,
                            ProxyConfig.PIPELINE_CLASS);
                } catch (Exception e) {
                    _logger.log(Level.SEVERE,"clb.proxy.cannot_activate_proxy");
                }
                return null;
            }
        });
        if (_logger.isLoggable(Level.FINEST)){
            _logger.log(Level.FINEST,"clb.proxy.activated");
        }
    }

    /**
     * Singleton method to get this instance.
     */
    public static synchronized HttpProxy getInstance() {
        if (_thisInstance == null) {
            _thisInstance = new HttpProxy();
        }

        return _thisInstance;
    }

    /**
     * Returns the pluggable framework invocation handler.
     */
    public ProxyLayerHandler getLayerHandler() {
        return this.layerHandler;
    }

    /**
     * Singleton object, so ensure nobody clones this.
     */
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    /**
     * Gets the connection manager for this proxy.
     */
    public ConnectionManager getConnectionManager() {
        return this.connectionManager;
    }

    /**
     * Method to proxy an Http request.
     * This method always keeps the connection alive.
     *
     * @param payload information about the payload that needs to be proxied.
     * @param buff byte buffer that contains the data.
     * @param key Selection key corresponding to the inbound channel.
     */
    public boolean doProxyHttp(ProxyRequestHandler task, ByteBuffer buff,
            SelectionKey clientkey) {
        boolean cachehandler = true;
        ConnectorHandler handler = null;
        long bytesRead = 0;
        long bytesWritten = 0;
        boolean moredata = false;
        if (_logger.isLoggable(Level.FINEST)){
            _logger.log(Level.FINEST, "clb.proxy.dotask.task",task);
        }
        if (task != null) {
            /**
             * taskInfo contains the buffer, length of the task
             * and the bytesWritten field, with this and the key for the
             * inbound channel we should be ready to read from
             * the client channel  and write bytes into server channel
             */
            connectionManager.registerServerEndpoint(clientkey, task);
            /*
             * We have the buff, start writing, if we want more we just
             * have to return to the selector and wait for data
             */
            bytesRead = buff.limit();
            buff.flip();
            try {
                handler = connectionManager.getHandler(task);
            } catch (Exception ex) {
                _logger.log(Level.SEVERE,"Failed : creating connection to backend", ex);
                connectionManager.cleanUpHandler(handler, task.getEndpoint());
                task.setError(true);
                return false;
            }
            task.setConnectorHandler(handler);
        } else {
            moredata = true;
            Exception writeEx = null;
            /**
             * If we dont have a task object it means that
             * we are receiving more data from an existing channel for
             * a known request that is being processed, for which
             * we had registered a ReadTask. Read the bytes from the channel and
             * send it.
             */
                   
            task = connectionManager.getServerEndpoint(clientkey);
            try {
                bytesRead = Reader.read(buff, (SocketChannel) clientkey.channel(),
                        ProxyConfig.getInstance().getReadTimeOutInt());
                if (_logger.isLoggable(Level.FINE)){
                    _logger.log(Level.FINE, "clb.proxy.bytes_read", "" +  bytesRead);
                }

            } catch (IOException ex) {
                _logger.log(Level.SEVERE,"clb.proxy.bytes_read_failed ",
                        ex.getMessage());
                writeEx = ex;               
            }
            if ((writeEx != null) || (bytesRead == -1)){                               
                /**
                 * Close the BE channel also because
                 * that must be waiting for data.
                 */
                connectionManager.cleanUpHandler(task.getConnectorHandler(),
                        task.getEndpoint());
                return false;
            }
        }
        if (task == null) {
            _logger.log(Level.SEVERE,"clb.proxy.doproxy_task_null");
            return false;
        }
        handler = task.getConnectorHandler()
        Exception exception = null;
        if (bytesRead <= 0) {
            /* Go back to Grizzly 1.0 selector thread and
             * register the read key, return true will ensure keepalive.
             */
            return cachehandler;
        } else {
            try {
                int retry = 0;
                int pos = buff.position();
                int limit = buff.limit();
                while (true) {                                      
                    try {
                        bytesWritten = handler.write(buff, true);
                        task.setConnectorHandler(handler);
                        break;
                    } catch (Exception ioe) {
                        if (moredata) {
                            throw new IOException("More data for a closed BE channel");
                        }
                        retry++;
                        buff.position(pos);
                        buff.limit(limit);
                        if (retry > retryAttempts) {
                            throw ioe;
                        }
                    }
                    handler = connectionManager.getHandler(task);                   
                }
               
                if (task.isTransferEncoding()) {
                     task.updateEnd((ByteBuffer)buff.flip(), moredata);
                }else {
                    task.setBytesWritten(task.getBytesWritten() + bytesWritten);
                }
                if (!task.hasRemaining()) {

                    if (_logger.isLoggable(Level.FINEST)){
                        _logger.log(Level.FINEST, "clb.proxy.finished_reading");
                    }
                    cachehandler = false;

                }
                if (_logger.isLoggable(Level.FINE)){
                    _logger.log(Level.FINE,
                            "clb.proxy.bytes_written", "" +  bytesWritten);
                }

            } catch (IOException ioe) {
                exception = ioe;
            } catch (Exception ex) {
                exception = ex;
            } finally {
                if (exception != null) {
                    _logger.log(Level.SEVERE, "Exception in HttpProxy ", exception);
                    connectionManager.cleanUpHandler(handler, task.getEndpoint());
                    task.setError(true);
                    return false;
                }
            }
        }
        return cachehandler;
    }

    /**
     * Selector thread that would help the connection manager
     * to park the requests if the response from the remote host takes
     * a long time
     */
    public void setSelectorThread(SelectorThread selthread) {
        connectionManager.setSelectorThread(selthread);
    }

    /**
     * This is called by the handler when the selection key expires.
     * We have to handle this by removing the connection reference
     * and also cancelling the selection key corresponding to the
     * backend channel.
     */
    public void expireKey(SelectionKey key) {
        //do something , because we got a notification saying
        // the client channel key has expired
        connectionManager.removeClientEndpoint(key);
    }
}
TOP

Related Classes of org.jvnet.glassfish.comms.clb.proxy.HttpProxy

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.