index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsSupport.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;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.lang.Nullable;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metrics.collector.MethodMetricsCollector;
import org.apache.dubbo.metrics.collector.ServiceMetricsCollector;
import org.apache.dubbo.metrics.event.MetricsEvent;
import org.apache.dubbo.metrics.event.TimeCounterEvent;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.key.MetricsPlaceValue;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_CHAR_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_MODULE;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_VERSION_KEY;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_INTERFACE_KEY;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_METHOD_KEY;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE;
import static org.apache.dubbo.metrics.MetricsConstants.INVOCATION;
import static org.apache.dubbo.metrics.MetricsConstants.METHOD_METRICS;
import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE;
public class MetricsSupport {
private static final String version = Version.getVersion();
private static final String commitId = Version.getLastCommitId();
public static Map<String, String> applicationTags(ApplicationModel applicationModel) {
return applicationTags(applicationModel, null);
}
public static Map<String, String> applicationTags(
ApplicationModel applicationModel, @Nullable Map<String, String> extraInfo) {
Map<String, String> tags = new HashMap<>();
tags.put(TAG_APPLICATION_NAME, applicationModel.getApplicationName());
tags.put(TAG_APPLICATION_MODULE, applicationModel.getInternalId());
if (CollectionUtils.isNotEmptyMap(extraInfo)) {
tags.putAll(extraInfo);
}
return tags;
}
public static Map<String, String> gitTags(Map<String, String> tags) {
tags.put(MetricsKey.METADATA_GIT_COMMITID_METRIC.getName(), commitId);
tags.put(TAG_APPLICATION_VERSION_KEY, version);
return tags;
}
public static Map<String, String> hostTags(Map<String, String> tags) {
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_HOSTNAME, getLocalHostName());
return tags;
}
public static Map<String, String> serviceTags(
ApplicationModel applicationModel, String serviceKey, Map<String, String> extraInfo) {
Map<String, String> tags = applicationTags(applicationModel, extraInfo);
tags.put(TAG_INTERFACE_KEY, serviceKey);
return tags;
}
public static Map<String, String> methodTags(
ApplicationModel applicationModel, String serviceKey, String methodName) {
Map<String, String> tags = applicationTags(applicationModel);
tags.put(TAG_INTERFACE_KEY, serviceKey);
tags.put(TAG_METHOD_KEY, methodName);
return tags;
}
public static MetricsKey getMetricsKey(Throwable throwable) {
MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED;
if (throwable instanceof RpcException) {
RpcException e = (RpcException) throwable;
if (e.isTimeout()) {
targetKey = MetricsKey.METRIC_REQUESTS_TIMEOUT;
}
if (e.isLimitExceed()) {
targetKey = MetricsKey.METRIC_REQUESTS_LIMIT;
}
if (e.isBiz()) {
targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED;
}
if (e.isSerialization()) {
targetKey = MetricsKey.METRIC_REQUESTS_CODEC_FAILED;
}
if (e.isNetwork()) {
targetKey = MetricsKey.METRIC_REQUESTS_NETWORK_FAILED;
}
} else {
targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED;
}
return targetKey;
}
public static MetricsKey getAggMetricsKey(Throwable throwable) {
MetricsKey targetKey = MetricsKey.METRIC_REQUESTS_FAILED_AGG;
if (throwable instanceof RpcException) {
RpcException e = (RpcException) throwable;
if (e.isTimeout()) {
targetKey = MetricsKey.METRIC_REQUESTS_TIMEOUT_AGG;
}
if (e.isLimitExceed()) {
targetKey = MetricsKey.METRIC_REQUESTS_LIMIT_AGG;
}
if (e.isBiz()) {
targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG;
}
if (e.isSerialization()) {
targetKey = MetricsKey.METRIC_REQUESTS_CODEC_FAILED_AGG;
}
if (e.isNetwork()) {
targetKey = MetricsKey.METRIC_REQUESTS_NETWORK_FAILED_AGG;
}
} else {
targetKey = MetricsKey.METRIC_REQUEST_BUSINESS_FAILED_AGG;
}
return targetKey;
}
public static String getSide(Invocation invocation) {
Optional<? extends Invoker<?>> invoker = Optional.ofNullable(invocation.getInvoker());
return invoker.isPresent() ? invoker.get().getUrl().getSide() : PROVIDER_SIDE;
}
public static String getInterfaceName(Invocation invocation) {
if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) {
return invocation.getServiceModel().getServiceMetadata().getServiceInterfaceName();
} else {
String serviceUniqueName = invocation.getTargetServiceUniqueName();
String interfaceAndVersion;
if (StringUtils.isBlank(serviceUniqueName)) {
return "";
}
String[] arr = serviceUniqueName.split(PATH_SEPARATOR);
if (arr.length == 2) {
interfaceAndVersion = arr[1];
} else {
interfaceAndVersion = arr[0];
}
String[] ivArr = interfaceAndVersion.split(GROUP_CHAR_SEPARATOR);
return ivArr[0];
}
}
public static String getGroup(Invocation invocation) {
if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) {
return invocation.getServiceModel().getServiceMetadata().getGroup();
} else {
String serviceUniqueName = invocation.getTargetServiceUniqueName();
String group = null;
String[] arr = serviceUniqueName.split(PATH_SEPARATOR);
if (arr.length == 2) {
group = arr[0];
}
return group;
}
}
public static String getVersion(Invocation invocation) {
if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) {
return invocation.getServiceModel().getServiceMetadata().getVersion();
} else {
String interfaceAndVersion;
String[] arr = invocation.getTargetServiceUniqueName().split(PATH_SEPARATOR);
if (arr.length == 2) {
interfaceAndVersion = arr[1];
} else {
interfaceAndVersion = arr[0];
}
String[] ivArr = interfaceAndVersion.split(GROUP_CHAR_SEPARATOR);
return ivArr.length == 2 ? ivArr[1] : null;
}
}
/**
* Incr service num
*/
public static void increment(
MetricsKey metricsKey,
MetricsPlaceValue placeType,
ServiceMetricsCollector<TimeCounterEvent> collector,
MetricsEvent event) {
collector.increment(
event.getAttachmentValue(ATTACHMENT_KEY_SERVICE),
new MetricsKeyWrapper(metricsKey, placeType),
SELF_INCREMENT_SIZE);
}
/**
* Incr service num&&rt
*/
public static void incrAndAddRt(
MetricsKey metricsKey,
MetricsPlaceValue placeType,
ServiceMetricsCollector<TimeCounterEvent> collector,
TimeCounterEvent event) {
collector.increment(
event.getAttachmentValue(ATTACHMENT_KEY_SERVICE),
new MetricsKeyWrapper(metricsKey, placeType),
SELF_INCREMENT_SIZE);
Invocation invocation = event.getAttachmentValue(INVOCATION);
if (invocation != null) {
collector.addServiceRt(
invocation, placeType.getType(), event.getTimePair().calc());
} else {
collector.addServiceRt(
(String) event.getAttachmentValue(ATTACHMENT_KEY_SERVICE),
placeType.getType(),
event.getTimePair().calc());
}
}
/**
* Incr method num
*/
public static void increment(
MetricsKey metricsKey,
MetricsPlaceValue placeType,
MethodMetricsCollector<TimeCounterEvent> collector,
MetricsEvent event) {
collector.increment(
event.getAttachmentValue(METHOD_METRICS),
new MetricsKeyWrapper(metricsKey, placeType),
SELF_INCREMENT_SIZE);
}
public static void init(
MetricsKey metricsKey,
MetricsPlaceValue placeType,
MethodMetricsCollector<TimeCounterEvent> collector,
MetricsEvent event) {
collector.init(event.getAttachmentValue(INVOCATION), new MetricsKeyWrapper(metricsKey, placeType));
}
/**
* Dec method num
*/
public static void dec(
MetricsKey metricsKey,
MetricsPlaceValue placeType,
MethodMetricsCollector<TimeCounterEvent> collector,
MetricsEvent event) {
collector.increment(
event.getAttachmentValue(METHOD_METRICS),
new MetricsKeyWrapper(metricsKey, placeType),
-SELF_INCREMENT_SIZE);
}
/**
* Incr method num&&rt
*/
public static void incrAndAddRt(
MetricsKey metricsKey,
MetricsPlaceValue placeType,
MethodMetricsCollector<TimeCounterEvent> collector,
TimeCounterEvent event) {
collector.increment(
event.getAttachmentValue(METHOD_METRICS),
new MetricsKeyWrapper(metricsKey, placeType),
SELF_INCREMENT_SIZE);
collector.addMethodRt(
event.getAttachmentValue(INVOCATION),
placeType.getType(),
event.getTimePair().calc());
}
/**
* Generate a complete indicator item for an interface/method
*/
public static <T> void fillZero(Map<?, Map<T, AtomicLong>> data) {
if (CollectionUtils.isEmptyMap(data)) {
return;
}
Set<T> allKeyMetrics =
data.values().stream().flatMap(map -> map.keySet().stream()).collect(Collectors.toSet());
data.forEach((keyWrapper, mapVal) -> {
for (T key : allKeyMetrics) {
mapVal.computeIfAbsent(key, k -> new AtomicLong(0));
}
});
}
}
| 8,100 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/Metric.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;
import java.util.Map;
public interface Metric {
Map<String, String> getTags();
}
| 8,101 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ServiceKeyMetric.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;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import java.util.Objects;
/**
* Metric class for service.
*/
public class ServiceKeyMetric extends ApplicationMetric {
private final String serviceKey;
public ServiceKeyMetric(ApplicationModel applicationModel, String serviceKey) {
super(applicationModel);
this.serviceKey = serviceKey;
}
@Override
public Map<String, String> getTags() {
return MetricsSupport.serviceTags(getApplicationModel(), serviceKey, getExtraInfo());
}
public String getServiceKey() {
return serviceKey;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ServiceKeyMetric)) {
return false;
}
ServiceKeyMetric that = (ServiceKeyMetric) o;
return serviceKey.equals(that.serviceKey) && Objects.equals(extraInfo, that.extraInfo);
}
private volatile int hashCode = 0;
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(getApplicationName(), serviceKey, extraInfo);
}
return hashCode;
}
@Override
public String toString() {
return "ServiceKeyMetric{" + "applicationName='"
+ getApplicationName() + '\'' + ", serviceKey='"
+ serviceKey + '\'' + '}';
}
}
| 8,102 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ThreadPoolRejectMetric.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;
import org.apache.dubbo.common.utils.ConfigUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_PID;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_THREAD_NAME;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
public class ThreadPoolRejectMetric implements Metric {
private String applicationName;
private String threadPoolName;
public ThreadPoolRejectMetric(String applicationName, String threadPoolName) {
this.applicationName = applicationName;
this.threadPoolName = threadPoolName;
}
public String getThreadPoolName() {
return threadPoolName;
}
public void setThreadPoolName(String threadPoolName) {
this.threadPoolName = threadPoolName;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ThreadPoolRejectMetric that = (ThreadPoolRejectMetric) o;
return Objects.equals(applicationName, that.applicationName)
&& Objects.equals(threadPoolName, that.threadPoolName);
}
@Override
public int hashCode() {
return Objects.hash(applicationName, threadPoolName);
}
public Map<String, String> getTags() {
Map<String, String> tags = new HashMap<>();
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_PID, ConfigUtils.getPid() + "");
tags.put(TAG_HOSTNAME, getLocalHostName());
tags.put(TAG_APPLICATION_NAME, applicationName);
tags.put(TAG_THREAD_NAME, threadPoolName);
return tags;
}
}
| 8,103 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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;
}
}
| 8,104 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ConfigCenterMetric.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;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_CHANGE_TYPE;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_CONFIG_CENTER;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_GROUP_KEY;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_HOSTNAME;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_IP;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_KEY_KEY;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHostName;
public class ConfigCenterMetric implements Metric {
private String applicationName;
private String key;
private String group;
private String configCenter;
private String changeType;
public ConfigCenterMetric() {}
public ConfigCenterMetric(
String applicationName, String key, String group, String configCenter, String changeType) {
this.applicationName = applicationName;
this.key = key;
this.group = group;
this.configCenter = configCenter;
this.changeType = changeType;
}
@Override
public Map<String, String> getTags() {
Map<String, String> tags = new HashMap<>();
tags.put(TAG_IP, getLocalHost());
tags.put(TAG_HOSTNAME, getLocalHostName());
tags.put(TAG_APPLICATION_NAME, applicationName);
tags.put(TAG_KEY_KEY, key);
tags.put(TAG_GROUP_KEY, group);
tags.put(TAG_CONFIG_CENTER, configCenter);
tags.put(TAG_CHANGE_TYPE, changeType.toLowerCase());
return tags;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConfigCenterMetric that = (ConfigCenterMetric) o;
if (!Objects.equals(applicationName, that.applicationName)) return false;
if (!Objects.equals(key, that.key)) return false;
if (!Objects.equals(group, that.group)) return false;
if (!Objects.equals(configCenter, that.configCenter)) return false;
return Objects.equals(changeType, that.changeType);
}
@Override
public int hashCode() {
return Objects.hash(applicationName, key, group, configCenter, changeType);
}
}
| 8,105 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/ApplicationMetric.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;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import java.util.Objects;
public class ApplicationMetric implements Metric {
private final ApplicationModel applicationModel;
protected Map<String, String> extraInfo;
public ApplicationMetric(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public String getApplicationName() {
return getApplicationModel().getApplicationName();
}
@Override
public Map<String, String> getTags() {
return hostTags(gitTags(MetricsSupport.applicationTags(applicationModel, getExtraInfo())));
}
public Map<String, String> gitTags(Map<String, String> tags) {
return MetricsSupport.gitTags(tags);
}
public Map<String, String> hostTags(Map<String, String> tags) {
return MetricsSupport.hostTags(tags);
}
public Map<String, String> getExtraInfo() {
return extraInfo;
}
public void setExtraInfo(Map<String, String> extraInfo) {
this.extraInfo = extraInfo;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ApplicationMetric that = (ApplicationMetric) o;
return getApplicationName().equals(that.applicationModel.getApplicationName())
&& Objects.equals(extraInfo, that.extraInfo);
}
private volatile int hashCode;
@Override
public int hashCode() {
if (hashCode == 0) {
hashCode = Objects.hash(getApplicationName(), extraInfo);
}
return hashCode;
}
}
| 8,106 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/MetricsCategory.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;
/**
* Metric category.
*/
public enum MetricsCategory {
RT,
QPS,
REQUESTS,
APPLICATION,
CONFIGCENTER,
REGISTRY,
METADATA,
THREAD_POOL,
}
| 8,107 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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);
}
}
| 8,108 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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"),
;
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 final String getDescription() {
return this.description;
}
MetricsKey(String name, String description) {
this.name = name;
this.description = description;
}
}
| 8,109 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsKeyWrapper.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.metrics.model.sample.MetricSample;
import java.util.Objects;
import io.micrometer.common.lang.Nullable;
/**
* Let {@link MetricsKey MetricsKey} output dynamic, custom string content
*/
public class MetricsKeyWrapper {
/**
* Metrics key when exporting
*/
private final MetricsKey metricsKey;
/**
* The value corresponding to the MetricsKey placeholder (if exist)
*/
private final MetricsPlaceValue placeType;
/**
* Exported sample type
*/
private MetricSample.Type sampleType = MetricSample.Type.COUNTER;
/**
* When the MetricsPlaceType is null, it is equivalent to a single MetricsKey.
* Use the decorator mode to share a container with MetricsKey
*/
public MetricsKeyWrapper(MetricsKey metricsKey, @Nullable MetricsPlaceValue placeType) {
this.metricsKey = metricsKey;
this.placeType = placeType;
}
public MetricsKeyWrapper setSampleType(MetricSample.Type sampleType) {
this.sampleType = sampleType;
return this;
}
public MetricSample.Type getSampleType() {
return sampleType;
}
public MetricsPlaceValue getPlaceType() {
return placeType;
}
public String getType() {
return getPlaceType().getType();
}
public MetricsKey getMetricsKey() {
return metricsKey;
}
public boolean isKey(MetricsKey metricsKey, String registryOpType) {
return metricsKey == getMetricsKey() && registryOpType.equals(getType());
}
public MetricsLevel getLevel() {
return getPlaceType().getMetricsLevel();
}
public String targetKey() {
if (placeType == null) {
return metricsKey.getName();
}
try {
return String.format(metricsKey.getName(), getType());
} catch (Exception ignore) {
return metricsKey.getName();
}
}
public String targetDesc() {
if (placeType == null) {
return metricsKey.getDescription();
}
try {
return String.format(metricsKey.getDescription(), getType());
} catch (Exception ignore) {
return metricsKey.getDescription();
}
}
public static MetricsKeyWrapper wrapper(MetricsKey metricsKey) {
return new MetricsKeyWrapper(metricsKey, null);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricsKeyWrapper wrapper = (MetricsKeyWrapper) o;
if (metricsKey != wrapper.metricsKey) return false;
return Objects.equals(placeType, wrapper.placeType);
}
@Override
public int hashCode() {
int result = metricsKey != null ? metricsKey.hashCode() : 0;
result = 31 * result + (placeType != null ? placeType.hashCode() : 0);
return result;
}
}
| 8,110 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsCat.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.metrics.collector.CombMetricsCollector;
import org.apache.dubbo.metrics.listener.AbstractMetricsKeyListener;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* The behavior wrapper class of MetricsKey,
* which saves the complete content of the key {@link MetricsPlaceValue},
* the corresponding collector {@link CombMetricsCollector},
* and the event listener (generate function) at the key level {@link AbstractMetricsKeyListener}
*/
public class MetricsCat {
private MetricsPlaceValue placeType;
private final Function<CombMetricsCollector, AbstractMetricsKeyListener> eventFunc;
/**
* @param metricsKey The key corresponding to the listening event, not necessarily the export key(export key may be dynamic)
* @param biFunc Binary function, corresponding to MetricsKey with less content, corresponding to post event
*/
public MetricsCat(
MetricsKey metricsKey, BiFunction<MetricsKey, CombMetricsCollector, AbstractMetricsKeyListener> biFunc) {
this.eventFunc = collector -> biFunc.apply(metricsKey, collector);
}
/**
* @param tpFunc Ternary function, corresponding to finish and error events, because an additional record rt is required, and the type of metricsKey is required
*/
public MetricsCat(
MetricsKey metricsKey,
TpFunction<MetricsKey, MetricsPlaceValue, CombMetricsCollector, AbstractMetricsKeyListener> tpFunc) {
this.eventFunc = collector -> tpFunc.apply(metricsKey, placeType, collector);
}
public MetricsCat setPlaceType(MetricsPlaceValue placeType) {
this.placeType = placeType;
return this;
}
public Function<CombMetricsCollector, AbstractMetricsKeyListener> getEventFunc() {
return eventFunc;
}
@FunctionalInterface
public interface TpFunction<T, U, K, R> {
R apply(T t, U u, K k);
}
}
| 8,111 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/CategoryOverall.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.lang.Nullable;
/**
* The overall event set, including the event processing functions in three stages
*/
public class CategoryOverall {
private final MetricsCat post;
private MetricsCat finish;
private MetricsCat error;
/**
* @param placeType When placeType is null, it means that placeType is obtained dynamically
* @param post Statistics of the number of events, as long as it occurs, it will take effect, so it cannot be null
*/
public CategoryOverall(
@Nullable MetricsPlaceValue placeType,
MetricsCat post,
@Nullable MetricsCat finish,
@Nullable MetricsCat error) {
this.post = post.setPlaceType(placeType);
if (finish != null) {
this.finish = finish.setPlaceType(placeType);
}
if (error != null) {
this.error = error.setPlaceType(placeType);
}
}
public MetricsCat getPost() {
return post;
}
public MetricsCat getFinish() {
return finish;
}
public MetricsCat getError() {
return error;
}
}
| 8,112 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/key/MetricsPlaceValue.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;
/**
* The value corresponding to the placeholder in {@link MetricsKey}
*/
public class MetricsPlaceValue {
private final String type;
private final MetricsLevel metricsLevel;
private MetricsPlaceValue(String type, MetricsLevel metricsLevel) {
this.type = type;
this.metricsLevel = metricsLevel;
}
public static MetricsPlaceValue of(String type, MetricsLevel metricsLevel) {
return new MetricsPlaceValue(type, metricsLevel);
}
public String getType() {
return type;
}
public MetricsLevel getMetricsLevel() {
return metricsLevel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricsPlaceValue that = (MetricsPlaceValue) o;
if (!type.equals(that.type)) return false;
return metricsLevel == that.metricsLevel;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + metricsLevel.hashCode();
return result;
}
}
| 8,113 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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
}
| 8,114 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongAccumulatorContainer.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.container;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import java.util.concurrent.atomic.LongAccumulator;
public class LongAccumulatorContainer extends LongContainer<LongAccumulator> {
public LongAccumulatorContainer(MetricsKeyWrapper metricsKeyWrapper, LongAccumulator accumulator) {
super(
metricsKeyWrapper,
() -> accumulator,
(responseTime, longAccumulator) -> longAccumulator.accumulate(responseTime));
}
}
| 8,115 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/AtomicLongContainer.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.container;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
public class AtomicLongContainer extends LongContainer<AtomicLong> {
public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper) {
super(metricsKeyWrapper, AtomicLong::new, (responseTime, longAccumulator) -> longAccumulator.set(responseTime));
}
public AtomicLongContainer(MetricsKeyWrapper metricsKeyWrapper, BiConsumer<Long, AtomicLong> consumerFunc) {
super(metricsKeyWrapper, AtomicLong::new, consumerFunc);
}
}
| 8,116 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.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.container;
import org.apache.dubbo.metrics.model.Metric;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Long type data container
* @param <N>
*/
public class LongContainer<N extends Number> extends ConcurrentHashMap<Metric, N> {
/**
* Provide the metric type name
*/
private final transient MetricsKeyWrapper metricsKeyWrapper;
/**
* The initial value corresponding to the key is generally 0 of different data types
*/
private final transient Function<Metric, N> initFunc;
/**
* Statistical data calculation function, which can be self-increment, self-decrement, or more complex avg function
*/
private final transient BiConsumer<Long, N> consumerFunc;
/**
* Data output function required by {@link GaugeMetricSample GaugeMetricSample}
*/
private transient Function<Metric, Long> valueSupplier;
public LongContainer(MetricsKeyWrapper metricsKeyWrapper, Supplier<N> initFunc, BiConsumer<Long, N> consumerFunc) {
super(128, 0.5f);
this.metricsKeyWrapper = metricsKeyWrapper;
this.initFunc = s -> initFunc.get();
this.consumerFunc = consumerFunc;
this.valueSupplier = k -> this.get(k).longValue();
}
public boolean specifyType(String type) {
return type.equals(getMetricsKeyWrapper().getType());
}
public MetricsKeyWrapper getMetricsKeyWrapper() {
return metricsKeyWrapper;
}
public boolean isKeyWrapper(MetricsKey metricsKey, String registryOpType) {
return metricsKeyWrapper.isKey(metricsKey, registryOpType);
}
public Function<Metric, N> getInitFunc() {
return initFunc;
}
public BiConsumer<Long, N> getConsumerFunc() {
return consumerFunc;
}
public Function<Metric, Long> getValueSupplier() {
return valueSupplier;
}
public void setValueSupplier(Function<Metric, Long> valueSupplier) {
this.valueSupplier = valueSupplier;
}
@Override
public String toString() {
return "LongContainer{" + "metricsKeyWrapper=" + metricsKeyWrapper + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
LongContainer<?> that = (LongContainer<?>) o;
return metricsKeyWrapper.equals(that.metricsKeyWrapper);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + metricsKeyWrapper.hashCode();
return result;
}
}
| 8,117 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/CounterMetricSample.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.sample;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import java.util.Map;
public class CounterMetricSample<T extends Number> extends MetricSample {
private final T value;
public CounterMetricSample(
String name, String description, Map<String, String> tags, MetricsCategory category, T value) {
super(name, description, tags, Type.COUNTER, category);
this.value = value;
}
public CounterMetricSample(
MetricsKeyWrapper metricsKeyWrapper, Map<String, String> tags, MetricsCategory category, T value) {
this(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tags, category, value);
}
public T getValue() {
return value;
}
}
| 8,118 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/GaugeMetricSample.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.sample;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import java.util.Map;
import java.util.Objects;
import java.util.function.ToDoubleFunction;
/**
* GaugeMetricSample.
*/
public class GaugeMetricSample<T> extends MetricSample {
private final T value;
private final ToDoubleFunction<T> apply;
public GaugeMetricSample(
MetricsKey metricsKey,
Map<String, String> tags,
MetricsCategory category,
T value,
ToDoubleFunction<T> apply) {
this(metricsKey.getName(), metricsKey.getDescription(), tags, category, null, value, apply);
}
public GaugeMetricSample(
MetricsKeyWrapper metricsKeyWrapper,
Map<String, String> tags,
MetricsCategory category,
T value,
ToDoubleFunction<T> apply) {
this(metricsKeyWrapper.targetKey(), metricsKeyWrapper.targetDesc(), tags, category, null, value, apply);
}
public GaugeMetricSample(
String name,
String description,
Map<String, String> tags,
MetricsCategory category,
T value,
ToDoubleFunction<T> apply) {
this(name, description, tags, category, null, value, apply);
}
public GaugeMetricSample(
String name,
String description,
Map<String, String> tags,
MetricsCategory category,
String baseUnit,
T value,
ToDoubleFunction<T> apply) {
super(name, description, tags, Type.GAUGE, category, baseUnit);
this.value = Objects.requireNonNull(value, "The GaugeMetricSample value cannot be null");
this.apply = Objects.requireNonNull(apply, "The GaugeMetricSample apply cannot be null");
}
public T getValue() {
return this.value;
}
public ToDoubleFunction<T> getApply() {
return this.apply;
}
public long applyAsLong() {
return (long) getApply().applyAsDouble(getValue());
}
public double applyAsDouble() {
return getApply().applyAsDouble(getValue());
}
}
| 8,119 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/sample/MetricSample.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.sample;
import org.apache.dubbo.metrics.model.MetricsCategory;
import java.util.Map;
import java.util.Objects;
/**
* MetricSample.
*/
public class MetricSample {
private String name;
private String description;
private Map<String, String> tags;
private Type type;
private MetricsCategory category;
private String baseUnit;
public MetricSample(
String name, String description, Map<String, String> tags, Type type, MetricsCategory category) {
this(name, description, tags, type, category, null);
}
public MetricSample(
String name,
String description,
Map<String, String> tags,
Type type,
MetricsCategory category,
String baseUnit) {
this.name = name;
this.description = description;
this.tags = tags;
this.type = type;
this.category = category;
this.baseUnit = baseUnit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public MetricsCategory getCategory() {
return category;
}
public void setCategory(MetricsCategory category) {
this.category = category;
}
public String getBaseUnit() {
return baseUnit;
}
public void setBaseUnit(String baseUnit) {
this.baseUnit = baseUnit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricSample that = (MetricSample) o;
return Objects.equals(name, that.name)
&& Objects.equals(description, that.description)
&& Objects.equals(baseUnit, that.baseUnit)
&& type == that.type
&& Objects.equals(category, that.category)
&& Objects.equals(tags, that.tags);
}
@Override
public int hashCode() {
return Objects.hash(name, description, baseUnit, type, category, tags);
}
@Override
public String toString() {
return "MetricSample{" + "name='"
+ name + '\'' + ", description='"
+ description + '\'' + ", baseUnit='"
+ baseUnit + '\'' + ", type="
+ type + ", category="
+ category + ", tags="
+ tags + '}';
}
public enum Type {
COUNTER,
GAUGE,
LONG_TASK_TIMER,
TIMER,
DISTRIBUTION_SUMMARY
}
}
| 8,120 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporter.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.report;
/**
* Metrics Reporter.
* Report metrics to specific metrics server(e.g. Prometheus).
*/
public interface MetricsReporter {
/**
* Initialize metrics reporter.
*/
void init();
void resetIfSamplesChanged();
String getResponse();
default String getResponseWithName(String metricsName) {
return null;
}
}
| 8,121 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsExport.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.report;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import java.util.List;
/**
* Metrics data export.
* Export data in a unified format for external collection(e.g. Prometheus).
*/
public interface MetricsExport {
/**
* export all.
*/
List<MetricSample> export(MetricsCategory category);
/**
* Check if samples have been changed.
* Note that this method will reset the changed flag to false using CAS.
*
* @return true if samples have been changed
*/
boolean calSamplesChanged();
}
| 8,122 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsReporterFactory.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.report;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* AbstractMetricsReporterFactory.
*/
public abstract class AbstractMetricsReporterFactory implements MetricsReporterFactory {
private final ApplicationModel applicationModel;
public AbstractMetricsReporterFactory(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
protected ApplicationModel getApplicationModel() {
return applicationModel;
}
}
| 8,123 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/AbstractMetricsExport.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.report;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
* Store public information such as application
*/
public abstract class AbstractMetricsExport implements MetricsExport {
private final ApplicationModel applicationModel;
public AbstractMetricsExport(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public String getAppName() {
return getApplicationModel().getApplicationName();
}
}
| 8,124 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/report/MetricsReporterFactory.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.report;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* The factory interface to create the instance of {@link MetricsReporter}.
*/
@SPI(value = "nop", scope = ExtensionScope.APPLICATION)
public interface MetricsReporterFactory {
/**
* Create metrics reporter.
*
* @param url URL
* @return Metrics reporter implementation.
*/
@Adaptive({CommonConstants.PROTOCOL_KEY})
MetricsReporter createMetricsReporter(URL url);
}
| 8,125 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsEntity.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.service;
import org.apache.dubbo.metrics.model.MetricsCategory;
import java.util.Map;
import java.util.Objects;
/**
* Metrics response entity.
*/
public class MetricsEntity {
private String name;
private Map<String, String> tags;
private MetricsCategory category;
private Object value;
public MetricsEntity() {}
public MetricsEntity(String name, Map<String, String> tags, MetricsCategory category, Object value) {
this.name = name;
this.tags = tags;
this.category = category;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public MetricsCategory getCategory() {
return category;
}
public void setCategory(MetricsCategory category) {
this.category = category;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetricsEntity entity = (MetricsEntity) o;
return Objects.equals(name, entity.name)
&& Objects.equals(tags, entity.tags)
&& Objects.equals(category, entity.category)
&& Objects.equals(value, entity.value);
}
@Override
public int hashCode() {
return Objects.hash(name, tags, category, value);
}
}
| 8,126 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsService.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.service;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.metrics.collector.MetricsCollector;
import org.apache.dubbo.metrics.model.MetricsCategory;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.metrics.service.MetricsService.DEFAULT_EXTENSION_NAME;
/**
* Metrics Service.
* Provide an interface to get metrics from {@link MetricsCollector}
*/
@SPI(value = DEFAULT_EXTENSION_NAME, scope = ExtensionScope.APPLICATION)
public interface MetricsService {
/**
* Default {@link MetricsService} extension name.
*/
String DEFAULT_EXTENSION_NAME = "default";
/**
* The contract version of {@link MetricsService}, the future update must make sure compatible.
*/
String VERSION = "1.0.0";
/**
* Get metrics by prefixes
*
* @param categories categories
* @return metrics - key=MetricCategory value=MetricsEntityList
*/
Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories(List<MetricsCategory> categories);
/**
* Get metrics by interface and prefixes
*
* @param serviceUniqueName serviceUniqueName (eg.group/interfaceName:version)
* @param categories categories
* @return metrics - key=MetricCategory value=MetricsEntityList
*/
Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories(
String serviceUniqueName, List<MetricsCategory> categories);
/**
* Get metrics by interface、method and prefixes
*
* @param serviceUniqueName serviceUniqueName (eg.group/interfaceName:version)
* @param methodName methodName
* @param parameterTypes method parameter types
* @param categories categories
* @return metrics - key=MetricCategory value=MetricsEntityList
*/
Map<MetricsCategory, List<MetricsEntity>> getMetricsByCategories(
String serviceUniqueName, String methodName, Class<?>[] parameterTypes, List<MetricsCategory> categories);
}
| 8,127 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/service/MetricsServiceExporter.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.service;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* The exporter of {@link MetricsService}
*/
@SPI(value = "default", scope = ExtensionScope.APPLICATION)
public interface MetricsServiceExporter {
/**
* Initialize exporter
*/
void init();
/**
* Exports the {@link MetricsService} as a Dubbo service
*
* @return {@link MetricsServiceExporter itself}
*/
MetricsServiceExporter export();
/**
* Unexports the {@link MetricsService}
*
* @return {@link MetricsServiceExporter itself}
*/
MetricsServiceExporter unexport();
}
| 8,128 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/RtStatComposite.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.data;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.metrics.model.Metric;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.ServiceKeyMetric;
import org.apache.dubbo.metrics.model.container.AtomicLongContainer;
import org.apache.dubbo.metrics.model.container.LongAccumulatorContainer;
import org.apache.dubbo.metrics.model.container.LongContainer;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.key.MetricsPlaceValue;
import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.metrics.report.AbstractMetricsExport;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
/**
* The data container of the rt dimension, including application, service, and method levels,
* if there is no actual call to the existing call method,
* the key will not be displayed when exporting (to be optimized)
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class RtStatComposite extends AbstractMetricsExport {
private boolean serviceLevel;
private final AtomicBoolean samplesChanged = new AtomicBoolean(true);
public RtStatComposite(ApplicationModel applicationModel) {
super(applicationModel);
this.serviceLevel = MethodMetric.isServiceLevel(getApplicationModel());
}
private final Map<String, List<LongContainer<? extends Number>>> rtStats = new ConcurrentHashMap<>();
public void init(MetricsPlaceValue... placeValues) {
if (placeValues == null) {
return;
}
for (MetricsPlaceValue placeValue : placeValues) {
List<LongContainer<? extends Number>> containers = initStats(placeValue);
for (LongContainer<? extends Number> container : containers) {
rtStats.computeIfAbsent(container.getMetricsKeyWrapper().getType(), k -> new ArrayList<>())
.add(container);
}
}
samplesChanged.set(true);
}
private List<LongContainer<? extends Number>> initStats(MetricsPlaceValue placeValue) {
List<LongContainer<? extends Number>> singleRtStats = new ArrayList<>();
singleRtStats.add(new AtomicLongContainer(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, placeValue)));
singleRtStats.add(new LongAccumulatorContainer(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, placeValue),
new LongAccumulator(Long::min, Long.MAX_VALUE)));
singleRtStats.add(new LongAccumulatorContainer(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, placeValue),
new LongAccumulator(Long::max, Long.MIN_VALUE)));
singleRtStats.add(new AtomicLongContainer(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue),
(responseTime, longAccumulator) -> longAccumulator.addAndGet(responseTime)));
// AvgContainer is a special counter that stores the number of times but outputs function of sum/times
AtomicLongContainer avgContainer = new AtomicLongContainer(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, placeValue), (k, v) -> v.incrementAndGet());
avgContainer.setValueSupplier(applicationName -> {
LongContainer<? extends Number> totalContainer = rtStats.values().stream()
.flatMap(List::stream)
.filter(longContainer -> longContainer.isKeyWrapper(MetricsKey.METRIC_RT_SUM, placeValue.getType()))
.findFirst()
.get();
AtomicLong totalRtTimes = avgContainer.get(applicationName);
AtomicLong totalRtSum = (AtomicLong) totalContainer.get(applicationName);
return totalRtSum.get() / totalRtTimes.get();
});
singleRtStats.add(avgContainer);
return singleRtStats;
}
public void calcServiceKeyRt(String registryOpType, Long responseTime, Metric key) {
for (LongContainer container : rtStats.get(registryOpType)) {
Number current = (Number) container.get(key);
if (current == null) {
container.putIfAbsent(key, container.getInitFunc().apply(key));
samplesChanged.set(true);
current = (Number) container.get(key);
}
container.getConsumerFunc().accept(responseTime, current);
}
}
public void calcServiceKeyRt(Invocation invocation, String registryOpType, Long responseTime) {
List<Action> actions;
if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceKey() != null) {
Map<String, Object> attributeMap =
invocation.getServiceModel().getServiceMetadata().getAttributeMap();
Map<String, List<Action>> cache = (Map<String, List<Action>>) attributeMap.get("ServiceKeyRt");
if (cache == null) {
attributeMap.putIfAbsent("ServiceKeyRt", new ConcurrentHashMap<>(32));
cache = (Map<String, List<Action>>) attributeMap.get("ServiceKeyRt");
}
actions = cache.get(registryOpType);
if (actions == null) {
actions = calServiceRtActions(invocation, registryOpType);
cache.putIfAbsent(registryOpType, actions);
samplesChanged.set(true);
actions = cache.get(registryOpType);
}
} else {
actions = calServiceRtActions(invocation, registryOpType);
}
for (Action action : actions) {
action.run(responseTime);
}
}
private List<Action> calServiceRtActions(Invocation invocation, String registryOpType) {
List<Action> actions;
actions = new LinkedList<>();
ServiceKeyMetric key = new ServiceKeyMetric(getApplicationModel(), invocation.getTargetServiceUniqueName());
for (LongContainer container : rtStats.get(registryOpType)) {
Number current = (Number) container.get(key);
if (current == null) {
container.putIfAbsent(key, container.getInitFunc().apply(key));
samplesChanged.set(true);
current = (Number) container.get(key);
}
actions.add(new Action(container.getConsumerFunc(), current));
}
return actions;
}
public void calcMethodKeyRt(Invocation invocation, String registryOpType, Long responseTime) {
List<Action> actions;
if (invocation.getServiceModel() != null && invocation.getServiceModel().getServiceMetadata() != null) {
Map<String, Object> attributeMap =
invocation.getServiceModel().getServiceMetadata().getAttributeMap();
Map<String, List<Action>> cache = (Map<String, List<Action>>) attributeMap.get("MethodKeyRt");
if (cache == null) {
attributeMap.putIfAbsent("MethodKeyRt", new ConcurrentHashMap<>(32));
cache = (Map<String, List<Action>>) attributeMap.get("MethodKeyRt");
}
actions = cache.get(registryOpType);
if (actions == null) {
actions = calMethodRtActions(invocation, registryOpType);
cache.putIfAbsent(registryOpType, actions);
samplesChanged.set(true);
actions = cache.get(registryOpType);
}
} else {
actions = calMethodRtActions(invocation, registryOpType);
}
for (Action action : actions) {
action.run(responseTime);
}
}
private List<Action> calMethodRtActions(Invocation invocation, String registryOpType) {
List<Action> actions;
actions = new LinkedList<>();
for (LongContainer container : rtStats.get(registryOpType)) {
MethodMetric key = new MethodMetric(getApplicationModel(), invocation, serviceLevel);
Number current = (Number) container.get(key);
if (current == null) {
container.putIfAbsent(key, container.getInitFunc().apply(key));
samplesChanged.set(true);
current = (Number) container.get(key);
}
actions.add(new Action(container.getConsumerFunc(), current));
}
return actions;
}
public List<MetricSample> export(MetricsCategory category) {
List<MetricSample> list = new ArrayList<>();
for (List<LongContainer<? extends Number>> containers : rtStats.values()) {
for (LongContainer<? extends Number> container : containers) {
MetricsKeyWrapper metricsKeyWrapper = container.getMetricsKeyWrapper();
for (Metric key : container.keySet()) {
// Use keySet to obtain the original key instance reference of ConcurrentHashMap to avoid early
// recycling of the micrometer
list.add(new GaugeMetricSample<>(
metricsKeyWrapper.targetKey(),
metricsKeyWrapper.targetDesc(),
key.getTags(),
category,
key,
value -> container.getValueSupplier().apply(value)));
}
}
}
return list;
}
public List<LongContainer<? extends Number>> getRtStats() {
return rtStats.values().stream().flatMap(List::stream).collect(Collectors.toList());
}
private static class Action {
private final BiConsumer<Long, Number> consumerFunc;
private final Number initValue;
public Action(BiConsumer<Long, Number> consumerFunc, Number initValue) {
this.consumerFunc = consumerFunc;
this.initValue = initValue;
}
public void run(Long responseTime) {
consumerFunc.accept(responseTime, initValue);
}
}
@Override
public boolean calSamplesChanged() {
// CAS to get and reset the flag in an atomic operation
return samplesChanged.compareAndSet(true, false);
}
}
| 8,129 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/BaseStatComposite.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.data;
import org.apache.dubbo.metrics.collector.MetricsCollector;
import org.apache.dubbo.metrics.model.ApplicationMetric;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.ServiceKeyMetric;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.metrics.report.MetricsExport;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* As a data aggregator, use internal data containers calculates and classifies
* the registry data collected by {@link MetricsCollector MetricsCollector}, and
* provides an {@link MetricsExport MetricsExport} interface for exporting standard output formats.
*/
public abstract class BaseStatComposite implements MetricsExport {
private ApplicationStatComposite applicationStatComposite;
private ServiceStatComposite serviceStatComposite;
private MethodStatComposite methodStatComposite;
private RtStatComposite rtStatComposite;
public BaseStatComposite(ApplicationModel applicationModel) {
init(new ApplicationStatComposite(applicationModel));
init(new ServiceStatComposite(applicationModel));
init(new MethodStatComposite(applicationModel));
init(new RtStatComposite(applicationModel));
}
protected void init(ApplicationStatComposite applicationStatComposite) {
this.applicationStatComposite = applicationStatComposite;
}
protected void init(ServiceStatComposite serviceStatComposite) {
this.serviceStatComposite = serviceStatComposite;
}
protected void init(MethodStatComposite methodStatComposite) {
this.methodStatComposite = methodStatComposite;
}
protected void init(RtStatComposite rtStatComposite) {
this.rtStatComposite = rtStatComposite;
}
public void calcApplicationRt(String registryOpType, Long responseTime) {
rtStatComposite.calcServiceKeyRt(
registryOpType, responseTime, new ApplicationMetric(rtStatComposite.getApplicationModel()));
}
public void calcServiceKeyRt(String serviceKey, String registryOpType, Long responseTime) {
rtStatComposite.calcServiceKeyRt(
registryOpType, responseTime, new ServiceKeyMetric(rtStatComposite.getApplicationModel(), serviceKey));
}
public void calcServiceKeyRt(Invocation invocation, String registryOpType, Long responseTime) {
rtStatComposite.calcServiceKeyRt(invocation, registryOpType, responseTime);
}
public void calcMethodKeyRt(Invocation invocation, String registryOpType, Long responseTime) {
rtStatComposite.calcMethodKeyRt(invocation, registryOpType, responseTime);
}
public void setServiceKey(MetricsKeyWrapper metricsKey, String serviceKey, int num) {
serviceStatComposite.setServiceKey(metricsKey, serviceKey, num);
}
public void setServiceKey(MetricsKeyWrapper metricsKey, String serviceKey, int num, Map<String, String> extra) {
serviceStatComposite.setExtraServiceKey(metricsKey, serviceKey, num, extra);
}
public void incrementApp(MetricsKey metricsKey, int size) {
applicationStatComposite.incrementSize(metricsKey, size);
}
public void incrementServiceKey(MetricsKeyWrapper metricsKeyWrapper, String attServiceKey, int size) {
serviceStatComposite.incrementServiceKey(metricsKeyWrapper, attServiceKey, size);
}
public void incrementServiceKey(
MetricsKeyWrapper metricsKeyWrapper, String attServiceKey, Map<String, String> extra, int size) {
serviceStatComposite.incrementExtraServiceKey(metricsKeyWrapper, attServiceKey, extra, size);
}
public void incrementMethodKey(MetricsKeyWrapper metricsKeyWrapper, MethodMetric methodMetric, int size) {
methodStatComposite.incrementMethodKey(metricsKeyWrapper, methodMetric, size);
}
public void initMethodKey(MetricsKeyWrapper metricsKeyWrapper, Invocation invocation) {
methodStatComposite.initMethodKey(metricsKeyWrapper, invocation);
}
@Override
public List<MetricSample> export(MetricsCategory category) {
List<MetricSample> list = new ArrayList<>();
list.addAll(applicationStatComposite.export(category));
list.addAll(rtStatComposite.export(category));
list.addAll(serviceStatComposite.export(category));
list.addAll(methodStatComposite.export(category));
return list;
}
public ApplicationStatComposite getApplicationStatComposite() {
return applicationStatComposite;
}
public RtStatComposite getRtStatComposite() {
return rtStatComposite;
}
@Override
public boolean calSamplesChanged() {
// Should ensure that all the composite's samplesChanged have been compareAndSet, and cannot flip the `or` logic
boolean changed = applicationStatComposite.calSamplesChanged();
changed = rtStatComposite.calSamplesChanged() || changed;
changed = serviceStatComposite.calSamplesChanged() || changed;
changed = methodStatComposite.calSamplesChanged() || changed;
return changed;
}
}
| 8,130 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ServiceStatComposite.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.data;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.ServiceKeyMetric;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.metrics.report.AbstractMetricsExport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Service-level data container, for the initialized MetricsKey,
* different from the null value of the Map type (the key is not displayed when there is no data),
* the key is displayed and the initial data is 0 value of the AtomicLong type
*/
public class ServiceStatComposite extends AbstractMetricsExport {
private final AtomicBoolean samplesChanged = new AtomicBoolean(true);
public ServiceStatComposite(ApplicationModel applicationModel) {
super(applicationModel);
}
private final Map<MetricsKeyWrapper, Map<ServiceKeyMetric, AtomicLong>> serviceWrapperNumStats =
new ConcurrentHashMap<>();
public void initWrapper(List<MetricsKeyWrapper> metricsKeyWrappers) {
if (CollectionUtils.isEmpty(metricsKeyWrappers)) {
return;
}
metricsKeyWrappers.forEach(appKey -> {
serviceWrapperNumStats.put(appKey, new ConcurrentHashMap<>());
});
samplesChanged.set(true);
}
public void incrementServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int size) {
incrementExtraServiceKey(wrapper, serviceKey, null, size);
}
public void incrementExtraServiceKey(
MetricsKeyWrapper wrapper, String serviceKey, Map<String, String> extra, int size) {
if (!serviceWrapperNumStats.containsKey(wrapper)) {
return;
}
ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(getApplicationModel(), serviceKey);
if (extra != null) {
serviceKeyMetric.setExtraInfo(extra);
}
Map<ServiceKeyMetric, AtomicLong> map = serviceWrapperNumStats.get(wrapper);
AtomicLong metrics = map.get(serviceKeyMetric);
if (metrics == null) {
metrics = map.computeIfAbsent(serviceKeyMetric, k -> new AtomicLong(0L));
samplesChanged.set(true);
}
metrics.getAndAdd(size);
// MetricsSupport.fillZero(serviceWrapperNumStats);
}
public void setServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int num) {
setExtraServiceKey(wrapper, serviceKey, num, null);
}
public void setExtraServiceKey(MetricsKeyWrapper wrapper, String serviceKey, int num, Map<String, String> extra) {
if (!serviceWrapperNumStats.containsKey(wrapper)) {
return;
}
ServiceKeyMetric serviceKeyMetric = new ServiceKeyMetric(getApplicationModel(), serviceKey);
if (extra != null) {
serviceKeyMetric.setExtraInfo(extra);
}
Map<ServiceKeyMetric, AtomicLong> stats = serviceWrapperNumStats.get(wrapper);
AtomicLong metrics = stats.get(serviceKeyMetric);
if (metrics == null) {
metrics = stats.computeIfAbsent(serviceKeyMetric, k -> new AtomicLong(0L));
samplesChanged.set(true);
}
metrics.set(num);
}
@Override
public List<MetricSample> export(MetricsCategory category) {
List<MetricSample> list = new ArrayList<>();
for (MetricsKeyWrapper wrapper : serviceWrapperNumStats.keySet()) {
Map<ServiceKeyMetric, AtomicLong> stringAtomicLongMap = serviceWrapperNumStats.get(wrapper);
for (ServiceKeyMetric serviceKeyMetric : stringAtomicLongMap.keySet()) {
list.add(new GaugeMetricSample<>(
wrapper, serviceKeyMetric.getTags(), category, stringAtomicLongMap, value -> value.get(
serviceKeyMetric)
.get()));
}
}
return list;
}
@Override
public boolean calSamplesChanged() {
// CAS to get and reset the flag in an atomic operation
return samplesChanged.compareAndSet(true, false);
}
}
| 8,131 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/ApplicationStatComposite.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.data;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.MetricsSupport;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.metrics.report.AbstractMetricsExport;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Application-level data container, for the initialized MetricsKey,
* different from the null value of the Map type (the key is not displayed when there is no data),
* the key is displayed and the initial data is 0 value of the AtomicLong type
*/
public class ApplicationStatComposite extends AbstractMetricsExport {
public ApplicationStatComposite(ApplicationModel applicationModel) {
super(applicationModel);
}
private final Map<MetricsKey, AtomicLong> applicationNumStats = new ConcurrentHashMap<>();
private final AtomicBoolean samplesChanged = new AtomicBoolean(true);
public void init(List<MetricsKey> appKeys) {
if (CollectionUtils.isEmpty(appKeys)) {
return;
}
appKeys.forEach(appKey -> {
applicationNumStats.put(appKey, new AtomicLong(0L));
});
samplesChanged.set(true);
}
public void incrementSize(MetricsKey metricsKey, int size) {
if (!applicationNumStats.containsKey(metricsKey)) {
return;
}
applicationNumStats.get(metricsKey).getAndAdd(size);
}
public List<MetricSample> export(MetricsCategory category) {
List<MetricSample> list = new ArrayList<>();
for (MetricsKey type : applicationNumStats.keySet()) {
list.add(convertToSample(type, category, applicationNumStats.get(type)));
}
return list;
}
@SuppressWarnings({"rawtypes"})
private GaugeMetricSample convertToSample(MetricsKey type, MetricsCategory category, AtomicLong targetNumber) {
return new GaugeMetricSample<>(
type, MetricsSupport.applicationTags(getApplicationModel()), category, targetNumber, AtomicLong::get);
}
public Map<MetricsKey, AtomicLong> getApplicationNumStats() {
return applicationNumStats;
}
@Override
public boolean calSamplesChanged() {
// CAS to get and reset the flag in an atomic operation
return samplesChanged.compareAndSet(true, false);
}
}
| 8,132 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/data/MethodStatComposite.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.data;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metrics.exception.MetricsNeverHappenException;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.metrics.model.MetricsCategory;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.sample.CounterMetricSample;
import org.apache.dubbo.metrics.model.sample.GaugeMetricSample;
import org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.metrics.report.AbstractMetricsExport;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Method-level data container,
* if there is no actual call to the existing call method,
* the key will not be displayed when exporting (to be optimized)
*/
public class MethodStatComposite extends AbstractMetricsExport {
private boolean serviceLevel;
private final AtomicBoolean samplesChanged = new AtomicBoolean(true);
public MethodStatComposite(ApplicationModel applicationModel) {
super(applicationModel);
this.serviceLevel = MethodMetric.isServiceLevel(getApplicationModel());
}
private final Map<MetricsKeyWrapper, Map<MethodMetric, AtomicLong>> methodNumStats = new ConcurrentHashMap<>();
public void initWrapper(List<MetricsKeyWrapper> metricsKeyWrappers) {
if (CollectionUtils.isEmpty(metricsKeyWrappers)) {
return;
}
metricsKeyWrappers.forEach(appKey -> {
methodNumStats.put(appKey, new ConcurrentHashMap<>());
});
samplesChanged.set(true);
}
public void initMethodKey(MetricsKeyWrapper wrapper, Invocation invocation) {
if (!methodNumStats.containsKey(wrapper)) {
return;
}
methodNumStats
.get(wrapper)
.computeIfAbsent(
new MethodMetric(getApplicationModel(), invocation, serviceLevel), k -> new AtomicLong(0L));
samplesChanged.set(true);
}
public void incrementMethodKey(MetricsKeyWrapper wrapper, MethodMetric methodMetric, int size) {
if (!methodNumStats.containsKey(wrapper)) {
return;
}
AtomicLong stat = methodNumStats.get(wrapper).get(methodMetric);
if (stat == null) {
methodNumStats.get(wrapper).computeIfAbsent(methodMetric, (k) -> new AtomicLong(0L));
samplesChanged.set(true);
stat = methodNumStats.get(wrapper).get(methodMetric);
}
stat.getAndAdd(size);
// MetricsSupport.fillZero(methodNumStats);
}
public List<MetricSample> export(MetricsCategory category) {
List<MetricSample> list = new ArrayList<>();
for (MetricsKeyWrapper wrapper : methodNumStats.keySet()) {
Map<MethodMetric, AtomicLong> stringAtomicLongMap = methodNumStats.get(wrapper);
for (MethodMetric methodMetric : stringAtomicLongMap.keySet()) {
if (wrapper.getSampleType() == MetricSample.Type.COUNTER) {
list.add(new CounterMetricSample<>(
wrapper, methodMetric.getTags(), category, stringAtomicLongMap.get(methodMetric)));
} else if (wrapper.getSampleType() == MetricSample.Type.GAUGE) {
list.add(new GaugeMetricSample<>(
wrapper, methodMetric.getTags(), category, stringAtomicLongMap, value -> value.get(
methodMetric)
.get()));
} else {
throw new MetricsNeverHappenException("Unsupported metricSample type: " + wrapper.getSampleType());
}
}
}
return list;
}
@Override
public boolean calSamplesChanged() {
// CAS to get and reset the flag in an atomic operation
return samplesChanged.compareAndSet(true, false);
}
}
| 8,133 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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);
}
}
| 8,134 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsDispatcher.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.common.extension.ExtensionLoader;
import org.apache.dubbo.metrics.collector.MetricsCollector;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
/**
* Global spi event publisher
*/
public class MetricsDispatcher extends SimpleMetricsEventMulticaster {
@SuppressWarnings({"rawtypes"})
public MetricsDispatcher(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
ExtensionLoader<MetricsCollector> extensionLoader = applicationModel.getExtensionLoader(MetricsCollector.class);
if (extensionLoader != null) {
List<MetricsCollector> customizeCollectors = extensionLoader.getActivateExtensions();
for (MetricsCollector customizeCollector : customizeCollectors) {
beanFactory.registerBean(customizeCollector);
}
customizeCollectors.forEach(this::addListener);
}
}
}
| 8,135 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/MetricsInitEvent.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.MetricsConstants;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.metrics.model.MetricsSupport;
import org.apache.dubbo.metrics.model.key.MetricsLevel;
import org.apache.dubbo.metrics.model.key.TypeWrapper;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.metrics.MetricsConstants.ATTACHMENT_KEY_SERVICE;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METRIC_REQUESTS;
public class MetricsInitEvent extends TimeCounterEvent {
private static final TypeWrapper METRIC_EVENT = new TypeWrapper(MetricsLevel.SERVICE, METRIC_REQUESTS);
public MetricsInitEvent(ApplicationModel source, TypeWrapper typeWrapper) {
super(source, typeWrapper);
}
public static MetricsInitEvent toMetricsInitEvent(
ApplicationModel applicationModel, Invocation invocation, boolean serviceLevel) {
MethodMetric methodMetric = new MethodMetric(applicationModel, invocation, serviceLevel);
MetricsInitEvent initEvent = new MetricsInitEvent(applicationModel, METRIC_EVENT);
initEvent.putAttachment(MetricsConstants.INVOCATION, invocation);
initEvent.putAttachment(MetricsConstants.METHOD_METRICS, methodMetric);
initEvent.putAttachment(ATTACHMENT_KEY_SERVICE, MetricsSupport.getInterfaceName(invocation));
initEvent.putAttachment(MetricsConstants.INVOCATION_SIDE, MetricsSupport.getSide(invocation));
return initEvent;
}
}
| 8,136 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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.getSource() == null) {
return;
}
MetricsDispatcher dispatcher = event.getMetricsDispatcher();
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) {
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) {
MetricsDispatcher dispatcher = validate(event);
if (dispatcher == null) return;
tryInvoke(() -> dispatcher.publishEvent(event));
}
public static void after(MetricsEvent event, Object result) {
MetricsDispatcher dispatcher = validate(event);
if (dispatcher == null) return;
tryInvoke(() -> {
event.customAfterPost(result);
dispatcher.publishFinishEvent((TimeCounterEvent) event);
});
}
public static void error(MetricsEvent event) {
MetricsDispatcher dispatcher = validate(event);
if (dispatcher == null) return;
tryInvoke(() -> dispatcher.publishErrorEvent((TimeCounterEvent) event));
}
private static MetricsDispatcher validate(MetricsEvent event) {
MetricsDispatcher dispatcher = event.getMetricsDispatcher();
if (dispatcher == null) {
return null;
}
if (!(event instanceof TimeCounterEvent)) {
return null;
}
return dispatcher;
}
}
| 8,137 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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.MethodMetric;
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. {@link MethodMetric})
*/
protected final transient ApplicationModel source;
private boolean available = true;
private final TypeWrapper typeWrapper;
private final String appName;
private final MetricsDispatcher metricsDispatcher;
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, MetricsDispatcher metricsDispatcher, 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 (metricsDispatcher == null) {
if (this.source.isDestroyed()) {
this.metricsDispatcher = null;
} else {
ScopeBeanFactory beanFactory = this.source.getBeanFactory();
if (beanFactory.isDestroyed()) {
this.metricsDispatcher = null;
} else {
MetricsDispatcher dispatcher = beanFactory.getBean(MetricsDispatcher.class);
this.metricsDispatcher = dispatcher;
}
}
} else {
this.metricsDispatcher = metricsDispatcher;
}
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 MetricsDispatcher getMetricsDispatcher() {
return metricsDispatcher;
}
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;
}
}
}
| 8,138 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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, MetricsDispatcher metricsDispatcher, TypeWrapper typeWrapper) {
super(source, appName, metricsDispatcher, typeWrapper);
this.timePair = TimePair.start();
}
public TimePair getTimePair() {
return timePair;
}
}
| 8,139 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/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);
}
| 8,140 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/event/SimpleMetricsEventMulticaster.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.utils.StringUtils;
import org.apache.dubbo.metrics.listener.MetricsLifeListener;
import org.apache.dubbo.metrics.listener.MetricsListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
/**
* A simple event publisher that defines lifecycle events and supports rt events
*/
public class SimpleMetricsEventMulticaster implements MetricsEventMulticaster {
private final List<MetricsListener<?>> listeners = Collections.synchronizedList(new ArrayList<>());
@Override
public void addListener(MetricsListener<?> listener) {
listeners.add(listener);
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void publishEvent(MetricsEvent event) {
if (validateIfApplicationConfigExist(event)) return;
for (MetricsListener listener : listeners) {
if (listener.isSupport(event)) {
listener.onEvent(event);
}
}
}
private boolean validateIfApplicationConfigExist(MetricsEvent event) {
if (event.getSource() != null) {
// Check if exist application config
return StringUtils.isEmpty(event.appName());
}
return false;
}
@Override
@SuppressWarnings({"unchecked"})
public void publishFinishEvent(TimeCounterEvent event) {
publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventFinish(event));
}
@Override
@SuppressWarnings({"unchecked"})
public void publishErrorEvent(TimeCounterEvent event) {
publishTimeEvent(event, metricsLifeListener -> metricsLifeListener.onEventError(event));
}
@SuppressWarnings({"rawtypes"})
private void publishTimeEvent(MetricsEvent event, Consumer<MetricsLifeListener> consumer) {
if (validateIfApplicationConfigExist(event)) return;
if (event instanceof TimeCounterEvent) {
((TimeCounterEvent) event).getTimePair().end();
}
for (MetricsListener listener : listeners) {
if (listener instanceof MetricsLifeListener && listener.isSupport(event)) {
consumer.accept(((MetricsLifeListener) listener));
}
}
}
}
| 8,141 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import java.util.Objects;
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((map, key, value) -> Objects.requireNonNull(map).setAttachment(key, value));
this.invoker = invoker;
this.invocation = invocation;
setCarrier(invocation);
}
public Invoker<?> getInvoker() {
return invoker;
}
public Invocation getInvocation() {
return invocation;
}
}
| 8,142 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
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.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_METHOD;
import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.RPC_SERVICE;
import static org.apache.dubbo.metrics.observation.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
}
}
| 8,143 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
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((stringObjectMap, s) -> String.valueOf(stringObjectMap.getAttachment(s)));
this.invoker = invoker;
this.invocation = invocation;
setCarrier(invocation);
}
public Invoker<?> getInvoker() {
return invoker;
}
public Invocation getInvocation() {
return invocation;
}
}
| 8,144 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
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());
}
}
| 8,145 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
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;
}
}
| 8,146 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
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;
}
}
| 8,147 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
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 java.util.List;
import io.micrometer.common.KeyValues;
import static org.apache.dubbo.metrics.observation.DubboObservationDocumentation.LowCardinalityKeyNames.NET_PEER_NAME;
import static org.apache.dubbo.metrics.observation.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());
}
}
| 8,148 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/observation/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.metrics.observation;
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";
}
}
}
}
| 8,149 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/AccessKeyAuthenticatorTest.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.auth;
import org.apache.dubbo.auth.exception.RpcAuthenticationException;
import org.apache.dubbo.auth.model.AccessKeyPair;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AccessKeyAuthenticatorTest {
@Test
void testSignForRequest() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk");
Invocation invocation = new RpcInvocation();
AccessKeyAuthenticator helper = mock(AccessKeyAuthenticator.class);
doCallRealMethod().when(helper).sign(invocation, url);
when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString()))
.thenReturn("dubbo");
AccessKeyPair accessKeyPair = mock(AccessKeyPair.class);
when(accessKeyPair.getSecretKey()).thenReturn("sk");
when(helper.getAccessKeyPair(invocation, url)).thenReturn(accessKeyPair);
helper.sign(invocation, url);
assertEquals(String.valueOf(invocation.getAttachment(CommonConstants.CONSUMER)), url.getApplication());
assertNotNull(invocation.getAttachments().get(Constants.REQUEST_SIGNATURE_KEY));
assertEquals(invocation.getAttachments().get(Constants.REQUEST_SIGNATURE_KEY), "dubbo");
}
@Test
void testAuthenticateRequest() throws RpcAuthenticationException {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk");
Invocation invocation = new RpcInvocation();
invocation.setAttachment(Constants.ACCESS_KEY_ID_KEY, "ak");
invocation.setAttachment(Constants.REQUEST_SIGNATURE_KEY, "dubbo");
invocation.setAttachment(Constants.REQUEST_TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));
invocation.setAttachment(CommonConstants.CONSUMER, "test");
AccessKeyAuthenticator helper = mock(AccessKeyAuthenticator.class);
doCallRealMethod().when(helper).authenticate(invocation, url);
when(helper.getSignature(eq(url), eq(invocation), eq("sk"), anyString()))
.thenReturn("dubbo");
AccessKeyPair accessKeyPair = mock(AccessKeyPair.class);
when(accessKeyPair.getSecretKey()).thenReturn("sk");
when(helper.getAccessKeyPair(invocation, url)).thenReturn(accessKeyPair);
assertDoesNotThrow(() -> helper.authenticate(invocation, url));
}
@Test
void testAuthenticateRequestNoSignature() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk");
Invocation invocation = new RpcInvocation();
AccessKeyAuthenticator helper = new AccessKeyAuthenticator(ApplicationModel.defaultModel());
assertThrows(RpcAuthenticationException.class, () -> helper.authenticate(invocation, url));
}
@Test
void testGetAccessKeyPairFailed() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181").addParameter(Constants.ACCESS_KEY_ID_KEY, "ak");
AccessKeyAuthenticator helper = new AccessKeyAuthenticator(ApplicationModel.defaultModel());
Invocation invocation = mock(Invocation.class);
assertThrows(RuntimeException.class, () -> helper.getAccessKeyPair(invocation, url));
}
@Test
void testGetSignatureNoParameter() {
URL url = mock(URL.class);
Invocation invocation = mock(Invocation.class);
String secretKey = "123456";
AccessKeyAuthenticator helper = new AccessKeyAuthenticator(ApplicationModel.defaultModel());
String signature = helper.getSignature(url, invocation, secretKey, String.valueOf(System.currentTimeMillis()));
assertNotNull(signature);
}
@Test
void testGetSignatureWithParameter() {
URL url = mock(URL.class);
when(url.getParameter(Constants.PARAMETER_SIGNATURE_ENABLE_KEY, false)).thenReturn(true);
Invocation invocation = mock(Invocation.class);
String secretKey = "123456";
Object[] params = {"dubbo", new ArrayList()};
when(invocation.getArguments()).thenReturn(params);
AccessKeyAuthenticator helper = new AccessKeyAuthenticator(ApplicationModel.defaultModel());
String signature = helper.getSignature(url, invocation, secretKey, String.valueOf(System.currentTimeMillis()));
assertNotNull(signature);
Object[] fakeParams = {"dubbo1", new ArrayList<>()};
when(invocation.getArguments()).thenReturn(fakeParams);
String signature1 = helper.getSignature(url, invocation, secretKey, String.valueOf(System.currentTimeMillis()));
assertNotEquals(signature, signature1);
}
}
| 8,150 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/DefaultAccessKeyStorageTest.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.auth;
import org.apache.dubbo.auth.model.AccessKeyPair;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
class DefaultAccessKeyStorageTest {
@Test
void testGetAccessKey() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk");
DefaultAccessKeyStorage defaultAccessKeyStorage = new DefaultAccessKeyStorage();
AccessKeyPair accessKey = defaultAccessKeyStorage.getAccessKey(url, mock(Invocation.class));
assertNotNull(accessKey);
assertEquals(accessKey.getAccessKey(), "ak");
assertEquals(accessKey.getSecretKey(), "sk");
}
}
| 8,151 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/utils/SignatureUtilsTest.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.auth.utils;
import java.util.ArrayList;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SignatureUtilsTest {
@Test
void testEncryptWithObject() {
Object[] objects = new Object[] {new ArrayList<>(), "temp"};
String encryptWithObject = SignatureUtils.sign(objects, "TestMethod#hello", "TOKEN");
Assertions.assertEquals(encryptWithObject, "t6c7PasKguovqSrVRcTQU4wTZt/ybl0jBCUMgAt/zQw=");
}
@Test
void testEncryptWithNoParameters() {
String encryptWithNoParams = SignatureUtils.sign(null, "TestMethod#hello", "TOKEN");
Assertions.assertEquals(encryptWithNoParams, "2DGkTcyXg4plU24rY8MZkEJwOMRW3o+wUP3HssRc3EE=");
}
}
| 8,152 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ProviderAuthFilterTest.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.auth.filter;
import org.apache.dubbo.auth.Constants;
import org.apache.dubbo.auth.exception.RpcAuthenticationException;
import org.apache.dubbo.auth.utils.SignatureUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ProviderAuthFilterTest {
@Test
void testAuthDisabled() {
URL url = mock(URL.class);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invoker.getUrl()).thenReturn(url);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
providerAuthFilter.invoke(invoker, invocation);
verify(url, never()).getParameter(eq(Constants.AUTHENTICATOR), eq(Constants.DEFAULT_AUTHENTICATOR));
}
@Test
void testAuthEnabled() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invoker.getUrl()).thenReturn(url);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
providerAuthFilter.invoke(invoker, invocation);
verify(invocation, atLeastOnce()).getAttachment(anyString());
}
@Test
void testAuthFailed() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(null);
when(invoker.getUrl()).thenReturn(url);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
Result result = providerAuthFilter.invoke(invoker, invocation);
assertTrue(result.hasException());
}
@Test
void testAuthFailedWhenNoSignature() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(null);
when(invoker.getUrl()).thenReturn(url);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
Result result = providerAuthFilter.invoke(invoker, invocation);
assertTrue(result.hasException());
}
@Test
void testAuthFailedWhenNoAccessKeyPair() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(CommonConstants.APPLICATION_KEY, "test-provider")
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invocation.getObjectAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn("dubbo");
when(invocation.getObjectAttachment(Constants.AK_KEY)).thenReturn("ak");
when(invocation.getObjectAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer");
when(invocation.getObjectAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(System.currentTimeMillis());
when(invoker.getUrl()).thenReturn(url);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
Result result = providerAuthFilter.invoke(invoker, invocation);
assertTrue(result.hasException());
assertTrue(result.getException() instanceof RpcAuthenticationException);
}
@Test
void testAuthFailedWhenParameterError() {
String service = "org.apache.dubbo.DemoService";
String method = "test";
Object[] originalParams = new Object[] {"dubbo1", "dubbo2"};
long currentTimeMillis = System.currentTimeMillis();
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.setServiceInterface(service)
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk")
.addParameter(CommonConstants.APPLICATION_KEY, "test-provider")
.addParameter(Constants.PARAMETER_SIGNATURE_ENABLE_KEY, true)
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invocation.getObjectAttachment(Constants.AK_KEY)).thenReturn("ak");
when(invocation.getObjectAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer");
when(invocation.getObjectAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(currentTimeMillis);
when(invocation.getMethodName()).thenReturn(method);
Object[] fakeParams = new Object[] {"dubbo1", "dubbo3"};
when(invocation.getArguments()).thenReturn(fakeParams);
when(invoker.getUrl()).thenReturn(url);
String requestString = String.format(
Constants.SIGNATURE_STRING_FORMAT,
url.getColonSeparatedKey(),
invocation.getMethodName(),
"sk",
currentTimeMillis);
String sign = SignatureUtils.sign(originalParams, requestString, "sk");
when(invocation.getObjectAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
Result result = providerAuthFilter.invoke(invoker, invocation);
assertTrue(result.hasException());
assertTrue(result.getException() instanceof RpcAuthenticationException);
}
@Test
void testAuthSuccessfully() {
String service = "org.apache.dubbo.DemoService";
String method = "test";
long currentTimeMillis = System.currentTimeMillis();
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.setServiceInterface(service)
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk")
.addParameter(CommonConstants.APPLICATION_KEY, "test-provider")
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(RpcInvocation.class);
when(invocation.getAttachment(Constants.AK_KEY)).thenReturn("ak");
when(invocation.getAttachment(CommonConstants.CONSUMER)).thenReturn("test-consumer");
when(invocation.getAttachment(Constants.REQUEST_TIMESTAMP_KEY)).thenReturn(String.valueOf(currentTimeMillis));
when(invocation.getMethodName()).thenReturn(method);
when(invoker.getUrl()).thenReturn(url);
String requestString = String.format(
Constants.SIGNATURE_STRING_FORMAT,
url.getColonSeparatedKey(),
invocation.getMethodName(),
"sk",
currentTimeMillis);
String sign = SignatureUtils.sign(requestString, "sk");
when(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY)).thenReturn(sign);
ProviderAuthFilter providerAuthFilter = new ProviderAuthFilter(ApplicationModel.defaultModel());
Result result = providerAuthFilter.invoke(invoker, invocation);
assertNull(result);
}
}
| 8,153 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/test/java/org/apache/dubbo/auth/filter/ConsumerSignFilterTest.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.auth.filter;
import org.apache.dubbo.auth.Constants;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ConsumerSignFilterTest {
@Test
void testAuthDisabled() {
URL url = mock(URL.class);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(Invocation.class);
when(invoker.getUrl()).thenReturn(url);
ConsumerSignFilter consumerSignFilter = new ConsumerSignFilter(ApplicationModel.defaultModel());
consumerSignFilter.invoke(invoker, invocation);
verify(invocation, never()).setAttachment(eq(Constants.REQUEST_SIGNATURE_KEY), anyString());
}
@Test
void testAuthEnabled() {
URL url = URL.valueOf("dubbo://10.10.10.10:2181")
.addParameter(Constants.ACCESS_KEY_ID_KEY, "ak")
.addParameter(Constants.SECRET_ACCESS_KEY_KEY, "sk")
.addParameter(CommonConstants.APPLICATION_KEY, "test")
.addParameter(Constants.SERVICE_AUTH, true);
Invoker invoker = mock(Invoker.class);
Invocation invocation = mock(Invocation.class);
when(invoker.getUrl()).thenReturn(url);
ConsumerSignFilter consumerSignFilter = new ConsumerSignFilter(ApplicationModel.defaultModel());
consumerSignFilter.invoke(invoker, invocation);
verify(invocation, times(1)).setAttachment(eq(Constants.REQUEST_SIGNATURE_KEY), anyString());
}
}
| 8,154 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/AccessKeyAuthenticator.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.auth;
import org.apache.dubbo.auth.exception.AccessKeyNotFoundException;
import org.apache.dubbo.auth.exception.RpcAuthenticationException;
import org.apache.dubbo.auth.model.AccessKeyPair;
import org.apache.dubbo.auth.spi.AccessKeyStorage;
import org.apache.dubbo.auth.spi.Authenticator;
import org.apache.dubbo.auth.utils.SignatureUtils;
import org.apache.dubbo.common.URL;
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.model.ApplicationModel;
import org.apache.dubbo.rpc.support.RpcUtils;
public class AccessKeyAuthenticator implements Authenticator {
private final ApplicationModel applicationModel;
public AccessKeyAuthenticator(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public void sign(Invocation invocation, URL url) {
String currentTime = String.valueOf(System.currentTimeMillis());
AccessKeyPair accessKeyPair = getAccessKeyPair(invocation, url);
invocation.setAttachment(
Constants.REQUEST_SIGNATURE_KEY,
getSignature(url, invocation, accessKeyPair.getSecretKey(), currentTime));
invocation.setAttachment(Constants.REQUEST_TIMESTAMP_KEY, currentTime);
invocation.setAttachment(Constants.AK_KEY, accessKeyPair.getAccessKey());
invocation.setAttachment(CommonConstants.CONSUMER, url.getApplication());
}
@Override
public void authenticate(Invocation invocation, URL url) throws RpcAuthenticationException {
String accessKeyId = String.valueOf(invocation.getAttachment(Constants.AK_KEY));
String requestTimestamp = String.valueOf(invocation.getAttachment(Constants.REQUEST_TIMESTAMP_KEY));
String originSignature = String.valueOf(invocation.getAttachment(Constants.REQUEST_SIGNATURE_KEY));
String consumer = String.valueOf(invocation.getAttachment(CommonConstants.CONSUMER));
if (StringUtils.isAnyEmpty(accessKeyId, consumer, requestTimestamp, originSignature)) {
throw new RpcAuthenticationException("Failed to authenticate, maybe consumer side did not enable the auth");
}
AccessKeyPair accessKeyPair;
try {
accessKeyPair = getAccessKeyPair(invocation, url);
} catch (Exception e) {
throw new RpcAuthenticationException("Failed to authenticate , can't load the accessKeyPair", e);
}
String computeSignature = getSignature(url, invocation, accessKeyPair.getSecretKey(), requestTimestamp);
boolean success = computeSignature.equals(originSignature);
if (!success) {
throw new RpcAuthenticationException("Failed to authenticate, signature is not correct");
}
}
AccessKeyPair getAccessKeyPair(Invocation invocation, URL url) {
AccessKeyStorage accessKeyStorage = applicationModel
.getExtensionLoader(AccessKeyStorage.class)
.getExtension(url.getParameter(Constants.ACCESS_KEY_STORAGE_KEY, Constants.DEFAULT_ACCESS_KEY_STORAGE));
AccessKeyPair accessKeyPair;
try {
accessKeyPair = accessKeyStorage.getAccessKey(url, invocation);
if (accessKeyPair == null
|| StringUtils.isAnyEmpty(accessKeyPair.getAccessKey(), accessKeyPair.getSecretKey())) {
throw new AccessKeyNotFoundException("AccessKeyId or secretAccessKey not found");
}
} catch (Exception e) {
throw new RuntimeException("Can't load the AccessKeyPair from accessKeyStorage", e);
}
return accessKeyPair;
}
String getSignature(URL url, Invocation invocation, String secretKey, String time) {
String requestString = String.format(
Constants.SIGNATURE_STRING_FORMAT,
url.getColonSeparatedKey(),
RpcUtils.getMethodName(invocation),
secretKey,
time);
boolean parameterEncrypt = url.getParameter(Constants.PARAMETER_SIGNATURE_ENABLE_KEY, false);
if (parameterEncrypt) {
return SignatureUtils.sign(invocation.getArguments(), requestString, secretKey);
}
return SignatureUtils.sign(requestString, secretKey);
}
}
| 8,155 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/DefaultAccessKeyStorage.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.auth;
import org.apache.dubbo.auth.model.AccessKeyPair;
import org.apache.dubbo.auth.spi.AccessKeyStorage;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
/**
* The default implementation of {@link AccessKeyStorage}
*/
public class DefaultAccessKeyStorage implements AccessKeyStorage {
@Override
public AccessKeyPair getAccessKey(URL url, Invocation invocation) {
AccessKeyPair accessKeyPair = new AccessKeyPair();
String accessKeyId = url.getParameter(Constants.ACCESS_KEY_ID_KEY);
String secretAccessKey = url.getParameter(Constants.SECRET_ACCESS_KEY_KEY);
accessKeyPair.setAccessKey(accessKeyId);
accessKeyPair.setSecretKey(secretAccessKey);
return accessKeyPair;
}
}
| 8,156 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/Constants.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.auth;
public interface Constants {
String SERVICE_AUTH = "auth";
String AUTHENTICATOR = "authenticator";
String DEFAULT_AUTHENTICATOR = "accesskey";
String DEFAULT_ACCESS_KEY_STORAGE = "urlstorage";
String ACCESS_KEY_STORAGE_KEY = "accessKey.storage";
// the key starting with "." shouldn't be output
String ACCESS_KEY_ID_KEY = ".accessKeyId";
// the key starting with "." shouldn't be output
String SECRET_ACCESS_KEY_KEY = ".secretAccessKey";
String REQUEST_TIMESTAMP_KEY = "timestamp";
String REQUEST_SIGNATURE_KEY = "signature";
String AK_KEY = "ak";
String SIGNATURE_STRING_FORMAT = "%s#%s#%s#%s";
String PARAMETER_SIGNATURE_ENABLE_KEY = "param.sign";
}
| 8,157 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/utils/SignatureUtils.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.auth.utils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class SignatureUtils {
private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
public static String sign(String metadata, String key) throws RuntimeException {
return sign(metadata.getBytes(StandardCharsets.UTF_8), key);
}
public static String sign(Object[] parameters, String metadata, String key) throws RuntimeException {
if (parameters == null) {
return sign(metadata, key);
}
for (int i = 0; i < parameters.length; i++) {
if (!(parameters[i] instanceof Serializable)) {
throw new IllegalArgumentException("The parameter [" + i + "] to be signed was not serializable.");
}
}
Object[] includeMetadata = new Object[parameters.length + 1];
System.arraycopy(parameters, 0, includeMetadata, 0, parameters.length);
includeMetadata[parameters.length] = metadata;
byte[] includeMetadataBytes;
try {
includeMetadataBytes = toByteArray(includeMetadata);
} catch (IOException e) {
throw new RuntimeException("Failed to generate HMAC: " + e.getMessage());
}
return sign(includeMetadataBytes, key);
}
private static String sign(byte[] data, String key) throws RuntimeException {
Mac mac;
try {
mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to generate HMAC: no such algorithm exception " + HMAC_SHA256_ALGORITHM);
}
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA256_ALGORITHM);
try {
mac.init(signingKey);
} catch (InvalidKeyException e) {
throw new RuntimeException("Failed to generate HMAC: invalid key exception");
}
byte[] rawHmac;
try {
// compute the hmac on input data bytes
rawHmac = mac.doFinal(data);
} catch (IllegalStateException e) {
throw new RuntimeException("Failed to generate HMAC: " + e.getMessage());
}
// base64-encode the hmac
return Base64.getEncoder().encodeToString(rawHmac);
}
private static byte[] toByteArray(Object[] parameters) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(parameters);
out.flush();
return bos.toByteArray();
}
}
}
| 8,158 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/AccessKeyStorage.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.auth.spi;
import org.apache.dubbo.auth.model.AccessKeyPair;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
/**
* This SPI Extension support us to store our {@link AccessKeyPair} or load {@link AccessKeyPair} from other
* storage, such as filesystem.
*/
@SPI
public interface AccessKeyStorage {
/**
* get AccessKeyPair of this request
*
* @param url
* @param invocation
* @return
*/
AccessKeyPair getAccessKey(URL url, Invocation invocation);
}
| 8,159 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/spi/Authenticator.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.auth.spi;
import org.apache.dubbo.auth.exception.RpcAuthenticationException;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
@SPI("accessKey")
public interface Authenticator {
/**
* give a sign to request
*
* @param invocation
* @param url
*/
void sign(Invocation invocation, URL url);
/**
* verify the signature of the request is valid or not
* @param invocation
* @param url
* @throws RpcAuthenticationException when failed to authenticate current invocation
*/
void authenticate(Invocation invocation, URL url) throws RpcAuthenticationException;
}
| 8,160 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/model/AccessKeyPair.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.auth.model;
/**
* The model of AK/SK pair
*/
public class AccessKeyPair {
private String accessKey;
private String secretKey;
private String consumerSide;
private String providerSide;
private String creator;
private String options;
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getConsumerSide() {
return consumerSide;
}
public void setConsumerSide(String consumerSide) {
this.consumerSide = consumerSide;
}
public String getProviderSide() {
return providerSide;
}
public void setProviderSide(String providerSide) {
this.providerSide = providerSide;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getOptions() {
return options;
}
public void setOptions(String options) {
this.options = options;
}
@Override
public String toString() {
return "AccessKeyPair{" + "accessKey='"
+ accessKey + '\'' + ", secretKey='"
+ secretKey + '\'' + ", consumerSide='"
+ consumerSide + '\'' + ", providerSide='"
+ providerSide + '\'' + ", creator='"
+ creator + '\'' + ", options='"
+ options + '\'' + '}';
}
}
| 8,161 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ProviderAuthFilter.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.auth.filter;
import org.apache.dubbo.auth.Constants;
import org.apache.dubbo.auth.spi.Authenticator;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.AsyncRpcResult;
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;
@Activate(group = CommonConstants.PROVIDER, value = Constants.SERVICE_AUTH, order = -10000)
public class ProviderAuthFilter implements Filter {
private final ApplicationModel applicationModel;
public ProviderAuthFilter(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
boolean shouldAuth = url.getParameter(Constants.SERVICE_AUTH, false);
if (shouldAuth) {
Authenticator authenticator = applicationModel
.getExtensionLoader(Authenticator.class)
.getExtension(url.getParameter(Constants.AUTHENTICATOR, Constants.DEFAULT_AUTHENTICATOR));
try {
authenticator.authenticate(invocation, url);
} catch (Exception e) {
return AsyncRpcResult.newDefaultAsyncResult(e, invocation);
}
}
return invoker.invoke(invocation);
}
}
| 8,162 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/filter/ConsumerSignFilter.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.auth.filter;
import org.apache.dubbo.auth.Constants;
import org.apache.dubbo.auth.spi.Authenticator;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
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;
/**
* The ConsumerSignFilter
*
* @see org.apache.dubbo.rpc.Filter
*/
@Activate(group = CommonConstants.CONSUMER, value = Constants.SERVICE_AUTH, order = -10000)
public class ConsumerSignFilter implements Filter {
private final ApplicationModel applicationModel;
public ConsumerSignFilter(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
URL url = invoker.getUrl();
boolean shouldAuth = url.getParameter(Constants.SERVICE_AUTH, false);
if (shouldAuth) {
Authenticator authenticator = applicationModel
.getExtensionLoader(Authenticator.class)
.getExtension(url.getParameter(Constants.AUTHENTICATOR, Constants.DEFAULT_AUTHENTICATOR));
authenticator.sign(invocation, url);
}
return invoker.invoke(invocation);
}
}
| 8,163 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/RpcAuthenticationException.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.auth.exception;
public class RpcAuthenticationException extends Exception {
public RpcAuthenticationException() {}
public RpcAuthenticationException(String message) {
super(message);
}
public RpcAuthenticationException(String message, Throwable cause) {
super(message, cause);
}
}
| 8,164 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth
|
Create_ds/dubbo/dubbo-plugin/dubbo-auth/src/main/java/org/apache/dubbo/auth/exception/AccessKeyNotFoundException.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.auth.exception;
import org.apache.dubbo.auth.model.AccessKeyPair;
/**
* Signals that an attempt to get the {@link AccessKeyPair} has failed.
*/
public class AccessKeyNotFoundException extends Exception {
private static final long serialVersionUID = 7106108446396804404L;
public AccessKeyNotFoundException() {}
public AccessKeyNotFoundException(String message) {
super(message);
}
}
| 8,165 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/BaseCommand.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.qos.api;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface BaseCommand {
default boolean logResult() {
return true;
}
String execute(CommandContext commandContext, String[] args);
}
| 8,166 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/PermissionLevel.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.qos.api;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Arrays;
public enum PermissionLevel {
/**
* the lowest permission level (default), can access with
* anonymousAccessPermissionLevel=PUBLIC / anonymousAccessPermissionLevel=1 or higher
*/
PUBLIC(1),
/**
* the middle permission level, default permission for each cmd
*/
PROTECTED(2),
/**
* the highest permission level, suppose only the localhost can access this command
*/
PRIVATE(3),
/**
* It is the reserved anonymous permission level, can not access any command
*/
NONE(Integer.MIN_VALUE),
;
private final int level;
PermissionLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
// find the permission level by the level value, if not found, return default PUBLIC level
public static PermissionLevel from(String permissionLevel) {
if (StringUtils.isNumber(permissionLevel)) {
return Arrays.stream(values())
.filter(p -> String.valueOf(p.getLevel()).equals(permissionLevel.trim()))
.findFirst()
.orElse(PUBLIC);
}
return Arrays.stream(values())
.filter(p -> p.name()
.equalsIgnoreCase(String.valueOf(permissionLevel).trim()))
.findFirst()
.orElse(PUBLIC);
}
}
| 8,167 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/CommandContext.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.qos.api;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import io.netty.channel.Channel;
public class CommandContext {
private String commandName;
private String[] args;
private Channel remote;
private boolean isHttp;
private Object originRequest;
private int httpCode = 200;
private QosConfiguration qosConfiguration;
public CommandContext(String commandName) {
this.commandName = commandName;
}
public CommandContext(String commandName, String[] args, boolean isHttp) {
this.commandName = commandName;
this.args = args;
this.isHttp = isHttp;
}
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
public String[] getArgs() {
return args;
}
public void setArgs(String[] args) {
this.args = args;
}
public Channel getRemote() {
return remote;
}
public void setRemote(Channel remote) {
this.remote = remote;
}
public boolean isHttp() {
return isHttp;
}
public void setHttp(boolean http) {
isHttp = http;
}
public Object getOriginRequest() {
return originRequest;
}
public void setOriginRequest(Object originRequest) {
this.originRequest = originRequest;
}
public int getHttpCode() {
return httpCode;
}
public void setHttpCode(int httpCode) {
this.httpCode = httpCode;
}
public void setQosConfiguration(QosConfiguration qosConfiguration) {
this.qosConfiguration = qosConfiguration;
}
public QosConfiguration getQosConfiguration() {
return qosConfiguration;
}
public boolean isAllowAnonymousAccess() {
return this.qosConfiguration.isAllowAnonymousAccess();
}
@Override
public String toString() {
return "CommandContext{" + "commandName='"
+ commandName + '\'' + ", args="
+ Arrays.toString(args) + ", remote="
+ Optional.ofNullable(remote)
.map(Channel::remoteAddress)
.map(Objects::toString)
.orElse("unknown") + ", local="
+ Optional.ofNullable(remote)
.map(Channel::localAddress)
.map(Objects::toString)
.orElse("unknown") + ", isHttp="
+ isHttp + ", httpCode="
+ httpCode + ", qosConfiguration="
+ qosConfiguration + '}';
}
}
| 8,168 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/Cmd.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.qos.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Command
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Cmd {
/**
* Command name
*
* @return command name
*/
String name();
/**
* Command description
*
* @return command description
*/
String summary();
/**
* Command example
*
* @return command example
*/
String[] example() default {};
/**
* Command order in help
*
* @return command order in help
*/
int sort() default 0;
/**
* Command required access permission level
*
* @return command permission level
*/
PermissionLevel requiredPermissionLevel() default PermissionLevel.PROTECTED;
}
| 8,169 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos-api/src/main/java/org/apache/dubbo/qos/api/QosConfiguration.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.qos.api;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.function.Predicate;
public class QosConfiguration {
private String welcome;
private boolean acceptForeignIp;
// the whitelist of foreign IP when acceptForeignIp = false, the delimiter is colon(,)
// support specific ip and an ip range from CIDR specification
private String acceptForeignIpWhitelist;
private Predicate<String> acceptForeignIpWhitelistPredicate;
// this permission level for anonymous access, it will ignore the acceptForeignIp and acceptForeignIpWhitelist
// configurations
// Access permission depends on the config anonymousAccessPermissionLevel and the cmd required permission level
// the default value is Cmd.PermissionLevel.PUBLIC, can only access PUBLIC level cmd
private PermissionLevel anonymousAccessPermissionLevel = PermissionLevel.PUBLIC;
// the allow commands for anonymous access, the delimiter is colon(,)
private String anonymousAllowCommands;
private QosConfiguration() {}
public QosConfiguration(Builder builder) {
this.welcome = builder.getWelcome();
this.acceptForeignIp = builder.isAcceptForeignIp();
this.acceptForeignIpWhitelist = builder.getAcceptForeignIpWhitelist();
this.anonymousAccessPermissionLevel = builder.getAnonymousAccessPermissionLevel();
this.anonymousAllowCommands = builder.getAnonymousAllowCommands();
buildPredicate();
}
private void buildPredicate() {
if (StringUtils.isNotEmpty(acceptForeignIpWhitelist)) {
this.acceptForeignIpWhitelistPredicate = Arrays.stream(acceptForeignIpWhitelist.split(","))
.map(String::trim)
.filter(StringUtils::isNotEmpty)
.map(foreignIpPattern -> (Predicate<String>) foreignIp -> {
try {
// hard code port to -1
return NetUtils.matchIpExpression(foreignIpPattern, foreignIp, -1);
} catch (UnknownHostException ignore) {
// ignore illegal CIDR specification
}
return false;
})
.reduce(Predicate::or)
.orElse(s -> false);
} else {
this.acceptForeignIpWhitelistPredicate = foreignIp -> false;
}
}
public boolean isAllowAnonymousAccess() {
return PermissionLevel.NONE != anonymousAccessPermissionLevel;
}
public String getWelcome() {
return welcome;
}
public PermissionLevel getAnonymousAccessPermissionLevel() {
return anonymousAccessPermissionLevel;
}
public String getAcceptForeignIpWhitelist() {
return acceptForeignIpWhitelist;
}
public Predicate<String> getAcceptForeignIpWhitelistPredicate() {
return acceptForeignIpWhitelistPredicate;
}
public boolean isAcceptForeignIp() {
return acceptForeignIp;
}
public String getAnonymousAllowCommands() {
return anonymousAllowCommands;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String welcome;
private boolean acceptForeignIp;
private String acceptForeignIpWhitelist;
private PermissionLevel anonymousAccessPermissionLevel = PermissionLevel.PUBLIC;
private String anonymousAllowCommands;
private Builder() {}
public Builder welcome(String welcome) {
this.welcome = welcome;
return this;
}
public Builder acceptForeignIp(boolean acceptForeignIp) {
this.acceptForeignIp = acceptForeignIp;
return this;
}
public Builder acceptForeignIpWhitelist(String acceptForeignIpWhitelist) {
this.acceptForeignIpWhitelist = acceptForeignIpWhitelist;
return this;
}
public Builder anonymousAccessPermissionLevel(String anonymousAccessPermissionLevel) {
this.anonymousAccessPermissionLevel = PermissionLevel.from(anonymousAccessPermissionLevel);
return this;
}
public Builder anonymousAllowCommands(String anonymousAllowCommands) {
this.anonymousAllowCommands = anonymousAllowCommands;
return this;
}
public QosConfiguration build() {
return new QosConfiguration(this);
}
public String getWelcome() {
return welcome;
}
public boolean isAcceptForeignIp() {
return acceptForeignIp;
}
public String getAcceptForeignIpWhitelist() {
return acceptForeignIpWhitelist;
}
public PermissionLevel getAnonymousAccessPermissionLevel() {
return anonymousAccessPermissionLevel;
}
public String getAnonymousAllowCommands() {
return anonymousAllowCommands;
}
}
}
| 8,170 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/test/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecTest.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.spring.security.jackson;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
public class ObjectMapperCodecTest {
private ObjectMapperCodec mapper = new ObjectMapperCodec();
@Test
public void testOAuth2AuthorizedClientCodec() {
ClientRegistration clientRegistration = clientRegistration().build();
OAuth2AuthorizedClient authorizedClient =
new OAuth2AuthorizedClient(clientRegistration, "principal-name", noScopes());
String content = mapper.serialize(authorizedClient);
OAuth2AuthorizedClient deserialize = mapper.deserialize(content.getBytes(), OAuth2AuthorizedClient.class);
Assertions.assertNotNull(deserialize);
}
public static ClientRegistration.Builder clientRegistration() {
// @formatter:off
return ClientRegistration.withRegistrationId("registration-id")
.redirectUri("http://localhost/uua/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://example.com/login/oauth/authorize")
.tokenUri("https://example.com/login/oauth/access_token")
.jwkSetUri("https://example.com/oauth2/jwk")
.issuerUri("https://example.com")
.userInfoUri("https://api.example.com/user")
.userNameAttributeName("id")
.clientName("Client Name")
.clientId("client-id")
.clientSecret("client-secret");
// @formatter:on
}
public static OAuth2AccessToken noScopes() {
return new OAuth2AccessToken(
OAuth2AccessToken.TokenType.BEARER,
"no-scopes",
Instant.now(),
Instant.now().plus(Duration.ofDays(1)));
}
}
| 8,171 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/utils/SecurityNames.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.spring.security.utils;
public final class SecurityNames {
public static final String SECURITY_AUTHENTICATION_CONTEXT_KEY = "security_authentication_context";
public static final String SECURITY_CONTEXT_HOLDER_CLASS_NAME =
"org.springframework.security.core.context.SecurityContextHolder";
public static final String CORE_JACKSON_2_MODULE_CLASS_NAME =
"org.springframework.security.jackson2.CoreJackson2Module";
public static final String OBJECT_MAPPER_CLASS_NAME = "com.fasterxml.jackson.databind.ObjectMapper";
public static final String JAVA_TIME_MODULE_CLASS_NAME = "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule";
public static final String SIMPLE_MODULE_CLASS_NAME = "com.fasterxml.jackson.databind.module.SimpleModule";
private SecurityNames() {}
}
| 8,172 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/model/SecurityScopeModelInitializer.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.spring.security.model;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
import org.apache.dubbo.spring.security.jackson.ObjectMapperCodec;
import org.apache.dubbo.spring.security.jackson.ObjectMapperCodecCustomer;
import java.util.Set;
import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME;
@Activate(
onClass = {
SECURITY_CONTEXT_HOLDER_CLASS_NAME,
CORE_JACKSON_2_MODULE_CLASS_NAME,
OBJECT_MAPPER_CLASS_NAME,
JAVA_TIME_MODULE_CLASS_NAME,
SIMPLE_MODULE_CLASS_NAME
})
public class SecurityScopeModelInitializer implements ScopeModelInitializer {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
try {
ObjectMapperCodec objectMapperCodec = new ObjectMapperCodec();
Set<ObjectMapperCodecCustomer> objectMapperCodecCustomerList = frameworkModel
.getExtensionLoader(ObjectMapperCodecCustomer.class)
.getSupportedExtensionInstances();
for (ObjectMapperCodecCustomer objectMapperCodecCustomer : objectMapperCodecCustomerList) {
objectMapperCodecCustomer.customize(objectMapperCodec);
}
beanFactory.registerBean(objectMapperCodec);
} catch (Throwable t) {
logger.info(
"Failed to initialize ObjectMapperCodecCustomer and spring security related features are disabled.",
t);
}
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| 8,173 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationResolverFilter.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.spring.security.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.StringUtils;
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.spring.security.jackson.ObjectMapperCodec;
import org.apache.dubbo.spring.security.utils.SecurityNames;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME;
@Activate(
group = CommonConstants.PROVIDER,
order = -10000,
onClass = {
SECURITY_CONTEXT_HOLDER_CLASS_NAME,
CORE_JACKSON_2_MODULE_CLASS_NAME,
OBJECT_MAPPER_CLASS_NAME,
JAVA_TIME_MODULE_CLASS_NAME,
SIMPLE_MODULE_CLASS_NAME
})
public class ContextHolderAuthenticationResolverFilter implements Filter {
private final ObjectMapperCodec mapper;
public ContextHolderAuthenticationResolverFilter(ApplicationModel applicationModel) {
this.mapper = applicationModel.getBeanFactory().getBean(ObjectMapperCodec.class);
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (this.mapper != null) {
getSecurityContext(invocation);
}
return invoker.invoke(invocation);
}
private void getSecurityContext(Invocation invocation) {
String authenticationJSON = invocation.getAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY);
if (StringUtils.isBlank(authenticationJSON)) {
return;
}
Authentication authentication = mapper.deserialize(authenticationJSON, Authentication.class);
if (authentication == null) {
return;
}
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
| 8,174 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/AuthenticationExceptionTranslatorFilter.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.spring.security.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
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.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import static org.apache.dubbo.rpc.RpcException.AUTHORIZATION_EXCEPTION;
import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME;
@Activate(
group = CommonConstants.PROVIDER,
order = Integer.MAX_VALUE,
onClass = {
SECURITY_CONTEXT_HOLDER_CLASS_NAME,
CORE_JACKSON_2_MODULE_CLASS_NAME,
OBJECT_MAPPER_CLASS_NAME,
JAVA_TIME_MODULE_CLASS_NAME,
SIMPLE_MODULE_CLASS_NAME
})
public class AuthenticationExceptionTranslatorFilter implements Filter, Filter.Listener {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) {
if (this.isTranslate(result)) {
RpcException rpcException = new RpcException(result.getException().getMessage());
rpcException.setCode(AUTHORIZATION_EXCEPTION);
result.setException(rpcException);
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {}
private boolean isTranslate(Result result) {
Throwable exception = result.getException();
return result.hasException()
&& (exception instanceof AuthenticationException || exception instanceof AccessDeniedException);
}
}
| 8,175 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderAuthenticationPrepareFilter.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.spring.security.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
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.spring.security.jackson.ObjectMapperCodec;
import org.apache.dubbo.spring.security.utils.SecurityNames;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.apache.dubbo.spring.security.utils.SecurityNames.CORE_JACKSON_2_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.JAVA_TIME_MODULE_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.OBJECT_MAPPER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_CONTEXT_HOLDER_CLASS_NAME;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SIMPLE_MODULE_CLASS_NAME;
@Activate(
group = CommonConstants.CONSUMER,
order = -10000,
onClass = {
SECURITY_CONTEXT_HOLDER_CLASS_NAME,
CORE_JACKSON_2_MODULE_CLASS_NAME,
OBJECT_MAPPER_CLASS_NAME,
JAVA_TIME_MODULE_CLASS_NAME,
SIMPLE_MODULE_CLASS_NAME
})
public class ContextHolderAuthenticationPrepareFilter implements ClusterFilter {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final ObjectMapperCodec mapper;
public ContextHolderAuthenticationPrepareFilter(ApplicationModel applicationModel) {
this.mapper = applicationModel.getBeanFactory().getBean(ObjectMapperCodec.class);
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (this.mapper != null) {
setSecurityContext(invocation);
}
return invoker.invoke(invocation);
}
private void setSecurityContext(Invocation invocation) {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
String content = mapper.serialize(authentication);
if (StringUtils.isBlank(content)) {
return;
}
invocation.setObjectAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY, content);
}
}
| 8,176 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/filter/ContextHolderParametersSelectedTransferFilter.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.spring.security.filter;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.spring.security.utils.SecurityNames;
import java.util.Map;
import java.util.Objects;
import static org.apache.dubbo.spring.security.utils.SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY;
@Activate(group = CommonConstants.CONSUMER, order = -1)
public class ContextHolderParametersSelectedTransferFilter implements ClusterFilter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) {
this.setSecurityContextIfExists(invocation);
return invoker.invoke(invocation);
}
private void setSecurityContextIfExists(Invocation invocation) {
Map<String, Object> resultMap = RpcContext.getServerAttachment().getObjectAttachments();
Object authentication = resultMap.get(SECURITY_AUTHENTICATION_CONTEXT_KEY);
if (Objects.isNull(authentication)) {
return;
}
invocation.setObjectAttachment(SecurityNames.SECURITY_AUTHENTICATION_CONTEXT_KEY, authentication);
}
}
| 8,177 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodec.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.spring.security.jackson;
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.ClassUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.security.jackson2.CoreJackson2Module;
public class ObjectMapperCodec {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ObjectMapperCodec.class);
private final ObjectMapper mapper = new ObjectMapper();
public ObjectMapperCodec() {
registerDefaultModule();
}
public <T> T deserialize(byte[] bytes, Class<T> clazz) {
try {
if (bytes == null || bytes.length == 0) {
return null;
}
return mapper.readValue(bytes, clazz);
} catch (Exception exception) {
logger.warn(
LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION,
"objectMapper! deserialize error, you can try to customize the ObjectMapperCodecCustomer.",
"",
"",
exception);
}
return null;
}
public <T> T deserialize(String content, Class<T> clazz) {
if (StringUtils.isBlank(content)) {
return null;
}
return deserialize(content.getBytes(), clazz);
}
public String serialize(Object object) {
try {
if (object == null) {
return null;
}
return mapper.writeValueAsString(object);
} catch (Exception ex) {
logger.warn(
LoggerCodeConstants.COMMON_JSON_CONVERT_EXCEPTION,
"objectMapper! serialize error, you can try to customize the ObjectMapperCodecCustomer.",
"",
"",
ex);
}
return null;
}
public ObjectMapperCodec addModule(SimpleModule simpleModule) {
mapper.registerModule(simpleModule);
return this;
}
public ObjectMapperCodec configureMapper(Consumer<ObjectMapper> objectMapperConfigure) {
objectMapperConfigure.accept(this.mapper);
return this;
}
private void registerDefaultModule() {
mapper.registerModule(new CoreJackson2Module());
mapper.registerModule(new JavaTimeModule());
List<String> jacksonModuleClassNameList = new ArrayList<>();
jacksonModuleClassNameList.add(
"org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module");
jacksonModuleClassNameList.add(
"org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module");
jacksonModuleClassNameList.add("org.springframework.security.web.server.jackson2.WebServerJackson2Module");
jacksonModuleClassNameList.add("com.fasterxml.jackson.module.paramnames.ParameterNamesModule");
jacksonModuleClassNameList.add("org.springframework.security.web.jackson2.WebServletJackson2Module");
jacksonModuleClassNameList.add("org.springframework.security.web.jackson2.WebJackson2Module");
jacksonModuleClassNameList.add("org.springframework.boot.jackson.JsonMixinModule");
jacksonModuleClassNameList.add("org.springframework.security.ldap.jackson2.LdapJackson2Module");
loadModuleIfPresent(jacksonModuleClassNameList);
}
private void loadModuleIfPresent(List<String> jacksonModuleClassNameList) {
for (String moduleClassName : jacksonModuleClassNameList) {
try {
SimpleModule objectMapperModule =
(SimpleModule) ClassUtils.forName(moduleClassName, ObjectMapperCodec.class.getClassLoader())
.getDeclaredConstructor()
.newInstance();
mapper.registerModule(objectMapperModule);
} catch (Throwable ex) {
}
}
}
}
| 8,178 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-spring-security/src/main/java/org/apache/dubbo/spring/security/jackson/ObjectMapperCodecCustomer.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.spring.security.jackson;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ObjectMapperCodecCustomer {
void customize(ObjectMapperCodec objectMapperCodec);
}
| 8,179 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertManagerTest.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.security.cert;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateResponse;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateServiceGrpc;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.IOException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import io.grpc.Channel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.awaitility.Awaitility.await;
import static org.mockito.Answers.CALLS_REAL_METHODS;
class DubboCertManagerTest {
@Test
void test1() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel) {
@Override
protected void connect0(CertConfig certConfig) {
Assertions.assertEquals("127.0.0.1:30060", certConfig.getRemoteAddress());
Assertions.assertEquals("caCertPath", certConfig.getCaCertPath());
}
@Override
protected CertPair generateCert() {
return null;
}
@Override
protected void scheduleRefresh() {}
};
certManager.connect(new CertConfig("127.0.0.1:30060", null, "caCertPath", "oidc"));
Assertions.assertEquals(new CertConfig("127.0.0.1:30060", null, "caCertPath", "oidc"), certManager.certConfig);
certManager.connect(new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123"));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "Kubernetes", "caCertPath", "oidc123"), certManager.certConfig);
certManager.connect(new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
CertConfig certConfig = new CertConfig("127.0.0.1:30060", "vm", "caCertPath", "oidc");
Assertions.assertThrows(IllegalArgumentException.class, () -> certManager.connect(certConfig));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
certManager.connect(null);
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
certManager.connect(new CertConfig(null, null, null, null));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
certManager.channel = Mockito.mock(Channel.class);
certManager.connect(new CertConfig("error", null, "error", "error"));
Assertions.assertEquals(
new CertConfig("127.0.0.1:30060", "kubernetes", "caCertPath", "oidc345"), certManager.certConfig);
frameworkModel.destroy();
}
@Test
void testRefresh() {
FrameworkModel frameworkModel = new FrameworkModel();
AtomicInteger count = new AtomicInteger(0);
DubboCertManager certManager = new DubboCertManager(frameworkModel) {
@Override
protected CertPair generateCert() {
count.incrementAndGet();
return null;
}
};
certManager.certConfig = new CertConfig(null, null, null, null, 10);
certManager.scheduleRefresh();
Assertions.assertNotNull(certManager.refreshFuture);
await().until(() -> count.get() > 1);
certManager.refreshFuture.cancel(false);
frameworkModel.destroy();
}
@Test
void testConnect1() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, null, null);
certManager.connect0(certConfig);
Assertions.assertNotNull(certManager.channel);
Assertions.assertEquals("127.0.0.1:30062", certManager.channel.authority());
frameworkModel.destroy();
}
@Test
void testConnect2() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
String file =
this.getClass().getClassLoader().getResource("certs/ca.crt").getFile();
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, file, null);
certManager.connect0(certConfig);
Assertions.assertNotNull(certManager.channel);
Assertions.assertEquals("127.0.0.1:30062", certManager.channel.authority());
frameworkModel.destroy();
}
@Test
void testConnect3() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
String file = this.getClass()
.getClassLoader()
.getResource("certs/broken-ca.crt")
.getFile();
CertConfig certConfig = new CertConfig("127.0.0.1:30062", null, file, null);
Assertions.assertThrows(RuntimeException.class, () -> certManager.connect0(certConfig));
frameworkModel.destroy();
}
@Test
void testDisconnect() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
ScheduledFuture scheduledFuture = Mockito.mock(ScheduledFuture.class);
certManager.refreshFuture = scheduledFuture;
certManager.disConnect();
Assertions.assertNull(certManager.refreshFuture);
Mockito.verify(scheduledFuture, Mockito.times(1)).cancel(true);
certManager.channel = Mockito.mock(Channel.class);
certManager.disConnect();
Assertions.assertNull(certManager.channel);
frameworkModel.destroy();
}
@Test
void testConnected() {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
Assertions.assertFalse(certManager.isConnected());
certManager.certConfig = Mockito.mock(CertConfig.class);
Assertions.assertFalse(certManager.isConnected());
certManager.channel = Mockito.mock(Channel.class);
Assertions.assertFalse(certManager.isConnected());
certManager.certPair = Mockito.mock(CertPair.class);
Assertions.assertTrue(certManager.isConnected());
frameworkModel.destroy();
}
@Test
void testGenerateCert() {
FrameworkModel frameworkModel = new FrameworkModel();
AtomicBoolean exception = new AtomicBoolean(false);
AtomicReference<CertPair> certPairReference = new AtomicReference<>();
DubboCertManager certManager = new DubboCertManager(frameworkModel) {
@Override
protected CertPair refreshCert() throws IOException {
if (exception.get()) {
throw new IOException("test");
}
return certPairReference.get();
}
};
CertPair certPair = new CertPair("", "", "", Long.MAX_VALUE);
certPairReference.set(certPair);
Assertions.assertEquals(certPair, certManager.generateCert());
certManager.certPair = new CertPair("", "", "", Long.MAX_VALUE - 10000);
Assertions.assertEquals(new CertPair("", "", "", Long.MAX_VALUE - 10000), certManager.generateCert());
certManager.certPair = new CertPair("", "", "", 0);
Assertions.assertEquals(certPair, certManager.generateCert());
certManager.certPair = new CertPair("", "", "", 0);
certPairReference.set(null);
Assertions.assertEquals(new CertPair("", "", "", 0), certManager.generateCert());
exception.set(true);
Assertions.assertEquals(new CertPair("", "", "", 0), certManager.generateCert());
frameworkModel.destroy();
}
@Test
void testSignWithRsa() {
DubboCertManager.KeyPair keyPair = DubboCertManager.signWithRsa();
Assertions.assertNotNull(keyPair);
Assertions.assertNotNull(keyPair.getPrivateKey());
Assertions.assertNotNull(keyPair.getPublicKey());
Assertions.assertNotNull(keyPair.getSigner());
}
@Test
void testSignWithEcdsa() {
DubboCertManager.KeyPair keyPair = DubboCertManager.signWithEcdsa();
Assertions.assertNotNull(keyPair);
Assertions.assertNotNull(keyPair.getPrivateKey());
Assertions.assertNotNull(keyPair.getPublicKey());
Assertions.assertNotNull(keyPair.getSigner());
}
@Test
void testRefreshCert() throws IOException {
try (MockedStatic<DubboCertManager> managerMock =
Mockito.mockStatic(DubboCertManager.class, CALLS_REAL_METHODS)) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertManager certManager = new DubboCertManager(frameworkModel);
managerMock.when(DubboCertManager::signWithEcdsa).thenReturn(null);
managerMock.when(DubboCertManager::signWithRsa).thenReturn(null);
Assertions.assertNull(certManager.refreshCert());
managerMock.when(DubboCertManager::signWithEcdsa).thenCallRealMethod();
certManager.channel = Mockito.mock(Channel.class);
try (MockedStatic<DubboCertificateServiceGrpc> mockGrpc =
Mockito.mockStatic(DubboCertificateServiceGrpc.class, CALLS_REAL_METHODS)) {
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub =
Mockito.mock(DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub.class);
mockGrpc.when(() -> DubboCertificateServiceGrpc.newBlockingStub(Mockito.any(Channel.class)))
.thenReturn(stub);
Mockito.when(stub.createCertificate(Mockito.any()))
.thenReturn(DubboCertificateResponse.newBuilder()
.setSuccess(false)
.build());
certManager.certConfig = new CertConfig(null, null, null, null);
Assertions.assertNull(certManager.refreshCert());
String file = this.getClass()
.getClassLoader()
.getResource("certs/token")
.getFile();
Mockito.when(stub.withInterceptors(Mockito.any())).thenReturn(stub);
certManager.certConfig = new CertConfig(null, null, null, file);
Assertions.assertNull(certManager.refreshCert());
Mockito.verify(stub, Mockito.times(1)).withInterceptors(Mockito.any());
Mockito.when(stub.createCertificate(Mockito.any()))
.thenReturn(DubboCertificateResponse.newBuilder()
.setSuccess(true)
.setCertPem("certPem")
.addTrustCerts("trustCerts")
.setExpireTime(123456)
.build());
CertPair certPair = certManager.refreshCert();
Assertions.assertNotNull(certPair);
Assertions.assertEquals("certPem", certPair.getCertificate());
Assertions.assertEquals("trustCerts", certPair.getTrustCerts());
Assertions.assertEquals(123456, certPair.getExpireTime());
Mockito.when(stub.createCertificate(Mockito.any())).thenReturn(null);
Assertions.assertNull(certManager.refreshCert());
}
frameworkModel.destroy();
}
}
}
| 8,180 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/DubboCertProviderTest.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.security.cert;
import org.apache.dubbo.common.ssl.AuthPolicy;
import org.apache.dubbo.common.ssl.Cert;
import org.apache.dubbo.common.ssl.ProviderCert;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
class DubboCertProviderTest {
@Test
void testEnable() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Mockito.when(reference.get().isConnected()).thenReturn(true);
Assertions.assertTrue(provider.isSupport(null));
Mockito.when(reference.get().isConnected()).thenReturn(false);
Assertions.assertFalse(provider.isSupport(null));
frameworkModel.destroy();
}
}
@Test
void testEnable1() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("io.grpc.Channel")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertFalse(provider.isSupport(null));
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void testEnable2() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertFalse(provider.isSupport(null));
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void getProviderConnectionConfigTest() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertNull(provider.getProviderConnectionConfig(null));
CertPair certPair = new CertPair("privateKey", "publicKey", "trustCerts", 12345);
Mockito.when(reference.get().generateCert()).thenReturn(certPair);
ProviderCert providerConnectionConfig = provider.getProviderConnectionConfig(null);
Assertions.assertArrayEquals("privateKey".getBytes(), providerConnectionConfig.getPrivateKey());
Assertions.assertArrayEquals("publicKey".getBytes(), providerConnectionConfig.getKeyCertChain());
Assertions.assertArrayEquals("trustCerts".getBytes(), providerConnectionConfig.getTrustCert());
Assertions.assertEquals(AuthPolicy.NONE, providerConnectionConfig.getAuthPolicy());
frameworkModel.destroy();
}
}
@Test
void getConsumerConnectionConfigTest() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
DubboCertProvider provider = new DubboCertProvider(frameworkModel);
Assertions.assertNull(provider.getConsumerConnectionConfig(null));
CertPair certPair = new CertPair("privateKey", "publicKey", "trustCerts", 12345);
Mockito.when(reference.get().generateCert()).thenReturn(certPair);
Cert connectionConfig = provider.getConsumerConnectionConfig(null);
Assertions.assertArrayEquals("privateKey".getBytes(), connectionConfig.getPrivateKey());
Assertions.assertArrayEquals("publicKey".getBytes(), connectionConfig.getKeyCertChain());
Assertions.assertArrayEquals("trustCerts".getBytes(), connectionConfig.getTrustCert());
frameworkModel.destroy();
}
}
}
| 8,181 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/test/java/org/apache/dubbo/security/cert/CertDeployerListenerTest.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.security.cert;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
class CertDeployerListenerTest {
@Test
void testEmpty1() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(0)).connect(Mockito.any());
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testEmpty2() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
applicationModel.getApplicationConfigManager().setSsl(new SslConfig());
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(0)).connect(Mockito.any());
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testCreate() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(1)).connect(Mockito.any());
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testFailure() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getApplicationConfigManager().addMetadataReport(new MetadataReportConfig("absent"));
ApplicationDeployer deployer = applicationModel.getDeployer();
Assertions.assertThrows(IllegalArgumentException.class, deployer::start);
Mockito.verify(reference.get(), Mockito.times(1)).connect(Mockito.any());
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Test
void testNotFound1() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("io.grpc.Channel")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
applicationModel.getDeployer().stop();
Assertions.assertEquals(0, construction.constructed().size());
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void testNotFound2() {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader newClassLoader = new ClassLoader(originClassLoader) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder")) {
throw new ClassNotFoundException("Test");
}
return super.loadClass(name);
}
};
Thread.currentThread().setContextClassLoader(newClassLoader);
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
// ignore
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
applicationModel.getDeployer().stop();
Assertions.assertEquals(0, construction.constructed().size());
frameworkModel.destroy();
}
Thread.currentThread().setContextClassLoader(originClassLoader);
}
@Test
void testParams1() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setCaAddress("127.0.0.1:30060");
sslConfig.setCaCertPath("certs/ca.crt");
sslConfig.setOidcTokenPath("token");
sslConfig.setEnvType("test");
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(1))
.connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token"));
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
}
}
@Disabled("Enable me until properties from envs work.")
@Test
void testParams2() {
AtomicReference<DubboCertManager> reference = new AtomicReference<>();
try (MockedConstruction<DubboCertManager> construction =
Mockito.mockConstruction(DubboCertManager.class, (mock, context) -> {
reference.set(mock);
})) {
System.setProperty("dubbo.ssl.ca-address", "127.0.0.1:30060");
System.setProperty("dubbo.ssl.ca-cert-path", "certs/ca.crt");
System.setProperty("dubbo.ssl.oidc-token-path", "token");
System.setProperty("dubbo.ssl.env-type", "test");
FrameworkModel frameworkModel = new FrameworkModel();
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("test"));
applicationModel.getDeployer().start();
Mockito.verify(reference.get(), Mockito.times(1))
.connect(new CertConfig("127.0.0.1:30060", "test", "certs/ca.crt", "token"));
applicationModel.getDeployer().stop();
Mockito.verify(reference.get(), Mockito.atLeast(1)).disConnect();
frameworkModel.destroy();
System.clearProperty("dubbo.ssl.ca-address");
System.clearProperty("dubbo.ssl.ca-cert-path");
System.clearProperty("dubbo.ssl.oidc-token-path");
System.clearProperty("dubbo.ssl.env-type");
}
}
}
| 8,182 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertProvider.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.security.cert;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.ssl.AuthPolicy;
import org.apache.dubbo.common.ssl.Cert;
import org.apache.dubbo.common.ssl.CertProvider;
import org.apache.dubbo.common.ssl.ProviderCert;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.nio.charset.StandardCharsets;
@Activate
public class DubboCertProvider implements CertProvider {
private final DubboCertManager dubboCertManager;
public DubboCertProvider(FrameworkModel frameworkModel) {
dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class);
}
@Override
public boolean isSupport(URL address) {
return dubboCertManager != null && dubboCertManager.isConnected();
}
@Override
public ProviderCert getProviderConnectionConfig(URL localAddress) {
CertPair certPair = dubboCertManager.generateCert();
if (certPair == null) {
return null;
}
return new ProviderCert(
certPair.getCertificate().getBytes(StandardCharsets.UTF_8),
certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8),
certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8),
AuthPolicy.NONE);
}
@Override
public Cert getConsumerConnectionConfig(URL remoteAddress) {
CertPair certPair = dubboCertManager.generateCert();
if (certPair == null) {
return null;
}
return new Cert(
certPair.getCertificate().getBytes(StandardCharsets.UTF_8),
certPair.getPrivateKey().getBytes(StandardCharsets.UTF_8),
certPair.getTrustCerts().getBytes(StandardCharsets.UTF_8));
}
}
| 8,183 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertDeployerListener.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.security.cert;
import org.apache.dubbo.common.deploy.ApplicationDeployListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Objects;
public class CertDeployerListener implements ApplicationDeployListener {
private final DubboCertManager dubboCertManager;
public CertDeployerListener(FrameworkModel frameworkModel) {
dubboCertManager = frameworkModel.getBeanFactory().getBean(DubboCertManager.class);
}
@Override
public void onInitialize(ApplicationModel scopeModel) {}
@Override
public void onStarting(ApplicationModel scopeModel) {
scopeModel.getApplicationConfigManager().getSsl().ifPresent(sslConfig -> {
if (Objects.nonNull(sslConfig.getCaAddress()) && dubboCertManager != null) {
CertConfig certConfig = new CertConfig(
sslConfig.getCaAddress(),
sslConfig.getEnvType(),
sslConfig.getCaCertPath(),
sslConfig.getOidcTokenPath());
dubboCertManager.connect(certConfig);
}
});
}
@Override
public void onStarted(ApplicationModel scopeModel) {}
@Override
public void onStopping(ApplicationModel scopeModel) {
if (dubboCertManager != null) {
dubboCertManager.disConnect();
}
}
@Override
public void onStopped(ApplicationModel scopeModel) {}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {
if (dubboCertManager != null) {
dubboCertManager.disConnect();
}
}
}
| 8,184 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertPair.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.security.cert;
import java.util.Objects;
public class CertPair {
private final String privateKey;
private final String certificate;
private final String trustCerts;
private final long expireTime;
public CertPair(String privateKey, String certificate, String trustCerts, long expireTime) {
this.privateKey = privateKey;
this.certificate = certificate;
this.trustCerts = trustCerts;
this.expireTime = expireTime;
}
public String getPrivateKey() {
return privateKey;
}
public String getCertificate() {
return certificate;
}
public String getTrustCerts() {
return trustCerts;
}
public long getExpireTime() {
return expireTime;
}
public boolean isExpire() {
return System.currentTimeMillis() > expireTime;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CertPair certPair = (CertPair) o;
return expireTime == certPair.expireTime
&& Objects.equals(privateKey, certPair.privateKey)
&& Objects.equals(certificate, certPair.certificate)
&& Objects.equals(trustCerts, certPair.trustCerts);
}
@Override
public int hashCode() {
return Objects.hash(privateKey, certificate, trustCerts, expireTime);
}
}
| 8,185 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertScopeModelInitializer.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.security.cert;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class CertScopeModelInitializer implements ScopeModelInitializer {
public static boolean isSupported() {
try {
ClassUtils.forName("io.grpc.Channel");
ClassUtils.forName("org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder");
return true;
} catch (Throwable t) {
return false;
}
}
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
if (isSupported()) {
beanFactory.registerBean(DubboCertManager.class);
}
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| 8,186 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/DubboCertManager.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.security.cert;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateRequest;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateResponse;
import org.apache.dubbo.auth.v1alpha1.DubboCertificateServiceGrpc;
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.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import io.grpc.Channel;
import io.grpc.Metadata;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import org.bouncycastle.util.io.pem.PemObject;
import static io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CERT_GENERATE_FAILED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SSL_CONNECT_INSECURE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_GENERATE_CERT_ISTIO;
public class DubboCertManager {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboCertManager.class);
private final FrameworkModel frameworkModel;
/**
* gRPC channel to Dubbo Cert Authority server
*/
protected volatile Channel channel;
/**
* Cert pair for current Dubbo instance
*/
protected volatile CertPair certPair;
/**
* Path to OpenID Connect Token file
*/
protected volatile CertConfig certConfig;
/**
* Refresh cert pair for current Dubbo instance
*/
protected volatile ScheduledFuture<?> refreshFuture;
public DubboCertManager(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
public synchronized void connect(CertConfig certConfig) {
if (channel != null) {
logger.error(INTERNAL_ERROR, "", "", "Dubbo Cert Authority server is already connected.");
return;
}
if (certConfig == null) {
// No cert config, return
return;
}
if (StringUtils.isEmpty(certConfig.getRemoteAddress())) {
// No remote address configured, return
return;
}
if (StringUtils.isNotEmpty(certConfig.getEnvType())
&& !"Kubernetes".equalsIgnoreCase(certConfig.getEnvType())) {
throw new IllegalArgumentException("Only support Kubernetes env now.");
}
// Create gRPC connection
connect0(certConfig);
this.certConfig = certConfig;
// Try to generate cert from remote
generateCert();
// Schedule refresh task
scheduleRefresh();
}
/**
* Create task to refresh cert pair for current Dubbo instance
*/
protected void scheduleRefresh() {
FrameworkExecutorRepository repository =
frameworkModel.getBeanFactory().getBean(FrameworkExecutorRepository.class);
refreshFuture = repository
.getSharedScheduledExecutor()
.scheduleAtFixedRate(
this::generateCert,
certConfig.getRefreshInterval(),
certConfig.getRefreshInterval(),
TimeUnit.MILLISECONDS);
}
/**
* Try to connect to remote certificate authorization
*
* @param certConfig certificate authorization address
*/
protected void connect0(CertConfig certConfig) {
String caCertPath = certConfig.getCaCertPath();
String remoteAddress = certConfig.getRemoteAddress();
logger.info(
"Try to connect to Dubbo Cert Authority server: " + remoteAddress + ", caCertPath: " + remoteAddress);
try {
if (StringUtils.isNotEmpty(caCertPath)) {
channel = NettyChannelBuilder.forTarget(remoteAddress)
.sslContext(GrpcSslContexts.forClient()
.trustManager(new File(caCertPath))
.build())
.build();
} else {
logger.warn(
CONFIG_SSL_CONNECT_INSECURE,
"",
"",
"No caCertPath is provided, will use insecure connection.");
channel = NettyChannelBuilder.forTarget(remoteAddress)
.sslContext(GrpcSslContexts.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build())
.build();
}
} catch (Exception e) {
logger.error(LoggerCodeConstants.CONFIG_SSL_PATH_LOAD_FAILED, "", "", "Failed to load SSL cert file.", e);
throw new RuntimeException(e);
}
}
public synchronized void disConnect() {
if (refreshFuture != null) {
refreshFuture.cancel(true);
refreshFuture = null;
}
if (channel != null) {
channel = null;
}
}
public boolean isConnected() {
return certConfig != null && channel != null && certPair != null;
}
protected CertPair generateCert() {
if (certPair != null && !certPair.isExpire()) {
return certPair;
}
synchronized (this) {
if (certPair == null || certPair.isExpire()) {
try {
logger.info("Try to generate cert from Dubbo Certificate Authority.");
CertPair certFromRemote = refreshCert();
if (certFromRemote != null) {
certPair = certFromRemote;
} else {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Cert from Dubbo Certificate Authority failed.");
}
} catch (Exception e) {
logger.error(REGISTRY_FAILED_GENERATE_CERT_ISTIO, "", "", "Generate Cert from Istio failed.", e);
}
}
}
return certPair;
}
/**
* Request remote certificate authorization to generate cert pair for current Dubbo instance
*
* @return cert pair
* @throws IOException ioException
*/
protected CertPair refreshCert() throws IOException {
KeyPair keyPair = signWithEcdsa();
if (keyPair == null) {
keyPair = signWithRsa();
}
if (keyPair == null) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Key failed. Please check if your system support.");
return null;
}
String csr = generateCsr(keyPair);
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub =
DubboCertificateServiceGrpc.newBlockingStub(channel);
stub = setHeaderIfNeed(stub);
String privateKeyPem = generatePrivatePemKey(keyPair);
DubboCertificateResponse certificateResponse = stub.createCertificate(generateRequest(csr));
if (certificateResponse == null || !certificateResponse.getSuccess()) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Failed to generate cert from Dubbo Certificate Authority. " + "Message: "
+ (certificateResponse == null ? "null" : certificateResponse.getMessage()));
return null;
}
logger.info("Successfully generate cert from Dubbo Certificate Authority. Cert expire time: "
+ certificateResponse.getExpireTime());
return new CertPair(
privateKeyPem,
certificateResponse.getCertPem(),
String.join("\n", certificateResponse.getTrustCertsList()),
certificateResponse.getExpireTime());
}
private DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub setHeaderIfNeed(
DubboCertificateServiceGrpc.DubboCertificateServiceBlockingStub stub) throws IOException {
String oidcTokenPath = certConfig.getOidcTokenPath();
if (StringUtils.isNotEmpty(oidcTokenPath)) {
Metadata header = new Metadata();
Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
header.put(
key,
"Bearer "
+ IOUtils.read(new FileReader(oidcTokenPath))
.replace("\n", "")
.replace("\t", "")
.replace("\r", "")
.trim());
stub = stub.withInterceptors(newAttachHeadersInterceptor(header));
logger.info("Use oidc token from " + oidcTokenPath + " to connect to Dubbo Certificate Authority.");
} else {
logger.warn(
CONFIG_SSL_CONNECT_INSECURE,
"",
"",
"Use insecure connection to connect to Dubbo Certificate Authority. Reason: No oidc token is provided.");
}
return stub;
}
/**
* Generate key pair with RSA
*
* @return key pair
*/
protected static KeyPair signWithRsa() {
KeyPair keyPair = null;
try {
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
kpGenerator.initialize(4096);
java.security.KeyPair keypair = kpGenerator.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey privateKey = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(keypair.getPrivate());
keyPair = new KeyPair(publicKey, privateKey, signer);
} catch (NoSuchAlgorithmException | OperatorCreationException e) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Key with SHA256WithRSA algorithm failed. Please check if your system support.",
e);
}
return keyPair;
}
/**
* Generate key pair with ECDSA
*
* @return key pair
*/
protected static KeyPair signWithEcdsa() {
KeyPair keyPair = null;
try {
ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
g.initialize(ecSpec, new SecureRandom());
java.security.KeyPair keypair = g.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey privateKey = keypair.getPrivate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(privateKey);
keyPair = new KeyPair(publicKey, privateKey, signer);
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException e) {
logger.error(
CONFIG_SSL_CERT_GENERATE_FAILED,
"",
"",
"Generate Key with secp256r1 algorithm failed. Please check if your system support. "
+ "Will attempt to generate with RSA2048.",
e);
}
return keyPair;
}
private DubboCertificateRequest generateRequest(String csr) {
return DubboCertificateRequest.newBuilder()
.setCsr(csr)
.setType("CONNECTION")
.build();
}
/**
* Generate private key in pem encoded
*
* @param keyPair key pair
* @return private key
* @throws IOException ioException
*/
private String generatePrivatePemKey(KeyPair keyPair) throws IOException {
String key = generatePemKey("RSA PRIVATE KEY", keyPair.getPrivateKey().getEncoded());
if (logger.isDebugEnabled()) {
logger.debug("Generated Private Key. \n" + key);
}
return key;
}
/**
* Generate content in pem encoded
*
* @param type content type
* @param content content
* @return encoded data
* @throws IOException ioException
*/
private String generatePemKey(String type, byte[] content) throws IOException {
PemObject pemObject = new PemObject(type, content);
StringWriter str = new StringWriter();
JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(str);
jcaPEMWriter.writeObject(pemObject);
jcaPEMWriter.close();
str.close();
return str.toString();
}
/**
* Generate CSR (Certificate Sign Request)
*
* @param keyPair key pair to request
* @return csr
* @throws IOException ioException
*/
private String generateCsr(KeyPair keyPair) throws IOException {
PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder(
new X500Name("O=" + "cluster.domain"), keyPair.getPublicKey())
.build(keyPair.getSigner());
String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded());
if (logger.isDebugEnabled()) {
logger.debug("CSR Request to Dubbo Certificate Authorization. \n" + csr);
}
return csr;
}
protected static class KeyPair {
private final PublicKey publicKey;
private final PrivateKey privateKey;
private final ContentSigner signer;
public KeyPair(PublicKey publicKey, PrivateKey privateKey, ContentSigner signer) {
this.publicKey = publicKey;
this.privateKey = privateKey;
this.signer = signer;
}
public PublicKey getPublicKey() {
return publicKey;
}
public PrivateKey getPrivateKey() {
return privateKey;
}
public ContentSigner getSigner() {
return signer;
}
}
}
| 8,187 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/Constants.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.security.cert;
public interface Constants {
int DEFAULT_REFRESH_INTERVAL = 30_000;
}
| 8,188 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security
|
Create_ds/dubbo/dubbo-plugin/dubbo-security/src/main/java/org/apache/dubbo/security/cert/CertConfig.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.security.cert;
import java.util.Objects;
import static org.apache.dubbo.security.cert.Constants.DEFAULT_REFRESH_INTERVAL;
public class CertConfig {
private final String remoteAddress;
private final String envType;
private final String caCertPath;
/**
* Path to OpenID Connect Token file
*/
private final String oidcTokenPath;
private final int refreshInterval;
public CertConfig(String remoteAddress, String envType, String caCertPath, String oidcTokenPath) {
this(remoteAddress, envType, caCertPath, oidcTokenPath, DEFAULT_REFRESH_INTERVAL);
}
public CertConfig(
String remoteAddress, String envType, String caCertPath, String oidcTokenPath, int refreshInterval) {
this.remoteAddress = remoteAddress;
this.envType = envType;
this.caCertPath = caCertPath;
this.oidcTokenPath = oidcTokenPath;
this.refreshInterval = refreshInterval;
}
public String getRemoteAddress() {
return remoteAddress;
}
public String getEnvType() {
return envType;
}
public String getCaCertPath() {
return caCertPath;
}
public String getOidcTokenPath() {
return oidcTokenPath;
}
public int getRefreshInterval() {
return refreshInterval;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CertConfig that = (CertConfig) o;
return Objects.equals(remoteAddress, that.remoteAddress)
&& Objects.equals(envType, that.envType)
&& Objects.equals(caCertPath, that.caCertPath)
&& Objects.equals(oidcTokenPath, that.oidcTokenPath);
}
@Override
public int hashCode() {
return Objects.hash(remoteAddress, envType, caCertPath, oidcTokenPath);
}
}
| 8,189 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToManyMethodHandlerTest.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.reactive;
import org.apache.dubbo.reactive.handler.OneToManyMethodHandler;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
/**
* Unit test for OneToManyMethodHandler
*/
public final class OneToManyMethodHandlerTest {
private CreateObserverAdapter creator;
@BeforeEach
void init() {
creator = new CreateObserverAdapter();
}
@Test
void testInvoke() {
String request = "1,2,3,4,5,6,7";
OneToManyMethodHandler<String, String> handler =
new OneToManyMethodHandler<>(requestMono -> requestMono.flatMapMany(r -> Flux.fromArray(r.split(","))));
CompletableFuture<?> future = handler.invoke(new Object[] {request, creator.getResponseObserver()});
Assertions.assertTrue(future.isDone());
Assertions.assertEquals(7, creator.getNextCounter().get());
Assertions.assertEquals(0, creator.getErrorCounter().get());
Assertions.assertEquals(1, creator.getCompleteCounter().get());
}
@Test
void testError() {
String request = "1,2,3,4,5,6,7";
OneToManyMethodHandler<String, String> handler =
new OneToManyMethodHandler<>(requestMono -> Flux.create(emitter -> {
for (int i = 0; i < 10; i++) {
if (i == 6) {
emitter.error(new Throwable());
} else {
emitter.next(String.valueOf(i));
}
}
}));
CompletableFuture<?> future = handler.invoke(new Object[] {request, creator.getResponseObserver()});
Assertions.assertTrue(future.isDone());
Assertions.assertEquals(6, creator.getNextCounter().get());
Assertions.assertEquals(1, creator.getErrorCounter().get());
Assertions.assertEquals(0, creator.getCompleteCounter().get());
}
}
| 8,190 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/OneToOneMethodHandlerTest.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.reactive;
import org.apache.dubbo.reactive.handler.OneToOneMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Unit test for OneToOneMethodHandler
*/
public final class OneToOneMethodHandlerTest {
@Test
void testInvoke() throws ExecutionException, InterruptedException {
String request = "request";
OneToOneMethodHandler<String, String> handler =
new OneToOneMethodHandler<>(requestMono -> requestMono.map(r -> r + "Test"));
CompletableFuture<?> future = handler.invoke(new Object[] {request});
assertEquals("requestTest", future.get());
}
}
| 8,191 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToManyMethodHandlerTest.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.reactive;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.handler.ManyToManyMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Unit test for ManyToManyMethodHandler
*/
public final class ManyToManyMethodHandlerTest {
@Test
void testInvoke() throws ExecutionException, InterruptedException {
CreateObserverAdapter creator = new CreateObserverAdapter();
ManyToManyMethodHandler<String, String> handler =
new ManyToManyMethodHandler<>(requestFlux -> requestFlux.map(r -> r + "0"));
CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {creator.getResponseObserver()});
StreamObserver<String> requestObserver = future.get();
for (int i = 0; i < 10; i++) {
requestObserver.onNext(String.valueOf(i));
}
requestObserver.onCompleted();
Assertions.assertEquals(10, creator.getNextCounter().get());
Assertions.assertEquals(0, creator.getErrorCounter().get());
Assertions.assertEquals(1, creator.getCompleteCounter().get());
}
}
| 8,192 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/ManyToOneMethodHandlerTest.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.reactive;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.reactive.handler.ManyToOneMethodHandler;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit test for ManyToOneMethodHandler
*/
public final class ManyToOneMethodHandlerTest {
private StreamObserver<String> requestObserver;
private CreateObserverAdapter creator;
@BeforeEach
void init() throws ExecutionException, InterruptedException {
creator = new CreateObserverAdapter();
ManyToOneMethodHandler<String, String> handler = new ManyToOneMethodHandler<>(requestFlux ->
requestFlux.map(Integer::valueOf).reduce(Integer::sum).map(String::valueOf));
CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {creator.getResponseObserver()});
requestObserver = future.get();
}
@Test
void testInvoker() {
for (int i = 0; i < 10; i++) {
requestObserver.onNext(String.valueOf(i));
}
requestObserver.onCompleted();
Assertions.assertEquals(1, creator.getNextCounter().get());
Assertions.assertEquals(0, creator.getErrorCounter().get());
Assertions.assertEquals(1, creator.getCompleteCounter().get());
}
@Test
void testError() {
for (int i = 0; i < 10; i++) {
if (i == 6) {
requestObserver.onError(new Throwable());
}
requestObserver.onNext(String.valueOf(i));
}
requestObserver.onCompleted();
Assertions.assertEquals(0, creator.getNextCounter().get());
Assertions.assertEquals(1, creator.getErrorCounter().get());
Assertions.assertEquals(0, creator.getCompleteCounter().get());
}
}
| 8,193 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/test/java/org/apache/dubbo/reactive/CreateObserverAdapter.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.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter;
import java.util.concurrent.atomic.AtomicInteger;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
public class CreateObserverAdapter {
private ServerCallToObserverAdapter<String> responseObserver;
private AtomicInteger nextCounter;
private AtomicInteger completeCounter;
private AtomicInteger errorCounter;
CreateObserverAdapter() {
nextCounter = new AtomicInteger();
completeCounter = new AtomicInteger();
errorCounter = new AtomicInteger();
responseObserver = Mockito.mock(ServerCallToObserverAdapter.class);
doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString());
doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted();
doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class));
}
public AtomicInteger getCompleteCounter() {
return completeCounter;
}
public AtomicInteger getNextCounter() {
return nextCounter;
}
public AtomicInteger getErrorCounter() {
return errorCounter;
}
public ServerCallToObserverAdapter<String> getResponseObserver() {
return this.responseObserver;
}
}
| 8,194 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorPublisher.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.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
/**
* Used in ManyToOne and ManyToMany in server. <br>
* It is a Publisher for user subscriber to subscribe. <br>
* It is a StreamObserver for requestStream. <br>
* It is a Subscription for user subscriber to request and pass request to responseStream.
*/
public class ServerTripleReactorPublisher<T> extends AbstractTripleReactorPublisher<T> {
public ServerTripleReactorPublisher(CallStreamObserver<?> callStreamObserver) {
super.onSubscribe(callStreamObserver);
}
}
| 8,195 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorPublisher.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.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
import java.util.function.Consumer;
/**
* Used in OneToMany & ManyToOne & ManyToMany in client. <br>
* It is a Publisher for user subscriber to subscribe. <br>
* It is a StreamObserver for responseStream. <br>
* It is a Subscription for user subscriber to request and pass request to requestStream.
*/
public class ClientTripleReactorPublisher<T> extends AbstractTripleReactorPublisher<T> {
public ClientTripleReactorPublisher() {}
public ClientTripleReactorPublisher(Consumer<CallStreamObserver<?>> onSubscribe, Runnable shutdownHook) {
super(onSubscribe, shutdownHook);
}
@Override
public void beforeStart(ClientCallToObserverAdapter<T> clientCallToObserverAdapter) {
super.onSubscribe(clientCallToObserverAdapter);
}
}
| 8,196 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ClientTripleReactorSubscriber.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.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter;
/**
* The subscriber in client to subscribe user publisher and is subscribed by ClientStreamObserver.
*/
public class ClientTripleReactorSubscriber<T> extends AbstractTripleReactorSubscriber<T> {
@Override
public void cancel() {
if (!isCanceled()) {
super.cancel();
((ClientCallToObserverAdapter<T>) downstream).cancel(new Exception("Cancelled"));
}
}
}
| 8,197 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorSubscriber.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.reactive;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.util.annotation.NonNull;
/**
* The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Reactive API. <br>
* Passing the data from Reactive producer to CallStreamObserver.
*/
public abstract class AbstractTripleReactorSubscriber<T> implements Subscriber<T>, CoreSubscriber<T> {
private volatile boolean isCancelled;
protected volatile CallStreamObserver<T> downstream;
private final AtomicBoolean SUBSCRIBED = new AtomicBoolean();
private volatile Subscription subscription;
private final AtomicBoolean HAS_SUBSCRIBED = new AtomicBoolean();
// complete status
private volatile boolean isDone;
/**
* Binding the downstream, and call subscription#request(1).
*
* @param downstream downstream
*/
public void subscribe(final CallStreamObserver<T> downstream) {
if (downstream == null) {
throw new NullPointerException();
}
if (this.downstream == null && SUBSCRIBED.compareAndSet(false, true)) {
this.downstream = downstream;
subscription.request(1);
}
}
@Override
public void onSubscribe(@NonNull final Subscription subscription) {
if (this.subscription == null && HAS_SUBSCRIBED.compareAndSet(false, true)) {
this.subscription = subscription;
return;
}
// onSubscribe cannot be called repeatedly
subscription.cancel();
}
@Override
public void onNext(T t) {
if (!isDone && !isCanceled()) {
downstream.onNext(t);
subscription.request(1);
}
}
@Override
public void onError(Throwable throwable) {
if (!isCanceled()) {
isDone = true;
downstream.onError(throwable);
}
}
@Override
public void onComplete() {
if (!isCanceled()) {
isDone = true;
downstream.onCompleted();
}
}
public void cancel() {
if (!isCancelled && subscription != null) {
isCancelled = true;
subscription.cancel();
}
}
public boolean isCanceled() {
return isCancelled;
}
}
| 8,198 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/ServerTripleReactorSubscriber.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.reactive;
import org.apache.dubbo.rpc.CancellationContext;
import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver;
import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver;
/**
* The Subscriber in server to passing the data produced by user publisher to responseStream.
*/
public class ServerTripleReactorSubscriber<T> extends AbstractTripleReactorSubscriber<T> {
@Override
public void subscribe(CallStreamObserver<T> downstream) {
super.subscribe(downstream);
if (downstream instanceof CancelableStreamObserver) {
CancelableStreamObserver<?> observer = (CancelableStreamObserver<?>) downstream;
final CancellationContext context;
if (observer.getCancellationContext() == null) {
context = new CancellationContext();
observer.setCancellationContext(context);
} else {
context = observer.getCancellationContext();
}
context.addListener(ctx -> super.cancel());
}
}
}
| 8,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.