public Channel getActiveChannel() throws InterruptedException {
      List<InetSocketAddress> addresses = m_descriptor.getRemoteAddresses();

      if (!addresses.equals(m_addresses)) { // first time or addresses changed
        m_addresses = addresses;

        for (int i = 0; i < addresses.size(); i++) {
          InetSocketAddress address = addresses.get(i);
          ChannelFuture future = m_bootstrap.connect(address).sync();

          if (future.isSuccess()) {
            // close old channel
            if (m_channel != null) {
              m_channel.close();
            }

            // m_logger.info(String.format("Connected to %s server(%s:%s)", m_descriptor.getName(),
            // address.getHostName(), address.getPort()));
            m_channel = future.channel();
            m_index = i;
            break;
          }
        }

        return m_channel;
      } else {
        // closed by peer
        if (m_channel != null && m_channel.closeFuture().isSuccess()) {
          // TODO
        }

        // try to recover connection to primary server
        if (m_index > 0) {
          if (m_primary == null) {
            long now = System.currentTimeMillis();

            if (m_lastCheckTime + m_failBackCheckInternal < now) {
              InetSocketAddress address = m_addresses.get(m_index);

              m_lastCheckTime = now;
              m_primary = m_bootstrap.connect(address);
            }
          } else {
            Channel channel = m_primary.channel();

            if (channel.isOpen() && channel.isActive()) {
              m_channel = channel;
              m_index = 0;
            }
          }
        }

        if (m_channel != null && m_channel.isOpen() && m_channel.isActive()) {
          return m_channel;
        } else {
          return null;
        }
      }
    }
 @Override
 public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
   if (msg instanceof ByteBuf) {
     // handle normal request
     final ByteBuf chunk = (ByteBuf) msg;
     if (flushedBuffer) {
       bufferedMode = false;
     }
     if (bufferedMode) {
       try {
         channelBuffer.writeBytes(chunk);
         ctx.channel().read();
       } catch (IndexOutOfBoundsException iobe) {
         logger.trace(
             "Flushing buffer upstream and switching to chunked mode as downstream response too large");
         bufferedMode = false;
         // write and flush buffer upstream
         if (outboundChannel.isActive()) {
           outboundChannel
               .writeAndFlush(channelBuffer)
               .addListener(
                   new ChannelFutureListener() {
                     @Override
                     public void operationComplete(ChannelFuture future) throws Exception {
                       if (future.isSuccess()) {
                         // write and flush this chunk upstream in case this single chunk is too
                         // large for buffer
                         channelRead(ctx, chunk);
                       } else {
                         future.channel().close();
                       }
                     }
                   });
         }
       }
     } else {
       bufferedMode = false;
       if (outboundChannel.isActive()) {
         outboundChannel
             .writeAndFlush(chunk)
             .addListener(
                 new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                     if (future.isSuccess()) {
                       // was able to flush out data, start to read the next chunk
                       ctx.channel().read();
                     } else {
                       future.channel().close();
                     }
                   }
                 });
       }
     }
   }
 }
  public synchronized void pause() {
    if (paused) {
      return;
    }

    if (channelClazz == null) {
      return;
    }

    // We *pause* the acceptor so no new connections are made
    if (serverChannelGroup != null) {
      ChannelGroupFuture future = serverChannelGroup.close().awaitUninterruptibly();
      if (!future.isSuccess()) {
        ActiveMQServerLogger.LOGGER.nettyChannelGroupBindError();
        Iterator<Channel> iterator = future.group().iterator();
        while (iterator.hasNext()) {
          Channel channel = iterator.next();
          if (channel.isActive()) {
            ActiveMQServerLogger.LOGGER.nettyChannelStillBound(channel, channel.remoteAddress());
          }
        }
      }
    }
    paused = true;
  }
 @Override
 public void dispatch(Channel session, Request request) {
   if (request != null) {
     int sn = request.getSn();
     int module = request.getModule();
     int cmd = request.getCmd();
     Response response = Response.valueOf(sn, module, cmd);
     response.setMessageType(request.getMessageType());
     CommandResolver commandResolver = COMMAND_RESOLVER.get(Integer.valueOf(cmd));
     if (commandResolver != null) {
       if (logger.isDebugEnabled()) {
         logger.debug(
             String.format(
                 "module:[%d], cmd:[%d]",
                 new Object[] {Integer.valueOf(module), Integer.valueOf(cmd)}));
       }
       try {
         commandResolver.execute(request);
       } catch (Exception e) {
         e.printStackTrace();
       }
     } else {
       if (logger.isDebugEnabled()) {
         logger.error(
             String.format(
                 "No Invoker for module:[%d], cmd:[%d]",
                 new Object[] {Integer.valueOf(module), Integer.valueOf(cmd)}));
       }
       response.setStatus(-1);
       if (session.isActive()) {
         session.writeAndFlush(response);
       }
     }
   }
 }
