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


##########
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:
   Fixed in 94958fd3066. An unreachable BRPC probe no longer blocks FE 
management startup merely because the separate heartbeat endpoint is alive. The 
master heartbeat/journal acknowledgement and explicit FALSE registration 
responses still gate startup, and BE signature verification remains enforced. 
Added regression coverage for unreachable workers and both remaining barriers.



##########
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:
   Fixed in 94958fd3066. FE pings use a separate bounded pool and share a 100ms 
early publication budget before BE/broker dispatch. Late replies are retained 
and journaled. Saturated FE submissions are admitted after worker dispatch 
using the existing bounded backpressure, preserving every peer and parallel 
slow pings. Full-round and real one/two-worker queue tests cover these cases; 
mutations dropping peers or serializing slow pings fail the new assertions.



##########
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:
   Fixed in 94958fd3066. Both signer constructors cache the immutable Base64 
public key, so signing and publication reuse the same encoded identity. Added 
reuse coverage for RPC and scanner signatures. Mutable JCA objects remain per 
request; the optional ThreadLocal optimization is deferred because no profiling 
evidence was collected for it.



##########
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:
   Fixed in 94958fd3066. Unknown remote identities now share a five-second 
per-client negative cache with coalesced loads. Failed metadata calls are not 
cached, and known identities remain available even if later legacy replies omit 
the field. Deterministic expiry/concurrency/failure tests pass; the native 
lifecycle regression also verifies upgrade discovery on the same client without 
restarting 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: [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