Support the usage of SocketOption when nio is used and the java versi… (#8085)

* Support the usage of SocketOption when nio is used and the java version >= 7.

Motivation:

The JDK uses SocketOption since java7 to support configuration options on the underyling Channel. We should allow to create a ChannelOption from a given SocketOption if nio is used. This also allows us to expose the same featureset in terms of configuration as the java nio implementation does without any extra effort.

Modifications:

- Add NioChannelOption which allows to wrap an existing SocketOption which then can be applied to the nio transport.
- Add test-cases

Result:

Support the same configuration options as the JDK. Also fixes https://github.com/netty/netty/issues/8072.
This commit is contained in:
Norman Maurer 2018-07-25 12:32:28 +08:00 committed by GitHub
parent 77ec839792
commit 952eeb8e1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 303 additions and 9 deletions

View File

@ -702,6 +702,8 @@
<ignore>java.nio.channels.SocketChannel</ignore> <ignore>java.nio.channels.SocketChannel</ignore>
<ignore>java.net.StandardProtocolFamily</ignore> <ignore>java.net.StandardProtocolFamily</ignore>
<ignore>java.nio.channels.spi.SelectorProvider</ignore> <ignore>java.nio.channels.spi.SelectorProvider</ignore>
<ignore>java.net.SocketOption</ignore>
<ignore>java.nio.channels.NetworkChannel</ignore>
<!-- Self-signed certificate generation --> <!-- Self-signed certificate generation -->
<ignore>sun.security.x509.AlgorithmId</ignore> <ignore>sun.security.x509.AlgorithmId</ignore>

View File

@ -0,0 +1,82 @@
/*
* Copyright 2018 The Netty Project
*
* The Netty Project 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 io.netty.channel.socket.nio;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import java.io.IOException;
import java.net.SocketOption;
import java.nio.channels.NetworkChannel;
import java.util.Set;
/**
* Provides {@link ChannelOption} over a given {@link SocketOption} which is then passed through the underlying
* {@link NetworkChannel}.
*/
public final class NioChannelOption<T> extends ChannelOption<T> {
private final SocketOption<T> option;
@SuppressWarnings("deprecation")
private NioChannelOption(SocketOption<T> option) {
super(option.name());
this.option = option;
}
/**
* Returns a {@link ChannelOption} for the given {@link SocketOption}.
*/
public static <T> ChannelOption<T> of(SocketOption<T> option) {
return new NioChannelOption<T>(option);
}
// Internal helper methods to remove code duplication between Nio*Channel implementations.
static <T> boolean setOption(NetworkChannel channel, NioChannelOption<T> option, T value) {
if (!channel.supportedOptions().contains(option.option)) {
return false;
}
try {
channel.setOption(option.option, value);
return true;
} catch (IOException e) {
throw new ChannelException(e);
}
}
static <T> T getOption(NetworkChannel channel, NioChannelOption<T> option) {
if (!channel.supportedOptions().contains(option.option)) {
return null;
}
try {
return channel.getOption(option.option);
} catch (IOException e) {
throw new ChannelException(e);
}
}
@SuppressWarnings("unchecked")
static ChannelOption[] getOptions(NetworkChannel channel) {
Set<SocketOption<?>> supportedOpts = channel.supportedOptions();
ChannelOption<?>[] extraOpts = new ChannelOption[supportedOpts.size()];
int i = 0;
for (SocketOption<?> opt : supportedOpts) {
extraOpts[i++] = new NioChannelOption(opt);
}
return extraOpts;
}
}

View File

@ -16,6 +16,7 @@
package io.netty.channel.socket.nio; package io.netty.channel.socket.nio;
import io.netty.channel.ChannelException; import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.DatagramChannelConfig; import io.netty.channel.socket.DatagramChannelConfig;
import io.netty.channel.socket.DefaultDatagramChannelConfig; import io.netty.channel.socket.DefaultDatagramChannelConfig;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
@ -27,6 +28,7 @@ import java.net.NetworkInterface;
import java.net.SocketException; import java.net.SocketException;
import java.nio.channels.DatagramChannel; import java.nio.channels.DatagramChannel;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Map;
/** /**
* The default {@link NioDatagramChannelConfig} implementation. * The default {@link NioDatagramChannelConfig} implementation.
@ -205,4 +207,29 @@ class NioDatagramChannelConfig extends DefaultDatagramChannelConfig {
} }
} }
} }
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
if (PlatformDependent.javaVersion() >= 7 && option instanceof NioChannelOption) {
return NioChannelOption.setOption(javaChannel, (NioChannelOption<T>) option, value);
}
return super.setOption(option, value);
}
@Override
public <T> T getOption(ChannelOption<T> option) {
if (PlatformDependent.javaVersion() >= 7 && option instanceof NioChannelOption) {
return NioChannelOption.getOption(javaChannel, (NioChannelOption<T>) option);
}
return super.getOption(option);
}
@SuppressWarnings("unchecked")
@Override
public Map<ChannelOption<?>, Object> getOptions() {
if (PlatformDependent.javaVersion() >= 7) {
return getOptions(super.getOptions(), NioChannelOption.getOptions(javaChannel));
}
return super.getOptions();
}
} }

View File

@ -17,6 +17,7 @@ package io.netty.channel.socket.nio;
import io.netty.channel.ChannelException; import io.netty.channel.ChannelException;
import io.netty.channel.ChannelMetadata; import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelOutboundBuffer;
import io.netty.util.internal.SocketUtils; import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioMessageChannel; import io.netty.channel.nio.AbstractNioMessageChannel;
@ -35,6 +36,7 @@ import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider; import java.nio.channels.spi.SelectorProvider;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* A {@link io.netty.channel.socket.ServerSocketChannel} implementation which uses * A {@link io.netty.channel.socket.ServerSocketChannel} implementation which uses
@ -199,6 +201,35 @@ public class NioServerSocketChannel extends AbstractNioMessageChannel
protected void autoReadCleared() { protected void autoReadCleared() {
clearReadPending(); clearReadPending();
} }
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
if (PlatformDependent.javaVersion() >= 7 && option instanceof NioChannelOption) {
return NioChannelOption.setOption(jdkChannel(), (NioChannelOption<T>) option, value);
}
return super.setOption(option, value);
}
@Override
public <T> T getOption(ChannelOption<T> option) {
if (PlatformDependent.javaVersion() >= 7 && option instanceof NioChannelOption) {
return NioChannelOption.getOption(jdkChannel(), (NioChannelOption<T>) option);
}
return super.getOption(option);
}
@SuppressWarnings("unchecked")
@Override
public Map<ChannelOption<?>, Object> getOptions() {
if (PlatformDependent.javaVersion() >= 7) {
return getOptions(super.getOptions(), NioChannelOption.getOptions(jdkChannel()));
}
return super.getOptions();
}
private ServerSocketChannel jdkChannel() {
return ((NioServerSocketChannel) channel).javaChannel();
}
} }
// Override just to to be able to call directly via unit tests. // Override just to to be able to call directly via unit tests.

View File

@ -20,6 +20,7 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelException; import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundBuffer; import io.netty.channel.ChannelOutboundBuffer;
import io.netty.channel.ChannelPromise; import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop; import io.netty.channel.EventLoop;
@ -44,6 +45,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey; import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider; import java.nio.channels.spi.SelectorProvider;
import java.util.Map;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import static io.netty.channel.internal.ChannelUtils.MAX_BYTES_PER_GATHERING_WRITE_ATTEMPTED_LOW_THRESHOLD; import static io.netty.channel.internal.ChannelUtils.MAX_BYTES_PER_GATHERING_WRITE_ATTEMPTED_LOW_THRESHOLD;
@ -461,7 +463,6 @@ public class NioSocketChannel extends AbstractNioByteChannel implements io.netty
private final class NioSocketChannelConfig extends DefaultSocketChannelConfig { private final class NioSocketChannelConfig extends DefaultSocketChannelConfig {
private volatile int maxBytesPerGatheringWrite = Integer.MAX_VALUE; private volatile int maxBytesPerGatheringWrite = Integer.MAX_VALUE;
private NioSocketChannelConfig(NioSocketChannel channel, Socket javaSocket) { private NioSocketChannelConfig(NioSocketChannel channel, Socket javaSocket) {
super(channel, javaSocket); super(channel, javaSocket);
calculateMaxBytesPerGatheringWrite(); calculateMaxBytesPerGatheringWrite();
@ -479,6 +480,31 @@ public class NioSocketChannel extends AbstractNioByteChannel implements io.netty
return this; return this;
} }
@Override
public <T> boolean setOption(ChannelOption<T> option, T value) {
if (PlatformDependent.javaVersion() >= 7 && option instanceof NioChannelOption) {
return NioChannelOption.setOption(jdkChannel(), (NioChannelOption<T>) option, value);
}
return super.setOption(option, value);
}
@Override
public <T> T getOption(ChannelOption<T> option) {
if (PlatformDependent.javaVersion() >= 7 && option instanceof NioChannelOption) {
return NioChannelOption.getOption(jdkChannel(), (NioChannelOption<T>) option);
}
return super.getOption(option);
}
@SuppressWarnings("unchecked")
@Override
public Map<ChannelOption<?>, Object> getOptions() {
if (PlatformDependent.javaVersion() >= 7) {
return getOptions(super.getOptions(), NioChannelOption.getOptions(jdkChannel()));
}
return super.getOptions();
}
void setMaxBytesPerGatheringWrite(int maxBytesPerGatheringWrite) { void setMaxBytesPerGatheringWrite(int maxBytesPerGatheringWrite) {
this.maxBytesPerGatheringWrite = maxBytesPerGatheringWrite; this.maxBytesPerGatheringWrite = maxBytesPerGatheringWrite;
} }
@ -494,5 +520,9 @@ public class NioSocketChannel extends AbstractNioByteChannel implements io.netty
setMaxBytesPerGatheringWrite(getSendBufferSize() << 1); setMaxBytesPerGatheringWrite(getSendBufferSize() << 1);
} }
} }
private SocketChannel jdkChannel() {
return ((NioSocketChannel) channel).javaChannel();
}
} }
} }

View File

@ -0,0 +1,69 @@
/*
* Copyright 2018 The Netty Project
*
* The Netty Project 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 io.netty.channel.socket.nio;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.AbstractNioChannel;
import org.junit.Test;
import java.io.IOException;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.nio.channels.NetworkChannel;
import static org.junit.Assert.*;
public abstract class AbstractNioChannelTest<T extends AbstractNioChannel> {
protected abstract T newNioChannel();
protected abstract NetworkChannel jdkChannel(T channel);
protected abstract SocketOption<?> newInvalidOption();
@Test
public void testNioChannelOption() throws IOException {
T channel = newNioChannel();
try {
NetworkChannel jdkChannel = jdkChannel(channel);
ChannelOption<Boolean> option = NioChannelOption.of(StandardSocketOptions.SO_REUSEADDR);
boolean value1 = jdkChannel.getOption(StandardSocketOptions.SO_REUSEADDR);
boolean value2 = channel.config().getOption(option);
assertEquals(value1, value2);
channel.config().setOption(option, !value2);
boolean value3 = jdkChannel.getOption(StandardSocketOptions.SO_REUSEADDR);
boolean value4 = channel.config().getOption(option);
assertEquals(value3, value4);
assertNotEquals(value1, value4);
} finally {
channel.unsafe().closeForcibly();
}
}
@Test
public void testInvalidNioChannelOption() {
T channel = newNioChannel();
try {
ChannelOption<?> option = NioChannelOption.of(newInvalidOption());
assertFalse(channel.config().setOption(option, null));
assertNull(channel.config().getOption(option));
} finally {
channel.unsafe().closeForcibly();
}
}
}

View File

@ -13,24 +13,27 @@
* License for the specific language governing permissions and limitations * License for the specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package io.netty.channel.nio; package io.netty.channel.socket.nio;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption; import io.netty.channel.ChannelOption;
import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.GlobalEventExecutor;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.nio.channels.NetworkChannel;
public class NioDatagramChannelTest { public class NioDatagramChannelTest extends AbstractNioChannelTest<NioDatagramChannel> {
/** /**
* Test try to reproduce issue #1335 * Test try to reproduce issue #1335
@ -61,4 +64,19 @@ public class NioDatagramChannelTest {
group.shutdownGracefully().sync(); group.shutdownGracefully().sync();
} }
} }
@Override
protected NioDatagramChannel newNioChannel() {
return new NioDatagramChannel();
}
@Override
protected NetworkChannel jdkChannel(NioDatagramChannel channel) {
return channel.javaChannel();
}
@Override
protected SocketOption<?> newInvalidOption() {
return StandardSocketOptions.TCP_NODELAY;
}
} }

View File

@ -22,9 +22,12 @@ import org.junit.Test;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.nio.channels.NetworkChannel;
import java.nio.channels.ServerSocketChannel; import java.nio.channels.ServerSocketChannel;
public class NioServerSocketChannelTest { public class NioServerSocketChannelTest extends AbstractNioChannelTest<NioServerSocketChannel> {
@Test @Test
public void testCloseOnError() throws Exception { public void testCloseOnError() throws Exception {
@ -41,4 +44,19 @@ public class NioServerSocketChannelTest {
group.shutdownGracefully(); group.shutdownGracefully();
} }
} }
@Override
protected NioServerSocketChannel newNioChannel() {
return new NioServerSocketChannel();
}
@Override
protected NetworkChannel jdkChannel(NioServerSocketChannel channel) {
return channel.javaChannel();
}
@Override
protected SocketOption<?> newInvalidOption() {
return StandardSocketOptions.IP_MULTICAST_IF;
}
} }

View File

@ -13,7 +13,7 @@
* License for the specific language governing permissions and limitations * License for the specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package io.netty.channel.nio; package io.netty.channel.socket.nio;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap; import io.netty.bootstrap.ServerBootstrap;
@ -30,9 +30,8 @@ import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoop; import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil; import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil; import io.netty.util.NetUtil;
import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.PlatformDependent;
@ -46,7 +45,10 @@ import java.net.InetSocketAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedChannelException;
import java.nio.channels.NetworkChannel;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@ -55,7 +57,7 @@ import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class NioSocketChannelTest { public class NioSocketChannelTest extends AbstractNioChannelTest<NioSocketChannel> {
/** /**
* Reproduces the issue #1600 * Reproduces the issue #1600
@ -278,4 +280,19 @@ public class NioSocketChannelTest {
group.shutdownGracefully(); group.shutdownGracefully();
} }
} }
@Override
protected NioSocketChannel newNioChannel() {
return new NioSocketChannel();
}
@Override
protected NetworkChannel jdkChannel(NioSocketChannel channel) {
return channel.javaChannel();
}
@Override
protected SocketOption<?> newInvalidOption() {
return StandardSocketOptions.IP_MULTICAST_IF;
}
} }