Remove UDT transport for Netty 5. (#8578)

Motivation:

The UDT transport was marked as @Deprecated a long time ago as the underlying native library is not really maintained anymore. We should remove it as part of Netty 5.

Modifications:

Remove UDT transport

Result:

Dont try to maintain a transport which uses an unmaintained native lib internally.
This commit is contained in:
Norman Maurer 2018-11-20 19:26:20 +01:00 committed by GitHub
parent 4891f1183d
commit e4fae1c98e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
76 changed files with 0 additions and 6166 deletions

View File

@ -455,13 +455,6 @@
<scope>compile</scope> <scope>compile</scope>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-transport-udt</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>netty-example</artifactId> <artifactId>netty-example</artifactId>

View File

@ -176,11 +176,6 @@
<artifactId>netty-transport-sctp</artifactId> <artifactId>netty-transport-sctp</artifactId>
<version>5.0.0.Final-SNAPSHOT</version> <version>5.0.0.Final-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-udt</artifactId>
<version>5.0.0.Final-SNAPSHOT</version>
</dependency>
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-example</artifactId> <artifactId>netty-example</artifactId>

View File

@ -114,11 +114,6 @@
<groupId>com.yammer.metrics</groupId> <groupId>com.yammer.metrics</groupId>
<artifactId>metrics-core</artifactId> <artifactId>metrics-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-transport-udt</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>netty-transport-rxtx</artifactId> <artifactId>netty-transport-rxtx</artifactId>

View File

@ -1,71 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.bytes;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.util.concurrent.ThreadFactory;
/**
* UDT Byte Stream Client
* <p>
* Sends one message when a connection is open and echoes back any received data
* to the server. Simply put, the echo client initiates the ping-pong traffic
* between the echo client and server by sending the first message to the
* server.
*/
public final class ByteEchoClient {
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
public static void main(String[] args) throws Exception {
// Configure the client.
final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
connectFactory, NioUdtProvider.BYTE_PROVIDER);
try {
final Bootstrap boot = new Bootstrap();
boot.group(connectGroup)
.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(final UdtChannel ch)
throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new ByteEchoClientHandler());
}
});
// Start the client.
final ChannelFuture f = boot.connect(HOST, PORT).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
connectGroup.shutdownGracefully();
}
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.bytes;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo client. It initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server on activation.
*/
public class ByteEchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final ByteBuf message;
public ByteEchoClientHandler() {
super(false);
message = Unpooled.buffer(ByteEchoClient.SIZE);
for (int i = 0; i < message.capacity(); i++) {
message.writeByte((byte) i);
}
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

View File

@ -1,72 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.bytes;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.util.concurrent.ThreadFactory;
/**
* UDT Byte Stream Server
* <p>
* Echoes back any received data from a client.
*/
public final class ByteEchoServer {
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
public static void main(String[] args) throws Exception {
final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER);
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory, NioUdtProvider.BYTE_PROVIDER);
// Configure the server.
try {
final ServerBootstrap boot = new ServerBootstrap();
boot.group(acceptGroup, connectGroup)
.channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
.option(ChannelOption.SO_BACKLOG, 10)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(final UdtChannel ch)
throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new ByteEchoServerHandler());
}
});
// Start the server.
final ChannelFuture future = boot.bind(PORT).sync();
// Wait until the server socket is closed.
future.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
acceptGroup.shutdownGracefully();
connectGroup.shutdownGracefully();
}
}
}

View File

@ -1,49 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.bytes;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo server.
*/
@Sharable
public class ByteEchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Examples show how to use UDT Byte Streams.
*/
package io.netty.example.udt.echo.bytes;

View File

@ -1,75 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Logger;
/**
* UDT Message Flow client
* <p>
* Sends one message when a connection is open and echoes back any received data
* to the server. Simply put, the echo client initiates the ping-pong traffic
* between the echo client and server by sending the first message to the
* server.
*/
public final class MsgEchoClient {
private static final Logger log = Logger.getLogger(MsgEchoClient.class.getName());
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
public static void main(String[] args) throws Exception {
// Configure the client.
final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
connectFactory, NioUdtProvider.MESSAGE_PROVIDER);
try {
final Bootstrap boot = new Bootstrap();
boot.group(connectGroup)
.channelFactory(NioUdtProvider.MESSAGE_CONNECTOR)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(final UdtChannel ch)
throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new MsgEchoClientHandler());
}
});
// Start the client.
final ChannelFuture f = boot.connect(HOST, PORT).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
connectGroup.shutdownGracefully();
}
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.udt.UdtMessage;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo client. It initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server on activation.
*/
public class MsgEchoClientHandler extends SimpleChannelInboundHandler<UdtMessage> {
private final UdtMessage message;
public MsgEchoClientHandler() {
super(false);
final ByteBuf byteBuf = Unpooled.buffer(MsgEchoClient.SIZE);
for (int i = 0; i < byteBuf.capacity(); i++) {
byteBuf.writeByte((byte) i);
}
message = new UdtMessage(byteBuf);
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, UdtMessage msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

View File

@ -1,74 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.message;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.util.concurrent.ThreadFactory;
/**
* UDT Message Flow Server
* <p>
* Echoes back any received data from a client.
*/
public final class MsgEchoServer {
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
public static void main(String[] args) throws Exception {
final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
final NioEventLoopGroup acceptGroup =
new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.MESSAGE_PROVIDER);
final NioEventLoopGroup connectGroup =
new NioEventLoopGroup(1, connectFactory, NioUdtProvider.MESSAGE_PROVIDER);
// Configure the server.
try {
final ServerBootstrap boot = new ServerBootstrap();
boot.group(acceptGroup, connectGroup)
.channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR)
.option(ChannelOption.SO_BACKLOG, 10)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(final UdtChannel ch)
throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new MsgEchoServerHandler());
}
});
// Start the server.
final ChannelFuture future = boot.bind(PORT).sync();
// Wait until the server socket is closed.
future.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
acceptGroup.shutdownGracefully();
connectGroup.shutdownGracefully();
}
}
}

View File

@ -1,49 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.message;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo server.
*/
@Sharable
public class MsgEchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Examples show how to use UDT Message Flows.
*/
package io.netty.example.udt.echo.message;

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Examples show how to use UDT with simple Echo Handlers.
*/
package io.netty.example.udt.echo;

View File

@ -1,32 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvous;
/**
* Peer to Peer Config
*/
public final class Config {
private Config() {
}
public static final String hostOne = "localhost";
public static final int portOne = 1231;
public static final String hostTwo = "localhost";
public static final int portTwo = 1232;
}

View File

