Exemplo n.º 1
0
    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 exceptionCaught(ChannelHandlerContext ctx, Throwable t) {

    Channel ch = ctx.channel();

    // Prevent recursion when the client close the connection during a write operation. In that
    // scenario the sendError will be invoked, but will fail since the channel has already been
    // closed
    // For an unknown reason,
    if (ch.attr(ATTACHMENT) != null
        && Error.class.isAssignableFrom(ch.attr(ATTACHMENT).get().getClass())) {
      return;
    }

    Throwable cause = t.getCause();
    if (cause instanceof TooLongFrameException) {
      sendError(ctx, BAD_REQUEST, null);
      return;
    }

    ch.attr(ATTACHMENT).set(new Error());
    if (ch.isOpen()) {
      sendError(ctx, INTERNAL_SERVER_ERROR, null);
    }

    if (ctx.channel().isActive()) {
      sendError(ctx, INTERNAL_SERVER_ERROR, null);
    }
  }
  protected void increaseCounter(Runnable task) {
    if (!shouldCount(task)) {
      return;
    }

    Settings settings = this.settings;
    long maxChannelMemorySize = settings.maxChannelMemorySize;

    int increment = settings.objectSizeEstimator.estimateSize(task);

    if (task instanceof ChannelEventRunnable) {
      ChannelEventRunnable eventTask = (ChannelEventRunnable) task;
      eventTask.estimatedSize = increment;
      Channel channel = eventTask.getEvent().getChannel();
      long channelCounter = getChannelCounter(channel).addAndGet(increment);
      // System.out.println("IC: " + channelCounter + ", " + increment);
      if (maxChannelMemorySize != 0 && channelCounter >= maxChannelMemorySize && channel.isOpen()) {
        if (channel.isReadable()) {
          // System.out.println("UNREADABLE");
          ChannelHandlerContext ctx = eventTask.getContext();
          if (ctx.getHandler() instanceof ExecutionHandler) {
            // readSuspended = true;
            ctx.setAttachment(Boolean.TRUE);
          }
          channel.setReadable(false);
        }
      }
    } else {
      ((MemoryAwareRunnable) task).estimatedSize = increment;
    }

    if (totalLimiter != null) {
      totalLimiter.increase(increment);
    }
  }
Exemplo n.º 4
0
 protected void a(ChannelHandlerContext var1, Packet var2) throws Exception {
   if (k.isOpen()) {
     try {
       var2.handle(m);
     } catch (class_ko var4) {;
     }
   }
 }
Exemplo n.º 5
0
 @Override
 public void shutdown() {
   notifyShutdown(Status.OK.withDescription("Channel requested transport to shut down"));
   // Notifying of termination is automatically done when the channel closes.
   if (channel != null && channel.isOpen()) {
     channel.close();
   }
 }
  @Override
  public void close(Channel channel) throws Exception {
    try {
      if (channel.isOpen()) channel.close().sync();

    } catch (InterruptedException e) {
      logger.error("close channel Error ", e);
    }
    // 将channel移除
    removeChannel(channel);
  }
Exemplo n.º 7
0
  private void m() {
    if ((k != null) && k.isOpen()) {
      j.readLock().lock();

      try {
        while (!i.isEmpty()) {
          class_ek.class_a_in_class_ek var1 = (class_ek.class_a_in_class_ek) i.poll();
          this.a(var1.a, var1.b);
        }
      } finally {
        j.readLock().unlock();
      }
    }
  }
Exemplo n.º 8
0
 public void l() {
   if ((k != null) && !k.isOpen()) {
     if (!p) {
       p = true;
       if (j() != null) {
         i().a(j());
       } else if (i() != null) {
         i().a(new class_fa("Disconnected"));
       }
     } else {
       g.warn("handleDisconnection() called twice");
     }
   }
 }
  @Test
  public void listenerExceptionShouldCloseConnection() throws Exception {
    final Http2Headers headers = dummyHeaders();
    doThrow(new RuntimeException("Fake Exception"))
        .when(serverListener)
        .onHeadersRead(
            any(ChannelHandlerContext.class),
            eq(3),
            eq(headers),
            eq(0),
            eq((short) 16),
            eq(false),
            eq(0),
            eq(false));

    bootstrapEnv(1, 0, 1, 1);

    // Create a latch to track when the close occurs.
    final CountDownLatch closeLatch = new CountDownLatch(1);
    clientChannel
        .closeFuture()
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                closeLatch.countDown();
              }
            });

    // Create a single stream by sending a HEADERS frame to the server.
    runInChannel(
        clientChannel,
        new Http2Runnable() {
          @Override
          public void run() {
            http2Client
                .encoder()
                .writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise());
          }
        });

    // Wait for the server to create the stream.
    assertTrue(serverSettingsAckLatch.await(5, SECONDS));
    assertTrue(requestLatch.await(5, SECONDS));

    // Wait for the close to occur.
    assertTrue(closeLatch.await(5, SECONDS));
    assertFalse(clientChannel.isOpen());
  }
