This is an automated email from the ASF dual-hosted git repository.
zaynt4606 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/celeborn.git
The following commit(s) were added to refs/heads/main by this push:
new 54679ba79d [CELEBORN-2468] Add module-specific transport bootstrap
configuration
54679ba79d is described below
commit 54679ba79d22b82a82de654f41c3e37d6d39af58
Author: Kalvin2077 <[email protected]>
AuthorDate: Thu Nov 5 00:51:54 2026 +0800
[CELEBORN-2468] Add module-specific transport bootstrap configuration
### What changes were proposed in this pull request?
Extract the configurable transport bootstrap support from #3857:
- Add module-specific client/server bootstrap settings in `CelebornConf`.
- Load, order, and close configured bootstraps in `TransportContext`.
- Integrate lifecycle management into RPC, Worker, and shuffle clients.
### Why are the changes needed?
Allow deployments to plug in custom transport authentication through
configuration without modifying Celeborn's core transport code.
### Does this PR resolve a correctness bug?
- [ ] Yes
### Does this PR introduce _any_ user-facing change?
- [x] Yes
Adds `celeborn.<module>.client.bootstrap.classes` and
`celeborn.<module>.server.bootstrap.classes`, both empty by default. Configured
bootstraps run before native registration/SASL bootstraps when enabled.
### How was this patch tested?
Focused validation covered bootstrap loading, ordering, cleanup, and
client/Worker lifecycle. 85 tests passed on JDK 8 and 9 passed with the JDK 17
runtime, using the Flink 1.18 profile. Spotless passed.
Closes #3894 from Kalvin2077/split/pr3857-1-transport-bootstraps.
Authored-by: Kalvin2077 <[email protected]>
Signed-off-by: zhengtao <[email protected]>
Co-Authored-By: Codex <[email protected]>
AI-Model: gpt-6
AI-Contributed/Feature: 0/430
AI-Contributed/UT: 0/708
---
.../flink/client/FlinkShuffleClientImpl.java | 35 ++-
.../plugin/flink/FlinkBootstrapSuiteJ.java | 125 ++++++++
.../apache/celeborn/client/ShuffleClientImpl.java | 28 +-
.../client/ShuffleClientBootstrapSuiteJ.java | 97 +++++++
...erverBootstrap.java => TransportBootstrap.java} | 23 +-
.../celeborn/common/network/TransportContext.java | 75 ++++-
.../network/client/TransportClientBootstrap.java | 8 +-
.../network/client/TransportClientFactory.java | 4 +-
.../common/network/server/TransportServer.java | 3 +-
.../network/server/TransportServerBootstrap.java | 9 +-
.../common/network/util/TransportConf.java | 9 +
.../org/apache/celeborn/common/CelebornConf.scala | 43 +++
.../celeborn/common/rpc/netty/NettyRpcEnv.scala | 30 +-
.../network/security/TransportBootstrapSuiteJ.java | 315 +++++++++++++++++++++
docs/configuration/network.md | 2 +
docs/security.md | 110 +++++++
.../celeborn/service/deploy/worker/Worker.scala | 45 ++-
.../deploy/worker/WorkerBootstrapSuite.scala | 171 +++++++++++
18 files changed, 1067 insertions(+), 65 deletions(-)
diff --git
a/client-flink/common/src/main/java/org/apache/celeborn/plugin/flink/client/FlinkShuffleClientImpl.java
b/client-flink/common/src/main/java/org/apache/celeborn/plugin/flink/client/FlinkShuffleClientImpl.java
index 81a5cef222..1ad93cdecb 100644
---
a/client-flink/common/src/main/java/org/apache/celeborn/plugin/flink/client/FlinkShuffleClientImpl.java
+++
b/client-flink/common/src/main/java/org/apache/celeborn/plugin/flink/client/FlinkShuffleClientImpl.java
@@ -84,7 +84,7 @@ public class FlinkShuffleClientImpl extends ShuffleClientImpl
{
JavaUtils.newConcurrentHashMap();
private long driverTimestamp;
- private final TransportContext context;
+ private TransportContext context;
/** The buffer size bytes in flink, default value is 32KB. */
private final int bufferSizeBytes;
@@ -163,6 +163,9 @@ public class FlinkShuffleClientImpl extends
ShuffleClientImpl {
if (flinkTransportClientFactory != null) {
flinkTransportClientFactory.close();
}
+ if (context != null) {
+ context.close();
+ }
if (readClientHandler != null) {
readClientHandler.close();
}
@@ -191,13 +194,12 @@ public class FlinkShuffleClientImpl extends
ShuffleClientImpl {
BATCH_HEADER_SIZE, BufferUtils.HEADER_LENGTH_PREFIX));
}
this.bufferSizeBytes = bufferSizeBytes;
- String module = TransportModuleConstants.DATA_MODULE;
- TransportConf dataTransportConf =
- Utils.fromCelebornConf(conf, module, conf.networkIoThreads(module));
- this.context =
- new TransportContext(
- dataTransportConf, readClientHandler,
conf.clientCloseIdleConnections());
- this.setupLifecycleManagerRef(driverHost, port);
+ try {
+ this.setupLifecycleManagerRef(driverHost, port);
+ } catch (RuntimeException | Error e) {
+ super.shutdown();
+ throw e;
+ }
this.driverTimestamp = driverTimestamp;
this.openStreamThreadPool =
ThreadUtils.newDaemonCachedThreadPool(
@@ -206,8 +208,21 @@ public class FlinkShuffleClientImpl extends
ShuffleClientImpl {
private void initializeTransportClientFactory() {
if (null == flinkTransportClientFactory) {
- flinkTransportClientFactory =
- new FlinkTransportClientFactory(context, createBootstraps(),
bufferSizeBytes);
+ String module = TransportModuleConstants.DATA_MODULE;
+ TransportConf dataTransportConf =
+ Utils.fromCelebornConf(conf, module, conf.networkIoThreads(module));
+ TransportContext newContext =
+ new TransportContext(
+ dataTransportConf, readClientHandler,
conf.clientCloseIdleConnections());
+ try {
+ FlinkTransportClientFactory factory =
+ new FlinkTransportClientFactory(newContext, createBootstraps(),
bufferSizeBytes);
+ context = newContext;
+ flinkTransportClientFactory = factory;
+ } catch (RuntimeException | Error e) {
+ newContext.close();
+ throw e;
+ }
}
}
diff --git
a/client-flink/common/src/test/java/org/apache/celeborn/plugin/flink/FlinkBootstrapSuiteJ.java
b/client-flink/common/src/test/java/org/apache/celeborn/plugin/flink/FlinkBootstrapSuiteJ.java
new file mode 100644
index 0000000000..5eab264ec3
--- /dev/null
+++
b/client-flink/common/src/test/java/org/apache/celeborn/plugin/flink/FlinkBootstrapSuiteJ.java
@@ -0,0 +1,125 @@
+/*
+ * 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.celeborn.plugin.flink;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import org.apache.celeborn.common.CelebornConf;
+import org.apache.celeborn.common.network.client.TransportClient;
+import org.apache.celeborn.common.network.client.TransportClientBootstrap;
+import org.apache.celeborn.common.network.util.TransportConf;
+import org.apache.celeborn.common.rpc.RpcEndpointRef;
+import org.apache.celeborn.plugin.flink.client.FlinkShuffleClientImpl;
+
+public class FlinkBootstrapSuiteJ {
+ @Before
+ public void resetCounts() {
+ CountingBootstrap.created.set(0);
+ CountingBootstrap.closed.set(0);
+ }
+
+ @Test
+ public void shutdownClosesBothDataContextsExactlyOnce() {
+ FlinkShuffleClientImpl client = new TestClient(configuration(false));
+ try {
+ client.getDataClientFactory();
+ assertEquals(2, CountingBootstrap.created.get());
+ } finally {
+ client.shutdown();
+ client.shutdown();
+ }
+ assertEquals(2, CountingBootstrap.closed.get());
+ }
+
+ @Test
+ public void
readContextWaitsForLifecycleManagerAndRecoversFromInitializationFailure() {
+ AtomicInteger calls = new AtomicInteger();
+ FlinkShuffleClientImpl client =
+ new TestClient(configuration(true)) {
+ @Override
+ protected List<TransportClientBootstrap> createBootstraps() {
+ // The first call initializes push; the second initializes Flink
read.
+ if (calls.incrementAndGet() == 2) {
+ throw new IllegalStateException("Application registration is
unavailable");
+ }
+ return Collections.emptyList();
+ }
+ };
+ try {
+ assertEquals(0, CountingBootstrap.created.get());
+ RpcEndpointRef endpoint = mock(RpcEndpointRef.class);
+ assertThrows(IllegalStateException.class, () ->
client.setupLifecycleManagerRef(endpoint));
+ assertEquals(CountingBootstrap.closed.get() + 1,
CountingBootstrap.created.get());
+ client.setupLifecycleManagerRef(endpoint);
+ assertNotNull(client.getDataClientFactory());
+ assertEquals(CountingBootstrap.closed.get() + 2,
CountingBootstrap.created.get());
+ } finally {
+ client.shutdown();
+ }
+ assertEquals(CountingBootstrap.created.get(),
CountingBootstrap.closed.get());
+ }
+
+ private static CelebornConf configuration(boolean authenticated) {
+ return new CelebornConf(false)
+ .set("celeborn.auth.enabled", Boolean.toString(authenticated))
+ .set("celeborn.internal.port.enabled", "true")
+ .set("celeborn.data.client.bootstrap.classes",
CountingBootstrap.class.getName())
+ .set("celeborn.data.io.clientThreads", "1")
+ .set("celeborn.rpc_app_client.io.clientThreads", "1")
+ .set("celeborn.rpc_app_client.dispatcher.threads", "1");
+ }
+
+ private static class TestClient extends FlinkShuffleClientImpl {
+ TestClient(CelebornConf conf) {
+ super("application", "localhost", 1232, 1L, conf, null, 64);
+ }
+
+ @Override
+ public void setupLifecycleManagerRef(String host, int port) {}
+
+ @Override
+ protected List<TransportClientBootstrap> createBootstraps() {
+ return Collections.emptyList();
+ }
+ }
+
+ public static class CountingBootstrap implements TransportClientBootstrap {
+ static final AtomicInteger created = new AtomicInteger();
+ static final AtomicInteger closed = new AtomicInteger();
+
+ public CountingBootstrap(TransportConf conf) {
+ created.incrementAndGet();
+ }
+
+ @Override
+ public void doBootstrap(TransportClient client) {}
+
+ @Override
+ public void close() {
+ closed.incrementAndGet();
+ }
+ }
+}
diff --git
a/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
b/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
index 6b99c5c82b..0a6048a0cd 100644
--- a/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
+++ b/client/src/main/java/org/apache/celeborn/client/ShuffleClientImpl.java
@@ -234,9 +234,14 @@ public class ShuffleClientImpl extends ShuffleClient {
Role.CLIENT(),
scala.None$.empty());
- String module = TransportModuleConstants.DATA_MODULE;
- dataTransportConf = Utils.fromCelebornConf(conf, module,
conf.networkIoThreads(module));
- initDataClientFactoryIfNeeded();
+ try {
+ String module = TransportModuleConstants.DATA_MODULE;
+ dataTransportConf = Utils.fromCelebornConf(conf, module,
conf.networkIoThreads(module));
+ initDataClientFactoryIfNeeded();
+ } catch (RuntimeException | Error e) {
+ rpcEnv.shutdown();
+ throw e;
+ }
int pushDataRetryThreads = conf.clientPushRetryThreads();
pushDataRetryPool =
ThreadUtils.newDaemonThreadPoolScheduledExecutor(
@@ -279,19 +284,20 @@ public class ShuffleClientImpl extends ShuffleClient {
}
private void initDataClientFactoryIfNeeded() {
- if (dataClientFactory != null) {
+ if (dataClientFactory != null || (authEnabled && lifecycleManagerRef ==
null)) {
return;
}
- this.transportContext =
+ TransportContext context =
new TransportContext(
dataTransportConf, new BaseMessageHandler(),
conf.clientCloseIdleConnections());
- if (!authEnabled) {
+ try {
logger.info("Initializing data client factory for {}.", appUniqueId);
- dataClientFactory = transportContext.createClientFactory();
- } else if (lifecycleManagerRef != null) {
- logger.info("Initializing data client factory for secured {}.",
appUniqueId);
- List<TransportClientBootstrap> bootstraps = createBootstraps();
- dataClientFactory = transportContext.createClientFactory(bootstraps);
+ TransportClientFactory factory =
context.createClientFactory(createBootstraps());
+ transportContext = context;
+ dataClientFactory = factory;
+ } catch (RuntimeException | Error e) {
+ context.close();
+ throw e;
}
}
diff --git
a/client/src/test/java/org/apache/celeborn/client/ShuffleClientBootstrapSuiteJ.java
b/client/src/test/java/org/apache/celeborn/client/ShuffleClientBootstrapSuiteJ.java
new file mode 100644
index 0000000000..ce32f54dc7
--- /dev/null
+++
b/client/src/test/java/org/apache/celeborn/client/ShuffleClientBootstrapSuiteJ.java
@@ -0,0 +1,97 @@
+/*
+ * 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.celeborn.client;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Test;
+
+import org.apache.celeborn.common.CelebornConf;
+import org.apache.celeborn.common.network.client.TransportClient;
+import org.apache.celeborn.common.network.client.TransportClientBootstrap;
+import org.apache.celeborn.common.network.util.TransportConf;
+import org.apache.celeborn.common.rpc.RpcEndpointRef;
+
+public class ShuffleClientBootstrapSuiteJ {
+ @Test
+ public void dataBootstrapsAreLazyAndCleanedUpOnRetryAndShutdown() {
+ CountingBootstrap.created.set(0);
+ CountingBootstrap.closed.set(0);
+ AtomicInteger attempts = new AtomicInteger();
+ ShuffleClientImpl client =
+ new ShuffleClientImpl("application", configuration(), null) {
+ @Override
+ protected List<TransportClientBootstrap> createBootstraps() {
+ if (attempts.getAndIncrement() == 0) {
+ throw new IllegalStateException("Application registration is
unavailable");
+ }
+ return Collections.emptyList();
+ }
+ };
+ try {
+ assertNull(client.getDataClientFactory());
+ assertEquals(0, CountingBootstrap.created.get());
+ RpcEndpointRef endpoint = mock(RpcEndpointRef.class);
+ assertThrows(IllegalStateException.class, () ->
client.setupLifecycleManagerRef(endpoint));
+ assertNull(client.getDataClientFactory());
+ assertEquals(1, CountingBootstrap.created.get());
+ assertEquals(1, CountingBootstrap.closed.get());
+ client.setupLifecycleManagerRef(endpoint);
+ assertNotNull(client.getDataClientFactory());
+ client.setupLifecycleManagerRef(endpoint);
+ assertEquals(2, CountingBootstrap.created.get());
+ assertEquals(1, CountingBootstrap.closed.get());
+ } finally {
+ client.shutdown();
+ client.shutdown();
+ }
+ assertEquals(2, CountingBootstrap.closed.get());
+ }
+
+ private static CelebornConf configuration() {
+ return new CelebornConf(false)
+ .set("celeborn.auth.enabled", "true")
+ .set("celeborn.internal.port.enabled", "true")
+ .set("celeborn.data.client.bootstrap.classes",
CountingBootstrap.class.getName())
+ .set("celeborn.data.io.clientThreads", "1")
+ .set("celeborn.rpc_app_client.io.clientThreads", "1")
+ .set("celeborn.rpc_app_client.dispatcher.threads", "1");
+ }
+
+ public static class CountingBootstrap implements TransportClientBootstrap {
+ static final AtomicInteger created = new AtomicInteger();
+ static final AtomicInteger closed = new AtomicInteger();
+
+ public CountingBootstrap(TransportConf conf) {
+ created.incrementAndGet();
+ }
+
+ @Override
+ public void doBootstrap(TransportClient client) {}
+
+ @Override
+ public void close() {
+ closed.incrementAndGet();
+ }
+ }
+}
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
b/common/src/main/java/org/apache/celeborn/common/network/TransportBootstrap.java
similarity index 54%
copy from
common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
copy to
common/src/main/java/org/apache/celeborn/common/network/TransportBootstrap.java
index cc367a05f5..101b1410d5 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/TransportBootstrap.java
@@ -15,22 +15,15 @@
* limitations under the License.
*/
-package org.apache.celeborn.common.network.server;
+package org.apache.celeborn.common.network;
-import io.netty.channel.Channel;
-
-/**
- * A bootstrap which is executed on a TransportServer's client channel once a
client connects to the
- * server. This allows customizing the client channel to allow for things such
as SASL
- * authentication.
- */
-public interface TransportServerBootstrap {
+/** Shared lifecycle for client and server transport bootstraps. */
+public interface TransportBootstrap extends AutoCloseable {
/**
- * Customizes the channel to include new features, if needed.
- *
- * @param channel The connected channel opened by the client.
- * @param baseMessageHandler The RPC handler for the server.
- * @return The base message handler to use for the channel.
+ * Releases resources owned by a configured bootstrap. Configured instances
are shared across a
+ * transport context's connections and closed by that context after its
factories and servers.
+ * Caller-supplied instances remain the caller's responsibility.
*/
- BaseMessageHandler doBootstrap(Channel channel, BaseMessageHandler
baseMessageHandler);
+ @Override
+ default void close() throws Exception {}
}
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/TransportContext.java
b/common/src/main/java/org/apache/celeborn/common/network/TransportContext.java
index 7145bdbaac..d7e2412182 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/TransportContext.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/TransportContext.java
@@ -18,8 +18,10 @@
package org.apache.celeborn.common.network;
import java.io.Closeable;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
@@ -47,6 +49,7 @@ import org.apache.celeborn.common.network.util.FrameDecoder;
import org.apache.celeborn.common.network.util.NettyLogger;
import org.apache.celeborn.common.network.util.TransportConf;
import org.apache.celeborn.common.network.util.TransportFrameDecoder;
+import org.apache.celeborn.reflect.DynConstructors;
/**
* Contains the context to create a {@link TransportServer}, {@link
TransportClientFactory}, and to
@@ -73,6 +76,9 @@ public class TransportContext implements Closeable {
@Nullable private final SSLFactory sslFactory;
private final boolean enableHeartbeat;
private final AbstractSource source;
+ private final List<TransportClientBootstrap> configuredClientBootstraps =
new ArrayList<>();
+ private final List<TransportServerBootstrap> configuredServerBootstraps =
new ArrayList<>();
+ private final AtomicBoolean closed = new AtomicBoolean();
private static final MessageEncoder ENCODER = MessageEncoder.INSTANCE;
private static final SslMessageEncoder SSL_ENCODER =
SslMessageEncoder.INSTANCE;
@@ -87,10 +93,21 @@ public class TransportContext implements Closeable {
this.conf = conf;
this.msgHandler = msgHandler;
this.closeIdleConnections = closeIdleConnections;
- this.sslFactory = SSLFactory.createSslFactory(conf);
this.channelsLimiter = channelsLimiter;
this.enableHeartbeat = enableHeartbeat;
this.source = source;
+ try {
+ for (String className : conf.clientBootstrapClasses()) {
+ configuredClientBootstraps.add(loadBootstrap(className,
TransportClientBootstrap.class));
+ }
+ for (String className : conf.serverBootstrapClasses()) {
+ configuredServerBootstraps.add(loadBootstrap(className,
TransportServerBootstrap.class));
+ }
+ this.sslFactory = SSLFactory.createSslFactory(conf);
+ } catch (RuntimeException | LinkageError e) {
+ closeBootstraps();
+ throw e;
+ }
if (null != this.sslFactory) {
logger.info(
@@ -137,6 +154,26 @@ public class TransportContext implements Closeable {
return new TransportClientFactory(this, bootstraps);
}
+ /** Also used by direct factory constructors, including engine-specific
subclasses. */
+ public List<TransportClientBootstrap> resolveClientBootstraps(
+ List<TransportClientBootstrap> bootstraps) {
+ List<TransportClientBootstrap> resolved = new
ArrayList<>(configuredClientBootstraps);
+ resolved.addAll(bootstraps);
+ return resolved;
+ }
+
+ /** Configured handlers receive requests in configuration order, before
caller handlers. */
+ public List<TransportServerBootstrap> resolveServerBootstraps(
+ List<TransportServerBootstrap> bootstraps) {
+ List<TransportServerBootstrap> resolved = new ArrayList<>(bootstraps);
+ // Each wrapper receives requests before its delegate, so install
configured wrappers in
+ // reverse.
+ for (int i = configuredServerBootstraps.size() - 1; i >= 0; i--) {
+ resolved.add(configuredServerBootstraps.get(i));
+ }
+ return resolved;
+ }
+
public TransportClientFactory createClientFactory() {
return createClientFactory(Collections.emptyList());
}
@@ -280,10 +317,42 @@ public class TransportContext implements Closeable {
return source;
}
+ private <T> T loadBootstrap(String className, Class<T> expected) {
+ try {
+ Class<? extends T> implementation =
+ Class.forName(className, false,
Thread.currentThread().getContextClassLoader())
+ .asSubclass(expected);
+ return expected.cast(
+ DynConstructors.builder(expected)
+ .impl(implementation, TransportConf.class)
+ .impl(implementation)
+ .buildChecked()
+ .newInstance(conf));
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Unable to load transport bootstrap "
+ className, e);
+ }
+ }
+
+ private void closeBootstraps() {
+ List<AutoCloseable> bootstraps = new
ArrayList<>(configuredClientBootstraps);
+ bootstraps.addAll(configuredServerBootstraps);
+ Collections.reverse(bootstraps);
+ for (AutoCloseable bootstrap : bootstraps) {
+ try {
+ bootstrap.close();
+ } catch (Exception e) {
+ logger.warn("Error closing transport bootstrap {}.",
bootstrap.getClass().getName(), e);
+ }
+ }
+ }
+
@Override
public void close() {
- if (sslFactory != null) {
- sslFactory.destroy();
+ if (closed.compareAndSet(false, true)) {
+ closeBootstraps();
+ if (sslFactory != null) {
+ sslFactory.destroy();
+ }
}
}
}
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientBootstrap.java
b/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientBootstrap.java
index 66bb83b378..49143916c8 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientBootstrap.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientBootstrap.java
@@ -17,6 +17,8 @@
package org.apache.celeborn.common.network.client;
+import org.apache.celeborn.common.network.TransportBootstrap;
+
/**
* A bootstrap which is executed on a TransportClient before it is returned to
the user. This
* enables an initial exchange of information (e.g., SASL authentication
tokens) on a once-per-
@@ -26,9 +28,11 @@ package org.apache.celeborn.common.network.client;
* reasonable to perform an expensive bootstrapping operation, as they often
share a lifespan with
* the JVM itself.
*/
-public interface TransportClientBootstrap {
+public interface TransportClientBootstrap extends TransportBootstrap {
/**
- * Performs the bootstrapping operation, throwing an exception on failure.
+ * Performs the bootstrapping operation, throwing an exception on failure.
Authentication must
+ * finish before this method returns. Configured instances are shared across
connections and must
+ * support concurrent calls.
*
* @param client the transport client to bootstrap
* @throws RuntimeException
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientFactory.java
b/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientFactory.java
index f96ddceb96..f3965d412a 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientFactory.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/client/TransportClientFactory.java
@@ -31,7 +31,6 @@ import java.util.function.Supplier;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
-import com.google.common.collect.Lists;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
@@ -105,7 +104,8 @@ public class TransportClientFactory implements Closeable {
TransportContext context, List<TransportClientBootstrap>
clientBootstraps) {
this.context = Preconditions.checkNotNull(context);
TransportConf conf = context.getConf();
- this.clientBootstraps =
Lists.newArrayList(Preconditions.checkNotNull(clientBootstraps));
+ this.clientBootstraps =
+
context.resolveClientBootstraps(Preconditions.checkNotNull(clientBootstraps));
this.connectionPool = JavaUtils.newConcurrentHashMap();
this.numConnectionsPerPeer = conf.numConnectionsPerPeer();
this.connectTimeoutMs = conf.connectTimeoutMs();
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/server/TransportServer.java
b/common/src/main/java/org/apache/celeborn/common/network/server/TransportServer.java
index a8e7e752b6..93fd326cf0 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/server/TransportServer.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/server/TransportServer.java
@@ -23,7 +23,6 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
@@ -63,7 +62,7 @@ public class TransportServer implements Closeable {
this.conf = context.getConf();
this.source = context.getSource();
this.appMessageHandler =
Preconditions.checkNotNull(context.getMsgHandler());
- this.bootstraps =
Lists.newArrayList(Preconditions.checkNotNull(bootstraps));
+ this.bootstraps =
context.resolveServerBootstraps(Preconditions.checkNotNull(bootstraps));
boolean shouldClose = true;
try {
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
b/common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
index cc367a05f5..5bcfe28133 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/server/TransportServerBootstrap.java
@@ -19,14 +19,19 @@ package org.apache.celeborn.common.network.server;
import io.netty.channel.Channel;
+import org.apache.celeborn.common.network.TransportBootstrap;
+
/**
* A bootstrap which is executed on a TransportServer's client channel once a
client connects to the
* server. This allows customizing the client channel to allow for things such
as SASL
* authentication.
*/
-public interface TransportServerBootstrap {
+public interface TransportServerBootstrap extends TransportBootstrap {
/**
- * Customizes the channel to include new features, if needed.
+ * Customizes the channel to include new features, if needed. Configured
instances are shared
+ * across connections; create a separate handler for each connection.
Authentication handlers must
+ * establish identity before forwarding business requests and preserve the
delegate's registration
+ * checks and channel lifecycle callbacks.
*
* @param channel The connected channel opened by the client.
* @param baseMessageHandler The RPC handler for the server.
diff --git
a/common/src/main/java/org/apache/celeborn/common/network/util/TransportConf.java
b/common/src/main/java/org/apache/celeborn/common/network/util/TransportConf.java
index ce37ae9788..dded15a049 100644
---
a/common/src/main/java/org/apache/celeborn/common/network/util/TransportConf.java
+++
b/common/src/main/java/org/apache/celeborn/common/network/util/TransportConf.java
@@ -18,6 +18,7 @@
package org.apache.celeborn.common.network.util;
import java.io.File;
+import java.util.List;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.kqueue.KQueue;
@@ -173,6 +174,14 @@ public class TransportConf {
return celebornConf.authEnabled();
}
+ public List<String> clientBootstrapClasses() {
+ return celebornConf.clientBootstrapClasses(module);
+ }
+
+ public List<String> serverBootstrapClasses() {
+ return celebornConf.serverBootstrapClasses(module);
+ }
+
/** Whether Secure (SSL/TLS) wire communication is enabled. */
public boolean sslEnabled() {
return celebornConf.sslEnabled(module);
diff --git
a/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
b/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
index f66e4f251f..1fc382d479 100644
--- a/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
+++ b/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
@@ -548,6 +548,18 @@ class CelebornConf(loadDefaults: Boolean) extends
Cloneable with Logging with Se
CelebornConf.networkIoMode())
}
+ def clientBootstrapClasses(module: String): java.util.List[String] = {
+ val entry = TRANSPORT_CLIENT_BOOTSTRAP_CLASSES
+ entry.valueConverter(
+ get(entry.key.replace("<module>", module),
entry.defaultValueString)).asJava
+ }
+
+ def serverBootstrapClasses(module: String): java.util.List[String] = {
+ val entry = TRANSPORT_SERVER_BOOTSTRAP_CLASSES
+ entry.valueConverter(
+ get(entry.key.replace("<module>", module),
entry.defaultValueString)).asJava
+ }
+
def networkIoPreferDirectBufs(module: String): Boolean = {
getTransportConfBoolean(module, NETWORK_IO_PREFER_DIRECT_BUFS)
}
@@ -6850,6 +6862,37 @@ object CelebornConf extends Logging {
.timeConf(TimeUnit.MILLISECONDS)
.createWithDefaultString("30s")
+ val TRANSPORT_CLIENT_BOOTSTRAP_CLASSES: ConfigEntry[Seq[String]] =
+ buildConf("celeborn.<module>.client.bootstrap.classes")
+ .categories("network", "security")
+ .version("1.0.0")
+ .doc("Ordered TransportClientBootstrap classes with a public
TransportConf or no-argument " +
+ "constructor. Run before the caller's bootstraps, including native
SASL when enabled. " +
+ "Applies only to the exact transport module; does not inherit parent
module settings. " +
+ "Instances are owned and closed by the transport context. " +
+ "When composing with native authentication, leave
`TransportClient.clientId` to the native " +
+ "layer or set the same Celeborn application ID. Keep independent
plugin identities in " +
+ "per-connection state.")
+ .stringConf
+ .toSequence
+ .createWithDefault(Seq.empty)
+
+ val TRANSPORT_SERVER_BOOTSTRAP_CLASSES: ConfigEntry[Seq[String]] =
+ buildConf("celeborn.<module>.server.bootstrap.classes")
+ .categories("network", "security")
+ .version("1.0.0")
+ .doc("Ordered TransportServerBootstrap classes with a public
TransportConf or no-argument " +
+ "constructor. Receive requests in configuration order before the
caller's handlers, " +
+ "including native SASL when enabled. Applies only to the exact
transport module; " +
+ "does not inherit parent module settings. " +
+ "Instances are owned and closed by the transport context. " +
+ "When composing with native authentication, leave
`TransportClient.clientId` to the native " +
+ "layer or set the same Celeborn application ID. Keep independent
plugin identities in " +
+ "per-connection state.")
+ .stringConf
+ .toSequence
+ .createWithDefault(Seq.empty)
+
val INTERNAL_PORT_ENABLED: ConfigEntry[Boolean] =
buildConf("celeborn.internal.port.enabled")
.categories("master", "worker")
diff --git
a/common/src/main/scala/org/apache/celeborn/common/rpc/netty/NettyRpcEnv.scala
b/common/src/main/scala/org/apache/celeborn/common/rpc/netty/NettyRpcEnv.scala
index ed002d3b0b..a194f29cf6 100644
---
a/common/src/main/scala/org/apache/celeborn/common/rpc/netty/NettyRpcEnv.scala
+++
b/common/src/main/scala/org/apache/celeborn/common/rpc/netty/NettyRpcEnv.scala
@@ -63,12 +63,19 @@ class NettyRpcEnv(
// Visible for tests
private[netty] val transportContext =
- new TransportContext(
- transportConf,
- new NettyRpcHandler(dispatcher, this),
- false,
- false,
- config.source.orNull)
+ try {
+ new TransportContext(
+ transportConf,
+ new NettyRpcHandler(dispatcher, this),
+ false,
+ false,
+ config.source.orNull)
+ } catch {
+ case e: Throwable if NonFatal(e) || e.isInstanceOf[LinkageError] =>
+ Utils.tryLogNonFatalError { dispatcher.stop() }
+ Utils.tryLogNonFatalError { _rpcSource.destroy() }
+ throw e
+ }
private def createClientBootstraps():
java.util.List[TransportClientBootstrap] = {
val bootstrapOpt = securityContext.flatMap(_.clientSaslContext.map {
clientSaslContext =>
@@ -90,7 +97,16 @@ class NettyRpcEnv(
bootstrapOpt.toList.asJava
}
- val clientFactory =
transportContext.createClientFactory(createClientBootstraps())
+ val clientFactory =
+ try {
+ transportContext.createClientFactory(createClientBootstraps())
+ } catch {
+ case e: Throwable if NonFatal(e) || e.isInstanceOf[LinkageError] =>
+ Utils.tryLogNonFatalError { transportContext.close() }
+ Utils.tryLogNonFatalError { dispatcher.stop() }
+ Utils.tryLogNonFatalError { _rpcSource.destroy() }
+ throw e
+ }
private val timeoutScheduler =
ThreadUtils.newDaemonSingleThreadScheduledExecutor("celeborn-netty-rpc-env-timeout-checker")
diff --git
a/common/src/test/java/org/apache/celeborn/common/network/security/TransportBootstrapSuiteJ.java
b/common/src/test/java/org/apache/celeborn/common/network/security/TransportBootstrapSuiteJ.java
new file mode 100644
index 0000000000..f0a7a47692
--- /dev/null
+++
b/common/src/test/java/org/apache/celeborn/common/network/security/TransportBootstrapSuiteJ.java
@@ -0,0 +1,315 @@
+/*
+ * 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.celeborn.common.network.security;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import com.google.common.base.Throwables;
+import io.netty.channel.Channel;
+import org.junit.Test;
+
+import org.apache.celeborn.common.CelebornConf;
+import org.apache.celeborn.common.network.TransportContext;
+import org.apache.celeborn.common.network.client.RpcResponseCallback;
+import org.apache.celeborn.common.network.client.TransportClient;
+import org.apache.celeborn.common.network.client.TransportClientBootstrap;
+import org.apache.celeborn.common.network.client.TransportClientFactory;
+import org.apache.celeborn.common.network.protocol.RequestMessage;
+import org.apache.celeborn.common.network.sasl.SaslClientBootstrap;
+import org.apache.celeborn.common.network.sasl.SaslCredentials;
+import org.apache.celeborn.common.network.sasl.SaslRpcHandler;
+import org.apache.celeborn.common.network.sasl.SaslServerBootstrap;
+import org.apache.celeborn.common.network.sasl.SecretRegistryImpl;
+import org.apache.celeborn.common.network.server.BaseMessageHandler;
+import org.apache.celeborn.common.network.server.TransportServer;
+import org.apache.celeborn.common.network.server.TransportServerBootstrap;
+import org.apache.celeborn.common.network.util.TransportConf;
+import org.apache.celeborn.common.util.JavaUtils;
+
+public class TransportBootstrapSuiteJ {
+ private static final String APP = "application";
+ private static final String SECRET = "application-secret";
+ private static final String NATIVE_SECRET = "native-secret";
+ private static final String CLIENT_CLASSES =
"celeborn.shuffle.client.bootstrap.classes";
+ private static final String SERVER_CLASSES =
"celeborn.shuffle.server.bootstrap.classes";
+
+ @Test
+ public void configuredBootstrapsComposeWithNativeSasl() throws Exception {
+ EchoHandler handler = new EchoHandler();
+ TransportConf conf =
+ transportConf(
+ configuration()
+ .set(CLIENT_CLASSES, ConfiguredSaslClient.class.getName())
+ .set(SERVER_CLASSES, ConfiguredSaslServer.class.getName()));
+ try (TransportContext serverContext = new TransportContext(conf, handler);
+ TransportContext clientContext = new TransportContext(conf, new
BaseMessageHandler());
+ TransportServer server =
+ new TransportServer(
+ serverContext,
+ "localhost",
+ 0,
+ Collections.singletonList(new SaslServerBootstrap(conf,
registry(NATIVE_SECRET))));
+ TransportClientFactory factory =
+ new TransportClientFactory(
+ clientContext,
+ Collections.singletonList(
+ new SaslClientBootstrap(conf, APP, new
SaslCredentials(APP, NATIVE_SECRET))));
+ TransportClient client = factory.createClient("localhost",
server.getPort())) {
+ assertEquals(APP, client.getClientId());
+ assertEquals(
+ APP,
JavaUtils.bytesToString(client.sendRpcSync(JavaUtils.stringToBytes(APP),
10000)));
+ assertEquals(
+ "Business handler must not receive either SASL handshake", 1,
handler.requests.get());
+ assertThrows(IllegalStateException.class, () ->
client.setClientId("other-application"));
+ IOException unauthorized =
+ assertThrows(
+ IOException.class,
+ () ->
client.sendRpcSync(JavaUtils.stringToBytes("other-application"), 10000));
+ assertTrue(
+ Throwables.getRootCause(unauthorized)
+ .getMessage()
+ .contains("not authorized for application"));
+ assertEquals(APP, client.getClientId());
+ }
+ }
+
+ @Test
+ public void invalidConfiguredCredentialsCloseConnectionBeforeNativeSasl()
throws Exception {
+ InvalidConfiguredSaslClient.client = null;
+ EchoHandler handler = spy(new EchoHandler());
+ AtomicReference<SaslRpcHandler> nativeHandler = new AtomicReference<>();
+ TransportConf conf =
+ transportConf(
+ configuration()
+ .set(CLIENT_CLASSES,
InvalidConfiguredSaslClient.class.getName())
+ .set(SERVER_CLASSES, ConfiguredSaslServer.class.getName()));
+ SaslClientBootstrap nativeClient =
+ spy(new SaslClientBootstrap(conf, APP, new SaslCredentials(APP,
NATIVE_SECRET)));
+ SaslServerBootstrap nativeServer = new SaslServerBootstrap(conf,
registry(NATIVE_SECRET));
+ try (TransportContext serverContext = new TransportContext(conf, handler);
+ TransportContext clientContext = new TransportContext(conf, new
BaseMessageHandler());
+ TransportServer server =
+ serverContext.createServer(
+ "localhost",
+ 0,
+ Collections.singletonList(
+ (channel, delegate) -> {
+ SaslRpcHandler saslHandler =
+ spy((SaslRpcHandler)
nativeServer.doBootstrap(channel, delegate));
+ nativeHandler.set(saslHandler);
+ return saslHandler;
+ }));
+ TransportClientFactory factory =
+
clientContext.createClientFactory(Collections.singletonList(nativeClient))) {
+ RuntimeException failure =
+ assertThrows(
+ RuntimeException.class, () -> factory.createClient("localhost",
server.getPort()));
+
assertTrue(Throwables.getRootCause(failure).getMessage().contains("Mismatched
response"));
+ assertNotNull(InvalidConfiguredSaslClient.client);
+ assertFalse(InvalidConfiguredSaslClient.client.getChannel().isOpen());
+ verify(nativeClient, never()).doBootstrap(any(TransportClient.class));
+ verify(handler,
timeout(10000)).channelInactive(any(TransportClient.class));
+ assertNotNull(nativeHandler.get());
+ verify(nativeHandler.get(), never()).doAuthChallenge(any(), any(),
any());
+ assertEquals(0, handler.requests.get());
+ }
+ }
+
+ @Test
+ public void configurationIsExactModuleAndSupportsBothConstructorForms() {
+ CountingBootstrap.created.set(0);
+ NoArgBootstrap.created.set(0);
+ CelebornConf conf =
+ configuration()
+ .set("celeborn.rpc.client.bootstrap.classes",
String.class.getName())
+ .set(
+ CLIENT_CLASSES,
+ CountingBootstrap.class.getName() + "," +
NoArgBootstrap.class.getName());
+ try (TransportContext ignored = new TransportContext(transportConf(conf),
new EchoHandler());
+ TransportContext internal =
+ new TransportContext(new TransportConf("rpc_service", conf), new
EchoHandler())) {
+ assertEquals(1, CountingBootstrap.created.get());
+ assertEquals("shuffle", CountingBootstrap.module);
+ assertEquals(1, NoArgBootstrap.created.get());
+ }
+ conf.set(CLIENT_CLASSES, "");
+ try (TransportContext ignored = new TransportContext(transportConf(conf),
new EchoHandler())) {
+ assertEquals(1, CountingBootstrap.created.get());
+ }
+ }
+
+ @Test
+ public void contextOwnsConfiguredInstancesNotFactoriesOrServers() {
+ CountingBootstrap.created.set(0);
+ CountingBootstrap.closed.set(0);
+ NoArgBootstrap.created.set(0);
+ String bootstrapClasses =
+ CountingBootstrap.class.getName() + "," +
NoArgBootstrap.class.getName();
+ TransportConf conf =
+ transportConf(
+ configuration()
+ .set(CLIENT_CLASSES, bootstrapClasses)
+ .set(SERVER_CLASSES, bootstrapClasses));
+ try (TransportContext context = new TransportContext(conf, new
EchoHandler())) {
+ assertEquals(2, CountingBootstrap.created.get());
+ assertEquals(2, NoArgBootstrap.created.get());
+ try (TransportClientFactory first = context.createClientFactory();
+ TransportClientFactory second = context.createClientFactory();
+ TransportServer server = context.createServer("localhost", 0)) {
+ assertEquals(2, CountingBootstrap.created.get());
+ }
+ assertEquals(0, CountingBootstrap.closed.get());
+ context.close();
+ }
+ assertEquals(2, CountingBootstrap.closed.get());
+ }
+
+ @Test
+ public void invalidBootstrapClosesPreviouslyCreatedInstances() {
+ for (Class<?> invalid : new Class<?>[] {String.class,
FailingBootstrap.class}) {
+ CountingBootstrap.closed.set(0);
+ TransportConf conf =
+ transportConf(
+ configuration()
+ .set(CLIENT_CLASSES, CountingBootstrap.class.getName())
+ .set(SERVER_CLASSES, invalid.getName()));
+ assertThrows(
+ IllegalArgumentException.class, () -> new TransportContext(conf, new
EchoHandler()));
+ assertEquals(1, CountingBootstrap.closed.get());
+ }
+ }
+
+ private static CelebornConf configuration() {
+ return new CelebornConf(false)
+ .set("celeborn.shuffle.io.maxRetries", "1")
+ .set("celeborn.shuffle.io.numConnectionsPerPeer", "1")
+ .set("celeborn.shuffle.io.clientThreads", "1")
+ .set("celeborn.shuffle.io.serverThreads", "1");
+ }
+
+ private static TransportConf transportConf(CelebornConf conf) {
+ return new TransportConf("shuffle", conf);
+ }
+
+ private static SecretRegistryImpl registry(String secret) {
+ SecretRegistryImpl registry = new SecretRegistryImpl();
+ registry.register(APP, secret);
+ return registry;
+ }
+
+ private static class EchoHandler extends BaseMessageHandler {
+ final AtomicInteger requests = new AtomicInteger();
+
+ @Override
+ public boolean checkRegistered() {
+ return true;
+ }
+
+ @Override
+ public void receive(
+ TransportClient client, RequestMessage message, RpcResponseCallback
callback) {
+ requests.incrementAndGet();
+ try {
+ checkAuth(client,
JavaUtils.bytesToString(message.body().nioByteBuffer()));
+ callback.onSuccess(JavaUtils.stringToBytes(client.getClientId()));
+ } catch (IOException e) {
+ callback.onFailure(e);
+ }
+ }
+ }
+
+ public static class ConfiguredSaslClient extends SaslClientBootstrap {
+ public ConfiguredSaslClient(TransportConf conf) {
+ super(conf, APP, new SaslCredentials(APP, SECRET));
+ }
+ }
+
+ public static class ConfiguredSaslServer extends SaslServerBootstrap {
+ public ConfiguredSaslServer(TransportConf conf) {
+ super(conf, registry(SECRET));
+ }
+ }
+
+ public static class InvalidConfiguredSaslClient extends SaslClientBootstrap {
+ static TransportClient client;
+
+ public InvalidConfiguredSaslClient(TransportConf conf) {
+ super(conf, APP, new SaslCredentials(APP, "invalid-" + SECRET));
+ }
+
+ @Override
+ public void doBootstrap(TransportClient client) {
+ InvalidConfiguredSaslClient.client = client;
+ super.doBootstrap(client);
+ }
+ }
+
+ public static class CountingBootstrap
+ implements TransportClientBootstrap, TransportServerBootstrap {
+ static final AtomicInteger created = new AtomicInteger();
+ static final AtomicInteger closed = new AtomicInteger();
+ static String module;
+
+ public CountingBootstrap(TransportConf conf) {
+ created.incrementAndGet();
+ module = conf.getModuleName();
+ }
+
+ @Override
+ public void doBootstrap(TransportClient client) {}
+
+ @Override
+ public BaseMessageHandler doBootstrap(Channel channel, BaseMessageHandler
handler) {
+ return handler;
+ }
+
+ @Override
+ public void close() {
+ closed.incrementAndGet();
+ }
+ }
+
+ public static class NoArgBootstrap implements TransportClientBootstrap,
TransportServerBootstrap {
+ static final AtomicInteger created = new AtomicInteger();
+
+ public NoArgBootstrap() {
+ created.incrementAndGet();
+ }
+
+ @Override
+ public void doBootstrap(TransportClient client) {}
+
+ @Override
+ public BaseMessageHandler doBootstrap(Channel channel, BaseMessageHandler
handler) {
+ return handler;
+ }
+ }
+
+ public static class FailingBootstrap extends CountingBootstrap {
+ public FailingBootstrap(TransportConf conf) {
+ super(conf);
+ throw new IllegalStateException("Cannot initialize bootstrap");
+ }
+ }
+}
diff --git a/docs/configuration/network.md b/docs/configuration/network.md
index 636bca1bcb..432dcb9ef5 100644
--- a/docs/configuration/network.md
+++ b/docs/configuration/network.md
@@ -19,6 +19,7 @@ license: |
<!--begin-include-->
| Key | Default | isDynamic | Description | Since | Deprecated |
| --- | ------- | --------- | ----------- | ----- | ---------- |
+| celeborn.<module>.client.bootstrap.classes | | false | Ordered
TransportClientBootstrap classes with a public TransportConf or no-argument
constructor. Run before the caller's bootstraps, including native SASL when
enabled. Applies only to the exact transport module; does not inherit parent
module settings. Instances are owned and closed by the transport context. When
composing with native authentication, leave `TransportClient.clientId` to the
native layer or set the same Celeb [...]
| celeborn.<module>.fetch.timeoutCheck.interval | 5s | false | Interval
for checking fetch data timeout. It only support setting <module> to `data`
since it works for shuffle client fetch data. | 0.3.0 | |
| celeborn.<module>.fetch.timeoutCheck.threads | 4 | false | Threads num
for checking fetch data timeout. It only support setting <module> to `data`
since it works for shuffle client fetch data. | 0.3.0 | |
| celeborn.<module>.heartbeat.interval | 60s | false | The heartbeat
interval between worker and client. If setting <module> to `push`, it works for
worker receiving push data. If setting <module> to `fetch`, it works for worker
fetch server. If you are using the "celeborn.client.heartbeat.interval", please
use the new configs for each module according to your needs or replace it with
"celeborn.push.heartbeat.interval" and "celeborn.fetch.heartbeat.interval". |
0.3.0 | celeborn.cl [...]
@@ -40,6 +41,7 @@ license: |
| celeborn.<module>.io.threads | 8 | false | Default number of threads
used in the server and client thread pool. This specifies thread configuration
based on JVM's allocation of cores. If setting <module> to `data`, it works for
shuffle client push and fetch data. | | |
| celeborn.<module>.push.timeoutCheck.interval | 5s | false | Interval
for checking push data timeout. If setting <module> to `data`, it works for
shuffle client push data. If setting <module> to `push`, it works for Flink
shuffle client push data. If setting <module> to `replicate`, it works for
replicate client of worker replicating data to peer worker. | 0.3.0 | |
| celeborn.<module>.push.timeoutCheck.threads | 4 | false | Threads num
for checking push data timeout. If setting <module> to `data`, it works for
shuffle client push data. If setting <module> to `push`, it works for Flink
shuffle client push data. If setting <module> to `replicate`, it works for
replicate client of worker replicating data to peer worker. | 0.3.0 | |
+| celeborn.<module>.server.bootstrap.classes | | false | Ordered
TransportServerBootstrap classes with a public TransportConf or no-argument
constructor. Receive requests in configuration order before the caller's
handlers, including native SASL when enabled. Applies only to the exact
transport module; does not inherit parent module settings. Instances are owned
and closed by the transport context. When composing with native authentication,
leave `TransportClient.clientId` to the [...]
| celeborn.<role>.rpc.dispatcher.threads | <value of
celeborn.rpc.dispatcher.threads> | false | Threads number of message
dispatcher event loop for roles | | |
| celeborn.io.maxDefaultNettyThreads | 64 | false | Max default netty threads
| 0.3.2 | |
| celeborn.network.advertise.preferIpAddress | <value of
celeborn.network.bind.preferIpAddress> | false | When `true`, prefer to use
IP address, otherwise FQDN for advertise address. | 0.6.0 | |
diff --git a/docs/security.md b/docs/security.md
index 588ee985e3..7e7f8f8dd3 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -145,3 +145,113 @@ celeborn.master.ha.node.3.ratis.port 9872
spark.celeborn.auth.enabled true
```
+## Configurable transport bootstraps
+
+Transport bootstraps let a plugin perform an additional handshake when a
connection opens.
+Implement `org.apache.celeborn.common.network.client.TransportClientBootstrap`
on the initiating
+side and `org.apache.celeborn.common.network.server.TransportServerBootstrap`
on the accepting side.
+Celeborn's existing request authorization checks still apply after the
handshake.
+
+### Configuration and deployment
+
+Compile the plugin against the matching Celeborn transport API and put its
classes and dependencies
+on the classpath of every participating process. Celeborn uses the thread
context class loader.
+Each class must implement the interface for its configured side and expose a
public constructor
+taking `TransportConf`, or a public no-argument constructor. The
`TransportConf` constructor takes
+precedence when both exist.
+
+Shaded Spark and Flink clients relocate dependencies such as Netty, including
types in bootstrap
+method signatures. Build the plugin for the distribution that loads it, using
matching relocated
+types for a shaded client. Keep Celeborn API classes out of the plugin JAR so
the host supplies them.
+
+Configure comma-separated class names with these properties. Both default to
an empty list:
+
+| Property | Meaning |
+| --- | --- |
+| `celeborn.<module>.client.bootstrap.classes` | Client bootstraps, in
handshake execution order. |
+| `celeborn.<module>.server.bootstrap.classes` | Server bootstraps, in
handshake execution order. |
+
+Bootstrap lists apply only to the exact module name and do not inherit parent
module settings.
+Configure matching lists on both sides of each participating transport:
+
+| Transport | Initiating side | Accepting side |
+| --- | --- | --- |
+| LifecycleManager RPC to Master/Worker, with `celeborn.auth.enabled=false` |
`rpc_app_lifecyclemanager` client | `rpc_service` server |
+| LifecycleManager RPC to Master/Worker, with `celeborn.auth.enabled=true` |
`rpc_service` client | `rpc_service` server |
+| Service RPC between Master/Worker processes | `rpc_service` client |
`rpc_service` server |
+| Shuffle push | Application `data` client | Worker `push` server |
+| Shuffle fetch | Application `data` client | Worker `fetch` server |
+| Worker replication | Worker `replicate` client | Worker `replicate` server |
+| RPC within an application | The initiating process's `rpc_app_client` or
`rpc_app_lifecyclemanager` client | The receiving process's `rpc_app_client` or
`rpc_app_lifecyclemanager` server |
+
+Public and internal Master/Worker RPC listeners both use `rpc_service`. Their
bootstrap lists
+cannot be configured separately, so a plugin must support the peers using both
listeners.
+
+For example, a plugin protecting shuffle data connections could use these
settings.
+Replace the `com.example.security` placeholders with the installed plugin
class names:
+
+```properties
+# Application-side Celeborn configuration.
+celeborn.data.client.bootstrap.classes
com.example.security.TokenClientBootstrap
+
+# Worker-side Celeborn configuration.
+celeborn.push.server.bootstrap.classes
com.example.security.TokenServerBootstrap
+celeborn.fetch.server.bootstrap.classes
com.example.security.TokenServerBootstrap
+```
+
+When supplying Celeborn settings through Spark configuration, prefix the names
with `spark.`.
+Configure RPC and replication separately if those transports use the plugin.
+
+### Handshake order and handler obligations
+
+For client and server lists `A,B`, a connection completes A's handshake, then
B's. Configured client
+bootstraps run before caller-supplied bootstraps. Configured server wrappers
receive requests in
+configuration order, before caller-supplied handlers. Caller-supplied lists
retain their existing
+ordering behavior.
+
+Configured bootstraps run whether `celeborn.auth.enabled` is enabled or
disabled. When native
+authentication is enabled, configured handshakes precede Celeborn's
registration or SASL handshake
+on transports that use them. Each layer must finish its handshake before
forwarding requests to
+the next layer. TLS remains a separate transport setting.
+
+`TransportClient.clientId` is reserved for the Celeborn application ID used by
existing application
+authorization checks, including `BaseMessageHandler.checkAuth()`. A configured
bootstrap must leave
+this field to native registration/SASL or establish the same application
identity. Both layers can
+set the same application ID; setting it to an independent plugin principal
prevents later native
+authentication with a different application ID. `setClientId()` rejects
changing or clearing an
+assigned identity.
+
+Keep independent plugin principals and authentication-completion state in
per-connection handler
+fields or channel attributes, not in `clientId` or shared bootstrap fields. A
non-null `clientId`
+does not prove authentication succeeded: native SASL can assign it before
credential validation
+finishes. Each authentication layer must still gate requests on its own
completed handshake.
+
+The client bootstrap must finish authentication before `doBootstrap` returns
and throw on failure.
+A failed client handshake closes the connection and prevents it from being
returned or pooled.
+A server bootstrap must reject business requests until authentication
completes, including one-way
+and data requests. Its handler must preserve the delegate's registration
checks and lifecycle
+callbacks. If activation starts business traffic, defer `channelActive` until
authentication
+succeeds; continue forwarding `channelInactive` and `exceptionCaught`,
including failed handshakes.
+The plugin implements these server-side checks and callback rules.
+
+### Instance lifecycle
+
+Celeborn creates one instance per list entry and transport context, shared
across that context's
+connections. Configuring the same class on both sides creates separate
instances. Implementations
+must support concurrent connections and keep connection-specific state in
separate handlers.
+Clients can read refreshed credentials in `doBootstrap` for each new
connection; credential changes
+do not automatically reauthenticate existing connections.
+
+The transport context closes configured instances once, in reverse
construction order. Owners
+close factories and servers before their context. Channel shutdown is
asynchronous, so plugins
+must coordinate in-flight callbacks with resource cleanup. Caller-supplied
bootstrap instances
+remain the caller's responsibility.
+
+An invalid class, constructor failure, or class-initialization failure
prevents context creation
+and closes previously constructed instances. A constructor that fails must
release its own
+resources before throwing. If an instance's `close` throws an exception,
Celeborn logs it and
+continues closing the remaining instances.
+
+Validate successful and failed handshakes, reconnection, native SASL
composition, and shutdown
+against the actual client and service JARs used in the deployment, including
shaded clients.
+
diff --git
a/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Worker.scala
b/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Worker.scala
index 9a96bef46c..5f01924a80 100644
---
a/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Worker.scala
+++
b/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Worker.scala
@@ -24,6 +24,7 @@ import java.util.concurrent._
import java.util.concurrent.atomic.{AtomicBoolean, AtomicIntegerArray}
import scala.collection.JavaConverters._
+import scala.util.control.NonFatal
import com.google.common.annotations.VisibleForTesting
import io.netty.util.HashedWheelTimer
@@ -40,7 +41,7 @@ import
org.apache.celeborn.common.metrics.source.{JVMCPUSource, JVMSource, Resou
import org.apache.celeborn.common.network.{CelebornRackResolver,
TransportContext}
import org.apache.celeborn.common.network.protocol.TransportMessagesHelper
import org.apache.celeborn.common.network.sasl.SaslServerBootstrap
-import org.apache.celeborn.common.network.server.TransportServerBootstrap
+import org.apache.celeborn.common.network.server.{TransportServer,
TransportServerBootstrap}
import org.apache.celeborn.common.network.util.TransportConf
import org.apache.celeborn.common.protocol.{PartitionType,
PbRegisterWorkerResponse, PbWorkerLostResponse, RpcNameConstants,
TransportModuleConstants, WorkerEventType}
import org.apache.celeborn.common.protocol.PbWorkerStatus.State
@@ -227,9 +228,15 @@ private[celeborn] class Worker(
pushServerLimiter,
conf.workerPushHeartbeatEnabled,
workerSource)
- (
- transportContext,
- transportContext.createServer(conf.workerPushPort,
getServerBootstraps(transportConf)))
+ try {
+ (
+ transportContext,
+ transportContext.createServer(conf.workerPushPort,
getServerBootstraps(transportConf)))
+ } catch {
+ case e: Throwable if NonFatal(e) || e.isInstanceOf[LinkageError] =>
+ Utils.tryLogNonFatalError { transportContext.close() }
+ throw e
+ }
}
val replicateHandler = new PushDataHandler(workerSource)
@@ -248,10 +255,19 @@ private[celeborn] class Worker(
replicateLimiter,
false,
workerSource)
- (
- transportContext,
- transportContext.createServer(conf.workerReplicatePort),
- transportContext.createClientFactory())
+ var server: TransportServer = null
+ try {
+ server = transportContext.createServer(conf.workerReplicatePort)
+ val factory = transportContext.createClientFactory()
+ (transportContext, server, factory)
+ } catch {
+ case e: Throwable if NonFatal(e) || e.isInstanceOf[LinkageError] =>
+ if (server != null) {
+ Utils.tryLogNonFatalError { server.close() }
+ }
+ Utils.tryLogNonFatalError { transportContext.close() }
+ throw e
+ }
}
var fetchHandler: FetchHandler = _
@@ -269,9 +285,15 @@ private[celeborn] class Worker(
conf.workerFetchHeartbeatEnabled,
workerSource,
conf.metricsCollectCriticalEnabled)
- (
- transportContext,
- transportContext.createServer(conf.workerFetchPort,
getServerBootstraps(transportConf)))
+ try {
+ (
+ transportContext,
+ transportContext.createServer(conf.workerFetchPort,
getServerBootstraps(transportConf)))
+ } catch {
+ case e: Throwable if NonFatal(e) || e.isInstanceOf[LinkageError] =>
+ Utils.tryLogNonFatalError { transportContext.close() }
+ throw e
+ }
}
private val pushPort = pushServer.getPort
@@ -688,6 +710,7 @@ private[celeborn] class Worker(
replicateServer.shutdown(exitKind)
fetchServer.shutdown(exitKind)
pushServer.shutdown(exitKind)
+ replicateClientFactory.close()
replicateTransportContext.close()
fetchServerTransportContext.close()
pushServerTransportContext.close()
diff --git
a/worker/src/test/scala/org/apache/celeborn/service/deploy/worker/WorkerBootstrapSuite.scala
b/worker/src/test/scala/org/apache/celeborn/service/deploy/worker/WorkerBootstrapSuite.scala
new file mode 100644
index 0000000000..71743cc44e
--- /dev/null
+++
b/worker/src/test/scala/org/apache/celeborn/service/deploy/worker/WorkerBootstrapSuite.scala
@@ -0,0 +1,171 @@
+/*
+ * 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.celeborn.service.deploy.worker
+
+import java.lang.management.ManagementFactory
+import java.nio.charset.StandardCharsets
+import java.nio.file.{Files, Paths}
+import java.util.concurrent.{CopyOnWriteArrayList, TimeUnit}
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.collection.JavaConverters._
+import scala.util.control.NonFatal
+
+import io.netty.channel.Channel
+import org.scalatest.funsuite.AnyFunSuite
+
+import org.apache.celeborn.common.CelebornConf
+import org.apache.celeborn.common.network.TransportContext
+import org.apache.celeborn.common.network.client.{TransportClient,
TransportClientBootstrap}
+import org.apache.celeborn.common.network.server.{BaseMessageHandler,
TransportServerBootstrap}
+import org.apache.celeborn.common.network.util.TransportConf
+import org.apache.celeborn.common.util.{CelebornExitKind, JavaUtils}
+import org.apache.celeborn.service.deploy.worker.memory.MemoryManager
+
+class WorkerBootstrapSuite extends AnyFunSuite {
+ test("stop closes Worker bootstraps after the replication client factory") {
+ // Worker shutdown closes the global MemoryManager, which other discovered
suites may own.
+ val output = Files.createTempFile("celeborn-worker-bootstrap-", ".out")
+ val java = Paths.get(System.getProperty("java.home"), "bin",
"java").toString
+ val moduleOptions =
ManagementFactory.getRuntimeMXBean.getInputArguments.asScala
+ .filter(arg => arg.startsWith("--add-opens=") ||
arg.startsWith("--add-exports="))
+ val command = Seq(
+ java,
+ "-ea",
+ "-Xmx1g",
+ "-XX:MaxDirectMemorySize=256m",
+ "-XX:+IgnoreUnrecognizedVMOptions") ++ moduleOptions ++ Seq(
+ "-cp",
+ System.getProperty("java.class.path"),
+ "org.apache.celeborn.service.deploy.worker.WorkerBootstrapSuite")
+ val process = new ProcessBuilder(command: _*)
+ .redirectErrorStream(true).redirectOutput(output.toFile).start()
+ try {
+ val finished = process.waitFor(45, TimeUnit.SECONDS)
+ if (!finished) {
+ process.destroyForcibly()
+ process.waitFor(5, TimeUnit.SECONDS)
+ }
+ val details = new String(Files.readAllBytes(output),
StandardCharsets.UTF_8)
+ assert(finished, s"Worker bootstrap probe timed out: $details")
+ assert(process.exitValue() == 0, details)
+ } finally {
+ if (process.isAlive) process.destroyForcibly()
+ Files.deleteIfExists(output)
+ }
+ }
+}
+
+object WorkerBootstrapSuite {
+ val serverBootstraps = new CopyOnWriteArrayList[CountingServerBootstrap]()
+ val clientBootstraps = new CopyOnWriteArrayList[CountingClientBootstrap]()
+
+ def main(args: Array[String]): Unit = {
+ try {
+ verifyShutdown()
+ } catch {
+ case NonFatal(e) =>
+ e.printStackTrace()
+ System.exit(1)
+ }
+ System.exit(0)
+ }
+
+ private def verifyShutdown(): Unit = {
+ serverBootstraps.clear()
+ clientBootstraps.clear()
+ val storageDir = Files.createTempDirectory("worker-bootstrap-").toFile
+ val conf = new CelebornConf(false)
+ .set(CelebornConf.WORKER_STORAGE_DIRS.key, storageDir.getPath)
+ .set(CelebornConf.WORKER_DISK_MONITOR_CHECKLIST.key, "readwrite")
+ .set("celeborn.rpc_service.io.serverThreads", "1")
+ .set("celeborn.rpc_service.io.clientThreads", "1")
+ .set("celeborn.rpc_service.dispatcher.threads", "1")
+ .set("celeborn.replicate.client.bootstrap.classes",
classOf[CountingClientBootstrap].getName)
+ Seq("push", "fetch", "replicate").foreach { module =>
+ conf.set(
+ s"celeborn.$module.server.bootstrap.classes",
+ classOf[CountingServerBootstrap].getName)
+ conf.set(s"celeborn.worker.$module.io.threads", "1")
+ }
+ val peerConf = new
CelebornConf(false).set("celeborn.shuffle.io.serverThreads", "1")
+ val peerContext = new TransportContext(
+ new TransportConf("shuffle", peerConf),
+ new BaseMessageHandler())
+ val peerServer = peerContext.createServer("localhost", 0)
+ var worker: Worker = null
+ try {
+ worker = new Worker(conf, new WorkerArguments(Array("--host",
"localhost"), conf))
+ assert(serverBootstraps.size() == 3)
+ assert(serverBootstraps.asScala.map(_.module).toSet == Set("push",
"fetch", "replicate"))
+ assert(clientBootstraps.size() == 1)
+ val clientBootstrap = clientBootstraps.get(0)
+ assert(clientBootstrap.module == "replicate")
+ val client = worker.replicateClientFactory.createClient("localhost",
peerServer.getPort)
+ assert(client.isActive)
+
+ // The peer stays open so shutting down Worker's own servers cannot
close this connection.
+ worker.stop(CelebornExitKind.EXIT_IMMEDIATELY)
+ worker.stop(CelebornExitKind.EXIT_IMMEDIATELY)
+ assert(serverBootstraps.asScala.forall(_.closed.get() == 1))
+ assert(clientBootstrap.closed.get() == 1)
+ assert(
+ clientBootstrap.clientClosedBeforeBootstrap,
+ "The replication client must close before its configured bootstrap")
+ } finally {
+ if (worker != null) {
+ worker.rpcEnv.shutdown()
+ worker.stop(CelebornExitKind.EXIT_IMMEDIATELY)
+ worker.replicateClientFactory.close()
+ }
+ peerServer.close()
+ peerContext.close()
+ MemoryManager.reset()
+ JavaUtils.deleteRecursively(storageDir)
+ }
+ }
+ class CountingServerBootstrap(conf: TransportConf) extends
TransportServerBootstrap {
+ val module: String = conf.getModuleName
+ val closed = new AtomicInteger()
+ serverBootstraps.add(this)
+
+ override def doBootstrap(channel: Channel, handler: BaseMessageHandler):
BaseMessageHandler =
+ handler
+
+ override def close(): Unit = {
+ closed.incrementAndGet()
+ }
+ }
+
+ class CountingClientBootstrap(conf: TransportConf) extends
TransportClientBootstrap {
+ val module: String = conf.getModuleName
+ val closed = new AtomicInteger()
+ private var client: TransportClient = _
+ var clientClosedBeforeBootstrap = false
+ clientBootstraps.add(this)
+
+ override def doBootstrap(transportClient: TransportClient): Unit = {
+ client = transportClient
+ }
+
+ override def close(): Unit = {
+ clientClosedBeforeBootstrap = client != null && !client.isActive
+ closed.incrementAndGet()
+ }
+ }
+}