@ -1,76 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvous;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.ThreadFactory;
/**
* UDT Message Flow Peer
* <p>
* Sends one message when a connection is open and echoes back any received data
* to the other peer.
*/
public abstract class MsgEchoPeerBase {
protected final int messageSize;
protected final InetSocketAddress self;
protected final InetSocketAddress peer;
protected MsgEchoPeerBase(final InetSocketAddress self, final InetSocketAddress peer, final int messageSize) {
this.messageSize = messageSize;
this.self = self;
this.peer = peer;
}
public void run() throws Exception {
// Configure the peer.
final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
connectFactory, NioUdtProvider.MESSAGE_PROVIDER);
try {
final Bootstrap boot = new Bootstrap();
boot.group(connectGroup)
.channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(final UdtChannel ch)
throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new MsgEchoPeerHandler(messageSize));
}
});
// Start the peer.
final ChannelFuture f = boot.connect(peer, self).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
connectGroup.shutdownGracefully();
}
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvous;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.udt.UdtMessage;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo peer. It initiates the ping-pong traffic
* between the echo peers by sending the first message to the other peer on
* activation.
*/
public class MsgEchoPeerHandler extends SimpleChannelInboundHandler<UdtMessage> {
private final UdtMessage message;
public MsgEchoPeerHandler(final int messageSize) {
super(false);
final ByteBuf byteBuf = Unpooled.buffer(messageSize);
for (int i = 0; i < byteBuf.capacity(); i++) {
byteBuf.writeByte((byte) i);
}
message = new UdtMessage(byteBuf);
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, UdtMessage message) {
ctx.write(message);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvous;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
/**
* UDT Message Flow Peer
* <p>
* Sends one message when a connection is open and echoes back any received data
* to the other peer.
*/
public class MsgEchoPeerOne extends MsgEchoPeerBase {
public MsgEchoPeerOne(final InetSocketAddress self, final InetSocketAddress peer, final int messageSize) {
super(self, peer, messageSize);
}
public static void main(final String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress self = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress peer = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
new MsgEchoPeerOne(self, peer, messageSize).run();
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvous;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
/**
* UDT Message Flow Peer
* <p>
* Sends one message when a connection is open and echoes back any received data
* to the other peer.
*/
public class MsgEchoPeerTwo extends MsgEchoPeerBase {
public MsgEchoPeerTwo(final InetSocketAddress self, final InetSocketAddress peer, final int messageSize) {
super(self, peer, messageSize);
}
public static void main(final String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress self = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress peer = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
new MsgEchoPeerTwo(self, peer, messageSize).run();
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Examples show how to use UDT Message Rendezvous.
*/
package io.netty.example.udt.echo.rendezvous;

View File

@ -1,74 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvousBytes;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import java.net.SocketAddress;
import java.util.concurrent.ThreadFactory;
/**
* UDT Byte Stream Peer
* <p/>
* Sends one message when a connection is open and echoes back any received data
* to the server. Simply put, the echo client initiates the ping-pong traffic
* between the echo client and server by sending the first message to the
* server.
* <p/>
*/
public class ByteEchoPeerBase {
protected final int messageSize;
protected final SocketAddress myAddress;
protected final SocketAddress peerAddress;
public ByteEchoPeerBase(int messageSize, SocketAddress myAddress, SocketAddress peerAddress) {
this.messageSize = messageSize;
this.myAddress = myAddress;
this.peerAddress = peerAddress;
}
public void run() throws Exception {
final ThreadFactory connectFactory = new DefaultThreadFactory("rendezvous");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
connectFactory, NioUdtProvider.BYTE_PROVIDER);
try {
final Bootstrap bootstrap = new Bootstrap();
bootstrap.group(connectGroup)
.channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
protected void initChannel(UdtChannel ch) throws Exception {
ch.pipeline().addLast(
new LoggingHandler(LogLevel.INFO),
new ByteEchoPeerHandler(messageSize));
}
});
final ChannelFuture future = bootstrap.connect(peerAddress, myAddress).sync();
future.channel().closeFuture().sync();
} finally {
connectGroup.shutdownGracefully();
}
}
}

View File

@ -1,62 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvousBytes;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* Handler implementation for the echo client. It initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server on activation.
*/
public class ByteEchoPeerHandler extends SimpleChannelInboundHandler<ByteBuf> {
private final ByteBuf message;
public ByteEchoPeerHandler(final int messageSize) {
super(false);
message = Unpooled.buffer(messageSize);
for (int i = 0; i < message.capacity(); i++) {
message.writeByte((byte) i);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.err.println("ECHO active " + NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) {
ctx.write(buf);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}

View File

@ -1,45 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvousBytes;
import io.netty.example.udt.echo.rendezvous.Config;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
/**
* UDT Byte Stream Peer
* <p/>
* Sends one message when a connection is open and echoes back any received data
* to the server. Simply put, the echo client initiates the ping-pong traffic
* between the echo client and server by sending the first message to the
* server.
* <p/>
*/
public class ByteEchoPeerOne extends ByteEchoPeerBase {
public ByteEchoPeerOne(int messageSize, SocketAddress myAddress, SocketAddress peerAddress) {
super(messageSize, myAddress, peerAddress);
}
public static void main(String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress myAddress = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
final InetSocketAddress peerAddress = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
new ByteEchoPeerOne(messageSize, myAddress, peerAddress).run();
}
}

View File

@ -1,45 +0,0 @@
/*
* Copyright 2012 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.example.udt.echo.rendezvousBytes;
import io.netty.example.udt.echo.rendezvous.Config;
import io.netty.util.internal.SocketUtils;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
/**
* UDT Byte Stream Peer
* <p/>
* Sends one message when a connection is open and echoes back any received data
* to the server. Simply put, the echo client initiates the ping-pong traffic
* between the echo client and server by sending the first message to the
* server.
* <p/>
*/
public class ByteEchoPeerTwo extends ByteEchoPeerBase {
public ByteEchoPeerTwo(int messageSize, SocketAddress myAddress, SocketAddress peerAddress) {
super(messageSize, myAddress, peerAddress);
}
public static void main(String[] args) throws Exception {
final int messageSize = 64 * 1024;
final InetSocketAddress myAddress = SocketUtils.socketAddress(Config.hostTwo, Config.portTwo);
final InetSocketAddress peerAddress = SocketUtils.socketAddress(Config.hostOne, Config.portOne);
new ByteEchoPeerTwo(messageSize, myAddress, peerAddress).run();
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Examples show how to use UDT Byte Streams Rendezvous.
*/
package io.netty.example.udt.echo.rendezvousBytes;

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Examples show how to use UDT.
*/
package io.netty.example.udt;

View File

@ -292,7 +292,6 @@
<module>transport-native-kqueue</module> <module>transport-native-kqueue</module>
<module>transport-rxtx</module> <module>transport-rxtx</module>
<module>transport-sctp</module> <module>transport-sctp</module>
<module>transport-udt</module>
<module>handler</module> <module>handler</module>
<module>handler-proxy</module> <module>handler-proxy</module>
<module>example</module> <module>example</module>
@ -449,12 +448,6 @@
<version>2.1.7</version> <version>2.1.7</version>
</dependency> </dependency>
<dependency>
<groupId>com.barchart.udt</groupId>
<artifactId>barchart-udt-bundle</artifactId>
<version>2.3.0</version>
</dependency>
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId> <artifactId>servlet-api</artifactId>

View File

@ -157,12 +157,6 @@
<version>${project.version}</version> <version>${project.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-transport-udt</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.ops4j.pax.exam</groupId> <groupId>org.ops4j.pax.exam</groupId>

View File

@ -94,7 +94,6 @@ public class OsgiBundleTest {
options.add(systemProperty("pax.exam.osgi.unresolved.fail").value("true")); options.add(systemProperty("pax.exam.osgi.unresolved.fail").value("true"));
options.addAll(Arrays.asList(junitBundles())); options.addAll(Arrays.asList(junitBundles()));
options.add(mavenBundle("com.barchart.udt", "barchart-udt-bundle").versionAsInProject());
options.add(wrappedBundle(mavenBundle("org.rxtx", "rxtx").versionAsInProject())); options.add(wrappedBundle(mavenBundle("org.rxtx", "rxtx").versionAsInProject()));
for (String name : BUNDLES) { for (String name : BUNDLES) {

View File

@ -44,11 +44,6 @@
<artifactId>netty-codec-http</artifactId> <artifactId>netty-codec-http</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-udt</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>${tcnative.artifactId}</artifactId> <artifactId>${tcnative.artifactId}</artifactId>

View File

@ -1,383 +0,0 @@
/*
* Copyright 2012 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.testsuite.transport.udt;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.NetUtil;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.ThreadFactory;
import static org.junit.Assert.*;
/**
* Verify UDT connect/disconnect life cycle.
*/
public class UDTClientServerConnectionTest {
static class Client implements Runnable {
static final Logger log = LoggerFactory.getLogger(Client.class);
private final InetSocketAddress address;
volatile Channel channel;
volatile boolean isRunning;
volatile boolean isShutdown;
Client(InetSocketAddress address) {
this.address = address;
}
@Override
public void run() {
final Bootstrap boot = new Bootstrap();
final ThreadFactory clientFactory = new DefaultThreadFactory("client");
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
clientFactory, NioUdtProvider.BYTE_PROVIDER);
try {
boot.group(connectGroup)
.channelFactory(NioUdtProvider.BYTE_CONNECTOR)
.handler(new ChannelInitializer<UdtChannel>() {
@Override
protected void initChannel(final UdtChannel ch)
throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framer",
new DelimiterBasedFrameDecoder(8192,
Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder(
CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(
CharsetUtil.UTF_8));
pipeline.addLast("handler", new ClientHandler());
}
});
channel = boot.connect(address).sync().channel();
isRunning = true;
log.info("Client ready.");
waitForRunning(false);
log.info("Client closing...");
channel.close().sync();
isShutdown = true;
log.info("Client is done.");
} catch (final Throwable e) {
log.error("Client failed.", e);
} finally {
connectGroup.shutdownGracefully().syncUninterruptibly();
}
}
void shutdown() {
isRunning = false;
}
void waitForActive(final boolean isActive) throws Exception {
for (int k = 0; k < WAIT_COUNT; k++) {
Thread.sleep(WAIT_SLEEP);
final ClientHandler handler = channel.pipeline().get(
ClientHandler.class);
if (handler != null && isActive == handler.isActive) {
return;
}
}
}
void waitForRunning(final boolean isRunning) throws Exception {
for (int k = 0; k < WAIT_COUNT; k++) {
if (isRunning == this.isRunning) {
return;
}
Thread.sleep(WAIT_SLEEP);
}
}
private void waitForShutdown() throws Exception {
for (int k = 0; k < WAIT_COUNT; k++) {
if (isShutdown) {
return;
}
Thread.sleep(WAIT_SLEEP);
}
}
}
static class ClientHandler extends SimpleChannelInboundHandler<Object> {
static final Logger log = LoggerFactory.getLogger(ClientHandler.class);
volatile boolean isActive;
@Override
public void channelActive(final ChannelHandlerContext ctx)
throws Exception {
isActive = true;
log.info("Client active {}", ctx.channel());
super.channelActive(ctx);
}
@Override
public void channelInactive(final ChannelHandlerContext ctx)
throws Exception {
isActive = false;
log.info("Client inactive {}", ctx.channel());
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx,
final Throwable cause) throws Exception {
log.warn("Client unexpected exception from downstream.", cause);
ctx.close();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("Client received: " + msg);
}
}
static class Server implements Runnable {
static final Logger log = LoggerFactory.getLogger(Server.class);
final ChannelGroup group = new DefaultChannelGroup("server group", GlobalEventExecutor.INSTANCE);
private final InetSocketAddress address;
volatile Channel channel;
volatile boolean isRunning;
volatile boolean isShutdown;
Server(InetSocketAddress address) {
this.address = address;
}
@Override
public void run() {
final ServerBootstrap boot = new ServerBootstrap();
final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
final ThreadFactory serverFactory = new DefaultThreadFactory("server");
final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1,
acceptFactory, NioUdtProvider.BYTE_PROVIDER);
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1,
serverFactory, NioUdtProvider.BYTE_PROVIDER);
try {
boot.group(acceptGroup, connectGroup)
.channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
.childHandler(new ChannelInitializer<UdtChannel>() {
@Override
protected void initChannel(final UdtChannel ch)
throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framer",
new DelimiterBasedFrameDecoder(8192,
Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder(
CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(
CharsetUtil.UTF_8));
pipeline.addLast("handler", new ServerHandler(
group));
}
});
channel = boot.bind(address).sync().channel();
isRunning = true;
log.info("Server ready.");
waitForRunning(false);
log.info("Server closing acceptor...");
channel.close().sync();
log.info("Server closing connectors...");
group.close().sync();
isShutdown = true;
log.info("Server is done.");
} catch (final Throwable e) {
log.error("Server failure.", e);
} finally {
acceptGroup.shutdownGracefully();
connectGroup.shutdownGracefully();
acceptGroup.terminationFuture().syncUninterruptibly();
connectGroup.terminationFuture().syncUninterruptibly();
}
}
void shutdown() {
isRunning = false;
}
void waitForActive(final boolean isActive) throws Exception {
for (int k = 0; k < WAIT_COUNT; k++) {
Thread.sleep(WAIT_SLEEP);
if (isActive) {
for (final Channel channel : group) {
final ServerHandler handler = channel.pipeline().get(
ServerHandler.class);
if (handler != null && handler.isActive) {
return;
}
}
} else {
if (group.isEmpty()) {
return;
}
}
}
}
void waitForRunning(final boolean isRunning) throws Exception {
for (int k = 0; k < WAIT_COUNT; k++) {
if (isRunning == this.isRunning) {
return;
}
Thread.sleep(WAIT_SLEEP);
}
}
void waitForShutdown() throws Exception {
for (int k = 0; k < WAIT_COUNT; k++) {
if (isShutdown) {
return;
}
Thread.sleep(WAIT_SLEEP);
}
}
}
static class ServerHandler extends
SimpleChannelInboundHandler<Object> {
static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
final ChannelGroup group;
volatile boolean isActive;
ServerHandler(final ChannelGroup group) {
this.group = group;
}
@Override
public void channelActive(final ChannelHandlerContext ctx)
throws Exception {
group.add(ctx.channel());
isActive = true;
log.info("Server active : {}", ctx.channel());
super.channelActive(ctx);
}
@Override
public void channelInactive(final ChannelHandlerContext ctx)
throws Exception {
group.remove(ctx.channel());
isActive = false;
log.info("Server inactive: {}", ctx.channel());
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx,
final Throwable cause) {
log.warn("Server close on exception.", cause);
ctx.close();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("Server received: " + msg);
}
}
static final Logger log = LoggerFactory
.getLogger(UDTClientServerConnectionTest.class);
/**
* Maximum wait time is 5 seconds.
* <p>
* wait-time = {@code WAIT_COUNT} * {@value #WAIT_SLEEP}
*/
static final int WAIT_COUNT = 50;
static final int WAIT_SLEEP = 100;
/**
* Verify UDT client/server connect and disconnect.
*/
@Test
public void connection() throws Exception {
log.info("Starting server.");
// Using LOCALHOST4 as UDT transport does not support IPV6 :(
final Server server = new Server(new InetSocketAddress(NetUtil.LOCALHOST4, 0));
final Thread serverTread = new Thread(server, "server-*");
serverTread.start();
server.waitForRunning(true);
assertTrue(server.isRunning);
log.info("Starting client.");
final Client client = new Client((InetSocketAddress) server.channel.localAddress());
final Thread clientThread = new Thread(client, "client-*");
clientThread.start();
client.waitForRunning(true);
assertTrue(client.isRunning);
log.info("Wait till connection is active.");
client.waitForActive(true);
server.waitForActive(true);
log.info("Verify connection is active.");
assertEquals("group must have one", 1, server.group.size());
log.info("Stopping client.");
client.shutdown();
client.waitForShutdown();
assertTrue(client.isShutdown);
log.info("Wait till connection is inactive.");
client.waitForActive(false);
server.waitForActive(false);
log.info("Verify connection is inactive.");
assertEquals("group must be empty", 0, server.group.size());
log.info("Stopping server.");
server.shutdown();
server.waitForShutdown();
assertTrue(server.isShutdown);
log.info("Finished server.");
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* Test suite classes for UDT.
*/
package io.netty.testsuite.transport.udt;

View File

@ -1,7 +0,0 @@
#
# native udt library extract location
#
/lib

View File

@ -1,86 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2012 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.netty</groupId>
<artifactId>netty-parent</artifactId>
<version>5.0.0.Final-SNAPSHOT</version>
</parent>
<artifactId>netty-transport-udt</artifactId>
<packaging>jar</packaging>
<name>Netty/Transport/UDT</name>
<properties>
<javaModuleName>io.netty.transport.udt</javaModuleName>
</properties>
<dependencies>
<!-- MAIN -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-buffer</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netty-transport</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.barchart.udt</groupId>
<artifactId>barchart-udt-bundle</artifactId>
</dependency>
<!-- TEST -->
<!-- see https://github.com/netty/netty/issues/874 -->
<dependency>
<groupId>com.yammer.metrics</groupId>
<artifactId>metrics-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.caliper</groupId>
<artifactId>caliper</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- run each test in separate JVM -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>always</forkMode>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,313 +0,0 @@
/*
* Copyright 2012 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.udt;
import com.barchart.udt.OptionUDT;
import com.barchart.udt.SocketUDT;
import com.barchart.udt.nio.ChannelUDT;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultChannelConfig;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.WriteBufferWaterMark;
import java.io.IOException;
import java.util.Map;
import static io.netty.channel.ChannelOption.SO_LINGER;
import static io.netty.channel.ChannelOption.SO_RCVBUF;
import static io.netty.channel.ChannelOption.SO_REUSEADDR;
import static io.netty.channel.ChannelOption.SO_SNDBUF;
import static io.netty.channel.udt.UdtChannelOption.PROTOCOL_RECEIVE_BUFFER_SIZE;
import static io.netty.channel.udt.UdtChannelOption.PROTOCOL_SEND_BUFFER_SIZE;
import static io.netty.channel.udt.UdtChannelOption.SYSTEM_RECEIVE_BUFFER_SIZE;
import static io.netty.channel.udt.UdtChannelOption.SYSTEM_SEND_BUFFER_SIZE;
/**
* The default {@link UdtChannelConfig} implementation.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class DefaultUdtChannelConfig extends DefaultChannelConfig implements
UdtChannelConfig {
private static final int K = 1024;
private static final int M = K * K;
private volatile int protocolReceiveBufferSize = 10 * M;
private volatile int protocolSendBufferSize = 10 * M;
private volatile int systemReceiveBufferSize = M;
private volatile int systemSendBufferSize = M;
private volatile int allocatorReceiveBufferSize = 128 * K;
private volatile int allocatorSendBufferSize = 128 * K;
private volatile int soLinger;
private volatile boolean reuseAddress = true;
public DefaultUdtChannelConfig(final UdtChannel channel,
final ChannelUDT channelUDT, final boolean apply)
throws IOException {
super(channel);
if (apply) {
apply(channelUDT);
}
}
protected void apply(final ChannelUDT channelUDT) throws IOException {
final SocketUDT socketUDT = channelUDT.socketUDT();
socketUDT.setReuseAddress(isReuseAddress());
socketUDT.setSendBufferSize(getSendBufferSize());
if (getSoLinger() <= 0) {
socketUDT.setSoLinger(false, 0);
} else {
socketUDT.setSoLinger(true, getSoLinger());
}
socketUDT.setOption(OptionUDT.Protocol_Receive_Buffer_Size,
getProtocolReceiveBufferSize());
socketUDT.setOption(OptionUDT.Protocol_Send_Buffer_Size,
getProtocolSendBufferSize());
socketUDT.setOption(OptionUDT.System_Receive_Buffer_Size,
getSystemReceiveBufferSize());
socketUDT.setOption(OptionUDT.System_Send_Buffer_Size,
getSystemSendBufferSize());
}
@Override
public int getProtocolReceiveBufferSize() {
return protocolReceiveBufferSize;
}
@SuppressWarnings("unchecked")
@Override
public <T> T getOption(final ChannelOption<T> option) {
if (option == PROTOCOL_RECEIVE_BUFFER_SIZE) {
return (T) Integer.valueOf(getProtocolReceiveBufferSize());
}
if (option == PROTOCOL_SEND_BUFFER_SIZE) {
return (T) Integer.valueOf(getProtocolSendBufferSize());
}
if (option == SYSTEM_RECEIVE_BUFFER_SIZE) {
return (T) Integer.valueOf(getSystemReceiveBufferSize());
}
if (option == SYSTEM_SEND_BUFFER_SIZE) {
return (T) Integer.valueOf(getSystemSendBufferSize());
}
if (option == SO_RCVBUF) {
return (T) Integer.valueOf(getReceiveBufferSize());
}
if (option == SO_SNDBUF) {
return (T) Integer.valueOf(getSendBufferSize());
}
if (option == SO_REUSEADDR) {
return (T) Boolean.valueOf(isReuseAddress());
}
if (option == SO_LINGER) {
return (T) Integer.valueOf(getSoLinger());
}
return super.getOption(option);
}
@Override
public Map<ChannelOption<?>, Object> getOptions() {
return getOptions(super.getOptions(), PROTOCOL_RECEIVE_BUFFER_SIZE,
PROTOCOL_SEND_BUFFER_SIZE, SYSTEM_RECEIVE_BUFFER_SIZE,
SYSTEM_SEND_BUFFER_SIZE, SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR,
SO_LINGER);
}
@Override
public int getReceiveBufferSize() {
return allocatorReceiveBufferSize;
}
@Override
public int getSendBufferSize() {
return allocatorSendBufferSize;
}
@Override
public int getSoLinger() {
return soLinger;
}
@Override
public boolean isReuseAddress() {
return reuseAddress;
}
@Override
public UdtChannelConfig setProtocolReceiveBufferSize(final int protocolReceiveBufferSize) {
this.protocolReceiveBufferSize = protocolReceiveBufferSize;
return this;
}
@Override
public <T> boolean setOption(final ChannelOption<T> option, final T value) {
validate(option, value);
if (option == PROTOCOL_RECEIVE_BUFFER_SIZE) {
setProtocolReceiveBufferSize((Integer) value);
} else if (option == PROTOCOL_SEND_BUFFER_SIZE) {
setProtocolSendBufferSize((Integer) value);
} else if (option == SYSTEM_RECEIVE_BUFFER_SIZE) {
setSystemReceiveBufferSize((Integer) value);
} else if (option == SYSTEM_SEND_BUFFER_SIZE) {
setSystemSendBufferSize((Integer) value);
} else if (option == SO_RCVBUF) {
setReceiveBufferSize((Integer) value);
} else if (option == SO_SNDBUF) {
setSendBufferSize((Integer) value);
} else if (option == SO_REUSEADDR) {
setReuseAddress((Boolean) value);
} else if (option == SO_LINGER) {
setSoLinger((Integer) value);
} else {
return super.setOption(option, value);
}
return true;
}
@Override
public UdtChannelConfig setReceiveBufferSize(final int receiveBufferSize) {
allocatorReceiveBufferSize = receiveBufferSize;
return this;
}
@Override
public UdtChannelConfig setReuseAddress(final boolean reuseAddress) {
this.reuseAddress = reuseAddress;
return this;
}
@Override
public UdtChannelConfig setSendBufferSize(final int sendBufferSize) {
allocatorSendBufferSize = sendBufferSize;
return this;
}
@Override
public UdtChannelConfig setSoLinger(final int soLinger) {
this.soLinger = soLinger;
return this;
}
@Override
public int getSystemReceiveBufferSize() {
return systemReceiveBufferSize;
}
@Override
public UdtChannelConfig setSystemSendBufferSize(
final int systemReceiveBufferSize) {
this.systemReceiveBufferSize = systemReceiveBufferSize;
return this;
}
@Override
public int getProtocolSendBufferSize() {
return protocolSendBufferSize;
}
@Override
public UdtChannelConfig setProtocolSendBufferSize(
final int protocolSendBufferSize) {
this.protocolSendBufferSize = protocolSendBufferSize;
return this;
}
@Override
public UdtChannelConfig setSystemReceiveBufferSize(
final int systemSendBufferSize) {
this.systemSendBufferSize = systemSendBufferSize;
return this;
}
@Override
public int getSystemSendBufferSize() {
return systemSendBufferSize;
}
@Override
public UdtChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) {
super.setConnectTimeoutMillis(connectTimeoutMillis);
return this;
}
@Override
@Deprecated
public UdtChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) {
super.setMaxMessagesPerRead(maxMessagesPerRead);
return this;
}
@Override
public UdtChannelConfig setWriteSpinCount(int writeSpinCount) {
super.setWriteSpinCount(writeSpinCount);
return this;
}
@Override
public UdtChannelConfig setAllocator(ByteBufAllocator allocator) {
super.setAllocator(allocator);
return this;
}
@Override
public UdtChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) {
super.setRecvByteBufAllocator(allocator);
return this;
}
@Override
public UdtChannelConfig setAutoRead(boolean autoRead) {
super.setAutoRead(autoRead);
return this;
}
@Override
public UdtChannelConfig setAutoClose(boolean autoClose) {
super.setAutoClose(autoClose);
return this;
}
@Override
public UdtChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) {
super.setWriteBufferLowWaterMark(writeBufferLowWaterMark);
return this;
}
@Override
public UdtChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) {
super.setWriteBufferHighWaterMark(writeBufferHighWaterMark);
return this;
}
@Override
public UdtChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark) {
super.setWriteBufferWaterMark(writeBufferWaterMark);
return this;
}
@Override
public UdtChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) {
super.setMessageSizeEstimator(estimator);
return this;
}
}

View File

@ -1,209 +0,0 @@
/*
* Copyright 2013 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.udt;
import com.barchart.udt.nio.ChannelUDT;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelOption;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.WriteBufferWaterMark;
import java.io.IOException;
import java.util.Map;
import static io.netty.channel.ChannelOption.SO_BACKLOG;
/**
* The default {@link UdtServerChannelConfig} implementation.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class DefaultUdtServerChannelConfig extends DefaultUdtChannelConfig
implements UdtServerChannelConfig {
private volatile int backlog = 64;
public DefaultUdtServerChannelConfig(
final UdtChannel channel, final ChannelUDT channelUDT, final boolean apply) throws IOException {
super(channel, channelUDT, apply);
if (apply) {
apply(channelUDT);
}
}
@Override
protected void apply(final ChannelUDT channelUDT) throws IOException {
// nothing to apply for now.
}
@Override
public int getBacklog() {
return backlog;
}
@SuppressWarnings("unchecked")
@Override
public <T> T getOption(final ChannelOption<T> option) {
if (option == SO_BACKLOG) {
return (T) Integer.valueOf(getBacklog());
}
return super.getOption(option);
}
@Override
public Map<ChannelOption<?>, Object> getOptions() {
return getOptions(super.getOptions(), SO_BACKLOG);
}
@Override
public UdtServerChannelConfig setBacklog(final int backlog) {
this.backlog = backlog;
return this;
}
@Override
public <T> boolean setOption(final ChannelOption<T> option, final T value) {
validate(option, value);
if (option == SO_BACKLOG) {
setBacklog((Integer) value);
} else {
return super.setOption(option, value);
}
return true;
}
@Override
public UdtServerChannelConfig setProtocolReceiveBufferSize(
final int protocolReceiveBufferSize) {
super.setProtocolReceiveBufferSize(protocolReceiveBufferSize);
return this;
}
@Override
public UdtServerChannelConfig setProtocolSendBufferSize(
final int protocolSendBufferSize) {
super.setProtocolSendBufferSize(protocolSendBufferSize);
return this;
}
@Override
public UdtServerChannelConfig setReceiveBufferSize(
final int receiveBufferSize) {
super.setReceiveBufferSize(receiveBufferSize);
return this;
}
@Override
public UdtServerChannelConfig setReuseAddress(final boolean reuseAddress) {
super.setReuseAddress(reuseAddress);
return this;
}
@Override
public UdtServerChannelConfig setSendBufferSize(final int sendBufferSize) {
super.setSendBufferSize(sendBufferSize);
return this;
}
@Override
public UdtServerChannelConfig setSoLinger(final int soLinger) {
super.setSoLinger(soLinger);
return this;
}
@Override
public UdtServerChannelConfig setSystemReceiveBufferSize(
final int systemSendBufferSize) {
super.setSystemReceiveBufferSize(systemSendBufferSize);
return this;
}
@Override
public UdtServerChannelConfig setSystemSendBufferSize(
final int systemReceiveBufferSize) {
super.setSystemSendBufferSize(systemReceiveBufferSize);
return this;
}
@Override
public UdtServerChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) {
super.setConnectTimeoutMillis(connectTimeoutMillis);
return this;
}
@Override
@Deprecated
public UdtServerChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) {
super.setMaxMessagesPerRead(maxMessagesPerRead);
return this;
}
@Override
public UdtServerChannelConfig setWriteSpinCount(int writeSpinCount) {
super.setWriteSpinCount(writeSpinCount);
return this;
}
@Override
public UdtServerChannelConfig setAllocator(ByteBufAllocator allocator) {
super.setAllocator(allocator);
return this;
}
@Override
public UdtServerChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) {
super.setRecvByteBufAllocator(allocator);
return this;
}
@Override
public UdtServerChannelConfig setAutoRead(boolean autoRead) {
super.setAutoRead(autoRead);
return this;
}
@Override
public UdtServerChannelConfig setAutoClose(boolean autoClose) {
super.setAutoClose(autoClose);
return this;
}
@Override
public UdtServerChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) {
super.setWriteBufferLowWaterMark(writeBufferLowWaterMark);
return this;
}
@Override
public UdtServerChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) {
super.setWriteBufferHighWaterMark(writeBufferHighWaterMark);
return this;
}
@Override
public UdtServerChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark) {
super.setWriteBufferWaterMark(writeBufferWaterMark);
return this;
}
@Override
public UdtServerChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) {
super.setMessageSizeEstimator(estimator);
return this;
}
}

View File

@ -1,44 +0,0 @@
/*
* Copyright 2012 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.udt;
import io.netty.channel.Channel;
import io.netty.channel.udt.nio.NioUdtProvider;
import java.net.InetSocketAddress;
/**
* UDT {@link Channel}.
* <p>
* Supported UDT {@link UdtChannel} are available via {@link NioUdtProvider}.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public interface UdtChannel extends Channel {
/**
* Returns the {@link UdtChannelConfig} of the channel.
*/
@Override
UdtChannelConfig config();
@Override
InetSocketAddress localAddress();
@Override
InetSocketAddress remoteAddress();
}

View File

@ -1,192 +0,0 @@
/*
* Copyright 2012 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.udt;
import com.barchart.udt.OptionUDT;
import com.barchart.udt.TypeUDT;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.WriteBufferWaterMark;
/**
* A {@link ChannelConfig} for a {@link UdtChannel}.
* <p>
* <h3>Available options</h3>
* In addition to the options provided by {@link ChannelConfig},
* {@link UdtChannelConfig} allows the following options in the option map:
* <p>
* <table border="1" cellspacing="0" cellpadding="6">
* <tr>
* <th>Name</th>
* <th>Associated setter method</th>
* </tr><tr>
* <td>{@link ChannelOption#SO_REUSEADDR}</td><td>{@link #setReuseAddress(boolean)}</td>
* </tr><tr>
* <td>{@link ChannelOption#SO_RCVBUF}</td><td>{@link #setReceiveBufferSize(int)}</td>
* </tr><tr>
* <td>{@link ChannelOption#SO_SNDBUF}</td><td>{@link #setSendBufferSize(int)}</td>
* </tr><tr>
* <td>{@link ChannelOption#SO_REUSEADDR}</td><td>{@link #setReuseAddress(boolean)}</td>
* </tr><tr>
* <td>{@link ChannelOption#SO_LINGER}</td><td>{@link #setSoLinger(int)}</td>
* </tr><tr>
* <td>{@link ChannelOption#SO_RCVBUF}</td><td>{@link #setReceiveBufferSize(int)}</td>
* </tr><tr>
* <td>{@link ChannelOption#SO_SNDBUF}</td><td>{@link #setSendBufferSize(int)}</td>
* </tr><tr>
* <td>{@link UdtChannelOption#PROTOCOL_RECEIVE_BUFFER_SIZE}</td>
* <td>{@link #setProtocolReceiveBufferSize(int)}</td>
* </tr><tr>
* <td>{@link UdtChannelOption#PROTOCOL_SEND_BUFFER_SIZE}</td>
* <td>{@link #setProtocolSendBufferSize(int)}</td>
* </tr><tr>
* <td>{@link UdtChannelOption#SYSTEM_RECEIVE_BUFFER_SIZE}</td>
* <td>{@link #setSystemReceiveBufferSize(int)}</td>
* </tr><tr>
* <td>{@link UdtChannelOption#SYSTEM_SEND_BUFFER_SIZE}</td>
* <td>{@link #setSystemSendBufferSize(int)}</td>
* </tr>
* </table>
* <p>
* Note that {@link TypeUDT#DATAGRAM} message oriented channels treat
* {@code "receiveBufferSize"} and {@code "sendBufferSize"} as maximum message
* size. If received or sent message does not fit specified sizes,
* {@link ChannelException} will be thrown.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public interface UdtChannelConfig extends ChannelConfig {
/**
* Gets {@link OptionUDT#Protocol_Receive_Buffer_Size}
*/
int getProtocolReceiveBufferSize();
/**
* Gets {@link OptionUDT#Protocol_Send_Buffer_Size}
*/
int getProtocolSendBufferSize();
/**
* Gets the {@link ChannelOption#SO_RCVBUF} option.
*/
int getReceiveBufferSize();
/**
* Gets the {@link ChannelOption#SO_SNDBUF} option.
*/
int getSendBufferSize();
/**
* Gets the {@link ChannelOption#SO_LINGER} option.
*/
int getSoLinger();
/**
* Gets {@link OptionUDT#System_Receive_Buffer_Size}
*/
int getSystemReceiveBufferSize();
/**
* Gets {@link OptionUDT#System_Send_Buffer_Size}
*/
int getSystemSendBufferSize();
/**
* Gets the {@link ChannelOption#SO_REUSEADDR} option.
*/
boolean isReuseAddress();
@Override
UdtChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis);
@Override
@Deprecated
UdtChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead);
@Override
UdtChannelConfig setWriteSpinCount(int writeSpinCount);
@Override
UdtChannelConfig setAllocator(ByteBufAllocator allocator);
@Override
UdtChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator);
@Override
UdtChannelConfig setAutoRead(boolean autoRead);
@Override
UdtChannelConfig setAutoClose(boolean autoClose);
@Override
UdtChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
@Override
UdtChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
@Override
UdtChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark);
@Override
UdtChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator);
/**
* Sets {@link OptionUDT#Protocol_Receive_Buffer_Size}
*/
UdtChannelConfig setProtocolReceiveBufferSize(int size);
/**
* Sets {@link OptionUDT#Protocol_Send_Buffer_Size}
*/
UdtChannelConfig setProtocolSendBufferSize(int size);
/**
* Sets the {@link ChannelOption#SO_RCVBUF} option.
*/
UdtChannelConfig setReceiveBufferSize(int receiveBufferSize);
/**
* Sets the {@link ChannelOption#SO_REUSEADDR} option.
*/
UdtChannelConfig setReuseAddress(boolean reuseAddress);
/**
* Sets the {@link ChannelOption#SO_SNDBUF} option.
*/
UdtChannelConfig setSendBufferSize(int sendBufferSize);
/**
* Sets the {@link ChannelOption#SO_LINGER} option.
*/
UdtChannelConfig setSoLinger(int soLinger);
/**
* Sets {@link OptionUDT#System_Receive_Buffer_Size}
*/
UdtChannelConfig setSystemReceiveBufferSize(int size);
/**
* Sets {@link OptionUDT#System_Send_Buffer_Size}
*/
UdtChannelConfig setSystemSendBufferSize(int size);
}

View File

@ -1,57 +0,0 @@
/*
* Copyright 2013 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.udt;
import com.barchart.udt.OptionUDT;
import io.netty.channel.ChannelOption;
/**
* Options for the UDT transport
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public final class UdtChannelOption<T> extends ChannelOption<T> {
/**
* See {@link OptionUDT#Protocol_Receive_Buffer_Size}.
*/
public static final ChannelOption<Integer> PROTOCOL_RECEIVE_BUFFER_SIZE =
valueOf(UdtChannelOption.class, "PROTOCOL_RECEIVE_BUFFER_SIZE");
/**
* See {@link OptionUDT#Protocol_Send_Buffer_Size}.
*/
public static final ChannelOption<Integer> PROTOCOL_SEND_BUFFER_SIZE =
valueOf(UdtChannelOption.class, "PROTOCOL_SEND_BUFFER_SIZE");
/**
* See {@link OptionUDT#System_Receive_Buffer_Size}.
*/
public static final ChannelOption<Integer> SYSTEM_RECEIVE_BUFFER_SIZE =
valueOf(UdtChannelOption.class, "SYSTEM_RECEIVE_BUFFER_SIZE");
/**
* See {@link OptionUDT#System_Send_Buffer_Size}.
*/
public static final ChannelOption<Integer> SYSTEM_SEND_BUFFER_SIZE =
valueOf(UdtChannelOption.class, "SYSTEM_SEND_BUFFER_SIZE");
@SuppressWarnings({ "unused", "deprecation" })
private UdtChannelOption() {
super(null);
}
}

View File

@ -1,80 +0,0 @@
/*
* Copyright 2012 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.udt;
import com.barchart.udt.TypeUDT;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.DefaultByteBufHolder;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* The message container that is used for {@link TypeUDT#DATAGRAM} messages.
* @see NioUdtProvider#MESSAGE_CONNECTOR
* @see NioUdtProvider#MESSAGE_RENDEZVOUS
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public final class UdtMessage extends DefaultByteBufHolder {
public UdtMessage(final ByteBuf data) {
super(data);
}
@Override
public UdtMessage copy() {
return (UdtMessage) super.copy();
}
@Override
public UdtMessage duplicate() {
return (UdtMessage) super.duplicate();
}
@Override
public UdtMessage retainedDuplicate() {
return (UdtMessage) super.retainedDuplicate();
}
@Override
public UdtMessage replace(ByteBuf content) {
return new UdtMessage(content);
}
@Override
public UdtMessage retain() {
super.retain();
return this;
}
@Override
public UdtMessage retain(int increment) {
super.retain(increment);
return this;
}
@Override
public UdtMessage touch() {
super.touch();
return this;
}
@Override
public UdtMessage touch(Object hint) {
super.touch(hint);
return this;
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright 2013 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.udt;
import io.netty.channel.ServerChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
/**
* UDT {@link ServerChannel}.
* <p>
* Supported UDT {@link UdtServerChannel} are available via {@link NioUdtProvider}.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public interface UdtServerChannel extends ServerChannel, UdtChannel {
}

View File

@ -1,110 +0,0 @@
/*
* Copyright 2013 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.udt;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.KindUDT;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelOption;
import io.netty.channel.MessageSizeEstimator;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.WriteBufferWaterMark;
/**
* A {@link ChannelConfig} for a {@link UdtServerChannel}.
* <p>
* Note that {@link TypeUDT#DATAGRAM} message oriented channels treat
* {@code "receiveBufferSize"} and {@code "sendBufferSize"} as maximum message
* size. If received or sent message does not fit specified sizes,
* {@link ChannelException} will be thrown.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public interface UdtServerChannelConfig extends UdtChannelConfig {
/**
* Gets {@link KindUDT#ACCEPTOR} channel backlog via
* {@link ChannelOption#SO_BACKLOG}.
*/
int getBacklog();
/**
* Sets {@link KindUDT#ACCEPTOR} channel backlog via
* {@link ChannelOption#SO_BACKLOG}.
*/
UdtServerChannelConfig setBacklog(int backlog);
@Override
UdtServerChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis);
@Override
@Deprecated
UdtServerChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead);
@Override
UdtServerChannelConfig setWriteSpinCount(int writeSpinCount);
@Override
UdtServerChannelConfig setAllocator(ByteBufAllocator allocator);
@Override
UdtServerChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator);
@Override
UdtServerChannelConfig setAutoRead(boolean autoRead);
@Override
UdtServerChannelConfig setAutoClose(boolean autoClose);
@Override
UdtServerChannelConfig setProtocolReceiveBufferSize(int size);
@Override
UdtServerChannelConfig setProtocolSendBufferSize(int size);
@Override
UdtServerChannelConfig setReceiveBufferSize(int receiveBufferSize);
@Override
UdtServerChannelConfig setReuseAddress(boolean reuseAddress);
@Override
UdtServerChannelConfig setSendBufferSize(int sendBufferSize);
@Override
UdtServerChannelConfig setSoLinger(int soLinger);
@Override
UdtServerChannelConfig setSystemReceiveBufferSize(int size);
@Override
UdtServerChannelConfig setSystemSendBufferSize(int size);
@Override
UdtServerChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark);
@Override
UdtServerChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark);
@Override
UdtServerChannelConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark);
@Override
UdtServerChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator);
}

