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 cb01d9fe0ef6 CAMEL-27087: camel-coap - an observe consumer releases
the endpoint of its client when it stops (#30312)
cb01d9fe0ef6 is described below
commit cb01d9fe0ef63ec1a8c6070308631bc7b563bf8a
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 18 15:04:03 2026 +0530
CAMEL-27087: camel-coap - an observe consumer releases the endpoint of its
client when it stops (#30312)
The observe consumer (observe=true) creates its client with
CoAPEndpoint.createCoapClient, which gives the client its own Californium
endpoint: a bound UDP socket (or a DTLS / TCP connector) with its receiver
and
sender threads. On stop it cancelled the observation and shut the client
down,
which does not destroy that endpoint, so every stop of the route (or of the
consumer) left a socket and its threads behind. CAMEL-26049 fixed the same
leak
in the producer and left the consumer out, as the endpoint carries the
cancel
of the observation (CAMEL-25742).
The stop now waits for the answer to that cancel (the response without the
observe option, or an error), at most 5 seconds, and then destroys the
endpoint of the client. Nothing is waited for when no cancel is sent (no
relation, or a relation that was already cancelled).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../java/org/apache/camel/coap/CoAPObserver.java | 55 +++++++++++++--
.../coap/CoAPObserverStopDestroysEndpointTest.java | 81 ++++++++++++++++++++++
2 files changed, 131 insertions(+), 5 deletions(-)
diff --git
a/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPObserver.java
b/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPObserver.java
index 7b2c973193a4..dc95f88cf595 100644
---
a/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPObserver.java
+++
b/components/camel-coap/src/main/java/org/apache/camel/coap/CoAPObserver.java
@@ -17,6 +17,8 @@
package org.apache.camel.coap;
import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -27,11 +29,18 @@ import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapHandler;
import org.eclipse.californium.core.CoapObserveRelation;
import org.eclipse.californium.core.CoapResponse;
+import org.eclipse.californium.core.network.Endpoint;
/**
* The CoAP observer.
*/
public class CoAPObserver extends DefaultConsumer implements CoapHandler {
+ // how long a stop waits for the answer to the cancel of the observation,
before it releases the endpoint of the client
+ // (the wait only runs out when no answer comes, such as when the server
cannot be reached: then each stop of an
+ // observe consumer takes up to this long, one after the other on a
context shutdown; the wait stays in the stop so
+ // that the endpoint is released before the stop returns, also when the
JVM exits after it)
+ private static final long CANCEL_TIMEOUT_MILLIS = 5000;
+
private final CoAPEndpoint endpoint;
// guards client and observation: onError() runs on a Californium thread
and observes again, which must not race
// doStop(), or the new observation is not cancelled (the server keeps
notifying it) or the client is gone
@@ -79,20 +88,34 @@ public class CoAPObserver extends DefaultConsumer
implements CoapHandler {
protected void doStop() throws Exception {
// cancel the observation, or the server keeps sending notifications
to this consumer after it was stopped, and
// a route that is started again then gets every notification twice
(once from the stopped consumer)
+ Observation current;
+ CoapClient stopped;
lock.lock();
try {
- Observation current = observation;
+ current = observation;
observation = null;
if (current != null) {
current.cancel();
}
- if (client != null) {
- client.shutdown();
- client = null;
+ stopped = client;
+ client = null;
+ if (stopped != null) {
+ stopped.shutdown();
}
} finally {
lock.unlock();
}
+ if (stopped != null) {
+ // the client has its own endpoint (createCoapClient), which
CoapClient.shutdown() does not release (bound
+ // socket and its threads): destroy it once the cancel went out,
which is sent through it
+ if (current != null) {
+ current.awaitCancelled(CANCEL_TIMEOUT_MILLIS);
+ }
+ Endpoint clientEndpoint = stopped.getEndpoint();
+ if (clientEndpoint != null) {
+ clientEndpoint.destroy();
+ }
+ }
super.doStop();
}
@@ -128,12 +151,27 @@ public class CoAPObserver extends DefaultConsumer
implements CoapHandler {
private final class Observation implements CoapHandler {
private volatile boolean cancelled;
private volatile CoapObserveRelation relation;
+ // counted down when the answer to the cancel came, or the cancel
failed
+ private final CountDownLatch cancelDone = new CountDownLatch(1);
void cancel() {
cancelled = true;
CoapObserveRelation current = relation;
- if (current != null) {
+ if (current != null && !current.isCanceled()) {
current.proactiveCancel();
+ } else {
+ // nothing is sent (no relation, or it was cancelled already,
such as for a resource that is not
+ // observable), so no answer comes
+ cancelDone.countDown();
+ }
+ }
+
+ void awaitCancelled(long timeoutMillis) {
+ try {
+ cancelDone.await(timeoutMillis, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ // the endpoint is destroyed anyway
+ Thread.currentThread().interrupt();
}
}
@@ -141,6 +179,11 @@ public class CoAPObserver extends DefaultConsumer
implements CoapHandler {
public void onLoad(CoapResponse response) {
if (!cancelled) {
CoAPObserver.this.onLoad(response);
+ } else if (!response.getOptions().hasObserve()) {
+ // the answer to the cancel (a notification that was already
on its way has the observe option). A
+ // server that wrongly answers the cancel with the observe
option is not seen here, and the stop then
+ // waits for CANCEL_TIMEOUT_MILLIS
+ cancelDone.countDown();
}
}
@@ -148,6 +191,8 @@ public class CoAPObserver extends DefaultConsumer
implements CoapHandler {
public void onError() {
if (!cancelled) {
CoAPObserver.this.onError();
+ } else {
+ cancelDone.countDown();
}
}
}
diff --git
a/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPObserverStopDestroysEndpointTest.java
b/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPObserverStopDestroysEndpointTest.java
new file mode 100644
index 000000000000..7f03d23a0a6c
--- /dev/null
+++
b/components/camel-coap/src/test/java/org/apache/camel/coap/CoAPObserverStopDestroysEndpointTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.coap;
+
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.eclipse.californium.core.CoapResource;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * An observe consumer that stops must release the endpoint of its client (its
bound socket and threads), once the
+ * cancel of its observation went out.
+ */
+class CoAPObserverStopDestroysEndpointTest extends CoAPTestSupport {
+
+ @Test
+ void routeRestartsReleaseTheEndpointsOfTheStoppedObservers() throws
Exception {
+ MockEndpoint mock = getMockEndpoint("mock:observed");
+ // generous waits: a CoAP request that is lost is sent again only
after the ACK timeout (2 to 3 seconds, doubled
+ // at each retransmission)
+ await().atMost(30, TimeUnit.SECONDS).until(() ->
mock.getReceivedCounter() >= 1 && observerCount() == 1);
+ Set<Thread> before = Thread.getAllStackTraces().keySet();
+
+ for (int i = 0; i < 5; i++) {
+ context.getRouteController().stopRoute("observer");
+ await().atMost(30, TimeUnit.SECONDS).until(() -> observerCount()
== 0);
+ mock.reset();
+ context.getRouteController().startRoute("observer");
+ await().atMost(30, TimeUnit.SECONDS).until(() ->
mock.getReceivedCounter() >= 1 && observerCount() == 1);
+ }
+ context.getRouteController().stopRoute("observer");
+
+ // the cancel of the observation still reaches the server
+ await().atMost(30, TimeUnit.SECONDS).until(() -> observerCount() == 0);
+ await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
+ long receivers = Thread.getAllStackTraces().keySet().stream()
+ .filter(t -> !before.contains(t) && t.isAlive() &&
t.getName().startsWith("UDP-Receiver"))
+ .count();
+ assertEquals(0, receivers, "UDP receiver threads of stopped CoAP
observers still alive after 5 restarts");
+ });
+ }
+
+ private int observerCount() {
+ CoAPComponent component = context.getComponent("coap",
CoAPComponent.class);
+ CoapResource resource = (CoapResource)
component.servers.get(PORT.getPort()).getRoot().getChild("TestResource");
+ return resource.getObserverCount();
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ fromF("coap://localhost:%d/TestResource?observable=true",
PORT.getPort()).setBody(constant("Hello"));
+
+ fromF("coap://localhost:%d/TestResource?observe=true",
PORT.getPort()).routeId("observer")
+ .to("mock:observed");
+ }
+ };
+ }
+}