<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
sshProxyServer = new SshProxyServer(Executors.newScheduledThreadPool(1), workerGroup, eventExecutor);
final InetSocketAddress inetAddress = getInetAddress(bindingAddress, portNumber);
- final SshProxyServerConfigurationBuilder sshProxyServerConfigurationBuilder = new SshProxyServerConfigurationBuilder();
+ final SshProxyServerConfigurationBuilder sshProxyServerConfigurationBuilder =
+ new SshProxyServerConfigurationBuilder();
sshProxyServerConfigurationBuilder.setBindingAddress(inetAddress);
sshProxyServerConfigurationBuilder.setLocalAddress(localAddress);
sshProxyServerConfigurationBuilder.setAuthenticator(authProvider);
private InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
try {
- IpAddress ipAddress= IpAddressBuilder.getDefaultInstance(bindingAddress);
- final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
+ IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
+ final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null
+ ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
return new InetSocketAddress(inetAd, Integer.valueOf(portNumber));
} catch (final UnknownHostException e) {
throw new IllegalArgumentException("Unable to bind netconf endpoint to address " + bindingAddress, e);
* This command handles all netconf related rpc and forwards to delegate server.
* Uses netty to make a local connection to delegate server.
*
+ * <p>
* Command is Apache Mina SSH terminology for objects handling ssh data.
*/
public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
final Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(clientEventGroup).channel(LocalChannel.class);
- clientBootstrap
- .handler(new ChannelInitializer<LocalChannel>() {
- @Override
- public void initChannel(final LocalChannel ch) throws Exception {
- ch.pipeline().addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback));
- }
- });
+ clientBootstrap.handler(new ChannelInitializer<LocalChannel>() {
+ @Override
+ public void initChannel(final LocalChannel ch) throws Exception {
+ ch.pipeline()
+ .addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback));
+ }
+ });
clientChannelFuture = clientBootstrap.connect(localAddress);
clientChannelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
- if(future.isSuccess()) {
+ if (future.isSuccess()) {
clientChannel = clientChannelFuture.channel();
} else {
- LOG.warn("Unable to establish internal connection to netconf server for client: {}", getClientAddress());
+ LOG.warn("Unable to establish internal connection to netconf server for client: {}",
+ getClientAddress());
Preconditions.checkNotNull(callback, "Exit callback must be set");
- callback.onExit(1, "Unable to establish internal connection to netconf server for client: "+ getClientAddress());
+ callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
+ + getClientAddress());
}
}
});
getClientAddress(), clientChannel);
clientChannelFuture.cancel(true);
- if(clientChannel != null) {
+ if (clientChannel != null) {
clientChannel.close().addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
if (future.isSuccess() == false) {
- LOG.warn("Unable to release internal connection to netconf server on channel: {}", clientChannel);
+ LOG.warn("Unable to release internal connection to netconf server on channel: {}",
+ clientChannel);
}
}
});
final SocketAddress remoteAddress = session.getIoSession().getRemoteAddress();
String hostName = "";
String port = "";
- if(remoteAddress instanceof InetSocketAddress) {
+ if (remoteAddress instanceof InetSocketAddress) {
hostName = ((InetSocketAddress) remoteAddress).getAddress().getHostAddress();
port = Integer.toString(((InetSocketAddress) remoteAddress).getPort());
}
import org.slf4j.LoggerFactory;
/**
- * Netty handler that reads SSH from remote client and writes to delegate server and reads from delegate server and writes to remote client
+ * Netty handler that reads SSH from remote client and writes to delegate server
+ * and reads from delegate server and writes to remote client.
*/
final class SshProxyClientHandler extends ChannelInboundHandlerAdapter {
private final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader;
private final ExitCallback callback;
- public SshProxyClientHandler(final IoInputStream in, final IoOutputStream out,
- final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader,
- final ExitCallback callback) {
+ SshProxyClientHandler(final IoInputStream in, final IoOutputStream out,
+ final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader,
+ final ExitCallback callback) {
this.in = in;
this.out = out;
this.netconfHelloMessageAdditionalHeader = netconfHelloMessageAdditionalHeader;
}, new AsyncSshHandlerReader.ReadMsgHandler() {
@Override
public void onMessageRead(final ByteBuf msg) {
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("Forwarding message for client: {} on channel: {}, message: {}",
- netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), AsyncSshHandlerWriter.byteBufToString(msg));
+ netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(),
+ AsyncSshHandlerWriter.byteBufToString(msg));
}
// Just forward to delegate
ctx.writeAndFlush(msg);
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
LOG.debug("Internal connection to netconf server was dropped for client: {} on channel: ",
netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel());
- callback.onExit(1, "Internal connection to netconf server was dropped for client: " +
- netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel());
+ callback.onExit(1, "Internal connection to netconf server was dropped for client: "
+ + netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel());
super.channelInactive(ctx);
}
private final EventLoopGroup clientGroup;
private final IoServiceFactoryFactory nioServiceWithPoolFactoryFactory;
- public SshProxyServer(final ScheduledExecutorService minaTimerExecutor, final EventLoopGroup clientGroup, final ExecutorService nioExecutor) {
+ public SshProxyServer(final ScheduledExecutorService minaTimerExecutor,
+ final EventLoopGroup clientGroup, final ExecutorService nioExecutor) {
this.minaTimerExecutor = minaTimerExecutor;
this.clientGroup = clientGroup;
- this.nioServiceWithPoolFactoryFactory = new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor);
+ this.nioServiceWithPoolFactoryFactory =
+ new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor);
this.sshServer = SshServer.setUpDefaultServer();
}
sshServer.setProperties(getProperties(sshProxyServerConfiguration));
final RemoteNetconfCommand.NetconfCommandFactory netconfCommandFactory =
- new RemoteNetconfCommand.NetconfCommandFactory(clientGroup, sshProxyServerConfiguration.getLocalAddress());
+ new RemoteNetconfCommand.NetconfCommandFactory(clientGroup,
+ sshProxyServerConfiguration.getLocalAddress());
sshServer.setSubsystemFactories(ImmutableList.of(netconfCommandFactory));
sshServer.start();
}
}
/**
- * Based on Nio2ServiceFactory with one addition: injectable executor
+ * Based on Nio2ServiceFactory with one addition: injectable executor.
*/
- private static final class NioServiceWithPoolFactory extends CloseableUtils.AbstractCloseable implements IoServiceFactory {
+ private static final class NioServiceWithPoolFactory
+ extends CloseableUtils.AbstractCloseable implements IoServiceFactory {
private final FactoryManager manager;
private final AsynchronousChannelGroup group;
- public NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) {
+ NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) {
this.manager = manager;
try {
group = AsynchronousChannelGroup.withThreadPool(executor);
return new Nio2Acceptor(manager, handler, group);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
protected void doCloseImmediately() {
try {
private final KeyPairProvider keyPairProvider;
private final int idleTimeout;
- SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress, final AuthProvider authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) {
+ SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress,
+ final AuthProvider authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) {
this.bindingAddress = Preconditions.checkNotNull(bindingAddress);
this.localAddress = Preconditions.checkNotNull(localAddress);
this.authenticator = Preconditions.checkNotNull(authenticator);
}
public SshProxyServerConfiguration createSshProxyServerConfiguration() {
- return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, keyPairProvider, idleTimeout);
+ return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator,
+ keyPairProvider, idleTimeout);
}
public static SshProxyServerConfigurationBuilder create() {
private final ServiceTracker<AuthProvider, AuthProvider> listenerTracker;
private volatile AuthProvider authProvider;
- public AuthProviderTracker(final BundleContext bundleContext) {
+ AuthProviderTracker(final BundleContext bundleContext) {
this.bundleContext = bundleContext;
listenerTracker = new ServiceTracker<>(bundleContext, AuthProvider.class, this);
listenerTracker.open();
public void start(final BundleContext bundleContext) throws IOException, InvalidSyntaxException {
minaTimerExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactory() {
@Override
- public Thread newThread(final Runnable r) {
- return new Thread(r, "netconf-ssh-server-mina-timers");
+ public Thread newThread(final Runnable runnable) {
+ return new Thread(runnable, "netconf-ssh-server-mina-timers");
}
});
clientGroup = new NioEventLoopGroup();
server.close();
}
- if(authProviderTracker != null) {
+ if (authProviderTracker != null) {
authProviderTracker.stop();
}
- if(nioExecutor!=null) {
+ if (nioExecutor != null) {
nioExecutor.shutdownNow();
}
- if(clientGroup != null) {
+ if (clientGroup != null) {
clientGroup.shutdownGracefully();
}
- if(minaTimerExecutor != null) {
+ if (minaTimerExecutor != null) {
minaTimerExecutor.shutdownNow();
}
}
this.channelInitializer = channelInitializer;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void run() {
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
- Bootstrap b = new Bootstrap();
+ Bootstrap bootstrap = new Bootstrap();
- b.group(group)
+ bootstrap.group(group)
.channel(LocalChannel.class)
.handler(channelInitializer);
// Start the client.
LocalAddress localAddress = new LocalAddress("foo");
- ChannelFuture f = b.connect(localAddress).sync();
+ ChannelFuture future = bootstrap.connect(localAddress).sync();
// Wait until the connection is closed.
- f.channel().closeFuture().sync();
+ future.channel().closeFuture().sync();
} catch (Exception e) {
LOG.error("Error in client", e);
throw new RuntimeException("Error in client", e);
private ChannelHandlerContext ctx;
private final StringBuilder fromServer = new StringBuilder();
- public static enum State {CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED}
+ public enum State {
+ CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED
+ }
private State state = State.CONNECTING;
public class EchoServer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void run() {
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup)
+ ServerBootstrap bootstrap = new ServerBootstrap();
+ bootstrap.group(bossGroup, workerGroup)
.channel(LocalServerChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
// Start the server.
LocalAddress localAddress = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
- ChannelFuture f = b.bind(localAddress).sync();
+ ChannelFuture future = bootstrap.bind(localAddress).sync();
// Wait until the server socket is closed.
- f.channel().closeFuture().sync();
+ future.channel().closeFuture().sync();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
private static final Logger LOG = LoggerFactory.getLogger(EchoServerHandler.class);
private String fromLastNewLine = "";
private final Splitter splitter = Splitter.onPattern("\r?\n");
+
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
LOG.debug("sleep start");
--- /dev/null
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.netconf.netty;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import java.nio.charset.StandardCharsets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ProxyClientHandler extends ChannelInboundHandlerAdapter {
+ private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
+
+ private final ChannelHandlerContext remoteCtx;
+
+
+ ProxyClientHandler(ChannelHandlerContext remoteCtx) {
+ this.remoteCtx = remoteCtx;
+ }
+
+ @Override
+ public void channelActive(ChannelHandlerContext ctx) {
+ LOG.info("client active");
+ }
+
+ @Override
+ public void channelRead(ChannelHandlerContext ctx, Object msg) {
+ ByteBuf bb = (ByteBuf) msg;
+ LOG.info(">{}", bb.toString(StandardCharsets.UTF_8));
+ remoteCtx.write(msg);
+ }
+
+ @Override
+ public void channelReadComplete(ChannelHandlerContext ctx) {
+ LOG.debug("Flushing server ctx");
+ remoteCtx.flush();
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ // Close the connection when an exception is raised.
+ LOG.warn("Unexpected exception from downstream", cause);
+ ctx.close();
+ }
+
+ // called both when local or remote connection dies
+ @Override
+ public void channelInactive(ChannelHandlerContext ctx) {
+ LOG.debug("channelInactive() called, closing remote client ctx");
+ remoteCtx.close();
+ }
+}
this.proxyHandlerFactory = proxyHandlerFactory;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void run() {
// Configure the server.
final EventLoopGroup bossGroup = new NioEventLoopGroup();
// Start the server.
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
- ChannelFuture f = serverBootstrap.bind(address).sync();
+ ChannelFuture future = serverBootstrap.bind(address).sync();
// Wait until the server socket is closed.
- f.channel().closeFuture().sync();
+ future.channel().closeFuture().sync();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
workerGroup.shutdownGracefully();
}
}
- public static interface ProxyHandlerFactory {
+
+ public interface ProxyHandlerFactory {
ChannelHandler create(EventLoopGroup bossGroup, LocalAddress localAddress);
}
package org.opendaylight.netconf.netty;
import io.netty.bootstrap.Bootstrap;
-import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
import io.netty.channel.local.LocalChannel;
-import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
}
-class ProxyClientHandler extends ChannelInboundHandlerAdapter {
- private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
-
- private final ChannelHandlerContext remoteCtx;
-
-
- public ProxyClientHandler(ChannelHandlerContext remoteCtx) {
- this.remoteCtx = remoteCtx;
- }
-
- @Override
- public void channelActive(ChannelHandlerContext ctx) {
- LOG.info("client active");
- }
-
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- ByteBuf bb = (ByteBuf) msg;
- LOG.info(">{}", bb.toString(StandardCharsets.UTF_8));
- remoteCtx.write(msg);
- }
-
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) {
- LOG.debug("Flushing server ctx");
- remoteCtx.flush();
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- // Close the connection when an exception is raised.
- LOG.warn("Unexpected exception from downstream", cause);
- ctx.close();
- }
-
- // called both when local or remote connection dies
- @Override
- public void channelInactive(ChannelHandlerContext ctx) {
- LOG.debug("channelInactive() called, closing remote client ctx");
- remoteCtx.close();
- }
-}
final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831);
final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec);
- sshProxyServer.bind(
- new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() {
- @Override
- public boolean authenticated(final String username, final String password) {
- return true;
- }
- }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
+ sshProxyServer.bind(new SshProxyServerConfigurationBuilder()
+ .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS)
+ .setAuthenticator(new AuthProvider() {
+ @Override
+ public boolean authenticated(final String username, final String password) {
+ return true;
+ }
+ })
+ .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString()))
+ .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
final EchoClientHandler echoClientHandler = connectClient(addr);
Stopwatch stopwatch = Stopwatch.createStarted();
- while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
+ while (echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
Thread.sleep(500);
}
assertTrue(echoClientHandler.isConnected());
final InetSocketAddress address = new InetSocketAddress(12345);
final EchoClientHandler echoClientHandler = connectClient(address);
final Stopwatch stopwatch = Stopwatch.createStarted();
- while(echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) {
+ while (echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) {
Thread.sleep(100);
}
assertFalse(echoClientHandler.isConnected());
final InetSocketAddress addr = InetSocketAddress.createUnresolved(HOST, PORT);
server = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
- server.bind(
- new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() {
+ server.bind(new SshProxyServerConfigurationBuilder()
+ .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS)
+ .setAuthenticator(new AuthProvider() {
@Override
public boolean authenticated(final String username, final String password) {
return true;
}
- }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
+ })
+ .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString()))
+ .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
LOG.info("SSH server started on {}", PORT);
}