You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@uniffle.apache.org by "xumanbu (via GitHub)" <gi...@apache.org> on 2023/03/27 10:04:18 UTC

[GitHub] [incubator-uniffle] xumanbu opened a new pull request, #771: [#584] transport client pool for netty

xumanbu opened a new pull request, #771:
URL: https://github.com/apache/incubator-uniffle/pull/771

   <!--
   1. Title: [#<issue>] <type>(<scope>): <subject>
      Examples:
        - "[#123] feat(operator): support xxx"
        - "[#233] fix: check null before access result in xxx"
        - "[MINOR] refactor: fix typo in variable name"
        - "[MINOR] docs: fix typo in README"
        - "[#255] test: fix flaky test NameOfTheTest"
      Reference: https://www.conventionalcommits.org/en/v1.0.0/
   2. Contributor guidelines:
      https://github.com/apache/incubator-uniffle/blob/master/CONTRIBUTING.md
   3. If the PR is unfinished, please mark this PR as draft.
   -->
   
   ### What changes were proposed in this pull request?
   
   (Please outline the changes and how this PR fixes the issue.)
   
   ### Why are the changes needed?
   Fix: # (584)
   
   ### Does this PR introduce _any_ user-facing change?
   
   (Please list the user-facing changes introduced by your change, including
     1. add  for netty rpc client TransportClient
     2. TransportClientFactory for connection pool
     3. TransportResponseHandler 
   
   ### How was this patch tested?
   be provided later
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151465304


##########
common/src/main/java/org/apache/uniffle/common/config/RssClientConf.java:
##########
@@ -43,4 +44,55 @@ public class RssClientConf {
       .defaultValue(ShuffleDataDistributionType.NORMAL)
       .withDescription("The type of partition shuffle data distribution, including normal and local_order. "
           + "The default value is normal. This config is only valid in Spark3.x");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECT_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.io.connect.timeout.ms")
+      .intType()
+      .defaultValue(10 * 1000)
+      .withDescription("netty connect to server time out mills");
+
+  public static final ConfigOption<IOMode> NETTY_IO_MODE = ConfigOptions
+      .key("rss.client.netty.io.mode")
+      .enumType(IOMode.class)
+      .defaultValue(IOMode.NIO)
+      .withDescription("Netty EventLoopGroup backend, available options: NIO, EPOLL.");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECTION_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.client.connection.timeout.ms")
+      .intType()
+      .defaultValue(10 * 60 * 1000)
+      .withDescription("connection active timeout");
+
+  public static final ConfigOption<Integer> NETTY_CLIENT_THREADS = ConfigOptions
+      .key("rss.client.netty.client.threads")
+      .intType()
+      .defaultValue(0)
+      .withDescription("Number of threads used in the client thread pool.");
+
+  public static final ConfigOption<Boolean> NETWORK_CLIENT_PREFER_DIRECT_BUFS = ConfigOptions
+      .key("rss.client.netty.client.prefer.direct.bufs")
+      .booleanType()
+      .defaultValue(true)
+      .withDescription("If true, we will prefer allocating off-heap byte buffers within Netty.");
+
+  public static final ConfigOption<Integer> NETTY_CLIENT_NUM_CONNECTIONS_PER_PEER = ConfigOptions
+      .key("rss.client.netty.client.connections.per.peer")
+      .intType()
+      .defaultValue(2)

Review Comment:
   I think default value small is safty. In small number uniffle server cluster,the large value will case a lot of connections to server.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1486542512

   > @xumanbu would you mind modify the pr description to the current status?
   
   done.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1486594753

   > > > @xumanbu would you mind modify the pr description to the current status?
   > > 
   > > 
   > > done.
   > 
   > I think the content of `Does this PR introduce any user-facing change?` should fall into `What changes were proposed in this pull request?`?
   > 
   > And regarding the user changes, you could describe it as `add client configurations and add the ability to reuse netty clients`. And you may update the user documentation after the netty feature is completed.
   
   thanks for your guidance. edited.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1488188200

   
   We better add some UTs.
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1153964662


##########
common/src/main/java/org/apache/uniffle/common/netty/client/RpcResponseCallback.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import org.apache.uniffle.common.netty.protocol.RpcResponse;
+
+public interface RpcResponseCallback {
+  /**
+   * Successful serialized result from server.
+   *
+   * <p>After `onSuccess` returns, `response` will be recycled and its content will become invalid.
+   * Please copy the content of `response` if you want to use it after `onSuccess` returns.
+   */
+  void onSuccess(RpcResponse rpcResponse);

Review Comment:
   `GetMemoryShuffleDataResponse` will extend `Message`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1492810073

   There is one comment left. https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150436391 Could you address it?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1153967071


##########
common/src/main/java/org/apache/uniffle/common/netty/client/RpcResponseCallback.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import org.apache.uniffle.common.netty.protocol.RpcResponse;
+
+public interface RpcResponseCallback {
+  /**
+   * Successful serialized result from server.
+   *
+   * <p>After `onSuccess` returns, `response` will be recycled and its content will become invalid.
+   * Please copy the content of `response` if you want to use it after `onSuccess` returns.
+   */
+  void onSuccess(RpcResponse rpcResponse);

Review Comment:
   Seems every Response type will have `status` and `retMsg` attr, it can extend RPCResponse, my mistake.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150138369


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportContext.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.timeout.IdleStateHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.MessageEncoder;
+
+public class TransportContext {
+  private static final Logger logger = LoggerFactory.getLogger(TransportContext.class);
+
+  private TransportConf transportConf;
+
+  private static final MessageEncoder ENCODER = MessageEncoder.INSTANCE;
+
+  public TransportContext(TransportConf transportConf) {
+    this.transportConf = transportConf;
+  }
+
+  public TransportClientFactory createClientFactory() {
+    return new TransportClientFactory(this);
+  }
+
+  public TransportResponseHandler initializePipeline(
+      SocketChannel channel, ChannelInboundHandlerAdapter decoder) {
+    try {
+      TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
+      channel
+          .pipeline()
+          .addLast("encoder", ENCODER) // out
+          .addLast("decoder", decoder) // in

Review Comment:
   My mistake. Ignore it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] advancedxy commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1486550759

   > > @xumanbu would you mind modify the pr description to the current status?
   > 
   > done.
   
   I think the  content of `Does this PR introduce any user-facing change?` should fall into `What changes were proposed in this pull request?`?
   
   And regarding the user changes, you could describe it as `add client configurations and add the ability to reuse netty clients`. And you may update the user documentation after the netty feature is completed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1149979651


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.MessageDecoder;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new MessageDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);
+    }
+
+    int clientIndex =
+        partitionId < 0 ? rand.nextInt(numConnectionsPerPeer) : partitionId % numConnectionsPerPeer;
+    TransportClient cachedClient = clientPool.clients[clientIndex];
+
+    if (cachedClient != null && cachedClient.isActive()) {
+      // Make sure that the channel will not timeout by updating the last use time of the
+      // handler. Then check that the client is still alive, in case it timed out before
+      // this code was able to update things.
+      TransportResponseHandler handler =
+          cachedClient.getChannel().pipeline().get(TransportResponseHandler.class);
+
+      if (cachedClient.isActive()) {
+        logger.trace(
+            "Returning cached connection to {}: {}", cachedClient.getSocketAddress(), cachedClient);
+        return cachedClient;
+      }
+    }
+
+    // If we reach here, we don't have an existing connection open. Let's create a new one.
+    // Multiple threads might race here to create new connections. Keep only one of them active.
+    final long preResolveHost = System.nanoTime();
+    final InetSocketAddress resolvedAddress = new InetSocketAddress(remoteHost, remotePort);
+    final long hostResolveTimeMs = (System.nanoTime() - preResolveHost) / 1000000;
+    if (hostResolveTimeMs > 2000) {
+      logger.warn("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    } else {
+      logger.trace("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    }
+
+    synchronized (clientPool.locks[clientIndex]) {
+      cachedClient = clientPool.clients[clientIndex];
+
+      if (cachedClient != null) {
+        if (cachedClient.isActive()) {
+          logger.trace("Returning cached connection to {}: {}", resolvedAddress, cachedClient);
+          return cachedClient;
+        } else {
+          logger.info("Found inactive connection to {}, creating a new one.", resolvedAddress);
+        }
+      }
+      clientPool.clients[clientIndex] = internalCreateClient(resolvedAddress, decoder);
+      return clientPool.clients[clientIndex];
+    }
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, -1);
+  }
+
+  /**
+   * Create a completely new {@link TransportClient} to the given remote host / port. This
+   * connection is not pooled.
+   *
+   * <p>As with {@link #createClient(String, int)}, this method is blocking.
+   */
+  private TransportClient internalCreateClient(
+      InetSocketAddress address, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    Bootstrap bootstrap = new Bootstrap();
+    bootstrap
+        .group(workerGroup)
+        .channel(socketChannelClass)
+        // Disable Nagle's Algorithm since we don't want packets to wait
+        .option(ChannelOption.TCP_NODELAY, true)
+        .option(ChannelOption.SO_KEEPALIVE, true)
+        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectTimeoutMs())
+        .option(ChannelOption.ALLOCATOR, pooledAllocator);
+
+    if (conf.receiveBuf() > 0) {
+      bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
+    }
+
+    if (conf.sendBuf() > 0) {
+      bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
+    }
+
+    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
+    final AtomicReference<Channel> channelRef = new AtomicReference<>();
+
+    bootstrap.handler(
+        new ChannelInitializer<SocketChannel>() {
+          @Override
+          public void initChannel(SocketChannel ch) {
+            TransportResponseHandler transportResponseHandler = context.initializePipeline(ch, decoder);
+            TransportClient client = new TransportClient(ch, transportResponseHandler);
+            clientRef.set(client);
+            channelRef.set(ch);
+          }
+        });
+
+    // Connect to the remote server
+    ChannelFuture cf = bootstrap.connect(address);
+    if (!cf.await(conf.connectTimeoutMs())) {
+      throw new IOException(
+          String.format("Connecting to %s timed out (%s ms)", address, conf.connectTimeoutMs()));
+    } else if (cf.cause() != null) {
+      throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
+    }
+
+    TransportClient client = clientRef.get();
+    assert client != null : "Channel future completed successfully with null client";
+
+    logger.debug("Connection to {} successful", address);
+
+    return client;
+  }
+
+  /**
+   * Close all connections in the connection pool, and shutdown the worker thread pool.
+   */
+  @Override
+  public void close() {
+    // Go through all clients and close them if they are active.
+    for (ClientPool clientPool : connectionPool.values()) {
+      for (int i = 0; i < clientPool.clients.length; i++) {
+        TransportClient client = clientPool.clients[i];
+        if (client != null) {
+          clientPool.clients[i] = null;
+          JavaUtils.closeQuietly(client);
+        }
+      }
+    }
+    connectionPool.clear();
+
+    // SPARK-19147

Review Comment:
   Could we remove this comment?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));
+    }
+  }
+
+
+  @Override
+  public void close() throws IOException {
+    // close is a local operation and should finish with milliseconds; timeout just to be safe
+    channel.close().awaitUninterruptibly(10, TimeUnit.SECONDS);

Review Comment:
   Why do we choose `10`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] codecov-commenter commented on pull request #771: [#584] feat(netty): transport client pool for netty

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1484983699

   ## [Codecov](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#771](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (42b4e2b) into [master](https://codecov.io/gh/apache/incubator-uniffle/commit/d60d675d38c833b99b012a1f4c726a012ce93463?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (d60d675) will **increase** coverage by `1.49%`.
   > The diff coverage is `16.12%`.
   
   ```diff
   @@             Coverage Diff              @@
   ##             master     #771      +/-   ##
   ============================================
   + Coverage     60.63%   62.13%   +1.49%     
   - Complexity     1893     1954      +61     
   ============================================
     Files           238      237       -1     
     Lines         13000    11588    -1412     
     Branches       1090     1136      +46     
   ============================================
   - Hits           7883     7200     -683     
   + Misses         4679     3993     -686     
   + Partials        438      395      -43     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [...e/uniffle/common/netty/client/TransportClient.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9jbGllbnQvVHJhbnNwb3J0Q2xpZW50LmphdmE=) | `0.00% <0.00%> (ø)` | |
   | [...le/common/netty/client/TransportClientFactory.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9jbGllbnQvVHJhbnNwb3J0Q2xpZW50RmFjdG9yeS5qYXZh) | `0.00% <0.00%> (ø)` | |
   | [...che/uniffle/common/netty/client/TransportConf.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9jbGllbnQvVHJhbnNwb3J0Q29uZi5qYXZh) | `0.00% <0.00%> (ø)` | |
   | [.../uniffle/common/netty/client/TransportContext.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9jbGllbnQvVHJhbnNwb3J0Q29udGV4dC5qYXZh) | `0.00% <0.00%> (ø)` | |
   | [.../common/netty/handle/TransportResponseHandler.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9oYW5kbGUvVHJhbnNwb3J0UmVzcG9uc2VIYW5kbGVyLmphdmE=) | `0.00% <0.00%> (ø)` | |
   | [.../uniffle/common/netty/protocol/MessageDecoder.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9wcm90b2NvbC9NZXNzYWdlRGVjb2Rlci5qYXZh) | `0.00% <0.00%> (ø)` | |
   | [.../uniffle/common/netty/protocol/MessageEncoder.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9uZXR0eS9wcm90b2NvbC9NZXNzYWdlRW5jb2Rlci5qYXZh) | `0.00% <0.00%> (ø)` | |
   | [...rg/apache/uniffle/common/config/RssClientConf.java](https://codecov.io/gh/apache/incubator-uniffle/pull/771?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-Y29tbW9uL3NyYy9tYWluL2phdmEvb3JnL2FwYWNoZS91bmlmZmxlL2NvbW1vbi9jb25maWcvUnNzQ2xpZW50Q29uZi5qYXZh) | `98.21% <100.00%> (+4.46%)` | :arrow_up: |
   
   ... and [59 files with indirect coverage changes](https://codecov.io/gh/apache/incubator-uniffle/pull/771/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on a diff in pull request #771: [#584] feat(netty): transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1149946736


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportContext.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.timeout.IdleStateHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.MessageEncoder;
+
+public class TransportContext {
+  private static final Logger logger = LoggerFactory.getLogger(TransportContext.class);
+
+  private TransportConf transportConf;
+
+  private static final MessageEncoder ENCODER = MessageEncoder.INSTANCE;
+
+  public TransportContext(TransportConf transportConf) {
+    this.transportConf = transportConf;
+  }
+
+  public TransportClientFactory createClientFactory() {
+    return new TransportClientFactory(this);
+  }
+
+  public TransportResponseHandler initializePipeline(
+      SocketChannel channel, ChannelInboundHandlerAdapter decoder) {
+    try {
+      TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
+      channel
+          .pipeline()
+          .addLast("encoder", ENCODER) // out
+          .addLast("decoder", decoder) // in

Review Comment:
   Is it right?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151461270


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();

Review Comment:
   OK.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1488187832

   We better Add some UTs.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1155450849


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {

Review Comment:
   use non-static inner class for Listener is for the method to access the attributes of the out class,such as channel,handle.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1486303280

   @xumanbu Encoder and Decoder already added, see #742 .


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] smallzhongfeng commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "smallzhongfeng (via GitHub)" <gi...@apache.org>.
smallzhongfeng commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150420594


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();

Review Comment:
    Maybe we can use `JavaUtils.newConcurrentMap()`



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new TransportFrameDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);

Review Comment:
   Could we use `computeIfAbsent` to merge this two lines?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151478708


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportContext.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.timeout.IdleStateHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.MessageEncoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+
+public class TransportContext {
+  private static final Logger logger = LoggerFactory.getLogger(TransportContext.class);
+
+  private TransportConf transportConf;
+
+  private static final MessageEncoder ENCODER = MessageEncoder.INSTANCE;
+
+  public TransportContext(TransportConf transportConf) {
+    this.transportConf = transportConf;
+  }
+
+  public TransportClientFactory createClientFactory() {
+    return new TransportClientFactory(this);
+  }
+
+  public TransportResponseHandler initializePipeline(
+      SocketChannel channel, ChannelInboundHandlerAdapter decoder) {
+    TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
+    channel
+        .pipeline()
+        .addLast("encoder", ENCODER) // out
+        .addLast("decoder", decoder) // in

Review Comment:
   encoder is stateless,decoder is statful for each channel,so I think decorder need created at client create.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] advancedxy commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151530335


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);

Review Comment:
   > Preconditions#checkNotNull will throw NPE when object is null,
   
   `Objects#requireNonNull` does exactly the same. The point is that we should prefer std lib over guava as guava has its reputation to break things in various versions, therefore it will cause class conflict for other systems which also has different version of guava.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] advancedxy commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150421787


##########
common/src/main/java/org/apache/uniffle/common/config/RssClientConf.java:
##########
@@ -43,4 +44,55 @@ public class RssClientConf {
       .defaultValue(ShuffleDataDistributionType.NORMAL)
       .withDescription("The type of partition shuffle data distribution, including normal and local_order. "
           + "The default value is normal. This config is only valid in Spark3.x");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECT_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.io.connect.timeout.ms")
+      .intType()
+      .defaultValue(10 * 1000)
+      .withDescription("netty connect to server time out mills");
+
+  public static final ConfigOption<IOMode> NETTY_IO_MODE = ConfigOptions
+      .key("rss.client.netty.io.mode")
+      .enumType(IOMode.class)
+      .defaultValue(IOMode.NIO)
+      .withDescription("Netty EventLoopGroup backend, available options: NIO, EPOLL.");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECTION_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.client.connection.timeout.ms")
+      .intType()
+      .defaultValue(10 * 60 * 1000)
+      .withDescription("connection active timeout");
+
+  public static final ConfigOption<Integer> NETTY_CLIENT_THREADS = ConfigOptions
+      .key("rss.client.netty.client.threads")
+      .intType()
+      .defaultValue(0)
+      .withDescription("Number of threads used in the client thread pool.");
+
+  public static final ConfigOption<Boolean> NETWORK_CLIENT_PREFER_DIRECT_BUFS = ConfigOptions
+      .key("rss.client.netty.client.prefer.direct.bufs")
+      .booleanType()
+      .defaultValue(true)
+      .withDescription("If true, we will prefer allocating off-heap byte buffers within Netty.");
+
+  public static final ConfigOption<Integer> NETTY_CLIENT_NUM_CONNECTIONS_PER_PEER = ConfigOptions
+      .key("rss.client.netty.client.connections.per.peer")
+      .intType()
+      .defaultValue(2)

Review Comment:
   is this too small?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);

Review Comment:
   Use `java.util.Objects#requireNonNull` instead?



##########
common/src/main/java/org/apache/uniffle/common/config/RssClientConf.java:
##########
@@ -43,4 +44,55 @@ public class RssClientConf {
       .defaultValue(ShuffleDataDistributionType.NORMAL)
       .withDescription("The type of partition shuffle data distribution, including normal and local_order. "
           + "The default value is normal. This config is only valid in Spark3.x");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECT_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.io.connect.timeout.ms")
+      .intType()
+      .defaultValue(10 * 1000)
+      .withDescription("netty connect to server time out mills");
+
+  public static final ConfigOption<IOMode> NETTY_IO_MODE = ConfigOptions
+      .key("rss.client.netty.io.mode")

Review Comment:
   @leixm added `rss.server.netty.epoll.enable` for netty sever,do you guys it's better to rename that configuration to `rss.server.netty.io.mode` instead? So they are more consistent. 



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new TransportFrameDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);
+    }

Review Comment:
   ```suggestion
       ClientPool clientPool = connectionPool.computeIfAbsent(unresolvedAddress, x -> new ClientPool(numConnectionsPerPeer));
   ```
   ?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new TransportFrameDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);
