gaborgsomogyi commented on code in PR #30043:
URL: https://github.com/apache/flink/pull/30043#discussion_r4707076199
##########
flink-runtime/src/test/java/org/apache/flink/runtime/minicluster/MiniClusterITCase.java:
##########
@@ -69,6 +95,101 @@
/** Integration test cases for the {@link MiniCluster}. */
class MiniClusterITCase {
+ @Test
+ @Timeout(60)
+ void startObtainsDelegationTokensOnlyOnce() throws Exception {
+ final MockDelegationTokenProvider provider =
+ new MockDelegationTokenProvider(new MockTokenService());
+ final Map<Class<?>, Iterator<?>> plugins = new HashMap<>();
+ plugins.put(DelegationTokenProvider.class,
Collections.singletonList(provider).iterator());
+ plugins.put(
+ DelegationTokenReceiver.class,
+ Collections.singletonList(new
MockDelegationTokenReceiver()).iterator());
+ final Configuration config = new Configuration();
+ config.set(getBooleanConfigOption(CONFIG_PREFIX + ".throw.enabled"),
false);
+ final MiniClusterConfiguration cfg =
+ new MiniClusterConfiguration.Builder()
+ .withRandomPorts()
+ .setConfiguration(config)
+ .setPluginManager(new TestingPluginManager(plugins))
+ .build();
+
+ try (final MiniCluster miniCluster = new MiniCluster(cfg)) {
+ miniCluster.start();
+ // The job needs the ResourceManager, whose leader session must
not obtain tokens again.
+ miniCluster.executeJobBlocking(getSimpleJob(1));
+
+ assertThat(provider.obtainCalls()).isEqualTo(1);
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ void
closeAsyncShutsDownEverythingEvenIfTheDelegationTokenManagerFailsToStop()
+ throws Exception {
+ final MiniClusterWithManagerFailingToStop miniCluster =
+ new MiniClusterWithManagerFailingToStop();
+ miniCluster.start();
+
+ assertThat(miniCluster.closeAsync())
+ .as("termination of a mini cluster whose delegation token
manager fails to stop")
+ .failsWithin(Duration.ofSeconds(30))
+ .withThrowableOfType(ExecutionException.class)
+ .withCauseInstanceOf(IllegalStateException.class)
+ .withMessageContaining(STOP_FAILURE_MESSAGE);
+ assertThat(miniCluster.ioExecutor.isTerminated())
+ .as("io executor, the last service which a mini cluster shuts
down")
+ .isTrue();
+ }
+
+ @Test
+ @Timeout(60)
+ void startReportsItsFailureEvenIfTheDelegationTokenManagerFailsToStop() {
+ final IllegalStateException startFailure = new
IllegalStateException("HA services failed");
+ final MiniClusterWithManagerFailingToStop miniCluster =
+ new MiniClusterWithManagerFailingToStop() {
+ @Override
+ protected HighAvailabilityServices
createHighAvailabilityServices(
+ Configuration configuration, Executor executor) {
+ throw startFailure;
+ }
+ };
+
+ try {
+ assertThatThrownBy(miniCluster::start)
+ .isSameAs(startFailure)
+ .hasSuppressedException(new
IllegalStateException(STOP_FAILURE_MESSAGE));
+ } finally {
+ miniCluster.ioExecutor.shutdownNow();
Review Comment:
The leak is older than this PR. `MiniCluster#start()` calls `close()` on
failure, which does nothing while `running` is false, so every failed start
leaves the RPC services, the metric registry and the working directory behind.
Changed the test to release what it can reach. A fix in `start()` itself would
be its own ticket.
##########
flink-runtime/src/test/java/org/apache/flink/runtime/security/token/DelegationTokenHaTakeoverTest.java:
##########
@@ -0,0 +1,335 @@
+/*
+ * 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.flink.runtime.security.token;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.clusterframework.types.ResourceID;
+import org.apache.flink.runtime.dispatcher.runner.DefaultDispatcherRunner;
+import org.apache.flink.runtime.dispatcher.runner.DispatcherRunner;
+import
org.apache.flink.runtime.dispatcher.runner.SessionDispatcherLeaderProcessFactory;
+import
org.apache.flink.runtime.dispatcher.runner.TestingDispatcherGatewayService;
+import org.apache.flink.runtime.entrypoint.ClusterInformation;
+import org.apache.flink.runtime.heartbeat.TestingHeartbeatServices;
+import
org.apache.flink.runtime.highavailability.TestingHighAvailabilityServices;
+import
org.apache.flink.runtime.highavailability.nonha.embedded.EmbeddedJobResultStore;
+import org.apache.flink.runtime.jobmanager.TestingPersistenceComponentFactory;
+import org.apache.flink.runtime.jobmaster.JobResult;
+import org.apache.flink.runtime.leaderelection.LeaderInformation;
+import org.apache.flink.runtime.leaderelection.TestingLeaderElection;
+import org.apache.flink.runtime.metrics.util.TestingMetricRegistry;
+import org.apache.flink.runtime.resourcemanager.ResourceManager;
+import org.apache.flink.runtime.resourcemanager.ResourceManagerServiceImpl;
+import org.apache.flink.runtime.resourcemanager.TestingResourceManagerFactory;
+import org.apache.flink.runtime.rpc.RpcUtils;
+import org.apache.flink.runtime.rpc.TestingRpcService;
+import org.apache.flink.runtime.testutils.TestingApplicationResultStore;
+import org.apache.flink.runtime.testutils.TestingApplicationStore;
+import org.apache.flink.runtime.testutils.TestingExecutionPlanStore;
+import org.apache.flink.runtime.util.TestingFatalErrorHandler;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Tests the delegation tokens of JobManagers which take over the leadership
from each other. Every
+ * simulated JobManager process has the real {@link
ResourceManagerServiceImpl}, Dispatcher runner
+ * and {@link DefaultDelegationTokenManager}. The leader election, the token
service and the storage
+ * are fakes, and the storage fails like the real one when it is used with an
expired token.
+ */
+class DelegationTokenHaTakeoverTest {
+
+ private static final Duration TIMEOUT = Duration.ofSeconds(10);
+
+ private static TestingRpcService rpcService;
+
+ private final MockTokenService tokenService = new MockTokenService();
+
+ @BeforeAll
+ static void setupClass() {
+ rpcService = new TestingRpcService();
+ }
+
+ @AfterAll
+ static void teardownClass() throws Exception {
+ RpcUtils.terminateRpcService(rpcService);
+ }
+
+ @Test
+ void standbyKeepsTheTokensOfItsReceiverValid() throws Exception {
+ try (JobManagerProcess standby = new JobManagerProcess("standby")) {
+ standby.start();
+
+ tokenService.expireEverythingIssuedSoFar();
+ standby.tokens.obtainIsDue();
+
+
assertThat(standby.tokens.receiver().heldGeneration()).isEqualTo(2);
+
assertThat(tokenService.isValid(standby.tokens.receiver().heldGeneration())).isTrue();
+ }
+ }
+
+ @Test
+ void formerLeaderKeepsTheTokensOfItsReceiverValid() throws Exception {
+ try (JobManagerProcess jobManager = new JobManagerProcess("former
leader")) {
+ jobManager.start();
+ jobManager.becomeLeader();
+ jobManager.loseLeadership();
+
+ tokenService.expireEverythingIssuedSoFar();
+ jobManager.tokens.obtainIsDue();
+
+
assertThat(jobManager.tokens.receiver().heldGeneration()).isEqualTo(2);
+
assertThat(tokenService.isValid(jobManager.tokens.receiver().heldGeneration()))
+ .isTrue();
+ }
+ }
+
+ @Test
+ void standbyTakesOverWhileTheTokenServiceHangs() throws Exception {
+ try (JobManagerProcess leader = new JobManagerProcess("leader");
+ JobManagerProcess standby = new JobManagerProcess("standby")) {
+ leader.start();
+ standby.start();
+ leader.becomeLeader();
+
+ // The time passes and both obtain new tokens, then the leader
dies.
+ tokenService.expireEverythingIssuedSoFar();
+ leader.tokens.obtainIsDue();
+ standby.tokens.obtainIsDue();
+ leader.loseLeadership();
+
+ standby.hangTokenService();
Review Comment:
Added `standbyTakesOverWhileItsScheduledObtainHangs`, a takeover while a
scheduled obtain waits for the token service. The old test only shows that the
takeover does not call it.
##########
flink-runtime/src/test/java/org/apache/flink/runtime/security/token/DefaultDelegationTokenManagerLifecycleTest.java:
##########
@@ -0,0 +1,447 @@
+/*
+ * 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.flink.runtime.security.token;
+
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.ThrowingConsumer;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.flink.core.testutils.CommonTestUtils.waitUtil;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Tests for the two lifetimes of the {@link DefaultDelegationTokenManager}:
obtaining the tokens
+ * lasts as long as the process, a listener which distributes them lasts as
long as a leader
+ * session.
+ */
+class DefaultDelegationTokenManagerLifecycleTest {
+
+ private static final Duration TIMEOUT = Duration.ofSeconds(10);
+
+ /** The default obtain time ratio of 0.75 applied to the 60 seconds a
token lives. */
+ private static final long OBTAIN_DELAY_MILLIS = 45_000L;
+
+ private final MockTokenService tokenService =
+ new MockTokenService(
+ Clock.fixed(Instant.ofEpochMilli(1_000_000L),
ZoneOffset.UTC),
+ Duration.ofSeconds(60));
+ private final DelegationTokenManagerTestHarness harness =
+ new DelegationTokenManagerTestHarness(tokenService);
+ private final DefaultDelegationTokenManager manager = harness.manager();
+ private final MockDelegationTokenProvider provider = harness.provider();
+ private final MockDelegationTokenReceiver receiver = harness.receiver();
+
+ //
------------------------------------------------------------------------------------------
+ // Obtaining the tokens for the process
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void
startObtainsTokensForTheReceiversAndSchedulesTheNextObtainWithoutAnyListener()
+ throws Exception {
+ manager.start();
+
+ assertThat(provider.obtainCalls()).isEqualTo(1);
+ assertThat(receiver.receivedGenerations()).containsExactly(1);
+
assertThat(harness.pendingObtainDelaysMillis()).containsExactly(OBTAIN_DELAY_MILLIS);
+ }
+
+ @Test
+ void scheduledObtainsKeepUpdatingTheReceiversWithoutAnyListener() throws
Exception {
+ manager.start();
+
+ harness.obtainIsDue();
+ harness.obtainIsDue();
+
+ assertThat(provider.obtainCalls()).isEqualTo(3);
+ assertThat(receiver.receivedGenerations()).containsExactly(1, 2, 3);
+
assertThat(harness.pendingObtainDelaysMillis()).containsExactly(OBTAIN_DELAY_MILLIS);
+ }
+
+ @Test
+ void startWithoutRequiredTokensObtainsNothingAndSchedulesNothing() throws
Exception {
+ provider.setTokensRequired(false);
+
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ assertThat(provider.obtainCalls()).isZero();
+ assertThat(receiver.receivedGenerations()).isEmpty();
+ assertThat(listener.receivedGenerations()).isEmpty();
+ assertThat(harness.pendingObtainDelaysMillis()).isEmpty();
+ }
+
+ //
------------------------------------------------------------------------------------------
+ // The listener of a leader session
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void attachHandsOverTheLatestTokensWithoutContactingTheTokenService()
throws Exception {
+ manager.start();
+ harness.obtainIsDue();
+ final RecordingListener listener = new RecordingListener();
+
+ manager.attachListener(listener);
+
+ assertThat(listener.receivedGenerations()).containsExactly(2);
+ assertThat(provider.obtainCalls()).isEqualTo(2);
+ }
+
+ @Test
+ void obtainedTokensAreDeliveredToTheAttachedListenerInOrder() throws
Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ harness.obtainIsDue();
+ harness.obtainIsDue();
+
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2, 3);
+ }
+
+ @Test
+ void detachEndsTheDeliveryButTheObtainingContinues() throws Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ manager.detachListener(listener);
+ harness.obtainIsDue();
+
+ assertThat(listener.receivedGenerations()).containsExactly(1);
+ assertThat(receiver.receivedGenerations()).containsExactly(1, 2);
+ assertThat(provider.obtainCalls()).isEqualTo(2);
+
assertThat(harness.pendingObtainDelaysMillis()).containsExactly(OBTAIN_DELAY_MILLIS);
+ }
+
+ @Test
+ void nextLeaderSessionGetsTheTokensObtainedWhileNobodyWasAttached() throws
Exception {
+ manager.start();
+ final RecordingListener firstSession = new RecordingListener();
+ manager.attachListener(firstSession);
+ harness.obtainIsDue();
+ manager.detachListener(firstSession);
+ harness.obtainIsDue();
+
+ final RecordingListener secondSession = new RecordingListener();
+ manager.attachListener(secondSession);
+
+ assertThat(firstSession.receivedGenerations()).containsExactly(1, 2);
+ assertThat(secondSession.receivedGenerations()).containsExactly(3);
+ assertThat(provider.obtainCalls()).isEqualTo(3);
+ }
+
+ @Test
+ void detachOfAnEarlierListenerKeepsTheCurrentOne() throws Exception {
+ manager.start();
+ final RecordingListener earlierSession = new RecordingListener();
+ final RecordingListener currentSession = new RecordingListener();
+ manager.attachListener(earlierSession);
+ manager.attachListener(currentSession);
+
+ manager.detachListener(earlierSession);
+ harness.obtainIsDue();
+
+ assertThat(currentSession.receivedGenerations()).containsExactly(1, 2);
+ assertThat(earlierSession.receivedGenerations()).containsExactly(1);
+ }
+
+ @Test
+ void obtainDuringTheReplayOfAnAttachIsDeliveredAfterTheReplay() throws
Exception {
+ manager.start();
+ final CountDownLatch replayInListener = new CountDownLatch(1);
+ final CountDownLatch replayReleased = new CountDownLatch(1);
+ final RecordingListener listener =
+ new RecordingListener(
+ generation -> {
+ if (generation == 1) {
+ replayInListener.countDown();
+ replayReleased.await();
+ }
+ });
+ final ExecutorService attacher = Executors.newSingleThreadExecutor();
+ final ExecutorService obtainer = Executors.newSingleThreadExecutor();
+ try {
+ final Future<?> attach =
+ attacher.submit(
+ () -> {
+ manager.attachListener(listener);
+ return null;
+ });
+ assertThat(replayInListener.await(TIMEOUT.toMillis(),
TimeUnit.MILLISECONDS))
+ .as("the replay reached the listener")
+ .isTrue();
+
+ final Thread obtainerThread =
obtainer.submit(Thread::currentThread).get();
+ final Future<?> obtain = obtainer.submit(harness::obtainIsDue);
+ // The obtain must queue up behind the replay. A manager which
lets it pass delivers
+ // the new tokens first, which is what the assertion below detects.
+ waitUtil(
+ () -> obtain.isDone() || obtainerThread.getState() ==
Thread.State.BLOCKED,
+ TIMEOUT,
+ "The obtain neither completed nor waits for the replay");
+ replayReleased.countDown();
+ attach.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ obtain.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2);
+ } finally {
+ replayReleased.countDown();
+ attacher.shutdownNow();
+ obtainer.shutdownNow();
+ }
+ }
+
+ @Test
+ void detachWaitsForTheDeliveryInProgressAndNothingIsDeliveredAfterwards()
throws Exception {
+ manager.start();
+ final AtomicBoolean holdNextCallback = new AtomicBoolean();
+ final CountDownLatch obtainInListener = new CountDownLatch(1);
+ final CountDownLatch obtainReleased = new CountDownLatch(1);
+ final RecordingListener listener =
+ new RecordingListener(
+ generation -> {
+ if (holdNextCallback.compareAndSet(true, false)) {
+ obtainInListener.countDown();
+ obtainReleased.await();
+ }
+ });
+ manager.attachListener(listener);
+ // Only the callback of the obtain is held, a callback on the test
thread would hang it.
+ holdNextCallback.set(true);
+ final ExecutorService obtainer = Executors.newSingleThreadExecutor();
+ final ExecutorService detacher = Executors.newSingleThreadExecutor();
+ try {
+ final Future<?> obtain = obtainer.submit(harness::obtainIsDue);
+ assertThat(obtainInListener.await(TIMEOUT.toMillis(),
TimeUnit.MILLISECONDS))
+ .as("the obtain reached the listener")
+ .isTrue();
+
+ final Thread detacherThread =
detacher.submit(Thread::currentThread).get();
+ final Future<?> detach = detacher.submit(() ->
manager.detachListener(listener));
+ // The detach must wait for the callback in progress. A manager
which lets it pass
+ // returns here while the callback is still held.
+ waitUtil(
+ () -> detach.isDone() || detacherThread.getState() ==
Thread.State.BLOCKED,
+ TIMEOUT,
+ "The detach neither returned nor waits for the callback in
progress");
+ assertThat(detach).as("detach returned during a
callback").isNotDone();
+
+ obtainReleased.countDown();
+ obtain.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ detach.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2);
+
+ harness.obtainIsDue();
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2);
+ } finally {
+ obtainReleased.countDown();
+ obtainer.shutdownNow();
+ detacher.shutdownNow();
+ }
+ }
+
+ //
------------------------------------------------------------------------------------------
+ // Stop
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void stopCancelsTheScheduledObtainAndReleasesTheListener() throws
Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ manager.stop();
+ harness.obtainIsDue();
+
+ assertThat(harness.pendingObtainDelaysMillis()).isEmpty();
+ assertThat(provider.obtainCalls()).isEqualTo(1);
+ assertThat(listener.receivedGenerations()).containsExactly(1);
+ assertThatThrownBy(() -> manager.attachListener(new
RecordingListener()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("must be running to attach a listener")
+ .hasMessageContaining("STOPPED");
+ }
+
+ @Test
+ void stopDuringAnObtainNeitherReschedulesNorDeliversItsTokens() throws
Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+ provider.duringObtain(manager::stop);
+
+ harness.obtainIsDue();
+
+ assertThat(provider.obtainCalls()).isEqualTo(2);
+ assertThat(harness.pendingObtainDelaysMillis()).isEmpty();
+ assertThat(listener.receivedGenerations()).containsExactly(1);
+ assertThatThrownBy(manager::start)
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("can only be started once")
+ .hasMessageContaining("STOPPED");
+ }
+
+ //
------------------------------------------------------------------------------------------
+ // Failures
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void failureOfTheFirstObtainFailsTheStartAndStopsTheManager() {
+ provider.failWith(new IllegalStateException("token service
unreachable"));
+
+ assertThatThrownBy(manager::start)
+ .isInstanceOf(FlinkRuntimeException.class)
+ .hasRootCauseInstanceOf(IllegalStateException.class)
+ .hasRootCauseMessage("token service unreachable");
+
+ assertThat(provider.obtainCalls()).isEqualTo(1);
+ assertThat(receiver.receivedGenerations()).isEmpty();
+ assertThat(harness.pendingObtainDelaysMillis()).isEmpty();
+ assertThatThrownBy(() -> manager.attachListener(new
RecordingListener()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("STOPPED");
+ }
+
+ @Test
+ void errorOfTheFirstObtainIsNotWrappedAndStopsTheManager() {
+ provider.duringObtain(
+ () -> {
+ throw new NoClassDefFoundError("provider library is
missing");
+ });
+
+ assertThatThrownBy(manager::start)
+ .isInstanceOf(NoClassDefFoundError.class)
+ .hasMessage("provider library is missing");
+
+ assertThat(harness.pendingObtainDelaysMillis()).isEmpty();
+ assertThatThrownBy(() -> manager.attachListener(new
RecordingListener()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("STOPPED");
+ }
+
+ @Test
+ void failedObtainIsRetriedBeforeTheTokensExpire() throws Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ provider.failWith(new IllegalStateException("token service
unreachable"));
+ harness.obtainIsDue();
+
+ assertThat(receiver.receivedGenerations()).containsExactly(1);
+ // The retry is capped at a third of the 60 seconds the held token
still lives.
+ assertThat(harness.pendingObtainDelaysMillis())
+ .hasSize(1)
+ .allSatisfy(retryDelay -> assertThat(retryDelay).isBetween(0L,
20_000L));
Review Comment:
Changed. The token lives three seconds now, so the assertion only holds if
the manager remembers the expiry.
##########
flink-runtime/src/main/java/org/apache/flink/runtime/security/token/DefaultDelegationTokenManager.java:
##########
@@ -222,171 +194,195 @@ static void checkProviderAndReceiverConsistency(
LOG.info("Provider and receiver instances are consistent");
}
- @VisibleForTesting
- static void checkSamePrefixedProviders(
- Map<String, DelegationTokenProvider> providers, Set<String>
warnings) {
- Set<String> providerPrefixes = new HashSet<>();
- for (String name : providers.keySet()) {
- String[] split = name.split("-");
- if (!providerPrefixes.add(split[0])) {
- String msg =
- String.format(
- "Multiple providers loaded with the same
prefix: %s. This might lead to unintended consequences, please consider using
only one of them.",
- split[0]);
- warnings.add(msg);
- }
- }
- }
-
/**
* Obtains new tokens in a one-time fashion and leaves it up to the caller
to distribute them.
*/
@Override
public void obtainDelegationTokens(DelegationTokenContainer container)
throws Exception {
LOG.info("Obtaining delegation tokens");
- obtainDelegationTokensAndGetNextRenewal(container);
+ obtainDelegationTokensAndGetExpiry(container);
LOG.info("Delegation tokens obtained successfully");
}
+ /**
+ * Obtains the tokens of the providers which require them, adds them to
the container and
+ * returns their expiry: the earliest {@code validUntil} of the obtained
tokens, empty if no
+ * provider reports one.
+ */
+ protected Optional<Long> obtainDelegationTokensAndGetExpiry(
+ DelegationTokenContainer container) {
+ return
delegationTokenProviderRepository.obtainDelegationTokensAndGetExpiry(container);
+ }
+
+ /**
+ * Starts obtaining tokens for the lifetime of the process: obtains tokens
inline, propagates
+ * them to the local JVM receivers and schedules the next obtain. A
failure of the first obtain
+ * is not retried but thrown, because the process may need the tokens
right away (e.g.
+ * BlobServer).
+ */
@Override
- public void obtainDelegationTokens() throws Exception {
- LOG.info("Obtaining delegation tokens");
+ public void start() throws Exception {
+ checkNotNull(scheduledExecutor, "Scheduled executor must not be null");
+ checkNotNull(ioExecutor, "IO executor must not be null");
+ synchronized (stateLock) {
+ checkState(
+ state == State.CREATED,
+ "The delegation token manager can only be started once,
current state: %s",
+ state);
+ state = State.RUNNING;
+ }
+
+ try {
+ obtainDistributeAndScheduleNext();
+ } catch (Throwable t) {
+ stop();
+ throw t;
+ }
+ }
+
+ @Override
+ public void attachListener(Listener listener) throws Exception {
+ checkNotNull(listener, "Listener must not be null");
+ synchronized (stateLock) {
+ checkState(
+ state == State.RUNNING,
+ "The delegation token manager must be running to attach a
listener, current state: %s",
+ state);
+ if (this.listener != null && this.listener != listener) {
+ LOG.warn("Replacing the attached delegation token listener");
+ }
+ this.listener = listener;
+ LOG.info("Delegation token listener attached");
+ }
+ deliverLatestTokens();
Review Comment:
That's a nice catch, changed. Tokens past their expiry are not handed to the
listener any more, so a reconnecting TaskManager keeps the tokens it holds.
##########
flink-runtime/src/main/java/org/apache/flink/runtime/security/token/DefaultDelegationTokenManager.java:
##########
@@ -222,171 +194,195 @@ static void checkProviderAndReceiverConsistency(
LOG.info("Provider and receiver instances are consistent");
}
- @VisibleForTesting
- static void checkSamePrefixedProviders(
- Map<String, DelegationTokenProvider> providers, Set<String>
warnings) {
- Set<String> providerPrefixes = new HashSet<>();
- for (String name : providers.keySet()) {
- String[] split = name.split("-");
- if (!providerPrefixes.add(split[0])) {
- String msg =
- String.format(
- "Multiple providers loaded with the same
prefix: %s. This might lead to unintended consequences, please consider using
only one of them.",
- split[0]);
- warnings.add(msg);
- }
- }
- }
-
/**
* Obtains new tokens in a one-time fashion and leaves it up to the caller
to distribute them.
*/
@Override
public void obtainDelegationTokens(DelegationTokenContainer container)
throws Exception {
LOG.info("Obtaining delegation tokens");
- obtainDelegationTokensAndGetNextRenewal(container);
+ obtainDelegationTokensAndGetExpiry(container);
LOG.info("Delegation tokens obtained successfully");
}
+ /**
+ * Obtains the tokens of the providers which require them, adds them to
the container and
+ * returns their expiry: the earliest {@code validUntil} of the obtained
tokens, empty if no
+ * provider reports one.
+ */
+ protected Optional<Long> obtainDelegationTokensAndGetExpiry(
+ DelegationTokenContainer container) {
+ return
delegationTokenProviderRepository.obtainDelegationTokensAndGetExpiry(container);
+ }
+
+ /**
+ * Starts obtaining tokens for the lifetime of the process: obtains tokens
inline, propagates
+ * them to the local JVM receivers and schedules the next obtain. A
failure of the first obtain
+ * is not retried but thrown, because the process may need the tokens
right away (e.g.
+ * BlobServer).
+ */
@Override
- public void obtainDelegationTokens() throws Exception {
- LOG.info("Obtaining delegation tokens");
+ public void start() throws Exception {
+ checkNotNull(scheduledExecutor, "Scheduled executor must not be null");
+ checkNotNull(ioExecutor, "IO executor must not be null");
+ synchronized (stateLock) {
+ checkState(
+ state == State.CREATED,
+ "The delegation token manager can only be started once,
current state: %s",
+ state);
+ state = State.RUNNING;
+ }
+
+ try {
+ obtainDistributeAndScheduleNext();
+ } catch (Throwable t) {
+ stop();
+ throw t;
+ }
+ }
+
+ @Override
+ public void attachListener(Listener listener) throws Exception {
+ checkNotNull(listener, "Listener must not be null");
+ synchronized (stateLock) {
+ checkState(
+ state == State.RUNNING,
+ "The delegation token manager must be running to attach a
listener, current state: %s",
+ state);
+ if (this.listener != null && this.listener != listener) {
+ LOG.warn("Replacing the attached delegation token listener");
+ }
+ this.listener = listener;
+ LOG.info("Delegation token listener attached");
+ }
+ deliverLatestTokens();
+ }
+
+ @Override
+ public void detachListener(Listener listener) {
+ checkNotNull(listener, "Listener must not be null");
+ // Waits for the delivery in progress, so that no callback runs once
this method returns.
+ synchronized (deliveryLock) {
+ synchronized (stateLock) {
+ if (this.listener == listener) {
+ this.listener = null;
+ LOG.info("Delegation token listener detached");
+ }
+ }
+ }
+ }
+
+ /**
+ * One obtain: gets new tokens from the providers, updates the local JVM
receivers, stores the
+ * tokens as the latest ones, delivers them to the attached listener and
schedules the next
+ * obtain.
+ */
+ private void obtainDistributeAndScheduleNext() throws Exception {
+ LOG.info("Obtaining and distributing delegation tokens");
DelegationTokenContainer container = new DelegationTokenContainer();
- obtainDelegationTokensAndGetNextRenewal(container);
- LOG.info("Delegation tokens obtained successfully");
+ Optional<Long> expiry = obtainDelegationTokensAndGetExpiry(container);
if (container.hasTokens()) {
delegationTokenReceiverRepository.onNewTokensObtained(container);
+
storeAndDeliverLatestTokens(InstantiationUtil.serializeObject(container));
} else {
- LOG.warn("No tokens obtained so skipping notifications");
+ LOG.warn("No tokens obtained so skipping the update of the
receivers and the delivery");
+ }
+
+ if (expiry.isPresent()) {
+ lastKnownExpiry = expiry.get();
+ currentRetryBackoff = renewalRetryInitialBackoff;
+ long obtainDelay = calculateObtainDelay(clock, expiry.get());
+ if (scheduleNextObtainIfRunning(obtainDelay)) {
+ LOG.info(
+ "Next delegation token obtain scheduled with {} delay",
+
TimeUtils.formatWithHighestUnit(Duration.ofMillis(obtainDelay)));
+ }
+ } else {
+ LOG.warn(
+ "Next delegation token obtain not scheduled because either
no tokens were obtained or none of the tokens specified its expiry");
Review Comment:
Intended. An empty `validUntil` means the tokens are valid forever (see
`ObtainedDelegationTokens`), so the manager has nothing to obtain again and a
takeover hands over what the process holds. If HBase tokens expire,
`HBaseDelegationTokenProvider` has to report it.
##########
flink-runtime/src/test/java/org/apache/flink/runtime/security/token/DefaultDelegationTokenManagerLifecycleTest.java:
##########
@@ -0,0 +1,447 @@
+/*
+ * 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.flink.runtime.security.token;
+
+import org.apache.flink.util.FlinkRuntimeException;
+import org.apache.flink.util.function.ThrowingConsumer;
+
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static org.apache.flink.core.testutils.CommonTestUtils.waitUtil;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Tests for the two lifetimes of the {@link DefaultDelegationTokenManager}:
obtaining the tokens
+ * lasts as long as the process, a listener which distributes them lasts as
long as a leader
+ * session.
+ */
+class DefaultDelegationTokenManagerLifecycleTest {
+
+ private static final Duration TIMEOUT = Duration.ofSeconds(10);
+
+ /** The default obtain time ratio of 0.75 applied to the 60 seconds a
token lives. */
+ private static final long OBTAIN_DELAY_MILLIS = 45_000L;
+
+ private final MockTokenService tokenService =
+ new MockTokenService(
+ Clock.fixed(Instant.ofEpochMilli(1_000_000L),
ZoneOffset.UTC),
+ Duration.ofSeconds(60));
+ private final DelegationTokenManagerTestHarness harness =
+ new DelegationTokenManagerTestHarness(tokenService);
+ private final DefaultDelegationTokenManager manager = harness.manager();
+ private final MockDelegationTokenProvider provider = harness.provider();
+ private final MockDelegationTokenReceiver receiver = harness.receiver();
+
+ //
------------------------------------------------------------------------------------------
+ // Obtaining the tokens for the process
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void
startObtainsTokensForTheReceiversAndSchedulesTheNextObtainWithoutAnyListener()
+ throws Exception {
+ manager.start();
+
+ assertThat(provider.obtainCalls()).isEqualTo(1);
+ assertThat(receiver.receivedGenerations()).containsExactly(1);
+
assertThat(harness.pendingObtainDelaysMillis()).containsExactly(OBTAIN_DELAY_MILLIS);
+ }
+
+ @Test
+ void scheduledObtainsKeepUpdatingTheReceiversWithoutAnyListener() throws
Exception {
+ manager.start();
+
+ harness.obtainIsDue();
+ harness.obtainIsDue();
+
+ assertThat(provider.obtainCalls()).isEqualTo(3);
+ assertThat(receiver.receivedGenerations()).containsExactly(1, 2, 3);
+
assertThat(harness.pendingObtainDelaysMillis()).containsExactly(OBTAIN_DELAY_MILLIS);
+ }
+
+ @Test
+ void startWithoutRequiredTokensObtainsNothingAndSchedulesNothing() throws
Exception {
+ provider.setTokensRequired(false);
+
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ assertThat(provider.obtainCalls()).isZero();
+ assertThat(receiver.receivedGenerations()).isEmpty();
+ assertThat(listener.receivedGenerations()).isEmpty();
+ assertThat(harness.pendingObtainDelaysMillis()).isEmpty();
+ }
+
+ //
------------------------------------------------------------------------------------------
+ // The listener of a leader session
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void attachHandsOverTheLatestTokensWithoutContactingTheTokenService()
throws Exception {
+ manager.start();
+ harness.obtainIsDue();
+ final RecordingListener listener = new RecordingListener();
+
+ manager.attachListener(listener);
+
+ assertThat(listener.receivedGenerations()).containsExactly(2);
+ assertThat(provider.obtainCalls()).isEqualTo(2);
+ }
+
+ @Test
+ void obtainedTokensAreDeliveredToTheAttachedListenerInOrder() throws
Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ harness.obtainIsDue();
+ harness.obtainIsDue();
+
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2, 3);
+ }
+
+ @Test
+ void detachEndsTheDeliveryButTheObtainingContinues() throws Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ manager.detachListener(listener);
+ harness.obtainIsDue();
+
+ assertThat(listener.receivedGenerations()).containsExactly(1);
+ assertThat(receiver.receivedGenerations()).containsExactly(1, 2);
+ assertThat(provider.obtainCalls()).isEqualTo(2);
+
assertThat(harness.pendingObtainDelaysMillis()).containsExactly(OBTAIN_DELAY_MILLIS);
+ }
+
+ @Test
+ void nextLeaderSessionGetsTheTokensObtainedWhileNobodyWasAttached() throws
Exception {
+ manager.start();
+ final RecordingListener firstSession = new RecordingListener();
+ manager.attachListener(firstSession);
+ harness.obtainIsDue();
+ manager.detachListener(firstSession);
+ harness.obtainIsDue();
+
+ final RecordingListener secondSession = new RecordingListener();
+ manager.attachListener(secondSession);
+
+ assertThat(firstSession.receivedGenerations()).containsExactly(1, 2);
+ assertThat(secondSession.receivedGenerations()).containsExactly(3);
+ assertThat(provider.obtainCalls()).isEqualTo(3);
+ }
+
+ @Test
+ void detachOfAnEarlierListenerKeepsTheCurrentOne() throws Exception {
+ manager.start();
+ final RecordingListener earlierSession = new RecordingListener();
+ final RecordingListener currentSession = new RecordingListener();
+ manager.attachListener(earlierSession);
+ manager.attachListener(currentSession);
+
+ manager.detachListener(earlierSession);
+ harness.obtainIsDue();
+
+ assertThat(currentSession.receivedGenerations()).containsExactly(1, 2);
+ assertThat(earlierSession.receivedGenerations()).containsExactly(1);
+ }
+
+ @Test
+ void obtainDuringTheReplayOfAnAttachIsDeliveredAfterTheReplay() throws
Exception {
+ manager.start();
+ final CountDownLatch replayInListener = new CountDownLatch(1);
+ final CountDownLatch replayReleased = new CountDownLatch(1);
+ final RecordingListener listener =
+ new RecordingListener(
+ generation -> {
+ if (generation == 1) {
+ replayInListener.countDown();
+ replayReleased.await();
+ }
+ });
+ final ExecutorService attacher = Executors.newSingleThreadExecutor();
+ final ExecutorService obtainer = Executors.newSingleThreadExecutor();
+ try {
+ final Future<?> attach =
+ attacher.submit(
+ () -> {
+ manager.attachListener(listener);
+ return null;
+ });
+ assertThat(replayInListener.await(TIMEOUT.toMillis(),
TimeUnit.MILLISECONDS))
+ .as("the replay reached the listener")
+ .isTrue();
+
+ final Thread obtainerThread =
obtainer.submit(Thread::currentThread).get();
+ final Future<?> obtain = obtainer.submit(harness::obtainIsDue);
+ // The obtain must queue up behind the replay. A manager which
lets it pass delivers
+ // the new tokens first, which is what the assertion below detects.
+ waitUtil(
+ () -> obtain.isDone() || obtainerThread.getState() ==
Thread.State.BLOCKED,
+ TIMEOUT,
+ "The obtain neither completed nor waits for the replay");
+ replayReleased.countDown();
+ attach.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ obtain.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2);
+ } finally {
+ replayReleased.countDown();
+ attacher.shutdownNow();
+ obtainer.shutdownNow();
+ }
+ }
+
+ @Test
+ void detachWaitsForTheDeliveryInProgressAndNothingIsDeliveredAfterwards()
throws Exception {
+ manager.start();
+ final AtomicBoolean holdNextCallback = new AtomicBoolean();
+ final CountDownLatch obtainInListener = new CountDownLatch(1);
+ final CountDownLatch obtainReleased = new CountDownLatch(1);
+ final RecordingListener listener =
+ new RecordingListener(
+ generation -> {
+ if (holdNextCallback.compareAndSet(true, false)) {
+ obtainInListener.countDown();
+ obtainReleased.await();
+ }
+ });
+ manager.attachListener(listener);
+ // Only the callback of the obtain is held, a callback on the test
thread would hang it.
+ holdNextCallback.set(true);
+ final ExecutorService obtainer = Executors.newSingleThreadExecutor();
+ final ExecutorService detacher = Executors.newSingleThreadExecutor();
+ try {
+ final Future<?> obtain = obtainer.submit(harness::obtainIsDue);
+ assertThat(obtainInListener.await(TIMEOUT.toMillis(),
TimeUnit.MILLISECONDS))
+ .as("the obtain reached the listener")
+ .isTrue();
+
+ final Thread detacherThread =
detacher.submit(Thread::currentThread).get();
+ final Future<?> detach = detacher.submit(() ->
manager.detachListener(listener));
+ // The detach must wait for the callback in progress. A manager
which lets it pass
+ // returns here while the callback is still held.
+ waitUtil(
+ () -> detach.isDone() || detacherThread.getState() ==
Thread.State.BLOCKED,
+ TIMEOUT,
+ "The detach neither returned nor waits for the callback in
progress");
+ assertThat(detach).as("detach returned during a
callback").isNotDone();
+
+ obtainReleased.countDown();
+ obtain.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ detach.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2);
+
+ harness.obtainIsDue();
+ assertThat(listener.receivedGenerations()).containsExactly(1, 2);
+ } finally {
+ obtainReleased.countDown();
+ obtainer.shutdownNow();
+ detacher.shutdownNow();
+ }
+ }
+
+ //
------------------------------------------------------------------------------------------
+ // Stop
+ //
------------------------------------------------------------------------------------------
+
+ @Test
+ void stopCancelsTheScheduledObtainAndReleasesTheListener() throws
Exception {
+ manager.start();
+ final RecordingListener listener = new RecordingListener();
+ manager.attachListener(listener);
+
+ manager.stop();
Review Comment:
Changed. The scheduled obtain checks the state before it runs. One which is
already inside the provider call when `stop()` is called still completes.
--
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]