示例#5
0
  public void onMessage(Message message) {
    if (message.getType() == MessageType.MSG && message.get(MessageProperty.ROOM).equals("#main")) {
      long userId = message.get(MessageProperty.USER_ID);
      String name = message.get(MessageProperty.NAME);
      UserCredentials userCredentials = null;
      if (needsFetchingConnectionData(userId)) {
        userCredentials = fetchConnectionDataForUser(name, userId);
      }

      if (userCredentials != null) {
        String id = userCredentials.getId();
        Channel channel = connections.get(id.toLowerCase());
        if (channel == null || !channel.isActive()) {
          try {
            channel = createConnection(id, userCredentials.getToken());
          } catch (InterruptedException e) {
            logger.warn("", e);
          }
        }
        if (channel != null) {
          channel.attr(lastMessageAttrKey).set(System.currentTimeMillis());
          channel.writeAndFlush(
              "PRIVMSG #" + this.channel + " :" + message.get(MessageProperty.TEXT) + "\r\n");
        }
      }
    }
  }
  private void handleHTTP(OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise)
      throws IOException {
    Channel channel = ctx.channel();
    Attribute<Boolean> attr = channel.attr(WRITE_ONCE);

    Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());

    if (!channel.isActive() || queue.isEmpty() || !attr.compareAndSet(null, true)) {
      promise.setSuccess();
      return;
    }

    ByteBuf out = encoder.allocateBuffer(ctx.alloc());
    Boolean b64 = ctx.channel().attr(EncoderHandler.B64).get();
    if (b64 != null && b64) {
      Integer jsonpIndex = ctx.channel().attr(EncoderHandler.JSONP_INDEX).get();
      encoder.encodeJsonP(jsonpIndex, queue, out, ctx.alloc(), 50);
      String type = "application/javascript";
      if (jsonpIndex == null) {
        type = "text/plain";
      }
      sendMessage(msg, channel, out, type, promise);
    } else {
      encoder.encodePackets(queue, out, ctx.alloc(), 50);
      sendMessage(msg, channel, out, "application/octet-stream", promise);
    }
  }
  void responseReceived(int id, @Nullable ByteBuf buffer) {
    Channel channel = requests.remove(id);
    if (channel == null || !channel.isActive()) {
      if (buffer != null) {
        buffer.release();
      }
      return;
    }

    if (buffer == null) {
      Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel);
      return;
    }

    HttpResponse httpResponse =
        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);
    try {
      parseHeaders(httpResponse, buffer);
      Responses.addServer(httpResponse);
      if (!HttpHeaderUtil.isContentLengthSet(httpResponse)) {
        HttpHeaderUtil.setContentLength(httpResponse, buffer.readableBytes());
      }
    } catch (Throwable e) {
      buffer.release();
      try {
        LOG.error(e);
      } finally {
        Responses.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR, channel);
      }
      return;
    }
    channel.writeAndFlush(httpResponse);
  }
 /** Stop listening */
 public void unbind() {
   final Channel _channel = channel;
   if (_channel != null && _channel.isActive()) {
     _channel.close();
     channel = null;
   }
 }
 @Override
 public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
   ByteBuf out = outboundChannel.outboundByteBuffer();
   out.writeBytes(in);
   if (outboundChannel.isActive()) {
     outboundChannel.flush();
   }
 }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   cause.printStackTrace();
   Channel ch = ctx.channel();
   if (ch.isActive()) {
     ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
   }
 }
 private static void sendBadGateway(@NotNull Channel channel) {
   try {
     if (channel.isActive()) {
       Responses.sendStatus(HttpResponseStatus.BAD_GATEWAY, channel);
     }
   } catch (Throwable e) {
     NettyUtil.log(e, LOG);
   }
 }
 static boolean isActive(Channel ch) {
   final boolean active;
   if (!ch.isActive()) {
     active = false;
   } else {
     final HttpSessionHandler sessionHandler = ch.pipeline().get(HttpSessionHandler.class);
     active = sessionHandler != null ? sessionHandler.active : false;
   }
   return active;
 }
示例#13
0
  @Test
  public void testExceptionChannelActive() throws Exception {
    sut.setState(CommandHandler.LifecycleState.ACTIVE);

    when(channel.isActive()).thenReturn(true);

    sut.channelActive(context);
    sut.exceptionCaught(context, new Exception());
    verify(context).fireExceptionCaught(any(Exception.class));
  }
