📄 channelniosocket.java
字号:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jk.common;
import java.util.Set;
import java.util.Iterator;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.net.URLEncoder;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import org.apache.jk.core.JkHandler;
import org.apache.jk.core.Msg;
import org.apache.jk.core.MsgContext;
import org.apache.jk.core.JkChannel;
import org.apache.jk.core.WorkerEnv;
import org.apache.coyote.Request;
import org.apache.coyote.RequestGroupInfo;
import org.apache.coyote.RequestInfo;
import org.apache.tomcat.util.modeler.Registry;
import org.apache.tomcat.util.threads.ThreadPool;
import org.apache.tomcat.util.threads.ThreadPoolRunnable;
/**
* Accept ( and send ) TCP messages.
*
* @author Costin Manolache
* @author Bill Barker
* jmx:mbean name="jk:service=ChannelNioSocket"
* description="Accept socket connections"
* jmx:notification name="org.apache.coyote.INVOKE
* jmx:notification-handler name="org.apache.jk.JK_SEND_PACKET
* jmx:notification-handler name="org.apache.jk.JK_RECEIVE_PACKET
* jmx:notification-handler name="org.apache.jk.JK_FLUSH
*
* Jk can use multiple protocols/transports.
* Various container adapters should load this object ( as a bean ),
* set configurations and use it. Note that the connector will handle
* all incoming protocols - it's not specific to ajp1x. The protocol
* is abstracted by MsgContext/Message/Channel.
*
* A lot of the 'original' behavior is hardcoded - this uses Ajp13 wire protocol,
* TCP, Ajp14 API etc.
* As we add other protocols/transports/APIs this will change, the current goal
* is to get the same level of functionality as in the original jk connector.
*
* XXX Make the 'message type' pluggable
*/
public class ChannelNioSocket extends JkHandler
implements NotificationBroadcaster, JkChannel {
private static org.apache.juli.logging.Log log =
org.apache.juli.logging.LogFactory.getLog( ChannelNioSocket.class );
private int startPort=8009;
private int maxPort=8019; // 0 for backward compat.
private int port=startPort;
private InetAddress inet;
private int serverTimeout = 0;
private boolean tcpNoDelay=true; // nodelay to true by default
private int linger=100;
private int socketTimeout = 0;
private boolean nioIsBroken = false;
private Selector selector = null;
private int bufferSize = 8*1024;
private int packetSize = 8*1024;
private long requestCount=0;
/* Turning this to true will reduce the latency with about 20%.
But it requires changes in tomcat to make sure client-requested
flush() is honored ( on my test, I got 367->433 RPS and
52->35ms average time with a simple servlet )
*/
ThreadPool tp=ThreadPool.createThreadPool(true);
/* ==================== Tcp socket options ==================== */
/**
* jmx:managed-constructor description="default constructor"
*/
public ChannelNioSocket() {
// This should be integrated with the domain setup
}
public ThreadPool getThreadPool() {
return tp;
}
public long getRequestCount() {
return requestCount;
}
/** Set the port for the ajp13 channel.
* To support seemless load balancing and jni, we treat this
* as the 'base' port - we'll try up until we find one that is not
* used. We'll also provide the 'difference' to the main coyote
* handler - that will be our 'sessionID' and the position in
* the scoreboard and the suffix for the unix domain socket.
*
* jmx:managed-attribute description="Port to listen" access="READ_WRITE"
*/
public void setPort( int port ) {
this.startPort=port;
this.port=port;
this.maxPort=port+10;
}
public int getPort() {
return port;
}
public void setAddress(InetAddress inet) {
this.inet=inet;
}
public void setBufferSize(int bs) {
if(bs > 8*1024) {
bufferSize = bs;
}
}
public int getBufferSize() {
return bufferSize;
}
public void setPacketSize(int ps) {
if(ps < 8*1024) {
ps = 8*1024;
}
packetSize = ps;
}
public int getPacketSize() {
return packetSize;
}
/**
* jmx:managed-attribute description="Bind on a specified address" access="READ_WRITE"
*/
public void setAddress(String inet) {
try {
this.inet= InetAddress.getByName( inet );
} catch( Exception ex ) {
log.error("Error parsing "+inet,ex);
}
}
public String getAddress() {
if( inet!=null)
return inet.toString();
return "/0.0.0.0";
}
/**
* Sets the timeout in ms of the server sockets created by this
* server. This method allows the developer to make servers
* more or less responsive to having their server sockets
* shut down.
*
* <p>By default this value is 1000ms.
*/
public void setServerTimeout(int timeout) {
this.serverTimeout = timeout;
}
public int getServerTimeout() {
return serverTimeout;
}
public void setTcpNoDelay( boolean b ) {
tcpNoDelay=b;
}
public boolean getTcpNoDelay() {
return tcpNoDelay;
}
public void setSoLinger( int i ) {
linger=i;
}
public int getSoLinger() {
return linger;
}
public void setSoTimeout( int i ) {
socketTimeout=i;
}
public int getSoTimeout() {
return socketTimeout;
}
public void setMaxPort( int i ) {
maxPort=i;
}
public int getMaxPort() {
return maxPort;
}
/** At startup we'll look for the first free port in the range.
The difference between this port and the beggining of the range
is the 'id'.
This is usefull for lb cases ( less config ).
*/
public int getInstanceId() {
return port-startPort;
}
/** If set to false, the thread pool will be created in
* non-daemon mode, and will prevent main from exiting
*/
public void setDaemon( boolean b ) {
tp.setDaemon( b );
}
public boolean getDaemon() {
return tp.getDaemon();
}
public void setMaxThreads( int i ) {
if( log.isDebugEnabled()) log.debug("Setting maxThreads " + i);
tp.setMaxThreads(i);
}
public void setMinSpareThreads( int i ) {
if( log.isDebugEnabled()) log.debug("Setting minSpareThreads " + i);
tp.setMinSpareThreads(i);
}
public void setMaxSpareThreads( int i ) {
if( log.isDebugEnabled()) log.debug("Setting maxSpareThreads " + i);
tp.setMaxSpareThreads(i);
}
public int getMaxThreads() {
return tp.getMaxThreads();
}
public int getMinSpareThreads() {
return tp.getMinSpareThreads();
}
public int getMaxSpareThreads() {
return tp.getMaxSpareThreads();
}
public void setBacklog(int i) {
}
public void setNioIsBroken(boolean nib) {
nioIsBroken = nib;
}
public boolean getNioIsBroken() {
return nioIsBroken;
}
/* ==================== ==================== */
ServerSocket sSocket;
final int socketNote=1;
final int isNote=2;
final int osNote=3;
final int notifNote=4;
boolean paused = false;
public void pause() throws Exception {
synchronized(this) {
paused = true;
}
}
public void resume() {
synchronized(this) {
paused = false;
notify();
}
}
public void accept( MsgContext ep ) throws IOException {
if( sSocket==null ) return;
synchronized(this) {
while(paused) {
try{
wait();
} catch(InterruptedException ie) {
//Ignore, since can't happen
}
}
}
SocketChannel sc=sSocket.getChannel().accept();
Socket s = sc.socket();
ep.setNote( socketNote, s );
if(log.isDebugEnabled() )
log.debug("Accepted socket " + s +" channel " + sc.isBlocking());
try {
setSocketOptions(s);
} catch(SocketException sex) {
log.debug("Error initializing Socket Options", sex);
}
requestCount++;
sc.configureBlocking(false);
InputStream is=new SocketInputStream(sc);
OutputStream os = new SocketOutputStream(sc);
ep.setNote( isNote, is );
ep.setNote( osNote, os );
ep.setControl( tp );
}
private void setSocketOptions(Socket s) throws SocketException {
if( socketTimeout > 0 )
s.setSoTimeout( socketTimeout );
s.setTcpNoDelay( tcpNoDelay ); // set socket tcpnodelay state
if( linger > 0 )
s.setSoLinger( true, linger);
}
public void resetCounters() {
requestCount=0;
}
/** Called after you change some fields at runtime using jmx.
Experimental for now.
*/
public void reinit() throws IOException {
destroy();
init();
}
/**
* jmx:managed-operation
*/
public void init() throws IOException {
// Find a port.
if (startPort == 0) {
port = 0;
if(log.isInfoEnabled())
log.info("JK: ajp13 disabling channelNioSocket");
running = true;
return;
}
if (maxPort < startPort)
maxPort = startPort;
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
for( int i=startPort; i<=maxPort; i++ ) {
try {
InetSocketAddress iddr = null;
if( inet == null ) {
iddr = new InetSocketAddress( i);
} else {
iddr=new InetSocketAddress( inet, i);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -