@Override
 public void sendResponse(Throwable error) throws IOException {
   BytesStreamOutput stream;
   try {
     stream = BytesStreamOutput.Cached.cached();
     writeResponseExceptionHeader(stream);
     RemoteTransportException tx =
         new RemoteTransportException(
             transport.nodeName(),
             transport.wrapAddress(channel.getLocalAddress()),
             action,
             error);
     ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
     too.writeObject(tx);
     too.close();
   } catch (NotSerializableException e) {
     stream = BytesStreamOutput.Cached.cached();
     writeResponseExceptionHeader(stream);
     RemoteTransportException tx =
         new RemoteTransportException(
             transport.nodeName(),
             transport.wrapAddress(channel.getLocalAddress()),
             action,
             new NotSerializableTransportException(error));
     ThrowableObjectOutputStream too = new ThrowableObjectOutputStream(stream);
     too.writeObject(tx);
     too.close();
   }
   ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(stream.copiedByteArray());
   buffer.setInt(0, buffer.writerIndex() - 4); // update real size.
   channel.write(buffer);
 }
Example #2
0
 /** Stop all sockets */
 @PreDestroy
 public void stopListener() {
   for (Channel channel : channels) {
     logger.info("Stop socket on port " + channel.getLocalAddress());
     channel.unbind();
   }
 }
  /** Sometime when connect one bad channel which isn't writable, it will call this function */
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
    // register the newly established channel
    Channel channel = event.getChannel();
    LOG.info(
        "connection established to :{}, local port:{}",
        client.getRemoteAddr(),
        channel.getLocalAddress());

    client.handleResponse();
  }
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
    // register the newly established channel
    Channel channel = ctx.getChannel();
    client.channelConnected(channel);

    LOG.info(
        "Connection established from {} to {}",
        channel.getLocalAddress(),
        channel.getRemoteAddress());
  }
Example #5
0
 @Override
 public void handler(Channel channel, BaseProtocol baseProtocol) {
   BlockCreateRequest request = (BlockCreateRequest) baseProtocol;
   int blockId = request.getBlockId();
   try {
     BlockWrite.getInstance().writeBlock(blockId);
     BlockCreateResult result = new BlockCreateResult();
     result.setMessageId(request.getMessageId());
     channel.write(result);
   } catch (Exception e) {
     logger.error("创建block" + blockId + "出错", e);
     String localAddress = channel.getLocalAddress().toString();
     BlockCreateError blockCreateError = new BlockCreateError();
     blockCreateError.setMessageId(request.getMessageId());
     blockCreateError.setErrorMsg(
         localAddress + ":" + "创建block:" + blockId + ":出错\n" + ExceptionUtils.exception2String(e));
     channel.write(blockCreateError);
   }
 }
  public NettySMTPClientSession(
      Channel channel,
      Logger logger,
      SMTPClientConfig config,
      SMTPDeliveryMode mode,
      SSLEngine engine) {
    super(
        logger,
        config,
        mode,
        (InetSocketAddress) channel.getLocalAddress(),
        (InetSocketAddress) channel.getRemoteAddress());
    this.channel = channel;
    channel
        .getPipeline()
        .addBefore(IDLE_HANDLER_KEY, "callback", new CloseHandler(closeFuture, logger));

    this.engine = engine;
  }
  // IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
  // but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports
  // and any request to us will be intercepted
  // so, we bind to 127.0.0.1 and 0.0.0.0
  private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
    InetAddress localAddress;
    try {
      localAddress = InetAddress.getByName("127.0.0.1");
    } catch (UnknownHostException e) {
      LOG.error(e);
      return -1;
    }

    for (int i = 0; i < portsCount; i++) {
      int port = firstPort + i;
      try {
        openChannels.add(bootstrap.bind(new InetSocketAddress(localAddress, port)));
        return port;
      } catch (ChannelException e) {
        if (!openChannels.isEmpty()) {
          openChannels.close();
          openChannels.clear();
        }

        if (portsCount == 1) {
          throw e;
        } else if (!tryAnyPort && i == (portsCount - 1)) {
          LOG.error(e);
        }
      }
    }

    if (tryAnyPort) {
      LOG.info("We cannot bind to our default range, so, try to bind to any free port");
      try {
        Channel channel = bootstrap.bind(new InetSocketAddress(localAddress, 0));
        openChannels.add(channel);
        return ((InetSocketAddress) channel.getLocalAddress()).getPort();
      } catch (ChannelException e) {
        LOG.error(e);
      }
    }

    return -1;
  }
  // TODO change AbstractService to throw InterruptedException
  @Override
  public synchronized void start() {
    Configuration conf = getConfig();
    ServerBootstrap bootstrap = new ServerBootstrap(selector);
    try {
      pipelineFact = new HttpPipelineFactory(conf);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
    bootstrap.setPipelineFactory(pipelineFact);
    port = conf.getInt(ConfVars.PULLSERVER_PORT.varname, ConfVars.PULLSERVER_PORT.defaultIntVal);
    Channel ch = bootstrap.bind(new InetSocketAddress(port));
    accepted.add(ch);
    port = ((InetSocketAddress) ch.getLocalAddress()).getPort();
    conf.set(ConfVars.PULLSERVER_PORT.varname, Integer.toString(port));
    pipelineFact.PullServer.setPort(port);
    LOG.info(getName() + " listening on port " + port);
    super.start();

    sslFileBufferSize =
        conf.getInt(SUFFLE_SSL_FILE_BUFFER_SIZE_KEY, DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE);
  }
  @Test
  @SuppressWarnings("deprecation")
  public void testCompatibleObjectEcho() throws Throwable {
    ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor));
    ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor));

    EchoHandler sh = new EchoHandler();
    EchoHandler ch = new EchoHandler();

    sb.getPipeline().addLast("decoder", new CompatibleObjectDecoder());
    sb.getPipeline().addLast("encoder", new CompatibleObjectEncoder());
    sb.getPipeline().addLast("handler", sh);

    cb.getPipeline().addLast("decoder", new CompatibleObjectDecoder());
    cb.getPipeline().addLast("encoder", new CompatibleObjectEncoder());
    cb.getPipeline().addLast("handler", ch);

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());

    Channel cc = ccf.getChannel();
    for (String element : data) {
      cc.write(element);
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }
  // IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
  // but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports
  // and any request to us will be intercepted
  // so, we bind to 127.0.0.1 and 0.0.0.0
  private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
    String property = System.getProperty(PROPERTY_ONLY_ANY_HOST);
    boolean onlyAnyHost =
        property == null
            ? (SystemInfo.isLinux || SystemInfo.isWindows && !SystemInfo.isWinVistaOrNewer)
            : (property.isEmpty() || Boolean.valueOf(property));
    boolean portChecked = false;
    for (int i = 0; i < portsCount; i++) {
      int port = firstPort + i;
      ChannelException channelException = null;
      try {
        openChannels.add(bootstrap.bind(new InetSocketAddress(port)));
        if (!onlyAnyHost) {
          InetSocketAddress localAddress = null;
          try {
            localAddress = new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port);
            openChannels.add(bootstrap.bind(localAddress));
          } catch (UnknownHostException ignored) {
            return port;
          } catch (ChannelException e) {
            channelException = e;
            if (!portChecked) {
              portChecked = true;
              assert localAddress != null;
              if (checkPortSafe(localAddress)) {
                return port;
              }
            }
          }
        }
      } catch (ChannelException e) {
        channelException = e;
      }

      if (channelException == null) {
        return port;
      } else {
        if (!openChannels.isEmpty()) {
          openChannels.close();
          openChannels.clear();
        }

        if (portsCount == 1) {
          throw channelException;
        } else if (!tryAnyPort && i == (portsCount - 1)) {
          LOG.error(channelException);
        }
      }
    }

    if (tryAnyPort) {
      LOG.info("We cannot bind to our default range, so, try to bind to any free port");
      try {
        Channel channel = bootstrap.bind(new InetSocketAddress(0));
        openChannels.add(channel);
        return ((InetSocketAddress) channel.getLocalAddress()).getPort();
      } catch (ChannelException e) {
        LOG.error(e);
      }
    }

    return -1;
  }
