anton-vinogradov commented on code in PR #13874:
URL: https://github.com/apache/ignite/pull/13874#discussion_r4739586980


##########
modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java:
##########
@@ -128,146 +123,202 @@ private long consecutiveHotReloadFailures() {
         return sum;
     }
 
-    /** Runs the hourly check of the factories with hot reload enabled. */
-    private void checkFactories() {
-        if (log.isDebugEnabled())
-            log.debug("TLS hot reload check started");
-
-        for (RegisteredFactory registered : factories) {
-            if (registered.hotReloadFactory() != null)
-                registered.check();
-        }
-    }
-
     /** {@inheritDoc} */
     @Override public void onKernalStop(boolean cancel) {
         if (executor != null)
             executor.shutdownNow();
     }
 
     /**
-     * Reloads a registered factory. For a factory with hot reload enabled, 
waits for its running check and resets its failure
-     * count.
+     * Reloads a registered factory. If the factory has automatic checks, 
waits for its running check, resets its failure
+     * count and schedules its next check for the loaded certificates. If they 
are already due, the next check comes after
+     * {@link #CHECK_PERIOD}, because an automatic reload right away would 
load the same certificates from the source. If the
+     * factory cannot give the automatic reload time of the loaded 
certificates, the reload still succeeds, and the next check
+     * comes after {@link #CHECK_PERIOD}. The node start schedules the first 
check of each factory with automatic reload
+     * enabled, so a reload before the start only loads the factory.
      *
      * @param factory Registered factory to reload.
      */
-    public void reload(AbstractSslContextFactory factory) {
+    public void reload(ReloadableSslFactory factory) {
         for (RegisteredFactory registered : factories) {
             if (registered.factory == factory)
                 registered.reload();
         }
     }
 
-    /** Registered factory with its transports and hot reload state. The 
hourly check and manual reload hold its monitor. */
+    /** Registered factory with its transports and automatic reload state. Its 
checks and manual reload hold its monitor. */
     private class RegisteredFactory {
         /** */
         private final Factory<SSLContext> factory;
 
+        /** The factory if the registry can reload it, {@code null} otherwise. 
*/
+        @Nullable private final ReloadableSslFactory reloadable;
+
         /** */
         private final String transports;
 
         /** */
         private final AtomicInteger failures = new AtomicInteger();
 
+        /** Next automatic check, or {@code null} if the factory has no 
automatic checks. */
+        @Nullable private ScheduledFuture<?> nextCheck;
+
+        /** Automatic reload time that the registry logged last, or {@code -1} 
before the first log. */
+        private long loggedAutoReloadTime = -1;
+
         /** */
         private RegisteredFactory(Factory<SSLContext> factory, String 
transports) {
             this.factory = factory;
             this.transports = transports;
-        }
 
-        /** @return The factory if hot reload is enabled for it, {@code null} 
otherwise. */
-        @Nullable private AbstractSslContextFactory hotReloadFactory() {
-            return factory instanceof AbstractSslContextFactory sslFactory && 
sslFactory.isHotReloadEnabled() ? sslFactory : null;
+            reloadable = factory instanceof ReloadableSslFactory sslFactory ? 
sslFactory : null;
         }
 
         /**
-         * Checks the factory unless the registry has stopped. Counts and logs 
a failed check, so it does not stop
-         * the other factories or the schedule. A check that fails while the 
registry stops is logged at debug level
-         * and not counted.
+         * Checks the factory unless the registry has stopped, and schedules 
its next check. Counts and logs a failed
+         * check and retries it after {@link #CHECK_PERIOD}, so a failure does 
not stop the checks. A check that fails
+         * while the registry stops is logged at debug level and not counted.
          */
         private synchronized void check() {
             if (executor.isShutdown())
                 return;
 
+            if (log.isDebugEnabled())
+                log.debug("TLS automatic reload check started [transports=" + 
transports + ']');
+
+            long nextCheckDelay = CHECK_PERIOD;
+
             try {
-                reloadIfDue();
+                nextCheckDelay = reloadIfDue();
             }
             catch (Throwable e) {
                 if (!executor.isShutdown()) {
                     failures.incrementAndGet();
 
-                    log.warning("TLS hot reload failed [transports=" + 
transports + ", nextAttempt="
+                    log.warning("TLS automatic reload failed [transports=" + 
transports + ", nextAttempt="
                         + new Date(System.currentTimeMillis() + CHECK_PERIOD) 
+ ']', e);
                 }
                 else if (log.isDebugEnabled())
-                    log.debug("TLS hot reload failed during node stop 
[transports=" + transports + ", err=" + e + ']');
+                    log.debug("TLS automatic reload failed during node stop 
[transports=" + transports + ", err=" + e + ']');
             }
+
+            scheduleCheck(nextCheckDelay);
         }
 
         /**
-         * Reloads the factory if its hot reload time has come, and ends the 
failure streak if it has not.
+         * Reloads the factory if its automatic reload time has come, and ends 
the failure streak if it has not.
          *
+         * @return Delay of the next check.
          * @throws IgniteException If the reload fails or leaves certificates 
that are still due.
          */
-        private void reloadIfDue() {
-            AbstractSslContextFactory sslFactory = 
(AbstractSslContextFactory)factory;
+        private long reloadIfDue() {
+            long autoReloadTime = reloadable.autoReloadTime();

Review Comment:
   No defence is needed here. Only entries with a non-null `reloadable` get 
their first scheduled check, and each later check runs on the same entry, whose 
field is final. I added an assertion in `reloadIfDue()` to make that explicit.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java:
##########
@@ -128,146 +123,202 @@ private long consecutiveHotReloadFailures() {
         return sum;
     }
 
-    /** Runs the hourly check of the factories with hot reload enabled. */
-    private void checkFactories() {
-        if (log.isDebugEnabled())
-            log.debug("TLS hot reload check started");
-
-        for (RegisteredFactory registered : factories) {
-            if (registered.hotReloadFactory() != null)
-                registered.check();
-        }
-    }
-
     /** {@inheritDoc} */
     @Override public void onKernalStop(boolean cancel) {
         if (executor != null)
             executor.shutdownNow();
     }
 
     /**
-     * Reloads a registered factory. For a factory with hot reload enabled, 
waits for its running check and resets its failure
-     * count.
+     * Reloads a registered factory. If the factory has automatic checks, 
waits for its running check, resets its failure
+     * count and schedules its next check for the loaded certificates. If they 
are already due, the next check comes after
+     * {@link #CHECK_PERIOD}, because an automatic reload right away would 
load the same certificates from the source. If the
+     * factory cannot give the automatic reload time of the loaded 
certificates, the reload still succeeds, and the next check
+     * comes after {@link #CHECK_PERIOD}. The node start schedules the first 
check of each factory with automatic reload
+     * enabled, so a reload before the start only loads the factory.
      *
      * @param factory Registered factory to reload.
      */
-    public void reload(AbstractSslContextFactory factory) {
+    public void reload(ReloadableSslFactory factory) {
         for (RegisteredFactory registered : factories) {
             if (registered.factory == factory)
                 registered.reload();
         }
     }
 
-    /** Registered factory with its transports and hot reload state. The 
hourly check and manual reload hold its monitor. */
+    /** Registered factory with its transports and automatic reload state. Its 
checks and manual reload hold its monitor. */
     private class RegisteredFactory {
         /** */
         private final Factory<SSLContext> factory;
 
+        /** The factory if the registry can reload it, {@code null} otherwise. 
*/
+        @Nullable private final ReloadableSslFactory reloadable;
+
         /** */
         private final String transports;
 
         /** */
         private final AtomicInteger failures = new AtomicInteger();
 
+        /** Next automatic check, or {@code null} if the factory has no 
automatic checks. */
+        @Nullable private ScheduledFuture<?> nextCheck;
+
+        /** Automatic reload time that the registry logged last, or {@code -1} 
before the first log. */
+        private long loggedAutoReloadTime = -1;
+
         /** */
         private RegisteredFactory(Factory<SSLContext> factory, String 
transports) {
             this.factory = factory;
             this.transports = transports;
-        }
 
-        /** @return The factory if hot reload is enabled for it, {@code null} 
otherwise. */
-        @Nullable private AbstractSslContextFactory hotReloadFactory() {
-            return factory instanceof AbstractSslContextFactory sslFactory && 
sslFactory.isHotReloadEnabled() ? sslFactory : null;
+            reloadable = factory instanceof ReloadableSslFactory sslFactory ? 
sslFactory : null;
         }
 
         /**
-         * Checks the factory unless the registry has stopped. Counts and logs 
a failed check, so it does not stop
-         * the other factories or the schedule. A check that fails while the 
registry stops is logged at debug level
-         * and not counted.
+         * Checks the factory unless the registry has stopped, and schedules 
its next check. Counts and logs a failed
+         * check and retries it after {@link #CHECK_PERIOD}, so a failure does 
not stop the checks. A check that fails
+         * while the registry stops is logged at debug level and not counted.
          */
         private synchronized void check() {
             if (executor.isShutdown())
                 return;
 
+            if (log.isDebugEnabled())
+                log.debug("TLS automatic reload check started [transports=" + 
transports + ']');
+
+            long nextCheckDelay = CHECK_PERIOD;
+
             try {
-                reloadIfDue();
+                nextCheckDelay = reloadIfDue();
             }
             catch (Throwable e) {
                 if (!executor.isShutdown()) {
                     failures.incrementAndGet();
 
-                    log.warning("TLS hot reload failed [transports=" + 
transports + ", nextAttempt="
+                    log.warning("TLS automatic reload failed [transports=" + 
transports + ", nextAttempt="
                         + new Date(System.currentTimeMillis() + CHECK_PERIOD) 
+ ']', e);
                 }
                 else if (log.isDebugEnabled())
-                    log.debug("TLS hot reload failed during node stop 
[transports=" + transports + ", err=" + e + ']');
+                    log.debug("TLS automatic reload failed during node stop 
[transports=" + transports + ", err=" + e + ']');
             }
+
+            scheduleCheck(nextCheckDelay);
         }
 
         /**
-         * Reloads the factory if its hot reload time has come, and ends the 
failure streak if it has not.
+         * Reloads the factory if its automatic reload time has come, and ends 
the failure streak if it has not.
          *
+         * @return Delay of the next check.
          * @throws IgniteException If the reload fails or leaves certificates 
that are still due.
          */
-        private void reloadIfDue() {
-            AbstractSslContextFactory sslFactory = 
(AbstractSslContextFactory)factory;
+        private long reloadIfDue() {
+            long autoReloadTime = reloadable.autoReloadTime();
+
+            logAutoReloadTime(autoReloadTime);
 
-            if (!due(sslFactory.getHotReloadTime())) {
+            long nextCheckDelay = nextCheckDelay(autoReloadTime);
+
+            if (nextCheckDelay != 0) {
                 failures.set(0);
 
-                return;
+                return nextCheckDelay;
             }
 
-            automaticHotReloadAttempts.incrementAndGet();
+            autoReloadAttempts.incrementAndGet();
 
             if (log.isInfoEnabled())
-                log.info("TLS hot reload started [transports=" + transports + 
']');
+                log.info("TLS automatic reload started [transports=" + 
transports + ']');
 
-            sslFactory.init();
+            reloadable.init();
 
-            long hotReloadTime = sslFactory.getHotReloadTime();
+            autoReloadTime = reloadable.autoReloadTime();
+            nextCheckDelay = nextCheckDelay(autoReloadTime);
 
-            if (due(hotReloadTime)) {
-                throw new IgniteException("Loaded certificates are still due 
for hot reload [hotReloadTime="
-                    + new Date(hotReloadTime) + ']');
+            if (nextCheckDelay == 0) {
+                throw new IgniteException("Loaded certificates are still due 
for automatic reload [autoReloadTime="
+                    + new Date(autoReloadTime) + ']');
             }
 
             failures.set(0);
 
             if (log.isInfoEnabled())
-                log.info("TLS hot reload succeeded [transports=" + transports 
+ ']');
+                log.info("TLS automatic reload succeeded [transports=" + 
transports + ']');
+
+            logAutoReloadTime(autoReloadTime);
 
-            logHotReloadTime(hotReloadTime);
+            return nextCheckDelay;
         }
 
-        /** @return Whether the loaded certificates have a hot reload time, 
and it has come. */
-        private static boolean due(long hotReloadTime) {
-            return hotReloadTime != 0 && hotReloadTime <= 
System.currentTimeMillis();
+        /**
+         * @param autoReloadTime Automatic reload time of the loaded 
certificates, or {@code 0} if they have none.
+         * @return Delay until the automatic reload time, but no longer than 
{@link #CHECK_PERIOD}, or {@code 0} if the time has
+         *     come. Certificates without an automatic reload time are checked 
again after the full period.
+         */
+        private static long nextCheckDelay(long autoReloadTime) {
+            if (autoReloadTime == 0)
+                return CHECK_PERIOD;
+
+            return Math.max(0, Math.min(autoReloadTime - 
System.currentTimeMillis(), CHECK_PERIOD));
+        }
+
+        /** Replaces the scheduled check of the factory with one after the 
given delay. */
+        private synchronized void scheduleCheck(long delay) {
+            if (nextCheck != null)
+                nextCheck.cancel(false);
+
+            try {
+                nextCheck = executor.schedule(new 
OperationContextAwareRunnable(this::check, null), delay, MILLISECONDS);
+            }
+            catch (RejectedExecutionException ignored) {
+                // The registry has stopped.
+            }
         }
 
         /** */
         private synchronized void reload() {
             manualReloadAttempts.incrementAndGet();
 
-            ((AbstractSslContextFactory)factory).init();
+            reloadable.init();

Review Comment:
   The manual command first checks that every factory supports reload, and the 
registry then finds the entry by that same instance, so its `reloadable` is not 
null. I added the assertion in `reload()` as well.



##########
modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java:
##########
@@ -0,0 +1,602 @@
+/*
+ * 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.ignite.internal.processors.rest.protocols.http.jetty;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.security.cert.Certificate;
+import java.util.Deque;
+import java.util.List;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+import javax.net.ssl.SNIHostName;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.TrustManagerFactory;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.configuration.ConnectorConfiguration;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.management.api.CommandInvoker;
+import org.apache.ignite.internal.management.api.NoArg;
+import org.apache.ignite.internal.management.ssl.SslReloadCommand;
+import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory;
+import org.apache.ignite.ssl.TestCertificateAuthority;
+import org.apache.ignite.ssl.jetty.AutoReloadJettySslFactory;
+import org.apache.ignite.testframework.junits.WithSystemProperty;
+import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
+import org.eclipse.jetty.util.resource.Resource;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import static java.util.concurrent.TimeUnit.DAYS;
+import static java.util.concurrent.TimeUnit.HOURS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.apache.ignite.IgniteSystemProperties.IGNITE_JETTY_PORT;
+import static 
org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_JETTY_PORT;
+import static 
org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_TCP_PORT;
+import static 
org.apache.ignite.internal.processors.rest.protocols.http.jetty.GridJettyRestProtocol.DFLT_JETTY_PORT;
+import static 
org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS;
+import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD;
+import static org.apache.ignite.ssl.TestCertificateAuthority.save;
+import static org.apache.ignite.testframework.GridTestUtils.assertThrows;
+import static 
org.apache.ignite.testframework.GridTestUtils.assertThrowsAnyCause;
+import static org.apache.ignite.testframework.GridTestUtils.waitForCondition;
+
+/**
+ * TLS reload of the HTTP REST connector configured in Jetty XML. The standard 
Jetty factory reads its key store from a file
+ * and requires an SNI host name ({@code jetty/https.xml}); {@code 
jetty/https-detector.xml} reads the same file through
+ * a connector that accepts HTTP and HTTPS on one port. The custom factory 
({@code jetty/https-source.xml}) takes its
+ * key stores from {@link SourceSslContextFactory}; {@code 
jetty/https-source-manual.xml} configures the same source
+ * with automatic reload disabled. The connectors in these files set no port, 
so the tests set {@code IGNITE_JETTY_PORT};
+ * otherwise the node would publish port 0.
+ */
+@WithSystemProperty(key = IGNITE_JETTY_PORT, value = DFLT_JETTY_PORT)
+public class JettyRestHttpsReloadTest extends GridCommonAbstractTest {
+    /** Path read by the HTTPS connector in {@code jetty/https.xml}. */
+    private static final String KEY_STORE_PATH = 
"ignite.test.JettyRestHttpsReloadTest.keyStorePath";
+
+    /** Host name in the server certificates and the HTTPS requests. */
+    private static final String HOST = "localhost";
+
+    /** Upper bound for waiting for an event that must happen. */
+    private static final long TIMEOUT_MS = 30_000;
+
+    /** */
+    @Rule public TemporaryFolder tmp = new TemporaryFolder();
+
+    /** Current time rounded down to seconds, the precision of certificate 
dates. */
+    private final long now = System.currentTimeMillis() / 1_000 * 1_000;
+
+    /** Issuer of all server certificates, which the HTTPS clients trust. */
+    private TestCertificateAuthority ca;
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTest() throws Exception {
+        super.beforeTest();
+
+        ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + 
DAYS.toMillis(365));
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        stopAllGrids();
+        SourceSslContextFactory.supply();
+
+        super.afterTest();
+    }
+
+    /**
+     * Given: HTTPS serves certificate A from a key store file of the standard 
Jetty factory.
+     * When: the file gets certificate B, and the operator runs the reload 
command.
+     * Then: the command reports HTTP REST as reloaded, and a new client sees 
B.
+     */
+    @Test
+    @WithSystemProperty(key = KEY_STORE_PATH, value = "")
+    public void testReloadCommandAppliesReplacementKeyStore() throws Exception 
{
+        KeyStore a = fresh();
+        KeyStore b = fresh();
+        Path keys = keyStoreFile(a);
+
+        IgniteEx node = startGrid(jettyConfig("jetty/https.xml"));
+
+        assertEquals(a.getCertificate(HOST), serverCertificate(node));
+
+        save(b, keys);
+
+        assertTrue(reload(node).contains(": HTTP REST: reloaded"));
+        assertEquals(b.getCertificate(HOST), serverCertificate(node));
+    }
+
+    /**
+     * Given: the Jetty connector accepts HTTP and HTTPS on one port, so its 
TLS factory sits inside
+     *     a {@code DetectorConnectionFactory}, and HTTPS serves certificate A 
from a key store file.
+     * When: the file gets certificate B, and the operator runs the reload 
command.
+     * Then: the command reports HTTP REST as reloaded, and a new client sees 
B.
+     */
+    @Test
+    @WithSystemProperty(key = KEY_STORE_PATH, value = "")
+    public void testReloadCommandFindsTlsFactoryInsideDetector() throws 
Exception {
+        KeyStore a = fresh();
+        KeyStore b = fresh();
+        Path keys = keyStoreFile(a);
+
+        IgniteEx node = startGrid(jettyConfig("jetty/https-detector.xml"));
+
+        assertEquals(a.getCertificate(HOST), serverCertificate(node));
+
+        save(b, keys);
+
+        assertTrue(reload(node).contains(": HTTP REST: reloaded"));
+        assertEquals(b.getCertificate(HOST), serverCertificate(node));
+    }
+
+    /**
+     * Given: HTTPS serves certificate A from a key store file of the standard 
Jetty factory, which selects certificates
+     *     by SNI host name.
+     * When: the file becomes unreadable and the operator runs the reload 
command, then the file gets certificate B and
+     *     the operator runs the command again.
+     * Then: the first command reports the node and the cause, and a new 
client that sends the host name still sees A.
+     *     After the second command, a new client sees B.
+     */
+    @Test
+    @WithSystemProperty(key = KEY_STORE_PATH, value = "")
+    public void testFailedReloadKeepsLastWorkingKeys() throws Exception {
+        KeyStore a = fresh();
+        KeyStore b = fresh();
+        Path keys = keyStoreFile(a);
+
+        IgniteEx node = startGrid(jettyConfig("jetty/https.xml"));
+
+        Files.writeString(keys, "not a key store");
+
+        assertThrowsAnyCause(log, () -> reload(node), IgniteException.class, 
node.localNode().id() + ": failed: HTTP REST: ");
+        assertEquals(a.getCertificate(HOST), serverCertificate(node));
+
+        save(b, keys);
+        reload(node);
+
+        assertEquals(b.getCertificate(HOST), serverCertificate(node));
+    }
+
+    /**
+     * Given: a custom Jetty factory starts with certificate A, which is due 
for automatic reload, and its source then supplies B.
+     * When: the node runs its automatic reload check at startup, then the 
source fails and the operator runs the reload command.
+     * Then: a new client sees B after the check. The command fails, and a new 
client still sees B.
+     */
+    @Test
+    public void testAutoReloadedKeysSurviveFailedManualReload() throws 
Exception {

Review Comment:
   Yes, and the wait is that check. The source supplies A at startup and B on 
the next load, so a new TLS connection sees B only after automatic reload 
applies the replacement. After the manual reload fails, another connection must 
still see B. If the automatic check skips `init()`, the test fails while 
waiting for B.



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