View File

@ -1,163 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.ServerSocketChannelUDT;
import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.udt.DefaultUdtServerChannelConfig;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.UdtServerChannel;
import io.netty.channel.udt.UdtServerChannelConfig;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import static java.nio.channels.SelectionKey.*;
/**
* Common base for Netty Byte/Message UDT Stream/Datagram acceptors.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public abstract class NioUdtAcceptorChannel extends AbstractNioMessageChannel implements UdtServerChannel {
protected static final InternalLogger logger =
InternalLoggerFactory.getInstance(NioUdtAcceptorChannel.class);
private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16);
private final UdtServerChannelConfig config;
protected NioUdtAcceptorChannel(final ServerSocketChannelUDT channelUDT) {
super(null, channelUDT, OP_ACCEPT);
try {
channelUDT.configureBlocking(false);
config = new DefaultUdtServerChannelConfig(this, channelUDT, true);
} catch (final Exception e) {
try {
channelUDT.close();
} catch (final Exception e2) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close channel.", e2);
}
}
throw new ChannelException("Failed to configure channel.", e);
}
}
protected NioUdtAcceptorChannel(final TypeUDT type) {
this(NioUdtProvider.newAcceptorChannelUDT(type));
}
@Override
public UdtServerChannelConfig config() {
return config;
}
@Override
protected void doBind(final SocketAddress localAddress) throws Exception {
javaChannel().socket().bind(localAddress, config.getBacklog());
}
@Override
protected void doClose() throws Exception {
javaChannel().close();
}
@Override
protected boolean doConnect(final SocketAddress remoteAddress,
final SocketAddress localAddress) throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void doDisconnect() throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void doFinishConnect() throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected final Object filterOutboundMessage(Object msg) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public boolean isActive() {
return javaChannel().socket().isBound();
}
@Override
protected ServerSocketChannelUDT javaChannel() {
return (ServerSocketChannelUDT) super.javaChannel();
}
@Override
protected SocketAddress localAddress0() {
return SocketUtils.localSocketAddress(javaChannel().socket());
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress) super.localAddress();
}
@Override
public InetSocketAddress remoteAddress() {
return null;
}
@Override
protected SocketAddress remoteAddress0() {
return null;
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
final SocketChannelUDT channelUDT = (SocketChannelUDT) SocketUtils.accept(javaChannel());
if (channelUDT == null) {
return 0;
} else {
buf.add(newConnectorChannel(channelUDT));
return 1;
}
}
protected abstract UdtChannel newConnectorChannel(SocketChannelUDT channelUDT);
}

View File

@ -1,38 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.channel.udt.UdtChannel;
/**
* Byte Channel Acceptor for UDT Streams.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class NioUdtByteAcceptorChannel extends NioUdtAcceptorChannel {
public NioUdtByteAcceptorChannel() {
super(TypeUDT.STREAM);
}
@Override
protected UdtChannel newConnectorChannel(SocketChannelUDT channelUDT) {
return new NioUdtByteConnectorChannel(this, channelUDT);
}
}

View File

@ -1,213 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFuture;
import io.netty.channel.FileRegion;
import io.netty.channel.RecvByteBufAllocator;
import io.netty.channel.nio.AbstractNioByteChannel;
import io.netty.channel.udt.DefaultUdtChannelConfig;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.UdtChannelConfig;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import static java.nio.channels.SelectionKey.OP_CONNECT;
/**
* Byte Channel Connector for UDT Streams.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class NioUdtByteConnectorChannel extends AbstractNioByteChannel implements UdtChannel {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(NioUdtByteConnectorChannel.class);
private final UdtChannelConfig config;
public NioUdtByteConnectorChannel() {
this(TypeUDT.STREAM);
}
public NioUdtByteConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) {
super(parent, channelUDT);
try {
channelUDT.configureBlocking(false);
switch (channelUDT.socketUDT().status()) {
case INIT:
case OPENED:
config = new DefaultUdtChannelConfig(this, channelUDT, true);
break;
default:
config = new DefaultUdtChannelConfig(this, channelUDT, false);
break;
}
} catch (final Exception e) {
try {
channelUDT.close();
} catch (final Exception e2) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close channel.", e2);
}
}
throw new ChannelException("Failed to configure channel.", e);
}
}
public NioUdtByteConnectorChannel(final SocketChannelUDT channelUDT) {
this(null, channelUDT);
}
public NioUdtByteConnectorChannel(final TypeUDT type) {
this(NioUdtProvider.newConnectorChannelUDT(type));
}
@Override
public UdtChannelConfig config() {
return config;
}
@Override
protected void doBind(final SocketAddress localAddress) throws Exception {
privilegedBind(javaChannel(), localAddress);
}
@Override
protected void doClose() throws Exception {
javaChannel().close();
}
@Override
protected boolean doConnect(final SocketAddress remoteAddress,
final SocketAddress localAddress) throws Exception {
doBind(localAddress != null? localAddress : new InetSocketAddress(0));
boolean success = false;
try {
final boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);
if (!connected) {
selectionKey().interestOps(
selectionKey().interestOps() | OP_CONNECT);
}
success = true;
return connected;
} finally {
if (!success) {
doClose();
}
}
}
@Override
protected void doDisconnect() throws Exception {
doClose();
}
@Override
protected void doFinishConnect() throws Exception {
if (javaChannel().finishConnect()) {
selectionKey().interestOps(
selectionKey().interestOps() & ~OP_CONNECT);
} else {
throw new Error(
"Provider error: failed to finish connect. Provider library should be upgraded.");
}
}
@Override
protected int doReadBytes(final ByteBuf byteBuf) throws Exception {
final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
allocHandle.attemptedBytesRead(byteBuf.writableBytes());
return byteBuf.writeBytes(javaChannel(), allocHandle.attemptedBytesRead());
}
@Override
protected int doWriteBytes(final ByteBuf byteBuf) throws Exception {
final int expectedWrittenBytes = byteBuf.readableBytes();
return byteBuf.readBytes(javaChannel(), expectedWrittenBytes);
}
@Override
protected ChannelFuture shutdownInput() {
return newFailedFuture(new UnsupportedOperationException("shutdownInput"));
}
@Override
protected long doWriteFileRegion(FileRegion region) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public boolean isActive() {
final SocketChannelUDT channelUDT = javaChannel();
return channelUDT.isOpen() && channelUDT.isConnectFinished();
}
@Override
protected SocketChannelUDT javaChannel() {
return (SocketChannelUDT) super.javaChannel();
}
@Override
protected SocketAddress localAddress0() {
return javaChannel().socket().getLocalSocketAddress();
}
@Override
protected SocketAddress remoteAddress0() {
return javaChannel().socket().getRemoteSocketAddress();
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress) super.localAddress();
}
@Override
public InetSocketAddress remoteAddress() {
return (InetSocketAddress) super.remoteAddress();
}
private static void privilegedBind(final SocketChannelUDT socketChannel, final SocketAddress localAddress)
throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socketChannel.bind(localAddress);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
}

View File

@ -1,32 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
/**
* Byte Channel Rendezvous for UDT Streams.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class NioUdtByteRendezvousChannel extends NioUdtByteConnectorChannel {
public NioUdtByteRendezvousChannel() {
super(NioUdtProvider.newRendezvousChannelUDT(TypeUDT.STREAM));
}
}

View File

@ -1,38 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.channel.udt.UdtChannel;
/**
* Message Channel Acceptor for UDT Datagrams.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class NioUdtMessageAcceptorChannel extends NioUdtAcceptorChannel {
public NioUdtMessageAcceptorChannel() {
super(TypeUDT.DATAGRAM);
}
@Override
protected UdtChannel newConnectorChannel(SocketChannelUDT channelUDT) {
return new NioUdtMessageConnectorChannel(this, channelUDT);
}
}

View File

@ -1,255 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelOutboundBuffer;
import io.netty.util.internal.SocketUtils;
import io.netty.channel.nio.AbstractNioMessageChannel;
import io.netty.channel.udt.DefaultUdtChannelConfig;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.UdtChannelConfig;
import io.netty.channel.udt.UdtMessage;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.List;
import static java.nio.channels.SelectionKey.*;
/**
* Message Connector for UDT Datagrams.
* <p>
* Note: send/receive must use {@link UdtMessage} in the pipeline
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class NioUdtMessageConnectorChannel extends AbstractNioMessageChannel implements UdtChannel {
private static final InternalLogger logger =
InternalLoggerFactory.getInstance(NioUdtMessageConnectorChannel.class);
private static final ChannelMetadata METADATA = new ChannelMetadata(false);
private final UdtChannelConfig config;
public NioUdtMessageConnectorChannel() {
this(TypeUDT.DATAGRAM);
}
public NioUdtMessageConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) {
super(parent, channelUDT, OP_READ);
try {
channelUDT.configureBlocking(false);
switch (channelUDT.socketUDT().status()) {
case INIT:
case OPENED:
config = new DefaultUdtChannelConfig(this, channelUDT, true);
break;
default:
config = new DefaultUdtChannelConfig(this, channelUDT, false);
break;
}
} catch (final Exception e) {
try {
channelUDT.close();
} catch (final Exception e2) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to close channel.", e2);
}
}
throw new ChannelException("Failed to configure channel.", e);
}
}
public NioUdtMessageConnectorChannel(final SocketChannelUDT channelUDT) {
this(null, channelUDT);
}
public NioUdtMessageConnectorChannel(final TypeUDT type) {
this(NioUdtProvider.newConnectorChannelUDT(type));
}
@Override
public UdtChannelConfig config() {
return config;
}
@Override
protected void doBind(final SocketAddress localAddress) throws Exception {
privilegedBind(javaChannel(), localAddress);
}
@Override
protected void doClose() throws Exception {
javaChannel().close();
}
@Override
protected boolean doConnect(final SocketAddress remoteAddress,
final SocketAddress localAddress) throws Exception {
doBind(localAddress != null? localAddress : new InetSocketAddress(0));
boolean success = false;
try {
final boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);
if (!connected) {
selectionKey().interestOps(
selectionKey().interestOps() | OP_CONNECT);
}
success = true;
return connected;
} finally {
if (!success) {
doClose();
}
}
}
@Override
protected void doDisconnect() throws Exception {
doClose();
}
@Override
protected void doFinishConnect() throws Exception {
if (javaChannel().finishConnect()) {
selectionKey().interestOps(
selectionKey().interestOps() & ~OP_CONNECT);
} else {
throw new Error(
"Provider error: failed to finish connect. Provider library should be upgraded.");
}
}
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
final int maximumMessageSize = config.getReceiveBufferSize();
final ByteBuf byteBuf = config.getAllocator().directBuffer(
maximumMessageSize);
final int receivedMessageSize = byteBuf.writeBytes(javaChannel(),
maximumMessageSize);
if (receivedMessageSize <= 0) {
byteBuf.release();
return 0;
}
if (receivedMessageSize >= maximumMessageSize) {
javaChannel().close();
throw new ChannelException(
"Invalid config : increase receive buffer size to avoid message truncation");
}
// delivers a message
buf.add(new UdtMessage(byteBuf));
return 1;
}
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
// expects a message
final UdtMessage message = (UdtMessage) msg;
final ByteBuf byteBuf = message.content();
final int messageSize = byteBuf.readableBytes();
if (messageSize == 0) {
return true;
}
final long writtenBytes;
if (byteBuf.nioBufferCount() == 1) {
writtenBytes = javaChannel().write(byteBuf.nioBuffer());
} else {
writtenBytes = javaChannel().write(byteBuf.nioBuffers());
}
// wrote message completely
if (writtenBytes > 0 && writtenBytes != messageSize) {
throw new Error(
"Provider error: failed to write message. Provider library should be upgraded.");
}
return writtenBytes > 0;
}
@Override
public boolean isActive() {
final SocketChannelUDT channelUDT = javaChannel();
return channelUDT.isOpen() && channelUDT.isConnectFinished();
}
@Override
protected SocketChannelUDT javaChannel() {
return (SocketChannelUDT) super.javaChannel();
}
@Override
protected SocketAddress localAddress0() {
return javaChannel().socket().getLocalSocketAddress();
}
@Override
public ChannelMetadata metadata() {
return METADATA;
}
@Override
protected SocketAddress remoteAddress0() {
return javaChannel().socket().getRemoteSocketAddress();
}
@Override
public InetSocketAddress localAddress() {
return (InetSocketAddress) super.localAddress();
}
@Override
public InetSocketAddress remoteAddress() {
return (InetSocketAddress) super.remoteAddress();
}
private static void privilegedBind(final SocketChannelUDT socketChannel, final SocketAddress localAddress)
throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
socketChannel.bind(localAddress);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
}

View File

@ -1,34 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.TypeUDT;
import io.netty.channel.udt.UdtMessage;
/**
* Message Rendezvous for UDT Datagrams.
* <p>
* Note: send/receive must use {@link UdtMessage} in the pipeline
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public class NioUdtMessageRendezvousChannel extends NioUdtMessageConnectorChannel {
public NioUdtMessageRendezvousChannel() {
super(NioUdtProvider.newRendezvousChannelUDT(TypeUDT.DATAGRAM));
}
}

View File

@ -1,247 +0,0 @@
/*
* Copyright 2012 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.udt.nio;
import com.barchart.udt.SocketUDT;
import com.barchart.udt.TypeUDT;
import com.barchart.udt.nio.ChannelUDT;
import com.barchart.udt.nio.KindUDT;
import com.barchart.udt.nio.RendezvousChannelUDT;
import com.barchart.udt.nio.SelectorProviderUDT;
import com.barchart.udt.nio.ServerSocketChannelUDT;
import com.barchart.udt.nio.SocketChannelUDT;
import io.netty.channel.Channel;
import io.netty.channel.ChannelException;
import io.netty.channel.ChannelFactory;
import io.netty.channel.udt.UdtChannel;
import io.netty.channel.udt.UdtServerChannel;
import java.io.IOException;
import java.nio.channels.spi.SelectorProvider;
/**
* UDT NIO components provider:
* <p>
* Provides {@link ChannelFactory} for UDT channels.
* <p>
* Provides {@link SelectorProvider} for UDT channels.
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
@Deprecated
public final class NioUdtProvider<T extends UdtChannel> implements ChannelFactory<T> {
/**
* {@link ChannelFactory} for UDT Byte Acceptor. See {@link TypeUDT#STREAM}
* and {@link KindUDT#ACCEPTOR}.
*/
public static final ChannelFactory<UdtServerChannel> BYTE_ACCEPTOR = new NioUdtProvider<UdtServerChannel>(
TypeUDT.STREAM, KindUDT.ACCEPTOR);
/**
* {@link ChannelFactory} for UDT Byte Connector. See {@link TypeUDT#STREAM}
* and {@link KindUDT#CONNECTOR}.
*/
public static final ChannelFactory<UdtChannel> BYTE_CONNECTOR = new NioUdtProvider<UdtChannel>(
TypeUDT.STREAM, KindUDT.CONNECTOR);
/**
* {@link SelectorProvider} for UDT Byte channels. See
* {@link TypeUDT#STREAM}.
*/
public static final SelectorProvider BYTE_PROVIDER = SelectorProviderUDT.STREAM;
/**
* {@link ChannelFactory} for UDT Byte Rendezvous. See
* {@link TypeUDT#STREAM} and {@link KindUDT#RENDEZVOUS}.
*/
public static final ChannelFactory<UdtChannel> BYTE_RENDEZVOUS = new NioUdtProvider<UdtChannel>(
TypeUDT.STREAM, KindUDT.RENDEZVOUS);
/**
* {@link ChannelFactory} for UDT Message Acceptor. See
* {@link TypeUDT#DATAGRAM} and {@link KindUDT#ACCEPTOR}.
*/
public static final ChannelFactory<UdtServerChannel> MESSAGE_ACCEPTOR = new NioUdtProvider<UdtServerChannel>(
TypeUDT.DATAGRAM, KindUDT.ACCEPTOR);
/**
* {@link ChannelFactory} for UDT Message Connector. See
* {@link TypeUDT#DATAGRAM} and {@link KindUDT#CONNECTOR}.
*/
public static final ChannelFactory<UdtChannel> MESSAGE_CONNECTOR = new NioUdtProvider<UdtChannel>(
TypeUDT.DATAGRAM, KindUDT.CONNECTOR);
/**
* {@link SelectorProvider} for UDT Message channels. See
* {@link TypeUDT#DATAGRAM}.
*/
public static final SelectorProvider MESSAGE_PROVIDER = SelectorProviderUDT.DATAGRAM;
/**
* {@link ChannelFactory} for UDT Message Rendezvous. See
* {@link TypeUDT#DATAGRAM} and {@link KindUDT#RENDEZVOUS}.
*/
public static final ChannelFactory<UdtChannel> MESSAGE_RENDEZVOUS = new NioUdtProvider<UdtChannel>(
TypeUDT.DATAGRAM, KindUDT.RENDEZVOUS);
/**
* Expose underlying {@link ChannelUDT} for debugging and monitoring.
* <p>
* @return underlying {@link ChannelUDT} or null, if parameter is not
* {@link UdtChannel}
*/
public static ChannelUDT channelUDT(final Channel channel) {
// bytes
if (channel instanceof NioUdtByteAcceptorChannel) {
return ((NioUdtByteAcceptorChannel) channel).javaChannel();
}
if (channel instanceof NioUdtByteRendezvousChannel) {
return ((NioUdtByteRendezvousChannel) channel).javaChannel();
}
if (channel instanceof NioUdtByteConnectorChannel) {
return ((NioUdtByteConnectorChannel) channel).javaChannel();
}
// message
if (channel instanceof NioUdtMessageAcceptorChannel) {
return ((NioUdtMessageAcceptorChannel) channel).javaChannel();
}
if (channel instanceof NioUdtMessageRendezvousChannel) {
return ((NioUdtMessageRendezvousChannel) channel).javaChannel();
}
if (channel instanceof NioUdtMessageConnectorChannel) {
return ((NioUdtMessageConnectorChannel) channel).javaChannel();
}
return null;
}
/**
* Convenience factory for {@link KindUDT#ACCEPTOR} channels.
*/
static ServerSocketChannelUDT newAcceptorChannelUDT(
final TypeUDT type) {
try {
return SelectorProviderUDT.from(type).openServerSocketChannel();
} catch (final IOException e) {
throw new ChannelException("failed to open a server socket channel", e);
}
}
/**
* Convenience factory for {@link KindUDT#CONNECTOR} channels.
*/
static SocketChannelUDT newConnectorChannelUDT(final TypeUDT type) {
try {
return SelectorProviderUDT.from(type).openSocketChannel();
} catch (final IOException e) {
throw new ChannelException("failed to open a socket channel", e);
}
}
/**
* Convenience factory for {@link KindUDT#RENDEZVOUS} channels.
*/
static RendezvousChannelUDT newRendezvousChannelUDT(
final TypeUDT type) {
try {
return SelectorProviderUDT.from(type).openRendezvousChannel();
} catch (final IOException e) {
throw new ChannelException("failed to open a rendezvous channel", e);
}
}
/**
* Expose underlying {@link SocketUDT} for debugging and monitoring.
* <p>
* @return underlying {@link SocketUDT} or null, if parameter is not
* {@link UdtChannel}
*/
public static SocketUDT socketUDT(final Channel channel) {
final ChannelUDT channelUDT = channelUDT(channel);
if (channelUDT == null) {
return null;
} else {
return channelUDT.socketUDT();
}
}
private final KindUDT kind;
private final TypeUDT type;
/**
* {@link ChannelFactory} for given {@link TypeUDT} and {@link KindUDT}
*/
private NioUdtProvider(final TypeUDT type, final KindUDT kind) {
this.type = type;
this.kind = kind;
}
/**
* UDT Channel Kind. See {@link KindUDT}
*/
public KindUDT kind() {
return kind;
}
/**
* Produce new {@link UdtChannel} based on factory {@link #kind()} and
* {@link #type()}
*/
@SuppressWarnings("unchecked")
@Override
public T newChannel() {
switch (kind) {
case ACCEPTOR:
switch (type) {
case DATAGRAM:
return (T) new NioUdtMessageAcceptorChannel();
case STREAM:
return (T) new NioUdtByteAcceptorChannel();
default:
throw new IllegalStateException("wrong type=" + type);
}
case CONNECTOR:
switch (type) {
case DATAGRAM:
return (T) new NioUdtMessageConnectorChannel();
case STREAM:
return (T) new NioUdtByteConnectorChannel();
default:
throw new IllegalStateException("wrong type=" + type);
}
case RENDEZVOUS:
switch (type) {
case DATAGRAM:
return (T) new NioUdtMessageRendezvousChannel();
case STREAM:
return (T) new NioUdtByteRendezvousChannel();
default:
throw new IllegalStateException("wrong type=" + type);
}
default:
throw new IllegalStateException("wrong kind=" + kind);
}
}
/**
* UDT Socket Type. See {@link TypeUDT}
*/
public TypeUDT type() {
return type;
}
}