示例#14
0
  /** Binds this server to the address specified in the configuration. */
  private void bind() {
    SocketAddress address = getBindAddress(ServerConfig.Key.SERVER_PORT);

    logger.info("Binding to address: " + address + "...");
    ChannelFuture future = networkServer.bind(address);
    Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
      throw new RuntimeException("Failed to bind to address. Maybe it is already in use?");
    }
  }
示例#15
0
  public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    // final LocalAddress addr = new LocalAddress(PORT);
    final InetAddress HOST = InetAddress.getByName("192.168.220.128");
    // final InetSocketAddress addr = InetSocketAddress.createUnresolved("192.168.220.128",
    // Integer.parseInt(PORT));
    NioEventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK

    final SslContext sslCtx = null;

    try {

      Bootstrap b = new Bootstrap();
      b.group(clientGroup)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  // p.addLast(new LoggingHandler(LogLevel.INFO));
                  p.addLast(new LocalEchoClientHandler());
                }
              });

      // Start the client.
      ChannelFuture f = b.connect(HOST, PORT).sync();

      ByteBuf subsequentMessage = null;
      byte[] bytes = null;
      Channel ch = b.connect(HOST, PORT).channel();
      String line = null;
      System.out.println("Feel free to chat here");
      while (true) {
        line = new BufferedReader(new InputStreamReader(System.in)).readLine();
        if (line.equalsIgnoreCase("quit") || !ch.isActive()) {
          System.out.println("Prepare to close the connection.");
          break;
        }
        subsequentMessage = Unpooled.buffer();
        bytes = line.getBytes();
        subsequentMessage.writeBytes(bytes);

        ch.writeAndFlush(subsequentMessage);
      }

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();

    } finally {
      clientGroup.shutdownGracefully();
      System.out.println("Client closed");
    }
  }
  @Override
  public Channel fetch() {
    Channel ch = channels.fetch();

    if (ch != null && ch.isActive()) {
      if (ch.attr(GlobalConstance.attributeKey).get() == SessionState.Connect) {
        return ch;
      }
    }
    return null;
  }
 /**
  * Writes an the {@link Events#DISCONNECT} to the client, flushes all the pending writes and
  * closes the channel.
  */
 @Override
 public void close() {
   LOG.debug("Going to close tcp connection in class: {}", this.getClass().getName());
   Event event = Events.event(null, Events.DISCONNECT);
   if (channel.isActive()) {
     channel.write(event).addListener(ChannelFutureListener.CLOSE);
   } else {
     channel.close();
     LOG.trace("Unable to write the Event {} with type {} to socket", event, event.getType());
   }
 }
  public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg)
      throws Exception {
    LoggerUtil.debug(
        logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote msg", msg);

    remainMsgCount++;

    if (remainMsgCount <= 5) {
      remoteChannelCtx.read();
    }

    HttpObject ho = (HttpObject) msg;

    if (ho instanceof HttpResponse) {
      HttpResponse httpResponse = (HttpResponse) ho;

      LoggerUtil.info(
          forwardRestLogger,
          uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
          httpResponse.getStatus(),
          httpResponse.getProtocolVersion());

      httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
      httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE);
    }

    if (uaChannel.isActive()) {
      uaChannel
          .writeAndFlush(ho)
          .addListener(
              new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                  LoggerUtil.debug(
                      logger,
                      uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                      "Write to UA finished: " + future.isSuccess());
                  if (future.isSuccess()) {
                    remainMsgCount--;
                    remoteChannelCtx.read();
                    LoggerUtil.debug(
                        logger,
                        uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY),
                        "Fire read again");
                  } else {
                    remoteChannelCtx.close();
                  }
                }
              });
    } else {
      remoteChannelCtx.close();
    }
  }
示例#19
0
  /** Binds the query server to the address specified in the configuration. */
  private void bindQuery() {
    if (!config.getBoolean(ServerConfig.Key.QUERY_ENABLED)) {
      return;
    }

    SocketAddress address = getBindAddress(ServerConfig.Key.QUERY_PORT);
    queryServer = new QueryServer(this, config.getBoolean(ServerConfig.Key.QUERY_PLUGINS));

    logger.info("Binding query to address: " + address + "...");
    ChannelFuture future = queryServer.bind(address);
    Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
      logger.warning("Failed to bind query. Address already in use?");
    }
  }
  private void markAsDone(NettyResponseFuture<?> future, final Channel channel)
      throws MalformedURLException {
    // We need to make sure everything is OK before adding the
    // connection back to the pool.
    try {
      future.done();
    } catch (Throwable t) {
      // Never propagate exception once we know we are done.
      LOGGER.debug(t.getMessage(), t);
    }

    if (!future.isKeepAlive() || !channel.isActive()) {
      channels.closeChannel(channel);
    }
  }
