This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new a3ef92e4403a CAMEL-27370: camel-smb - when the server goes away, the
next poll hangs in disconnect and blocks shutdown (#30596)
a3ef92e4403a is described below
commit a3ef92e4403a00e6d99522d5aaa78486c0259507
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 22 12:24:42 2026 +0100
CAMEL-27370: camel-smb - when the server goes away, the next poll hangs in
disconnect and blocks shutdown (#30596)
smbj waits up to its transact timeout (60 seconds by default) for the
server to answer the close of the share, and again for the logoff of
the session. When the server went away, the disconnect after the failed
poll, and the stop of the route, waited minutes. The disconnect now runs
in a thread of its own and waits at most 2 seconds; the rest completes
in the background, and the next connect uses a new SMB client, as smbj
would hand out the unanswered connection again.
smbj closes the directories it holds a lease on when the connection
closes, after the share, so each logged a WARN "Directory close failed
... DiskShare has already been closed" on every stop. They are now
closed first, while the share is open.
- camel-smb - the SMB client that a disconnect gives up waiting on is
closed once its connection is
When the disconnect timed out, the SMB client was replaced by a new one and
the old one was never closed. It is now handed to the background disconnect
thread, which closes it after the share, the session and the connection (or
closed at once when that thread completed meanwhile). The javadoc of close
says it runs in the background and never throws.
- camel-smb - complete a truncated comment
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
components/camel-smb/pom.xml | 6 +
.../apache/camel/component/smb/SmbOperations.java | 100 ++++++++++++++-
.../component/smb/SmbOperationsDisconnectTest.java | 111 ++++++++++++++++
.../camel/component/smb/SmbServerGoneIT.java | 140 +++++++++++++++++++++
4 files changed, 352 insertions(+), 5 deletions(-)
diff --git a/components/camel-smb/pom.xml b/components/camel-smb/pom.xml
index 6d76a5117fd8..8a77ecf480b3 100644
--- a/components/camel-smb/pom.xml
+++ b/components/camel-smb/pom.xml
@@ -77,6 +77,12 @@
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>${mockito-version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
diff --git
a/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbOperations.java
b/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbOperations.java
index 3868dd030b36..d6c0be0bbafd 100644
---
a/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbOperations.java
+++
b/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbOperations.java
@@ -23,6 +23,8 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.EnumSet;
import java.util.Iterator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import com.hierynomus.msdtyp.AccessMask;
@@ -66,6 +68,13 @@ public class SmbOperations implements SmbFileOperations {
private static final Logger LOG =
LoggerFactory.getLogger(SmbOperations.class);
+ /**
+ * How long a disconnect waits for the server to answer the close of the
share and the logoff of the session. smbj
+ * waits up to its transact timeout (60 seconds by default) for each of
them, so a server that went away would hold
+ * the poll, and the stop of the route, for minutes. The disconnect
completes in the background after this time.
+ */
+ static final long DISCONNECT_WAIT_MILLIS = 2000;
+
private final SmbConfiguration configuration;
private SmbEndpoint endpoint;
private boolean loggedIn;
@@ -76,7 +85,16 @@ public class SmbOperations implements SmbFileOperations {
public SmbOperations(SmbConfiguration configuration) {
this.configuration = configuration;
- this.smbClient = configuration == null ? new SMBClient() : new
SMBClient(configuration.createSmbConfig());
+ this.smbClient = createSmbClient();
+ }
+
+ SmbOperations(SmbConfiguration configuration, SMBClient smbClient) {
+ this.configuration = configuration;
+ this.smbClient = smbClient;
+ }
+
+ private SMBClient createSmbClient() {
+ return configuration == null ? new SMBClient() : new
SMBClient(configuration.createSmbConfig());
}
@Override
@@ -144,13 +162,74 @@ public class SmbOperations implements SmbFileOperations {
@Override
public void disconnect() throws GenericFileOperationFailedException {
loggedIn = false;
+ DiskShare currentShare = share;
+ Session currentSession = session;
+ Connection currentConnection = connection;
+ share = null;
+ session = null;
+ connection = null;
+ if (currentShare == null && currentSession == null &&
currentConnection == null) {
+ return;
+ }
+ if (endpoint == null) {
+ close(currentConnection, currentSession, currentShare);
+ return;
+ }
+ // the SMB client of the connection, when the disconnect does not wait
for it: closed once the connection is
+ // closed
+ AtomicReference<SMBClient> abandonedClient = new AtomicReference<>();
+ AtomicBoolean closed = new AtomicBoolean();
+ Thread disconnector =
endpoint.getCamelContext().getExecutorServiceManager()
+ .newThread("SmbDisconnect", () -> {
+ close(currentConnection, currentSession, currentShare);
+ closed.set(true);
+ close(abandonedClient.getAndSet(null));
+ });
+ disconnector.start();
+ try {
+ disconnector.join(DISCONNECT_WAIT_MILLIS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ if (disconnector.isAlive()) {
+ LOG.warn("Disconnecting from {}:{} waits for the server, which
does not answer."
+ + " The disconnect completes in the background.",
+ configuration.getHostname(), configuration.getPort());
+ // the SMB client hands out its open connection again to the next
connect, until the connection is closed
+ if (smbClient != null) {
+ abandonedClient.set(smbClient);
+ smbClient = createSmbClient();
+ if (closed.get()) {
+ // the background thread completed meanwhile, and may not
have seen the client
+ close(abandonedClient.getAndSet(null));
+ }
+ }
+ }
+ }
+
+ /**
+ * Closes the share, the session and the connection, in this order. {@link
#disconnect()} calls it from a background
+ * thread, as each close can wait for the server to answer. It never
throws: the failures are ignored (the leased
+ * directories are logged at DEBUG), so a server that went away cannot
keep the session or the connection open.
+ */
+ static void close(Connection connection, Session session, DiskShare share)
{
+ if (connection != null && share != null && share.isConnected()) {
+ // smbj closes the directories it holds a lease on (the listings
it caches) when the connection closes,
+ // after the share: closed then, each logs a WARN that the share
has already been closed. So close them
+ // first, while the share is open.
+ try {
+ connection.getLeaseManager().close();
+ } catch (Exception e) {
+ LOG.debug("Error closing the leased directories of {} due to:
{}. This exception is ignored.", share,
+ e.getMessage(), e);
+ }
+ }
if (share != null) {
try {
share.close();
- } catch (IOException e) {
+ } catch (Exception e) {
// ignore
}
- share = null;
}
if (session != null) {
try {
@@ -158,7 +237,6 @@ public class SmbOperations implements SmbFileOperations {
} catch (Exception e) {
// ignore
}
- session = null;
}
if (connection != null) {
try {
@@ -172,7 +250,19 @@ public class SmbOperations implements SmbFileOperations {
} catch (Exception e) {
// ignore
}
- connection = null;
+ }
+ }
+
+ /**
+ * Closes the SMB client and the connections it still has, ignoring
failures.
+ */
+ private static void close(SMBClient client) {
+ if (client != null) {
+ try {
+ client.close();
+ } catch (Exception e) {
+ LOG.debug("Error closing the SMB client due to: {}. This
exception is ignored.", e.getMessage(), e);
+ }
}
}
diff --git
a/components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbOperationsDisconnectTest.java
b/components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbOperationsDisconnectTest.java
new file mode 100644
index 000000000000..d4fc08aaf7fe
--- /dev/null
+++
b/components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbOperationsDisconnectTest.java
@@ -0,0 +1,111 @@
+/*
+ * 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.camel.component.smb;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import com.hierynomus.smbj.SMBClient;
+import com.hierynomus.smbj.auth.AuthenticationContext;
+import com.hierynomus.smbj.connection.Connection;
+import com.hierynomus.smbj.connection.LeaseManager;
+import com.hierynomus.smbj.session.Session;
+import com.hierynomus.smbj.share.DiskShare;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.camel.util.StopWatch;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Disconnecting from a server that does not answer no longer holds the poll
and the stop of the route, and does not
+ * leak the SMB client it gives up on; the directories smbj holds a lease on
are closed while the share is open.
+ */
+class SmbOperationsDisconnectTest extends CamelTestSupport {
+
+ private final SMBClient client = mock(SMBClient.class);
+ private final Connection connection = mock(Connection.class);
+ private final LeaseManager leaseManager = mock(LeaseManager.class);
+ private final Session session = mock(Session.class);
+ private final DiskShare share = mock(DiskShare.class);
+ private SmbOperations operations;
+
+ @BeforeEach
+ void connect() throws Exception {
+ when(client.connect(anyString(), anyInt())).thenReturn(connection);
+ when(connection.isConnected()).thenReturn(true);
+
when(connection.authenticate(any(AuthenticationContext.class))).thenReturn(session);
+ when(connection.getLeaseManager()).thenReturn(leaseManager);
+ when(session.connectShare("share")).thenReturn(share);
+ when(share.isConnected()).thenReturn(true);
+
+ SmbEndpoint endpoint =
context.getEndpoint("smb:localhost/share?username=scott&password=tiger",
SmbEndpoint.class);
+ operations = new SmbOperations(endpoint.getConfiguration(), client);
+ operations.setEndpoint(endpoint);
+ operations.connect(endpoint.getConfiguration(), null);
+ assertTrue(operations.isConnected());
+ }
+
+ @Test
+ void closesLeasedDirectoriesBeforeTheShare() throws Exception {
+ operations.disconnect();
+
+ InOrder order = inOrder(leaseManager, share, session, connection);
+ order.verify(leaseManager).close();
+ order.verify(share).close();
+ order.verify(session).close();
+ order.verify(connection).close();
+ // the client is used again for the next connect
+ verify(client, never()).close();
+ }
+
+ @Test
+ void serverThatDoesNotAnswer() throws Exception {
+ // the close of the share waits for an answer, as smbj does up to its
transact timeout
+ CountDownLatch answer = new CountDownLatch(1);
+ doAnswer(invocation -> answer.await(1,
TimeUnit.MINUTES)).when(share).close();
+
+ StopWatch watch = new StopWatch();
+ operations.disconnect();
+ long taken = watch.taken();
+
+ assertTrue(taken < SmbOperations.DISCONNECT_WAIT_MILLIS + 5000,
"disconnect took " + taken + " ms");
+ assertFalse(operations.isConnected());
+ verify(client, never()).close();
+
+ // the disconnect completes in the background once the server answers,
and then closes the abandoned client
+ answer.countDown();
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(() ->
verify(client).close());
+ InOrder order = inOrder(session, connection, client);
+ order.verify(session).close();
+ order.verify(connection).close();
+ order.verify(client).close();
+ }
+}
diff --git
a/components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbServerGoneIT.java
b/components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbServerGoneIT.java
new file mode 100644
index 000000000000..f4cb599f247b
--- /dev/null
+++
b/components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbServerGoneIT.java
@@ -0,0 +1,140 @@
+/*
+ * 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.camel.component.smb;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+
+import com.hierynomus.smbj.SmbConfig;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.infra.smb.services.SmbService;
+import org.apache.camel.test.infra.smb.services.SmbServiceFactory;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.camel.util.StopWatch;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.testcontainers.containers.GenericContainer;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+/**
+ * Stopping a route whose SMB server went away does not wait for the server to
answer the disconnect, and stopping a
+ * route logs no WARN for the directories smbj holds a lease on. Uses a server
of its own, as it pauses it.
+ */
+class SmbServerGoneIT extends CamelTestSupport {
+
+ // a server of its own, as the test pauses it
+ @RegisterExtension
+ static SmbService service = SmbServiceFactory.createService();
+
+ private static final long SMB_TIMEOUT_MILLIS = 10000;
+
+ private final List<String> warnings = new CopyOnWriteArrayList<>();
+ private final AbstractAppender appender
+ = new AbstractAppender("SmbServerGoneIT", null, null, true,
Property.EMPTY_ARRAY) {
+ @Override
+ public void append(LogEvent event) {
+ if (event.getLevel().isMoreSpecificThan(Level.WARN)) {
+ warnings.add(event.getLoggerName() + ": " +
event.getMessage().getFormattedMessage());
+ }
+ }
+ };
+
+ @Override
+ public boolean isUseRouteBuilder() {
+ return false;
+ }
+
+ @BeforeEach
+ void captureWarnings() {
+ appender.start();
+ LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
+ ctx.getConfiguration().getRootLogger().addAppender(appender,
Level.WARN, null);
+ ctx.updateLoggers();
+ }
+
+ @AfterEach
+ void removeAppender() {
+ LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
+
ctx.getConfiguration().getRootLogger().removeAppender(appender.getName());
+ ctx.updateLoggers();
+ appender.stop();
+ }
+
+ @Test
+ void stopLogsNoWarnForLeasedDirectories() throws Exception {
+ // noop=true: the directory does not change, so smbj keeps the lease
on it until the route stops
+ startRoute("leased", "noop=true");
+
+ context.stop();
+
+ assertTrue(warnings.isEmpty(), "warnings: " + warnings);
+ }
+
+ @Test
+ void stopWhenTheServerDoesNotAnswer() throws Exception {
+ assumeTrue(service instanceof
SmbServiceFactory.SmbLocalContainerService, "needs a local container to pause");
+ GenericContainer<?> container =
((SmbServiceFactory.SmbLocalContainerService) service).getContainer();
+
+ startRoute("gone", "delete=true");
+
container.getDockerClient().pauseContainerCmd(container.getContainerId()).exec();
+ try {
+ StopWatch watch = new StopWatch();
+ context.stop();
+ long taken = watch.taken();
+
+ // a poll that is running waits up to the timeout of the SmbConfig
for the server; before, the disconnect
+ // then waited that long again for the close of the share, and
again for the logoff of the session
+ assertTrue(taken < SMB_TIMEOUT_MILLIS +
SmbOperations.DISCONNECT_WAIT_MILLIS + 3000,
+ "the stop took " + taken + " ms");
+ } finally {
+
container.getDockerClient().unpauseContainerCmd(container.getContainerId()).exec();
+ }
+ }
+
+ private void startRoute(String directory, String options) throws Exception
{
+ context.getRegistry().bind("smbConfig", SmbConfig.builder()
+ .withTimeout(SMB_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
+ .build());
+ String uri =
String.format("smb:%s/%s/%s?username=%s&password=%s&delay=200&initialDelay=0&%s",
+ service.address(), service.shareName(), directory,
service.username(), service.password(), options);
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).to("mock:result");
+ }
+ });
+ context.start();
+
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedMessageCount(1);
+ template.sendBodyAndHeader(uri, "Hello World", Exchange.FILE_NAME,
"hello.txt");
+ mock.assertIsSatisfied();
+ }
+}