924060929 commented on code in PR #71174:
URL: https://github.com/apache/doris/pull/71174#discussion_r4780831124


##########
fe/fe-core/src/main/java/org/apache/doris/system/HeartbeatMgr.java:
##########
@@ -192,6 +187,16 @@ protected void runAfterCatalogReady() {
             hbResponses.add(executor.submit(handler));
         }
 
+        HbPackage hbPackage = new HbPackage();
+        // Recovering BEs must receive newly learned FE authorities before 
becoming schedulable.
+        collectHeartbeatResponses(hbResponses, hbPackage);

Review Comment:
   [P2] Waiting for all FE heartbeat futures before dispatching BE/Broker 
heartbeats serializes the round: a single blackholed/unresponsive Follower or 
Observer will delay every BE heartbeat by a full Thrift timeout each round (and 
up to 2x when `TTransportException` falls back to `Config.rpc_port`). Consider 
bounding the wait or skipping known-dead FEs on the critical path so a slow FE 
does not stall cluster-wide BE heartbeats.



##########
fe/fe-core/src/main/java/org/apache/doris/rpc/FrontendRpcKeyRegistration.java:
##########
@@ -0,0 +1,113 @@
+// 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.rpc;
+
+import org.apache.doris.catalog.Env;
+import org.apache.doris.common.Config;
+import org.apache.doris.system.Backend;
+import org.apache.doris.system.Frontend;
+import org.apache.doris.thrift.TNetworkAddress;
+
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.BooleanSupplier;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+/** Keeps query listeners closed until heartbeat publication and worker key 
registration complete. */
+public final class FrontendRpcKeyRegistration {
+    private FrontendRpcKeyRegistration() {
+    }
+
+    public static void awaitPublication() throws IOException, 
InterruptedException {
+        String key = InternalRpcRequestSigner.getInstance().getPublicKey();
+        BackendServiceProxy proxy = BackendServiceProxy.getInstance();
+        // Zero is the uninitialized heartbeat position, so it cannot 
acknowledge a startup.
+        long journalFence = Math.max(1, 
Env.getCurrentEnv().getReplayedJournalId());
+        // Publication and recovering-worker registration can span two 
configured heartbeat rounds.
+        long timeoutMs = 120_000 + TimeUnit.SECONDS.toMillis(2L * 
Config.heartbeat_interval_second);
+        awaitPublication(() -> 
Env.getCurrentSystemInfo().getAllClusterBackendsNoException().values(),
+                backend -> proxy.isFrontendKeyRegistered(
+                        new TNetworkAddress(backend.getHost(), 
backend.getBrpcPort()), key),
+                () -> isHeartbeatPublished(journalFence), timeoutMs);
+    }
+
+    static boolean isHeartbeatPublished(long journalFence) {
+        Env env = Env.getCurrentEnv();
+        Frontend self = env.getFeByName(env.getNodeName());
+        // An older process's heartbeat is journaled after its reported replay 
position;
+        // it cannot acknowledge the later journal position replayed during 
this startup.
+        return self != null && self.getReplayedJournalId() >= journalFence;
+    }
+
+    static void awaitPublication(Supplier<Collection<Backend>> backends,
+            Function<Backend, ListenableFuture<Boolean>> probe, 
BooleanSupplier heartbeatPublished, long timeoutMs)
+            throws IOException, InterruptedException {
+        long deadline = System.nanoTime() + 
TimeUnit.MILLISECONDS.toNanos(timeoutMs);
+        while (true) {
+            // A new FE can miss this round's ping while all BEs are down. 
Wait for the master's
+            // replay-position acknowledgment so the next recovery heartbeat 
already knows this FE's key.
+            boolean complete = heartbeatPublished.getAsBoolean();
+            Map<Backend, ListenableFuture<Boolean>> pending = new 
LinkedHashMap<>();
+            try {
+                for (Backend backend : backends.get()) {
+                    // A newly registered BE has no BRPC endpoint until its 
first heartbeat.
+                    pending.put(backend, backend.getBrpcPort() > 0 ? 
probe.apply(backend)
+                            : Futures.immediateFuture(null));
+                }
+                // Issue probes together: dead workers must not add one 
network timeout each
+                // to startup. All calls use the existing gRPC executors and 
their own deadlines.
+                long roundDeadline = Math.min(deadline, System.nanoTime() + 
TimeUnit.SECONDS.toNanos(2));
+                for (Map.Entry<Backend, ListenableFuture<Boolean>> entry : 
pending.entrySet()) {
+                    Boolean registered;
+                    try {
+                        registered = entry.getValue().get(Math.max(0, 
roundDeadline - System.nanoTime()),
+                                TimeUnit.NANOSECONDS);
+                    } catch (TimeoutException e) {
+                        registered = null;
+                    } catch (ExecutionException e) {
+                        throw new IOException("Cannot check backend 
registration of the FE signing key", e.getCause());
+                    }
+                    // Reachable workers need the key even before their alive 
heartbeat is replayed.
+                    // Unreachable dead workers cannot receive a query and 
must not block recovery.
+                    if (Boolean.FALSE.equals(registered) || (registered == 
null && entry.getKey().isAlive())) {

Review Comment:
   [P2] A single BE with a healthy heartbeat port (so `isAlive()` remains 
`true`) but an unreachable/stalled BRPC port causes `isFrontendKeyRegistered` 
to return `null` on every round, blocking `DorisFE.start()` until 
`awaitPublication()` times out and exits the process (`System.exit(-1)`). In a 
single-FE or full-FE-restart scenario, this prevents operators from even 
connecting to MySQL/HTTP ports to drop/decommission the bad BE. Consider 
distinguishing explicit `Boolean.FALSE` from unreachable `null`, or logging an 
error and proceeding after timeout rather than crashing FE startup.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/doris/FeServiceClient.java:
##########
@@ -246,16 +247,31 @@ private <T> T masterCallWithRetry(ThriftCall<T> call, 
String errorMsg, int timeo
         throw new RuntimeException(errorMsg + ":" + lastMessage, 
lastException);
     }
 
+    public int getClusterId() {
+        Integer destination = clusterId;
+        if (destination == null) {
+            listBackends();

Review Comment:
   [P2] Against an older remote Doris cluster that omits `cluster_id`, 
`clusterId` stays `null`. While `CoordinatorContext` memoizes this per query, 
every new query still triggers a `listBackends()` Thrift RPC to the remote FE. 
Consider a short cooldown/TTL for unknown `clusterId` refreshes so high-QPS 
queries against legacy remote clusters do not flood `getBackendMeta` while 
still discovering upgrades promptly.



##########
fe/fe-core/src/main/java/org/apache/doris/rpc/InternalRpcRequestSigner.java:
##########
@@ -0,0 +1,232 @@
+// 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.rpc;
+
+import org.apache.doris.common.Config;
+
+import com.google.protobuf.CodedOutputStream;
+import com.google.protobuf.MessageLite;
+import io.grpc.Metadata;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.security.DigestOutputStream;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
+import java.security.Signature;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
+import java.util.Set;
+
+/** Signs execution requests without giving a backend reusable FE credentials. 
*/
+public final class InternalRpcRequestSigner {
+    static final Metadata.Key<String> KEY = Metadata.Key.of("x-doris-rpc-key", 
Metadata.ASCII_STRING_MARSHALLER);
+    static final Metadata.Key<String> TIME = 
Metadata.Key.of("x-doris-rpc-time", Metadata.ASCII_STRING_MARSHALLER);
+    static final Metadata.Key<String> SIGNATURE = 
Metadata.Key.of("x-doris-rpc-signature",
+            Metadata.ASCII_STRING_MARSHALLER);
+    private final KeyPair keyPair;
+
+    private static class Holder {
+        private static final InternalRpcRequestSigner INSTANCE = 
loadFromMetadata();
+    }
+
+    public static InternalRpcRequestSigner getInstance() {
+        return Holder.INSTANCE;
+    }
+
+    InternalRpcRequestSigner() {
+        try {
+            keyPair = 
KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
+        } catch (GeneralSecurityException e) {
+            throw new IllegalStateException("Cannot initialize internal RPC 
request signing", e);
+        }
+    }
+
+    private InternalRpcRequestSigner(KeyPair pair) {
+        keyPair = pair;
+    }
+
+    private static InternalRpcRequestSigner loadFromMetadata() {
+        Path directory = Path.of(Config.meta_dir);
+        Path privateFile = directory.resolve("internal-rpc-signing-key");
+        Set<PosixFilePermission> privateMode = 
PosixFilePermissions.fromString("rw-------");
+        try {
+            Files.createDirectories(directory);
+            try (FileChannel lockChannel = 
FileChannel.open(directory.resolve("internal-rpc-signing-key.lock"),
+                    Set.of(StandardOpenOption.CREATE, 
StandardOpenOption.WRITE),
+                    PosixFilePermissions.asFileAttribute(privateMode));
+                    FileLock lock = lockChannel.lock()) {
+                KeyPair pair;
+                if (Files.exists(privateFile, LinkOption.NOFOLLOW_LINKS)) {
+                    // Replacing this identity on restart invalidates 
connector checkpoint plans
+                    // and explicit cross-cluster trust. Corrupt or exposed 
keys must fail closed.
+                    if (!Files.isRegularFile(privateFile, 
LinkOption.NOFOLLOW_LINKS)
+                            || Files.size(privateFile) > 1024
+                            || 
!privateMode.containsAll(Files.getPosixFilePermissions(privateFile))) {
+                        throw new IOException("Invalid signing key file or 
permissions");
+                    }
+                    byte[] encoded;
+                    try (InputStream file = Files.newInputStream(privateFile)) 
{
+                        encoded = file.readNBytes(1025);
+                    }
+                    if (encoded.length > 1024) {
+                        throw new IOException("Signing key file is too large");
+                    }
+                    try (DataInputStream input = new DataInputStream(new 
ByteArrayInputStream(encoded))) {
+                        if (input.readInt() != 1) {
+                            throw new IOException("Unsupported signing key 
format");
+                        }
+                        KeyFactory factory = KeyFactory.getInstance("Ed25519");
+                        pair = new KeyPair(factory.generatePublic(new 
X509EncodedKeySpec(
+                                Base64.getDecoder().decode(input.readUTF()))),
+                                factory.generatePrivate(new 
PKCS8EncodedKeySpec(
+                                        
Base64.getDecoder().decode(input.readUTF()))));
+                        if (input.available() != 0) {
+                            throw new IOException("Trailing signing key data");
+                        }
+                    }
+                } else {
+                    pair = 
KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
+                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+                    try (DataOutputStream output = new 
DataOutputStream(bytes)) {
+                        output.writeInt(1);
+                        
output.writeUTF(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
+                        
output.writeUTF(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
+                    }
+                    writeAtomically(directory, privateFile, 
bytes.toByteArray(), privateMode);
+                }
+                InternalRpcRequestSigner signer = new 
InternalRpcRequestSigner(pair);
+                // Check both halves before publishing an authority that could 
never verify its own requests.
+                Signature check = Signature.getInstance("Ed25519");
+                byte[] challenge = 
"doris-rpc-signing-key-check".getBytes(StandardCharsets.US_ASCII);
+                check.initSign(pair.getPrivate());
+                // SunEC does not verify an untouched Signature consistently; 
initialize its message explicitly.
+                check.update(challenge);
+                byte[] proof = check.sign();
+                check.initVerify(pair.getPublic());
+                check.update(challenge);
+                if (!check.verify(proof)) {
+                    throw new IOException("Signing key pair does not match");
+                }
+                writeAtomically(directory, 
directory.resolve("internal-rpc-signing-key.pub"),
+                        
signer.getPublicKey().getBytes(StandardCharsets.US_ASCII),
+                        PosixFilePermissions.fromString("rw-r--r--"));
+                return signer;
+            }
+        } catch (IOException | GeneralSecurityException | 
IllegalArgumentException e) {
+            throw new IllegalStateException("Cannot load internal RPC signing 
identity", e);
+        }
+    }
+
+    private static void writeAtomically(Path directory, Path destination, 
byte[] bytes,
+            Set<PosixFilePermission> permissions) throws IOException {
+        Path staged = Files.createTempFile(directory, "rpc-signing-", ".tmp",
+                PosixFilePermissions.asFileAttribute(permissions));
+        try {
+            Files.write(staged, bytes);
+            try (FileChannel channel = FileChannel.open(staged, 
StandardOpenOption.WRITE)) {
+                channel.force(true);
+            }
+            Files.move(staged, destination, StandardCopyOption.ATOMIC_MOVE, 
StandardCopyOption.REPLACE_EXISTING);
+            try (FileChannel parent = FileChannel.open(directory, 
StandardOpenOption.READ)) {
+                parent.force(true);
+            }
+        } finally {
+            Files.deleteIfExists(staged);
+        }
+    }
+
+    public String getPublicKey() {

Review Comment:
   [P2] `keyPair` is immutable, but `getPublicKey()` clones the encoded bytes 
and Base64-encodes them on every call — including every signed RPC (`signData`) 
on hot paths like `tablet_fetch_data` and fragment dispatch. Cache the 
Base64-encoded `publicKey` once in the constructor (and consider `ThreadLocal` 
reuse for `MessageDigest`/`Signature` if high-QPS point queries show JCA 
provider lookup overhead).



-- 
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