private static int startRpcServer(boolean allowInsecurePorts) { Random rand = new Random(); int serverPort = 30000 + rand.nextInt(10000); int retries = 10; // A few retries in case initial choice is in use. while (true) { try { RpcProgram program = new TestFrameDecoder.TestRpcProgram("TestRpcProgram", "localhost", serverPort, 100000, 1, 2, allowInsecurePorts); SimpleTcpServer tcpServer = new SimpleTcpServer(serverPort, program, 1); tcpServer.run(); break; // Successfully bound a port, break out. } catch (ChannelException ce) { if (retries-- > 0) { serverPort += rand.nextInt(20); // Port in use? Try another. } else { throw ce; // Out of retries. } } } return serverPort; }
public synchronized int start(ChannelPipelineFactory pipelineFactory) { ServerBootstrap bootstrap = new ServerBootstrap(channelFactory); bootstrap.setPipelineFactory(pipelineFactory); // Try to bind to a port. If the port is 0, netty will select a port. int bindAttempt = 0; while (bindAttempt < DEFAULT_BIND_ATTEMPT_MAX) { try { InetSocketAddress address = new InetSocketAddress(port); Channel ch = bootstrap.bind(address); accepted.add(ch); port = ((InetSocketAddress) ch.getLocalAddress()).getPort(); break; } catch (ChannelException e) { LOG.warn("start: Likely failed to bind on attempt " + bindAttempt + " to port " + port, e); // Only increment the port number when set by the user if (port != 0) { ++port; } ++bindAttempt; } } LOG.info(this.getClass() + " is listening on port " + port); return port; }
@Test public void testNewChannel_forwardsWrappedFactoryFailure() { final ChannelException innerException = new ChannelException(); mockContext.checking(new Expectations() { { one(realChannelFactory).newChannel( with(any(ChannelPipeline.class))); will(throwException(innerException)); } }); try { factory.newChannel(Channels.pipeline(new SimpleChannelHandler())); fail("Expected ChannelException"); } catch (ChannelException e) { assertSame(innerException, e); } }
@Test public void testLifecycle() throws InterruptedException { boolean bound = false; for (int i = 0; i < 100 && !bound; i++) { try { Context context = new Context(); context.put("port", String.valueOf(selectedPort = 41414 + i)); context.put("bind", "0.0.0.0"); Configurables.configure(source, context); source.start(); bound = true; } catch (ChannelException e) { /* * NB: This assume we're using the Netty server under the hood and the * failure is to bind. Yucky. */ } } Assert .assertTrue("Reached start or error", LifecycleController.waitForOneOf( source, LifecycleState.START_OR_ERROR)); Assert.assertEquals("Server is started", LifecycleState.START, source.getLifecycleState()); source.stop(); Assert.assertTrue("Reached stop or error", LifecycleController.waitForOneOf(source, LifecycleState.STOP_OR_ERROR)); Assert.assertEquals("Server is stopped", LifecycleState.STOP, source.getLifecycleState()); }
private void startSource(String encoding, String ack, String batchSize, String maxLineLength) throws InterruptedException { boolean bound = false; for (int i = 0; i < 100 && !bound; i++) { try { Context context = new Context(); context.put("port", String.valueOf(selectedPort = 10500 + i)); context.put("bind", "0.0.0.0"); context.put("ack-every-event", ack); context.put("encoding", encoding); context.put("batch-size", batchSize); context.put("max-line-length", maxLineLength); Configurables.configure(source, context); source.start(); bound = true; } catch (ChannelException e) { /* * NB: This assume we're using the Netty server under the hood and the * failure is to bind. Yucky. */ } } Assert.assertTrue("Reached start or error", LifecycleController.waitForOneOf(source, LifecycleState.START_OR_ERROR)); Assert.assertEquals("Server is started", LifecycleState.START, source.getLifecycleState()); }
@Test public void testLifecycle() throws InterruptedException { boolean bound = false; for (int i = 0; i < 100 && !bound; i++) { try { Context context = new Context(); context.put("port", String.valueOf(selectedPort = 41414 + i)); context.put("host", "0.0.0.0"); Configurables.configure(source, context); source.start(); bound = true; } catch (ChannelException e) { // Assume port in use, try another one } } Assert .assertTrue("Reached start or error", LifecycleController.waitForOneOf( source, LifecycleState.START_OR_ERROR)); Assert.assertEquals("Server is started", LifecycleState.START, source.getLifecycleState()); source.stop(); Assert.assertTrue("Reached stop or error", LifecycleController.waitForOneOf(source, LifecycleState.STOP_OR_ERROR)); Assert.assertEquals("Server is stopped", LifecycleState.STOP, source.getLifecycleState()); }
private void startServer() { ChannelFactory channelFactory = new NioServerSocketChannelFactory( newCachedThreadPool(groupedThreads("onos/fpm", "sm-boss-%d")), newCachedThreadPool(groupedThreads("onos/fpm", "sm-worker-%d"))); ChannelPipelineFactory pipelineFactory = () -> { // Allocate a new session per connection FpmSessionHandler fpmSessionHandler = new FpmSessionHandler(new InternalFpmListener()); FpmFrameDecoder fpmFrameDecoder = new FpmFrameDecoder(); // Setup the processing pipeline ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("FpmFrameDecoder", fpmFrameDecoder); pipeline.addLast("FpmSession", fpmSessionHandler); return pipeline; }; InetSocketAddress listenAddress = new InetSocketAddress(FPM_PORT); serverBootstrap = new ServerBootstrap(channelFactory); serverBootstrap.setOption("child.reuseAddr", true); serverBootstrap.setOption("child.keepAlive", true); serverBootstrap.setOption("child.tcpNoDelay", true); serverBootstrap.setPipelineFactory(pipelineFactory); try { serverChannel = serverBootstrap.bind(listenAddress); allChannels.add(serverChannel); } catch (ChannelException e) { log.debug("Exception binding to FPM port {}: ", listenAddress.getPort(), e); stopServer(); } }
public void start() { log.debug("BGP Session Manager start."); isShutdown = false; ChannelFactory channelFactory = new NioServerSocketChannelFactory( newCachedThreadPool(groupedThreads("onos/bgp", "sm-boss-%d")), newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d"))); ChannelPipelineFactory pipelineFactory = () -> { // Allocate a new session per connection BgpSession bgpSessionHandler = new BgpSession(BgpSessionManager.this); BgpFrameDecoder bgpFrameDecoder = new BgpFrameDecoder(bgpSessionHandler); // Setup the processing pipeline ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("BgpFrameDecoder", bgpFrameDecoder); pipeline.addLast("BgpSession", bgpSessionHandler); return pipeline; }; InetSocketAddress listenAddress = new InetSocketAddress(bgpPort); serverBootstrap = new ServerBootstrap(channelFactory); // serverBootstrap.setOptions("reuseAddr", true); serverBootstrap.setOption("child.keepAlive", true); serverBootstrap.setOption("child.tcpNoDelay", true); serverBootstrap.setPipelineFactory(pipelineFactory); try { serverChannel = serverBootstrap.bind(listenAddress); allChannels.add(serverChannel); } catch (ChannelException e) { log.debug("Exception binding to BGP port {}: ", listenAddress.getPort(), e); } }
@Test public void start_failsWhenCantBindPort() { thrown.expect(ChannelException.class); thrown.expectMessage("Failed to bind to: 0.0.0.0/0.0.0.0:12345"); ScribeCollector.Builder builder = ScribeCollector.builder().storage(new InMemoryStorage()).port(12345); try (ScribeCollector first = builder.build().start()) { try (ScribeCollector samePort = builder.build().start()) { } } }
/** * Utility method to create RPC service from configuration and hostname, port. * * @param hostname The hostname/address that describes the TaskManager's data location. * @param port If true, the TaskManager will not initiate the TCP network stack. * @param configuration The configuration for the TaskManager. * @return The rpc service which is used to start and connect to the TaskManager RpcEndpoint . * @throws IOException Thrown, if the actor system can not bind to the address * @throws Exception Thrown is some other error occurs while creating akka actor system */ public static RpcService createRpcService(String hostname, int port, Configuration configuration) throws Exception { LOG.info("Starting AkkaRpcService at {}.", NetUtils.unresolvedHostAndPortToNormalizedString(hostname, port)); final ActorSystem actorSystem; try { Config akkaConfig; if (hostname != null && !hostname.isEmpty()) { // remote akka config akkaConfig = AkkaUtils.getAkkaConfig(configuration, hostname, port); } else { // local akka config akkaConfig = AkkaUtils.getAkkaConfig(configuration); } LOG.debug("Using akka configuration \n {}.", akkaConfig); actorSystem = AkkaUtils.createActorSystem(akkaConfig); } catch (Throwable t) { if (t instanceof ChannelException) { Throwable cause = t.getCause(); if (cause != null && t.getCause() instanceof java.net.BindException) { String address = NetUtils.hostAndPortToUrlString(hostname, port); throw new IOException("Unable to bind AkkaRpcService actor system to address " + address + " - " + cause.getMessage(), t); } } throw new Exception("Could not create TaskManager actor system", t); } final Time timeout = Time.milliseconds(AkkaUtils.getTimeout(configuration).toMillis()); return new AkkaRpcService(actorSystem, timeout); }
/** * Utility method to create RPC service from configuration and hostname, port. * * @param hostname The hostname/address that describes the TaskManager's data location. * @param port If true, the TaskManager will not initiate the TCP network stack. * @param configuration The configuration for the TaskManager. * @return The rpc service which is used to start and connect to the TaskManager RpcEndpoint . * @throws IOException Thrown, if the actor system can not bind to the address * @throws Exception Thrown is some other error occurs while creating akka actor system */ public static RpcService createRpcService(String hostname, int port, Configuration configuration) throws Exception { LOG.info("Starting AkkaRpcService at {}.", NetUtils.hostAndPortToUrlString(hostname, port)); final ActorSystem actorSystem; try { Config akkaConfig; if (hostname != null && !hostname.isEmpty()) { // remote akka config akkaConfig = AkkaUtils.getAkkaConfig(configuration, hostname, port); } else { // local akka config akkaConfig = AkkaUtils.getAkkaConfig(configuration); } LOG.debug("Using akka configuration \n {}.", akkaConfig); actorSystem = AkkaUtils.createActorSystem(akkaConfig); } catch (Throwable t) { if (t instanceof ChannelException) { Throwable cause = t.getCause(); if (cause != null && t.getCause() instanceof java.net.BindException) { String address = NetUtils.hostAndPortToUrlString(hostname, port); throw new IOException("Unable to bind AkkaRpcService actor system to address " + address + " - " + cause.getMessage(), t); } } throw new Exception("Could not create TaskManager actor system", t); } final Time timeout = Time.milliseconds(AkkaUtils.getTimeout(configuration).toMillis()); return new AkkaRpcService(actorSystem, timeout); }
public synchronized int start( Configuration conf, ChannelPipelineFactory pipelineFactory) { ServerBootstrap bootstrap = new ServerBootstrap(channelFactory); bootstrap.setPipelineFactory(pipelineFactory); bootstrap.setOption( BOOTSTRAP_BACKLOG_PARAM, conf.getInt(BACKLOG_CONF, DEFAULT_BACKLOG)); // Try to bind to a port. If the port is 0, netty will select a port. int bindAttempt = 0; while (bindAttempt < DEFAULT_BIND_ATTEMPT_MAX) { try { InetSocketAddress address = new InetSocketAddress(port); Channel ch = bootstrap.bind(address); accepted.add(ch); port = ((InetSocketAddress) ch.getLocalAddress()).getPort(); break; } catch (ChannelException e) { LOG.warn("start: Likely failed to bind on attempt " + bindAttempt + " to port " + port, e); // Only increment the port number when set by the user if (port != 0) { ++port; } ++bindAttempt; } } LOG.info(this.getClass() + " is listening on port " + port); return port; }
public void run(GameManager gameManager) throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); CreeperAuthenticationHandler handler = new CreeperAuthenticationHandler(gameManager); bootstrap.setPipelineFactory(new CreeperServerPipelineFactory(handler)); try { bootstrap.bind(new InetSocketAddress(port)); } catch (ChannelException e) { exitServer(e.getMessage(), 127); } }
@Test public void testFrames() { Random rand = new Random(); int serverPort = 30000 + rand.nextInt(10000); int retries = 10; // A few retries in case initial choice is in use. while (true) { try { RpcProgram program = new TestFrameDecoder.TestRpcProgram("TestRpcProgram", "localhost", serverPort, 100000, 1, 2); SimpleTcpServer tcpServer = new SimpleTcpServer(serverPort, program, 1); tcpServer.run(); break; // Successfully bound a port, break out. } catch (ChannelException ce) { if (retries-- > 0) { serverPort += rand.nextInt(20); // Port in use? Try another. } else { throw ce; // Out of retries. } } } XDR xdrOut = createGetportMount(); int headerSize = xdrOut.size(); int bufsize = 2 * 1024 * 1024; byte[] buffer = new byte[bufsize]; xdrOut.writeFixedOpaque(buffer); int requestSize = xdrOut.size() - headerSize; // Send the request to the server testRequest(xdrOut, serverPort); // Verify the server got the request with right size assertEquals(requestSize, resultSize); }
public boolean tryListen() { try { this.bootstrap.getPipeline().addLast("encoder", new NetworkEncoder()); this.bootstrap.getPipeline().addLast("decoder", new NetworkDecoder()); this.bootstrap.getPipeline().addLast("handler", new ConnectionHandler()); this.bootstrap.bind(new InetSocketAddress(this.ip, this.port)); } catch (final ChannelException ex) { logger.error("Couldn't open connection to " + this.ip + ":" + this.port + ".", ex); return false; } logger.info("Connection to " + this.ip + ":" + this.port + " created."); return true; }
private void startServer() { HashedWheelTimer timer = new HashedWheelTimer( groupedThreads("onos/fpm", "fpm-timer-%d", log)); ChannelFactory channelFactory = new NioServerSocketChannelFactory( newCachedThreadPool(groupedThreads("onos/fpm", "sm-boss-%d", log)), newCachedThreadPool(groupedThreads("onos/fpm", "sm-worker-%d", log))); ChannelPipelineFactory pipelineFactory = () -> { // Allocate a new session per connection IdleStateHandler idleHandler = new IdleStateHandler(timer, IDLE_TIMEOUT_SECS, 0, 0); FpmSessionHandler fpmSessionHandler = new FpmSessionHandler(this, new InternalFpmListener()); FpmFrameDecoder fpmFrameDecoder = new FpmFrameDecoder(); // Setup the processing pipeline ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("FpmFrameDecoder", fpmFrameDecoder); pipeline.addLast("idle", idleHandler); pipeline.addLast("FpmSession", fpmSessionHandler); return pipeline; }; InetSocketAddress listenAddress = new InetSocketAddress(FPM_PORT); serverBootstrap = new ServerBootstrap(channelFactory); serverBootstrap.setOption("child.reuseAddr", true); serverBootstrap.setOption("child.keepAlive", true); serverBootstrap.setOption("child.tcpNoDelay", true); serverBootstrap.setPipelineFactory(pipelineFactory); try { serverChannel = serverBootstrap.bind(listenAddress); allChannels.add(serverChannel); } catch (ChannelException e) { log.debug("Exception binding to FPM port {}: ", listenAddress.getPort(), e); stopServer(); } }
public void start() { log.debug("BGP Session Manager start."); isShutdown = false; ChannelFactory channelFactory = new NioServerSocketChannelFactory( newCachedThreadPool(groupedThreads("onos/bgp", "sm-boss-%d", log)), newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d", log))); ChannelPipelineFactory pipelineFactory = () -> { // Allocate a new session per connection BgpSession bgpSessionHandler = new BgpSession(BgpSessionManager.this); BgpFrameDecoder bgpFrameDecoder = new BgpFrameDecoder(bgpSessionHandler); // Setup the processing pipeline ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("BgpFrameDecoder", bgpFrameDecoder); pipeline.addLast("BgpSession", bgpSessionHandler); return pipeline; }; InetSocketAddress listenAddress = new InetSocketAddress(bgpPort); serverBootstrap = new ServerBootstrap(channelFactory); // serverBootstrap.setOptions("reuseAddr", true); serverBootstrap.setOption("child.keepAlive", true); serverBootstrap.setOption("child.tcpNoDelay", true); serverBootstrap.setPipelineFactory(pipelineFactory); try { serverChannel = serverBootstrap.bind(listenAddress); allChannels.add(serverChannel); } catch (ChannelException e) { log.debug("Exception binding to BGP port {}: ", listenAddress.getPort(), e); } }
@Override public void initialize(Map<String, String> configuration, GraylogServer graylogServer) throws MessageInputConfigurationException { socketAddress = new InetSocketAddress( configuration.get("listen_address"), Integer.parseInt(configuration.get("listen_port")) ); final ExecutorService bossThreadPool = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setNameFormat("input-relp-boss-%d") .build()); final ExecutorService workerThreadPool = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setNameFormat("input-relp-worker-%d") .build()); ServerBootstrap tcpBootstrap = new ServerBootstrap( new OioServerSocketChannelFactory(bossThreadPool, workerThreadPool) ); tcpBootstrap.setPipelineFactory(new RELPPipelineFactory(graylogServer)); try { tcpBootstrap.bind(socketAddress); } catch (ChannelException e) { LOG.error("Could not bind RELP input {}", socketAddress, e); } }
public int getReceiveBufferSize() { try { return socket.getReceiveBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } }
public int getSendBufferSize() { try { return socket.getSendBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } }
public int getSoLinger() { try { return socket.getSoLinger(); } catch (SocketException e) { throw new ChannelException(e); } }
public int getTrafficClass() { try { return socket.getTrafficClass(); } catch (SocketException e) { throw new ChannelException(e); } }
public boolean isKeepAlive() { try { return socket.getKeepAlive(); } catch (SocketException e) { throw new ChannelException(e); } }
public boolean isReuseAddress() { try { return socket.getReuseAddress(); } catch (SocketException e) { throw new ChannelException(e); } }
public boolean isTcpNoDelay() { try { return socket.getTcpNoDelay(); } catch (SocketException e) { throw new ChannelException(e); } }
public void setKeepAlive(boolean keepAlive) { try { socket.setKeepAlive(keepAlive); } catch (SocketException e) { throw new ChannelException(e); } }
public void setReceiveBufferSize(int receiveBufferSize) { try { socket.setReceiveBufferSize(receiveBufferSize); } catch (SocketException e) { throw new ChannelException(e); } }
public void setReuseAddress(boolean reuseAddress) { try { socket.setReuseAddress(reuseAddress); } catch (SocketException e) { throw new ChannelException(e); } }
public void setSendBufferSize(int sendBufferSize) { try { socket.setSendBufferSize(sendBufferSize); } catch (SocketException e) { throw new ChannelException(e); } }
public void setSoLinger(int soLinger) { try { if (soLinger < 0) { socket.setSoLinger(false, 0); } else { socket.setSoLinger(true, soLinger); } } catch (SocketException e) { throw new ChannelException(e); } }
public void setTcpNoDelay(boolean tcpNoDelay) { try { socket.setTcpNoDelay(tcpNoDelay); } catch (SocketException e) { throw new ChannelException(e); } }
public void setTrafficClass(int trafficClass) { try { socket.setTrafficClass(trafficClass); } catch (SocketException e) { throw new ChannelException(e); } }
public void run() { SocketAddress localAddress = channel.getLocalAddress(); SocketAddress remoteAddress = channel.getRemoteAddress(); if (localAddress == null || remoteAddress == null) { if (future != null) { future.setFailure(new ClosedChannelException()); } close(channel, succeededFuture(channel)); return; } try { if (server) { channel.channel.configureBlocking(false); } channel.channel.register(selector, channel.getRawInterestOps(), channel); if (future != null) { channel.setConnected(); future.setSuccess(); } if (server || !((NioClientSocketChannel) channel).boundManually) { fireChannelBound(channel, localAddress); } fireChannelConnected(channel, remoteAddress); } catch (IOException e) { if (future != null) { future.setFailure(e); } close(channel, succeededFuture(channel)); if (!(e instanceof ClosedChannelException)) { throw new ChannelException("Failed to register a socket to the selector.", e); } } }
public ReceiveBufferSizePredictor getReceiveBufferSizePredictor() { ReceiveBufferSizePredictor predictor = this.predictor; if (predictor == null) { try { this.predictor = predictor = getReceiveBufferSizePredictorFactory().getPredictor(); } catch (Exception e) { throw new ChannelException("Failed to create a new " + ReceiveBufferSizePredictor.class.getSimpleName() + '.', e); } } return predictor; }
private void writeMessage(final Channel channel, final String message) { if (!channel.isOpen()) { throw new ChannelException(); } PendingWrites.increment(channel); channel.write(message + "\n\n").addListener(LISTENER); }
static boolean isPending(final Channel channel) { final AtomicInteger pending = PENDING_WRITES.get(channel); if (pending == null) { throw new ChannelException("channel removed"); } return (pending.get() > MAX_PENDING_WRITES); }