Savonitar commented on code in PR #30043:
URL: https://github.com/apache/flink/pull/30043#discussion_r4700351741


##########
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:
   Should the replay be skipped once the tokens are past `lastKnownExpiry`?
   
   If standby obtains have been failing, a reconnecting TaskManager can 
overwrite still-valid credentials from the previous leader. Previously a failed 
obtaining on handover left those credentials active. 
   
   E.g. we have 2 JMs A and B:
   - A gave a worker an S3 token valid until 10:30.
   - B own S3 token expired at 10:00. B tried to obtain it, but the token 
service was unavailable.
   - At 10:05 A fails. The worker reconnects to B. The worker still has 25 
minutes of valid S3 access.
   
   Before the PR, B would try to fetch a token. If that failed, B would send no 
token, so the worker would keep its working one. With the PR, B sends its 
cached 10:00 token. The worker installs it over its 10:30 token and immediately 
loses S3 access.
   
   Or am I missing something? 



##########
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:
   After `hangTokenService()` nothing triggers an obtain, so the test shows 
that a takeover does not contact the token service, not that it survives a 
hanging call. Is that intentional?



##########
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:
   Could we also close the RPC and metrics services created before HA 
initialization fails? I ran this test twice, and both runs left their threads 
and a MiniCluster working directory behind.



##########
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:
   What if the timer has already handed the obtain to the IO executor when 
`stop()` is called? As far as I can see that obtain still runs after `stop()` 
returned, because `runScheduledObtainAndRetryOnFailure` does not check the 
state.



##########
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:
   The description lists this as intended. But `HBaseDelegationTokenProvider` 
returns no `validUntil` meanwhile HBase tokens can expire. A JobManager that 
takes over after that would hand the TaskManagers its start-time token, where a 
takeover used to obtain a fresh one. 
   Should `attachListener` trigger an obtain when none is scheduled?



##########
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:
   Could we use a three-second token and assert the retry is scheduled within 
one second? The uncapped retry already falls below 20 seconds, so this 
assertion passes even if the manager forgets the expiry.



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

Reply via email to