View File

@ -1,24 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* UDT Transport for NIO Channels.
* <p>
* @see io.netty.example.udt
*
* @deprecated The UDT transport is no longer maintained.
*/
package io.netty.channel.udt.nio;

View File

@ -1,24 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* UDT Transport.
* <p>
* @see io.netty.example.udt
*
* @deprecated The UDT transport is no longer maintained and will be removed.
*/
package io.netty.channel.udt;

View File

@ -1,50 +0,0 @@
/*
* Copyright 2012 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.test.udt.bench;
import io.netty.test.udt.util.CaliperBench;
import io.netty.test.udt.util.CaliperRunner;
import io.netty.test.udt.util.TrafficControl;
import java.util.List;
/**
* perform two way native udt socket send/recv
*/
public abstract class BenchXfer extends CaliperBench {
/** introduce network latency */
protected static List<String> latencyList() {
if (TrafficControl.isAvailable()) {
return CaliperRunner.valueList("0,10,30");
} else {
return CaliperRunner.valueList("0");
}
}
/** verify different message sizes */
protected static List<String> messageList() {
return CaliperRunner
.valueList("500,1500,3000,5000,10000,20000,50000,100000");
}
/** benchmark run time per each configuration */
protected static List<String> durationList() {
return CaliperRunner.valueList("30000");
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* UDT Benchmarks
*/
package io.netty.test.udt.bench;

View File

@ -1,66 +0,0 @@
/*
* Copyright 2012 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.test.udt.bench.xfer;
import io.netty.test.udt.bench.BenchXfer;
import io.netty.test.udt.util.CaliperRunner;
import io.netty.test.udt.util.TrafficControl;
import java.util.List;
import com.google.caliper.Param;
/**
* perform two way native TCP socket send/recv
*/
public class TcpNative extends BenchXfer {
@Param
private volatile int latency;
protected static List<String> latencyValues() {
return BenchXfer.latencyList();
}
@Param
private volatile int message;
protected static List<String> messageValues() {
return BenchXfer.messageList();
}
@Param
private volatile int duration;
protected static List<String> durationValues() {
return BenchXfer.durationList();
}
public void timeRun(final int reps) throws Exception {
log.info("init");
TrafficControl.delay(latency);
TrafficControl.delay(0);
log.info("done");
}
public static void main(final String[] args) throws Exception {
CaliperRunner.execute(TcpNative.class);
}
}

View File

@ -1,271 +0,0 @@
/*
* Copyright 2012 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.test.udt.bench.xfer;
import com.barchart.udt.SocketUDT;
import com.barchart.udt.StatusUDT;
import com.barchart.udt.TypeUDT;
import com.google.caliper.Param;
import io.netty.test.udt.bench.BenchXfer;
import io.netty.test.udt.util.CaliperRunner;
import io.netty.test.udt.util.TrafficControl;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.netty.test.udt.util.UnitHelp.*;
/**
* perform two way native UDT socket send/recv
*/
public class UdtNative extends BenchXfer {
@Param
private volatile int latency;
protected static List<String> latencyValues() {
return BenchXfer.latencyList();
}
@Param
private volatile int message;
protected static List<String> messageValues() {
return BenchXfer.messageList();
}
@Param
private volatile int duration;
protected static List<String> durationValues() {
return BenchXfer.durationList();
}
private volatile SocketUDT peer1;
private volatile SocketUDT peer2;
@Override
protected void setUp() throws Exception {
log.info("init");
TrafficControl.delay(latency);
final InetSocketAddress addr1 = localSocketAddress();
final InetSocketAddress addr2 = localSocketAddress();
peer1 = new SocketUDT(TypeUDT.DATAGRAM);
peer2 = new SocketUDT(TypeUDT.DATAGRAM);
peer1.setBlocking(false);
peer2.setBlocking(false);
peer1.setRendezvous(true);
peer2.setRendezvous(true);
peer1.bind(addr1);
peer2.bind(addr2);
socketAwait(peer1, StatusUDT.OPENED);
socketAwait(peer2, StatusUDT.OPENED);
peer1.connect(addr2);
peer2.connect(addr1);
socketAwait(peer1, StatusUDT.CONNECTED);
socketAwait(peer2, StatusUDT.CONNECTED);
peer1.setBlocking(true);
peer2.setBlocking(true);
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
peer1.setBlocking(false);
peer2.setBlocking(false);
peer1.close();
peer2.close();
socketAwait(peer1, StatusUDT.CLOSED, StatusUDT.BROKEN);
socketAwait(peer2, StatusUDT.CLOSED, StatusUDT.BROKEN);
TrafficControl.delay(0);
log.info("done");
}
/** benchmark invocation */
public void timeMain(final int reps) throws Exception {
final int threadCount = 4;
final CountDownLatch completion = new CountDownLatch(threadCount);
final AtomicBoolean isOn = new AtomicBoolean(true);
final Runnable sendPeer1 = new Runnable() {
@Override
public void run() {
try {
while (isOn.get()) {
runCore();
}
} catch (final Exception e) {
log.error("", e);
} finally {
completion.countDown();
}
}
final ByteBuffer buffer = ByteBuffer.allocateDirect(message);
long sequence;
void runCore() throws Exception {
buffer.rewind();
buffer.putLong(0, sequence++);
final int count = peer1.send(buffer);
if (count != message) {
throw new Exception("count");
}
measure().rate().mark(count);
}
};
final Runnable sendPeer2 = new Runnable() {
@Override
public void run() {
try {
while (isOn.get()) {
runCore();
}
} catch (final Exception e) {
log.error("", e);
} finally {
completion.countDown();
}
}
final ByteBuffer buffer = ByteBuffer.allocateDirect(message);
long sequence;
void runCore() throws Exception {
buffer.rewind();
buffer.putLong(0, sequence++);
final int count = peer2.send(buffer);
if (count != message) {
throw new Exception("count");
}
}
};
final Runnable recvPeer1 = new Runnable() {
@Override
public void run() {
try {
while (isOn.get()) {
runCore();
}
} catch (final Exception e) {
log.error("", e);
} finally {
completion.countDown();
}
}
final ByteBuffer buffer = ByteBuffer.allocateDirect(message);
long sequence;
void runCore() throws Exception {
buffer.rewind();
final int count = peer1.receive(buffer);
if (count != message) {
throw new Exception("count");
}
if (sequence ++ != buffer.getLong(0)) {
throw new Exception("sequence");
}
}
};
final Runnable recvPeer2 = new Runnable() {
@Override
public void run() {
try {
while (isOn.get()) {
runCore();
}
} catch (final Exception e) {
log.error("", e);
} finally {
completion.countDown();
}
}
final ByteBuffer buffer = ByteBuffer.allocateDirect(message);
long sequence;
void runCore() throws Exception {
buffer.rewind();
final int count = peer2.receive(buffer);
if (count != message) {
throw new Exception("count");
}
if (sequence ++ != buffer.getLong(0)) {
throw new Exception("sequence");
}
}
};
final ExecutorService executor = Executors
.newFixedThreadPool(threadCount);
executor.submit(recvPeer1);
executor.submit(recvPeer2);
executor.submit(sendPeer1);
executor.submit(sendPeer2);
markWait(duration);
isOn.set(false);
completion.await();
executor.shutdownNow();
}
public static void main(final String[] args) throws Exception {
CaliperRunner.execute(UdtNative.class);
}
}

View File

@ -1,135 +0,0 @@
/*
* Copyright 2012 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.test.udt.bench.xfer;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Meter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.test.udt.util.CustomReporter;
import io.netty.test.udt.util.EchoMessageHandler;
import io.netty.test.udt.util.TrafficControl;
import io.netty.test.udt.util.UnitHelp;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* perform two way netty send/recv
*/
public final class UdtNetty {
private UdtNetty() {
}
static final InternalLogger log = InternalLoggerFactory.getInstance(UdtNetty.class);
/** benchmark duration */
static final int time = 10 * 60 * 1000;
/** transfer chunk size */
static final int size = 64 * 1024;
static final Counter benchTime = Metrics.newCounter(UdtNetty.class,
"bench time");
static final Counter benchSize = Metrics.newCounter(UdtNetty.class,
"bench size");
static {
benchTime.inc(time);
benchSize.inc(size);
}
static final Meter rate = Metrics.newMeter(UdtNetty.class, "rate",
"bytes", TimeUnit.SECONDS);
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
TrafficControl.delay(0);
} catch (final Exception e) {
log.error("", e);
}
}
});
}
public static void main(final String[] args) throws Exception {
log.info("init");
TrafficControl.delay(0);
final AtomicBoolean isOn = new AtomicBoolean(true);
final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
final InetSocketAddress addr2 = UnitHelp.localSocketAddress();
final ChannelHandler handler1 = new EchoMessageHandler(rate, size);
final ChannelHandler handler2 = new EchoMessageHandler(null, size);
final NioEventLoopGroup group1 = new NioEventLoopGroup(
1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
final NioEventLoopGroup group2 = new NioEventLoopGroup(
1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
final Bootstrap peerBoot1 = new Bootstrap();
peerBoot1.group(group1)
.channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
.localAddress(addr1).remoteAddress(addr2).handler(handler1);
final Bootstrap peerBoot2 = new Bootstrap();
peerBoot2.group(group2)
.channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
.localAddress(addr2).remoteAddress(addr1).handler(handler2);
final ChannelFuture peerFuture1 = peerBoot1.connect();
final ChannelFuture peerFuture2 = peerBoot2.connect();
CustomReporter.enable(3, TimeUnit.SECONDS);
Thread.sleep(time);
isOn.set(false);
Thread.sleep(1000);
peerFuture1.channel().close().sync();
peerFuture2.channel().close().sync();
Thread.sleep(1000);
group1.shutdownGracefully();
group2.shutdownGracefully();
Metrics.defaultRegistry().shutdown();
TrafficControl.delay(0);
log.info("done");
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* UDT Transfer Speed Benchmarks
*/
package io.netty.test.udt.bench.xfer;

View File

@ -1,37 +0,0 @@
/*
* Copyright 2013 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.test.udt.nio;
import io.netty.test.udt.util.UnitHelp;
import org.junit.BeforeClass;
import static org.junit.Assume.*;
/**
* Base for UDT tests.
*/
public abstract class AbstractUdtTest {
/**
* UDT test assumptions.
*/
@BeforeClass
public static void assumeConditions() {
assumeTrue(UnitHelp.canLoadAndInitClass("com.barchart.udt.SocketUDT"));
}
}

View File

@ -1,33 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import io.netty.channel.udt.nio.NioUdtByteAcceptorChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class NioUdtByteAcceptorChannelTest extends AbstractUdtTest {
/**
* verify channel meta data
*/
@Test
public void metadata() throws Exception {
assertFalse(new NioUdtByteAcceptorChannel().metadata().hasDisconnect());
}
}

View File

@ -1,33 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import io.netty.channel.udt.nio.NioUdtByteConnectorChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class NioUdtByteConnectorChannelTest extends AbstractUdtTest {
/**
* verify channel meta data
*/
@Test
public void metadata() throws Exception {
assertFalse(new NioUdtByteConnectorChannel().metadata().hasDisconnect());
}
}

View File

@ -1,121 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Meter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.nio.NioUdtByteRendezvousChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.test.udt.util.EchoByteHandler;
import io.netty.test.udt.util.UnitHelp;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class NioUdtByteRendezvousChannelTest extends AbstractUdtTest {
private static final InternalLogger log = InternalLoggerFactory.getInstance(NioUdtByteAcceptorChannelTest.class);
/**
* verify channel meta data
*/
@Test
public void metadata() throws Exception {
assertFalse(new NioUdtByteRendezvousChannel().metadata().hasDisconnect());
}
/**
* verify basic echo byte rendezvous
*/
@Test(timeout = 10 * 1000)
public void basicEcho() throws Exception {
final int messageSize = 64 * 1024;
final int transferLimit = messageSize * 16;
final Meter rate1 = Metrics.newMeter(
NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes",
TimeUnit.SECONDS);
final Meter rate2 = Metrics.newMeter(
NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes",
TimeUnit.SECONDS);
final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
final InetSocketAddress addr2 = UnitHelp.localSocketAddress();
final EchoByteHandler handler1 = new EchoByteHandler(rate1, messageSize);
final EchoByteHandler handler2 = new EchoByteHandler(rate2, messageSize);
final NioEventLoopGroup group1 = new NioEventLoopGroup(
1, Executors.defaultThreadFactory(), NioUdtProvider.BYTE_PROVIDER);
final NioEventLoopGroup group2 = new NioEventLoopGroup(
1, Executors.defaultThreadFactory(), NioUdtProvider.BYTE_PROVIDER);
final Bootstrap boot1 = new Bootstrap();
boot1.group(group1)
.channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
.localAddress(addr1)
.remoteAddress(addr2)
.handler(handler1);
final Bootstrap boot2 = new Bootstrap();
boot2.group(group1)
.channelFactory(NioUdtProvider.BYTE_RENDEZVOUS)
.localAddress(addr2)
.remoteAddress(addr1)
.handler(handler2);
final ChannelFuture connectFuture1 = boot1.connect();
final ChannelFuture connectFuture2 = boot2.connect();
while (handler1.meter().count() < transferLimit
&& handler2.meter().count() < transferLimit) {
log.info("progress : {} {}", handler1.meter().count(), handler2
.meter().count());
Thread.sleep(1000);
}
connectFuture1.channel().close().sync();
connectFuture2.channel().close().sync();
log.info("handler1 : {}", handler1.meter().count());
log.info("handler2 : {}", handler2.meter().count());
assertTrue(handler1.meter().count() >= transferLimit);
assertTrue(handler2.meter().count() >= transferLimit);
assertEquals(handler1.meter().count(), handler2.meter().count());
group1.shutdownGracefully();
group2.shutdownGracefully();
group1.terminationFuture().sync();
group2.terminationFuture().sync();
}
}

View File

@ -1,33 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import io.netty.channel.udt.nio.NioUdtMessageAcceptorChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class NioUdtMessageAcceptorChannelTest extends AbstractUdtTest {
/**
* verify channel meta data
*/
@Test
public void metadata() throws Exception {
assertFalse(new NioUdtMessageAcceptorChannel().metadata().hasDisconnect());
}
}

View File

@ -1,33 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import io.netty.channel.udt.nio.NioUdtMessageConnectorChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class NioUdtMessageConnectorChannelTest extends AbstractUdtTest {
/**
* verify channel meta data
*/
@Test
public void metadata() throws Exception {
assertFalse(new NioUdtMessageConnectorChannel().metadata().hasDisconnect());
}
}

View File

@ -1,120 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Meter;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.udt.nio.NioUdtMessageRendezvousChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.test.udt.util.EchoMessageHandler;
import io.netty.test.udt.util.UnitHelp;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Ignore;
import org.junit.Test;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class NioUdtMessageRendezvousChannelTest extends AbstractUdtTest {
private static final InternalLogger log = InternalLoggerFactory.getInstance(NioUdtByteAcceptorChannelTest.class);
/**
* verify channel meta data
*/
@Test
public void metadata() throws Exception {
assertFalse(new NioUdtMessageRendezvousChannel().metadata().hasDisconnect());
}
/**
* verify basic echo message rendezvous
*
* FIXME: Re-enable after making it pass on Windows without unncessary tight loop.
* https://github.com/netty/netty/issues/2853
*/
@Test(timeout = 10 * 1000)
@Ignore
public void basicEcho() throws Exception {
final int messageSize = 64 * 1024;
final int transferLimit = messageSize * 16;
final Meter rate1 = Metrics.newMeter(
NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);
final Meter rate2 = Metrics.newMeter(
NioUdtMessageRendezvousChannelTest.class, "send rate", "bytes", TimeUnit.SECONDS);
final InetSocketAddress addr1 = UnitHelp.localSocketAddress();
final InetSocketAddress addr2 = UnitHelp.localSocketAddress();
final EchoMessageHandler handler1 = new EchoMessageHandler(rate1, messageSize);
final EchoMessageHandler handler2 = new EchoMessageHandler(rate2, messageSize);
final NioEventLoopGroup group1 = new NioEventLoopGroup(
1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
final NioEventLoopGroup group2 = new NioEventLoopGroup(
1, Executors.defaultThreadFactory(), NioUdtProvider.MESSAGE_PROVIDER);
final Bootstrap boot1 = new Bootstrap();
boot1.group(group1)
.channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
.localAddress(addr1).remoteAddress(addr2).handler(handler1);
final Bootstrap boot2 = new Bootstrap();
boot2.group(group2)
.channelFactory(NioUdtProvider.MESSAGE_RENDEZVOUS)
.localAddress(addr2).remoteAddress(addr1).handler(handler2);
final ChannelFuture connectFuture1 = boot1.connect();
final ChannelFuture connectFuture2 = boot2.connect();
while (handler1.meter().count() < transferLimit
&& handler2.meter().count() < transferLimit) {
log.info("progress : {} {}", handler1.meter().count(), handler2
.meter().count());
Thread.sleep(1000);
}
connectFuture1.channel().close().sync();
connectFuture2.channel().close().sync();
log.info("handler1 : {}", handler1.meter().count());
log.info("handler2 : {}", handler2.meter().count());
assertTrue(handler1.meter().count() >= transferLimit);
assertTrue(handler2.meter().count() >= transferLimit);
assertEquals(handler1.meter().count(), handler2.meter().count());
group1.shutdownGracefully();
group2.shutdownGracefully();
group1.terminationFuture().sync();
group2.terminationFuture().sync();
}
}

View File

@ -1,74 +0,0 @@
/*
* Copyright 2012 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.test.udt.nio;
import io.netty.channel.udt.UdtServerChannel;
import io.netty.channel.udt.nio.NioUdtByteAcceptorChannel;
import io.netty.channel.udt.nio.NioUdtByteConnectorChannel;
import io.netty.channel.udt.nio.NioUdtByteRendezvousChannel;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.channel.udt.nio.NioUdtMessageAcceptorChannel;
import io.netty.channel.udt.nio.NioUdtMessageConnectorChannel;
import io.netty.channel.udt.nio.NioUdtMessageRendezvousChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class NioUdtProviderTest extends AbstractUdtTest {
/**
* verify factory
*/
@Test
public void provideFactory() {
NioUdtByteAcceptorChannel nioUdtByteAcceptorChannel
= (NioUdtByteAcceptorChannel) NioUdtProvider.BYTE_ACCEPTOR.newChannel();
NioUdtByteConnectorChannel nioUdtByteConnectorChannel
= (NioUdtByteConnectorChannel) NioUdtProvider.BYTE_CONNECTOR.newChannel();
NioUdtByteRendezvousChannel nioUdtByteRendezvousChannel
= (NioUdtByteRendezvousChannel) NioUdtProvider.BYTE_RENDEZVOUS.newChannel();
NioUdtMessageAcceptorChannel nioUdtMessageAcceptorChannel
= (NioUdtMessageAcceptorChannel) NioUdtProvider.MESSAGE_ACCEPTOR.newChannel();
NioUdtMessageConnectorChannel nioUdtMessageConnectorChannel
= (NioUdtMessageConnectorChannel) NioUdtProvider.MESSAGE_CONNECTOR.newChannel();
NioUdtMessageRendezvousChannel nioUdtMessageRendezvousChannel
= (NioUdtMessageRendezvousChannel) NioUdtProvider.MESSAGE_RENDEZVOUS.newChannel();
// bytes
assertNotNull(nioUdtByteAcceptorChannel);
assertNotNull(nioUdtByteConnectorChannel);
assertNotNull(nioUdtByteRendezvousChannel);
// message
assertNotNull(nioUdtMessageAcceptorChannel);
assertNotNull(nioUdtMessageConnectorChannel);
assertNotNull(nioUdtMessageRendezvousChannel);
// channel
assertNotNull(NioUdtProvider.channelUDT(nioUdtByteAcceptorChannel));
assertNotNull(NioUdtProvider.channelUDT(nioUdtByteConnectorChannel));
assertNotNull(NioUdtProvider.channelUDT(nioUdtByteRendezvousChannel));
assertNotNull(NioUdtProvider.channelUDT(nioUdtMessageAcceptorChannel));
assertNotNull(NioUdtProvider.channelUDT(nioUdtMessageConnectorChannel));
assertNotNull(NioUdtProvider.channelUDT(nioUdtMessageRendezvousChannel));
// acceptor types
assertTrue(NioUdtProvider.BYTE_ACCEPTOR.newChannel() instanceof UdtServerChannel);
assertTrue(NioUdtProvider.MESSAGE_ACCEPTOR.newChannel() instanceof UdtServerChannel);
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* UDT NIO
*/
package io.netty.test.udt.nio;

View File

@ -1,99 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.google.caliper.SimpleBenchmark;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* Base class for caliper/metrics benchmarks.
*/
public abstract class CaliperBench extends SimpleBenchmark {
/**
* Ensure no network latency after JVM shutdown
*/
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
TrafficControl.delay(0);
} catch (final Exception e) {
e.printStackTrace();
}
}
});
}
protected final InternalLogger log = InternalLoggerFactory.getInstance(getClass());
private volatile CaliperMeasure measure;
/**
* Caliper metrics wrapper.
*/
protected CaliperMeasure measure() {
return measure;
}
/**
* Start measurement.
*/
@Override
protected void setUp() throws Exception {
measure = new CaliperMeasure();
}
/**
* Finish measurement.
*/
@Override
protected void tearDown() throws Exception {
measure.shutdown();
}
/**
* Measure time step and minimum run time.
*/
protected long markStep() {
return 3 * 1000;
}
/**
* Measure progress while in sleep.
*/
protected void markWait(final long time) throws Exception {
final long timeStart = System.currentTimeMillis();
while (true) {
Thread.sleep(markStep());
measure().mark();
final long timeFinish = System.currentTimeMillis();
if (timeFinish - timeStart >= time) {
System.out.print("+\n");
return;
} else {
System.out.print("-");
continue;
}
}
}
}

View File

@ -1,215 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.google.caliper.Measurement;
import com.google.caliper.MeasurementSet;
import com.google.caliper.Run;
import com.google.caliper.Scenario;
import com.google.caliper.ScenarioResult;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.Timer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Caliper measure with Metrics provider.
* <p>
* measure up to 3 values: {@link #rate()}, {@link #time()}, {@link #size()}
*/
public class CaliperMeasure {
/**
* Gauge any double value
*/
public static class SizeGuage extends Gauge<Double> {
private volatile Double size = 0.0;
@Override
public Double value() {
return size;
}
public void value(final double size) {
this.size = size;
}
}
/**
* Default rate measurement units.
*/
private static final Map<String, Integer> RATE_UNIT = new HashMap<String, Integer>();
static {
RATE_UNIT.put("Rate B/s", 1);
RATE_UNIT.put("Rate KB/s", 1024);
RATE_UNIT.put("Rate MB/s", 1024 * 1024);
RATE_UNIT.put("Rate GB/s", 1024 * 1024 * 1024);
}
/**
* Default time measurement units.
*/
private static final Map<String, Integer> TIME_UNIT = new HashMap<String, Integer>();
static {
TIME_UNIT.put("Time ns", 1);
TIME_UNIT.put("Time us", 1000);
TIME_UNIT.put("Time ms", 1000 * 1000);
TIME_UNIT.put("Time s ", 1000 * 1000 * 1000);
}
/**
* Default size measurement units.
*/
private static final Map<String, Integer> SIZE_UNIT = new HashMap<String, Integer>();
static {
SIZE_UNIT.put("Size B", 1);
SIZE_UNIT.put("Size KB", 1024);
SIZE_UNIT.put("Size MB", 1024 * 1024);
SIZE_UNIT.put("Size GB", 1024 * 1024 * 1024);
}
private final Map<Long, Measurement> rateMap = new HashMap<Long, Measurement>();
private final Map<Long, Measurement> timeMap = new HashMap<Long, Measurement>();
private final Map<Long, Measurement> sizeMap = new HashMap<Long, Measurement>();
private final MetricsRegistry metrics = new MetricsRegistry();
private final Meter rate = metrics.newMeter(getClass(), "rate", "bytes",
TimeUnit.SECONDS);
private final Timer time = metrics.newTimer(getClass(), "time",
TimeUnit.NANOSECONDS, TimeUnit.SECONDS);
private final SizeGuage size = new SizeGuage();
{
metrics.newGauge(getClass(), "", size);
}
/**
* Rate meter.
*/
public Meter rate() {
return rate;
}
/**
* Time meter.
*/
public Timer time() {
return time;
}
/**
* Size meter.
*/
public SizeGuage size() {
return size;
}
/**
* Workaround: zero breaks gwt web app.
*/
private static double filter(final double value) {
if (value <= 0.0) {
return 1.0;
} else {
return value;
}
}
/**
* Perform measurement; convert from metrics into caliper.
*/
@SuppressWarnings("FloatingPointEquality")
public void mark() {
final double rateValue = filter(rate.oneMinuteRate());
final double timeValue = filter(time.mean());
final double sizeValue = filter(size.value());
if (rateValue == 1.0 && timeValue == 1.0 && sizeValue == 1.0) {
/** ignore complete blank entries */
return;
}
final Measurement markRate = new Measurement(RATE_UNIT, rateValue,
rateValue);
rateMap.put(System.nanoTime(), markRate);
final Measurement markTime = new Measurement(TIME_UNIT, timeValue,
timeValue);
timeMap.put(System.nanoTime(), markTime);
final Measurement markSize = new Measurement(SIZE_UNIT, sizeValue,
sizeValue);
sizeMap.put(System.nanoTime(), markSize);
}
private final Map<String, String> variables = new HashMap<String, String>();
/**
* Caliper scenario variables.
*/
public Map<String, String> variables() {
return variables;
}
private static MeasurementSet measurementSet(final Map<Long, Measurement> map) {
final Measurement[] array = map.values().toArray(new Measurement[0]);
return new MeasurementSet(array);
}
/**
* Attach this measure to parent caliper run.
*/
public void appendTo(final Run run) {
final Scenario scenario = new Scenario(variables());
/** display rate as caliper durations */
final MeasurementSet timeSet = measurementSet(rateMap);
final String timeLog = null;
/** display time as caliper instances */
final MeasurementSet instSet = measurementSet(timeMap);
final String instLog = null;
/** display size as caliper memory */
final MeasurementSet heapSet = measurementSet(sizeMap);
final String heapLog = null;
final ScenarioResult scenarioResult = new ScenarioResult(timeSet,
timeLog, instSet, instLog, heapSet, heapLog);
final Map<Scenario, ScenarioResult> measurements = run
.getMeasurements();
measurements.put(scenario, scenarioResult);
}
/**
* Terminate metrics resources.
*/
public void shutdown() {
rate.stop();
time.stop();
metrics.shutdown();
}
}

View File

@ -1,239 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.google.caliper.ConfiguredBenchmark;
import com.google.caliper.Environment;
import com.google.caliper.EnvironmentGetter;
import com.google.caliper.Json;
import com.google.caliper.Result;
import com.google.caliper.Run;
import com.google.caliper.Runner;
import com.google.caliper.Scenario;
import com.google.caliper.ScenarioResult;
import com.google.caliper.SimpleBenchmark;
import com.yammer.metrics.core.TimerContext;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Custom caliper runner for {@link CaliperBench}.
*/
public final class CaliperRunner {
private static final InternalLogger log = InternalLoggerFactory.getInstance(CaliperRunner.class);
private CaliperRunner() {
}
/**
* Parse bench parameters.
*/
public static List<String> valueList(final String valueText) {
return Arrays.asList(valueText.split(","));
}
/**
* Execute full cycle: warm up, execute and publish benchmark.
*/
public static void execute(final Class<? extends CaliperBench> klaz)
throws Exception {
execute("WARMUP", klaz);
Run run = execute("REPORT", klaz);
publish(newResult(run));
}
/**
* Execute benchmark for all parameter combinations.
*/
public static Run execute(final String name,
final Class<? extends CaliperBench> klaz) throws Exception {
final CaliperBench booter = klaz.getConstructor().newInstance();
final List<Map<String, String>> varsSet = product(booter);
final Run run = newRun(klaz.getName());
int index = 0;
for (final Map<String, String> vars : varsSet) {
final int done = 100 * index++ / varsSet.size();
log.info("{} {}% {}", name, done, vars);
/** call setUp() */
final ConfiguredBenchmark runner = booter.createBenchmark(vars);
final CaliperBench bench = (CaliperBench) runner.getBenchmark();
final CaliperMeasure measure = bench.measure();
measure.variables().putAll(vars);
/** call timeXXX() */
runner.run(0);
/** call tearDown() */
runner.close();
measure.appendTo(run);
}
return run;
}
/**
* Convert caliper result into JSON string.
*/
public static String json(final Result result) {
return Json.getGsonInstance().toJson(result);
}
/**
* Map signature based on map values.
*/
public static String signature(final Map<String, String> map) {
final StringBuilder text = new StringBuilder();
for (final String item : map.values()) {
text.append(String.format("%20s", item));
}
return text.toString();
}
/**
* Generate all parameter combinations for {@link SimpleBenchmark}.
*/
public static List<Map<String, String>> product(final SimpleBenchmark bench) {
final Set<Map<String, String>> collect = new HashSet<Map<String, String>>();
final Map<String, Set<String>> pending = new TreeMap<String, Set<String>>();
for (final String name : new TreeSet<String>(bench.parameterNames())) {
pending.put(name, bench.parameterValues(name));
}
final List<Map<String, String>> list = new ArrayList<Map<String, String>>(
product(collect, pending));
final Comparator<Map<String, String>> comp = new Comparator<Map<String, String>>() {
@Override
public int compare(final Map<String, String> o1,
final Map<String, String> o2) {
return signature(o1).compareTo(signature(o2));
}
};
Collections.sort(list, comp);
return list;
}
/**
* Calculate ordered Cartesian product of sets.
*/
public static Set<Map<String, String>> product(
final Set<Map<String, String>> collect,
final Map<String, Set<String>> pending) {
if (pending.isEmpty()) {
return collect;
}
final Set<Map<String, String>> extract = new HashSet<Map<String, String>>();
final String key = pending.keySet().iterator().next();
for (final String value : pending.remove(key)) {
final Map<String, String> map = new TreeMap<String, String>();
map.put(key, value);
extract.add(map);
}
if (collect.isEmpty()) {
collect.addAll(extract);
return product(collect, pending);
} else {
final Set<Map<String, String>> inject = new HashSet<Map<String, String>>();
for (final Map<String, String> mapExtr : extract) {
for (final Map<String, String> mapColl : collect) {
final Map<String, String> mapProd = new TreeMap<String, String>();
mapProd.putAll(mapExtr);
mapProd.putAll(mapColl);
inject.add(mapProd);
}
}
return product(inject, pending);
}
}
/**
* Publish result on http://microbenchmarks.appspot.com
*/
public static void publish(final Result result) throws Exception {
final Runner runner = new Runner();
final Method method = runner.getClass().getDeclaredMethod(
"postResults", Result.class);
method.setAccessible(true);
method.invoke(runner, result);
}
/**
* Provide new named run instance.
*/
public static Run newRun(final String benchmarkName) {
final Map<Scenario, ScenarioResult> measurements = new HashMap<Scenario, ScenarioResult>();
final Date executedTimestamp = new Date();
return new Run(measurements, benchmarkName, executedTimestamp);
}
/**
* Make new result from run.
*/
public static Result newResult(final Run run) {
final Environment env = new EnvironmentGetter().getEnvironmentSnapshot();
return new Result(run, env);
}
/**
* Verify measure publication manually.
*/
public static void main(final String[] args) throws Exception {
final Run run = newRun("test-main");
for (int param = 0; param < 5; param++) {
final CaliperMeasure measure = new CaliperMeasure();
measure.variables().put("param", String.valueOf(param));
for (int step = 0; step < 5; step++) {
measure.rate().mark(50 + step);
final TimerContext time = measure.time().time();
Thread.sleep(15);
time.stop();
measure.size().value(50 + step);
measure.mark();
}
measure.appendTo(run);
}
final Result result = newResult(run);
publish(result);
System.out.println(json(result));
}
}

View File

@ -1,250 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Clock;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.Metered;
import com.yammer.metrics.core.Metric;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricPredicate;
import com.yammer.metrics.core.MetricProcessor;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.reporting.AbstractPollingReporter;
import com.yammer.metrics.stats.Snapshot;
import java.io.PrintStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* A simple reporters which prints out application metrics to a
* {@link PrintStream} periodically.
*/
public class CustomReporter extends AbstractPollingReporter implements
MetricProcessor<PrintStream> {
private static final int CONSOLE_WIDTH = 80;
/**
* Enables the console reporter for the default metrics registry, and causes
* it to print to STDOUT with the specified period.
*/
public static void enable(final long period, final TimeUnit unit) {
enable(Metrics.defaultRegistry(), period, unit);
}
/**
* Enables the console reporter for the given metrics registry, and causes
* it to print to STDOUT with the specified period and unrestricted output.
*/
public static void enable(final MetricsRegistry metricsRegistry,
final long period, final TimeUnit unit) {
final CustomReporter reporter = new CustomReporter(
metricsRegistry, System.out, MetricPredicate.ALL);
reporter.start(period, unit);
}
private final PrintStream out;
private final MetricPredicate predicate;
private final Clock clock;
private final TimeZone timeZone;
private final Locale locale;
/**
* Creates a new {@link CustomReporter} for the default metrics
* registry, with unrestricted output.
*/
public CustomReporter(final PrintStream out) {
this(Metrics.defaultRegistry(), out, MetricPredicate.ALL);
}
/**
* Creates a new {@link CustomReporter} for a given metrics registry.
*/
public CustomReporter(final MetricsRegistry metricsRegistry,
final PrintStream out, final MetricPredicate predicate) {
this(metricsRegistry, out, predicate, Clock.defaultClock(), TimeZone
.getDefault());
}
/**
* Creates a new {@link CustomReporter} for a given metrics registry.
*/
public CustomReporter(final MetricsRegistry metricsRegistry,
final PrintStream out, final MetricPredicate predicate,
final Clock clock, final TimeZone timeZone) {
this(metricsRegistry, out, predicate, clock, timeZone, Locale
.getDefault());
}
/**
* Creates a new {@link CustomReporter} for a given metrics registry.
*/
public CustomReporter(final MetricsRegistry metricsRegistry,
final PrintStream out, final MetricPredicate predicate,
final Clock clock, final TimeZone timeZone, final Locale locale) {
super(metricsRegistry, "console-reporter");
this.out = out;
this.predicate = predicate;
this.clock = clock;
this.timeZone = timeZone;
this.locale = locale;
}
@Override
public void run() {
try {
final DateFormat format = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.MEDIUM, locale);
format.setTimeZone(timeZone);
final String dateTime = format.format(new Date(clock.time()));
out.print(dateTime);
out.print(' ');
for (int i = 0; i < CONSOLE_WIDTH - dateTime.length() - 1; i++) {
out.print('=');
}
out.println();
for (final Entry<String, SortedMap<MetricName, Metric>> entry : getMetricsRegistry()
.groupedMetrics(predicate).entrySet()) {
out.print(entry.getKey());
out.println(':');
for (final Entry<MetricName, Metric> subEntry : entry
.getValue().entrySet()) {
out.print(" ");
out.print(subEntry.getKey().getName());
out.println(':');
subEntry.getValue().processWith(this, subEntry.getKey(),
out);
out.println();
}
out.println();
}
out.println();
out.flush();
} catch (final Exception e) {
e.printStackTrace(out);
}
}
@Override
public void processGauge(final MetricName name, final Gauge<?> gauge,
final PrintStream stream) {
stream.printf(locale, " value = %s\n", gauge.value());
}
@Override
public void processCounter(final MetricName name, final Counter counter,
final PrintStream stream) {
stream.printf(locale, " count = %,d\n", counter.count());
}
@Override
public void processMeter(final MetricName name, final Metered meter,
final PrintStream stream) {
final String unit = abbrev(meter.rateUnit());
stream.printf(locale, " count = %,d\n", meter.count());
stream.printf(locale, " mean rate = %,2.2f %s/%s\n",
meter.meanRate(), meter.eventType(), unit);
stream.printf(locale, " 1-minute rate = %,2.2f %s/%s\n",
meter.oneMinuteRate(), meter.eventType(), unit);
stream.printf(locale, " 5-minute rate = %,2.2f %s/%s\n",
meter.fiveMinuteRate(), meter.eventType(), unit);
stream.printf(locale, " 15-minute rate = %,2.2f %s/%s\n",
meter.fifteenMinuteRate(), meter.eventType(), unit);
}
@Override
public void processHistogram(final MetricName name,
final Histogram histogram, final PrintStream stream) {
final Snapshot snapshot = histogram.getSnapshot();
stream.printf(locale, " min = %,2.2f\n", histogram.min());
stream.printf(locale, " max = %,2.2f\n", histogram.max());
stream.printf(locale, " mean = %,2.2f\n", histogram.mean());
stream.printf(locale, " stddev = %,2.2f\n",
histogram.stdDev());
stream.printf(locale, " median = %,2.2f\n",
snapshot.getMedian());
stream.printf(locale, " 75%% <= %,2.2f\n",
snapshot.get75thPercentile());
stream.printf(locale, " 95%% <= %,2.2f\n",
snapshot.get95thPercentile());
stream.printf(locale, " 98%% <= %,2.2f\n",
snapshot.get98thPercentile());
stream.printf(locale, " 99%% <= %,2.2f\n",
snapshot.get99thPercentile());
stream.printf(locale, " 99.9%% <= %,2.2f\n",
snapshot.get999thPercentile());
}
@Override
public void processTimer(final MetricName name, final Timer timer,
final PrintStream stream) {
processMeter(name, timer, stream);
final String durationUnit = abbrev(timer.durationUnit());
final Snapshot snapshot = timer.getSnapshot();
stream.printf(locale, " min = %,2.2f %s\n", timer.min(),
durationUnit);
stream.printf(locale, " max = %,2.2f %s\n", timer.max(),
durationUnit);
stream.printf(locale, " mean = %,2.2f %s\n", timer.mean(),
durationUnit);
stream.printf(locale, " stddev = %,2.2f %s\n",
timer.stdDev(), durationUnit);
stream.printf(locale, " median = %,2.2f %s\n",
snapshot.getMedian(), durationUnit);
stream.printf(locale, " 75%% <= %,2.2f %s\n",
snapshot.get75thPercentile(), durationUnit);
stream.printf(locale, " 95%% <= %,2.2f %s\n",
snapshot.get95thPercentile(), durationUnit);
stream.printf(locale, " 98%% <= %,2.2f %s\n",
snapshot.get98thPercentile(), durationUnit);
stream.printf(locale, " 99%% <= %,2.2f %s\n",
snapshot.get99thPercentile(), durationUnit);
stream.printf(locale, " 99.9%% <= %,2.2f %s\n",
snapshot.get999thPercentile(), durationUnit);
}
private static String abbrev(final TimeUnit unit) {
switch (unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "us";
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
case MINUTES:
return "m";
case HOURS:
return "h";
case DAYS:
return "d";
default:
throw new IllegalArgumentException("Unrecognized TimeUnit: " + unit);
}
}
}