Exemplo n.º 10
0
  @Test
  public void commandNotExecutedChannelClosesWhileFlush() throws Exception {

    RedisCommands<String, String> connection = client.connect().sync();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter<String, String> channelWriter =
        getRedisChannelHandler(connection).getChannelWriter();

    connection.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    AsyncCommand<String, String, Object> command =
        new AsyncCommand<String, String, Object>(
            new Command<>(
                CommandType.INCR, new IntegerOutput(CODEC), new CommandArgs<>(CODEC).addKey(key))) {

          @Override
          public void encode(ByteBuf buf) {
            try {
              block.await();
            } catch (InterruptedException e) {
            }
            super.encode(buf);
          }
        };

    channelWriter.write(command);

    Channel channel = getChannel(getRedisChannelHandler(connection));
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isTrue();

    assertThat(verificationConnection.get(key)).isEqualTo("1");

    assertThat(getQueue(getRedisChannelHandler(connection))).isEmpty();
    assertThat(getCommandBuffer(getRedisChannelHandler(connection))).isEmpty();

    connection.close();
  }
Exemplo n.º 11
0
  @Test
  public void commandRetriedChannelClosesWhileFlush() throws Exception {

    assumeTrue(Version.identify().get("netty-transport").artifactVersion().startsWith("4.0.2"));

    RedisCommands<String, String> connection = client.connect().sync();
    RedisCommands<String, String> verificationConnection = client.connect().sync();
    RedisChannelWriter<String, String> channelWriter =
        getRedisChannelHandler(connection).getChannelWriter();

    connection.set(key, "1");
    assertThat(verificationConnection.get(key)).isEqualTo("1");

    final CountDownLatch block = new CountDownLatch(1);

    ConnectionWatchdog connectionWatchdog =
        Connections.getConnectionWatchdog(connection.getStatefulConnection());

    AsyncCommand<String, String, Object> command = getBlockOnEncodeCommand(block);

    channelWriter.write(command);

    connectionWatchdog.setReconnectSuspended(true);

    Channel channel = getChannel(getRedisChannelHandler(connection));
    channel.unsafe().disconnect(channel.newPromise());

    assertThat(channel.isOpen()).isFalse();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isFalse();
    block.countDown();
    assertThat(command.await(2, TimeUnit.SECONDS)).isFalse();

    connectionWatchdog.setReconnectSuspended(false);
    connectionWatchdog.scheduleReconnect();

    assertThat(command.await(2, TimeUnit.SECONDS)).isTrue();
    assertThat(command.isCancelled()).isFalse();
    assertThat(command.isDone()).isTrue();

    assertThat(verificationConnection.get(key)).isEqualTo("2");

    assertThat(getQueue(getRedisChannelHandler(connection))).isEmpty();
    assertThat(getCommandBuffer(getRedisChannelHandler(connection))).isEmpty();

    connection.close();
    verificationConnection.close();
  }
Exemplo n.º 12
0
  @Test
  public void nonHttp2ExceptionInPipelineShouldNotCloseConnection() throws Exception {
    bootstrapEnv(1, 1, 1, 1);

    // Create a latch to track when the close occurs.
    final CountDownLatch closeLatch = new CountDownLatch(1);
    clientChannel
        .closeFuture()
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                closeLatch.countDown();
              }
            });

    // Create a single stream by sending a HEADERS frame to the server.
    final Http2Headers headers = dummyHeaders();
    runInChannel(
        clientChannel,
        new Http2Runnable() {
          @Override
          public void run() {
            http2Client
                .encoder()
                .writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise());
          }
        });

    // Wait for the server to create the stream.
    assertTrue(serverSettingsAckLatch.await(5, SECONDS));
    assertTrue(requestLatch.await(5, SECONDS));

    // Add a handler that will immediately throw an exception.
    clientChannel
        .pipeline()
        .addFirst(
            new ChannelHandlerAdapter() {
              @Override
              public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                throw new RuntimeException("Fake Exception");
              }
            });

    // The close should NOT occur.
    assertFalse(closeLatch.await(5, SECONDS));
    assertTrue(clientChannel.isOpen());
  }
  private AtomicLong getChannelCounter(Channel channel) {
    AtomicLong counter = channelCounters.get(channel);
    if (counter == null) {
      counter = new AtomicLong();
      AtomicLong oldCounter = channelCounters.putIfAbsent(channel, counter);
      if (oldCounter != null) {
        counter = oldCounter;
      }
    }

    // Remove the entry when the channel closes.
    if (!channel.isOpen()) {
      channelCounters.remove(channel);
    }
    return counter;
  }
  protected void decreaseCounter(Runnable task) {
    if (!shouldCount(task)) {
      return;
    }

    Settings settings = this.settings;
    long maxChannelMemorySize = settings.maxChannelMemorySize;

    int increment;
    if (task instanceof ChannelEventRunnable) {
      increment = ((ChannelEventRunnable) task).estimatedSize;
    } else {
      increment = ((MemoryAwareRunnable) task).estimatedSize;
    }

    if (totalLimiter != null) {
      totalLimiter.decrease(increment);
    }

    if (task instanceof ChannelEventRunnable) {
      ChannelEventRunnable eventTask = (ChannelEventRunnable) task;
      Channel channel = eventTask.getEvent().getChannel();
      long channelCounter = getChannelCounter(channel).addAndGet(-increment);
      // System.out.println("DC: " + channelCounter + ", " + increment);
      if (maxChannelMemorySize != 0 && channelCounter < maxChannelMemorySize && channel.isOpen()) {
        if (!channel.isReadable()) {
          // System.out.println("READABLE");
          ChannelHandlerContext ctx = eventTask.getContext();
          if (ctx.getHandler() instanceof ExecutionHandler) {
            // check if the attachment was set as this means that we suspend the channel from reads.
            // This only works when
            // this pool is used with ExecutionHandler but I guess thats good enough for us.
            //
            // See #215
            if (ctx.getAttachment() != null) {
              // readSuspended = false;
              ctx.setAttachment(null);
              channel.setReadable(true);
            }
          } else {
            channel.setReadable(true);
          }
        }
      }
    }
  }
