Skip to content

Commit e1fbc4f

Browse files
Set TCP keepalive idle time so idle connections survive NAT
TCP connections with keepalive enabled used the OS idle time before the first probe, typically 2 hours. That is far longer than the idle timeouts of common NAT devices and load balancers (4 minutes for an Azure load balancer, 350 seconds for an AWS NAT gateway), which drop idle connections silently. The next read on such a connection fails with errors like the "Connection timed out" reported in #495. TCP Listener and TCP Sender sockets can now get a shorter idle time wherever they already enable keepalive: when "Keep Connection Open" is on, and always for TCP Sender server mode. The new oie.tcp.keepalive.idle system property sets the idle time in seconds and defaults to 120. The "Keep Connection Open" tooltips on both connectors now mention it. When the TCP plugin starts with the server, it reads the OS idle time (net.ipv4.tcp_keepalive_time on Linux) from a new socket and decides once how keepalive sockets are handled: - OS value higher than the property: each keepalive socket gets TCP_KEEPIDLE set to the property value. - OS value equal or lower: sockets are left alone and keep the OS value, so an admin who already lowered it keeps their setting. - OS value can't be read: sockets get the property value. - Property 0 or less, or TCP_KEEPIDLE not supported (such as Windows on a JDK without JDK-8308593): sockets are left alone. The decision isn't revisited until the engine restarts. If the OS value changes while the engine is running, sockets that get the property value keep getting it, even if the OS value drops below it. Sockets that are left alone use the OS value, so they follow the change, including a raise above the property value. This is a system property rather than a mirth.properties setting because the TCP connector is a plugin. No plugin has its own key in mirth.properties, and ConfigurationController has no generic accessor for its values, so reading one would mean adding TCP-specific code to core. WebServiceDispatcher reads http.maxRedirects the same way. An invalid property value logs an error and falls back to 120. If the OS rejects the value when it's set on a socket, the first failure logs an error and later ones log at DEBUG. Both are errors rather than warnings because the default log4j configuration only shows ERROR for this logger, and either one means the configured idle time isn't in effect. The decision is logged once at INFO, with the OS value when it can be read and what a later OS change does; the default log4j configuration doesn't show it. All of this is logged at server startup, before any TCP connection, because TcpServicePlugin.start() loads SocketUtil. Keepalive is explicitly disabled again when "Keep Connection Open" is off, as before. Behavior change: with Linux's default probe interval and count (75 seconds, 9 probes), a peer that disappears from an idle connection is now detected after about 13 minutes instead of about 2 hours 11 minutes. Issue: #495 Co-authored-by: Tony Germano <tony@germano.name> Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Mitch Gaffigan <mitch.gaffigan@comcast.net> Signed-off-by: Tony Germano <tony@germano.name>
1 parent 6d348a0 commit e1fbc4f

8 files changed

Lines changed: 145 additions & 7 deletions

File tree

