-
Notifications
You must be signed in to change notification settings - Fork 62
fix(icms): Fix ICMS reports DOWN on NAT closed connection #1214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dmikhaylovnv
wants to merge
6
commits into
main
Choose a base branch
from
fix/nats_closed_connection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f0feb5c
Re-implemented from sratch to be alined with cloud-functions approach
dmikhaylovnv 24130c7
Renaming config nats-enabled to enabled
dmikhaylovnv cdd09d9
Reverting enchancments
dmikhaylovnv d75fa99
Minor adjustments
dmikhaylovnv a81c5a1
Fixing connection creation in managed
dmikhaylovnv 424e3d1
Renaming allowedReconnection to unlimitedReconnects
dmikhaylovnv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -200,4 +200,4 @@ sis: | |
| AWS_REGION: "ncp" | ||
|
|
||
| # NATS Configuration | ||
| NATS_RECONNECT_ALLOWED: "true" | ||
| NATS_UNLIMITED_RECONNECTS: "true" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
295 changes: 295 additions & 0 deletions
295
...agement/icms-core/src/main/java/com/nvidia/icms/configuration/nats/NatsConfiguration.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,295 @@ | ||
| /* | ||
| * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| * | ||
| * Licensed 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 com.nvidia.icms.configuration.nats; | ||
|
|
||
| import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; | ||
|
|
||
| import io.micrometer.core.instrument.MeterRegistry; | ||
| import io.micrometer.tracing.Tracer; | ||
| import io.nats.client.Connection; | ||
| import io.nats.client.Connection.Status; | ||
| import io.nats.client.ConnectionListener.Events; | ||
| import io.nats.client.ErrorListener; | ||
| import io.nats.client.ForceReconnectOptions; | ||
| import io.nats.client.JetStream; | ||
| import io.nats.client.JetStreamManagement; | ||
| import io.nats.client.Nats; | ||
| import io.nats.client.Options; | ||
| import io.nats.client.Statistics; | ||
| import io.nats.client.impl.TracedNatsConnection; | ||
| import java.io.IOException; | ||
| import java.time.Duration; | ||
| import java.util.Arrays; | ||
| import java.util.Collection; | ||
| import java.util.List; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.concurrent.atomic.AtomicInteger; | ||
| import java.util.function.ToDoubleFunction; | ||
| import java.util.function.ToLongFunction; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.apache.commons.lang3.RandomUtils; | ||
| import org.springframework.beans.factory.InitializingBean; | ||
| import org.springframework.context.ApplicationContext; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.context.annotation.Scope; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| @Slf4j | ||
| @Configuration(proxyBeanMethods = false) | ||
| public final class NatsConfiguration { | ||
|
|
||
| private static Connection connect(Options options, Tracer tracer) | ||
| throws IOException, InterruptedException { | ||
| TracedNatsConnection conn = new TracedNatsConnection(options, tracer); | ||
| conn.connect(false); | ||
| return conn; | ||
| } | ||
|
|
||
| @Bean | ||
| @Scope(SCOPE_PROTOTYPE) | ||
| public Connection natsConnection( | ||
| NatsConfigurationProperties natsProperties, | ||
| Tracer tracer) | ||
| throws IOException, InterruptedException { | ||
| if (natsProperties.isEnabled()) { | ||
| var options = createDefaultOptions(natsProperties); | ||
| return connect(options, tracer); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| Options createDefaultOptions(NatsConfigurationProperties natsConfigurationProperties) { | ||
| var flushDuration = natsConfigurationProperties.getForceReconnectFlush().isPositive() ? | ||
| natsConfigurationProperties.getForceReconnectFlush() : Duration.ofSeconds(5); | ||
| var builder = Options.builder() | ||
| .server(natsConfigurationProperties.getNatsUrl()) | ||
| .connectionTimeout(natsConfigurationProperties.getConnectionTimeout()) | ||
| .useDispatcherWithExecutor() | ||
| .errorListener(new LoggingNatsErrorListener()) | ||
| .connectionListener( | ||
| (conn, type) -> { | ||
| log.info("nats connection event {} {}", type, | ||
| conn.getServerInfo()); | ||
| if (type == Events.LAME_DUCK) { | ||
| CompletableFuture.runAsync(() -> { | ||
| try { | ||
| // jitter | ||
| Thread.sleep(RandomUtils.secure().randomInt(0, 5000)); | ||
| // this may cause issues, but hopefully the active force | ||
| // reconnection is a smaller error window than waiting to get | ||
| // booted and detecting it normally. | ||
| log.info("client id {} force reconnecting to nats", | ||
| conn.getServerInfo().getClientId()); | ||
| conn.forceReconnect(ForceReconnectOptions.builder() | ||
| .flush(flushDuration) | ||
| .build()); | ||
| log.info("client id {} reconnected to nats", | ||
| conn.getServerInfo().getClientId()); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| log.warn("client id {} reconnect interrupted", | ||
| conn.getServerInfo().getClientId(), e); | ||
| throw new RuntimeException(e); | ||
| } catch (Exception e) { | ||
| log.warn("client id {} failed to reconnect to nats", | ||
| conn.getServerInfo().getClientId(), e); | ||
| throw new RuntimeException(e); | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
|
dmikhaylovnv marked this conversation as resolved.
|
||
| if (natsConfigurationProperties.getNkeySeed().isPresent()) { | ||
| var authHandler = Nats.staticCredentials(null, | ||
| natsConfigurationProperties.getNkeySeed() | ||
| .get().toCharArray()); | ||
| builder = builder.authHandler(authHandler); | ||
| } | ||
|
|
||
| if (natsConfigurationProperties.getReconnectJitter().isPositive()) { | ||
| Duration reconnectJitter = natsConfigurationProperties.getReconnectJitter(); | ||
| builder.reconnectJitter(reconnectJitter).reconnectJitterTls(reconnectJitter); | ||
| } | ||
|
|
||
| if (natsConfigurationProperties.isUnlimitedReconnects()) { | ||
| builder = builder.maxReconnects(-1); | ||
| } | ||
|
|
||
| if (natsConfigurationProperties.getPingInterval().isPositive()) { | ||
| builder.pingInterval(natsConfigurationProperties.getPingInterval()); | ||
| } else { | ||
| builder.pingInterval(Duration.ofSeconds(5)); | ||
| } | ||
|
|
||
| if (natsConfigurationProperties.getReconnectWait().isPositive()) { | ||
| builder.reconnectWait(natsConfigurationProperties.getReconnectWait()); | ||
| } else { | ||
| builder.reconnectWait(Duration.ofMillis(100)); | ||
| } | ||
|
|
||
| return builder.build(); | ||
| } | ||
|
|
||
| /** | ||
| * Custom error listener for logging NATS errors and exceptions. | ||
| */ | ||
| @Slf4j | ||
| private static class LoggingNatsErrorListener implements ErrorListener { | ||
|
|
||
| /** | ||
| * Logs errors that occur during the NATS connection lifecycle. | ||
| * | ||
| * @param conn The NATS connection where the error occurred. | ||
| * @param error The error message. | ||
| */ | ||
| @Override | ||
| public void errorOccurred(Connection conn, String error) { | ||
| log.error("nats error occurred {} {}", conn.getServerInfo(), error); | ||
| } | ||
|
|
||
| /** | ||
| * Logs exceptions that occur during the NATS connection lifecycle. | ||
| * | ||
| * @param conn The NATS connection where the exception occurred. | ||
| * @param exp The exception instance. | ||
| */ | ||
| @Override | ||
| public void exceptionOccurred(Connection conn, Exception exp) { | ||
| log.error("nats exception occurred {}", conn.getServerInfo(), exp); | ||
| } | ||
| } | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| public static class FixedNatsPool implements AutoCloseable { | ||
|
|
||
| private final Connection[] connections; | ||
| private final JetStream[] jetStreams; | ||
| private final JetStreamManagement[] jetStreamManagements; | ||
| private final AtomicInteger index = new AtomicInteger(); | ||
|
|
||
| public FixedNatsPool(ApplicationContext applicationContext, | ||
| NatsConfigurationProperties natsProperties) throws IOException { | ||
| int processors = Runtime.getRuntime().availableProcessors(); | ||
| int poolSize = natsProperties.isEnabled() ? | ||
| Math.min(processors, natsProperties.getMaxPoolSize()) : 0; | ||
| this.connections = new Connection[poolSize]; | ||
| this.jetStreams = new JetStream[connections.length]; | ||
| this.jetStreamManagements = new JetStreamManagement[connections.length]; | ||
| for (int i = 0; i < connections.length; i++) { | ||
| connections[i] = applicationContext.getBean(Connection.class); | ||
| jetStreams[i] = connections[i].jetStream(); | ||
| jetStreamManagements[i] = connections[i].jetStreamManagement(); | ||
| // force connection use | ||
| connections[i].RTT(); | ||
| } | ||
|
dmikhaylovnv marked this conversation as resolved.
|
||
| } | ||
|
dmikhaylovnv marked this conversation as resolved.
|
||
|
|
||
| @Override | ||
| public void close() throws Exception { | ||
|
dmikhaylovnv marked this conversation as resolved.
|
||
| for (Connection connection : connections) { | ||
| connection.close(); | ||
| } | ||
| } | ||
|
|
||
| private int nextIndex() { | ||
| if (connections.length == 0) { | ||
|
dmikhaylovnv marked this conversation as resolved.
|
||
| throw new IllegalStateException("NATS is not enabled"); | ||
| } | ||
| return Math.floorMod(index.getAndIncrement(), connections.length); | ||
| } | ||
|
|
||
| public Connection borrowConnection() { | ||
| return connections[nextIndex()]; | ||
| } | ||
|
|
||
| public JetStream borrowJetStream() { | ||
| return jetStreams[nextIndex()]; | ||
| } | ||
|
|
||
| public JetStreamManagement borrowJetStreamManagement() { | ||
| return jetStreamManagements[nextIndex()]; | ||
| } | ||
|
|
||
| public boolean healthy() { | ||
| for (Connection connection : connections) { | ||
| if (connection.getStatus() != Status.CONNECTED) { | ||
| log.warn("unhealthy nats connection {}", connection.getServerInfo()); | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| @Configuration(proxyBeanMethods = false) | ||
| static class NatsMetricsConfiguration implements InitializingBean { | ||
|
|
||
| private final Collection<Statistics> statistics; | ||
| private final MeterRegistry meterRegistry; | ||
|
|
||
| NatsMetricsConfiguration(FixedNatsPool fixedNatsPool, MeterRegistry meterRegistry) { | ||
| this.meterRegistry = meterRegistry; | ||
| this.statistics = Arrays.stream(fixedNatsPool.connections) | ||
| .map(Connection::getStatistics) | ||
| .toList(); | ||
| } | ||
|
|
||
| @Override | ||
| public void afterPropertiesSet() { | ||
| meterRegistry.more().counter("nats.pings", List.of(), | ||
| statistics, sumProperties(Statistics::getPings)); | ||
| meterRegistry.more().counter("nats.reconnects", List.of(), | ||
| statistics, sumProperties(Statistics::getReconnects)); | ||
| meterRegistry.more().counter("nats.dropped", List.of(), | ||
| statistics, sumProperties(Statistics::getDroppedCount)); | ||
| meterRegistry.more().counter("nats.oks", List.of(), | ||
| statistics, sumProperties(Statistics::getOKs)); | ||
| meterRegistry.more().counter("nats.errs", List.of(), | ||
| statistics, sumProperties(Statistics::getErrs)); | ||
| meterRegistry.more().counter("nats.exceptions", List.of(), | ||
| statistics, sumProperties(Statistics::getExceptions)); | ||
| meterRegistry.more().counter("nats.requests.sent", List.of(), | ||
| statistics, sumProperties(Statistics::getRequestsSent)); | ||
| meterRegistry.more().counter("nats.replies.received", List.of(), statistics, | ||
| sumProperties(Statistics::getRepliesReceived)); | ||
| meterRegistry.more().counter("nats.replies.received.duplicate", List.of(), statistics, | ||
| sumProperties(Statistics::getDuplicateRepliesReceived)); | ||
| meterRegistry.more().counter("nats.replies.received.orphan", List.of(), statistics, | ||
| sumProperties(Statistics::getOrphanRepliesReceived)); | ||
| meterRegistry.more().counter("nats.msgs.in", List.of(), | ||
| statistics, sumProperties(Statistics::getInMsgs)); | ||
| meterRegistry.more().counter("nats.msgs.out", List.of(), | ||
| statistics, sumProperties(Statistics::getOutMsgs)); | ||
| meterRegistry.more().counter("nats.bytes.in", List.of(), | ||
| statistics, sumProperties(Statistics::getInBytes)); | ||
| meterRegistry.more().counter("nats.bytes.out", List.of(), | ||
| statistics, sumProperties(Statistics::getOutBytes)); | ||
| meterRegistry.more().counter("nats.flush", List.of(), | ||
| statistics, sumProperties(Statistics::getFlushCounter)); | ||
| meterRegistry.gauge("nats.requests.outstanding", statistics, | ||
| sumProperties(Statistics::getOutstandingRequests)); | ||
| } | ||
|
|
||
| private static <T> ToDoubleFunction<Collection<T>> sumProperties( | ||
| ToLongFunction<T> propertyExtractor) { | ||
| return collection -> collection.stream().mapToLong(propertyExtractor).sum(); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.