+    }
+
+    int clientIndex =
+        partitionId < 0 ? rand.nextInt(numConnectionsPerPeer) : partitionId % numConnectionsPerPeer;
+    TransportClient cachedClient = clientPool.clients[clientIndex];
+
+    if (cachedClient != null && cachedClient.isActive()) {
+      // Make sure that the channel will not timeout by updating the last use time of the
+      // handler. Then check that the client is still alive, in case it timed out before
+      // this code was able to update things.
+      TransportResponseHandler handler =
+          cachedClient.getChannel().pipeline().get(TransportResponseHandler.class);
+
+      if (cachedClient.isActive()) {
+        logger.trace(
+            "Returning cached connection to {}: {}", cachedClient.getSocketAddress(), cachedClient);
+        return cachedClient;
+      }
+    }
+
+    // If we reach here, we don't have an existing connection open. Let's create a new one.
+    // Multiple threads might race here to create new connections. Keep only one of them active.
+    final long preResolveHost = System.nanoTime();
+    final InetSocketAddress resolvedAddress = new InetSocketAddress(remoteHost, remotePort);
+    final long hostResolveTimeMs = (System.nanoTime() - preResolveHost) / 1000000;
+    if (hostResolveTimeMs > 2000) {
+      logger.warn("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    } else {
+      logger.trace("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    }
+
+    synchronized (clientPool.locks[clientIndex]) {
+      cachedClient = clientPool.clients[clientIndex];
+
+      if (cachedClient != null) {
+        if (cachedClient.isActive()) {
+          logger.trace("Returning cached connection to {}: {}", resolvedAddress, cachedClient);
+          return cachedClient;
+        } else {
+          logger.info("Found inactive connection to {}, creating a new one.", resolvedAddress);
+        }
+      }
+      clientPool.clients[clientIndex] = internalCreateClient(resolvedAddress, decoder);

Review Comment:
   Could you wrap these block of code into the ClientPool structure?
   
   Such as `clientPoo.createClientIfAbsent`, which should be similar as ConcurrentMap's computeIfAbsent?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();

Review Comment:
   Use JavaUtils.newConcurrentMap?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {

Review Comment:
   Seems like that it's better to declare it as `public static class`?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportContext.java:
##########
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.timeout.IdleStateHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.MessageEncoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+
+public class TransportContext {
+  private static final Logger logger = LoggerFactory.getLogger(TransportContext.class);
+
+  private TransportConf transportConf;
+
+  private static final MessageEncoder ENCODER = MessageEncoder.INSTANCE;
+
+  public TransportContext(TransportConf transportConf) {
+    this.transportConf = transportConf;
+  }
+
+  public TransportClientFactory createClientFactory() {
+    return new TransportClientFactory(this);
+  }
+
+  public TransportResponseHandler initializePipeline(
+      SocketChannel channel, ChannelInboundHandlerAdapter decoder) {
+    TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
+    channel
+        .pipeline()
+        .addLast("encoder", ENCODER) // out
+        .addLast("decoder", decoder) // in

Review Comment:
   This seems doesn't align? 
   Why couldn't we create decoder ealier?



##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));

Review Comment:
   Still we add a logging here?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150135965


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportContext.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.handler.timeout.IdleStateHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.MessageEncoder;
+
+public class TransportContext {
+  private static final Logger logger = LoggerFactory.getLogger(TransportContext.class);
+
+  private TransportConf transportConf;
+
+  private static final MessageEncoder ENCODER = MessageEncoder.INSTANCE;
+
+  public TransportContext(TransportConf transportConf) {
+    this.transportConf = transportConf;
+  }
+
+  public TransportClientFactory createClientFactory() {
+    return new TransportClientFactory(this);
+  }
+
+  public TransportResponseHandler initializePipeline(
+      SocketChannel channel, ChannelInboundHandlerAdapter decoder) {
+    try {
+      TransportResponseHandler responseHandler = new TransportResponseHandler(channel);
+      channel
+          .pipeline()
+          .addLast("encoder", ENCODER) // out
+          .addLast("decoder", decoder) // in

Review Comment:
   I‘ll remove runtimeException catch,is this ok?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151473129


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));

Review Comment:
   make sense.I'll add same log.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1154151757


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));

Review Comment:
   same log is already add in parent method,so I think it's enough at now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150195242


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.MessageDecoder;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new MessageDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);
+    }
+
+    int clientIndex =
+        partitionId < 0 ? rand.nextInt(numConnectionsPerPeer) : partitionId % numConnectionsPerPeer;
+    TransportClient cachedClient = clientPool.clients[clientIndex];
+
+    if (cachedClient != null && cachedClient.isActive()) {
+      // Make sure that the channel will not timeout by updating the last use time of the
+      // handler. Then check that the client is still alive, in case it timed out before
+      // this code was able to update things.
+      TransportResponseHandler handler =
+          cachedClient.getChannel().pipeline().get(TransportResponseHandler.class);
+
+      if (cachedClient.isActive()) {
+        logger.trace(
+            "Returning cached connection to {}: {}", cachedClient.getSocketAddress(), cachedClient);
+        return cachedClient;
+      }
+    }
+
+    // If we reach here, we don't have an existing connection open. Let's create a new one.
+    // Multiple threads might race here to create new connections. Keep only one of them active.
+    final long preResolveHost = System.nanoTime();
+    final InetSocketAddress resolvedAddress = new InetSocketAddress(remoteHost, remotePort);
+    final long hostResolveTimeMs = (System.nanoTime() - preResolveHost) / 1000000;
+    if (hostResolveTimeMs > 2000) {
+      logger.warn("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    } else {
+      logger.trace("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    }
+
+    synchronized (clientPool.locks[clientIndex]) {
+      cachedClient = clientPool.clients[clientIndex];
+
+      if (cachedClient != null) {
+        if (cachedClient.isActive()) {
+          logger.trace("Returning cached connection to {}: {}", resolvedAddress, cachedClient);
+          return cachedClient;
+        } else {
+          logger.info("Found inactive connection to {}, creating a new one.", resolvedAddress);
+        }
+      }
+      clientPool.clients[clientIndex] = internalCreateClient(resolvedAddress, decoder);
+      return clientPool.clients[clientIndex];
+    }
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, -1);
+  }
+
+  /**
+   * Create a completely new {@link TransportClient} to the given remote host / port. This
+   * connection is not pooled.
+   *
+   * <p>As with {@link #createClient(String, int)}, this method is blocking.
+   */
+  private TransportClient internalCreateClient(
+      InetSocketAddress address, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    Bootstrap bootstrap = new Bootstrap();
+    bootstrap
+        .group(workerGroup)
+        .channel(socketChannelClass)
+        // Disable Nagle's Algorithm since we don't want packets to wait
+        .option(ChannelOption.TCP_NODELAY, true)
+        .option(ChannelOption.SO_KEEPALIVE, true)
+        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectTimeoutMs())
+        .option(ChannelOption.ALLOCATOR, pooledAllocator);
+
+    if (conf.receiveBuf() > 0) {
+      bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
+    }
+
+    if (conf.sendBuf() > 0) {
+      bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
+    }
+
+    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
+    final AtomicReference<Channel> channelRef = new AtomicReference<>();
+
+    bootstrap.handler(
+        new ChannelInitializer<SocketChannel>() {
+          @Override
+          public void initChannel(SocketChannel ch) {
+            TransportResponseHandler transportResponseHandler = context.initializePipeline(ch, decoder);
+            TransportClient client = new TransportClient(ch, transportResponseHandler);
+            clientRef.set(client);
+            channelRef.set(ch);
+          }
+        });
+
+    // Connect to the remote server
+    ChannelFuture cf = bootstrap.connect(address);
+    if (!cf.await(conf.connectTimeoutMs())) {
+      throw new IOException(
+          String.format("Connecting to %s timed out (%s ms)", address, conf.connectTimeoutMs()));
+    } else if (cf.cause() != null) {
+      throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
+    }
+
+    TransportClient client = clientRef.get();
+    assert client != null : "Channel future completed successfully with null client";
+
+    logger.debug("Connection to {} successful", address);
+
+    return client;
+  }
+
+  /**
+   * Close all connections in the connection pool, and shutdown the worker thread pool.
+   */
+  @Override
+  public void close() {
+    // Go through all clients and close them if they are active.
+    for (ClientPool clientPool : connectionPool.values()) {
+      for (int i = 0; i < clientPool.clients.length; i++) {
+        TransportClient client = clientPool.clients[i];
+        if (client != null) {
+          clientPool.clients[i] = null;
+          JavaUtils.closeQuietly(client);
+        }
+      }
+    }
+    connectionPool.clear();
+
+    // SPARK-19147

Review Comment:
   ```suggestion
       
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1153008561


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);

Review Comment:
   make sense.I'll instead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1153965269


##########
common/src/main/java/org/apache/uniffle/common/netty/client/RpcResponseCallback.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import org.apache.uniffle.common.netty.protocol.RpcResponse;
+
+public interface RpcResponseCallback {
+  /**
+   * Successful serialized result from server.
+   *
+   * <p>After `onSuccess` returns, `response` will be recycled and its content will become invalid.
+   * Please copy the content of `response` if you want to use it after `onSuccess` returns.
+   */
+  void onSuccess(RpcResponse rpcResponse);

Review Comment:
   Why do `GetMemoryShuffleDataResponse` need extend `Message`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1491229740

   > We better add some UTs.
   
   Spark don't have UTs, too. Maybe we can use Integration tests to guarantee the correctness when other prs were merged.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1493591574

   > @xumanbu There is one comment left. [#771 (comment)](https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150436391) Could you address it?
   
   My mistake.done.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1491231176

   > > We better add some UTs.
   > 
   > Spark don't have UTs, too. Maybe we can use Integration tests to guarantee the correctness when other prs were merged.
   
   Ok.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1153016010


##########
common/src/main/java/org/apache/uniffle/common/netty/client/RpcResponseCallback.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import org.apache.uniffle.common.netty.protocol.RpcResponse;
+
+public interface RpcResponseCallback {
+  /**
+   * Successful serialized result from server.
+   *
+   * <p>After `onSuccess` returns, `response` will be recycled and its content will become invalid.
+   * Please copy the content of `response` if you want to use it after `onSuccess` returns.
+   */
+  void onSuccess(RpcResponse rpcResponse);

Review Comment:
   getInMemoryShuffleData result will extends RPCResponse in your design?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151471444


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);

Review Comment:
   Preconditions#checkNotNull will throw NPE when object is null,Preconditions may easyer to use than Object#requireNonNull.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] leixm commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "leixm (via GitHub)" <gi...@apache.org>.
leixm commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151600270


##########
common/src/main/java/org/apache/uniffle/common/netty/client/RpcResponseCallback.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import org.apache.uniffle.common.netty.protocol.RpcResponse;
+
+public interface RpcResponseCallback {
+  /**
+   * Successful serialized result from server.
+   *
+   * <p>After `onSuccess` returns, `response` will be recycled and its content will become invalid.
+   * Please copy the content of `response` if you want to use it after `onSuccess` returns.
+   */
+  void onSuccess(RpcResponse rpcResponse);

Review Comment:
   In fact, not all response types are RPCResponse, such as getInMemoryShuffleData.



##########
common/src/main/java/org/apache/uniffle/common/config/RssClientConf.java:
##########
@@ -43,4 +44,55 @@ public class RssClientConf {
       .defaultValue(ShuffleDataDistributionType.NORMAL)
       .withDescription("The type of partition shuffle data distribution, including normal and local_order. "
           + "The default value is normal. This config is only valid in Spark3.x");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECT_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.io.connect.timeout.ms")
+      .intType()
+      .defaultValue(10 * 1000)
+      .withDescription("netty connect to server time out mills");
+
+  public static final ConfigOption<IOMode> NETTY_IO_MODE = ConfigOptions
+      .key("rss.client.netty.io.mode")
+      .enumType(IOMode.class)
+      .defaultValue(IOMode.NIO)
+      .withDescription("Netty EventLoopGroup backend, available options: NIO, EPOLL.");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECTION_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.client.connection.timeout.ms")
+      .intType()
+      .defaultValue(10 * 60 * 1000)
+      .withDescription("connection active timeout");
+
+  public static final ConfigOption<Integer> NETTY_CLIENT_THREADS = ConfigOptions
+      .key("rss.client.netty.client.threads")
+      .intType()
+      .defaultValue(0)
+      .withDescription("Number of threads used in the client thread pool.");
+
+  public static final ConfigOption<Boolean> NETWORK_CLIENT_PREFER_DIRECT_BUFS = ConfigOptions
+      .key("rss.client.netty.client.prefer.direct.bufs")
+      .booleanType()
+      .defaultValue(true)
+      .withDescription("If true, we will prefer allocating off-heap byte buffers within Netty.");
+
+  public static final ConfigOption<Integer> NETTY_CLIENT_NUM_CONNECTIONS_PER_PEER = ConfigOptions
+      .key("rss.client.netty.client.connections.per.peer")
+      .intType()
+      .defaultValue(2)

Review Comment:
   > 
   
   Make sense.



##########
common/src/main/java/org/apache/uniffle/common/config/RssClientConf.java:
##########
@@ -43,4 +44,55 @@ public class RssClientConf {
       .defaultValue(ShuffleDataDistributionType.NORMAL)
       .withDescription("The type of partition shuffle data distribution, including normal and local_order. "
           + "The default value is normal. This config is only valid in Spark3.x");
+
+  public static final ConfigOption<Integer> NETTY_IO_CONNECT_TIMEOUT_MS = ConfigOptions
+      .key("rss.client.netty.io.connect.timeout.ms")
+      .intType()
+      .defaultValue(10 * 1000)
+      .withDescription("netty connect to server time out mills");
+
+  public static final ConfigOption<IOMode> NETTY_IO_MODE = ConfigOptions
+      .key("rss.client.netty.io.mode")

Review Comment:
   It's ok for me, i will fix it later PRs.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] advancedxy commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1486478790

   @xumanbu would you mind modify the pr description to the current status?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150187421


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));
+    }
+  }
+
+
+  @Override
+  public void close() throws IOException {
+    // close is a local operation and should finish with milliseconds; timeout just to be safe
+    channel.close().awaitUninterruptibly(10, TimeUnit.SECONDS);

Review Comment:
   If we refer to Spark, It's also ok.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] jerqi merged pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi merged PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150269249


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.MessageDecoder;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new MessageDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);
+    }
+
+    int clientIndex =
+        partitionId < 0 ? rand.nextInt(numConnectionsPerPeer) : partitionId % numConnectionsPerPeer;
+    TransportClient cachedClient = clientPool.clients[clientIndex];
+
+    if (cachedClient != null && cachedClient.isActive()) {
+      // Make sure that the channel will not timeout by updating the last use time of the
+      // handler. Then check that the client is still alive, in case it timed out before
+      // this code was able to update things.
+      TransportResponseHandler handler =
+          cachedClient.getChannel().pipeline().get(TransportResponseHandler.class);
+
+      if (cachedClient.isActive()) {
+        logger.trace(
+            "Returning cached connection to {}: {}", cachedClient.getSocketAddress(), cachedClient);
+        return cachedClient;
+      }
+    }
+
+    // If we reach here, we don't have an existing connection open. Let's create a new one.
+    // Multiple threads might race here to create new connections. Keep only one of them active.
+    final long preResolveHost = System.nanoTime();
+    final InetSocketAddress resolvedAddress = new InetSocketAddress(remoteHost, remotePort);
+    final long hostResolveTimeMs = (System.nanoTime() - preResolveHost) / 1000000;
+    if (hostResolveTimeMs > 2000) {
+      logger.warn("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    } else {
+      logger.trace("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    }
+
+    synchronized (clientPool.locks[clientIndex]) {
+      cachedClient = clientPool.clients[clientIndex];
+
+      if (cachedClient != null) {
+        if (cachedClient.isActive()) {
+          logger.trace("Returning cached connection to {}: {}", resolvedAddress, cachedClient);
+          return cachedClient;
+        } else {
+          logger.info("Found inactive connection to {}, creating a new one.", resolvedAddress);
+        }
+      }
+      clientPool.clients[clientIndex] = internalCreateClient(resolvedAddress, decoder);
+      return clientPool.clients[clientIndex];
+    }
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, -1);
+  }
+
+  /**
+   * Create a completely new {@link TransportClient} to the given remote host / port. This
+   * connection is not pooled.
+   *
+   * <p>As with {@link #createClient(String, int)}, this method is blocking.
+   */
+  private TransportClient internalCreateClient(
+      InetSocketAddress address, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    Bootstrap bootstrap = new Bootstrap();
+    bootstrap
+        .group(workerGroup)
+        .channel(socketChannelClass)
+        // Disable Nagle's Algorithm since we don't want packets to wait
+        .option(ChannelOption.TCP_NODELAY, true)
+        .option(ChannelOption.SO_KEEPALIVE, true)
+        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectTimeoutMs())
+        .option(ChannelOption.ALLOCATOR, pooledAllocator);
+
+    if (conf.receiveBuf() > 0) {
+      bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
+    }
+
+    if (conf.sendBuf() > 0) {
+      bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
+    }
+
+    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
+    final AtomicReference<Channel> channelRef = new AtomicReference<>();
+
+    bootstrap.handler(
+        new ChannelInitializer<SocketChannel>() {
+          @Override
+          public void initChannel(SocketChannel ch) {
+            TransportResponseHandler transportResponseHandler = context.initializePipeline(ch, decoder);
+            TransportClient client = new TransportClient(ch, transportResponseHandler);
+            clientRef.set(client);
+            channelRef.set(ch);
+          }
+        });
+
+    // Connect to the remote server
+    ChannelFuture cf = bootstrap.connect(address);
+    if (!cf.await(conf.connectTimeoutMs())) {
+      throw new IOException(
+          String.format("Connecting to %s timed out (%s ms)", address, conf.connectTimeoutMs()));
+    } else if (cf.cause() != null) {
+      throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
+    }
+
+    TransportClient client = clientRef.get();
+    assert client != null : "Channel future completed successfully with null client";
+
+    logger.debug("Connection to {} successful", address);
+
+    return client;
+  }
+
+  /**
+   * Close all connections in the connection pool, and shutdown the worker thread pool.
+   */
+  @Override
+  public void close() {
+    // Go through all clients and close them if they are active.
+    for (ClientPool clientPool : connectionPool.values()) {
+      for (int i = 0; i < clientPool.clients.length; i++) {
+        TransportClient client = clientPool.clients[i];
+        if (client != null) {
+          clientPool.clients[i] = null;
+          JavaUtils.closeQuietly(client);
+        }
+      }
+    }
+    connectionPool.clear();
+
+    // SPARK-19147

Review Comment:
   I'll done.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150268631


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));
+    }
+  }
+
+
+  @Override
+  public void close() throws IOException {
+    // close is a local operation and should finish with milliseconds; timeout just to be safe
+    channel.close().awaitUninterruptibly(10, TimeUnit.SECONDS);

Review Comment:
   It's hard to determine actual channel close waiting time in same case, refer to spark is better.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#issuecomment-1486487315

   > @xumanbu Encoder and Decoder already added, see #742 .
   
   I'll rebase with https://github.com/apache/incubator-uniffle/pull/742


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] advancedxy commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "advancedxy (via GitHub)" <gi...@apache.org>.
advancedxy commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1150435574


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClient.java:
##########
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.netty.protocol.Message;
+import org.apache.uniffle.common.util.NettyUtils;
+
+
+public class TransportClient implements Closeable {
+  private static final Logger logger = LoggerFactory.getLogger(TransportClient.class);
+
+  private Channel channel;
+  private TransportResponseHandler handler;
+  private volatile boolean timedOut;
+
+  private static final AtomicLong counter = new AtomicLong();
+
+  public TransportClient(Channel channel, TransportResponseHandler handler) {
+    this.channel = Preconditions.checkNotNull(channel);
+    this.handler = Preconditions.checkNotNull(handler);
+    this.timedOut = false;
+  }
+
+  public Channel getChannel() {
+    return channel;
+  }
+
+  public boolean isActive() {
+    return !timedOut && (channel.isOpen() || channel.isActive());
+  }
+
+  public SocketAddress getSocketAddress() {
+    return channel.remoteAddress();
+  }
+
+  public ChannelFuture sendShuffleData(Message message, RpcResponseCallback callback) {
+    if (logger.isTraceEnabled()) {
+      logger.trace("Pushing data to {}", NettyUtils.getRemoteAddress(channel));
+    }
+    long requestId = requestId();
+    handler.addResponseCallback(requestId, callback);
+    RpcChannelListener listener = new RpcChannelListener(requestId, callback);
+    return channel.writeAndFlush(message).addListener(listener);
+  }
+
+  public static long requestId() {
+    return counter.getAndIncrement();
+  }
+
+  public class StdChannelListener implements GenericFutureListener<Future<? super Void>> {
+    final long startTime;
+    final Object requestId;
+
+    public StdChannelListener(Object requestId) {
+      this.startTime = System.currentTimeMillis();
+      this.requestId = requestId;
+    }
+
+    @Override
+    public void operationComplete(Future<? super Void> future) throws Exception {
+      if (future.isSuccess()) {
+        if (logger.isTraceEnabled()) {
+          long timeTaken = System.currentTimeMillis() - startTime;
+          logger.trace(
+              "Sending request {} to {} took {} ms",
+              requestId,
+              NettyUtils.getRemoteAddress(channel),
+              timeTaken);
+        }
+      } else {
+        String errorMsg =
+            String.format(
+                "Failed to send request %s to %s: %s, channel will be closed",
+                requestId, NettyUtils.getRemoteAddress(channel), future.cause());
+        logger.warn(errorMsg);
+        channel.close();
+        try {
+          handleFailure(errorMsg, future.cause());
+        } catch (Exception e) {
+          logger.error("Uncaught exception in RPC response callback handler!", e);
+        }
+      }
+    }
+
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      logger.error("Error encountered " + errorMsg, cause);
+    }
+  }
+
+  private class RpcChannelListener extends StdChannelListener {
+    final long rpcRequestId;
+    final RpcResponseCallback callback;
+
+    RpcChannelListener(long rpcRequestId, RpcResponseCallback callback) {
+      super("RPC " + rpcRequestId);
+      this.rpcRequestId = rpcRequestId;
+      this.callback = callback;
+    }
+
+    @Override
+    protected void handleFailure(String errorMsg, Throwable cause) {
+      handler.removeRpcRequest(rpcRequestId);
+      callback.onFailure(new IOException(errorMsg, cause));

Review Comment:
   should we add a logging here?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org


[GitHub] [incubator-uniffle] xumanbu commented on a diff in pull request #771: [#584] feat(netty): Add transport client pool for netty

Posted by "xumanbu (via GitHub)" <gi...@apache.org>.
xumanbu commented on code in PR #771:
URL: https://github.com/apache/incubator-uniffle/pull/771#discussion_r1151524853


##########
common/src/main/java/org/apache/uniffle/common/netty/client/TransportClientFactory.java:
##########
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.uniffle.common.netty.client;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Random;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.uniffle.common.netty.IOMode;
+import org.apache.uniffle.common.netty.TransportFrameDecoder;
+import org.apache.uniffle.common.netty.handle.TransportResponseHandler;
+import org.apache.uniffle.common.util.JavaUtils;
+import org.apache.uniffle.common.util.NettyUtils;
+
+public class TransportClientFactory implements Closeable {
+
+  /**
+   * A simple data structure to track the pool of clients between two peer nodes.
+   */
+  private static class ClientPool {
+    TransportClient[] clients;
+    Object[] locks;
+
+    ClientPool(int size) {
+      clients = new TransportClient[size];
+      locks = new Object[size];
+      for (int i = 0; i < size; i++) {
+        locks[i] = new Object();
+      }
+    }
+  }
+
+  private static final Logger logger = LoggerFactory.getLogger(TransportClientFactory.class);
+
+  private final TransportContext context;
+  private final TransportConf conf;
+  private final ConcurrentHashMap<SocketAddress, ClientPool> connectionPool;
+
+  /**
+   * Random number generator for picking connections between peers.
+   */
+  private final Random rand;
+
+  private final int numConnectionsPerPeer;
+
+  private final Class<? extends Channel> socketChannelClass;
+  private EventLoopGroup workerGroup;
+  private PooledByteBufAllocator pooledAllocator;
+
+  public TransportClientFactory(TransportContext context) {
+    this.context = Preconditions.checkNotNull(context);
+    this.conf = context.getConf();
+    this.connectionPool = new ConcurrentHashMap<>();
+    this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
+    this.rand = new Random();
+
+    IOMode ioMode = conf.ioMode();
+    this.socketChannelClass = NettyUtils.getClientChannelClass(ioMode);
+    this.workerGroup =
+        NettyUtils.createEventLoop(ioMode, conf.clientThreads(), "netty-rpc-client");
+    this.pooledAllocator =
+        NettyUtils.createPooledByteBufAllocator(
+            conf.preferDirectBufs(), false, conf.clientThreads());
+  }
+
+  public TransportClient createClient(String remoteHost, int remotePort, int partitionId)
+      throws IOException, InterruptedException {
+    return createClient(remoteHost, remotePort, partitionId, new TransportFrameDecoder());
+  }
+
+  public TransportClient createClient(
+      String remoteHost, int remotePort, int partitionId, ChannelInboundHandlerAdapter decoder)
+      throws IOException, InterruptedException {
+    // Get connection from the connection pool first.
+    // If it is not found or not active, create a new one.
+    // Use unresolved address here to avoid DNS resolution each time we creates a client.
+    final InetSocketAddress unresolvedAddress =
+        InetSocketAddress.createUnresolved(remoteHost, remotePort);
+
+    // Create the ClientPool if we don't have it yet.
+    ClientPool clientPool = connectionPool.get(unresolvedAddress);
+    if (clientPool == null) {
+      connectionPool.putIfAbsent(unresolvedAddress, new ClientPool(numConnectionsPerPeer));
+      clientPool = connectionPool.get(unresolvedAddress);
+    }
+
+    int clientIndex =
+        partitionId < 0 ? rand.nextInt(numConnectionsPerPeer) : partitionId % numConnectionsPerPeer;
+    TransportClient cachedClient = clientPool.clients[clientIndex];
+
+    if (cachedClient != null && cachedClient.isActive()) {
+      // Make sure that the channel will not timeout by updating the last use time of the
+      // handler. Then check that the client is still alive, in case it timed out before
+      // this code was able to update things.
+      TransportResponseHandler handler =
+          cachedClient.getChannel().pipeline().get(TransportResponseHandler.class);
+
+      if (cachedClient.isActive()) {
+        logger.trace(
+            "Returning cached connection to {}: {}", cachedClient.getSocketAddress(), cachedClient);
+        return cachedClient;
+      }
+    }
+
+    // If we reach here, we don't have an existing connection open. Let's create a new one.
+    // Multiple threads might race here to create new connections. Keep only one of them active.
+    final long preResolveHost = System.nanoTime();
+    final InetSocketAddress resolvedAddress = new InetSocketAddress(remoteHost, remotePort);
+    final long hostResolveTimeMs = (System.nanoTime() - preResolveHost) / 1000000;
+    if (hostResolveTimeMs > 2000) {
+      logger.warn("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    } else {
+      logger.trace("DNS resolution for {} took {} ms", resolvedAddress, hostResolveTimeMs);
+    }
+
+    synchronized (clientPool.locks[clientIndex]) {
+      cachedClient = clientPool.clients[clientIndex];
+
+      if (cachedClient != null) {
+        if (cachedClient.isActive()) {
+          logger.trace("Returning cached connection to {}: {}", resolvedAddress, cachedClient);
+          return cachedClient;
+        } else {
+          logger.info("Found inactive connection to {}, creating a new one.", resolvedAddress);
+        }
+      }
+      clientPool.clients[clientIndex] = internalCreateClient(resolvedAddress, decoder);

Review Comment:
   I'm trying  to create createClientIfAbsent function in ClientPool. like this :
   ``` 
   TransportClient createClientIfAbsent(
           int clientIndex
           , InetSocketAddress resolvedAddress
           , ChannelInboundHandlerAdapter decoder
           , BiFunction<InetSocketAddress,ChannelInboundHandlerAdapter,TransportClient> createClientFunction ){
        
           clients[clientIndex] = createClientFunction.apply(resolvedAddress, decoder);
           return clients[clientIndex];
         }
   } 
   ```
   but It seems not very graceful becuase of createClientFunction have two unrelated args.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@uniffle.apache.org
For additional commands, e-mail: issues-help@uniffle.apache.org