‎client/src/main/java/com/mirth/connect/connectors/tcp/TcpListener.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ private void initToolTips() {
505505
receiveTimeoutField.setToolTipText("The amount of time, in milliseconds, to wait without receiving a message before closing a connection.");
506506
bufferSizeField.setToolTipText("<html>Use larger values for larger messages, and smaller values <br>for smaller messages. Generally, the default value is fine.</html>");
507507

508-
toolTipText = "<html>Select No to close the listening socket after a received message has finished processing.<br/>Otherwise the socket will remain open until the sending system closes it. In that case,<br/>messages will only be processed if data is received and either the receive timeout is reached,<br/>the client closes the socket, or an end of message byte sequence has been detected.</html>";
508+
toolTipText = "<html>Select No to close the listening socket after a received message has finished processing.<br/>Otherwise the socket will remain open until the sending system closes it. In that case,<br/>messages will only be processed if data is received and either the receive timeout is reached,<br/>the client closes the socket, or an end of message byte sequence has been detected.<br/><br/>With Yes, TCP keepalive probes start after the connection has been idle for 120 seconds,<br/>or for the server's OS keepalive time if that is lower. The server's oie.tcp.keepalive.idle<br/>system property changes the 120 seconds.</html>";
509509
keepConnectionOpenYesRadio.setToolTipText(toolTipText);
510510
keepConnectionOpenNoRadio.setToolTipText(toolTipText);
511511

‎client/src/main/java/com/mirth/connect/connectors/tcp/TcpSender.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ public void actionPerformed(ActionEvent evt) {
440440
keepConnectionOpenYesRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
441441
keepConnectionOpenGroup.add(keepConnectionOpenYesRadio);
442442
keepConnectionOpenYesRadio.setText("Yes");
443-
keepConnectionOpenYesRadio.setToolTipText("<html>Select Yes to keep the connection to the host open across multiple messages.<br>Select No to immediately the close the connection to the host after sending each message.</html>");
443+
keepConnectionOpenYesRadio.setToolTipText("<html>Select Yes to keep the connection to the host open across multiple messages.<br>Select No to immediately the close the connection to the host after sending each message.<br><br>With Yes, TCP keepalive probes start after the connection has been idle for 120 seconds,<br>or for the server's OS keepalive time if that is lower. The server's oie.tcp.keepalive.idle<br>system property changes the 120 seconds.</html>");
444444
keepConnectionOpenYesRadio.setMargin(new Insets(0, 0, 0, 0));
445445
keepConnectionOpenYesRadio.addActionListener(new ActionListener() {
446446
public void actionPerformed(ActionEvent evt) {
@@ -452,7 +452,7 @@ public void actionPerformed(ActionEvent evt) {
452452
keepConnectionOpenNoRadio.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
453453
keepConnectionOpenGroup.add(keepConnectionOpenNoRadio);
454454
keepConnectionOpenNoRadio.setText("No");
455-
keepConnectionOpenNoRadio.setToolTipText("<html>Select Yes to keep the connection to the host open across multiple messages.<br>Select No to immediately the close the connection to the host after sending each message.</html>");
455+
keepConnectionOpenNoRadio.setToolTipText("<html>Select Yes to keep the connection to the host open across multiple messages.<br>Select No to immediately the close the connection to the host after sending each message.<br><br>With Yes, TCP keepalive probes start after the connection has been idle for 120 seconds,<br>or for the server's OS keepalive time if that is lower. The server's oie.tcp.keepalive.idle<br>system property changes the 120 seconds.</html>");
456456
keepConnectionOpenNoRadio.setMargin(new Insets(0, 0, 0, 0));
457457
keepConnectionOpenNoRadio.addActionListener(new ActionListener() {
458458
public void actionPerformed(ActionEvent evt) {

‎server/conf/custom.vmoptions‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@
2222
#
2323
# Any lines which do not match the special directives above will be passed through directly as
2424
# arguments to the java binary.
25+
#
26+
# Engine options set with -D:
27+
#
28+
# -Doie.tcp.keepalive.idle=<seconds>
29+
# : seconds a TCP connection with keepalive enabled can sit idle before the first
30+
# : keepalive probe is sent. Defaults to 120, which keeps idle connections alive
31+
# : through NAT devices and load balancers. Only lowers the OS default; a lower OS
32+
# : setting is kept. 0 or less always uses the OS default.
2533

2634

2735

‎server/src/main/java/com/mirth/connect/connectors/tcp/SocketUtil.java‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,28 @@
1313
import java.net.InetAddress;
1414
import java.net.InetSocketAddress;
1515
import java.net.Socket;
16+
import java.net.SocketException;
1617
import java.net.UnknownHostException;
18+
import java.util.Optional;
19+
import java.util.concurrent.atomic.AtomicBoolean;
1720

1821
import org.apache.commons.lang3.StringUtils;
22+
import org.apache.logging.log4j.LogManager;
23+
import org.apache.logging.log4j.Logger;
1924

2025
import com.mirth.connect.util.TcpUtil;
2126

27+
import jdk.net.ExtendedSocketOptions;
28+
2229
public class SocketUtil {
2330

31+
private static final Logger logger = LogManager.getLogger(SocketUtil.class);
32+
33+
static final String KEEPALIVE_IDLE_PROPERTY = "oie.tcp.keepalive.idle";
34+
static final int DEFAULT_KEEPALIVE_IDLE = 120;
35+
private static final Optional<Integer> KEEPALIVE_IDLE = initKeepAliveIdle();
36+
private static final AtomicBoolean keepAliveIdleFailed = new AtomicBoolean();
37+
2438
public static Socket createSocket(TcpConfiguration configuration) throws UnknownHostException, IOException {
2539
return createSocket(configuration, null);
2640
}
@@ -67,6 +81,72 @@ public static void connectSocket(Socket socket, String host, int port, int timeo
6781
socket.connect(new InetSocketAddress(InetAddress.getByName(TcpUtil.getFixedHost(host)), port), timeout);
6882
}
6983

84+
/**
85+
* Loads this class, which decides and logs the keepalive idle time. Called when the TCP plugin
86+
* starts so the decision, and any error in the oie.tcp.keepalive.idle system property, is
87+
* logged at server startup instead of at the first TCP connection.
88+
*/
89+
public static void init() {}
90+
91+
/**
92+
* Enables or disables TCP keepalive on a socket. When enabling, also lowers the idle time before
93+
* the first keepalive probe to the oie.tcp.keepalive.idle system property (in seconds) if the
94+
* OS default was higher when this class was loaded and the socket supports it. A value of 0 or
95+
* less leaves the OS default.
96+
*/
97+
public static void setKeepAlive(Socket socket, boolean keepAlive) throws SocketException {
98+
socket.setKeepAlive(keepAlive);
99+
100+
if (keepAlive && KEEPALIVE_IDLE.isPresent() && socket.supportedOptions().contains(ExtendedSocketOptions.TCP_KEEPIDLE)) {
101+
Integer idle = KEEPALIVE_IDLE.get();
102+
try {
103+
socket.setOption(ExtendedSocketOptions.TCP_KEEPIDLE, idle);
104+
} catch (IOException | IllegalArgumentException e) {
105+
if (keepAliveIdleFailed.compareAndSet(false, true)) {
106+
logger.error("Failed to set TCP_KEEPIDLE to {} seconds; using the OS default. Further failures will be logged at DEBUG.", idle, e);
107+
} else {
108+
logger.debug("Failed to set TCP_KEEPIDLE to {} seconds.", idle, e);
109+
}
110+
}
111+
}
112+
}
113+
114+
private static Optional<Integer> initKeepAliveIdle() {
115+
int idle = DEFAULT_KEEPALIVE_IDLE;
116+
String value = System.getProperty(KEEPALIVE_IDLE_PROPERTY);
117+
if (value != null) {
118+
try {
119+
idle = Integer.parseInt(value.trim());
120+
} catch (NumberFormatException e) {
121+
logger.error("Invalid value '{}' for {}; using {} seconds.", value, KEEPALIVE_IDLE_PROPERTY, DEFAULT_KEEPALIVE_IDLE);
122+
}
123+
}
124+
125+
if (idle <= 0) {
126+
logger.info("TCP connectors use the OS keepalive idle time; {} is {}.", KEEPALIVE_IDLE_PROPERTY, idle);
127+
return Optional.empty();
128+
}
129+
130+
try (Socket socket = new Socket()) {
131+
if (!socket.supportedOptions().contains(ExtendedSocketOptions.TCP_KEEPIDLE)) {
132+
logger.info("TCP connectors use the OS keepalive idle time; TCP_KEEPIDLE is not supported.");
133+
return Optional.empty();
134+
}
135+
136+
int osIdle = socket.getOption(ExtendedSocketOptions.TCP_KEEPIDLE);
137+
if (osIdle <= idle) {
138+
logger.info("TCP connectors use the OS keepalive idle time; its current value of {} seconds is not higher than {} ({} seconds). Later changes to the OS value still apply, but {} is not compared again until the server restarts.", osIdle, KEEPALIVE_IDLE_PROPERTY, idle, KEEPALIVE_IDLE_PROPERTY);
139+
return Optional.empty();
140+
}
141+
142+
logger.info("TCP connectors use a keepalive idle time of {} seconds instead of the current OS value of {} seconds. Later changes to the OS value are ignored until the server restarts.", idle, osIdle);
143+
} catch (IOException e) {
144+
logger.info("TCP connectors use a keepalive idle time of {} seconds; the current OS value could not be read. Later changes to the OS value are ignored until the server restarts.", idle);
145+
}
146+
147+
return Optional.of(idle);
148+
}
149+
70150
public static void closeSocket(Socket socket) throws IOException {
71151
if (socket != null) {
72152
/*

‎server/src/main/java/com/mirth/connect/connectors/tcp/TcpDispatcher.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ public Response send(ConnectorProperties connectorProperties, ConnectorMessage m
376376
socket.setReceiveBufferSize(bufferSize);
377377
socket.setSendBufferSize(bufferSize);
378378
socket.setSoTimeout(responseTimeout);
379-
socket.setKeepAlive(tcpDispatcherProperties.isKeepConnectionOpen());
379+
SocketUtil.setKeepAlive(socket, tcpDispatcherProperties.isKeepConnectionOpen());
380380

381381
eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.CONNECTED, SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket), true));
382382
}
@@ -810,7 +810,7 @@ private void initSocket(Socket socket) throws SocketException {
810810
socket.setReceiveBufferSize(bufferSize);
811811
socket.setSendBufferSize(bufferSize);
812812
socket.setSoTimeout(responseTimeout);
813-
socket.setKeepAlive(true);
813+
SocketUtil.setKeepAlive(socket, true);
814814
socket.setReuseAddress(true);
815815
socket.setTcpNoDelay(true);
816816
}

‎server/src/main/java/com/mirth/connect/connectors/tcp/TcpReceiver.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1067,7 +1067,7 @@ private void initSocket(Socket socket) throws SocketException {
10671067
socket.setReceiveBufferSize(bufferSize);
10681068
socket.setSendBufferSize(bufferSize);
10691069
socket.setSoTimeout(timeout);
1070-
socket.setKeepAlive(connectorProperties.isKeepConnectionOpen());
1070+
SocketUtil.setKeepAlive(socket, connectorProperties.isKeepConnectionOpen());
10711071
socket.setReuseAddress(true);
10721072
socket.setTcpNoDelay(true);
10731073
}

‎server/src/main/java/com/mirth/connect/connectors/tcp/TcpServicePlugin.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ public String getPluginPointName() {
2525
}
2626

2727
@Override
28-
public void start() {}
28+
public void start() {
29+
SocketUtil.init();
30+
}
2931

3032
@Override
3133
public void stop() {}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// SPDX-License-Identifier: MPL-2.0
2+
// SPDX-FileCopyrightText: 2026 Tony Germano <tony@germano.name>
3+
package com.mirth.connect.connectors.tcp;
4+
5+
import static org.junit.Assert.assertEquals;
6+
import static org.junit.Assert.assertFalse;
7+
import static org.junit.Assert.assertNull;
8+
import static org.junit.Assert.assertTrue;
9+
10+
import java.net.Socket;
11+
12+
import org.junit.Assume;
13+
import org.junit.Test;
14+
15+
import jdk.net.ExtendedSocketOptions;
16+
17+
public class SocketUtilTest {
18+
19+
@Test
20+
public void setKeepAliveEnablesKeepAliveAndCapsIdle() throws Exception {
21+
assertNull("Test expects " + SocketUtil.KEEPALIVE_IDLE_PROPERTY + " to be unset", System.getProperty(SocketUtil.KEEPALIVE_IDLE_PROPERTY));
22+
23+
try (Socket socket = new Socket()) {
24+
Assume.assumeTrue(socket.supportedOptions().contains(ExtendedSocketOptions.TCP_KEEPIDLE));
25+
int osIdle = socket.getOption(ExtendedSocketOptions.TCP_KEEPIDLE);
26+
27+
SocketUtil.setKeepAlive(socket, true);
28+
29+
assertTrue(socket.getKeepAlive());
30+
assertEquals(Math.min(osIdle, SocketUtil.DEFAULT_KEEPALIVE_IDLE), (int) socket.getOption(ExtendedSocketOptions.TCP_KEEPIDLE));
31+
}
32+
}
33+
34+
@Test
35+
public void setKeepAliveDisablesKeepAliveAndLeavesIdle() throws Exception {
36+
try (Socket socket = new Socket()) {
37+
socket.setKeepAlive(true);
38+
Integer idle = socket.supportedOptions().contains(ExtendedSocketOptions.TCP_KEEPIDLE) ? socket.getOption(ExtendedSocketOptions.TCP_KEEPIDLE) : null;
39+
40+
SocketUtil.setKeepAlive(socket, false);
41+
42+
assertFalse(socket.getKeepAlive());
43+
if (idle != null) {
44+
assertEquals(idle, socket.getOption(ExtendedSocketOptions.TCP_KEEPIDLE));
45+
}
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)