Exemplo n.º 15
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;
  }
Exemplo n.º 16
0
  public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer());

      Channel ch = b.connect(HOST, PORT).sync().channel();

      while (true) {
        Scanner scanner = new Scanner(System.in);
        Double bet = null;
        while (true) {
          try {
            bet = scanner.nextDouble();
            if (bet > MIN_BET && bet < MAX_BET) {
              break;
            }
            throw new InputMismatchException();
          } catch (InputMismatchException e) {
            System.out.println("Not correct!\r\n");
            scanner.nextLine();
          }
          if (!ch.isOpen()) {
            System.exit(0);
          }
        }
        ch.writeAndFlush(bet + "\r\n");

        while (true) {
          String action = scanner.nextLine();
          if (action.toLowerCase().equals(STAND) || action.toLowerCase().equals(DOUBLE)) {
            ch.writeAndFlush(action);
            break;
          } else if (action.toLowerCase().equals(HIT)) {
            ch.writeAndFlush(action);
          }
        }
      }
    } finally {
      group.shutdownGracefully();
    }
  }
Exemplo n.º 17
0
  public void sendMsg(Channel channel) {
    if (!channel.isOpen()) return;

    for (int i = 0; i < size(); i++) {
      int msgId = idBufList.get(bufCurIndex);
      Chunk msgbuf = chunkBufList.get(bufCurIndex);
      removeMsg();

      // 构造头文件数据
      ByteBuf head = channel.alloc().buffer(8);
      head.writeInt(msgbuf.length + 8);
      head.writeInt(msgId);

      // 写入头数据
      channel.write(head);
      // Chunk类型的msgbuf肯定是protobuf直接生成的 所以buffer属性中不会有多余数据 才能这么用
      // 其余地方Chunk类不建议直接使用内部的buffer
      channel.write(msgbuf.buffer);
    }
    channel.flush();
  }
Exemplo n.º 18
0
 public boolean isActive() {
   return !timedOut && (channel.isOpen() || channel.isActive());
 }
Exemplo n.º 19
0
 @Override
 public void shutdown() {
   if (channel.isOpen()) {
     channel.close();
   }
 }
Exemplo n.º 20
0
 public void a(IChatBaseComponent var1) {
   if (k.isOpen()) {
     k.close().awaitUninterruptibly();
     n = var1;
   }
 }
Exemplo n.º 21
0
  @Override
  public void close() {
    try {
      if (mDone) {
        return;
      }
      if (!mChannel.isOpen()) {
        return;
      }
      try {
        if (!CANCEL_ENABLED) {
          mChannel.close().sync();
          return;
        }
        if (remaining() > 0) {
          Protocol.ReadRequest cancelRequest =
              Protocol.ReadRequest.newBuilder()
                  .setId(mId)
                  .setCancel(true)
                  .setType(mRequestType)
                  .build();
          mChannel
              .writeAndFlush(new RPCProtoMessage(cancelRequest))
              .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }
      } catch (InterruptedException e) {
        mChannel.close();
        throw Throwables.propagate(e);
      }

      while (true) {
        try {
          ByteBuf buf = readPacket();
          // A null packet indicates the end of the stream.
          if (buf == null) {
            return;
          }
          buf.release();
        } catch (IOException e) {
          LOG.warn(
              "Failed to close the NettyBlockReader (block: {}, address: {}).", mId, mAddress, e);
          try {
            mChannel.close().sync();
          } catch (InterruptedException ee) {
            throw Throwables.propagate(ee);
          }
          return;
        }
      }
    } finally {
      if (mChannel.isOpen()) {
        Preconditions.checkState(mChannel.pipeline().last() instanceof PacketReadHandler);
        mChannel.pipeline().removeLast();

        // Make sure "autoread" is on before realsing the channel.
        resume();
      }
      mContext.releaseNettyChannel(mAddress, mChannel);
      mClosed = true;
    }
  }
Exemplo n.º 22
0
 public boolean g() {
   return (k != null) && k.isOpen();
 }