View File

@ -1,81 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.yammer.metrics.core.Meter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* Handler implementation for the echo client. It initiates the ping-pong
* traffic between the echo client and server by sending the first message to
* the server on activation.
*/
public class EchoByteHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log = InternalLoggerFactory.getInstance(EchoByteHandler.class);
private final ByteBuf message;
private final Meter meter;
public Meter meter() {
return meter;
}
public EchoByteHandler(final Meter meter, final int messageSize) {
this.meter = meter;
message = Unpooled.buffer(messageSize);
for (int i = 0; i < message.capacity(); i++) {
message.writeByte((byte) i);
}
}
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
log.info("ECHO active {}", NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
if (meter != null) {
meter.mark(buf.readableBytes());
}
ctx.writeAndFlush(msg);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx,
final Throwable e) {
log.error("exception : {}", e.getMessage());
ctx.close();
}
}

View File

@ -1,77 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.yammer.metrics.core.Meter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.udt.UdtMessage;
import io.netty.channel.udt.nio.NioUdtProvider;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* Handler implementation for the echo peer. It initiates the ping-pong traffic
* between the echo peers by sending the first message to the other peer on
* activation.
*/
public class EchoMessageHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger log = InternalLoggerFactory.getInstance(EchoMessageHandler.class);
private final Meter meter;
private final UdtMessage message;
public Meter meter() {
return meter;
}
public EchoMessageHandler(final Meter meter, final int messageSize) {
this.meter = meter;
final ByteBuf byteBuf = Unpooled.buffer(messageSize);
for (int i = 0; i < byteBuf.capacity(); i++) {
byteBuf.writeByte((byte) i);
}
message = new UdtMessage(byteBuf);
}
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
log.info("ECHO active {}", NioUdtProvider.socketUDT(ctx.channel()).toStringOptions());
ctx.writeAndFlush(message);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable e) {
log.error("exception", e);
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
UdtMessage udtMsg = (UdtMessage) msg;
if (meter != null) {
meter.mark(udtMsg.content().readableBytes());
}
ctx.writeAndFlush(msg);
}
}

