github-actions[bot] commented on code in PR #62880:
URL: https://github.com/apache/doris/pull/62880#discussion_r3147790407


##########
fe/be-java-extensions/max-compute-connector/src/main/java/org/apache/doris/maxcompute/MaxComputeFeClient.java:
##########
@@ -0,0 +1,270 @@
+// 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.doris.maxcompute;
+
+import org.apache.doris.thrift.FrontendService;
+import org.apache.doris.thrift.TMaxComputeBlockIdRequest;
+import org.apache.doris.thrift.TMaxComputeBlockIdResult;
+import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TStatus;
+import org.apache.doris.thrift.TStatusCode;
+
+import org.apache.log4j.Logger;
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.layered.TFramedTransport;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * FE thrift client used by MaxCompute writer runtime code in BE's embedded 
JVM.
+ */
+class MaxComputeFeClient {
+    static final String FE_HOST = "fe_host";
+    static final String FE_PORT = "fe_port";
+    static final String FE_RPC_TIMEOUT_MS = "fe_rpc_timeout_ms";
+    static final String FE_THRIFT_SERVER_TYPE = "fe_thrift_server_type";
+
+    private static final Logger LOG = 
Logger.getLogger(MaxComputeFeClient.class);
+    private static final int FETCH_BLOCK_ID_MAX_RETRY_TIMES = 3;
+    private static final long FETCH_BLOCK_ID_RETRY_SLEEP_MS = 10L;
+    private static final long FETCH_BLOCK_ID_LENGTH = 1L;
+    private static final int DEFAULT_FE_RPC_TIMEOUT_MS = 60000;
+    private static final String THREADED_SELECTOR = "THREADED_SELECTOR";
+    private static final String THREAD_POOL = "THREAD_POOL";
+
+    private final int rpcTimeoutMs;
+    private final String thriftServerType;
+    private final RpcExecutor rpcExecutor;
+    private final long retrySleepMs;
+    private TNetworkAddress masterAddress;
+
+    static MaxComputeFeClient create(Map<String, String> params) {
+        String host = requireParam(params, FE_HOST);
+        int port = Integer.parseInt(requireParam(params, FE_PORT));
+        int timeoutMs = Integer.parseInt(params.getOrDefault(FE_RPC_TIMEOUT_MS,
+                String.valueOf(DEFAULT_FE_RPC_TIMEOUT_MS)));
+        String serverType = params.getOrDefault(FE_THRIFT_SERVER_TYPE, 
THREAD_POOL);
+        return new MaxComputeFeClient(new TNetworkAddress(host, port), 
timeoutMs, serverType);
+    }
+
+    MaxComputeFeClient(TNetworkAddress masterAddress, int rpcTimeoutMs, String 
thriftServerType) {
+        this(masterAddress, rpcTimeoutMs, thriftServerType, new RpcExecutor() {
+            @Override
+            public <T> T call(TNetworkAddress address, int timeoutMs, boolean 
useFramedTransport,
+                    FeCall<T> call) throws Exception {
+                return callFe(address, timeoutMs, useFramedTransport, call);
+            }
+        }, FETCH_BLOCK_ID_RETRY_SLEEP_MS);
+    }
+
+    MaxComputeFeClient(TNetworkAddress masterAddress, int rpcTimeoutMs, String 
thriftServerType,
+            RpcExecutor rpcExecutor, long retrySleepMs) {
+        this.masterAddress = copyAddress(Objects.requireNonNull(masterAddress, 
"masterAddress"));
+        this.rpcTimeoutMs = rpcTimeoutMs;
+        this.thriftServerType = thriftServerType == null ? THREAD_POOL : 
thriftServerType;
+        this.rpcExecutor = Objects.requireNonNull(rpcExecutor, "rpcExecutor");
+        this.retrySleepMs = retrySleepMs;
+    }
+
+    long requestBlockId(long txnId, String writeSessionId) throws IOException {
+        if (txnId <= 0) {
+            throw new IOException("invalid MaxCompute txn_id for block_id 
allocation: " + txnId);
+        }
+        if (writeSessionId == null || writeSessionId.isEmpty()) {
+            throw new IOException("empty MaxCompute write_session_id for 
block_id allocation");
+        }
+
+        TMaxComputeBlockIdRequest request = buildBlockIdRequest(txnId, 
writeSessionId);
+        return callWithMasterRedirect(
+                "allocate MaxCompute block_id",
+                client -> client.getMaxComputeBlockIdRange(request),
+                (result, requestAddress, retryTimes) ->
+                        handleBlockIdResult(result, requestAddress, 
retryTimes, txnId, writeSessionId));
+    }
+
+    private <T, R> R callWithMasterRedirect(String operation, FeCall<T> call, 
ResponseHandler<T, R> handler)
+            throws IOException {
+        validateAddress(masterAddress);
+
+        Exception lastException = null;
+        for (int retryTimes = 0; retryTimes < FETCH_BLOCK_ID_MAX_RETRY_TIMES; 
retryTimes++) {
+            TNetworkAddress requestAddress = copyAddress(masterAddress);
+            T result;
+            try {
+                result = rpcExecutor.call(requestAddress, rpcTimeoutMs, 
useFramedTransport(), call);
+            } catch (Exception e) {
+                lastException = e;
+                LOG.warn("Failed to " + operation + ", rpc failure, 
retry_time="
+                        + retryTimes + ", fe=" + 
formatAddress(requestAddress), e);
+                sleepBeforeRetry();
+                continue;
+            }
+
+            try {
+                return handler.handle(result, requestAddress, retryTimes);
+            } catch (NotMasterException e) {
+                masterAddress = copyAddress(e.masterAddress);
+                lastException = e;
+                sleepBeforeRetry();
+            }
+        }
+
+        throw new IOException("failed to " + operation + " from FE", 
lastException);
+    }
+
+    private long handleBlockIdResult(TMaxComputeBlockIdResult result, 
TNetworkAddress requestAddress, int retryTimes,
+            long txnId, String writeSessionId) throws IOException, 
NotMasterException {
+        if (result == null || !result.isSetStatus()) {
+            throw new IOException("failed to allocate MaxCompute block_id from 
FE, missing status in response, "
+                    + "txn_id=" + txnId + ", write_session_id=" + 
writeSessionId);
+        }
+
+        TStatus status = result.getStatus();
+        TStatusCode code = status.getStatusCode();
+        if (code == null) {
+            throw new IOException("failed to allocate MaxCompute block_id from 
FE, missing status code, "
+                    + "txn_id=" + txnId + ", write_session_id=" + 
writeSessionId);
+        }
+        if (code == TStatusCode.NOT_MASTER) {
+            if (!result.isSetMasterAddress()) {
+                throw new IOException("failed to allocate MaxCompute block_id 
from FE, missing master address "
+                        + "in NOT_MASTER response, txn_id=" + txnId + ", 
write_session_id=" + writeSessionId);
+            }
+            LOG.warn("Failed to allocate MaxCompute block_id, requested 
non-master FE@"
+                    + formatAddress(requestAddress) + ", switch to FE@" + 
formatAddress(result.getMasterAddress())
+                    + ", retry_time=" + retryTimes + ", txn_id=" + txnId
+                    + ", write_session_id=" + writeSessionId);
+            throw new NotMasterException(result.getMasterAddress());
+        }
+
+        if (code != TStatusCode.OK) {
+            throw new IOException("failed to allocate MaxCompute block_id from 
FE, status="
+                    + statusErrorMessage(status) + ", txn_id=" + txnId
+                    + ", write_session_id=" + writeSessionId);
+        }
+
+        if (!result.isSetStart()) {
+            throw new IOException("failed to allocate MaxCompute block_id from 
FE, missing start in response, "
+                    + "txn_id=" + txnId + ", write_session_id=" + 
writeSessionId);
+        }
+        if (!result.isSetLength() || result.getLength() != 
FETCH_BLOCK_ID_LENGTH) {
+            throw new IOException("failed to allocate MaxCompute block_id from 
FE, expected length=1 but got "
+                    + result.getLength() + ", txn_id=" + txnId + ", 
write_session_id=" + writeSessionId);
+        }
+
+        LOG.info("Allocated MaxCompute block_id from FE@" + 
formatAddress(requestAddress)
+                + ", txn_id=" + txnId + ", write_session_id=" + writeSessionId
+                + ", block_id=" + result.getStart());
+        return result.getStart();
+    }
+
+    private static TMaxComputeBlockIdRequest buildBlockIdRequest(long txnId, 
String writeSessionId) {
+        TMaxComputeBlockIdRequest request = new TMaxComputeBlockIdRequest();
+        request.setTxnId(txnId);
+        request.setWriteSessionId(writeSessionId);
+        request.setLength(FETCH_BLOCK_ID_LENGTH);
+        return request;
+    }
+
+    private boolean useFramedTransport() {
+        return THREADED_SELECTOR.equalsIgnoreCase(thriftServerType);
+    }
+
+    private void sleepBeforeRetry() throws IOException {
+        try {
+            Thread.sleep(retrySleepMs);
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new IOException("interrupted while retrying MaxCompute 
block_id allocation", e);
+        }
+    }
+
+    private static <T> T callFe(TNetworkAddress address, int timeoutMs,
+            boolean useFramedTransport, FeCall<T> call) throws Exception {
+        TSocket socket = new TSocket(address.getHostname(), address.getPort(), 
timeoutMs);

Review Comment:
   Before this refactor, block-id allocation went through 
`ThriftRpcHelper::rpc<FrontendServiceClient>()`, so repeated requests reused 
Doris' FE client cache. `callFe()` now creates and closes a brand-new 
`TSocket`/`TTransport` for every `requestBlockId()`. Since `requestBlockId()` 
runs on every writer rotation (`rotateCurrentBatchWriter()`), small block sizes 
or many partitions now turn into one TCP connection per block. That is a 
hot-path regression and increases FE socket churn. Please keep a reusable 
client/transport per `MaxComputeFeClient` (or another pooled helper) instead of 
reconnecting for every allocation.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to