Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ private int buildWatchTimeout(URL url) {
private class ConsulNotifier implements Runnable {
private URL url;
private long consulIndex;
private boolean running;
private volatile boolean running;

ConsulNotifier(URL url, long consulIndex) {
this.url = url;
Expand All @@ -339,13 +339,8 @@ private class ConsulNotifier implements Runnable {

@Override
public void run() {
while (this.running) {
if (ANY_VALUE.equals(url.getServiceInterface())) {
processServices();
} else {
processService();
}
}
Runnable poll = ANY_VALUE.equals(url.getServiceInterface()) ? this::processServices : this::processService;
ConsulWatch.run(() -> running, poll, url.getServiceKey());
}

private void processService() {
Expand All @@ -366,9 +361,9 @@ private void processServices() {
Response<Map<String, List<String>>> response = getAllServices(consulIndex, buildWatchTimeout(url));
Long currentIndex = response.getConsulIndex();
if (currentIndex != null && currentIndex > consulIndex) {
consulIndex = currentIndex;
List<HealthService> services = getHealthServices(response.getValue());
List<URL> urls = convert(services, url);
consulIndex = currentIndex;
for (NotifyListener listener : getSubscribed().get(url)) {
doNotify(url, listener, urls);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ private int buildWatchTimeout() {
private class ConsulNotifier implements Runnable {
private final String serviceName;
private long consulIndex;
private boolean running;
private volatile boolean running;

private final List<ServiceInstancesChangedListener> listener;

Expand All @@ -365,9 +365,7 @@ private class ConsulNotifier implements Runnable {

@Override
public void run() {
while (this.running) {
processService();
}
ConsulWatch.run(() -> running, this::processService, serviceName);
}

private void processService() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* 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.dubbo.registry.consul;

import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;

import com.ecwid.consul.ConsulException;
import com.ecwid.consul.transport.TransportException;
import com.ecwid.consul.v1.OperationException;

import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;

/**
* Runs a Consul blocking watch across transient query failures.
*
* @date 2026/11/5
*/
final class ConsulWatch {
private static final Logger logger = LoggerFactory.getLogger(ConsulWatch.class);

private ConsulWatch() {
}

static void run(BooleanSupplier running, Runnable poll, String service) {
while (running.getAsBoolean() && !Thread.currentThread().isInterrupted()) {
try {
poll.run();
} catch (ConsulException failure) {
if (!isRetryable(failure)) {
throw failure;
}
if (!running.getAsBoolean() || Thread.currentThread().isInterrupted()) {
return;
}
logger.warn("Consul watch query failed for " + service + "; retrying", failure);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return;
}
}
}
}

private static boolean isRetryable(ConsulException failure) {
if (failure instanceof OperationException) {
int status = ((OperationException) failure).getStatusCode();
return status == 429 || status >= 500 && status < 600;
}
return failure instanceof TransportException;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* 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.dubbo.registry.consul;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Verifies that Consul watches resume after transient HTTP failures.
*
* @date 2026/11/5
*/
class ConsulWatchRecoveryTest {

@Test
void registryWatchResumesAfterServerError() throws Exception {
HttpServer server = startConsul();
ConsulRegistry registry = new ConsulRegistry(registryUrl(server));
URL consumer = URL.valueOf("consumer://127.0.0.1/example.Service");
CountDownLatch update = new CountDownLatch(2);
try {
registry.subscribe(consumer, urls -> update.countDown());
assertTrue(update.await(5, TimeUnit.SECONDS), "The registry watch should deliver the next update");
} finally {
registry.destroy();
server.stop(0);
}
}

@Test
void serviceDiscoveryWatchResumesAfterServerError() throws Exception {
HttpServer server = startConsul();
ApplicationModel applicationModel = FrameworkModel.defaultModel().newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
ConsulServiceDiscovery discovery = new ConsulServiceDiscovery(applicationModel, registryUrl(server));
CountDownLatch update = new CountDownLatch(1);
try {
discovery.addServiceInstancesChangedListener(
new ServiceInstancesChangedListener(Collections.singleton("example.Service"), discovery) {
@Override
public void onEvent(ServiceInstancesChangedEvent event) {
update.countDown();
}
});
assertTrue(update.await(5, TimeUnit.SECONDS), "The discovery watch should deliver the next update");
} finally {
discovery.destroy();
applicationModel.destroy();
server.stop(0);
}
}

@Test
void wildcardWatchRetriesServiceLookupWithoutSkippingCatalogIndex() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
AtomicInteger catalogRequests = new AtomicInteger();
AtomicInteger healthRequests = new AtomicInteger();
server.createContext("/v1/catalog/services", exchange -> {
boolean initial = catalogRequests.incrementAndGet() == 1;
respond(exchange, initial ? 10 : 11, initial ? "{}" : "{\"example.Service\":[\"dubbo\"]}");
});
server.createContext("/v1/health/service/example.Service", exchange -> {
if (healthRequests.incrementAndGet() == 1) {
unavailable(exchange);
} else {
respond(exchange, 11, "[]");
}
});
server.start();

ConsulRegistry registry = new ConsulRegistry(registryUrl(server));
URL consumer = URL.valueOf("consumer://127.0.0.1/*");
CountDownLatch update = new CountDownLatch(2);
try {
registry.subscribe(consumer, urls -> update.countDown());
assertTrue(update.await(5, TimeUnit.SECONDS), "The wildcard watch should retry the same catalog index");
} finally {
registry.destroy();
server.stop(0);
}
}

private static URL registryUrl(HttpServer server) {
return URL.valueOf("consul://127.0.0.1:" + server.getAddress().getPort());
}

private static HttpServer startConsul() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
AtomicInteger requests = new AtomicInteger();
server.createContext("/v1/health/service/example.Service", exchange -> {
int request = requests.incrementAndGet();
if (request == 2) {
unavailable(exchange);
} else {
respond(exchange, request == 1 ? 10 : 11, "[]");
}
});
server.start();
return server;
}

private static void respond(HttpExchange exchange, int index, String content) throws IOException {
try {
byte[] body = content.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("X-Consul-Index", String.valueOf(index));
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} finally {
exchange.close();
}
}

private static void unavailable(HttpExchange exchange) throws IOException {
try {
exchange.sendResponseHeaders(503, -1);
} finally {
exchange.close();
}
}

}
Loading