View File

@ -1,79 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
/**
* Introduce traffic control, such as transfer latency.
* <p>
* requires sudo setup for /sbin/tc under current account
* <p>
* see http://www.davidverhasselt.com/2008/01/27/passwordless-sudo/
*/
public final class TrafficControl {
private static final InternalLogger log = InternalLoggerFactory.getInstance(TrafficControl.class);
private TrafficControl() {
}
private static final String TC_DELAY = "sudo tc qdisc add dev %s root netem delay %sms limit %s";
private static final String TC_RESET = "sudo tc qdisc del dev %s root";
/**
* verify if traffic control is available
*/
public static boolean isAvailable() {
try {
final int millis = 100;
final int margin = 20;
delay(0);
final long time1 = UnitHelp.ping("localhost");
delay(millis);
final long time2 = UnitHelp.ping("localhost");
delay(0);
final long time3 = UnitHelp.ping("localhost");
return time2 >= time1 + millis - margin
&& time2 >= time3 + millis - margin;
} catch (final Throwable e) {
log.debug("", e);
return false;
}
}
/**
* Introduce round-trip delay on local host
* @param time - delay in milliseconds; use zero to remove delay.
*/
public static void delay(final int time) throws Exception {
if (time < 0) {
throw new IllegalArgumentException("negative latency");
}
final int delay = time / 2;
if (delay == 0) {
UnitHelp.process(String.format(TC_RESET, "lo"));
} else {
/** extend packet buffer queue to avoid packet loss due to latency */
final int limit = 1024 * 1024;
UnitHelp.process(String.format(TC_RESET, "lo"));
UnitHelp.process(String.format(TC_DELAY, "lo", delay, limit));
}
}
}

