repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java
dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistrySubDispatcher.java
/* * 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.metrics.registry.event; import org.apache.dubbo.metrics.event.SimpleMetricsEventMulticaster; import org.apache.dubbo.metrics.listener.MetricsApplicationListener; import org.apache.dubbo.metrics.model.key.CategoryOverall; import org.apache.dubbo.metrics.model.key.MetricsCat; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import java.util.Arrays; import java.util.List; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_DIRECTORY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_NOTIFY; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_REGISTER_SERVICE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE; import static org.apache.dubbo.metrics.registry.RegistryMetricsConstants.OP_TYPE_SUBSCRIBE_SERVICE; public final class RegistrySubDispatcher extends SimpleMetricsEventMulticaster { public RegistrySubDispatcher(RegistryMetricsCollector collector) { CategorySet.ALL.forEach(categorySet -> { super.addListener(categorySet.getPost().getEventFunc().apply(collector)); if (categorySet.getFinish() != null) { super.addListener(categorySet.getFinish().getEventFunc().apply(collector)); } if (categorySet.getError() != null) { super.addListener(categorySet.getError().getEventFunc().apply(collector)); } }); } /** * A closer aggregation of MetricsCat, a summary collection of certain types of events */ interface CategorySet { CategoryOverall APPLICATION_REGISTER = new CategoryOverall( OP_TYPE_REGISTER, MCat.APPLICATION_REGISTER_POST, MCat.APPLICATION_REGISTER_FINISH, MCat.APPLICATION_REGISTER_ERROR); CategoryOverall APPLICATION_SUBSCRIBE = new CategoryOverall( OP_TYPE_SUBSCRIBE, MCat.APPLICATION_SUBSCRIBE_POST, MCat.APPLICATION_SUBSCRIBE_FINISH, MCat.APPLICATION_SUBSCRIBE_ERROR); CategoryOverall APPLICATION_NOTIFY = new CategoryOverall(OP_TYPE_NOTIFY, MCat.APPLICATION_NOTIFY_POST, MCat.APPLICATION_NOTIFY_FINISH, null); CategoryOverall SERVICE_DIRECTORY = new CategoryOverall(OP_TYPE_DIRECTORY, MCat.APPLICATION_DIRECTORY_POST, null, null); CategoryOverall SERVICE_REGISTER = new CategoryOverall( OP_TYPE_REGISTER_SERVICE, MCat.SERVICE_REGISTER_POST, MCat.SERVICE_REGISTER_FINISH, MCat.SERVICE_REGISTER_ERROR); CategoryOverall SERVICE_SUBSCRIBE = new CategoryOverall( OP_TYPE_SUBSCRIBE_SERVICE, MCat.SERVICE_SUBSCRIBE_POST, MCat.SERVICE_SUBSCRIBE_FINISH, MCat.SERVICE_SUBSCRIBE_ERROR); List<CategoryOverall> ALL = Arrays.asList( APPLICATION_REGISTER, APPLICATION_SUBSCRIBE, APPLICATION_NOTIFY, SERVICE_DIRECTORY, SERVICE_REGISTER, SERVICE_SUBSCRIBE); } /** * {@link MetricsCat} MetricsCat collection, for better classification processing * Except for a few custom functions, most of them can build standard event listening functions through the static methods of MetricsApplicationListener */ interface MCat { // MetricsRegisterListener MetricsCat APPLICATION_REGISTER_POST = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPost); MetricsCat APPLICATION_REGISTER_FINISH = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinish); MetricsCat APPLICATION_REGISTER_ERROR = new MetricsCat(MetricsKey.REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onError); // MetricsSubscribeListener MetricsCat APPLICATION_SUBSCRIBE_POST = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPost); MetricsCat APPLICATION_SUBSCRIBE_FINISH = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinish); MetricsCat APPLICATION_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onError); // MetricsNotifyListener MetricsCat APPLICATION_NOTIFY_POST = new MetricsCat(MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsApplicationListener::onPostEventBuild); MetricsCat APPLICATION_NOTIFY_FINISH = new MetricsCat(MetricsKey.NOTIFY_METRIC_NUM_LAST, RegistrySpecListener::onFinishOfNotify); MetricsCat APPLICATION_DIRECTORY_POST = new MetricsCat(MetricsKey.DIRECTORY_METRIC_NUM_VALID, RegistrySpecListener::onPostOfDirectory); // MetricsServiceRegisterListener MetricsCat SERVICE_REGISTER_POST = new MetricsCat(MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, RegistrySpecListener::onPostOfService); MetricsCat SERVICE_REGISTER_FINISH = new MetricsCat( MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, RegistrySpecListener::onFinishOfService); MetricsCat SERVICE_REGISTER_ERROR = new MetricsCat( MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED, RegistrySpecListener::onErrorOfService); // MetricsServiceSubscribeListener MetricsCat SERVICE_SUBSCRIBE_POST = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, RegistrySpecListener::onPostOfService); MetricsCat SERVICE_SUBSCRIBE_FINISH = new MetricsCat( MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, RegistrySpecListener::onFinishOfService); MetricsCat SERVICE_SUBSCRIBE_ERROR = new MetricsCat(MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED, RegistrySpecListener::onErrorOfService); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java
dubbo-metrics/dubbo-metrics-registry/src/main/java/org/apache/dubbo/metrics/registry/event/RegistryEvent.java
/* * 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.metrics.registry.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.event.TimeCounterEvent; import org.apache.dubbo.metrics.model.key.MetricsKey; import org.apache.dubbo.metrics.model.key.MetricsLevel; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.metrics.registry.RegistryMetricsConstants; import org.apache.dubbo.metrics.registry.collector.RegistryMetricsCollector; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.List; import java.util.Map; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_DIRECTORY_MAP; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_LAST_NUM_MAP; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE; import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SIZE; /** * Registry related events */ public class RegistryEvent extends TimeCounterEvent { public RegistryEvent(ApplicationModel applicationModel, TypeWrapper typeWrapper) { super(applicationModel, typeWrapper); ScopeBeanFactory beanFactory = getSource().getBeanFactory(); RegistryMetricsCollector collector; if (!beanFactory.isDestroyed()) { collector = beanFactory.getBean(RegistryMetricsCollector.class); super.setAvailable(collector != null && collector.isCollectEnabled()); } } private static final TypeWrapper REGISTER_EVENT = new TypeWrapper( MetricsLevel.APP, MetricsKey.REGISTER_METRIC_REQUESTS, MetricsKey.REGISTER_METRIC_REQUESTS_SUCCEED, MetricsKey.REGISTER_METRIC_REQUESTS_FAILED); public static RegistryEvent toRegisterEvent(ApplicationModel applicationModel, List<String> registryClusterNames) { RegistryEvent registryEvent = new RegistryEvent(applicationModel, REGISTER_EVENT); registryEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, registryClusterNames); return registryEvent; } private static final TypeWrapper SUBSCRIBE_EVENT = new TypeWrapper( MetricsLevel.APP, MetricsKey.SUBSCRIBE_METRIC_NUM, MetricsKey.SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsKey.SUBSCRIBE_METRIC_NUM_FAILED); public static RegistryEvent toSubscribeEvent(ApplicationModel applicationModel, String registryClusterName) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, SUBSCRIBE_EVENT); ddEvent.putAttachment( RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, Collections.singletonList(registryClusterName)); return ddEvent; } private static final TypeWrapper NOTIFY_EVENT = new TypeWrapper( MetricsLevel.APP, MetricsKey.NOTIFY_METRIC_REQUESTS, MetricsKey.NOTIFY_METRIC_NUM_LAST, (MetricsKey) null); public static RegistryEvent toNotifyEvent(ApplicationModel applicationModel) { return new RegistryEvent(applicationModel, NOTIFY_EVENT) { @Override public void customAfterPost(Object postResult) { super.putAttachment(ATTACHMENT_KEY_LAST_NUM_MAP, postResult); } }; } private static final TypeWrapper RS_EVENT = new TypeWrapper( MetricsLevel.SERVICE, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED, MetricsKey.SERVICE_REGISTER_METRIC_REQUESTS_FAILED); public static RegistryEvent toRsEvent( ApplicationModel applicationModel, String serviceKey, int size, List<String> serviceDiscoveryNames) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, RS_EVENT); ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, size); ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); return ddEvent; } private static final TypeWrapper SS_EVENT = new TypeWrapper( MetricsLevel.SERVICE, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED, MetricsKey.SERVICE_SUBSCRIBE_METRIC_NUM_FAILED); public static RegistryEvent toSsEvent( ApplicationModel applicationModel, String serviceKey, List<String> serviceDiscoveryNames) { RegistryEvent ddEvent = new RegistryEvent(applicationModel, SS_EVENT); ddEvent.putAttachment(ATTACHMENT_KEY_SERVICE, serviceKey); ddEvent.putAttachment(ATTACHMENT_KEY_SIZE, 1); ddEvent.putAttachment(RegistryMetricsConstants.ATTACHMENT_REGISTRY_KEY, serviceDiscoveryNames); return ddEvent; } private static final TypeWrapper DIRECTORY_EVENT = new TypeWrapper(MetricsLevel.APP, MetricsKey.DIRECTORY_METRIC_NUM_VALID, null, null); public static RegistryEvent refreshDirectoryEvent( ApplicationModel applicationModel, Map<MetricsKey, Map<String, Integer>> summaryMap, Map<String, String> attachments) { RegistryEvent registryEvent = new RegistryEvent(applicationModel, DIRECTORY_EVENT); registryEvent.putAttachment(ATTACHMENT_DIRECTORY_MAP, summaryMap); registryEvent.putAttachments(attachments); return registryEvent; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConventionTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConventionTest.java
/* * 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.tracing; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.tracing.context.DubboClientContext; import org.apache.dubbo.tracing.utils.ObservationConventionUtils; import io.micrometer.common.KeyValues; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DefaultDubboClientObservationConventionTest { static DubboClientObservationConvention dubboClientObservationConvention = DefaultDubboClientObservationConvention.getInstance(); @Test void testGetName() { Assertions.assertEquals("rpc.client.duration", dubboClientObservationConvention.getName()); } @Test void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("testMethod"); invocation.setAttachment("interface", "com.example.TestService"); invocation.setTargetServiceUniqueName("targetServiceName1"); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setInvoker(invoker); DubboClientContext context = new DubboClientContext(invoker, invocation); KeyValues keyValues = dubboClientObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); Assertions.assertEquals( "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } @Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext context = new DubboClientContext(invoker, invocation); DefaultDubboClientObservationConvention convention = new DefaultDubboClientObservationConvention(); String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/MockInvocation.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/MockInvocation.java
/* * 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.tracing; import org.apache.dubbo.rpc.AttachmentsAdapter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.HashMap; import java.util.Map; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * MockInvocation.java */ public class MockInvocation extends RpcInvocation { private Map<String, Object> attachments; public MockInvocation() { attachments = new HashMap<>(); attachments.put(PATH_KEY, "dubbo"); attachments.put(GROUP_KEY, "dubbo"); attachments.put(VERSION_KEY, "1.0.0"); attachments.put(DUBBO_VERSION_KEY, "1.0.0"); attachments.put(TOKEN_KEY, "sfag"); attachments.put(TIMEOUT_KEY, "1000"); } @Override public String getTargetServiceUniqueName() { return null; } @Override public String getProtocolServiceKey() { return null; } public String getMethodName() { return "echo"; } @Override public String getServiceName() { return "DemoService"; } public Class<?>[] getParameterTypes() { return new Class[] {String.class}; } public Object[] getArguments() { return new Object[] {"aa"}; } public Map<String, String> getAttachments() { return new AttachmentsAdapter.ObjectToStringMap(attachments); } @Override public Map<String, Object> getObjectAttachments() { return attachments; } @Override public void setAttachment(String key, String value) { setObjectAttachment(key, value); } @Override public void setAttachment(String key, Object value) { setObjectAttachment(key, value); } @Override public void setObjectAttachment(String key, Object value) { attachments.put(key, value); } @Override public void setAttachmentIfAbsent(String key, String value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setAttachmentIfAbsent(String key, Object value) { setObjectAttachmentIfAbsent(key, value); } @Override public void setObjectAttachmentIfAbsent(String key, Object value) { attachments.put(key, value); } public Invoker<?> getInvoker() { return null; } @Override public void setServiceModel(ServiceModel serviceModel) {} @Override public ServiceModel getServiceModel() { return null; } @Override public Object put(Object key, Object value) { return null; } @Override public Object get(Object key) { return null; } @Override public Map<Object, Object> getAttributes() { return null; } public String getAttachment(String key) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key) { return attachments.get(key); } public String getAttachment(String key, String defaultValue) { return (String) getObjectAttachments().get(key); } @Override public Object getObjectAttachment(String key, Object defaultValue) { Object result = attachments.get(key); if (result == null) { return defaultValue; } return result; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConventionTest.java
/* * 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.tracing; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.tracing.context.DubboClientContext; import org.apache.dubbo.tracing.context.DubboServerContext; import org.apache.dubbo.tracing.utils.ObservationConventionUtils; import io.micrometer.common.KeyValues; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") public class DefaultDubboServerObservationConventionTest { static DubboServerObservationConvention dubboServerObservationConvention = DefaultDubboServerObservationConvention.getInstance(); @Test void testGetName() { Assertions.assertEquals("rpc.server.duration", dubboServerObservationConvention.getName()); } @Test void testGetLowCardinalityKeyValues() throws NoSuchFieldException, IllegalAccessException { RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("testMethod"); invocation.setAttachment("interface", "com.example.TestService"); invocation.setTargetServiceUniqueName("targetServiceName1"); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setInvoker(invoker); DubboServerContext context = new DubboServerContext(invoker, invocation); KeyValues keyValues = dubboServerObservationConvention.getLowCardinalityKeyValues(context); Assertions.assertEquals("testMethod", ObservationConventionUtils.getValueForKey(keyValues, "rpc.method")); Assertions.assertEquals( "targetServiceName1", ObservationConventionUtils.getValueForKey(keyValues, "rpc.service")); Assertions.assertEquals("apache_dubbo", ObservationConventionUtils.getValueForKey(keyValues, "rpc.system")); } @Test void testGetContextualName() { RpcInvocation invocation = new RpcInvocation(); Invoker<?> invoker = ObservationConventionUtils.getMockInvokerWithUrl(); invocation.setMethodName("testMethod"); invocation.setServiceName("com.example.TestService"); DubboClientContext context = new DubboClientContext(invoker, invocation); DefaultDubboClientObservationConvention convention = new DefaultDubboClientObservationConvention(); String contextualName = convention.getContextualName(context); Assertions.assertEquals("com.example.TestService/testMethod", contextualName); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactoryTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactoryTest.java
/* * 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.tracing.tracer; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.tracing.tracer.otel.OTelPropagatorProvider; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class PropagatorProviderFactoryTest { @Test void testPropagatorProviderFactory() { PropagatorProvider propagatorProvider = PropagatorProviderFactory.getPropagatorProvider(); Assert.notNull(propagatorProvider, "PropagatorProvider should not be null"); assertEquals(OTelPropagatorProvider.class, propagatorProvider.getClass()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProviderTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProviderTest.java
/* * 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.tracing.tracer.brave; import org.apache.dubbo.common.utils.Assert; import brave.Tracing; import io.micrometer.tracing.propagation.Propagator; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; class BravePropagatorProviderTest { @Test void testBravePropagatorProvider() { Tracing tracing = mock(Tracing.class); BravePropagatorProvider.createMicrometerPropagator(tracing); BravePropagatorProvider bravePropagatorProvider = new BravePropagatorProvider(); Propagator propagator = bravePropagatorProvider.getPropagator(); Assert.notNull(propagator, "Propagator don't be null."); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BraveProviderTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/brave/BraveProviderTest.java
/* * 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.tracing.tracer.brave; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.nested.BaggageConfig; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.config.nested.PropagationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.utils.PropagationType; import java.util.ArrayList; import java.util.List; import brave.propagation.Propagation; import io.micrometer.tracing.Tracer; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class BraveProviderTest { @Test void testGetTracer() { TracingConfig tracingConfig = new TracingConfig(); tracingConfig.setEnabled(true); ExporterConfig exporterConfig = new ExporterConfig(); exporterConfig.setZipkinConfig(new ExporterConfig.ZipkinConfig("")); tracingConfig.setTracingExporter(exporterConfig); BraveProvider braveProvider = new BraveProvider(ApplicationModel.defaultModel(), tracingConfig); Tracer tracer = braveProvider.getTracer(); Assert.notNull(tracer, "Tracer should not be null."); assertEquals(io.micrometer.tracing.brave.bridge.BraveTracer.class, tracer.getClass()); } @Test void testGetPropagator() { TracingConfig tracingConfig = mock(TracingConfig.class); PropagationConfig propagationConfig = mock(PropagationConfig.class); when(tracingConfig.getPropagation()).thenReturn(propagationConfig); BaggageConfig baggageConfig = mock(BaggageConfig.class); when(tracingConfig.getBaggage()).thenReturn(baggageConfig); // no baggage when(baggageConfig.getEnabled()).thenReturn(Boolean.FALSE); when(propagationConfig.getType()).thenReturn(PropagationType.W3C.getValue()); Propagation.Factory w3cPropagationFactoryWithoutBaggage = BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); assertEquals( io.micrometer.tracing.brave.bridge.W3CPropagation.class, w3cPropagationFactoryWithoutBaggage.getClass()); when(propagationConfig.getType()).thenReturn(PropagationType.B3.getValue()); Propagation.Factory b3PropagationFactoryWithoutBaggage = BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); Assert.notNull(b3PropagationFactoryWithoutBaggage, "b3PropagationFactoryWithoutBaggage should not be null."); // with baggage when(baggageConfig.getEnabled()).thenReturn(Boolean.TRUE); BaggageConfig.Correlation correlation = mock(BaggageConfig.Correlation.class); when(correlation.isEnabled()).thenReturn(Boolean.TRUE); when(baggageConfig.getCorrelation()).thenReturn(correlation); List<String> remoteFields = new ArrayList<>(); for (int i = 0; i < 10; i++) { remoteFields.add("test-hd-" + i); } when(baggageConfig.getRemoteFields()).thenReturn(remoteFields); Propagation.Factory propagationFactoryWithBaggage = BraveProvider.PropagatorFactory.getPropagationFactory(tracingConfig); Assert.notNull(propagationFactoryWithBaggage, "propagationFactoryWithBaggage should not be null."); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProviderTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProviderTest.java
/* * 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.tracing.tracer.otel; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.nested.BaggageConfig; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.config.nested.PropagationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.tracer.TracerProvider; import org.apache.dubbo.tracing.tracer.TracerProviderFactory; import org.apache.dubbo.tracing.utils.PropagationType; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; import io.micrometer.tracing.otel.bridge.OtelTracer; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.extension.trace.propagation.B3Propagator; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class OpenTelemetryProviderTest { @Test void testGetTracer() { TracingConfig tracingConfig = new TracingConfig(); tracingConfig.setEnabled(true); ExporterConfig exporterConfig = new ExporterConfig(); exporterConfig.setZipkinConfig(new ExporterConfig.ZipkinConfig("")); tracingConfig.setTracingExporter(exporterConfig); TracerProvider tracerProvider1 = TracerProviderFactory.getProvider(ApplicationModel.defaultModel(), tracingConfig); Assert.notNull(tracerProvider1, "TracerProvider should not be null."); Tracer tracer1 = tracerProvider1.getTracer(); assertEquals(OtelTracer.class, tracer1.getClass()); tracingConfig.setBaggage(new BaggageConfig(false)); TracerProvider tracerProvider2 = TracerProviderFactory.getProvider(ApplicationModel.defaultModel(), tracingConfig); Assert.notNull(tracerProvider2, "TracerProvider should not be null."); Tracer tracer2 = tracerProvider2.getTracer(); assertEquals(OtelTracer.class, tracer2.getClass()); } @Test void testGetPropagator() { PropagationConfig propagationConfig = mock(PropagationConfig.class); BaggageConfig baggageConfig = mock(BaggageConfig.class); OtelCurrentTraceContext otelCurrentTraceContext = mock(OtelCurrentTraceContext.class); when(baggageConfig.getEnabled()).thenReturn(Boolean.FALSE); when(propagationConfig.getType()).thenReturn(PropagationType.B3.getValue()); TextMapPropagator b3PropagatorWithoutBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator( propagationConfig, baggageConfig, otelCurrentTraceContext); assertEquals(B3Propagator.class, b3PropagatorWithoutBaggage.getClass()); when(propagationConfig.getType()).thenReturn(PropagationType.W3C.getValue()); TextMapPropagator w3cPropagatorWithoutBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator( propagationConfig, baggageConfig, otelCurrentTraceContext); assertEquals(W3CTraceContextPropagator.class, w3cPropagatorWithoutBaggage.getClass()); when(baggageConfig.getEnabled()).thenReturn(Boolean.TRUE); TextMapPropagator propagatorWithBaggage = OpenTelemetryProvider.PropagatorFactory.getPropagator( propagationConfig, baggageConfig, otelCurrentTraceContext); Assert.notNull(propagatorWithBaggage, "PropagatorWithBaggage should not be null"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProviderTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProviderTest.java
/* * 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.tracing.tracer.otel; import org.apache.dubbo.common.utils.Assert; import io.micrometer.tracing.propagation.Propagator; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.propagation.ContextPropagators; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; class OTelPropagatorProviderTest { @Test void testOTelPropagatorProvider() { ContextPropagators contextPropagators = mock(ContextPropagators.class); Tracer tracer = mock(Tracer.class); OTelPropagatorProvider.createMicrometerPropagator(contextPropagators, tracer); OTelPropagatorProvider oTelPropagatorProvider = new OTelPropagatorProvider(); Propagator propagator = oTelPropagatorProvider.getPropagator(); Assert.notNull(propagator, "Propagator don't be null."); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationSupportUtilTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationSupportUtilTest.java
/* * 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.tracing.utils; import org.apache.dubbo.common.utils.Assert; import org.junit.jupiter.api.Test; public class ObservationSupportUtilTest { @Test void testIsSupportObservation() { boolean supportObservation = ObservationSupportUtil.isSupportObservation(); Assert.assertTrue(supportObservation, "ObservationSupportUtil.isSupportObservation() should return true"); } @Test void testIsSupportTracing() { boolean supportTracing = ObservationSupportUtil.isSupportTracing(); Assert.assertTrue(supportTracing, "ObservationSupportUtil.isSupportTracing() should return true"); } @Test void testIsSupportOTelTracer() { boolean supportOTelTracer = ObservationSupportUtil.isSupportOTelTracer(); Assert.assertTrue(supportOTelTracer, "ObservationSupportUtil.isSupportOTelTracer() should return true"); } @Test void testIsSupportBraveTracer() { boolean supportBraveTracer = ObservationSupportUtil.isSupportBraveTracer(); Assert.assertTrue(supportBraveTracer, "ObservationSupportUtil.isSupportOTelTracer() should return true"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationConventionUtils.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/ObservationConventionUtils.java
/* * 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.tracing.utils; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import java.lang.reflect.Field; import io.micrometer.common.KeyValue; import io.micrometer.common.KeyValues; import org.mockito.Mockito; public class ObservationConventionUtils { public static Invoker<?> getMockInvokerWithUrl() { URL url = URL.valueOf( "dubbo://127.0.0.1:12345/com.example.TestService?anyhost=true&application=test&category=providers&dubbo=2.0.2&generic=false&interface=com.example.TestService&methods=testMethod&pid=26716&side=provider&timestamp=1633863896653"); Invoker<?> invoker = Mockito.mock(Invoker.class); Mockito.when(invoker.getUrl()).thenReturn(url); return invoker; } public static String getValueForKey(KeyValues keyValues, Object key) throws NoSuchFieldException, IllegalAccessException { Field f = KeyValues.class.getDeclaredField("sortedSet"); f.setAccessible(true); KeyValue[] kv = (KeyValue[]) f.get(keyValues); for (KeyValue keyValue : kv) { if (keyValue.getKey().equals(key)) { return keyValue.getValue(); } } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/PropagationTypeTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/utils/PropagationTypeTest.java
/* * 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.tracing.utils; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; class PropagationTypeTest { @Test void forValue() { PropagationType propagationType1 = PropagationType.forValue("W3C"); assertEquals(PropagationType.W3C, propagationType1); PropagationType propagationType2 = PropagationType.forValue("B3"); assertEquals(PropagationType.B3, propagationType2); PropagationType propagationType3 = PropagationType.forValue("B33"); assertNull(propagationType3); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporterTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporterTest.java
/* * 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.tracing.exporter.otlp; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.time.Duration; import io.opentelemetry.sdk.trace.export.SpanExporter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class OTlpSpanExporterTest { @Test void getSpanExporter() { ExporterConfig.OtlpConfig otlpConfig = mock(ExporterConfig.OtlpConfig.class); when(otlpConfig.getEndpoint()).thenReturn("http://localhost:9411/api/v2/spans"); when(otlpConfig.getTimeout()).thenReturn(Duration.ofSeconds(5)); when(otlpConfig.getCompressionMethod()).thenReturn("gzip"); SpanExporter spanExporter = OTlpSpanExporter.getSpanExporter(ApplicationModel.defaultModel(), otlpConfig); Assertions.assertNotNull(spanExporter); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandlerTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandlerTest.java
/* * 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.tracing.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.time.Duration; import brave.handler.SpanHandler; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ZipkinSpanHandlerTest { @Test void getSpanHandler() { ExporterConfig.ZipkinConfig zipkinConfig = mock(ExporterConfig.ZipkinConfig.class); when(zipkinConfig.getEndpoint()).thenReturn("http://localhost:9411/api/v2/spans"); when(zipkinConfig.getConnectTimeout()).thenReturn(Duration.ofSeconds(5)); SpanHandler spanHandler = ZipkinSpanHandler.getSpanHandler(ApplicationModel.defaultModel(), zipkinConfig); Assertions.assertNotNull(spanHandler); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporterTest.java
dubbo-metrics/dubbo-tracing/src/test/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporterTest.java
/* * 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.tracing.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.time.Duration; import io.opentelemetry.sdk.trace.export.SpanExporter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ZipkinSpanExporterTest { @Test void getSpanExporter() { ExporterConfig.ZipkinConfig zipkinConfig = mock(ExporterConfig.ZipkinConfig.class); when(zipkinConfig.getEndpoint()).thenReturn("http://localhost:9411/api/v2/spans"); when(zipkinConfig.getConnectTimeout()).thenReturn(Duration.ofSeconds(5)); when(zipkinConfig.getReadTimeout()).thenReturn(Duration.ofSeconds(5)); SpanExporter spanExporter = ZipkinSpanExporter.getSpanExporter(ApplicationModel.defaultModel(), zipkinConfig); Assertions.assertNotNull(spanExporter); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/AbstractDefaultDubboObservationConvention.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/AbstractDefaultDubboObservationConvention.java
/* * 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.tracing; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.RpcUtils; import io.micrometer.common.KeyValues; import io.micrometer.common.docs.KeyName; import io.micrometer.common.lang.Nullable; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_METHOD; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SERVICE; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SYSTEM; class AbstractDefaultDubboObservationConvention { KeyValues getLowCardinalityKeyValues(Invocation invocation) { KeyValues keyValues = KeyValues.of(RPC_SYSTEM.withValue("apache_dubbo")); String serviceName = StringUtils.hasText(invocation.getServiceName()) ? invocation.getServiceName() : readServiceName(invocation.getTargetServiceUniqueName()); keyValues = appendNonNull(keyValues, RPC_SERVICE, serviceName); return appendNonNull(keyValues, RPC_METHOD, RpcUtils.getMethodName(invocation)); } protected KeyValues appendNonNull(KeyValues keyValues, KeyName keyName, @Nullable String value) { if (value != null) { return keyValues.and(keyName.withValue(value)); } return keyValues; } String getContextualName(Invocation invocation) { String serviceName = StringUtils.hasText(invocation.getServiceName()) ? invocation.getServiceName() : readServiceName(invocation.getTargetServiceUniqueName()); String methodName = RpcUtils.getMethodName(invocation); String method = StringUtils.hasText(methodName) ? methodName : ""; return serviceName + CommonConstants.PATH_SEPARATOR + method; } private String readServiceName(String targetServiceUniqueName) { String[] splitByHyphen = targetServiceUniqueName.split( CommonConstants.PATH_SEPARATOR); // foo-provider/a.b.c:1.0.0 or a.b.c:1.0.0 String withVersion = splitByHyphen.length == 1 ? targetServiceUniqueName : splitByHyphen[1]; String[] splitByVersion = withVersion.split(CommonConstants.GROUP_CHAR_SEPARATOR); // a.b.c:1.0.0 if (splitByVersion.length == 1) { return withVersion; } return splitByVersion[0]; // a.b.c } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConvention.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboServerObservationConvention.java
/* * 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.tracing; import org.apache.dubbo.tracing.context.DubboServerContext; import io.micrometer.common.KeyValues; /** * Default implementation of the {@link DubboServerObservationConvention}. */ public class DefaultDubboServerObservationConvention extends AbstractDefaultDubboObservationConvention implements DubboServerObservationConvention { /** * Singleton instance of {@link DefaultDubboServerObservationConvention}. */ private static final DubboServerObservationConvention INSTANCE = new DefaultDubboServerObservationConvention(); public static DubboServerObservationConvention getInstance() { return INSTANCE; } @Override public String getName() { return "rpc.server.duration"; } @Override public KeyValues getLowCardinalityKeyValues(DubboServerContext context) { return super.getLowCardinalityKeyValues(context.getInvocation()); } @Override public String getContextualName(DubboServerContext context) { return super.getContextualName(context.getInvocation()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationDocumentation.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationDocumentation.java
/* * 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.tracing; import io.micrometer.common.docs.KeyName; import io.micrometer.common.lang.NonNullApi; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationConvention; import io.micrometer.observation.docs.ObservationDocumentation; /** * Documentation of Dubbo observations. */ public enum DubboObservationDocumentation implements ObservationDocumentation { /** * Server side Dubbo RPC Observation. */ SERVER { @Override public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() { return DefaultDubboServerObservationConvention.class; } @Override public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } }, /** * Client side Dubbo RPC Observation. */ CLIENT { @Override public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() { return DefaultDubboClientObservationConvention.class; } @Override public KeyName[] getLowCardinalityKeyNames() { return LowCardinalityKeyNames.values(); } }; @NonNullApi enum LowCardinalityKeyNames implements KeyName { /** * A string identifying the remoting system. * Must be "apache_dubbo". */ RPC_SYSTEM { @Override public String asString() { return "rpc.system"; } }, /** * The full (logical) name of the service being called, including its package name, if applicable. * Example: "myservice.EchoService". */ RPC_SERVICE { @Override public String asString() { return "rpc.service"; } }, /** * The name of the (logical) method being called, must be equal to the $method part in the span name. * Example: "exampleMethod". */ RPC_METHOD { @Override public String asString() { return "rpc.method"; } }, /** * RPC server host name. * Example: "example.com". */ NET_PEER_NAME { @Override public String asString() { return "net.peer.name"; } }, /** * Logical remote port number. * Example: 80; 8080; 443. */ NET_PEER_PORT { @Override public String asString() { return "net.peer.port"; } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationRegistry.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboObservationRegistry.java
/* * 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.tracing; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.metrics.utils.MetricsSupportUtil; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.handler.DubboClientTracingObservationHandler; import org.apache.dubbo.tracing.handler.DubboServerTracingObservationHandler; import org.apache.dubbo.tracing.metrics.ObservationMeter; import org.apache.dubbo.tracing.tracer.PropagatorProvider; import org.apache.dubbo.tracing.tracer.PropagatorProviderFactory; import org.apache.dubbo.tracing.tracer.TracerProvider; import org.apache.dubbo.tracing.tracer.TracerProviderFactory; import io.micrometer.observation.ObservationHandler; import io.micrometer.observation.ObservationRegistry; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.handler.DefaultTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; import io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler; import io.micrometer.tracing.propagation.Propagator; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_NOT_FOUND_TRACER_DEPENDENCY; public class DubboObservationRegistry { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboObservationRegistry.class); private final ApplicationModel applicationModel; private final TracingConfig tracingConfig; public DubboObservationRegistry(ApplicationModel applicationModel, TracingConfig tracingConfig) { this.applicationModel = applicationModel; this.tracingConfig = tracingConfig; } public void initObservationRegistry() { // If get ObservationRegistry.class from external(eg Spring.), use external. ObservationRegistry externalObservationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class); if (externalObservationRegistry != null) { if (logger.isDebugEnabled()) { logger.debug("ObservationRegistry.class from external is existed."); } return; } if (logger.isDebugEnabled()) { logger.debug("Tracing config is: " + JsonUtils.toJson(tracingConfig)); } TracerProvider tracerProvider = TracerProviderFactory.getProvider(applicationModel, tracingConfig); if (tracerProvider == null) { logger.warn( COMMON_NOT_FOUND_TRACER_DEPENDENCY, "", "", "Can not found OpenTelemetry/Brave tracer dependencies, skip init ObservationRegistry."); return; } // The real tracer will come from tracer implementation (OTel / Brave) Tracer tracer = tracerProvider.getTracer(); // The real propagator will come from tracer implementation (OTel / Brave) PropagatorProvider propagatorProvider = PropagatorProviderFactory.getPropagatorProvider(); Propagator propagator = propagatorProvider != null ? propagatorProvider.getPropagator() : Propagator.NOOP; ObservationRegistry registry = ObservationRegistry.create(); registry.observationConfig() // set up a first matching handler that creates spans - it comes from Micrometer Tracing. // set up spans for sending and receiving data over the wire and a default one. .observationHandler(new ObservationHandler.FirstMatchingCompositeObservationHandler( new PropagatingSenderTracingObservationHandler<>(tracer, propagator), new PropagatingReceiverTracingObservationHandler<>(tracer, propagator), new DefaultTracingObservationHandler(tracer))) .observationHandler(new ObservationHandler.FirstMatchingCompositeObservationHandler( new DubboClientTracingObservationHandler<>(tracer), new DubboServerTracingObservationHandler<>(tracer))); if (MetricsSupportUtil.isSupportMetrics()) { ObservationMeter.addMeterRegistry(registry, applicationModel); } applicationModel.getBeanFactory().registerBean(registry); applicationModel.getBeanFactory().registerBean(tracer); applicationModel.getBeanFactory().registerBean(propagator); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboClientObservationConvention.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboClientObservationConvention.java
/* * 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.tracing; import org.apache.dubbo.tracing.context.DubboClientContext; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationConvention; /** * {@link ObservationConvention} for a {@link DubboClientContext}. */ public interface DubboClientObservationConvention extends ObservationConvention<DubboClientContext> { @Override default boolean supportsContext(Observation.Context context) { return context instanceof DubboClientContext; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboServerObservationConvention.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DubboServerObservationConvention.java
/* * 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.tracing; import org.apache.dubbo.tracing.context.DubboServerContext; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationConvention; /** * {@link ObservationConvention} for a {@link DubboServerContext}. */ public interface DubboServerObservationConvention extends ObservationConvention<DubboServerContext> { @Override default boolean supportsContext(Observation.Context context) { return context instanceof DubboServerContext; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConvention.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/DefaultDubboClientObservationConvention.java
/* * 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.tracing; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcContextAttachment; import org.apache.dubbo.tracing.context.DubboClientContext; import java.util.List; import io.micrometer.common.KeyValues; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_NAME; import static org.apache.dubbo.tracing.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_PORT; /** * Default implementation of the {@link DubboClientObservationConvention}. */ public class DefaultDubboClientObservationConvention extends AbstractDefaultDubboObservationConvention implements DubboClientObservationConvention { /** * Singleton instance of {@link DefaultDubboClientObservationConvention}. */ private static final DubboClientObservationConvention INSTANCE = new DefaultDubboClientObservationConvention(); public static DubboClientObservationConvention getInstance() { return INSTANCE; } @Override public String getName() { return "rpc.client.duration"; } @Override public KeyValues getLowCardinalityKeyValues(DubboClientContext context) { KeyValues keyValues = super.getLowCardinalityKeyValues(context.getInvocation()); return withRemoteHostPort(keyValues, context); } private KeyValues withRemoteHostPort(KeyValues keyValues, DubboClientContext context) { List<Invoker<?>> invokedInvokers = context.getInvocation().getInvokedInvokers(); if (invokedInvokers.isEmpty()) { return keyValues; } // We'll attach tags only from the first invoker Invoker<?> invoker = invokedInvokers.get(0); URL url = invoker.getUrl(); RpcContextAttachment rpcContextAttachment = RpcContext.getClientAttachment(); String remoteHost = remoteHost(rpcContextAttachment, url); int remotePort = remotePort(rpcContextAttachment, url); return withRemoteHostPort(keyValues, remoteHost, remotePort); } private String remoteHost(RpcContextAttachment rpcContextAttachment, URL url) { String remoteHost = url != null ? url.getHost() : null; return remoteHost != null ? remoteHost : rpcContextAttachment.getRemoteHost(); } private int remotePort(RpcContextAttachment rpcContextAttachment, URL url) { Integer remotePort = url != null ? url.getPort() : null; if (remotePort != null) { return remotePort; } return rpcContextAttachment.getRemotePort() != 0 ? rpcContextAttachment.getRemotePort() : rpcContextAttachment.getLocalPort(); } private KeyValues withRemoteHostPort(KeyValues keyValues, String remoteHostName, int remotePort) { keyValues = appendNonNull(keyValues, NET_PEER_NAME, remoteHostName); if (remotePort == 0) { return keyValues; } return appendNonNull(keyValues, NET_PEER_PORT, String.valueOf(remotePort)); } @Override public String getContextualName(DubboClientContext context) { return super.getContextualName(context.getInvocation()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationSenderFilter.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationSenderFilter.java
/* * 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.tracing.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import org.apache.dubbo.tracing.DefaultDubboClientObservationConvention; import org.apache.dubbo.tracing.DubboClientObservationConvention; import org.apache.dubbo.tracing.DubboObservationDocumentation; import org.apache.dubbo.tracing.context.DubboClientContext; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; /** * A {@link Filter} that creates an {@link Observation} around the outgoing message. */ @Activate( group = CONSUMER, order = Integer.MIN_VALUE + 50, onClass = "io.micrometer.observation.NoopObservationRegistry") public class ObservationSenderFilter implements ClusterFilter, BaseFilter.Listener, ScopeModelAware { private final ObservationRegistry observationRegistry; private final DubboClientObservationConvention clientObservationConvention; public ObservationSenderFilter(ApplicationModel applicationModel) { observationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class); clientObservationConvention = applicationModel.getBeanFactory().getBean(DubboClientObservationConvention.class); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (observationRegistry == null) { return invoker.invoke(invocation); } final DubboClientContext senderContext = new DubboClientContext(invoker, invocation); final Observation observation = DubboObservationDocumentation.CLIENT.observation( this.clientObservationConvention, DefaultDubboClientObservationConvention.getInstance(), () -> senderContext, observationRegistry); invocation.put(Observation.class, observation.start()); return observation.scoped(() -> invoker.invoke(invocation)); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { final Observation observation = getObservation(invocation); if (observation == null) { return; } if (appResponse != null && appResponse.hasException()) { observation.error(appResponse.getException()); } observation.stop(); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { final Observation observation = getObservation(invocation); if (observation == null) { return; } observation.error(t); observation.stop(); } private Observation getObservation(Invocation invocation) { return (Observation) invocation.get(Observation.class); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilter.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/filter/ObservationReceiverFilter.java
/* * 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.tracing.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import org.apache.dubbo.tracing.DefaultDubboServerObservationConvention; import org.apache.dubbo.tracing.DubboObservationDocumentation; import org.apache.dubbo.tracing.DubboServerObservationConvention; import org.apache.dubbo.tracing.context.DubboServerContext; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationRegistry; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; /** * A {@link Filter} that creates an {@link Observation} around the incoming message. */ @Activate( group = PROVIDER, order = Integer.MIN_VALUE + 50, onClass = "io.micrometer.observation.NoopObservationRegistry") public class ObservationReceiverFilter implements Filter, BaseFilter.Listener, ScopeModelAware { private final ObservationRegistry observationRegistry; private final DubboServerObservationConvention serverObservationConvention; public ObservationReceiverFilter(ApplicationModel applicationModel) { observationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class); serverObservationConvention = applicationModel.getBeanFactory().getBean(DubboServerObservationConvention.class); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (observationRegistry == null) { return invoker.invoke(invocation); } final DubboServerContext receiverContext = new DubboServerContext(invoker, invocation); final Observation observation = DubboObservationDocumentation.SERVER.observation( this.serverObservationConvention, DefaultDubboServerObservationConvention.getInstance(), () -> receiverContext, observationRegistry); invocation.put(Observation.class, observation.start()); return observation.scoped(() -> invoker.invoke(invocation)); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { final Observation observation = getObservation(invocation); if (observation == null) { return; } if (appResponse != null && appResponse.hasException()) { observation.error(appResponse.getException()); } observation.stop(); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { final Observation observation = getObservation(invocation); if (observation == null) { return; } observation.error(t); observation.stop(); } private Observation getObservation(Invocation invocation) { return (Observation) invocation.get(Observation.class); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProviderFactory.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProviderFactory.java
/* * 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.tracing.tracer; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.tracer.brave.BraveProvider; import org.apache.dubbo.tracing.tracer.otel.OpenTelemetryProvider; import org.apache.dubbo.tracing.utils.ObservationSupportUtil; public class TracerProviderFactory { public static TracerProvider getProvider(ApplicationModel applicationModel, TracingConfig tracingConfig) { // If support OTel firstly, return OTel, then Brave. if (ObservationSupportUtil.isSupportOTelTracer()) { return new OpenTelemetryProvider(applicationModel, tracingConfig); } if (ObservationSupportUtil.isSupportBraveTracer()) { return new BraveProvider(applicationModel, tracingConfig); } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactory.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/PropagatorProviderFactory.java
/* * 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.tracing.tracer; import org.apache.dubbo.tracing.tracer.brave.BravePropagatorProvider; import org.apache.dubbo.tracing.tracer.otel.OTelPropagatorProvider; import org.apache.dubbo.tracing.utils.ObservationSupportUtil; public class PropagatorProviderFactory { public static PropagatorProvider getPropagatorProvider() { // If support OTel firstly, return OTel, then Brave. if (ObservationSupportUtil.isSupportOTelTracer()) { return new OTelPropagatorProvider(); } if (ObservationSupportUtil.isSupportBraveTracer()) { return new BravePropagatorProvider(); } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/PropagatorProvider.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/PropagatorProvider.java
/* * 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.tracing.tracer; import io.micrometer.tracing.propagation.Propagator; public interface PropagatorProvider { /** * The real propagator will come from tracer implementation (OTel / Brave) * * @return Propagator */ Propagator getPropagator(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProvider.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/TracerProvider.java
/* * 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.tracing.tracer; import io.micrometer.tracing.Tracer; public interface TracerProvider { /** * Tracer of Micrometer. The real tracer will come from tracer implementation (OTel / Brave) * * @return Tracer */ Tracer getTracer(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProvider.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BravePropagatorProvider.java
/* * 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.tracing.tracer.brave; import org.apache.dubbo.tracing.tracer.PropagatorProvider; import io.micrometer.tracing.brave.bridge.BravePropagator; import io.micrometer.tracing.propagation.Propagator; public class BravePropagatorProvider implements PropagatorProvider { private static Propagator propagator; @Override public Propagator getPropagator() { return propagator; } protected static void createMicrometerPropagator(brave.Tracing tracing) { propagator = new BravePropagator(tracing); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BraveProvider.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/brave/BraveProvider.java
/* * 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.tracing.tracer.brave; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.nested.BaggageConfig; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.exporter.zipkin.ZipkinSpanHandler; import org.apache.dubbo.tracing.tracer.TracerProvider; import org.apache.dubbo.tracing.utils.PropagationType; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import io.micrometer.tracing.CurrentTraceContext; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.brave.bridge.BraveBaggageManager; import io.micrometer.tracing.brave.bridge.BraveCurrentTraceContext; import io.micrometer.tracing.brave.bridge.BraveTracer; import io.micrometer.tracing.brave.bridge.W3CPropagation; import static org.apache.dubbo.tracing.utils.ObservationConstants.DEFAULT_APPLICATION_NAME; import static org.apache.dubbo.tracing.utils.ObservationSupportUtil.isSupportBraveURLSender; public class BraveProvider implements TracerProvider { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(BraveProvider.class); private static final BraveBaggageManager BRAVE_BAGGAGE_MANAGER = new BraveBaggageManager(); private final ApplicationModel applicationModel; private final TracingConfig tracingConfig; public BraveProvider(ApplicationModel applicationModel, TracingConfig tracingConfig) { this.applicationModel = applicationModel; this.tracingConfig = tracingConfig; } @Override public Tracer getTracer() { // [Brave component] SpanHandler is a component that gets called when a span is finished. List<brave.handler.SpanHandler> spanHandlerList = getSpanHandlers(); String applicationName = applicationModel .getApplicationConfigManager() .getApplication() .map(ApplicationConfig::getName) .orElse(DEFAULT_APPLICATION_NAME); // [Brave component] CurrentTraceContext is a Brave component that allows you to // retrieve the current TraceContext. brave.propagation.ThreadLocalCurrentTraceContext braveCurrentTraceContext = brave.propagation.ThreadLocalCurrentTraceContext.newBuilder() .addScopeDecorator(correlationScopeDecorator()) // Brave's automatic MDC setup .build(); // [Micrometer Tracing component] A Micrometer Tracing wrapper for Brave's CurrentTraceContext CurrentTraceContext bridgeContext = new BraveCurrentTraceContext(braveCurrentTraceContext); // [Brave component] Tracing is the root component that allows to configure the // tracer, handlers, context propagation etc. brave.Tracing.Builder builder = brave.Tracing.newBuilder() .currentTraceContext(braveCurrentTraceContext) .supportsJoin(false) .traceId128Bit(true) .localServiceName(applicationName) // For Baggage to work you need to provide a list of fields to propagate .propagationFactory(PropagatorFactory.getPropagationFactory(tracingConfig)) .sampler(getSampler()); spanHandlerList.forEach(builder::addSpanHandler); brave.Tracing tracing = builder.build(); BravePropagatorProvider.createMicrometerPropagator(tracing); // [Brave component] Tracer is a component that handles the life-cycle of a span brave.Tracer braveTracer = tracing.tracer(); // [Micrometer Tracing component] A Micrometer Tracing wrapper for Brave's Tracer return new BraveTracer(braveTracer, bridgeContext, BRAVE_BAGGAGE_MANAGER); } private List<brave.handler.SpanHandler> getSpanHandlers() { ExporterConfig exporterConfig = tracingConfig.getTracingExporter(); List<brave.handler.SpanHandler> res = new ArrayList<>(); if (!isSupportBraveURLSender()) { return res; } ExporterConfig.ZipkinConfig zipkinConfig = exporterConfig.getZipkinConfig(); if (zipkinConfig != null && StringUtils.isNotEmpty(zipkinConfig.getEndpoint())) { LOGGER.info("Create zipkin span handler."); res.add(ZipkinSpanHandler.getSpanHandler(applicationModel, zipkinConfig)); } return res; } private brave.sampler.Sampler getSampler() { return brave.sampler.Sampler.create(tracingConfig.getSampling().getProbability()); } private Optional<brave.baggage.CorrelationScopeCustomizer> correlationFieldsCorrelationScopeCustomizer() { BaggageConfig.Correlation correlation = tracingConfig.getBaggage().getCorrelation(); boolean enabled = correlation.isEnabled(); if (!enabled) { return Optional.empty(); } return Optional.of((builder) -> { List<String> correlationFields = correlation.getFields(); for (String field : correlationFields) { builder.add(brave.baggage.CorrelationScopeConfig.SingleCorrelationField.newBuilder( brave.baggage.BaggageField.create(field)) .flushOnUpdate() .build()); } }); } private brave.propagation.CurrentTraceContext.ScopeDecorator correlationScopeDecorator() { brave.baggage.CorrelationScopeDecorator.Builder builder = brave.context.slf4j.MDCScopeDecorator.newBuilder(); correlationFieldsCorrelationScopeCustomizer().ifPresent((customizer) -> customizer.customize(builder)); return builder.build(); } static class PropagatorFactory { public static brave.propagation.Propagation.Factory getPropagationFactory(TracingConfig tracingConfig) { BaggageConfig baggageConfig = tracingConfig.getBaggage(); if (baggageConfig == null || !baggageConfig.getEnabled()) { return getPropagationFactoryWithoutBaggage(tracingConfig); } return getPropagationFactoryWithBaggage(tracingConfig); } private static brave.propagation.Propagation.Factory getPropagationFactoryWithoutBaggage( TracingConfig tracingConfig) { PropagationType propagationType = PropagationType.forValue(tracingConfig.getPropagation().getType()); if (PropagationType.W3C == propagationType) { return new io.micrometer.tracing.brave.bridge.W3CPropagation(); } else { // Brave default propagation is B3 return brave.propagation.B3Propagation.newFactoryBuilder() .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) .build(); } } private static brave.propagation.Propagation.Factory getPropagationFactoryWithBaggage( TracingConfig tracingConfig) { PropagationType propagationType = PropagationType.forValue(tracingConfig.getPropagation().getType()); brave.propagation.Propagation.Factory delegate; if (PropagationType.W3C == propagationType) { delegate = new W3CPropagation(BRAVE_BAGGAGE_MANAGER, Collections.emptyList()); } else { // Brave default propagation is B3 delegate = brave.propagation.B3Propagation.newFactoryBuilder() .injectFormat(brave.propagation.B3Propagation.Format.SINGLE_NO_PARENT) .build(); } return getBaggageFactoryBuilder(delegate, tracingConfig).build(); } private static brave.baggage.BaggagePropagation.FactoryBuilder getBaggageFactoryBuilder( brave.propagation.Propagation.Factory delegate, TracingConfig tracingConfig) { brave.baggage.BaggagePropagation.FactoryBuilder builder = brave.baggage.BaggagePropagation.newFactoryBuilder(delegate); getBaggagePropagationCustomizers(tracingConfig).forEach((customizer) -> customizer.customize(builder)); return builder; } private static List<brave.baggage.BaggagePropagationCustomizer> getBaggagePropagationCustomizers( TracingConfig tracingConfig) { List<brave.baggage.BaggagePropagationCustomizer> res = new ArrayList<>(); if (tracingConfig.getBaggage().getCorrelation().isEnabled()) { res.add(remoteFieldsBaggagePropagationCustomizer(tracingConfig)); } return res; } private static brave.baggage.BaggagePropagationCustomizer remoteFieldsBaggagePropagationCustomizer( TracingConfig tracingConfig) { return (builder) -> { List<String> remoteFields = tracingConfig.getBaggage().getRemoteFields(); for (String fieldName : remoteFields) { builder.add(brave.baggage.BaggagePropagationConfig.SingleBaggageField.remote( brave.baggage.BaggageField.create(fieldName))); } }; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProvider.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OTelPropagatorProvider.java
/* * 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.tracing.tracer.otel; import org.apache.dubbo.tracing.tracer.PropagatorProvider; import io.micrometer.tracing.otel.bridge.OtelPropagator; import io.micrometer.tracing.propagation.Propagator; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.propagation.ContextPropagators; public class OTelPropagatorProvider implements PropagatorProvider { private static Propagator propagator; @Override public Propagator getPropagator() { return propagator; } protected static void createMicrometerPropagator(ContextPropagators contextPropagators, Tracer tracer) { propagator = new OtelPropagator(contextPropagators, tracer); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProvider.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/tracer/otel/OpenTelemetryProvider.java
/* * 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.tracing.tracer.otel; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.lang.Nullable; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.nested.BaggageConfig; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.config.nested.PropagationConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.tracing.exporter.otlp.OTlpSpanExporter; import org.apache.dubbo.tracing.exporter.zipkin.ZipkinSpanExporter; import org.apache.dubbo.tracing.tracer.TracerProvider; import org.apache.dubbo.tracing.utils.PropagationType; import java.util.ArrayList; import java.util.Collections; import java.util.List; import io.micrometer.tracing.Tracer; import io.micrometer.tracing.otel.bridge.CompositeSpanExporter; import io.micrometer.tracing.otel.bridge.EventListener; import io.micrometer.tracing.otel.bridge.EventPublishingContextWrapper; import io.micrometer.tracing.otel.bridge.OtelBaggageManager; import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; import io.micrometer.tracing.otel.bridge.OtelTracer; import io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener; import io.micrometer.tracing.otel.bridge.Slf4JEventListener; import io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator; import io.opentelemetry.api.common.AttributeKey; import static org.apache.dubbo.tracing.utils.ObservationConstants.DEFAULT_APPLICATION_NAME; public class OpenTelemetryProvider implements TracerProvider { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(OpenTelemetryProvider.class); private final ApplicationModel applicationModel; private final TracingConfig tracingConfig; private OTelEventPublisher publisher; private OtelCurrentTraceContext otelCurrentTraceContext; public OpenTelemetryProvider(ApplicationModel applicationModel, TracingConfig tracingConfig) { this.applicationModel = applicationModel; this.tracingConfig = tracingConfig; } @Override public Tracer getTracer() { // [OTel component] SpanExporter is a component that gets called when a span is finished. List<io.opentelemetry.sdk.trace.export.SpanExporter> spanExporters = getSpanExporters(); String applicationName = applicationModel .getApplicationConfigManager() .getApplication() .map(ApplicationConfig::getName) .orElse(DEFAULT_APPLICATION_NAME); this.publisher = new OTelEventPublisher(getEventListeners()); // [Micrometer Tracing component] A Micrometer Tracing wrapper for OTel this.otelCurrentTraceContext = createCurrentTraceContext(); // Due to https://github.com/micrometer-metrics/tracing/issues/343 String RESOURCE_ATTRIBUTES_CLASS_NAME = "io.opentelemetry.semconv.ResourceAttributes"; boolean isLowVersion = !ClassUtils.isPresent( RESOURCE_ATTRIBUTES_CLASS_NAME, Thread.currentThread().getContextClassLoader()); AttributeKey<String> serviceNameAttributeKey = AttributeKey.stringKey("service.name"); String SERVICE_NAME = "SERVICE_NAME"; if (isLowVersion) { RESOURCE_ATTRIBUTES_CLASS_NAME = "io.opentelemetry.semconv.resource.attributes.ResourceAttributes"; } try { serviceNameAttributeKey = (AttributeKey<String>) ClassUtils.resolveClass( RESOURCE_ATTRIBUTES_CLASS_NAME, Thread.currentThread().getContextClassLoader()) .getDeclaredField(SERVICE_NAME) .get(null); } catch (Throwable ignored) { } // [OTel component] SdkTracerProvider is an SDK implementation for TracerProvider io.opentelemetry.sdk.trace.SdkTracerProvider sdkTracerProvider = io.opentelemetry.sdk.trace.SdkTracerProvider.builder() .setSampler(getSampler()) .setResource(io.opentelemetry.sdk.resources.Resource.create( io.opentelemetry.api.common.Attributes.of(serviceNameAttributeKey, applicationName))) .addSpanProcessor(io.opentelemetry.sdk.trace.export.BatchSpanProcessor.builder( new CompositeSpanExporter(spanExporters, null, null, null)) .build()) .build(); io.opentelemetry.context.propagation.ContextPropagators otelContextPropagators = createOtelContextPropagators(); // [OTel component] The SDK implementation of OpenTelemetry io.opentelemetry.sdk.OpenTelemetrySdk openTelemetrySdk = io.opentelemetry.sdk.OpenTelemetrySdk.builder() .setTracerProvider(sdkTracerProvider) .setPropagators(otelContextPropagators) .build(); // [OTel component] Tracer is a component that handles the life-cycle of a span io.opentelemetry.api.trace.Tracer otelTracer = openTelemetrySdk.getTracerProvider().get("org.apache.dubbo", Version.getVersion()); OTelPropagatorProvider.createMicrometerPropagator(otelContextPropagators, otelTracer); // [Micrometer Tracing component] A Micrometer Tracing wrapper for OTel's Tracer. return new OtelTracer( otelTracer, otelCurrentTraceContext, publisher, new OtelBaggageManager( otelCurrentTraceContext, tracingConfig.getBaggage().getRemoteFields(), Collections.emptyList())); } private List<io.opentelemetry.sdk.trace.export.SpanExporter> getSpanExporters() { ExporterConfig exporterConfig = tracingConfig.getTracingExporter(); ExporterConfig.ZipkinConfig zipkinConfig = exporterConfig.getZipkinConfig(); ExporterConfig.OtlpConfig otlpConfig = exporterConfig.getOtlpConfig(); List<io.opentelemetry.sdk.trace.export.SpanExporter> res = new ArrayList<>(); if (zipkinConfig != null && StringUtils.isNotEmpty(zipkinConfig.getEndpoint())) { LOGGER.info("Create zipkin span exporter."); res.add(ZipkinSpanExporter.getSpanExporter(applicationModel, zipkinConfig)); } if (otlpConfig != null && StringUtils.isNotEmpty(otlpConfig.getEndpoint())) { LOGGER.info("Create OTlp span exporter."); res.add(OTlpSpanExporter.getSpanExporter(applicationModel, otlpConfig)); } return res; } /** * sampler with probability * * @return sampler */ private io.opentelemetry.sdk.trace.samplers.Sampler getSampler() { io.opentelemetry.sdk.trace.samplers.Sampler rootSampler = io.opentelemetry.sdk.trace.samplers.Sampler.traceIdRatioBased( tracingConfig.getSampling().getProbability()); return io.opentelemetry.sdk.trace.samplers.Sampler.parentBased(rootSampler); } private List<EventListener> getEventListeners() { List<EventListener> listeners = new ArrayList<>(); // [Micrometer Tracing component] A Micrometer Tracing listener for setting up MDC. Slf4JEventListener slf4JEventListener = new Slf4JEventListener(); listeners.add(slf4JEventListener); if (tracingConfig.getBaggage().getEnabled()) { // [Micrometer Tracing component] A Micrometer Tracing listener for setting Baggage in MDC. // Customizable with correlation fields. Slf4JBaggageEventListener slf4JBaggageEventListener = new Slf4JBaggageEventListener( tracingConfig.getBaggage().getCorrelation().getFields()); listeners.add(slf4JBaggageEventListener); } return listeners; } private OtelCurrentTraceContext createCurrentTraceContext() { io.opentelemetry.context.ContextStorage.addWrapper(new EventPublishingContextWrapper(publisher)); return new OtelCurrentTraceContext(); } private io.opentelemetry.context.propagation.ContextPropagators createOtelContextPropagators() { return io.opentelemetry.context.propagation.ContextPropagators.create( io.opentelemetry.context.propagation.TextMapPropagator.composite(PropagatorFactory.getPropagator( tracingConfig.getPropagation(), tracingConfig.getBaggage(), otelCurrentTraceContext))); } static class OTelEventPublisher implements OtelTracer.EventPublisher { private final List<EventListener> listeners; OTelEventPublisher(List<EventListener> listeners) { this.listeners = listeners; } @Override public void publishEvent(Object event) { for (EventListener listener : this.listeners) { listener.onEvent(event); } } } static class PropagatorFactory { public static io.opentelemetry.context.propagation.TextMapPropagator getPropagator( PropagationConfig propagationConfig, @Nullable BaggageConfig baggageConfig, @Nullable OtelCurrentTraceContext currentTraceContext) { if (baggageConfig == null || !baggageConfig.getEnabled()) { return getPropagatorWithoutBaggage(propagationConfig); } return getPropagatorWithBaggage(propagationConfig, baggageConfig, currentTraceContext); } private static io.opentelemetry.context.propagation.TextMapPropagator getPropagatorWithoutBaggage( PropagationConfig propagationConfig) { String type = propagationConfig.getType(); PropagationType propagationType = PropagationType.forValue(type); if (PropagationType.B3 == propagationType) { return io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(); } else if (PropagationType.W3C == propagationType) { return io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(); } return io.opentelemetry.context.propagation.TextMapPropagator.noop(); } private static io.opentelemetry.context.propagation.TextMapPropagator getPropagatorWithBaggage( PropagationConfig propagationConfig, BaggageConfig baggageConfig, OtelCurrentTraceContext currentTraceContext) { String type = propagationConfig.getType(); PropagationType propagationType = PropagationType.forValue(type); if (PropagationType.B3 == propagationType) { List<String> remoteFields = baggageConfig.getRemoteFields(); return io.opentelemetry.context.propagation.TextMapPropagator.composite( io.opentelemetry.extension.trace.propagation.B3Propagator.injectingSingleHeader(), new BaggageTextMapPropagator( remoteFields, new OtelBaggageManager(currentTraceContext, remoteFields, Collections.emptyList()))); } else if (PropagationType.W3C == propagationType) { List<String> remoteFields = baggageConfig.getRemoteFields(); return io.opentelemetry.context.propagation.TextMapPropagator.composite( io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator.getInstance(), io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator.getInstance(), new BaggageTextMapPropagator( remoteFields, new OtelBaggageManager(currentTraceContext, remoteFields, Collections.emptyList()))); } return io.opentelemetry.context.propagation.TextMapPropagator.noop(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/metrics/ObservationMeter.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/metrics/ObservationMeter.java
/* * 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.tracing.metrics; import org.apache.dubbo.metrics.MetricsGlobalRegistry; import org.apache.dubbo.rpc.model.ApplicationModel; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.observation.ObservationRegistry; public class ObservationMeter { public static void addMeterRegistry(ObservationRegistry registry, ApplicationModel applicationModel) { MeterRegistry meterRegistry = MetricsGlobalRegistry.getCompositeRegistry(applicationModel); registry.observationConfig() .observationHandler( new io.micrometer.core.instrument.observation.DefaultMeterObservationHandler(meterRegistry)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/PropagationType.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/PropagationType.java
/* * 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.tracing.utils; public enum PropagationType { W3C("W3C"), B3("B3"); private final String value; PropagationType(String type) { this.value = type; } public String getValue() { return value; } public static PropagationType forValue(String value) { PropagationType[] values = values(); for (PropagationType type : values) { if (type.getValue().equals(value)) { return type; } } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationConstants.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationConstants.java
/* * 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.tracing.utils; public class ObservationConstants { public static final String DEFAULT_APPLICATION_NAME = "dubbo-application"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationSupportUtil.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/utils/ObservationSupportUtil.java
/* * 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.tracing.utils; import org.apache.dubbo.common.utils.ClassUtils; public class ObservationSupportUtil { public static boolean isSupportObservation() { return isClassPresent("io.micrometer.observation.Observation") && isClassPresent("io.micrometer.observation.ObservationRegistry") && isClassPresent("io.micrometer.observation.ObservationHandler"); } public static boolean isSupportTracing() { return isClassPresent("io.micrometer.tracing.Tracer") && isClassPresent("io.micrometer.tracing.propagation.Propagator"); } public static boolean isSupportOTelTracer() { return isClassPresent("io.micrometer.tracing.otel.bridge.OtelTracer") && isClassPresent("io.opentelemetry.sdk.trace.SdkTracerProvider") && isClassPresent("io.opentelemetry.api.OpenTelemetry"); } public static boolean isSupportBraveTracer() { return isClassPresent("io.micrometer.tracing.Tracer") && isClassPresent("io.micrometer.tracing.brave.bridge.BraveTracer") && isClassPresent("brave.Tracing"); } public static boolean isSupportBraveURLSender() { return isClassPresent("zipkin2.reporter.urlconnection.URLConnectionSender"); } private static boolean isClassPresent(String className) { return ClassUtils.isPresent(className, ObservationSupportUtil.class.getClassLoader()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporter.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/otlp/OTlpSpanExporter.java
/* * 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.tracing.exporter.otlp; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; import io.opentelemetry.sdk.trace.export.SpanExporter; /** * OTlp span exporter for OTel. */ public class OTlpSpanExporter { public static SpanExporter getSpanExporter( ApplicationModel applicationModel, ExporterConfig.OtlpConfig otlpConfig) { OtlpGrpcSpanExporter externalOTlpGrpcSpanExporter = applicationModel.getBeanFactory().getBean(OtlpGrpcSpanExporter.class); if (externalOTlpGrpcSpanExporter != null) { return externalOTlpGrpcSpanExporter; } OtlpHttpSpanExporter externalOtlpHttpSpanExporter = applicationModel.getBeanFactory().getBean(OtlpHttpSpanExporter.class); if (externalOtlpHttpSpanExporter != null) { return externalOtlpHttpSpanExporter; } OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder() .setEndpoint(otlpConfig.getEndpoint()) .setTimeout(otlpConfig.getTimeout()) .setCompression(otlpConfig.getCompressionMethod()); for (Map.Entry<String, String> entry : otlpConfig.getHeaders().entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } return builder.build(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandler.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanHandler.java
/* * 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.tracing.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import brave.handler.SpanHandler; import zipkin2.Span; import zipkin2.reporter.AsyncReporter; import zipkin2.reporter.BytesEncoder; import zipkin2.reporter.SpanBytesEncoder; import zipkin2.reporter.urlconnection.URLConnectionSender; /** * Zipkin span handler for Brave. */ public class ZipkinSpanHandler { public static SpanHandler getSpanHandler( ApplicationModel applicationModel, ExporterConfig.ZipkinConfig zipkinConfig) { URLConnectionSender sender = applicationModel.getBeanFactory().getBean(URLConnectionSender.class); if (sender == null) { URLConnectionSender.Builder builder = URLConnectionSender.newBuilder(); builder.connectTimeout((int) zipkinConfig.getConnectTimeout().toMillis()); builder.readTimeout((int) zipkinConfig.getReadTimeout().toMillis()); builder.endpoint(zipkinConfig.getEndpoint()); sender = builder.build(); } BytesEncoder<Span> spanBytesEncoder = getSpanBytesEncoder(applicationModel); AsyncReporter<Span> spanReporter = AsyncReporter.builder(sender).build(spanBytesEncoder); return zipkin2.reporter.brave.ZipkinSpanHandler.newBuilder(spanReporter).build(); } private static BytesEncoder<zipkin2.Span> getSpanBytesEncoder(ApplicationModel applicationModel) { BytesEncoder<zipkin2.Span> encoder = applicationModel.getBeanFactory().getBean(BytesEncoder.class); return encoder == null ? SpanBytesEncoder.JSON_V2 : encoder; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporter.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/exporter/zipkin/ZipkinSpanExporter.java
/* * 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.tracing.exporter.zipkin; import org.apache.dubbo.config.nested.ExporterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import zipkin2.Span; import zipkin2.reporter.BytesEncoder; import zipkin2.reporter.SpanBytesEncoder; /** * Zipkin span exporter for OTel. */ public class ZipkinSpanExporter { public static io.opentelemetry.sdk.trace.export.SpanExporter getSpanExporter( ApplicationModel applicationModel, ExporterConfig.ZipkinConfig zipkinConfig) { BytesEncoder<Span> spanBytesEncoder = getSpanBytesEncoder(applicationModel); return io.opentelemetry.exporter.zipkin.ZipkinSpanExporter.builder() .setEncoder(spanBytesEncoder) .setEndpoint(zipkinConfig.getEndpoint()) .setReadTimeout(zipkinConfig.getReadTimeout()) .build(); } private static BytesEncoder<Span> getSpanBytesEncoder(ApplicationModel applicationModel) { BytesEncoder<zipkin2.Span> encoder = applicationModel.getBeanFactory().getBean(BytesEncoder.class); return encoder == null ? SpanBytesEncoder.JSON_V2 : encoder; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/handler/DubboServerTracingObservationHandler.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/handler/DubboServerTracingObservationHandler.java
/* * 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.tracing.handler; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.tracing.context.DubboServerContext; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationHandler; import io.micrometer.tracing.TraceContext; import io.micrometer.tracing.Tracer; public class DubboServerTracingObservationHandler<T extends DubboServerContext> implements ObservationHandler<T> { private static final String DEFAULT_TRACE_ID_KEY = "traceId"; private final Tracer tracer; public DubboServerTracingObservationHandler(Tracer tracer) { this.tracer = tracer; } @Override public void onScopeOpened(T context) { TraceContext traceContext = tracer.currentTraceContext().context(); if (traceContext == null) { return; } RpcContext.getServerContext().setAttachment(DEFAULT_TRACE_ID_KEY, traceContext.traceId()); } @Override public boolean supportsContext(Observation.Context context) { return context instanceof DubboServerContext; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/handler/DubboClientTracingObservationHandler.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/handler/DubboClientTracingObservationHandler.java
/* * 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.tracing.handler; import org.apache.dubbo.tracing.context.DubboClientContext; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationHandler; import io.micrometer.tracing.Tracer; public class DubboClientTracingObservationHandler<T extends DubboClientContext> implements ObservationHandler<T> { private final Tracer tracer; public DubboClientTracingObservationHandler(Tracer tracer) { this.tracer = tracer; } @Override public void onScopeOpened(T context) {} @Override public boolean supportsContext(Observation.Context context) { return context instanceof DubboClientContext; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboClientContext.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboClientContext.java
/* * 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.tracing.context; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import java.util.Objects; import io.micrometer.observation.transport.Kind; import io.micrometer.observation.transport.SenderContext; /** * Provider context for RPC. */ public class DubboClientContext extends SenderContext<Invocation> { private final Invoker<?> invoker; private final Invocation invocation; public DubboClientContext(Invoker<?> invoker, Invocation invocation) { super((carrier, key, value) -> Objects.requireNonNull(carrier).setAttachment(key, value), Kind.CLIENT); this.invoker = invoker; this.invocation = invocation; setCarrier(invocation); } public Invoker<?> getInvoker() { return invoker; } public Invocation getInvocation() { return invocation; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboServerContext.java
dubbo-metrics/dubbo-tracing/src/main/java/org/apache/dubbo/tracing/context/DubboServerContext.java
/* * 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.tracing.context; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import io.micrometer.observation.transport.Kind; import io.micrometer.observation.transport.ReceiverContext; /** * Consumer context for RPC. */ public class DubboServerContext extends ReceiverContext<Invocation> { private final Invoker<?> invoker; private final Invocation invocation; public DubboServerContext(Invoker<?> invoker, Invocation invocation) { super((carrier, s) -> carrier.getAttachment(s), Kind.SERVER); this.invoker = invoker; this.invocation = invocation; setCarrier(invocation); } public Invoker<?> getInvoker() { return invoker; } public Invocation getInvocation() { return invocation; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/MetricsConstants.java
/* * 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.metrics; public interface MetricsConstants { String INVOCATION = "metric_filter_invocation"; String METHOD_METRICS = "metric_filter_method_metrics"; String INVOCATION_METRICS_COUNTER = "metric_filter_invocation_counter"; String INVOCATION_SIDE = "metric_filter_side"; String INVOCATION_REQUEST_ERROR = "metric_request_error"; String ATTACHMENT_KEY_SERVICE = "serviceKey"; String ATTACHMENT_KEY_SIZE = "size"; String ATTACHMENT_KEY_LAST_NUM_MAP = "lastNumMap"; String ATTACHMENT_DIRECTORY_MAP = "dirNum"; int SELF_INCREMENT_SIZE = 1; String NETTY_METRICS_MAP = "nettyMetricsMap"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/TimePair.java
/* * 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.metrics.model; public class TimePair { private final long begin; private long end; private static final TimePair empty = new TimePair(0L); public TimePair(long currentTimeMillis) { this.begin = currentTimeMillis; } public static TimePair start() { return new TimePair(System.currentTimeMillis()); } public void end() { this.end = System.currentTimeMillis(); } public long calc() { return end - begin; } public static TimePair empty() { return empty; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsLevel.java
/* * 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.metrics.model.key; public enum MetricsLevel { APP, SERVICE, METHOD, CONFIG, REGISTRY }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/TypeWrapper.java
/* * 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.metrics.model.key; import org.apache.dubbo.common.utils.Assert; public class TypeWrapper { private final MetricsLevel level; private final MetricsKey postType; private final MetricsKey finishType; private final MetricsKey errorType; public TypeWrapper(MetricsLevel level, MetricsKey postType) { this(level, postType, null, null); } public TypeWrapper(MetricsLevel level, MetricsKey postType, MetricsKey finishType, MetricsKey errorType) { this.level = level; this.postType = postType; this.finishType = finishType; this.errorType = errorType; } public MetricsLevel getLevel() { return level; } public boolean isAssignableFrom(Object type) { Assert.notNull(type, "Type can not be null"); return type.equals(postType) || type.equals(finishType) || type.equals(errorType); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKey.java
/* * 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.metrics.model.key; public enum MetricsKey { APPLICATION_METRIC_INFO("dubbo.application.info.total", "Total Application Info"), CONFIGCENTER_METRIC_TOTAL("dubbo.configcenter.total", "Config Changed Total"), // provider metrics key METRIC_REQUESTS("dubbo.%s.requests.total", "Total Requests"), METRIC_REQUESTS_SUCCEED("dubbo.%s.requests.succeed.total", "Total Succeed Requests"), METRIC_REQUEST_BUSINESS_FAILED("dubbo.%s.requests.business.failed.total", "Total Failed Business Requests"), METRIC_REQUESTS_PROCESSING("dubbo.%s.requests.processing.total", "Processing Requests"), METRIC_REQUESTS_TIMEOUT("dubbo.%s.requests.timeout.total", "Total Timeout Failed Requests"), METRIC_REQUESTS_LIMIT("dubbo.%s.requests.limit.total", "Total Limit Failed Requests"), METRIC_REQUESTS_FAILED("dubbo.%s.requests.unknown.failed.total", "Total Unknown Failed Requests"), METRIC_REQUESTS_TOTAL_FAILED("dubbo.%s.requests.failed.total", "Total Failed Requests"), METRIC_REQUESTS_NETWORK_FAILED("dubbo.%s.requests.failed.network.total", "Total network Failed Requests"), METRIC_REQUESTS_SERVICE_UNAVAILABLE_FAILED( "dubbo.%s.requests.failed.service.unavailable.total", "Total Service Unavailable Failed Requests"), METRIC_REQUESTS_CODEC_FAILED("dubbo.%s.requests.failed.codec.total", "Total Codec Failed Requests"), METRIC_REQUESTS_TOTAL_AGG("dubbo.%s.requests.total.aggregate", "Aggregated Total Requests"), METRIC_REQUESTS_SUCCEED_AGG("dubbo.%s.requests.succeed.aggregate", "Aggregated Succeed Requests"), METRIC_REQUESTS_FAILED_AGG("dubbo.%s.requests.failed.aggregate", "Aggregated Failed Requests"), METRIC_REQUEST_BUSINESS_FAILED_AGG( "dubbo.%s.requests.business.failed.aggregate", "Aggregated Business Failed Requests"), METRIC_REQUESTS_TIMEOUT_AGG("dubbo.%s.requests.timeout.failed.aggregate", "Aggregated timeout Failed Requests"), METRIC_REQUESTS_LIMIT_AGG("dubbo.%s.requests.limit.aggregate", "Aggregated limit Requests"), METRIC_REQUESTS_TOTAL_FAILED_AGG("dubbo.%s.requests.failed.total.aggregate", "Aggregated failed total Requests"), METRIC_REQUESTS_NETWORK_FAILED_AGG( "dubbo.%s.requests.failed.network.total.aggregate", "Aggregated failed network total Requests"), METRIC_REQUESTS_CODEC_FAILED_AGG( "dubbo.%s.requests.failed.codec.total.aggregate", "Aggregated failed codec total Requests"), METRIC_REQUESTS_TOTAL_SERVICE_UNAVAILABLE_FAILED_AGG( "dubbo.%s.requests.failed.service.unavailable.total.aggregate", "Aggregated failed codec total Requests"), METRIC_QPS("dubbo.%s.qps.total", "Query Per Seconds"), METRIC_RT_LAST("dubbo.%s.rt.milliseconds.last", "Last Response Time"), METRIC_RT_MIN("dubbo.%s.rt.milliseconds.min", "Min Response Time"), METRIC_RT_MAX("dubbo.%s.rt.milliseconds.max", "Max Response Time"), METRIC_RT_SUM("dubbo.%s.rt.milliseconds.sum", "Sum Response Time"), METRIC_RT_AVG("dubbo.%s.rt.milliseconds.avg", "Average Response Time"), METRIC_RT_P99("dubbo.%s.rt.milliseconds.p99", "Response Time P99"), METRIC_RT_P95("dubbo.%s.rt.milliseconds.p95", "Response Time P95"), METRIC_RT_P90("dubbo.%s.rt.milliseconds.p90", "Response Time P90"), METRIC_RT_P50("dubbo.%s.rt.milliseconds.p50", "Response Time P50"), METRIC_RT_MIN_AGG("dubbo.%s.rt.min.milliseconds.aggregate", "Aggregated Min Response"), METRIC_RT_MAX_AGG("dubbo.%s.rt.max.milliseconds.aggregate", "Aggregated Max Response"), METRIC_RT_AVG_AGG("dubbo.%s.rt.avg.milliseconds.aggregate", "Aggregated Avg Response"), // register metrics key REGISTER_METRIC_REQUESTS("dubbo.registry.register.requests.total", "Total Register Requests"), REGISTER_METRIC_REQUESTS_SUCCEED("dubbo.registry.register.requests.succeed.total", "Succeed Register Requests"), REGISTER_METRIC_REQUESTS_FAILED("dubbo.registry.register.requests.failed.total", "Failed Register Requests"), METRIC_RT_HISTOGRAM("dubbo.%s.rt.milliseconds.histogram", "Response Time Histogram"), GENERIC_METRIC_REQUESTS("dubbo.%s.requests.total", "Total %s Requests"), GENERIC_METRIC_REQUESTS_SUCCEED("dubbo.%s.requests.succeed.total", "Succeed %s Requests"), GENERIC_METRIC_REQUESTS_FAILED("dubbo.%s.requests.failed.total", "Failed %s Requests"), // subscribe metrics key SUBSCRIBE_METRIC_NUM("dubbo.registry.subscribe.num.total", "Total Subscribe Num"), SUBSCRIBE_METRIC_NUM_SUCCEED("dubbo.registry.subscribe.num.succeed.total", "Succeed Subscribe Num"), SUBSCRIBE_METRIC_NUM_FAILED("dubbo.registry.subscribe.num.failed.total", "Failed Subscribe Num"), // directory metrics key DIRECTORY_METRIC_NUM_ALL("dubbo.registry.directory.num.all", "All Directory Urls"), DIRECTORY_METRIC_NUM_VALID("dubbo.registry.directory.num.valid.total", "Valid Directory Urls"), DIRECTORY_METRIC_NUM_TO_RECONNECT("dubbo.registry.directory.num.to_reconnect.total", "ToReconnect Directory Urls"), DIRECTORY_METRIC_NUM_DISABLE("dubbo.registry.directory.num.disable.total", "Disable Directory Urls"), NOTIFY_METRIC_REQUESTS("dubbo.registry.notify.requests.total", "Total Notify Requests"), NOTIFY_METRIC_NUM_LAST("dubbo.registry.notify.num.last", "Last Notify Nums"), THREAD_POOL_CORE_SIZE("dubbo.thread.pool.core.size", "Thread Pool Core Size"), THREAD_POOL_LARGEST_SIZE("dubbo.thread.pool.largest.size", "Thread Pool Largest Size"), THREAD_POOL_MAX_SIZE("dubbo.thread.pool.max.size", "Thread Pool Max Size"), THREAD_POOL_ACTIVE_SIZE("dubbo.thread.pool.active.size", "Thread Pool Active Size"), THREAD_POOL_THREAD_COUNT("dubbo.thread.pool.thread.count", "Thread Pool Thread Count"), THREAD_POOL_QUEUE_SIZE("dubbo.thread.pool.queue.size", "Thread Pool Queue Size"), THREAD_POOL_THREAD_REJECT_COUNT("dubbo.thread.pool.reject.thread.count", "Thread Pool Reject Thread Count"), // metadata push metrics key METADATA_PUSH_METRIC_NUM("dubbo.metadata.push.num.total", "Total Push Num"), METADATA_PUSH_METRIC_NUM_SUCCEED("dubbo.metadata.push.num.succeed.total", "Succeed Push Num"), METADATA_PUSH_METRIC_NUM_FAILED("dubbo.metadata.push.num.failed.total", "Failed Push Num"), // metadata subscribe metrics key METADATA_SUBSCRIBE_METRIC_NUM("dubbo.metadata.subscribe.num.total", "Total Metadata Subscribe Num"), METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED( "dubbo.metadata.subscribe.num.succeed.total", "Succeed Metadata Subscribe Num"), METADATA_SUBSCRIBE_METRIC_NUM_FAILED("dubbo.metadata.subscribe.num.failed.total", "Failed Metadata Subscribe Num"), // register service metrics key SERVICE_REGISTER_METRIC_REQUESTS("dubbo.registry.register.service.total", "Total Service-Level Register Requests"), SERVICE_REGISTER_METRIC_REQUESTS_SUCCEED( "dubbo.registry.register.service.succeed.total", "Succeed Service-Level Register Requests"), SERVICE_REGISTER_METRIC_REQUESTS_FAILED( "dubbo.registry.register.service.failed.total", "Failed Service-Level Register Requests"), // subscribe metrics key SERVICE_SUBSCRIBE_METRIC_NUM("dubbo.registry.subscribe.service.num.total", "Total Service-Level Subscribe Num"), SERVICE_SUBSCRIBE_METRIC_NUM_SUCCEED( "dubbo.registry.subscribe.service.num.succeed.total", "Succeed Service-Level Num"), SERVICE_SUBSCRIBE_METRIC_NUM_FAILED( "dubbo.registry.subscribe.service.num.failed.total", "Failed Service-Level Num"), // store provider metadata service key STORE_PROVIDER_METADATA("dubbo.metadata.store.provider.total", "Store Provider Metadata"), STORE_PROVIDER_METADATA_SUCCEED("dubbo.metadata.store.provider.succeed.total", "Succeed Store Provider Metadata"), STORE_PROVIDER_METADATA_FAILED("dubbo.metadata.store.provider.failed.total", "Failed Store Provider Metadata"), METADATA_GIT_COMMITID_METRIC("git.commit.id", "Git Commit Id Metrics"), // consumer metrics key INVOKER_NO_AVAILABLE_COUNT( "dubbo.consumer.invoker.no.available.count", "Request Throw No Invoker Available Exception Count"), // count the number of occurrences of each error code ERROR_CODE_COUNT("dubbo.error.code.count", "The Count Of Occurrences for Each Error Code"), // netty metrics key NETTY_ALLOCATOR_HEAP_MEMORY_USED("netty.allocator.memory.used", "Netty Allocator Memory Used"), NETTY_ALLOCATOR_DIRECT_MEMORY_USED("netty.allocator.direct.memory.used", "Netty Allocator Direct Memory Used"), NETTY_ALLOCATOR_PINNED_DIRECT_MEMORY( "netty.allocator.pinned.direct.memory", "Netty Allocator Pinned Direct Memory"), NETTY_ALLOCATOR_PINNED_HEAP_MEMORY("netty.allocator.pinned.heap.memory", "Netty Allocator Pinned Heap Memory"), NETTY_ALLOCATOR_HEAP_ARENAS_NUM("netty.allocator.heap.arenas.num", "Netty Allocator Heap Arenas Num"), NETTY_ALLOCATOR_DIRECT_ARENAS_NUM("netty.allocator.direct.arenas.num", "Netty Allocator Direct Arenas Num"), NETTY_ALLOCATOR_NORMAL_CACHE_SIZE("netty.allocator.normal.cache.size", "Netty Allocator Normal Cache Size"), NETTY_ALLOCATOR_SMALL_CACHE_SIZE("netty.allocator.small.cache.size", "Netty Allocator Small Cache Size"), NETTY_ALLOCATOR_THREAD_LOCAL_CACHES_NUM( "netty.allocator.thread.local.caches.num", "Netty Allocator Thread Local Caches Num"), NETTY_ALLOCATOR_CHUNK_SIZE("netty.allocator.chunk.size", "Netty Allocator Chunk Size"), ; private String name; private String description; public final String getName() { return this.name; } public final String getNameByType(String type) { return String.format(name, type); } public static MetricsKey getMetricsByName(String name) { for (MetricsKey metricsKey : MetricsKey.values()) { if (metricsKey.getName().equals(name)) { return metricsKey; } } return null; } public final String getDescription() { return this.description; } MetricsKey(String name, String description) { this.name = name; this.description = description; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/exception/MetricsNeverHappenException.java
/* * 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.metrics.exception; public class MetricsNeverHappenException extends RuntimeException { public MetricsNeverHappenException(String message) { super(message); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/TimeCounterEvent.java
/* * 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.metrics.event; import org.apache.dubbo.metrics.model.TimePair; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; /** * Mark certain types of events, allow automatic recording of start and end times, and provide time pairs */ public abstract class TimeCounterEvent extends MetricsEvent { private final TimePair timePair; public TimeCounterEvent(ApplicationModel source, TypeWrapper typeWrapper) { super(source, typeWrapper); this.timePair = TimePair.start(); } public TimeCounterEvent( ApplicationModel source, String appName, MetricsEventMulticaster metricsDispatcher, TypeWrapper typeWrapper) { super(source, appName, metricsDispatcher, typeWrapper); this.timePair = TimePair.start(); } public TimePair getTimePair() { return timePair; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventMulticaster.java
/* * 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.metrics.event; import org.apache.dubbo.metrics.listener.MetricsListener; public interface MetricsEventMulticaster { void addListener(MetricsListener<?> listener); void publishEvent(MetricsEvent event); void publishFinishEvent(TimeCounterEvent event); void publishErrorEvent(TimeCounterEvent event); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEventBus.java
/* * 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.metrics.event; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION; /** * Dispatches events to listeners, and provides ways for listeners to register themselves. */ public class MetricsEventBus { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetricsEventBus.class); /** * Posts an event to all registered subscribers and only once. * * @param event event to post. */ public static void publish(MetricsEvent event) { if (event == null || event.getSource() == null) { return; } MetricsEventMulticaster dispatcher = event.getMetricsEventMulticaster(); Optional.ofNullable(dispatcher).ifPresent(d -> { tryInvoke(() -> d.publishEvent(event)); }); } /** * Posts an event to all registered subscribers. * Full lifecycle post, judging success or failure by whether there is an exception * Loop around the event target and return the original processing result * * @param event event to post. * @param targetSupplier original processing result targetSupplier */ public static <T> T post(MetricsEvent event, Supplier<T> targetSupplier) { return post(event, targetSupplier, null); } /** * Full lifecycle post, success and failure conditions can be customized * * @param event event to post. * @param targetSupplier original processing result supplier * @param trFunction Custom event success criteria, judged according to the returned boolean type * @param <T> Biz result type * @return Biz result */ public static <T> T post(MetricsEvent event, Supplier<T> targetSupplier, Function<T, Boolean> trFunction) { T result; tryInvoke(() -> before(event)); if (trFunction == null) { try { result = targetSupplier.get(); } catch (Throwable e) { tryInvoke(() -> error(event)); throw e; } tryInvoke(() -> after(event, result)); } else { // Custom failure status result = targetSupplier.get(); if (trFunction.apply(result)) { tryInvoke(() -> after(event, result)); } else { tryInvoke(() -> error(event)); } } return result; } public static void tryInvoke(Runnable runnable) { if (runnable == null) { return; } try { runnable.run(); } catch (Throwable e) { logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", "invoke metric event error" + e.getMessage()); } } /** * Applicable to the scene where execution and return are separated, * eventSaveRunner saves the event, so that the calculation rt is introverted */ public static void before(MetricsEvent event) { MetricsEventMulticaster dispatcher = validate(event); if (dispatcher == null) return; tryInvoke(() -> dispatcher.publishEvent(event)); } public static void after(MetricsEvent event, Object result) { MetricsEventMulticaster dispatcher = validate(event); if (dispatcher == null) return; tryInvoke(() -> { event.customAfterPost(result); if (event instanceof TimeCounterEvent) { dispatcher.publishFinishEvent((TimeCounterEvent) event); } }); } public static void error(MetricsEvent event) { MetricsEventMulticaster dispatcher = validate(event); if (dispatcher == null) return; tryInvoke(() -> { if (event instanceof TimeCounterEvent) { dispatcher.publishErrorEvent((TimeCounterEvent) event); } }); } private static MetricsEventMulticaster validate(MetricsEvent event) { MetricsEventMulticaster dispatcher = event.getMetricsEventMulticaster(); if (dispatcher == null) { return null; } if (!(event instanceof TimeCounterEvent)) { return null; } return dispatcher; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/event/MetricsEvent.java
/* * 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.metrics.event; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.metrics.exception.MetricsNeverHappenException; import org.apache.dubbo.metrics.model.key.TypeWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.IdentityHashMap; import java.util.Map; /** * BaseMetricsEvent. */ public abstract class MetricsEvent { /** * Metric object. (eg. MethodMetric) */ protected final transient ApplicationModel source; private boolean available = true; private final TypeWrapper typeWrapper; private final String appName; private final MetricsEventMulticaster metricsEventMulticaster; private final Map<String, Object> attachments = new IdentityHashMap<>(8); public MetricsEvent(ApplicationModel source, TypeWrapper typeWrapper) { this(source, null, null, typeWrapper); } public MetricsEvent( ApplicationModel source, String appName, MetricsEventMulticaster metricsEventMulticaster, TypeWrapper typeWrapper) { this.typeWrapper = typeWrapper; if (source == null) { this.source = ApplicationModel.defaultModel(); // Appears only in unit tests this.available = false; } else { this.source = source; } if (metricsEventMulticaster == null) { if (this.source.isDestroyed()) { this.metricsEventMulticaster = null; } else { ScopeBeanFactory beanFactory = this.source.getBeanFactory(); if (beanFactory.isDestroyed()) { this.metricsEventMulticaster = null; } else { MetricsEventMulticaster dispatcher = beanFactory.getBean(MetricsEventMulticaster.class); this.metricsEventMulticaster = dispatcher; } } } else { this.metricsEventMulticaster = metricsEventMulticaster; } if (appName == null) { this.appName = this.source.tryGetApplicationName(); } else { this.appName = appName; } } @SuppressWarnings("unchecked") public <T> T getAttachmentValue(String key) { if (key == null) { throw new MetricsNeverHappenException("Attachment key is null"); } return (T) attachments.get(key); } public Map<String, Object> getAttachments() { return Collections.unmodifiableMap(attachments); } public void putAttachment(String key, Object value) { attachments.put(key, value); } public void putAttachments(Map<String, String> attachments) { this.attachments.putAll(attachments); } public void setAvailable(boolean available) { this.available = available; } public boolean isAvailable() { return available; } public void customAfterPost(Object postResult) {} public ApplicationModel getSource() { return source; } public MetricsEventMulticaster getMetricsEventMulticaster() { return metricsEventMulticaster; } public String appName() { return appName; } public TypeWrapper getTypeWrapper() { return typeWrapper; } public boolean isAssignableFrom(Object type) { return typeWrapper.isAssignableFrom(type); } public String toString() { return getClass().getName() + "[source=" + source + "]"; } public enum Type { TOTAL("TOTAL_%s"), SUCCEED("SUCCEED_%s"), BUSINESS_FAILED("BUSINESS_FAILED_%s"), REQUEST_TIMEOUT("REQUEST_TIMEOUT_%s"), REQUEST_LIMIT("REQUEST_LIMIT_%s"), PROCESSING("PROCESSING_%s"), UNKNOWN_FAILED("UNKNOWN_FAILED_%s"), TOTAL_FAILED("TOTAL_FAILED_%s"), APPLICATION_INFO("APPLICATION_INFO_%s"), NETWORK_EXCEPTION("NETWORK_EXCEPTION_%s"), SERVICE_UNAVAILABLE("SERVICE_UNAVAILABLE_%s"), CODEC_EXCEPTION("CODEC_EXCEPTION_%s"), NO_INVOKER_AVAILABLE("NO_INVOKER_AVAILABLE_%s"), ; private final String name; public final String getName() { return this.name; } public final String getNameByType(String type) { return String.format(name, type); } Type(String name) { this.name = name; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java
dubbo-metrics/dubbo-metrics-event/src/main/java/org/apache/dubbo/metrics/listener/MetricsListener.java
/* * 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.metrics.listener; import org.apache.dubbo.metrics.event.MetricsEvent; /** * Metrics Listener. */ public interface MetricsListener<E extends MetricsEvent> { boolean isSupport(MetricsEvent event); /** * notify event. * * @param event BaseMetricsEvent */ void onEvent(E event); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java
dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java
/* * 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.configcenter.support.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; import org.apache.dubbo.common.extension.ExtensionLoader; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO refactor using mockito */ @Disabled("Disabled Due to Zookeeper in Github Actions") class ZookeeperDynamicConfigurationTest { private static CuratorFramework client; private static URL configUrl; private static DynamicConfiguration configuration; private static int zookeeperServerPort1; private static String zookeeperConnectionAddress1; @BeforeAll public static void setUp() throws Exception { zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1"); zookeeperServerPort1 = Integer.parseInt( zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1)); client = CuratorFrameworkFactory.newClient( "127.0.0.1:" + zookeeperServerPort1, 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3)); client.start(); try { setData("/dubbo/config/dubbo/dubbo.properties", "The content from dubbo.properties"); setData("/dubbo/config/dubbo/service:version:group.configurators", "The content from configurators"); setData("/dubbo/config/appname", "The content from higher level node"); setData("/dubbo/config/dubbo/appname.tag-router", "The content from appname tagrouters"); setData( "/dubbo/config/dubbo/never.change.DemoService.configurators", "Never change value from configurators"); } catch (Exception e) { e.printStackTrace(); } configUrl = URL.valueOf(zookeeperConnectionAddress1); configuration = ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class) .getExtension(configUrl.getProtocol()) .getDynamicConfiguration(configUrl); } private static void setData(String path, String data) throws Exception { if (client.checkExists().forPath(path) == null) { client.create().creatingParentsIfNeeded().forPath(path); } client.setData().forPath(path, data.getBytes()); } private ConfigurationListener mockListener(CountDownLatch latch, String[] value, Map<String, Integer> countMap) { ConfigurationListener listener = Mockito.mock(ConfigurationListener.class); Mockito.doAnswer(invoke -> { ConfigChangedEvent event = invoke.getArgument(0); Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); countMap.put(event.getKey(), ++count); value[0] = event.getContent(); latch.countDown(); return null; }) .when(listener) .process(Mockito.any()); return listener; } @Test void testGetConfig() { Assertions.assertEquals( "The content from dubbo.properties", configuration.getConfig("dubbo.properties", "dubbo")); } @Test void testAddListener() throws Exception { CountDownLatch latch = new CountDownLatch(4); String[] value1 = new String[1], value2 = new String[1], value3 = new String[1], value4 = new String[1]; Map<String, Integer> countMap1 = new HashMap<>(), countMap2 = new HashMap<>(), countMap3 = new HashMap<>(), countMap4 = new HashMap<>(); ConfigurationListener listener1 = mockListener(latch, value1, countMap1); ConfigurationListener listener2 = mockListener(latch, value2, countMap2); ConfigurationListener listener3 = mockListener(latch, value3, countMap3); ConfigurationListener listener4 = mockListener(latch, value4, countMap4); configuration.addListener("service:version:group.configurators", listener1); configuration.addListener("service:version:group.configurators", listener2); configuration.addListener("appname.tag-router", listener3); configuration.addListener("appname.tag-router", listener4); Thread.sleep(100); setData("/dubbo/config/dubbo/service:version:group.configurators", "new value1"); Thread.sleep(100); setData("/dubbo/config/dubbo/appname.tag-router", "new value2"); Thread.sleep(100); setData("/dubbo/config/appname", "new value3"); Thread.sleep(5000); latch.await(); Assertions.assertEquals(1, countMap1.get("service:version:group.configurators")); Assertions.assertEquals(1, countMap2.get("service:version:group.configurators")); Assertions.assertEquals(1, countMap3.get("appname.tag-router")); Assertions.assertEquals(1, countMap4.get("appname.tag-router")); Assertions.assertEquals("new value1", value1[0]); Assertions.assertEquals("new value1", value2[0]); Assertions.assertEquals("new value2", value3[0]); Assertions.assertEquals("new value2", value4[0]); } @Test void testPublishConfig() { String key = "user-service"; String group = "org.apache.dubbo.service.UserService"; String content = "test"; assertTrue(configuration.publishConfig(key, group, content)); assertEquals("test", configuration.getProperties(key, group)); } @Test void testPublishConfigCas() { String key = "user-service-cas"; String group = "org.apache.dubbo.service.UserService"; String content = "test"; ConfigItem configItem = configuration.getConfigItem(key, group); assertTrue(configuration.publishConfigCas(key, group, content, configItem.getTicket())); configItem = configuration.getConfigItem(key, group); assertEquals("test", configItem.getContent()); assertTrue(configuration.publishConfigCas(key, group, "newtest", configItem.getTicket())); assertFalse(configuration.publishConfigCas(key, group, "newtest2", configItem.getTicket())); assertEquals("newtest", configuration.getConfigItem(key, group).getContent()); } // // @Test // public void testGetConfigKeysAndContents() { // // String group = "mapping"; // String key = "org.apache.dubbo.service.UserService"; // String content = "app1"; // // String key2 = "org.apache.dubbo.service.UserService2"; // // assertTrue(configuration.publishConfig(key, group, content)); // assertTrue(configuration.publishConfig(key2, group, content)); // // Set<String> configKeys = configuration.getConfigKeys(group); // // assertEquals(new TreeSet(asList(key, key2)), configKeys); // } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java
dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java
/* * 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.configcenter.support.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration; import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClient; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.zookeeper.data.Stat; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION; public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration { private final Executor executor; private ZookeeperClient zkClient; private final CacheListener cacheListener; private static final int DEFAULT_ZK_EXECUTOR_THREADS_NUM = 1; private static final int DEFAULT_QUEUE = 10000; private static final Long THREAD_KEEP_ALIVE_TIME = 0L; private final ApplicationModel applicationModel; ZookeeperDynamicConfiguration( URL url, ZookeeperClientManager zookeeperClientManager, ApplicationModel applicationModel) { super(url); this.cacheListener = new CacheListener(); this.applicationModel = applicationModel; final String threadName = this.getClass().getSimpleName(); this.executor = new ThreadPoolExecutor( DEFAULT_ZK_EXECUTOR_THREADS_NUM, DEFAULT_ZK_EXECUTOR_THREADS_NUM, THREAD_KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(DEFAULT_QUEUE), new NamedThreadFactory(threadName, true), new AbortPolicyWithReport(threadName, url)); zkClient = zookeeperClientManager.connect(url); boolean isConnected = zkClient.isConnected(); if (!isConnected) { IllegalStateException illegalStateException = new IllegalStateException( "Failed to connect with zookeeper, pls check if url " + url + " is correct."); if (logger != null) { logger.error( CONFIG_FAILED_CONNECT_REGISTRY, "configuration server offline", "", "Failed to connect with zookeeper", illegalStateException); } throw illegalStateException; } } /** * @param key e.g., {service}.configurators, {service}.tagrouters, {group}.dubbo.properties * @return */ @Override public String getInternalProperty(String key) { return zkClient.getContent(buildPathKey("", key)); } @Override protected void doClose() throws Exception { // remove data listener Map<String, ZookeeperDataListener> pathKeyListeners = cacheListener.getPathKeyListeners(); for (Map.Entry<String, ZookeeperDataListener> entry : pathKeyListeners.entrySet()) { zkClient.removeDataListener(entry.getKey(), entry.getValue()); } cacheListener.clear(); // zkClient is shared in framework, should not close it here // zkClient.close(); // See: org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter#destroy() // All zk clients is created and destroyed in ZookeeperTransporter. zkClient = null; } @Override protected boolean doPublishConfig(String pathKey, String content) throws Exception { zkClient.createOrUpdate(pathKey, content, false); return true; } @Override public boolean publishConfigCas(String key, String group, String content, Object ticket) { try { if (ticket != null && !(ticket instanceof Stat)) { throw new IllegalArgumentException("zookeeper publishConfigCas requires stat type ticket"); } String pathKey = buildPathKey(group, key); zkClient.createOrUpdate(pathKey, content, false, ticket == null ? 0 : ((Stat) ticket).getVersion()); return true; } catch (Exception e) { logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "zookeeper publishConfigCas failed.", e); return false; } } @Override protected String doGetConfig(String pathKey) throws Exception { return zkClient.getContent(pathKey); } @Override public ConfigItem getConfigItem(String key, String group) { String pathKey = buildPathKey(group, key); return zkClient.getConfigItem(pathKey); } @Override protected boolean doRemoveConfig(String pathKey) throws Exception { zkClient.delete(pathKey); return true; } @Override protected Collection<String> doGetConfigKeys(String groupPath) { return zkClient.getChildren(groupPath); } @Override protected void doAddListener(String pathKey, ConfigurationListener listener, String key, String group) { ZookeeperDataListener cachedListener = cacheListener.getCachedListener(pathKey); if (cachedListener != null) { cachedListener.addListener(listener); } else { ZookeeperDataListener addedListener = cacheListener.addListener(pathKey, listener, key, group, applicationModel); zkClient.addDataListener(pathKey, addedListener, executor); } } @Override protected void doRemoveListener(String pathKey, ConfigurationListener listener) { ZookeeperDataListener zookeeperDataListener = cacheListener.removeListener(pathKey, listener); if (zookeeperDataListener != null && CollectionUtils.isEmpty(zookeeperDataListener.getListeners())) { zkClient.removeDataListener(pathKey, zookeeperDataListener); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java
dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java
/* * 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.configcenter.support.zookeeper; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.remoting.zookeeper.curator5.DataListener; import org.apache.dubbo.remoting.zookeeper.curator5.EventType; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * one path has multi configurationListeners */ public class ZookeeperDataListener implements DataListener { private String path; private String key; private String group; private Set<ConfigurationListener> listeners; private ApplicationModel applicationModel; public ZookeeperDataListener(String path, String key, String group, ApplicationModel applicationModel) { this.path = path; this.key = key; this.group = group; this.listeners = new CopyOnWriteArraySet<>(); this.applicationModel = applicationModel; } public void addListener(ConfigurationListener configurationListener) { listeners.add(configurationListener); } public void removeListener(ConfigurationListener configurationListener) { listeners.remove(configurationListener); } public Set<ConfigurationListener> getListeners() { return listeners; } @Override public void dataChanged(String path, Object value, EventType eventType) { if (!this.path.equals(path)) { return; } ConfigChangeType changeType; if (EventType.NodeCreated.equals(eventType)) { changeType = ConfigChangeType.ADDED; } else if (value == null) { changeType = ConfigChangeType.DELETED; } else { changeType = ConfigChangeType.MODIFIED; } ConfigChangedEvent configChangeEvent = new ConfigChangedEvent(key, group, (String) value, changeType); if (CollectionUtils.isNotEmpty(listeners)) { listeners.forEach(listener -> listener.process(configChangeEvent)); } MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( applicationModel, configChangeEvent.getKey(), configChangeEvent.getGroup(), ConfigCenterEvent.ZK_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java
dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java
/* * 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.configcenter.support.zookeeper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager; import org.apache.dubbo.rpc.model.ApplicationModel; public class ZookeeperDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { private final ZookeeperClientManager zookeeperClientManager; private final ApplicationModel applicationModel; public ZookeeperDynamicConfigurationFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; this.zookeeperClientManager = ZookeeperClientManager.getInstance(applicationModel); } @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new ZookeeperDynamicConfiguration(url, zookeeperClientManager, applicationModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java
dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java
/* * 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.configcenter.support.zookeeper; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * one path has one zookeeperDataListener */ public class CacheListener { private final ConcurrentMap<String, ZookeeperDataListener> pathKeyListeners = new ConcurrentHashMap<>(); public CacheListener() {} public ZookeeperDataListener addListener( String pathKey, ConfigurationListener configurationListener, String key, String group, ApplicationModel applicationModel) { ZookeeperDataListener zookeeperDataListener = ConcurrentHashMapUtils.computeIfAbsent( pathKeyListeners, pathKey, _pathKey -> new ZookeeperDataListener(_pathKey, key, group, applicationModel)); zookeeperDataListener.addListener(configurationListener); return zookeeperDataListener; } public ZookeeperDataListener removeListener(String pathKey, ConfigurationListener configurationListener) { ZookeeperDataListener zookeeperDataListener = pathKeyListeners.get(pathKey); if (zookeeperDataListener != null) { zookeeperDataListener.removeListener(configurationListener); if (CollectionUtils.isEmpty(zookeeperDataListener.getListeners())) { pathKeyListeners.remove(pathKey); } } return zookeeperDataListener; } public ZookeeperDataListener getCachedListener(String pathKey) { return pathKeyListeners.get(pathKey); } public Map<String, ZookeeperDataListener> getPathKeyListeners() { return pathKeyListeners; } public void clear() { pathKeyListeners.clear(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java
dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationTest.java
/* * 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.common.config.configcenter.file; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.URL.valueOf; import static org.apache.dubbo.common.config.configcenter.DynamicConfiguration.DEFAULT_GROUP; import static org.apache.dubbo.common.config.configcenter.file.FileSystemDynamicConfiguration.CONFIG_CENTER_DIR_PARAM_NAME; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link FileSystemDynamicConfiguration} Test */ // Test often failed on GitHub Actions Platform because of file system on Azure // Change to Disabled because DisabledIfEnvironmentVariable does not work on GitHub. @Disabled class FileSystemDynamicConfigurationTest { private final Logger logger = LoggerFactory.getLogger(getClass()); private FileSystemDynamicConfiguration configuration; private static final String KEY = "abc-def-ghi"; private static final String CONTENT = "Hello,World"; @BeforeEach public void init() { File rootDirectory = new File(getClassPath(), "config-center"); rootDirectory.mkdirs(); try { FileUtils.cleanDirectory(rootDirectory); } catch (IOException e) { e.printStackTrace(); } URL url = valueOf("dubbo://127.0.0.1:20880") .addParameter(CONFIG_CENTER_DIR_PARAM_NAME, rootDirectory.getAbsolutePath()); configuration = new FileSystemDynamicConfiguration(url); } @AfterEach public void destroy() throws Exception { FileUtils.deleteQuietly(configuration.getRootDirectory()); configuration.close(); } private String getClassPath() { return getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); } @Test void testInit() { assertEquals(new File(getClassPath(), "config-center"), configuration.getRootDirectory()); assertEquals("UTF-8", configuration.getEncoding()); assertEquals( ThreadPoolExecutor.class, configuration.getWorkersThreadPool().getClass()); assertEquals(1, (configuration.getWorkersThreadPool()).getCorePoolSize()); assertEquals(1, (configuration.getWorkersThreadPool()).getMaximumPoolSize()); if (configuration.isBasedPoolingWatchService()) { assertEquals(2, configuration.getDelay()); } else { assertNull(configuration.getDelay()); } } @Test void testPublishAndGetConfig() { assertTrue(configuration.publishConfig(KEY, CONTENT)); assertTrue(configuration.publishConfig(KEY, CONTENT)); assertTrue(configuration.publishConfig(KEY, CONTENT)); assertEquals(CONTENT, configuration.getConfig(KEY, DEFAULT_GROUP)); } @Test void testAddAndRemoveListener() throws InterruptedException { configuration.publishConfig(KEY, "A"); AtomicBoolean processedEvent = new AtomicBoolean(); configuration.addListener(KEY, event -> { processedEvent.set(true); assertEquals(KEY, event.getKey()); logger.info( String.format("[%s] " + event + "\n", Thread.currentThread().getName())); }); configuration.publishConfig(KEY, "B"); while (!processedEvent.get()) { Thread.sleep(1 * 1000L); } processedEvent.set(false); configuration.publishConfig(KEY, "C"); while (!processedEvent.get()) { Thread.sleep(1 * 1000L); } processedEvent.set(false); configuration.publishConfig(KEY, "D"); while (!processedEvent.get()) { Thread.sleep(1 * 1000L); } configuration.addListener("test", "test", event -> { processedEvent.set(true); assertEquals("test", event.getKey()); logger.info( String.format("[%s] " + event + "\n", Thread.currentThread().getName())); }); processedEvent.set(false); configuration.publishConfig("test", "test", "TEST"); while (!processedEvent.get()) { Thread.sleep(1 * 1000L); } configuration.publishConfig("test", "test", "TEST"); configuration.publishConfig("test", "test", "TEST"); configuration.publishConfig("test", "test", "TEST"); processedEvent.set(false); configuration.getRootDirectory(); File keyFile = new File(KEY, DEFAULT_GROUP); FileUtils.deleteQuietly(keyFile); while (!processedEvent.get()) { Thread.sleep(1 * 1000L); } } @Test void testRemoveConfig() throws Exception { assertTrue(configuration.publishConfig(KEY, DEFAULT_GROUP, "A")); assertEquals( "A", FileUtils.readFileToString(configuration.configFile(KEY, DEFAULT_GROUP), configuration.getEncoding())); assertTrue(configuration.removeConfig(KEY, DEFAULT_GROUP)); assertFalse(configuration.configFile(KEY, DEFAULT_GROUP).exists()); } // // @Test // public void testGetConfigKeys() throws Exception { // // assertTrue(configuration.publishConfig("A", DEFAULT_GROUP, "A")); // // assertTrue(configuration.publishConfig("B", DEFAULT_GROUP, "B")); // // assertTrue(configuration.publishConfig("C", DEFAULT_GROUP, "C")); // // assertEquals(new TreeSet(asList("A", "B", "C")), configuration.getConfigKeys(DEFAULT_GROUP)); // } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java
dubbo-configcenter/dubbo-configcenter-file/src/test/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactoryTest.java
/* * 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.common.config.configcenter.file; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * {@link FileSystemDynamicConfigurationFactory} Test * * @since 2.7.5 */ class FileSystemDynamicConfigurationFactoryTest { @Test void testGetFactory() { assertEquals( FileSystemDynamicConfigurationFactory.class, ConfigurationUtils.getDynamicConfigurationFactory(ApplicationModel.defaultModel(), "file") .getClass()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java
dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfiguration.java
/* * 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.common.config.configcenter.file; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.function.ThrowableConsumer; import org.apache.dubbo.common.function.ThrowableFunction; import org.apache.dubbo.common.lang.ShutdownHookCallbacks; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.io.File; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.FileUtils; import static java.lang.String.format; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableMap; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.commons.io.FileUtils.readFileToString; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_PROCESS_LISTENER; /** * File-System based {@link DynamicConfiguration} implementation * * @since 2.7.5 */ public class FileSystemDynamicConfiguration extends TreePathDynamicConfiguration { public static final String CONFIG_CENTER_DIR_PARAM_NAME = PARAM_NAME_PREFIX + "dir"; public static final String CONFIG_CENTER_ENCODING_PARAM_NAME = PARAM_NAME_PREFIX + "encoding"; public static final String DEFAULT_CONFIG_CENTER_DIR_PATH = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.USER_HOME) + File.separator + ".dubbo" + File.separator + "config-center"; public static final int DEFAULT_THREAD_POOL_SIZE = 1; public static final String DEFAULT_CONFIG_CENTER_ENCODING = "UTF-8"; private static final WatchEvent.Kind[] INTEREST_PATH_KINDS = of(ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); /** * The class name of {@linkplain sun.nio.fs.PollingWatchService} */ private static final String POLLING_WATCH_SERVICE_CLASS_NAME = "sun.nio.fs.PollingWatchService"; private static final int THREAD_POOL_SIZE = 1; /** * Logger */ private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FileSystemDynamicConfiguration.class); /** * The unmodifiable map for {@link ConfigChangeType} whose key is the {@link WatchEvent.Kind#name() name} of * {@link WatchEvent.Kind WatchEvent's Kind} */ private static final Map<String, ConfigChangeType> CONFIG_CHANGE_TYPES_MAP = unmodifiableMap(new HashMap<String, ConfigChangeType>() { // Initializes the elements that is mapping ConfigChangeType { put(ENTRY_CREATE.name(), ConfigChangeType.ADDED); put(ENTRY_DELETE.name(), ConfigChangeType.DELETED); put(ENTRY_MODIFY.name(), ConfigChangeType.MODIFIED); } }); private static final Optional<WatchService> watchService; /** * Is Pooling Based Watch Service * * @see #detectPoolingBasedWatchService(Optional) */ private static final boolean BASED_POOLING_WATCH_SERVICE; private static final WatchEvent.Modifier[] MODIFIERS; /** * the delay to action in seconds. If null, execute indirectly */ private static final Integer DELAY; /** * The thread pool for {@link WatchEvent WatchEvents} loop * It's optional if there is not any {@link ConfigurationListener} registration * * @see ThreadPoolExecutor */ private static final ThreadPoolExecutor WATCH_EVENTS_LOOP_THREAD_POOL; // static initialization static { watchService = newWatchService(); BASED_POOLING_WATCH_SERVICE = detectPoolingBasedWatchService(watchService); MODIFIERS = initWatchEventModifiers(); DELAY = initDelay(MODIFIERS); WATCH_EVENTS_LOOP_THREAD_POOL = newWatchEventsLoopThreadPool(); } /** * The Root Directory for config center */ private final File rootDirectory; private final String encoding; /** * The {@link Set} of {@link #groupDirectory(String) directories} that may be processing, * <p> * if {@link #isBasedPoolingWatchService()} is <code>false</code>, this properties will be * {@link Collections#emptySet() empty} * * @see #initProcessingDirectories() */ private final Set<File> processingDirectories; private final Map<File, List<ConfigurationListener>> listenersRepository; private ScopeModel scopeModel; private AtomicBoolean hasRegisteredShutdownHook = new AtomicBoolean(); public FileSystemDynamicConfiguration() { this(new File(DEFAULT_CONFIG_CENTER_DIR_PATH)); } public FileSystemDynamicConfiguration(File rootDirectory) { this(rootDirectory, DEFAULT_CONFIG_CENTER_ENCODING); } public FileSystemDynamicConfiguration(File rootDirectory, String encoding) { this(rootDirectory, encoding, DEFAULT_THREAD_POOL_PREFIX); } public FileSystemDynamicConfiguration(File rootDirectory, String encoding, String threadPoolPrefixName) { this(rootDirectory, encoding, threadPoolPrefixName, DEFAULT_THREAD_POOL_SIZE); } public FileSystemDynamicConfiguration( File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize) { this(rootDirectory, encoding, threadPoolPrefixName, threadPoolSize, DEFAULT_THREAD_POOL_KEEP_ALIVE_TIME); } public FileSystemDynamicConfiguration( File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize, long keepAliveTime) { super(rootDirectory.getAbsolutePath(), threadPoolPrefixName, threadPoolSize, keepAliveTime, DEFAULT_GROUP, -1L); this.rootDirectory = rootDirectory; this.encoding = encoding; this.processingDirectories = initProcessingDirectories(); this.listenersRepository = new HashMap<>(); registerDubboShutdownHook(); } public FileSystemDynamicConfiguration( File rootDirectory, String encoding, String threadPoolPrefixName, int threadPoolSize, long keepAliveTime, ScopeModel scopeModel) { super(rootDirectory.getAbsolutePath(), threadPoolPrefixName, threadPoolSize, keepAliveTime, DEFAULT_GROUP, -1L); this.rootDirectory = rootDirectory; this.encoding = encoding; this.processingDirectories = initProcessingDirectories(); this.listenersRepository = new HashMap<>(); this.scopeModel = scopeModel; registerDubboShutdownHook(); } public FileSystemDynamicConfiguration(URL url) { this( initDirectory(url), getEncoding(url), getThreadPoolPrefixName(url), getThreadPoolSize(url), getThreadPoolKeepAliveTime(url), url.getScopeModel()); } private Set<File> initProcessingDirectories() { return isBasedPoolingWatchService() ? new LinkedHashSet<>() : emptySet(); } public File configFile(String key, String group) { return new File(buildPathKey(group, key)); } private void doInListener(String configFilePath, BiConsumer<File, List<ConfigurationListener>> consumer) { watchService.ifPresent(watchService -> { File configFile = new File(configFilePath); executeMutually(configFile.getParentFile(), () -> { // process the WatchEvents if not start if (!isProcessingWatchEvents()) { processWatchEvents(watchService); } List<ConfigurationListener> listeners = getListeners(configFile); consumer.accept(configFile, listeners); // Nothing to return return null; }); }); } /** * Register the Dubbo ShutdownHook * * @since 2.7.8 */ private void registerDubboShutdownHook() { if (!hasRegisteredShutdownHook.compareAndSet(false, true)) { return; } ShutdownHookCallbacks shutdownHookCallbacks = ScopeModelUtil.getApplicationModel(scopeModel).getBeanFactory().getBean(ShutdownHookCallbacks.class); shutdownHookCallbacks.addCallback(() -> { watchService.ifPresent(w -> { try { w.close(); } catch (IOException e) { throw new RuntimeException(e); } }); getWatchEventsLoopThreadPool().shutdown(); }); } private static boolean isProcessingWatchEvents() { return getWatchEventsLoopThreadPool().getActiveCount() > 0; } /** * Process the {@link WatchEvent WatchEvents} loop in async execution * * @param watchService {@link WatchService} */ private void processWatchEvents(WatchService watchService) { getWatchEventsLoopThreadPool() .execute( () -> { // WatchEvents Loop while (true) { WatchKey watchKey = null; try { watchKey = watchService.take(); if (!watchKey.isValid()) { continue; } for (WatchEvent event : watchKey.pollEvents()) { WatchEvent.Kind kind = event.kind(); // configChangeType's key to match WatchEvent's Kind ConfigChangeType configChangeType = CONFIG_CHANGE_TYPES_MAP.get(kind.name()); if (configChangeType == null) { continue; } Path configDirectoryPath = (Path) watchKey.watchable(); Path currentPath = (Path) event.context(); Path configFilePath = configDirectoryPath.resolve(currentPath); File configDirectory = configDirectoryPath.toFile(); executeMutually(configDirectory, () -> { fireConfigChangeEvent( configDirectory, configFilePath.toFile(), configChangeType); signalConfigDirectory(configDirectory); return null; }); } } catch (Exception e) { return; } finally { if (watchKey != null) { // reset watchKey.reset(); } } } }); } private void signalConfigDirectory(File configDirectory) { if (isBasedPoolingWatchService()) { // remove configDirectory from processing set because it's done removeProcessingDirectory(configDirectory); // notify configDirectory notifyProcessingDirectory(configDirectory); if (logger.isDebugEnabled()) { logger.debug(format("The config rootDirectory[%s] is signalled...", configDirectory.getName())); } } } private void removeProcessingDirectory(File configDirectory) { processingDirectories.remove(configDirectory); } private void notifyProcessingDirectory(File configDirectory) { configDirectory.notifyAll(); } private List<ConfigurationListener> getListeners(File configFile) { return listenersRepository.computeIfAbsent(configFile, p -> new LinkedList<>()); } private void fireConfigChangeEvent(File configDirectory, File configFile, ConfigChangeType configChangeType) { String key = configFile.getName(); String value = getConfig(configFile); // fire ConfigChangeEvent one by one getListeners(configFile).forEach(listener -> { try { listener.process(new ConfigChangedEvent(key, configDirectory.getName(), value, configChangeType)); } catch (Throwable e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } }); } private boolean canRead(File file) { return file.exists() && file.canRead(); } @Override public Object getInternalProperty(String key) { return null; } @Override protected boolean doPublishConfig(String pathKey, String content) throws Exception { return delay(pathKey, configFile -> { FileUtils.write(configFile, content, getEncoding()); return true; }); } @Override protected String doGetConfig(String pathKey) throws Exception { File configFile = new File(pathKey); return getConfig(configFile); } @Override protected boolean doRemoveConfig(String pathKey) throws Exception { delay(pathKey, configFile -> { String content = getConfig(configFile); FileUtils.deleteQuietly(configFile); return content; }); return true; } @Override protected Collection<String> doGetConfigKeys(String groupPath) { File[] files = new File(groupPath).listFiles(File::isFile); if (files == null) { return new TreeSet<>(); } else { return Stream.of(files).map(File::getName).collect(Collectors.toList()); } } @Override protected void doAddListener(String pathKey, ConfigurationListener listener, String key, String group) { doInListener(pathKey, (configFilePath, listeners) -> { if (listeners.isEmpty()) { // If no element, it indicates watchService was registered before ThrowableConsumer.execute(configFilePath, configFile -> { FileUtils.forceMkdirParent(configFile); // A rootDirectory to be watched File configDirectory = configFile.getParentFile(); if (configDirectory != null) { // Register the configDirectory configDirectory.toPath().register(watchService.get(), INTEREST_PATH_KINDS, MODIFIERS); } }); } // Add into cache listeners.add(listener); }); } @Override protected void doRemoveListener(String pathKey, ConfigurationListener listener) { doInListener(pathKey, (file, listeners) -> { // Remove into cache listeners.remove(listener); }); } /** * Delay action for {@link #configFile(String, String) config file} * * @param configFilePath the key to represent a configuration * @param function the customized {@link Function function} with {@link File} * @param <V> the computed value * @return */ protected <V> V delay(String configFilePath, ThrowableFunction<File, V> function) { File configFile = new File(configFilePath); // Must be based on PoolingWatchService and has listeners under config file if (isBasedPoolingWatchService()) { File configDirectory = configFile.getParentFile(); executeMutually(configDirectory, () -> { if (hasListeners(configFile) && isProcessing(configDirectory)) { Integer delay = getDelay(); if (delay != null) { // wait for delay in seconds long timeout = SECONDS.toMillis(delay); if (logger.isDebugEnabled()) { logger.debug(format( "The config[path : %s] is about to delay in %d ms.", configFilePath, timeout)); } configDirectory.wait(timeout); } } addProcessing(configDirectory); return null; }); } V value = null; try { value = function.apply(configFile); } catch (Throwable e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } return value; } private boolean hasListeners(File configFile) { return getListeners(configFile).size() > 0; } /** * Is processing on {@link #buildGroupPath(String) config rootDirectory} * * @param configDirectory {@link #buildGroupPath(String) config rootDirectory} * @return if processing , return <code>true</code>, or <code>false</code> */ private boolean isProcessing(File configDirectory) { return processingDirectories.contains(configDirectory); } private void addProcessing(File configDirectory) { processingDirectories.add(configDirectory); } public Set<String> getConfigGroups() { return Stream.of(getRootDirectory().listFiles()) .filter(File::isDirectory) .map(File::getName) .collect(Collectors.toSet()); } protected String getConfig(File configFile) { return ThrowableFunction.execute( configFile, file -> canRead(configFile) ? readFileToString(configFile, getEncoding()) : null); } @Override protected void doClose() throws Exception {} public File getRootDirectory() { return rootDirectory; } public String getEncoding() { return encoding; } protected Integer getDelay() { return DELAY; } /** * It's whether the implementation of {@link WatchService} is based on {@linkplain sun.nio.fs.PollingWatchService} * or not. * <p> * * @return if based, return <code>true</code>, or <code>false</code> * @see #detectPoolingBasedWatchService(Optional) */ protected static boolean isBasedPoolingWatchService() { return BASED_POOLING_WATCH_SERVICE; } protected static ThreadPoolExecutor getWatchEventsLoopThreadPool() { return WATCH_EVENTS_LOOP_THREAD_POOL; } protected ThreadPoolExecutor getWorkersThreadPool() { return super.getWorkersThreadPool(); } private <V> V executeMutually(final Object mutex, Callable<V> callable) { V value = null; synchronized (mutex) { try { value = callable.call(); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } } } return value; } private static <T> T[] of(T... values) { return values; } private static Integer initDelay(WatchEvent.Modifier[] modifiers) { if (isBasedPoolingWatchService()) { return 2; } else { return null; } } private static WatchEvent.Modifier[] initWatchEventModifiers() { return of(); } /** * Detect the argument of {@link WatchService} is based on {@linkplain sun.nio.fs.PollingWatchService} * or not. * <p> * Some platforms do not provide the native implementation of {@link WatchService}, just use * {@linkplain sun.nio.fs.PollingWatchService} in periodic poll file modifications. * * @param watchService the instance of {@link WatchService} * @return if based, return <code>true</code>, or <code>false</code> */ private static boolean detectPoolingBasedWatchService(Optional<WatchService> watchService) { String className = watchService.map(Object::getClass).map(Class::getName).orElse(null); return POLLING_WATCH_SERVICE_CLASS_NAME.equals(className); } private static Optional<WatchService> newWatchService() { Optional<WatchService> watchService = null; FileSystem fileSystem = FileSystems.getDefault(); try { watchService = Optional.of(fileSystem.newWatchService()); } catch (IOException e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_PROCESS_LISTENER, "", "", e.getMessage(), e); } watchService = Optional.empty(); } return watchService; } protected static File initDirectory(URL url) { String directoryPath = getParameter(url, CONFIG_CENTER_DIR_PARAM_NAME, url == null ? null : url.getPath()); File rootDirectory = null; if (!StringUtils.isBlank(directoryPath)) { rootDirectory = new File("/" + directoryPath); } if (directoryPath == null || !rootDirectory.exists()) { // If the directory does not exist rootDirectory = new File(DEFAULT_CONFIG_CENTER_DIR_PATH); } if (!rootDirectory.exists() && !rootDirectory.mkdirs()) { throw new IllegalStateException( format("Dubbo config center rootDirectory[%s] can't be created!", rootDirectory.getAbsolutePath())); } return rootDirectory; } protected static String getEncoding(URL url) { return getParameter(url, CONFIG_CENTER_ENCODING_PARAM_NAME, DEFAULT_CONFIG_CENTER_ENCODING); } private static ThreadPoolExecutor newWatchEventsLoopThreadPool() { return new ThreadPoolExecutor( THREAD_POOL_SIZE, THREAD_POOL_SIZE, 0L, MILLISECONDS, new SynchronousQueue(), new NamedThreadFactory("dubbo-config-center-watch-events-loop", true)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactory.java
dubbo-configcenter/dubbo-configcenter-file/src/main/java/org/apache/dubbo/common/config/configcenter/file/FileSystemDynamicConfigurationFactory.java
/* * 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.common.config.configcenter.file; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory; /** * File-System based {@link DynamicConfigurationFactory} implementation * * @since 2.7.5 */ public class FileSystemDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new FileSystemDynamicConfiguration(url); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java
dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java
/* * 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.configcenter.support.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit test for nacos config center support */ // FIXME: waiting for embedded Nacos support, then we can open the switch. @Disabled("https://github.com/alibaba/nacos/issues/1188") class NacosDynamicConfigurationTest { private static final Logger logger = LoggerFactory.getLogger(NacosDynamicConfigurationTest.class); private static final String SESSION_TIMEOUT_KEY = "session"; private static NacosDynamicConfiguration config; /** * A test client to put data to Nacos server for testing purpose */ private static ConfigService nacosClient; @Test void testGetConfig() throws Exception { put("org.apache.dubbo.nacos.testService.configurators", "hello"); Thread.sleep(200); put("dubbo.properties", "test", "aaa=bbb"); Thread.sleep(200); put("org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", "helloworld"); Thread.sleep(200); Assertions.assertEquals( "hello", config.getConfig( "org.apache.dubbo.nacos.testService.configurators", DynamicConfiguration.DEFAULT_GROUP)); Assertions.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); Assertions.assertEquals( "helloworld", config.getConfig( "org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", DynamicConfiguration.DEFAULT_GROUP)); } @Test void testAddListener() throws Exception { CountDownLatch latch = new CountDownLatch(4); TestListener listener1 = new TestListener(latch); TestListener listener2 = new TestListener(latch); TestListener listener3 = new TestListener(latch); TestListener listener4 = new TestListener(latch); config.addListener("AService.configurators", listener1); config.addListener("AService.configurators", listener2); config.addListener("testapp.tag-router", listener3); config.addListener("testapp.tag-router", listener4); put("AService.configurators", "new value1"); Thread.sleep(200); put("testapp.tag-router", "new value2"); Thread.sleep(200); put("testapp", "new value3"); Thread.sleep(5000); latch.await(); Assertions.assertEquals(1, listener1.getCount("AService.configurators")); Assertions.assertEquals(1, listener2.getCount("AService.configurators")); Assertions.assertEquals(1, listener3.getCount("testapp.tag-router")); Assertions.assertEquals(1, listener4.getCount("testapp.tag-router")); Assertions.assertEquals("new value1", listener1.getValue()); Assertions.assertEquals("new value1", listener2.getValue()); Assertions.assertEquals("new value2", listener3.getValue()); Assertions.assertEquals("new value2", listener4.getValue()); } // // @Test // public void testGetConfigKeys() { // // put("key1", "a"); // put("key2", "b"); // // SortedSet<String> keys = config.getConfigKeys(DynamicConfiguration.DEFAULT_GROUP); // // Assertions.assertFalse(keys.isEmpty()); // // } private void put(String key, String value) { put(key, DynamicConfiguration.DEFAULT_GROUP, value); } private void put(String key, String group, String value) { try { nacosClient.publishConfig(key, group, value); } catch (Exception e) { logger.error("Error put value to nacos."); } } @BeforeAll public static void setUp() { String urlForDubbo = "nacos://" + "127.0.0.1:8848" + "/org.apache.dubbo.nacos.testService"; // timeout in 15 seconds. URL url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000); config = new NacosDynamicConfiguration(url, ApplicationModel.defaultModel()); try { nacosClient = NacosFactory.createConfigService("127.0.0.1:8848"); } catch (NacosException e) { e.printStackTrace(); } } @Test void testPublishConfig() { String key = "user-service"; String group = "org.apache.dubbo.service.UserService"; String content = "test"; assertTrue(config.publishConfig(key, group, content)); assertEquals("test", config.getProperties(key, group)); } @AfterAll public static void tearDown() {} private class TestListener implements ConfigurationListener { private CountDownLatch latch; private String value; private Map<String, Integer> countMap = new HashMap<>(); public TestListener(CountDownLatch latch) { this.latch = latch; } @Override public void process(ConfigChangedEvent event) { logger.info("{}: {}", this, event); Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); countMap.put(event.getKey(), ++count); value = event.getContent(); latch.countDown(); } public int getCount(String key) { return countMap.get(key); } public String getValue() { return value; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java
dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java
/* * 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.configcenter.support.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static org.mockito.ArgumentMatchers.any; class RetryTest { private static ApplicationModel applicationModel = ApplicationModel.defaultModel(); @Test void testRetryCreate() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); ConfigService mock = new MockConfigService() { @Override public String getServerStatus() { return atomicInteger.incrementAndGet() > 10 ? UP : DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createConfigService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10); Assertions.assertThrows( IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel)); try { new NacosDynamicConfiguration(url, applicationModel); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testDisable() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { ConfigService mock = new MockConfigService() { @Override public String getServerStatus() { return DOWN; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createConfigService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10) .addParameter("nacos.check", "false"); try { new NacosDynamicConfiguration(url, applicationModel); } catch (Throwable t) { Assertions.fail(t); } } } @Test void testRequest() { try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) { AtomicInteger atomicInteger = new AtomicInteger(0); ConfigService mock = new MockConfigService() { @Override public String getConfig(String dataId, String group, long timeoutMs) throws NacosException { if (atomicInteger.incrementAndGet() > 10) { return ""; } else { throw new NacosException(); } } @Override public String getServerStatus() { return UP; } }; nacosFactoryMockedStatic .when(() -> NacosFactory.createConfigService((Properties) any())) .thenReturn(mock); URL url = URL.valueOf("nacos://127.0.0.1:8848") .addParameter("nacos.retry", 5) .addParameter("nacos.retry-wait", 10); Assertions.assertThrows( IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel)); try { new NacosDynamicConfiguration(url, applicationModel); } catch (Throwable t) { Assertions.fail(t); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java
dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java
/* * 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.configcenter.support.nacos; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.filter.IConfigFilter; import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.exception.NacosException; public class MockConfigService implements ConfigService { @Override public String getConfig(String dataId, String group, long timeoutMs) throws NacosException { return null; } @Override public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException { return null; } @Override public void addListener(String dataId, String group, Listener listener) throws NacosException {} @Override public boolean publishConfig(String dataId, String group, String content) throws NacosException { return false; } @Override public boolean publishConfig(String dataId, String group, String content, String type) throws NacosException { return false; } @Override public boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException { return false; } @Override public boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type) throws NacosException { return false; } @Override public boolean removeConfig(String dataId, String group) throws NacosException { return false; } @Override public void removeListener(String dataId, String group, Listener listener) {} @Override public String getServerStatus() { return null; } @Override public void shutDown() throws NacosException {} @Override public void addConfigFilter(IConfigFilter iConfigFilter) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java
dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java
/* * 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.configcenter.support.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.model.ApplicationModel; import com.alibaba.nacos.api.PropertyKeyConst; /** * The nacos implementation of {@link AbstractDynamicConfigurationFactory} */ public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { private ApplicationModel applicationModel; public NacosDynamicConfigurationFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { URL nacosURL = url; if (CommonConstants.DUBBO.equals(url.getParameter(PropertyKeyConst.NAMESPACE))) { // Nacos use empty string as default namespace, replace default namespace "dubbo" to "" nacosURL = url.removeParameter(PropertyKeyConst.NAMESPACE); } return new NacosDynamicConfiguration(nacosURL, applicationModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java
dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java
/* * 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.configcenter.support.nacos; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.MD5Utils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executor; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.AbstractSharedListener; import com.alibaba.nacos.api.exception.NacosException; import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD; import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME; import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_NACOS; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED; import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of; import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * The nacos implementation of {@link DynamicConfiguration} */ public class NacosDynamicConfiguration implements DynamicConfiguration { private static final String GET_CONFIG_KEYS_PATH = "/v1/cs/configs"; private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); /** * the default timeout in millis to get config from nacos */ private static final long DEFAULT_TIMEOUT = 5000L; private final Properties nacosProperties; private static final String NACOS_RETRY_KEY = "nacos.retry"; private static final String NACOS_RETRY_WAIT_KEY = "nacos.retry-wait"; private static final String NACOS_CHECK_KEY = "nacos.check"; /** * The nacos configService */ private final NacosConfigServiceWrapper configService; private ApplicationModel applicationModel; /** * The map store the key to {@link NacosConfigListener} mapping */ private final ConcurrentMap<String, NacosConfigListener> watchListenerMap; private final MD5Utils md5Utils = new MD5Utils(); NacosDynamicConfiguration(URL url, ApplicationModel applicationModel) { this.nacosProperties = buildNacosProperties(url); this.configService = buildConfigService(url); this.watchListenerMap = new ConcurrentHashMap<>(); this.applicationModel = applicationModel; } private NacosConfigServiceWrapper buildConfigService(URL url) { int retryTimes = url.getPositiveParameter(NACOS_RETRY_KEY, 10); int sleepMsBetweenRetries = url.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 1000); boolean check = url.getParameter(NACOS_CHECK_KEY, true); ConfigService tmpConfigServices = null; try { for (int i = 0; i < retryTimes + 1; i++) { tmpConfigServices = NacosFactory.createConfigService(nacosProperties); String serverStatus = tmpConfigServices.getServerStatus(); boolean configServiceAvailable = testConfigService(tmpConfigServices); if (!check || (UP.equals(serverStatus) && configServiceAvailable)) { break; } else { logger.warn( LoggerCodeConstants.CONFIG_ERROR_NACOS, "", "", "Failed to connect to nacos config server. " + "Server status: " + serverStatus + ". " + "Config Service Available: " + configServiceAvailable + ". " + (i < retryTimes ? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". " : "Exceed retry max times.") + "Try times: " + (i + 1)); } tmpConfigServices.shutDown(); tmpConfigServices = null; Thread.sleep(sleepMsBetweenRetries); } } catch (NacosException e) { logger.error(CONFIG_ERROR_NACOS, "", "", e.getErrMsg(), e); throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos config service client.", e); Thread.currentThread().interrupt(); throw new IllegalStateException(e); } if (tmpConfigServices == null) { logger.error( CONFIG_ERROR_NACOS, "", "", "Failed to create nacos config service client. Reason: server status check failed."); throw new IllegalStateException( "Failed to create nacos config service client. Reason: server status check failed."); } return new NacosConfigServiceWrapper(tmpConfigServices); } private boolean testConfigService(ConfigService configService) { try { configService.getConfig("Dubbo-Nacos-Test", "Dubbo-Nacos-Test", DEFAULT_TIMEOUT); return true; } catch (NacosException e) { return false; } } private Properties buildNacosProperties(URL url) { Properties properties = new Properties(); setServerAddr(url, properties); setProperties(url, properties); return properties; } private void setServerAddr(URL url, Properties properties) { StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host .append(':') .append(url.getPort()); // Port // Append backup parameter as other servers String backup = url.getParameter(BACKUP_KEY); if (backup != null) { serverAddrBuilder.append(',').append(backup); } String serverAddr = serverAddrBuilder.toString(); properties.put(SERVER_ADDR, serverAddr); } private static void setProperties(URL url, Properties properties) { // Get the parameters from constants Map<String, String> parameters = url.getParameters(of(PropertyKeyConst.class)); // Put all parameters properties.putAll(parameters); if (StringUtils.isNotEmpty(url.getUsername())) { properties.put(USERNAME, url.getUsername()); } if (StringUtils.isNotEmpty(url.getPassword())) { properties.put(PASSWORD, url.getPassword()); } } private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName) { String propertyValue = url.getParameter(propertyName); if (StringUtils.isNotEmpty(propertyValue)) { properties.setProperty(propertyName, propertyValue); } } private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) { String propertyValue = url.getParameter(propertyName); if (StringUtils.isNotEmpty(propertyValue)) { properties.setProperty(propertyName, propertyValue); } else { properties.setProperty(propertyName, defaultValue); } } /** * Ignores the group parameter. * * @param key property key the native listener will listen on * @param group to distinguish different set of properties * @return */ private NacosConfigListener createTargetListener(String key, String group) { NacosConfigListener configListener = new NacosConfigListener(); configListener.fillContext(key, group); return configListener; } @Override public void close() throws Exception { configService.shutdown(); } @Override public void addListener(String key, String group, ConfigurationListener listener) { String listenerKey = buildListenerKey(key, group); NacosConfigListener nacosConfigListener = ConcurrentHashMapUtils.computeIfAbsent( watchListenerMap, listenerKey, k -> createTargetListener(key, group)); nacosConfigListener.addListener(listener); try { configService.addListener(key, group, nacosConfigListener); } catch (NacosException e) { logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e); } } @Override public void removeListener(String key, String group, ConfigurationListener listener) { String listenerKey = buildListenerKey(key, group); NacosConfigListener eventListener = watchListenerMap.get(listenerKey); if (eventListener != null) { eventListener.removeListener(listener); } } @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { try { long nacosTimeout = timeout < 0 ? getDefaultTimeout() : timeout; if (StringUtils.isEmpty(group)) { group = DEFAULT_GROUP; } return configService.getConfig(key, group, nacosTimeout); } catch (NacosException e) { logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e); } return null; } @Override public ConfigItem getConfigItem(String key, String group) { String content = getConfig(key, group); String casMd5 = ""; if (StringUtils.isNotEmpty(content)) { casMd5 = md5Utils.getMd5(content); } return new ConfigItem(content, casMd5); } @Override public Object getInternalProperty(String key) { try { return configService.getConfig(key, DEFAULT_GROUP, getDefaultTimeout()); } catch (NacosException e) { logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e); } return null; } @Override public boolean publishConfig(String key, String group, String content) { boolean published = false; try { published = configService.publishConfig(key, group, content); } catch (NacosException e) { logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e); } return published; } @Override public boolean publishConfigCas(String key, String group, String content, Object ticket) { try { if (!(ticket instanceof String)) { throw new IllegalArgumentException("nacos publishConfigCas requires string type ticket"); } return configService.publishConfigCas(key, group, content, (String) ticket); } catch (NacosException e) { logger.warn(CONFIG_ERROR_NACOS, "nacos publishConfigCas failed.", "", e.getMessage(), e); return false; } } @Override public long getDefaultTimeout() { return DEFAULT_TIMEOUT; } @Override public boolean removeConfig(String key, String group) { boolean removed = false; try { removed = configService.removeConfig(key, group); } catch (NacosException e) { if (logger.isErrorEnabled()) { logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e); } } return removed; } private String getProperty(String name, String defaultValue) { return nacosProperties.getProperty(name, defaultValue); } public class NacosConfigListener extends AbstractSharedListener { private Set<ConfigurationListener> listeners = new CopyOnWriteArraySet<>(); /** * cache data to store old value */ private Map<String, String> cacheData = new ConcurrentHashMap<>(); @Override public Executor getExecutor() { return null; } /** * receive * * @param dataId data ID * @param group group * @param configInfo content */ @Override public void innerReceive(String dataId, String group, String configInfo) { String oldValue = cacheData.get(dataId); ConfigChangedEvent event = new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue)); if (configInfo == null) { cacheData.remove(dataId); } else { cacheData.put(dataId, configInfo); } listeners.forEach(listener -> listener.process(event)); MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( applicationModel, event.getKey(), event.getGroup(), ConfigCenterEvent.NACOS_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE)); } void addListener(ConfigurationListener configurationListener) { this.listeners.add(configurationListener); } void removeListener(ConfigurationListener configurationListener) { this.listeners.remove(configurationListener); } private ConfigChangeType getChangeType(String configInfo, String oldValue) { if (StringUtils.isBlank(configInfo)) { return ConfigChangeType.DELETED; } if (StringUtils.isBlank(oldValue)) { return ConfigChangeType.ADDED; } return ConfigChangeType.MODIFIED; } } protected String buildListenerKey(String key, String group) { return key + HYPHEN_CHAR + group; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConfigServiceWrapper.java
dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConfigServiceWrapper.java
/* * 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.configcenter.support.nacos; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.Listener; import com.alibaba.nacos.api.exception.NacosException; import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR; import static org.apache.dubbo.common.utils.StringUtils.SLASH_CHAR; public class NacosConfigServiceWrapper { private static final String INNERCLASS_SYMBOL = "$"; private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___"; private static final long DEFAULT_TIMEOUT = 3000L; private final ConfigService configService; public NacosConfigServiceWrapper(ConfigService configService) { this.configService = configService; } public ConfigService getConfigService() { return configService; } public void addListener(String dataId, String group, Listener listener) throws NacosException { configService.addListener(handleInnerSymbol(dataId), handleInnerSymbol(group), listener); } public String getConfig(String dataId, String group) throws NacosException { return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), DEFAULT_TIMEOUT); } public String getConfig(String dataId, String group, long timeout) throws NacosException { return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), timeout); } public boolean publishConfig(String dataId, String group, String content) throws NacosException { return configService.publishConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), content); } public boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException { return configService.publishConfigCas(handleInnerSymbol(dataId), handleInnerSymbol(group), content, casMd5); } public boolean removeConfig(String dataId, String group) throws NacosException { return configService.removeConfig(handleInnerSymbol(dataId), handleInnerSymbol(group)); } public void shutdown() throws NacosException { configService.shutDown(); } /** * see {@link com.alibaba.nacos.client.config.utils.ParamUtils#isValid(java.lang.String)} */ private String handleInnerSymbol(String data) { if (data == null) { return null; } return data.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL).replace(SLASH_CHAR, HYPHEN_CHAR); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java
dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java
/* * 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.configcenter.support.apollo; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.Random; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.SettableFuture; 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 static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.fail; /** * Apollo dynamic configuration mock test. * Notice: EmbeddedApollo(apollo mock server) only support < junit5, please not upgrade the junit version in this UT, * the junit version in this UT is junit4, and the dependency comes from apollo-mockserver. */ class ApolloDynamicConfigurationTest { private static final String SESSION_TIMEOUT_KEY = "session"; private static final String DEFAULT_NAMESPACE = "dubbo"; private static ApolloDynamicConfiguration apolloDynamicConfiguration; private static URL url; private static ApplicationModel applicationModel; /** * The constant embeddedApollo. */ @RegisterExtension public static EmbeddedApolloJunit5 embeddedApollo = new EmbeddedApolloJunit5(); /** * Sets up. */ @BeforeEach public void setUp() { FrameworkModel.destroyAll(); String apolloUrl = System.getProperty("apollo.configService"); String urlForDubbo = "apollo://" + apolloUrl.substring(apolloUrl.lastIndexOf("/") + 1) + "/org.apache.dubbo.apollo.testService?namespace=dubbo&check=true"; url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000); applicationModel = ApplicationModel.defaultModel(); } // /** // * Embedded Apollo does not work as expected. // */ // @Test // public void testProperties() { // URL url = this.url.addParameter(GROUP_KEY, "dubbo") // .addParameter("namespace", "governance"); // // apolloDynamicConfiguration = new ApolloDynamicConfiguration(url); // putData("dubbo", "dubbo.registry.address", "zookeeper://127.0.0.1:2181"); // assertEquals("zookeeper://127.0.0.1:2181", apolloDynamicConfiguration.getProperties(null, "dubbo")); // // putData("governance", "router.tag", "router tag rule"); // assertEquals("router tag rule", apolloDynamicConfiguration.getConfig("router.tag", "governance")); // // } /** * Test get rule. */ @Test void testGetRule() { String mockKey = "mockKey1"; String mockValue = String.valueOf(new Random().nextInt()); putMockRuleData(mockKey, mockValue, DEFAULT_NAMESPACE); apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel); assertEquals(mockValue, apolloDynamicConfiguration.getConfig(mockKey, DEFAULT_NAMESPACE, 3000L)); mockKey = "notExistKey"; assertNull(apolloDynamicConfiguration.getConfig(mockKey, DEFAULT_NAMESPACE, 3000L)); } /** * Test get internal property. * * @throws InterruptedException the interrupted exception */ @Test void testGetInternalProperty() throws InterruptedException { String mockKey = "mockKey2"; String mockValue = String.valueOf(new Random().nextInt()); putMockRuleData(mockKey, mockValue, DEFAULT_NAMESPACE); TimeUnit.MILLISECONDS.sleep(1000); apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel); assertEquals(mockValue, apolloDynamicConfiguration.getInternalProperty(mockKey)); mockValue = "mockValue2"; System.setProperty(mockKey, mockValue); assertEquals(mockValue, apolloDynamicConfiguration.getInternalProperty(mockKey)); mockKey = "notExistKey"; assertNull(apolloDynamicConfiguration.getInternalProperty(mockKey)); } /** * Test add listener. * * @throws Exception the exception */ @Test void testAddListener() throws Exception { String mockKey = "mockKey3"; String mockValue = String.valueOf(new Random().nextInt()); final SettableFuture<org.apache.dubbo.common.config.configcenter.ConfigChangedEvent> future = SettableFuture.create(); apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel); apolloDynamicConfiguration.addListener(mockKey, DEFAULT_NAMESPACE, new ConfigurationListener() { @Override public void process(org.apache.dubbo.common.config.configcenter.ConfigChangedEvent event) { future.set(event); } }); putData(mockKey, mockValue); org.apache.dubbo.common.config.configcenter.ConfigChangedEvent result = future.get(3000, TimeUnit.MILLISECONDS); assertEquals(mockValue, result.getContent()); assertEquals(mockKey, result.getKey()); assertEquals(ConfigChangeType.MODIFIED, result.getChangeType()); } private static void putData(String namespace, String key, String value) { embeddedApollo.addOrModifyProperty(namespace, key, value); } private static void putData(String key, String value) { embeddedApollo.addOrModifyProperty(DEFAULT_NAMESPACE, key, value); } private static void putMockRuleData(String key, String value, String group) { String fileName = ApolloDynamicConfigurationTest.class.getResource("/").getPath() + "mockdata-" + group + ".properties"; putMockData(key, value, fileName); } private static void putMockData(String key, String value, String fileName) { Properties pro = new Properties(); FileOutputStream oFile = null; try { oFile = new FileOutputStream(fileName); pro.setProperty(key, value); pro.store(oFile, "put mock data"); } catch (IOException exx) { fail(exx.getMessage()); } finally { if (null != oFile) { try { oFile.close(); } catch (IOException e) { fail(e.getMessage()); } } } } /** * Tear down. */ @AfterEach public void tearDown() {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java
dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java
/* * 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.configcenter.support.apollo; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.JsonUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.dto.ApolloConfig; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; import com.ctrip.framework.apollo.core.utils.ResourceUtils; import com.ctrip.framework.apollo.internals.ConfigServiceLocator; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO; public class EmbeddedApolloJunit5 implements BeforeAllCallback, AfterAllCallback { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EmbeddedApolloJunit5.class); private static Method CONFIG_SERVICE_LOCATOR_CLEAR; private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR; private final Map<String, Map<String, String>> addedOrModifiedPropertiesOfNamespace = Maps.newConcurrentMap(); private final Map<String, Set<String>> deletedKeysOfNamespace = Maps.newConcurrentMap(); private MockWebServer server; static { try { System.setProperty("apollo.longPollingInitialDelayInMills", "0"); CONFIG_SERVICE_LOCATOR = ApolloInjector.getInstance(ConfigServiceLocator.class); CONFIG_SERVICE_LOCATOR_CLEAR = ConfigServiceLocator.class.getDeclaredMethod("initConfigServices"); CONFIG_SERVICE_LOCATOR_CLEAR.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } } private void clear() throws Exception { resetOverriddenProperties(); } private void mockConfigServiceUrl(String url) throws Exception { System.setProperty("apollo.configService", url); CONFIG_SERVICE_LOCATOR_CLEAR.invoke(CONFIG_SERVICE_LOCATOR); } private String loadConfigFor(String namespace) { String filename = String.format("mockdata-%s.properties", namespace); final Properties prop = ResourceUtils.readConfigFile(filename, new Properties()); Map<String, String> configurations = Maps.newHashMap(); for (String propertyName : prop.stringPropertyNames()) { configurations.put(propertyName, prop.getProperty(propertyName)); } ApolloConfig apolloConfig = new ApolloConfig("someAppId", "someCluster", namespace, "someReleaseKey"); Map<String, String> mergedConfigurations = mergeOverriddenProperties(namespace, configurations); apolloConfig.setConfigurations(mergedConfigurations); return JsonUtils.toJson(apolloConfig); } private String mockLongPollBody(String notificationsStr) { List<ApolloConfigNotification> oldNotifications = JsonUtils.toJavaList(notificationsStr, ApolloConfigNotification.class); List<ApolloConfigNotification> newNotifications = new ArrayList<>(); for (ApolloConfigNotification notification : oldNotifications) { newNotifications.add(new ApolloConfigNotification( notification.getNamespaceName(), notification.getNotificationId() + 1)); } return JsonUtils.toJson(newNotifications); } /** * Incorporate user modifications to namespace */ private Map<String, String> mergeOverriddenProperties(String namespace, Map<String, String> configurations) { if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { configurations.putAll(addedOrModifiedPropertiesOfNamespace.get(namespace)); } if (deletedKeysOfNamespace.containsKey(namespace)) { for (String k : deletedKeysOfNamespace.get(namespace)) { configurations.remove(k); } } return configurations; } /** * Add new property or update existed property */ public void addOrModifyProperty(String namespace, String someKey, String someValue) { if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { addedOrModifiedPropertiesOfNamespace.get(namespace).put(someKey, someValue); } else { Map<String, String> m = Maps.newConcurrentMap(); m.put(someKey, someValue); addedOrModifiedPropertiesOfNamespace.put(namespace, m); } } /** * Delete existed property */ public void deleteProperty(String namespace, String someKey) { if (deletedKeysOfNamespace.containsKey(namespace)) { deletedKeysOfNamespace.get(namespace).add(someKey); } else { Set<String> m = Sets.newConcurrentHashSet(); m.add(someKey); deletedKeysOfNamespace.put(namespace, m); } } /** * reset overridden properties */ public void resetOverriddenProperties() { addedOrModifiedPropertiesOfNamespace.clear(); deletedKeysOfNamespace.clear(); } @Override public void afterAll(ExtensionContext extensionContext) throws Exception { try { clear(); server.close(); } catch (Exception e) { logger.error(CONFIG_FAILED_CLOSE_CONNECT_APOLLO, "", "", "stop apollo server error", e); } } @Override public void beforeAll(ExtensionContext extensionContext) throws Exception { clear(); server = new MockWebServer(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().startsWith("/notifications/v2")) { String notifications = request.getRequestUrl().queryParameter("notifications"); return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications)); } if (request.getPath().startsWith("/configs")) { List<String> pathSegments = request.getRequestUrl().pathSegments(); // appId and cluster might be used in the future String appId = pathSegments.get(1); String cluster = pathSegments.get(2); String namespace = pathSegments.get(3); return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace)); } return new MockResponse().setResponseCode(404); } }; server.setDispatcher(dispatcher); server.start(); mockConfigServiceUrl("http://localhost:" + server.getPort()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java
dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java
/* * 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.configcenter.support.apollo; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.rpc.model.ApplicationModel; public class ApolloDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { private ApplicationModel applicationModel; public ApolloDynamicConfigurationFactory(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new ApolloDynamicConfiguration(url, applicationModel); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java
dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java
/* * 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.configcenter.support.apollo; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.configcenter.ConfigChangeType; import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; import org.apache.dubbo.common.config.configcenter.ConfigurationListener; import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.metrics.config.event.ConfigCenterEvent; import org.apache.dubbo.metrics.event.MetricsEventBus; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collectors; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.enums.ConfigSourceType; import com.ctrip.framework.apollo.enums.PropertyChangeType; import com.ctrip.framework.apollo.model.ConfigChange; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.APOLLO_ADDR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.APOLLO_APPID_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.APOLLO_CLUSTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ThirdPartyProperty.APOLLO_ENV_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO; import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE; /** * Apollo implementation, https://github.com/ctripcorp/apollo * <p> * Apollo will be used for management of both governance rules and .properties files, by default, these two different * kinds of data share the same namespace 'dubbo'. To gain better performance, we recommend separate them by giving * namespace and group different values, for example: * <p> * <dubbo:config-center namespace="governance" group="dubbo" />, 'dubbo=governance' is for governance rules while * 'group=dubbo' is for properties files. * <p> * Please see http://dubbo.apache.org/zh-cn/docs/user/configuration/config-center.html for details. */ public class ApolloDynamicConfiguration implements DynamicConfiguration { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ApolloDynamicConfiguration.class); private static final String APOLLO_PROTOCOL_PREFIX = "http://"; private static final String APOLLO_APPLICATION_KEY = "application"; private final URL url; private final Config dubboConfig; private final ConfigFile dubboConfigFile; private final ConcurrentMap<String, ApolloListener> listeners = new ConcurrentHashMap<>(); private final ApplicationModel applicationModel; ApolloDynamicConfiguration(URL url, ApplicationModel applicationModel) { this.url = url; this.applicationModel = applicationModel; // Instead of using Dubbo's configuration, I would suggest use the original configuration method Apollo // provides. String configEnv = url.getParameter(APOLLO_ENV_KEY); String configAddr = getAddressWithProtocolPrefix(url); String configCluster = url.getParameter(CLUSTER_KEY); String configAppId = url.getParameter(APOLLO_APPID_KEY); if (StringUtils.isEmpty(SystemPropertyConfigUtils.getSystemProperty(APOLLO_ENV_KEY)) && configEnv != null) { SystemPropertyConfigUtils.getSystemProperty(APOLLO_ENV_KEY, configEnv); } if (StringUtils.isEmpty(SystemPropertyConfigUtils.getSystemProperty(APOLLO_ADDR_KEY)) && !ANYHOST_VALUE.equals(url.getHost())) { SystemPropertyConfigUtils.setSystemProperty(APOLLO_ADDR_KEY, configAddr); } if (StringUtils.isEmpty(SystemPropertyConfigUtils.getSystemProperty(APOLLO_CLUSTER_KEY)) && configCluster != null) { SystemPropertyConfigUtils.getSystemProperty(APOLLO_CLUSTER_KEY, configCluster); } if (StringUtils.isEmpty(SystemPropertyConfigUtils.getSystemProperty(APOLLO_APPID_KEY)) && configAppId != null) { SystemPropertyConfigUtils.getSystemProperty(APOLLO_APPID_KEY, configAppId); } String namespace = url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP); String apolloNamespace = StringUtils.isEmpty(namespace) ? url.getGroup(DEFAULT_GROUP) : namespace; dubboConfig = ConfigService.getConfig(apolloNamespace); dubboConfigFile = ConfigService.getConfigFile(apolloNamespace, ConfigFileFormat.Properties); // Decide to fail or to continue when failed to connect to remote server. boolean check = url.getParameter(CHECK_KEY, true); if (dubboConfig.getSourceType() != ConfigSourceType.REMOTE) { if (check) { throw new IllegalStateException("Failed to connect to config center, the config center is Apollo, " + "the address is: " + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv)); } else { // 5-1 Failed to connect to configuration center. logger.warn( CONFIG_FAILED_CONNECT_REGISTRY, "configuration server offline", "", "Failed to connect to config center, the config center is Apollo, " + "the address is: " + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv) + ", will use the local cache value instead before eventually the connection is established."); } } } @Override public void close() { try { listeners.clear(); } catch (UnsupportedOperationException e) { logger.warn( CONFIG_FAILED_CLOSE_CONNECT_APOLLO, "", "", "Failed to close connect from config center, the config center is Apollo"); } } private String getAddressWithProtocolPrefix(URL url) { String address = url.getBackupAddress(); if (StringUtils.isNotEmpty(address)) { address = Arrays.stream(COMMA_SPLIT_PATTERN.split(address)) .map(addr -> { if (addr.startsWith(APOLLO_PROTOCOL_PREFIX)) { return addr; } return APOLLO_PROTOCOL_PREFIX + addr; }) .collect(Collectors.joining(",")); } return address; } /** * Since all governance rules will lay under dubbo group, this method now always uses the default dubboConfig and * ignores the group parameter. */ @Override public void addListener(String key, String group, ConfigurationListener listener) { ApolloListener apolloListener = ConcurrentHashMapUtils.computeIfAbsent(listeners, group + key, k -> createTargetListener(key, group)); apolloListener.addListener(listener); dubboConfig.addChangeListener(apolloListener, Collections.singleton(key)); } @Override public void removeListener(String key, String group, ConfigurationListener listener) { ApolloListener apolloListener = listeners.get(group + key); if (apolloListener != null) { apolloListener.removeListener(listener); if (!apolloListener.hasInternalListener()) { dubboConfig.removeChangeListener(apolloListener); } } } @Override public String getConfig(String key, String group, long timeout) throws IllegalStateException { if (StringUtils.isNotEmpty(group)) { if (group.equals(url.getApplication())) { return ConfigService.getAppConfig().getProperty(key, null); } else { return ConfigService.getConfig(group).getProperty(key, null); } } return dubboConfig.getProperty(key, null); } /** * Recommend specify namespace and group when using Apollo. * <p> * <dubbo:config-center namespace="governance" group="dubbo" />, 'dubbo=governance' is for governance rules while * 'group=dubbo' is for properties files. * * @param key default value is 'dubbo.properties', currently useless for Apollo. * @param group * @param timeout * @return * @throws IllegalStateException */ @Override public String getProperties(String key, String group, long timeout) throws IllegalStateException { if (StringUtils.isEmpty(group)) { return dubboConfigFile.getContent(); } if (group.equals(url.getApplication())) { return ConfigService.getConfigFile(APOLLO_APPLICATION_KEY, ConfigFileFormat.Properties) .getContent(); } ConfigFile configFile = ConfigService.getConfigFile(group, ConfigFileFormat.Properties); if (configFile == null) { throw new IllegalStateException("There is no namespace named " + group + " in Apollo."); } return configFile.getContent(); } /** * This method will be used by Configuration to get valid value at runtime. * The group is expected to be 'app level', which can be fetched from the 'config.appnamespace' in url if necessary. * But I think Apollo's inheritance feature of namespace can solve the problem . */ @Override public String getInternalProperty(String key) { return dubboConfig.getProperty(key, null); } /** * Ignores the group parameter. * * @param key property key the native listener will listen on * @param group to distinguish different set of properties * @return */ private ApolloListener createTargetListener(String key, String group) { return new ApolloListener(); } public class ApolloListener implements ConfigChangeListener { private Set<ConfigurationListener> listeners = new CopyOnWriteArraySet<>(); ApolloListener() {} @Override public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEvent) { for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); if ("".equals(change.getNewValue())) { logger.warn( CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO, "", "", "an empty rule is received for " + key + ", the current working rule is " + change.getOldValue() + ", the empty rule will not take effect."); return; } ConfigChangedEvent event = new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change)); listeners.forEach(listener -> listener.process(event)); MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent( applicationModel, event.getKey(), event.getGroup(), ConfigCenterEvent.APOLLO_PROTOCOL, ConfigChangeType.ADDED.name(), SELF_INCREMENT_SIZE)); } } private ConfigChangeType getChangeType(ConfigChange change) { if (change.getChangeType() == PropertyChangeType.DELETED) { return ConfigChangeType.DELETED; } return ConfigChangeType.MODIFIED; } void addListener(ConfigurationListener configurationListener) { this.listeners.add(configurationListener); } void removeListener(ConfigurationListener configurationListener) { this.listeners.remove(configurationListener); } boolean hasInternalListener() { return listeners != null && listeners.size() > 0; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapperFactory.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapperFactory.java
/* * 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.maven.plugin.protoc; import java.util.HashMap; import java.util.Map; import org.codehaus.plexus.util.Os; public class DubboProtocPluginWrapperFactory { private final LinuxDubboProtocPluginWrapper linuxProtocCommandBuilder = new LinuxDubboProtocPluginWrapper(); private final WinDubboProtocPluginWrapper winDubboProtocPluginWrapper = new WinDubboProtocPluginWrapper(); private final Map<String, DubboProtocPluginWrapper> dubboProtocPluginWrappers = new HashMap<>(); public DubboProtocPluginWrapperFactory() { dubboProtocPluginWrappers.put("linux", linuxProtocCommandBuilder); dubboProtocPluginWrappers.put("windows", winDubboProtocPluginWrapper); } public DubboProtocPluginWrapper findByOs() { if (Os.isFamily(Os.FAMILY_WINDOWS)) { return dubboProtocPluginWrappers.get("windows"); } return dubboProtocPluginWrappers.get("linux"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/WinDubboProtocPluginWrapper.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/WinDubboProtocPluginWrapper.java
/* * 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.maven.plugin.protoc; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import org.apache.maven.plugin.logging.Log; public class WinDubboProtocPluginWrapper implements DubboProtocPluginWrapper { @Override public File createProtocPlugin(DubboProtocPlugin dubboProtocPlugin, Log log) { File pluginDirectory = dubboProtocPlugin.getPluginDirectory(); pluginDirectory.mkdirs(); if (!pluginDirectory.isDirectory()) { throw new RuntimeException( "Unable to create protoc plugin directory: " + pluginDirectory.getAbsolutePath()); } File batFile = new File(dubboProtocPlugin.getPluginDirectory(), "protoc-gen-" + dubboProtocPlugin.getId() + ".bat"); try (PrintWriter out = new PrintWriter(new FileWriter(batFile))) { out.println("@echo off"); out.println("set JAVA_HOME=" + dubboProtocPlugin.getJavaHome()); StringBuilder classpath = new StringBuilder(256); classpath.append("set CLASSPATH="); for (File jar : dubboProtocPlugin.getResolvedJars()) { classpath.append(jar.getAbsolutePath()).append(";"); } out.println(classpath); out.println("\"%JAVA_HOME%\\bin\\java\" ^"); for (String jvmArg : dubboProtocPlugin.getJvmArgs()) { out.println(" " + jvmArg + " ^"); } out.println(" " + dubboProtocPlugin.getMainClass() + " ^"); for (String arg : dubboProtocPlugin.getArgs()) { out.println(" " + arg + " ^"); } out.println(" %*"); } catch (IOException e) { throw new RuntimeException("Unable to write BAT file: " + batFile.getAbsolutePath(), e); } return batFile; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/LinuxDubboProtocPluginWrapper.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/LinuxDubboProtocPluginWrapper.java
/* * 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.maven.plugin.protoc; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import org.apache.maven.plugin.logging.Log; public class LinuxDubboProtocPluginWrapper implements DubboProtocPluginWrapper { @Override public File createProtocPlugin(DubboProtocPlugin dubboProtocPlugin, Log log) { List<File> resolvedJars = dubboProtocPlugin.getResolvedJars(); createPluginDirectory(dubboProtocPlugin.getPluginDirectory()); File pluginExecutableFile = new File(dubboProtocPlugin.getPluginDirectory(), dubboProtocPlugin.getPluginName()); final File javaLocation = new File(dubboProtocPlugin.getJavaHome(), "bin/java"); if (log.isDebugEnabled()) { log.debug("javaLocation=" + javaLocation.getAbsolutePath()); } try (final PrintWriter out = new PrintWriter(new FileWriter(pluginExecutableFile))) { out.println("#!/bin/sh"); out.println(); out.print("CP="); for (int i = 0; i < resolvedJars.size(); i++) { if (i > 0) { out.print(":"); } out.print("\"" + resolvedJars.get(i).getAbsolutePath() + "\""); } out.println(); out.print("ARGS=\""); for (final String arg : dubboProtocPlugin.getArgs()) { out.print(arg + " "); } out.println("\""); out.print("JVMARGS=\""); for (final String jvmArg : dubboProtocPlugin.getJvmArgs()) { out.print(jvmArg + " "); } out.println("\""); out.println(); out.println("\"" + javaLocation.getAbsolutePath() + "\" $JVMARGS -cp $CP " + dubboProtocPlugin.getMainClass() + " $ARGS"); out.println(); boolean b = pluginExecutableFile.setExecutable(true); if (!b) { throw new RuntimeException("Could not make plugin executable: " + pluginExecutableFile); } return pluginExecutableFile; } catch (IOException e) { throw new RuntimeException("Could not write plugin script file: " + pluginExecutableFile, e); } } private void createPluginDirectory(File pluginDirectory) { pluginDirectory.mkdirs(); if (!pluginDirectory.isDirectory()) { throw new RuntimeException( "Could not create protoc plugin directory: " + pluginDirectory.getAbsolutePath()); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPlugin.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPlugin.java
/* * 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.maven.plugin.protoc; import java.io.File; import java.util.ArrayList; import java.util.List; public class DubboProtocPlugin { private String id; private String mainClass; private String dubboVersion; private String javaHome; private File pluginDirectory; private List<File> resolvedJars = new ArrayList<>(); private List<String> args = new ArrayList<>(); private List<String> jvmArgs = new ArrayList<>(); private File protocPlugin = null; public DubboProtocPlugin() {} public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMainClass() { return mainClass; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public String getDubboVersion() { return dubboVersion; } public void setDubboVersion(String dubboVersion) { this.dubboVersion = dubboVersion; } public String getJavaHome() { return javaHome; } public void setJavaHome(String javaHome) { this.javaHome = javaHome; } public File getPluginDirectory() { return pluginDirectory; } public void setPluginDirectory(File pluginDirectory) { this.pluginDirectory = pluginDirectory; } public List<File> getResolvedJars() { return resolvedJars; } public void setResolvedJars(List<File> resolvedJars) { this.resolvedJars = resolvedJars; } public void addResolvedJar(File jar) { resolvedJars.add(jar); } public List<String> getArgs() { return args; } public void setArgs(List<String> args) { this.args = args; } public void addArg(String arg) { args.add(arg); } public List<String> getJvmArgs() { return jvmArgs; } public void setJvmArgs(List<String> jvmArgs) { this.jvmArgs = jvmArgs; } public void addJvmArg(String jvmArg) { jvmArgs.add(jvmArg); } public String getPluginName() { return "protoc-gen-" + id; } public File getProtocPlugin() { return protocPlugin; } public void setProtocPlugin(File protocPlugin) { this.protocPlugin = protocPlugin; } @Override public String toString() { return "DubboProtocPlugin{" + "id='" + id + '\'' + ", mainClass='" + mainClass + '\'' + ", dubboVersion='" + dubboVersion + '\'' + ", javaHome='" + javaHome + '\'' + ", pluginDirectory=" + pluginDirectory + ", resolvedJars=" + resolvedJars + ", args=" + args + ", jvmArgs=" + jvmArgs + ", protocPlugin=" + protocPlugin + '}'; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapper.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocPluginWrapper.java
/* * 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.maven.plugin.protoc; import java.io.File; import org.apache.maven.plugin.logging.Log; public interface DubboProtocPluginWrapper { File createProtocPlugin(DubboProtocPlugin dubboProtocPlugin, Log log); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocCompilerMojo.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/DubboProtocCompilerMojo.java
/* * Copyright (c) 2019 Maven Protocol Buffers Plugin Authors. All rights reserved. * * 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 org.apache.dubbo.maven.plugin.protoc; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import org.apache.dubbo.maven.plugin.protoc.command.DefaultProtocCommandBuilder; import org.apache.dubbo.maven.plugin.protoc.enums.DubboGenerateTypeEnum; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.artifact.resolver.ArtifactResolutionResult; import org.apache.maven.artifact.resolver.ResolutionErrorHandler; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.repository.RepositorySystem; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.io.RawInputStreamFacade; import org.sonatype.plexus.build.incremental.BuildContext; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import static java.lang.String.format; import static java.util.Collections.emptyMap; import static java.util.Collections.singleton; import static org.codehaus.plexus.util.FileUtils.cleanDirectory; import static org.codehaus.plexus.util.FileUtils.copyStreamToFile; import static org.codehaus.plexus.util.FileUtils.getFiles; @Mojo( name = "compile", defaultPhase = LifecyclePhase.GENERATE_SOURCES, requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) public class DubboProtocCompilerMojo extends AbstractMojo { @Parameter(property = "protoSourceDir", defaultValue = "${basedir}/src/main/proto") private File protoSourceDir; @Parameter(property = "outputDir", defaultValue = "${project.build.directory}/generated-sources/protobuf/java") private File outputDir; @Parameter(required = false, property = "dubboVersion") private String dubboVersion; @Parameter(required = true, readonly = true, defaultValue = "${project.remoteArtifactRepositories}") private List<ArtifactRepository> remoteRepositories; @Parameter(required = false, property = "protocExecutable") private String protocExecutable; @Parameter(required = false, property = "protocArtifact") private String protocArtifact; @Parameter(required = false, property = "protocVersion") private String protocVersion; @Parameter(required = false, defaultValue = "${project.build.directory}/protoc-plugins") private File protocPluginDirectory; @Parameter(required = true, defaultValue = "${project.build.directory}/protoc-dependencies") private File temporaryProtoFileDirectory; @Parameter(required = true, property = "dubboGenerateType", defaultValue = "tri") private String dubboGenerateType; @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; @Parameter(defaultValue = "${session}", readonly = true) protected MavenSession session; @Parameter(required = true, readonly = true, property = "localRepository") private ArtifactRepository localRepository; @Component private ArtifactFactory artifactFactory; @Component private RepositorySystem repositorySystem; @Component private ResolutionErrorHandler resolutionErrorHandler; @Component protected MavenProjectHelper projectHelper; @Component protected BuildContext buildContext; final CommandLineUtils.StringStreamConsumer output = new CommandLineUtils.StringStreamConsumer(); final CommandLineUtils.StringStreamConsumer error = new CommandLineUtils.StringStreamConsumer(); private final DefaultProtocCommandBuilder defaultProtocCommandBuilder = new DefaultProtocCommandBuilder(); private final DubboProtocPluginWrapperFactory dubboProtocPluginWrapperFactory = new DubboProtocPluginWrapperFactory(); public void execute() throws MojoExecutionException, MojoFailureException { Properties versionMatrix = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try (InputStream stream = loader.getResourceAsStream("version-matrix.properties")) { versionMatrix.load(stream); } catch (IOException e) { getLog().warn("Unable to load default version matrix", e); } if (dubboVersion == null) { dubboVersion = versionMatrix.getProperty("dubbo.version"); } if (protocVersion == null) { protocVersion = versionMatrix.getProperty("protoc.version"); } if (protocArtifact == null) { final String osName = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.SYSTEM_OS_NAME); final String osArch = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.OS_ARCH); final String detectedName = normalizeOs(osName); final String detectedArch = normalizeArch(osArch); protocArtifact = "com.google.protobuf:protoc:" + protocVersion + ":exe:" + detectedName + '-' + detectedArch; } if (protocExecutable == null && protocArtifact != null) { final Artifact artifact = createProtocArtifact(protocArtifact); final File file = resolveBinaryArtifact(artifact); protocExecutable = file.getAbsolutePath(); } if (protocExecutable == null) { getLog().warn("No 'protocExecutable' parameter is configured, using the default: 'protoc'"); protocExecutable = "protoc"; } getLog().info("using protocExecutable: " + protocExecutable); DubboProtocPlugin dubboProtocPlugin = buildDubboProtocPlugin(dubboVersion, dubboGenerateType, protocPluginDirectory); getLog().info("build dubbo protoc plugin:" + dubboProtocPlugin + " success"); List<String> commandArgs = defaultProtocCommandBuilder.buildProtocCommandArgs(new ProtocMetaData(protocExecutable, makeAllProtoPaths(), findAllProtoFiles(protoSourceDir), outputDir, dubboProtocPlugin )); if (!outputDir.exists()) { FileUtils.mkdir(outputDir.getAbsolutePath()); } try { int exitStatus = executeCommandLine(commandArgs); getLog().info("execute commandLine finished with exit code: " + exitStatus); if (exitStatus != 0) { getLog().error("PROTOC FAILED: " + getError()); throw new MojoFailureException( "protoc did not exit cleanly. Review output for more information."); } else if (StringUtils.isNotBlank(getError())) { getLog().warn("PROTOC: " + getError()); } linkProtoFilesToMaven(); } catch (CommandLineException e) { throw new MojoExecutionException(e); } } private static String normalizeOs(String value) { value = normalize(value); if (value.startsWith("linux")) { return "linux"; } if (value.startsWith("mac") || value.startsWith("osx")) { return "osx"; } if (value.startsWith("windows")) { return "windows"; } return "unknown"; } private static String normalize(String value) { if (value == null) { return ""; } return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", ""); } private static String normalizeArch(String value) { value = normalize(value); if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) { return "x86_64"; } if ("aarch64".equals(value)) { return "aarch_64"; } return "unknown"; } public void linkProtoFilesToMaven() { linkProtoSources(); linkGeneratedFiles(); } public void linkProtoSources() { projectHelper.addResource(project, protoSourceDir.getAbsolutePath(), Collections.singletonList("**/*.proto*"), Collections.singletonList("")); } public void linkGeneratedFiles() { project.addCompileSourceRoot(outputDir.getAbsolutePath()); buildContext.refresh(outputDir); } public List<File> findAllProtoFiles(final File protoSourceDir) { if (protoSourceDir == null) { throw new RuntimeException("'protoSourceDir' is null"); } if (!protoSourceDir.isDirectory()) { throw new RuntimeException(format("%s is not a directory", protoSourceDir)); } final List<File> protoFilesInDirectory; try { protoFilesInDirectory = getFiles(protoSourceDir, "**/*.proto*", ""); } catch (IOException e) { throw new RuntimeException("Unable to retrieve the list of files: " + e.getMessage(), e); } getLog().info("protoFilesInDirectory: " + protoFilesInDirectory); return protoFilesInDirectory; } public int executeCommandLine(List<String> commandArgs) throws CommandLineException { final Commandline cl = new Commandline(); cl.setExecutable(protocExecutable); cl.addArguments(commandArgs.toArray(new String[]{})); int attemptsLeft = 3; while (true) { try { getLog().info("commandLine:" + cl.toString()); return CommandLineUtils.executeCommandLine(cl, null, output, error); } catch (CommandLineException e) { if (--attemptsLeft == 0 || e.getCause() == null) { throw e; } getLog().warn("[PROTOC] Unable to invoke protoc, will retry " + attemptsLeft + " time(s)", e); try { Thread.sleep(1000L); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } } } } private DubboProtocPlugin buildDubboProtocPlugin(String dubboVersion, String dubboGenerateType, File protocPluginDirectory) { DubboProtocPlugin dubboProtocPlugin = new DubboProtocPlugin(); DubboGenerateTypeEnum dubboGenerateTypeEnum = DubboGenerateTypeEnum.getByType(dubboGenerateType); if (dubboGenerateTypeEnum == null) { throw new RuntimeException(" can not find the dubboGenerateType: " + dubboGenerateType + ",please check it !"); } dubboProtocPlugin.setId(dubboGenerateType); dubboProtocPlugin.setMainClass(dubboGenerateTypeEnum.getMainClass()); dubboProtocPlugin.setDubboVersion(dubboVersion); dubboProtocPlugin.setPluginDirectory(protocPluginDirectory); dubboProtocPlugin.setJavaHome(SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_HOME)); DubboProtocPluginWrapper protocPluginWrapper = dubboProtocPluginWrapperFactory.findByOs(); dubboProtocPlugin.setResolvedJars(resolvePluginDependencies()); File protocPlugin = protocPluginWrapper.createProtocPlugin(dubboProtocPlugin, getLog()); boolean debugEnabled = getLog().isDebugEnabled(); if (debugEnabled) { getLog().debug("protocPlugin: " + protocPlugin.getAbsolutePath()); } dubboProtocPlugin.setProtocPlugin(protocPlugin); return dubboProtocPlugin; } private List<File> resolvePluginDependencies() { List<File> resolvedJars = new ArrayList<>(); final VersionRange versionSpec; try { versionSpec = VersionRange.createFromVersionSpec(dubboVersion); } catch (InvalidVersionSpecificationException e) { throw new RuntimeException("Invalid plugin version specification", e); } final Artifact protocPluginArtifact = artifactFactory.createDependencyArtifact( "org.apache.dubbo", "dubbo-compiler", versionSpec, "jar", "", Artifact.SCOPE_RUNTIME); final ArtifactResolutionRequest request = new ArtifactResolutionRequest() .setArtifact(project.getArtifact()) .setResolveRoot(false) .setArtifactDependencies(Collections.singleton(protocPluginArtifact)) .setManagedVersionMap(emptyMap()) .setLocalRepository(localRepository) .setRemoteRepositories(remoteRepositories) .setOffline(session.isOffline()) .setForceUpdate(session.getRequest().isUpdateSnapshots()) .setServers(session.getRequest().getServers()) .setMirrors(session.getRequest().getMirrors()) .setProxies(session.getRequest().getProxies()); final ArtifactResolutionResult result = repositorySystem.resolve(request); try { resolutionErrorHandler.throwErrors(request, result); } catch (ArtifactResolutionException e) { throw new RuntimeException("Unable to resolve plugin artifact: " + e.getMessage(), e); } final Set<Artifact> artifacts = result.getArtifacts(); if (artifacts == null || artifacts.isEmpty()) { throw new RuntimeException("Unable to resolve plugin artifact"); } for (final Artifact artifact : artifacts) { resolvedJars.add(artifact.getFile()); } if (getLog().isDebugEnabled()) { getLog().debug("Resolved jars: " + resolvedJars); } return resolvedJars; } protected Artifact createProtocArtifact(final String artifactSpec) { final String[] parts = artifactSpec.split(":"); if (parts.length < 3 || parts.length > 5) { throw new RuntimeException( "Invalid artifact specification format" + ", expected: groupId:artifactId:version[:type[:classifier]]" + ", actual: " + artifactSpec); } final String type = parts.length >= 4 ? parts[3] : "exe"; final String classifier = parts.length == 5 ? parts[4] : null; // parts: [com.google.protobuf, protoc, 3.6.0, exe, osx-x86_64] getLog().info("parts: " + Arrays.toString(parts)); return createDependencyArtifact(parts[0], parts[1], parts[2], type, classifier); } protected Artifact createDependencyArtifact( final String groupId, final String artifactId, final String version, final String type, final String classifier ) { final VersionRange versionSpec; try { versionSpec = VersionRange.createFromVersionSpec(version); } catch (final InvalidVersionSpecificationException e) { throw new RuntimeException("Invalid version specification", e); } return artifactFactory.createDependencyArtifact( groupId, artifactId, versionSpec, type, classifier, Artifact.SCOPE_RUNTIME); } protected File resolveBinaryArtifact(final Artifact artifact) { final ArtifactResolutionResult result; final ArtifactResolutionRequest request = new ArtifactResolutionRequest() .setArtifact(project.getArtifact()) .setResolveRoot(false) .setResolveTransitively(false) .setArtifactDependencies(singleton(artifact)) .setManagedVersionMap(emptyMap()) .setLocalRepository(localRepository) .setRemoteRepositories(remoteRepositories) .setOffline(session.isOffline()) .setForceUpdate(session.getRequest().isUpdateSnapshots()) .setServers(session.getRequest().getServers()) .setMirrors(session.getRequest().getMirrors()) .setProxies(session.getRequest().getProxies()); result = repositorySystem.resolve(request); try { resolutionErrorHandler.throwErrors(request, result); } catch (final ArtifactResolutionException e) { throw new RuntimeException("Unable to resolve artifact: " + e.getMessage(), e); } final Set<Artifact> artifacts = result.getArtifacts(); if (artifacts == null || artifacts.isEmpty()) { throw new RuntimeException("Unable to resolve artifact"); } final Artifact resolvedBinaryArtifact = artifacts.iterator().next(); if (getLog().isDebugEnabled()) { getLog().debug("Resolved artifact: " + resolvedBinaryArtifact); } final File sourceFile = resolvedBinaryArtifact.getFile(); final String sourceFileName = sourceFile.getName(); final String targetFileName; if (Os.isFamily(Os.FAMILY_WINDOWS) && !sourceFileName.endsWith(".exe")) { targetFileName = sourceFileName + ".exe"; } else { targetFileName = sourceFileName; } final File targetFile = new File(protocPluginDirectory, targetFileName); if (targetFile.exists()) { getLog().debug("Executable file already exists: " + targetFile.getAbsolutePath()); return targetFile; } try { FileUtils.forceMkdir(protocPluginDirectory); } catch (final IOException e) { throw new RuntimeException("Unable to create directory " + protocPluginDirectory, e); } try { FileUtils.copyFile(sourceFile, targetFile); } catch (final IOException e) { throw new RuntimeException("Unable to copy the file to " + protocPluginDirectory, e); } if (!Os.isFamily(Os.FAMILY_WINDOWS)) { boolean b = targetFile.setExecutable(true); if (!b) { throw new RuntimeException("Unable to make executable: " + targetFile.getAbsolutePath()); } } if (getLog().isDebugEnabled()) { getLog().debug("Executable file: " + targetFile.getAbsolutePath()); } return targetFile; } protected Set<File> makeAllProtoPaths() { File temp = temporaryProtoFileDirectory; if (temp.exists()) { try { cleanDirectory(temp); } catch (IOException e) { throw new RuntimeException("Unable to clean up temporary proto file directory", e); } } Set<File> protoDirectories = new LinkedHashSet<>(); if (protoSourceDir.exists()) { protoDirectories.add(protoSourceDir); } //noinspection deprecation for (Artifact artifact : project.getCompileArtifacts()) { File file = artifact.getFile(); if (file.isFile() && file.canRead() && !file.getName().endsWith(".xml")) { try (JarFile jar = new JarFile(file)) { Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); String jarEntryName = jarEntry.getName(); if (jarEntryName.endsWith(".proto")) { File targetDirectory; try { targetDirectory = new File(temp, hash(jar.getName())); String canonicalTargetDirectoryPath = targetDirectory.getCanonicalPath(); File target = new File(targetDirectory, jarEntryName); String canonicalTargetPath = target.getCanonicalPath(); if (!canonicalTargetPath.startsWith(canonicalTargetDirectoryPath + File.separator)) { throw new RuntimeException( "ZIP SLIP: Entry " + jarEntry.getName() + " in " + jar.getName() + " is outside of the target dir"); } FileUtils.mkdir(target.getParentFile().getAbsolutePath()); copyStreamToFile(new RawInputStreamFacade(jar.getInputStream(jarEntry)), target); } catch (IOException e) { throw new RuntimeException("Unable to unpack proto files", e); } protoDirectories.add(targetDirectory); } } } catch (IOException e) { throw new RuntimeException("Not a readable JAR artifact: " + file.getAbsolutePath(), e); } } else if (file.isDirectory()) { List<File> protoFiles; try { protoFiles = getFiles(file, "**/*.proto", null); } catch (IOException e) { throw new RuntimeException("Unable to scan for proto files in: " + file.getAbsolutePath(), e); } if (!protoFiles.isEmpty()) { protoDirectories.add(file); } } } return protoDirectories; } private static String hash(String input) { try { byte[] bytes = MessageDigest.getInstance("MD5").digest(input.getBytes(StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(32); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException("Unable to create MD5 digest", e); } } public String getError() { return fixUnicodeOutput(error.getOutput()); } public String getOutput() { return fixUnicodeOutput(output.getOutput()); } private static String fixUnicodeOutput(final String message) { // TODO default charset is not UTF-8 ? return new String(message.getBytes(), StandardCharsets.UTF_8); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/ProtocMetaData.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/ProtocMetaData.java
/* * 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.maven.plugin.protoc; import java.io.File; import java.util.Collection; import java.util.List; public class ProtocMetaData { private String protocExecutable; private Collection<File> protoSourceDirs; private List<File> protoFiles; private File outputDir; private DubboProtocPlugin dubboProtocPlugin; public ProtocMetaData() {} public ProtocMetaData( String protocExecutable, Collection<File> protoSourceDirs, List<File> protoFiles, File outputDir, DubboProtocPlugin dubboProtocPlugin) { this.protocExecutable = protocExecutable; this.protoSourceDirs = protoSourceDirs; this.protoFiles = protoFiles; this.outputDir = outputDir; this.dubboProtocPlugin = dubboProtocPlugin; } public String getProtocExecutable() { return protocExecutable; } public void setProtocExecutable(String protocExecutable) { this.protocExecutable = protocExecutable; } public Collection<File> getProtoSourceDirs() { return protoSourceDirs; } public void setProtoSourceDirs(Collection<File> protoSourceDirs) { this.protoSourceDirs = protoSourceDirs; } public List<File> getProtoFiles() { return protoFiles; } public void setProtoFiles(List<File> protoFiles) { this.protoFiles = protoFiles; } public File getOutputDir() { return outputDir; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public DubboProtocPlugin getDubboProtocPlugin() { return dubboProtocPlugin; } public void setDubboProtocPlugin(DubboProtocPlugin dubboProtocPlugin) { this.dubboProtocPlugin = dubboProtocPlugin; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/command/DefaultProtocCommandBuilder.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/command/DefaultProtocCommandBuilder.java
/* * 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.maven.plugin.protoc.command; import org.apache.dubbo.maven.plugin.protoc.DubboProtocPlugin; import org.apache.dubbo.maven.plugin.protoc.ProtocMetaData; import java.io.File; import java.util.ArrayList; import java.util.List; public class DefaultProtocCommandBuilder implements ProtocCommandArgsBuilder { @Override public List<String> buildProtocCommandArgs(ProtocMetaData protocMetaData) { List<String> command = new ArrayList<>(); for (final File protoSourceDir : protocMetaData.getProtoSourceDirs()) { command.add("--proto_path=" + protoSourceDir); } String outputOption = "--java_out="; outputOption += protocMetaData.getOutputDir(); command.add(outputOption); DubboProtocPlugin dubboProtocPlugin = protocMetaData.getDubboProtocPlugin(); command.add("--plugin=protoc-gen-" + dubboProtocPlugin.getId() + '=' + dubboProtocPlugin.getProtocPlugin()); command.add("--" + dubboProtocPlugin.getId() + "_out=" + protocMetaData.getOutputDir()); for (final File protoFile : protocMetaData.getProtoFiles()) { command.add(protoFile.toString()); } return command; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/command/ProtocCommandArgsBuilder.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/command/ProtocCommandArgsBuilder.java
/* * 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.maven.plugin.protoc.command; import org.apache.dubbo.maven.plugin.protoc.ProtocMetaData; import java.util.List; public interface ProtocCommandArgsBuilder { List<String> buildProtocCommandArgs(ProtocMetaData protocMetaData) throws RuntimeException; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/protoc/enums/DubboGenerateTypeEnum.java
/* * 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.maven.plugin.protoc.enums; public enum DubboGenerateTypeEnum { Tri("tri", "org.apache.dubbo.gen.tri.Dubbo3TripleGenerator"), Tri_reactor("tri_reactor", "org.apache.dubbo.gen.tri.reactive.ReactorDubbo3TripleGenerator"), ; private String id; private String mainClass; DubboGenerateTypeEnum(String id, String mainClass) { this.id = id; this.mainClass = mainClass; } public static DubboGenerateTypeEnum getByType(String dubboGenerateType) { DubboGenerateTypeEnum[] values = DubboGenerateTypeEnum.values(); for (DubboGenerateTypeEnum value : values) { if (value.getId().equals(dubboGenerateType)) { return value; } } return null; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMainClass() { return mainClass; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/Include.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/Include.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; /** * A model for a dependency to include. */ public class Include extends FilterableDependency { }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/ExcludeFilter.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/ExcludeFilter.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.artifact.Artifact; import java.util.Arrays; import java.util.List; /** * An {DependencyFilter} that filters out any artifact matching an {@link Exclude}. */ public class ExcludeFilter extends DependencyFilter { public ExcludeFilter(Exclude... excludes) { this(Arrays.asList(excludes)); } public ExcludeFilter(List<Exclude> excludes) { super(excludes); } @Override protected boolean filter(Artifact artifact) { for (FilterableDependency dependency : getFilters()) { if (equals(artifact, dependency)) { return true; } } return false; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/FilterableDependency.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/FilterableDependency.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.plugins.annotations.Parameter; /** * A model for a dependency to include or exclude. */ abstract class FilterableDependency { /** * The groupId of the artifact to exclude. */ @Parameter(required = true) private String groupId; /** * The artifactId of the artifact to exclude. */ @Parameter(required = true) private String artifactId; /** * The classifier of the artifact to exclude. */ @Parameter private String classifier; String getGroupId() { return this.groupId; } void setGroupId(String groupId) { this.groupId = groupId; } String getArtifactId() { return this.artifactId; } void setArtifactId(String artifactId) { this.artifactId = artifactId; } String getClassifier() { return this.classifier; } void setClassifier(String classifier) { this.classifier = classifier; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DependencyFilter.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DependencyFilter.java
/* * Copyright 2012-2020 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Base class for {@link ArtifactsFilter} based on a {@link org.apache.dubbo.maven.plugin.aot.FilterableDependency} list. */ public abstract class DependencyFilter extends AbstractArtifactsFilter { private final List<? extends FilterableDependency> filters; /** * Create a new instance with the list of {@link FilterableDependency} instance(s) to * use. * @param dependencies the source dependencies */ public DependencyFilter(List<? extends FilterableDependency> dependencies) { this.filters = dependencies; } @Override public Set<Artifact> filter(Set<Artifact> artifacts) throws ArtifactFilterException { Set<Artifact> result = new HashSet<>(); for (Artifact artifact : artifacts) { if (!filter(artifact)) { result.add(artifact); } } return result; } protected abstract boolean filter(Artifact artifact); /** * Check if the specified {@link Artifact} matches the * specified {@link org.apache.dubbo.maven.plugin.aot.FilterableDependency}. Returns * {@code true} if it should be excluded * @param artifact the Maven {@link Artifact} * @param dependency the {@link org.apache.dubbo.maven.plugin.aot.FilterableDependency} * @return {@code true} if the artifact matches the dependency */ protected final boolean equals(Artifact artifact, FilterableDependency dependency) { if (!dependency.getGroupId().equals(artifact.getGroupId())) { return false; } if (!dependency.getArtifactId().equals(artifact.getArtifactId())) { return false; } return (dependency.getClassifier() == null || artifact.getClassifier() != null && dependency.getClassifier().equals(artifact.getClassifier())); } protected final List<? extends FilterableDependency> getFilters() { return this.filters; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * Helper class to build the command-line arguments of a java process. */ final class CommandLineBuilder { private final List<String> options = new ArrayList<>(); private final List<URL> classpathElements = new ArrayList<>(); private final String mainClass; private final List<String> arguments = new ArrayList<>(); private CommandLineBuilder(String mainClass) { this.mainClass = mainClass; } static CommandLineBuilder forMainClass(String mainClass) { return new CommandLineBuilder(mainClass); } CommandLineBuilder withJvmArguments(String... jvmArguments) { if (jvmArguments != null) { this.options.addAll(Arrays.stream(jvmArguments).filter(Objects::nonNull).collect(Collectors.toList())); } return this; } CommandLineBuilder withSystemProperties(Map<String, String> systemProperties) { if (systemProperties != null) { systemProperties.entrySet().stream().map((e) -> SystemPropertyFormatter.format(e.getKey(), e.getValue())) .forEach(this.options::add); } return this; } CommandLineBuilder withClasspath(URL... elements) { this.classpathElements.addAll(Arrays.asList(elements)); return this; } CommandLineBuilder withArguments(String... arguments) { if (arguments != null) { this.arguments.addAll(Arrays.stream(arguments).filter(Objects::nonNull).collect(Collectors.toList())); } return this; } List<String> build() { List<String> commandLine = new ArrayList<>(); if (!this.options.isEmpty()) { commandLine.addAll(this.options); } if (!this.classpathElements.isEmpty()) { commandLine.add("-cp"); commandLine.add(ClasspathBuilder.build(this.classpathElements)); } commandLine.add(this.mainClass); if (!this.arguments.isEmpty()) { commandLine.addAll(this.arguments); } return commandLine; } static class ClasspathBuilder { static String build(List<URL> classpathElements) { StringBuilder classpath = new StringBuilder(); for (URL element : classpathElements) { if (classpath.length() > 0) { classpath.append(File.pathSeparator); } classpath.append(toFile(element)); } return classpath.toString(); } private static File toFile(URL element) { try { return new File(element.toURI()); } catch (URISyntaxException ex) { throw new IllegalArgumentException(ex); } } } /** * Format System properties. */ private static class SystemPropertyFormatter { static String format(String key, String value) { if (key == null) { return ""; } if (value == null || value.isEmpty()) { return String.format("-D%s", key); } return String.format("-D%s=\"%s\"", key, value); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/Exclude.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/Exclude.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; /** * A model for a dependency to exclude. */ public class Exclude extends FilterableDependency { }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractDependencyFilterMojo.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractDependencyFilterMojo.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactFeatureFilter; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import org.apache.maven.shared.artifact.filter.collection.FilterArtifacts; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; /** * A base mojo filtering the dependencies of the project. */ public abstract class AbstractDependencyFilterMojo extends AbstractMojo { /** * The Maven project. */ @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; /** * Collection of artifact definitions to include. The {@link Include} element defines * mandatory {@code groupId} and {@code artifactId} properties and an optional * mandatory {@code groupId} and {@code artifactId} properties and an optional * {@code classifier} property. */ @Parameter(property = "dubbo.includes") private List<Include> includes; /** * Collection of artifact definitions to exclude. The {@link Exclude} element defines * mandatory {@code groupId} and {@code artifactId} properties and an optional * {@code classifier} property. */ @Parameter(property = "dubbo.excludes") private List<Exclude> excludes; /** * Comma separated list of groupId names to exclude (exact match). */ @Parameter(property = "dubbo.excludeGroupIds", defaultValue = "") private String excludeGroupIds; protected void setExcludes(List<Exclude> excludes) { this.excludes = excludes; } protected void setIncludes(List<Include> includes) { this.includes = includes; } protected void setExcludeGroupIds(String excludeGroupIds) { this.excludeGroupIds = excludeGroupIds; } protected List<URL> getDependencyURLs(ArtifactsFilter... additionalFilters) throws MojoExecutionException { Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), additionalFilters); List<URL> urls = new ArrayList<>(); for (Artifact artifact : artifacts) { if (artifact.getFile() != null) { urls.add(toURL(artifact.getFile())); } } return urls; } protected final Set<Artifact> filterDependencies(Set<Artifact> dependencies, ArtifactsFilter... additionalFilters) throws MojoExecutionException { try { Set<Artifact> filtered = new LinkedHashSet<>(dependencies); filtered.retainAll(getFilters(additionalFilters).filter(dependencies)); return filtered; } catch (ArtifactFilterException ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } protected URL toURL(File file) { try { return file.toURI().toURL(); } catch (MalformedURLException ex) { throw new IllegalStateException("Invalid URL for " + file, ex); } } /** * Return artifact filters configured for this MOJO. * @param additionalFilters optional additional filters to apply * @return the filters */ private FilterArtifacts getFilters(ArtifactsFilter... additionalFilters) { FilterArtifacts filters = new FilterArtifacts(); for (ArtifactsFilter additionalFilter : additionalFilters) { filters.addFilter(additionalFilter); } filters.addFilter(new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds))); if (this.includes != null && !this.includes.isEmpty()) { filters.addFilter(new IncludeFilter(this.includes)); } if (this.excludes != null && !this.excludes.isEmpty()) { filters.addFilter(new ExcludeFilter(this.excludes)); } return filters; } private String cleanFilterConfig(String content) { if (content == null || content.trim().isEmpty()) { return ""; } StringBuilder cleaned = new StringBuilder(); StringTokenizer tokenizer = new StringTokenizer(content, ","); while (tokenizer.hasMoreElements()) { cleaned.append(tokenizer.nextToken().trim()); if (tokenizer.hasMoreElements()) { cleaned.append(","); } } return cleaned.toString(); } /** * {@link ArtifactFilter} to exclude test scope dependencies. */ protected static class ExcludeTestScopeArtifactFilter extends AbstractArtifactFeatureFilter { ExcludeTestScopeArtifactFilter() { super("", Artifact.SCOPE_TEST); } @Override protected String getArtifactFeature(Artifact artifact) { return artifact.getScope(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/MatchingGroupIdFilter.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/MatchingGroupIdFilter.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactFeatureFilter; /** * An {@link org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter * ArtifactsFilter} that filters by matching groupId. * * Preferred over the * {@link org.apache.maven.shared.artifact.filter.collection.GroupIdFilter} due to that * classes use of {@link String#startsWith} to match on prefix. */ public class MatchingGroupIdFilter extends AbstractArtifactFeatureFilter { /** * Create a new instance with the CSV groupId values that should be excluded. * @param exclude the group values to exclude */ public MatchingGroupIdFilter(String exclude) { super("", exclude); } @Override protected String getArtifactFeature(Artifact artifact) { return artifact.getGroupId(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DubboProcessAotMojo.java
/* * 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.maven.plugin.aot; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; @Mojo( name = "dubbo-process-aot", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) public class DubboProcessAotMojo extends AbstractAotMojo { private static final String AOT_PROCESSOR_CLASS_NAME = "org.apache.dubbo.aot.generate.AotProcessor"; /** * Directory containing the classes and resource files that should be packaged into * the archive. */ @Parameter(defaultValue = "${project.build.outputDirectory}", required = true) private File classesDirectory; /** * Directory containing the generated sources. */ @Parameter(defaultValue = "${project.build.directory}/dubbo-aot/main/sources", required = true) private File generatedSources; /** * Directory containing the generated resources. */ @Parameter(defaultValue = "${project.build.directory}/dubbo-aot/main/resources", required = true) private File generatedResources; /** * Directory containing the generated classes. */ @Parameter(defaultValue = "${project.build.directory}/dubbo-aot/main/classes", required = true) private File generatedClasses; /** * Name of the main class to use as the source for the AOT process. If not specified * the first compiled class found that contains a 'main' method will be used. */ @Parameter(property = "dubbo.aot.main-class") private String mainClass; /** * Application arguments that should be taken into account for AOT processing. */ @Parameter private String[] arguments; @Override protected void executeAot() throws Exception { URL[] classPath = getClassPath().toArray(new URL[0]); generateAotAssets(classPath, AOT_PROCESSOR_CLASS_NAME, getAotArguments(mainClass)); compileSourceFiles(classPath, this.generatedSources, this.classesDirectory); copyAll(this.generatedResources.toPath(), this.classesDirectory.toPath()); copyAll(this.generatedClasses.toPath(), this.classesDirectory.toPath()); } private String[] getAotArguments(String applicationClass) { List<String> aotArguments = new ArrayList<>(); aotArguments.add(applicationClass != null ? applicationClass : ""); aotArguments.add(this.generatedSources.toString()); aotArguments.add(this.generatedResources.toString()); aotArguments.add(this.generatedClasses.toString()); aotArguments.add(this.project.getGroupId()); aotArguments.add(this.project.getArtifactId()); aotArguments.addAll(new RunArguments(this.arguments).getArgs()); return aotArguments.toArray(new String[0]); } private List<URL> getClassPath() throws Exception { File[] directories = new File[] {this.classesDirectory, this.generatedClasses}; return getClassPath(directories, new ExcludeTestScopeArtifactFilter()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/RunArguments.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/RunArguments.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.codehaus.plexus.util.cli.CommandLineUtils; import java.util.Arrays; import java.util.Deque; import java.util.LinkedList; import java.util.Objects; /** * Parse and expose arguments specified in a single string. */ class RunArguments { private static final String[] NO_ARGS = {}; private final Deque<String> args = new LinkedList<>(); RunArguments(String arguments) { this(parseArgs(arguments)); } RunArguments(String[] args) { if (args != null) { Arrays.stream(args).filter(Objects::nonNull).forEach(this.args::add); } } Deque<String> getArgs() { return this.args; } String[] asArray() { return this.args.toArray(new String[0]); } private static String[] parseArgs(String arguments) { if (arguments == null || arguments.trim().isEmpty()) { return NO_ARGS; } try { arguments = arguments.replace('\n', ' ').replace('\t', ' '); return CommandLineUtils.translateCommandline(arguments); } catch (Exception ex) { throw new IllegalArgumentException("Failed to parse arguments [" + arguments + "]", ex); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaProcessExecutor.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaProcessExecutor.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.toolchain.Toolchain; import org.apache.maven.toolchain.ToolchainManager; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.function.Consumer; /** * Ease the execution of a Java process using Maven's toolchain support. */ class JavaProcessExecutor { private static final int EXIT_CODE_SIGINT = 130; private final MavenSession mavenSession; private final ToolchainManager toolchainManager; private final Consumer<RunProcess> runProcessCustomizer; JavaProcessExecutor(MavenSession mavenSession, ToolchainManager toolchainManager) { this(mavenSession, toolchainManager, null); } private JavaProcessExecutor(MavenSession mavenSession, ToolchainManager toolchainManager, Consumer<RunProcess> runProcessCustomizer) { this.mavenSession = mavenSession; this.toolchainManager = toolchainManager; this.runProcessCustomizer = runProcessCustomizer; } JavaProcessExecutor withRunProcessCustomizer(Consumer<RunProcess> customizer) { Consumer<RunProcess> combinedCustomizer = (this.runProcessCustomizer != null) ? this.runProcessCustomizer.andThen(customizer) : customizer; return new JavaProcessExecutor(this.mavenSession, this.toolchainManager, combinedCustomizer); } int run(File workingDirectory, List<String> args, Map<String, String> environmentVariables) throws MojoExecutionException { RunProcess runProcess = new RunProcess(workingDirectory, getJavaExecutable()); if (this.runProcessCustomizer != null) { this.runProcessCustomizer.accept(runProcess); } try { int exitCode = runProcess.run(true, args, environmentVariables); if (!hasTerminatedSuccessfully(exitCode)) { throw new MojoExecutionException("Process terminated with exit code: " + exitCode); } return exitCode; } catch (IOException ex) { throw new MojoExecutionException("Process execution failed", ex); } } RunProcess runAsync(File workingDirectory, List<String> args, Map<String, String> environmentVariables) throws MojoExecutionException { try { RunProcess runProcess = new RunProcess(workingDirectory, getJavaExecutable()); runProcess.run(false, args, environmentVariables); return runProcess; } catch (IOException ex) { throw new MojoExecutionException("Process execution failed", ex); } } private boolean hasTerminatedSuccessfully(int exitCode) { return (exitCode == 0 || exitCode == EXIT_CODE_SIGINT); } private String getJavaExecutable() { Toolchain toolchain = this.toolchainManager.getToolchainFromBuildContext("jdk", this.mavenSession); String javaExecutable = (toolchain != null) ? toolchain.findTool("java") : null; return (javaExecutable != null) ? javaExecutable : new JavaExecutable().toString(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaExecutable.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaExecutable.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.SystemPropertyConfigUtils; import java.io.File; import java.io.IOException; import java.util.Arrays; /** * Provides access to the java binary executable, regardless of OS. */ public class JavaExecutable { private final File file; public JavaExecutable() { String javaHome = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.SystemProperty.JAVA_HOME); Assert.assertTrue(StringUtils.isNotEmpty(javaHome), "Unable to find java executable due to missing 'java.home'"); this.file = findInJavaHome(javaHome); } private File findInJavaHome(String javaHome) { File bin = new File(new File(javaHome), "bin"); File command = new File(bin, "java.exe"); command = command.exists() ? command : new File(bin, "java"); Assert.assertTrue(command.exists(), () -> "Unable to find java in " + javaHome); return command; } /** * Create a new {@link ProcessBuilder} that will run with the Java executable. * * @param arguments the command arguments * @return a {@link ProcessBuilder} */ public ProcessBuilder processBuilder(String... arguments) { ProcessBuilder processBuilder = new ProcessBuilder(toString()); processBuilder.command().addAll(Arrays.asList(arguments)); return processBuilder; } @Override public String toString() { try { return this.file.getCanonicalPath(); } catch (IOException ex) { throw new IllegalStateException(ex); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/IncludeFilter.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/IncludeFilter.java
/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import java.util.List; /** * An {@link ArtifactsFilter} that filters out any artifact not matching an * {@link Include}. */ public class IncludeFilter extends DependencyFilter { public IncludeFilter(List<Include> includes) { super(includes); } @Override protected boolean filter(Artifact artifact) { for (FilterableDependency dependency : getFilters()) { if (equals(artifact, dependency)) { return false; } } return true; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/RunProcess.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/RunProcess.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; /** * Utility used to run a process. */ public class RunProcess { private static final long JUST_ENDED_LIMIT = 500; private final File workingDirectory; private final String[] command; private volatile Process process; private volatile long endTime; /** * Creates new {@link RunProcess} instance for the specified command. * @param command the program to execute and its arguments */ public RunProcess(String... command) { this(null, command); } /** * Creates new {@link RunProcess} instance for the specified working directory and * command. * @param workingDirectory the working directory of the child process or {@code null} * to run in the working directory of the current Java process * @param command the program to execute and its arguments */ public RunProcess(File workingDirectory, String... command) { this.workingDirectory = workingDirectory; this.command = command; } public int run(boolean waitForProcess, String... args) throws IOException { return run(waitForProcess, Arrays.asList(args), Collections.emptyMap()); } public int run(boolean waitForProcess, Collection<String> args, Map<String, String> environmentVariables) throws IOException { ProcessBuilder builder = new ProcessBuilder(this.command); builder.directory(this.workingDirectory); builder.command().addAll(args); builder.environment().putAll(environmentVariables); builder.redirectErrorStream(true); builder.inheritIO(); try { Process process = builder.start(); this.process = process; if (waitForProcess) { try { return process.waitFor(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return 1; } } return 5; } finally { if (waitForProcess) { this.endTime = System.currentTimeMillis(); this.process = null; } } } /** * Return the running process. * @return the process or {@code null} */ public Process getRunningProcess() { return this.process; } /** * Return if the process was stopped. * @return {@code true} if stopped */ public boolean handleSigInt() { if (allowChildToHandleSigInt()) { return true; } return doKill(); } private boolean allowChildToHandleSigInt() { Process process = this.process; if (process == null) { return true; } long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { if (!process.isAlive()) { return true; } try { Thread.sleep(500); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return false; } } return false; } /** * Kill this process. */ public void kill() { doKill(); } private boolean doKill() { // destroy the running process Process process = this.process; if (process != null) { try { process.destroy(); process.waitFor(); this.process = null; return true; } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } return false; } public boolean hasJustEnded() { return System.currentTimeMillis() < (this.endTime + JUST_ENDED_LIMIT); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaCompilerPluginConfiguration.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/JavaCompilerPluginConfiguration.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import java.util.Arrays; /** * Provides access to the Maven Java Compiler plugin configuration. */ class JavaCompilerPluginConfiguration { private final MavenProject project; JavaCompilerPluginConfiguration(MavenProject project) { this.project = project; } String getSourceMajorVersion() { String version = getConfigurationValue("source"); if (version == null) { version = getPropertyValue("maven.compiler.source"); } return majorVersionFor(version); } String getTargetMajorVersion() { String version = getConfigurationValue("target"); if (version == null) { version = getPropertyValue("maven.compiler.target"); } return majorVersionFor(version); } String getReleaseVersion() { String version = getConfigurationValue("release"); if (version == null) { version = getPropertyValue("maven.compiler.release"); } return majorVersionFor(version); } private String getConfigurationValue(String propertyName) { Plugin plugin = this.project.getPlugin("org.apache.maven.plugins:maven-compiler-plugin"); if (plugin != null) { Object pluginConfiguration = plugin.getConfiguration(); if (pluginConfiguration instanceof Xpp3Dom) { return getNodeValue((Xpp3Dom)pluginConfiguration, propertyName); } } return null; } private String getPropertyValue(String propertyName) { if (this.project.getProperties().containsKey(propertyName)) { return this.project.getProperties().get(propertyName).toString(); } return null; } private String getNodeValue(Xpp3Dom dom, String... childNames) { Xpp3Dom childNode = dom.getChild(childNames[0]); if (childNode == null) { return null; } if (childNames.length > 1) { return getNodeValue(childNode, Arrays.copyOfRange(childNames, 1, childNames.length)); } return childNode.getValue(); } private String majorVersionFor(String version) { if (version != null && version.startsWith("1.")) { return version.substring("1.".length()); } return version; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractAotMojo.java
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractAotMojo.java
/* * Copyright 2012-2022 the original author or authors. * * 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 * * https://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.maven.plugin.aot; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter; import org.apache.maven.toolchain.ToolchainManager; import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Abstract base class for AOT processing MOJOs. */ public abstract class AbstractAotMojo extends AbstractDependencyFilterMojo { /** * The current Maven session. This is used for toolchain manager API calls. */ @Parameter(defaultValue = "${session}", readonly = true) private MavenSession session; /** * The toolchain manager to use to locate a custom JDK. */ @Component private ToolchainManager toolchainManager; /** * Skip the execution. */ @Parameter(property = "dubbo.aot.skip", defaultValue = "false") private boolean skip; /** * List of JVM system properties to pass to the AOT process. */ @Parameter private Map<String, String> systemPropertyVariables; /** * JVM arguments that should be associated with the AOT process. On command line, make * sure to wrap multiple values between quotes. */ @Parameter(property = "dubbo.aot.jvmArguments") private String jvmArguments; /** * Arguments that should be provided to the AOT compile process. On command line, make * sure to wrap multiple values between quotes. */ @Parameter(property = "dubbo.aot.compilerArguments") private String compilerArguments; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.skip) { getLog().debug("Skipping AOT execution as per configuration"); return; } try { executeAot(); } catch (Exception ex) { throw new MojoExecutionException(ex.getMessage(), ex); } } protected abstract void executeAot() throws Exception; protected void generateAotAssets(URL[] classPath, String processorClassName, String... arguments) throws Exception { List<String> command = CommandLineBuilder.forMainClass(processorClassName) .withSystemProperties(this.systemPropertyVariables) .withJvmArguments(new RunArguments(this.jvmArguments).asArray()).withClasspath(classPath) .withArguments(arguments).build(); if (getLog().isDebugEnabled()) { getLog().debug("Generating AOT assets using command: " + command); } JavaProcessExecutor processExecutor = new JavaProcessExecutor(this.session, this.toolchainManager); getLog().info("dir: " + this.project.getBasedir()); processExecutor.run(this.project.getBasedir(), command, Collections.emptyMap()); } protected final void compileSourceFiles(URL[] classPath, File sourcesDirectory, File outputDirectory) throws Exception { List<File> sourceFiles; try (Stream<Path> pathStream = Files.walk(sourcesDirectory.toPath())) { sourceFiles = pathStream.filter(Files::isRegularFile).map(Path::toFile).collect(Collectors.toList()); } if (sourceFiles.isEmpty()) { return; } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) { JavaCompilerPluginConfiguration compilerConfiguration = new JavaCompilerPluginConfiguration(this.project); List<String> options = new ArrayList<>(); options.add("-cp"); options.add(CommandLineBuilder.ClasspathBuilder.build(Arrays.asList(classPath))); options.add("-d"); options.add(outputDirectory.toPath().toAbsolutePath().toString()); String releaseVersion = compilerConfiguration.getReleaseVersion(); if (releaseVersion != null) { options.add("--release"); options.add(releaseVersion); } else { options.add("--source"); options.add(compilerConfiguration.getSourceMajorVersion()); options.add("--target"); options.add(compilerConfiguration.getTargetMajorVersion()); } options.addAll(new RunArguments(this.compilerArguments).getArgs()); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFiles); Errors errors = new Errors(); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, errors, options, null, compilationUnits); boolean result = task.call(); if (!result || errors.hasReportedErrors()) { throw new IllegalStateException("Unable to compile generated source" + errors); } } } protected final List<URL> getClassPath(File[] directories, ArtifactsFilter... artifactFilters) throws MojoExecutionException { List<URL> urls = new ArrayList<>(); Arrays.stream(directories).map(this::toURL).forEach(urls::add); urls.addAll(getDependencyURLs(artifactFilters)); return urls; } protected final void copyAll(Path from, Path to) throws IOException { if (!Files.exists(from)) { return; } List<Path> files; try (Stream<Path> pathStream = Files.walk(from)) { files = pathStream.filter(Files::isRegularFile).collect(Collectors.toList()); } for (Path file : files) { String relativeFileName = file.subpath(from.getNameCount(), file.getNameCount()).toString(); getLog().debug("Copying '" + relativeFileName + "' to " + to); Path target = to.resolve(relativeFileName); Files.createDirectories(target.getParent()); Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING); } } /** * {@link DiagnosticListener} used to collect errors. */ protected static class Errors implements DiagnosticListener<JavaFileObject> { private final StringBuilder message = new StringBuilder(); @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { this.message.append("\n"); this.message.append(diagnostic.getMessage(Locale.getDefault())); if (diagnostic.getSource() != null) { this.message.append(" "); this.message.append(diagnostic.getSource().getName()); this.message.append(" "); this.message.append(diagnostic.getLineNumber()).append(":").append(diagnostic.getColumnNumber()); } } } boolean hasReportedErrors() { return this.message.length() > 0; } @Override public String toString() { return this.message.toString(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false