示例#21
0
  /** Binds the rcon server to the address specified in the configuration. */
  private void bindRcon() {
    if (!config.getBoolean(ServerConfig.Key.RCON_ENABLED)) {
      return;
    }

    SocketAddress address = getBindAddress(ServerConfig.Key.RCON_PORT);
    rconServer = new RconServer(this, config.getString(ServerConfig.Key.RCON_PASSWORD));

    logger.info("Binding rcon to address: " + address + "...");
    ChannelFuture future = rconServer.bind(address);
    Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
      logger.warning("Failed to bind rcon. Address already in use?");
    }
  }
示例#22
0
  public void bind(int port) throws BindException {
    SocketAddress address = this.getBindAddress(port);
    this.getLogger().info("Binding to address: " + address);
    ChannelFuture future = this.network.bind(address);
    Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
      Throwable cause = future.cause();
      if ((cause instanceof BindException)) {
        throw ((BindException) cause);
      }
      throw new RuntimeException("Failed to bind to address", cause);
    }

    this.getLogger().info("Successfully bound to: " + channel.localAddress());
    this.port = ((InetSocketAddress) channel.localAddress()).getPort();
  }
示例#23
0
  @Test
  public void testExceptionWithQueue() throws Exception {
    sut.setState(CommandHandler.LifecycleState.ACTIVE);
    q.clear();

    sut.channelActive(context);
    when(channel.isActive()).thenReturn(true);

    q.add(command);
    sut.exceptionCaught(context, new Exception());

    assertThat(q).isEmpty();
    assertThat(command.getException()).isNotNull();

    verify(context).fireExceptionCaught(any(Exception.class));
  }
 private void finishUpdate(
     final NettyResponseFuture<?> future, Channel channel, boolean lastValidChunk)
     throws IOException {
   if (lastValidChunk && future.isKeepAlive()) {
     channels.drainChannel(channel, future);
   } else {
     if (future.isKeepAlive()
         && channel.isActive()
         && channels.offerToPool(channels.getPoolKey(future), channel)) {
       markAsDone(future, channel);
       return;
     }
     channels.finishChannel(channel);
   }
   markAsDone(future, channel);
 }
示例#25
0
  private boolean checkWritable(ChannelFuture future) {
    boolean isWriteable = false;
    Channel channel = future.channel();

    if (future != null && channel.isOpen()) {
      if (channel.isActive() && channel.isWritable()) {
        isWriteable = true;
      } else {
        int count = m_attempts.incrementAndGet();

        if (count % 1000 == 0 || count == 1) {
          m_logger.error("Netty write buffer is full! Attempts: " + count);
        }
      }
    }

    return isWriteable;
  }
 @Override
 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
   if (bufferedMode && outboundChannel.isActive()) {
     flushedBuffer = true;
     outboundChannel
         .writeAndFlush(interceptor.intercept(ctx, channelBuffer, logger))
         .addListener(
             new ChannelFutureListener() {
               @Override
               public void operationComplete(ChannelFuture future) throws Exception {
                 if (future.isSuccess()) {
                   channelBuffer.clear();
                 } else {
                   future.channel().close();
                 }
               }
             });
   }
   super.channelReadComplete(ctx);
 }
  @Override
  public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
      IdleStateEvent e = (IdleStateEvent) evt;
      if (e.state() == IdleState.ALL_IDLE) {
        CouchbaseRequest keepAlive = createKeepAliveRequest();
        if (keepAlive != null) {
          keepAlive.observable().subscribe(new KeepAliveResponseAction(ctx));
          onKeepAliveFired(ctx, keepAlive);

          Channel channel = ctx.channel();
          if (channel.isActive() && channel.isWritable()) {
            ctx.pipeline().writeAndFlush(keepAlive);
          }
        }
      }
    } else {
      super.userEventTriggered(ctx, evt);
    }
  }
示例#28
0
 @Override
 public void run() {
   try {
     logger.debug("starting cleanup");
     for (Map.Entry<String, Channel> entry : connections.entrySet()) {
       Channel channel = entry.getValue();
       Long lastMessage = channel.attr(lastMessageAttrKey).get();
       if (System.currentTimeMillis() - lastMessage > FIVE_MINUTES) {
         channel.disconnect();
         connections.remove(entry.getKey());
         logger.debug("connection released for {}", entry.getKey());
       } else if (!channel.isActive()) {
         connections.remove(entry.getKey());
         logger.debug("connection released for {}", entry.getKey());
       }
     }
     logger.debug("cleanup complete");
   } catch (Exception e) {
     logger.error("exception while clean up", e);
   }
 }
 @Override
 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
   if (outboundChannel.isActive()) {
     outboundChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
   }
 }
示例#30
0
 public boolean isActive() {
   return !timedOut && (channel.isOpen() || channel.isActive());
 }