View File

@ -1,277 +0,0 @@
/*
* Copyright 2012 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.test.udt.util;
import com.barchart.udt.SocketUDT;
import com.barchart.udt.StatusUDT;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.IntBuffer;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
/**
* Unit test helper.
*/
public final class UnitHelp {
private static final InternalLogger log = InternalLoggerFactory.getInstance(UnitHelp.class);
private static final Pattern SPACES = Pattern.compile("\\s+");
/**
* Verify class loading with class initialization.
*/
public static boolean canLoadAndInitClass(String name) {
try {
Class.forName(name, true, UnitHelp.class.getClassLoader());
log.info("Class load and init success.");
return true;
} catch (Throwable e) {
log.warn("Class load or init failure.", e);
return false;
}
}
/**
* Zero out buffer.
*/
public static void clear(final IntBuffer buffer) {
for (int index = 0; index < buffer.capacity(); index++) {
buffer.put(index, 0);
}
}
/**
* Measure ping time to a host.
*/
public static long ping(final String host) throws Exception {
final String name = System.getProperty("os.name").toLowerCase();
final String command;
if (name.contains("linux")) {
command = "ping -c 1 " + host;
} else if (name.contains("mac os x")) {
command = "ping -c 1 " + host;
} else if (name.contains("windows")) {
command = "ping -n 1 " + host;
} else {
throw new Exception("unknown platform");
}
final long timeStart = System.currentTimeMillis();
process(command);
final long timeFinish = System.currentTimeMillis();
return timeFinish - timeStart;
}
/**
* Invoke external process and wait for completion.
*/
public static void process(final String command) throws Exception {
final ProcessBuilder builder = new ProcessBuilder(SPACES.split(command));
final Process process = builder.start();
process.waitFor();
}
/**
* @return newly allocated address or null for failure
*/
public static synchronized InetSocketAddress findLocalAddress(
final String host) {
ServerSocket socket = null;
try {
final InetAddress address = SocketUtils.addressByName(host);
socket = new ServerSocket(0, 3, address);
return (InetSocketAddress) socket.getLocalSocketAddress();
} catch (final Exception e) {
log.error("Failed to find address.");
return null;
} finally {
if (socket != null) {
try {
socket.close();
} catch (final Exception e) {
log.error("Failed to close socket.");
}
}
}
}
/**
* Find named address on local host.
*/
public static InetSocketAddress hostedSocketAddress(final String host)
throws Exception {
for (int k = 0; k < 10; k++) {
final InetSocketAddress address = findLocalAddress(host);
if (address == null) {
Thread.sleep(500);
continue;
}
return address;
}
throw new Exception("Failed to allocate address.");
}
/**
* Allocate available local address / port or throw exception.
*/
public static InetSocketAddress localSocketAddress() throws Exception {
return hostedSocketAddress("localhost");
}
/**
* Display contents of a buffer.
*/
public static void logBuffer(final String title, final IntBuffer buffer) {
for (int index = 0; index < buffer.capacity(); index++) {
final int value = buffer.get(index);
if (value == 0) {
continue;
}
log.info(String.format("%s [id: 0x%08x]", title, value));
}
}
/**
* Display java.class.path
*/
public static void logClassPath() {
final String classPath = System.getProperty("java.class.path");
final String[] entries = classPath.split(File.pathSeparator);
final StringBuilder text = new StringBuilder(1024);
for (final String item : entries) {
text.append("\n\t");
text.append(item);
}
log.info("\n\t[java.class.path]{}", text);
}
/**
* Display java.library.path
*/
public static void logLibraryPath() {
final String classPath = System.getProperty("java.library.path");
final String[] entries = classPath.split(File.pathSeparator);
final StringBuilder text = new StringBuilder(1024);
for (final String item : entries) {
text.append("\n\t");
text.append(item);
}
log.info("\n\t[java.library.path]{}", text);
}
/**
* Display current OS/ARCH.
*/
public static void logOsArch() {
final StringBuilder text = new StringBuilder(1024)
.append("\n\t")
.append(System.getProperty("os.name"))
.append("\n\t")
.append(System.getProperty("os.arch"));
log.info("\n\t[os/arch]{}", text);
}
/**
* Display contents of a set.
*/
public static void logSet(final Set<?> set) {
@SuppressWarnings("unchecked")
final TreeSet<?> treeSet = new TreeSet(set);
for (final Object item : treeSet) {
log.info("-> {}", item);
}
}
public static String property(final String name) {
final String value = System.getProperty(name);
if (value == null) {
log.error("property '{}' not defined; terminating", name);
System.exit(1);
}
return value;
}
public static int[] randomIntArray(final int length, final int range) {
final int[] array = new int[length];
final Random generator = PlatformDependent.threadLocalRandom();
for (int i = 0; i < array.length; i++) {
array[i] = generator.nextInt(range);
}
return array;
}
public static String randomString() {
return String.valueOf(System.currentTimeMillis());
}
public static String randomSuffix(final String name) {
return name + '-' + System.currentTimeMillis();
}
/**
* Block till socket reaches given state.
*/
public static void socketAwait(final SocketUDT socket,
final StatusUDT... statusArray) throws Exception {
while (true) {
for (final StatusUDT status : statusArray) {
if (socket.status() == status) {
return;
} else {
Thread.sleep(50);
}
}
}
}
public static Set<Integer> socketIndexSet(final IntBuffer buffer) {
final Set<Integer> set = new HashSet<Integer>();
while (buffer.hasRemaining()) {
set.add(buffer.get());
}
return set;
}
public static boolean socketPresent(final SocketUDT socket,
final IntBuffer buffer) {
for (int index = 0; index < buffer.capacity(); index++) {
if (buffer.get(index) == socket.id()) {
return true;
}
}
return false;
}
private UnitHelp() {
}
}

View File

@ -1,21 +0,0 @@
/*
* Copyright 2012 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.
*/
/**
* UDT Benchmarks and Tests Utilities
*/
package io.netty.test.udt.util;