Example #11
0
 @Override
 public <In, Out> int listenOnAnyPort(NetworkEndpointFactory<In, Out> endpointFactory) {
   Channel ch = listen(0, endpointFactory);
   InetSocketAddress addr = (InetSocketAddress) ch.getLocalAddress();
   return addr.getPort();
 }
Example #12
0
 private void fireInitialEvents() {
   // Fire the typical initial events.
   fireChannelOpen(channel);
   fireChannelBound(channel, channel.getLocalAddress());
   fireChannelConnected(channel, channel.getRemoteAddress());
 }
  @Test
  public void testSslEcho() throws Throwable {
    ServerBootstrap sb =
        new ServerBootstrap(newServerSocketChannelFactory(Executors.newCachedThreadPool()));
    ClientBootstrap cb =
        new ClientBootstrap(newClientSocketChannelFactory(Executors.newCachedThreadPool()));

    EchoHandler sh = new EchoHandler(true);
    EchoHandler ch = new EchoHandler(false);

    SSLEngine sse = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    SSLEngine cse = SecureChatSslContextFactory.getClientContext().createSSLEngine();
    sse.setUseClientMode(false);
    cse.setUseClientMode(true);

    // Workaround for blocking I/O transport write-write dead lock.
    sb.setOption("receiveBufferSize", 1048576);
    sb.setOption("receiveBufferSize", 1048576);

    sb.getPipeline().addFirst("ssl", new SslHandler(sse));
    sb.getPipeline().addLast("handler", sh);
    cb.getPipeline().addFirst("ssl", new SslHandler(cse));
    cb.getPipeline().addLast("handler", ch);
    ExecutorService eventExecutor = null;
    if (isExecutorRequired()) {
      eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0);
      sb.getPipeline().addFirst("executor", new ExecutionHandler(eventExecutor));
      cb.getPipeline().addFirst("executor", new ExecutionHandler(eventExecutor));
    }

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port));
    ccf.awaitUninterruptibly();
    if (!ccf.isSuccess()) {
      logger.error("Connection attempt failed", ccf.getCause());
      sc.close().awaitUninterruptibly();
    }
    assertTrue(ccf.isSuccess());

    Channel cc = ccf.getChannel();
    ChannelFuture hf = cc.getPipeline().get(SslHandler.class).handshake();
    hf.awaitUninterruptibly();
    if (!hf.isSuccess()) {
      logger.error("Handshake failed", hf.getCause());
      sh.channel.close().awaitUninterruptibly();
      ch.channel.close().awaitUninterruptibly();
      sc.close().awaitUninterruptibly();
    }

    assertTrue(hf.isSuccess());

    for (int i = 0; i < data.length; ) {
      int length = Math.min(random.nextInt(1024 * 64), data.length - i);
      cc.write(ChannelBuffers.wrappedBuffer(data, i, length));
      i += length;
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();
    cb.shutdown();
    sb.shutdown();
    cb.releaseExternalResources();
    sb.releaseExternalResources();

    if (eventExecutor != null) {
      eventExecutor.shutdown();
    }
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }