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


##########
modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java:
##########
@@ -0,0 +1,203 @@
+/*
+ * 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.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.util.function.Consumer;
+import javax.cache.configuration.Factory;
+import javax.net.ssl.SSLContext;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory;
+import org.apache.ignite.ssl.AbstractSslContextFactory;
+import org.apache.ignite.ssl.jetty.AutoReloadJettySslFactory;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.jetbrains.annotations.Nullable;
+
+import static 
org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS;
+
+/**
+ * Adapter through which the SSL factory registry reloads the TLS factory of 
the Jetty HTTPS connector. A failed reload
+ * leaves the previous keys and trust settings in use.
+ * Automatic reload follows the settings of the Jetty factory if it implements 
{@link AutoReloadJettySslFactory}. Otherwise
+ * automatic reload is enabled with the lead time {@link 
AbstractSslContextFactory#DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS}.
+ * <p>
+ * Jetty's factory guards its TLS state with an internal lock: it loads the 
state under this lock, and new connections
+ * take the state under it too. Before loading a replacement, Jetty clears the 
state. So that new connections never see
+ * a factory without keys, the reload and, if loading fails, the restore of 
the previous state run under this lock.
+ * Jetty lets callers hold the lock only inside {@link 
SslContextFactory#unload(Consumer)} and
+ * {@link SslContextFactory#reload(Consumer)}, so the work runs inside {@code 
unload(...)} and ends with {@link SkipUnload}.
+ * Jetty selects certificates for SNI host names from the key store of the 
state, so the restore keeps SNI selection.
+ * If the restore fails too, the factory has no state until the next 
successful reload, and the reload error carries
+ * that failure as a suppressed exception. A failed reload outside Ignite, 
such as one by Jetty's {@code KeyStoreScanner},
+ * can also leave the factory without state. Such a factory is due for 
automatic reload right away, and the reload has nothing
+ * to restore: it loads the configured sources.
+ * <p>
+ * After a failed reload, the factory gets back the context and stores set in 
{@code jetty.xml}, and the next reload
+ * reads its configured sources again. Once the factory has started, its 
getters return the loaded state rather than
+ * these settings. So the adapter cannot keep a context or store that code 
sets on the running factory: a failed reload
+ * drops it.
+ */
+class JettySslFactoryAdapter implements ReloadableSslFactory {
+    /** The adapter is serializable only because {@link Factory} is. 
Serializing it fails, as Jetty's factory is not serializable. */
+    private static final long serialVersionUID = 0L;
+
+    /** */
+    private final SslContextFactory factory;
+
+    /** State set in {@code jetty.xml}. The factory loads a {@code null} part 
from its configured source. */
+    private final TlsState configured;
+
+    /**
+     * @param factory TLS factory of the HTTPS connector before startup, when 
its getters return the state set in {@code jetty.xml}.
+     */
+    JettySslFactoryAdapter(SslContextFactory factory) {
+        assert !factory.isStarted();

Review Comment:
   Yes, without -ea a factory that jetty.xml had started went through, and the 
adapter kept its loaded keys as the configuration of later reloads. The 
constructor now throws IllegalStateException that asks to remove the start() 
call from the Jetty XML file, and testFactoryStartedBeforeIgniteIsRejected 
covers it.



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

Review Comment:
   The connectors there had no port, so Jetty listened on a port that the OS 
chose, while Ignite saw port 0 and published no REST address attributes, and 
the tests had no port to connect to. The XML files now set the port from 
IGNITE_JETTY_PORT with the default 8080, as other Ignite Jetty configurations 
do, so the class annotation and this sentence are gone.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java:
##########
@@ -91,35 +96,25 @@ public List<Entry<Factory<SSLContext>, String>> factories() 
{
     @Override public void onKernalStart(boolean active) {
         MetricRegistryImpl metrics = ctx.metric().registry("ssl");
 
-        metrics.register("ConsecutiveHotReloadFailures", 
this::consecutiveHotReloadFailures,
-            "Number of consecutive automatic hot reload failures.");
+        metrics.register("ConsecutiveAutoReloadFailures", 
this::consecutiveAutoReloadFailures,
+            "Number of consecutive automatic reload failures.");
         metrics.register("ManualReloadAttempts", manualReloadAttempts::get, 
"Number of manual reload attempts.");
-        metrics.register("AutomaticHotReloadAttempts", 
automaticHotReloadAttempts::get,
-            "Number of automatic hot reload attempts.");
-
-        boolean hotReload = false;
+        metrics.register("AutoReloadAttempts", autoReloadAttempts::get,
+            "Number of automatic reload attempts.");
 
         for (RegisteredFactory registered : factories) {
-            AbstractSslContextFactory sslFactory = 
registered.hotReloadFactory();
+            if (registered.reloadable == null || 
!registered.reloadable.isAutoReloadEnabled())
+                continue;
 
-            if (sslFactory != null) {
-                registered.logHotReloadTime(sslFactory.getHotReloadTime());
+            if (executor == null)
+                executor = newSingleThreadScheduledExecutor("ssl-auto-reload", 
ctx.igniteInstanceName());

Review Comment:
   TLS reload can block on the certificate source, for example a remote store, 
an HSM or a custom loadKeyStore. GridTimeoutProcessor calls onTimeout() inline 
in its single grid-timeout-worker, so a slow load would delay all other 
timeouts of that processor, and a long one could be reported as a blocked 
system-critical thread. A separate thread keeps the delay inside TLS reload. On 
node stop it gets an interrupt; whether a blocked read ends then depends on the 
source.



##########
modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java:
##########
@@ -62,65 +62,52 @@ public abstract class AbstractSslContextFactory implements 
Factory<SSLContext> {
     protected final AtomicReference<SSLContext> sslCtx = new 
AtomicReference<>();
 
     /** */
-    private boolean hotReloadEnabled;
+    private boolean autoReloadEnabled = true;
 
     /** */
-    private volatile long hotReloadBeforeExpiryMs = 
DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS;
+    private volatile long autoReloadBeforeExpiryMs = 
DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS;

Review Comment:
   Yes, Ignite keeps timing settings in milliseconds, for example 
failureDetectionTimeout, checkpointFrequency and 
ClientConnectorConfiguration.idleTimeout. Millisecond precision is not needed 
here, but short-lived certificates need a lead time of hours, so the unit must 
be finer than a day, and milliseconds follow the Ignite convention. The Ms 
suffix keeps the unit visible in Spring XML.



##########
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 = "")

Review Comment:
   After each test it restored the previous value of the key store path 
property, usually none, so later tests did not get a stale path. afterTest() 
now clears the property, and the annotations are gone; the key belongs to this 
test class and its XML files.



##########
modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java:
##########
@@ -128,146 +123,204 @@ 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. For a factory with automatic reload 
enabled, 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}.
      *
      * @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();
 
+        /** */
+        @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);
+
+            long nextCheckDelay = nextCheckDelay(autoReloadTime);
 
-            if (!due(sslFactory.getHotReloadTime())) {
+            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, once the registry has started. */
+        private synchronized void scheduleCheck(long delay) {
+            if (executor == null)

Review Comment:
   The flag is checked first: reload() returns before scheduleCheck() for a 
factory with automatic reload disabled. The null check covers a manual reload 
before onKernalStart(), which creates the executor and then schedules the first 
check of every factory with automatic reload enabled. This can happen when a 
JMX reload comes while the node starts: IgniteKernal registers the MBeans 
before it calls onKernalStart() of the components. 
testManualReloadBeforeStartLoadsFactory covers that case.



##########
modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.ssl;
+
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.Enumeration;
+import javax.cache.configuration.Factory;
+import javax.net.ssl.SSLContext;
+import org.apache.ignite.IgniteException;
+
+/** SSL context factory that the SSL factory registry can reload on request 
and before its certificates expire. */
+public interface ReloadableSslFactory extends Factory<SSLContext> {
+    /**
+     * Loads the keys and trust settings again for new connections. If loading 
fails, new connections keep the previous ones.
+     *
+     * @throws IgniteException If loading fails.
+     */
+    public void init();
+
+    /**
+     * The automatic reload time is the earliest expiry among the certificate 
chains of the private keys that new connections
+     * use, minus the lead time of the factory. A chain expires when any 
certificate in it expires.
+     * Keys without an X.509 certificate chain are ignored, as TLS cannot use 
them. A factory that has lost the keys

Review Comment:
   The interface covers only TLS factories, and the expiry comes from the 
notAfter dates of X.509 certificates. The javadoc now only says that the 
calculation skips keys without such a chain.



##########
modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java:
##########
@@ -0,0 +1,38 @@
+/*
+ * 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.ssl.jetty;
+
+import org.apache.ignite.ssl.AbstractSslContextFactory;
+
+/**
+ * Automatic reload settings of a Jetty SSL context factory that serves HTTPS 
for the HTTP REST endpoint. To change the settings
+ * of a factory, implement this interface in a subclass of Jetty's {@code 
SslContextFactory.Server}, add setters for both
+ * properties, and set them on the factory in the Jetty XML file. A factory 
that does not implement this interface keeps

Review Comment:
   Agreed, the interface needs only the getters. A setter is needed only for a 
property that jetty.xml sets with <Set>; the REST API docs now say so next to 
the jetty.xml example.



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