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-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerContextFilter.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.rpc.cluster.filter.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvokeMode;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.PenetrateAttachmentSelector;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.TimeoutCountDown;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_TIMEOUT_COUNTDOWN_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY;
/**
* ConsumerContextFilter set current RpcContext with invoker,invocation, local host, remote host and port
* for consumer invoker.It does it to make the requires info available to execution thread's RpcContext.
*
* @see Filter
* @see RpcContext
*/
@Activate(group = CONSUMER, order = Integer.MIN_VALUE)
public class ConsumerContextFilter implements ClusterFilter, ClusterFilter.Listener {
private Set<PenetrateAttachmentSelector> supportedSelectors;
public ConsumerContextFilter(ApplicationModel applicationModel) {
ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader =
applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class);
supportedSelectors = selectorExtensionLoader.getSupportedExtensionInstances();
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
RpcContext.getServiceContext()
.setInvoker(invoker)
.setInvocation(invocation)
.setLocalAddress(NetUtils.getLocalHost(), 0);
RpcContext context = RpcContext.getClientAttachment();
context.setAttachment(REMOTE_APPLICATION_KEY, invoker.getUrl().getApplication());
if (invocation instanceof RpcInvocation) {
((RpcInvocation) invocation).setInvoker(invoker);
}
if (CollectionUtils.isNotEmpty(supportedSelectors)) {
for (PenetrateAttachmentSelector supportedSelector : supportedSelectors) {
Map<String, Object> selected = supportedSelector.select(
invocation, RpcContext.getClientAttachment(), RpcContext.getServerAttachment());
if (CollectionUtils.isNotEmptyMap(selected)) {
((RpcInvocation) invocation).addObjectAttachments(selected);
}
}
} else {
((RpcInvocation) invocation)
.addObjectAttachments(RpcContext.getServerAttachment().getObjectAttachments());
}
Map<String, Object> contextAttachments =
RpcContext.getClientAttachment().getObjectAttachments();
if (CollectionUtils.isNotEmptyMap(contextAttachments)) {
/**
* invocation.addAttachmentsIfAbsent(context){@link RpcInvocation#addAttachmentsIfAbsent(Map)}should not be used here,
* because the {@link RpcContext#setAttachment(String, String)} is passed in the Filter when the call is triggered
* by the built-in retry mechanism of the Dubbo. The attachment to update RpcContext will no longer work, which is
* a mistake in most cases (for example, through Filter to RpcContext output traceId and spanId and other information).
*/
((RpcInvocation) invocation).addObjectAttachments(contextAttachments);
}
// pass default timeout set by end user (ReferenceConfig)
Object countDown = RpcContext.getServerAttachment().getObjectAttachment(TIME_COUNTDOWN_KEY);
if (countDown != null) {
String methodName = RpcUtils.getMethodName(invocation);
// When the client has enabled the timeout-countdown function,
// the subsequent calls launched by the Server side will be enabled by default,
// and support to turn off the function on a node to get rid of the timeout control.
if (invoker.getUrl().getMethodParameter(methodName, ENABLE_TIMEOUT_COUNTDOWN_KEY, true)) {
context.setObjectAttachment(TIME_COUNTDOWN_KEY, countDown);
TimeoutCountDown timeoutCountDown = (TimeoutCountDown) countDown;
if (timeoutCountDown.isExpired()) {
return AsyncRpcResult.newDefaultAsyncResult(
new RpcException(
RpcException.TIMEOUT_TERMINATE,
"No time left for making the following call: " + invocation.getServiceName() + "."
+ RpcUtils.getMethodName(invocation) + ", terminate directly."),
invocation);
}
}
}
RpcContext.removeClientResponseContext();
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
// pass attachments to result
Map<String, Object> map = appResponse.getObjectAttachments();
RpcContext.getClientResponseContext().setObjectAttachments(map);
removeContext(invocation);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
removeContext(invocation);
}
private void removeContext(Invocation invocation) {
RpcContext.removeClientAttachment();
if (invocation instanceof RpcInvocation) {
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
if (rpcInvocation.getInvokeMode() != null) {
// clear service context if not in sync mode
if (rpcInvocation.getInvokeMode() == InvokeMode.ASYNC
|| rpcInvocation.getInvokeMode() == InvokeMode.FUTURE) {
RpcContext.removeServiceContext();
}
}
}
// server context must not be removed because user might use it on callback.
// So the clear of is delayed til the start of the next rpc call, see RpcContext.removeServerContext(); in
// invoke() above
// RpcContext.removeServerContext();
}
}
| 7,900 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ObservationSenderFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.rpc.cluster.filter.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metrics.observation.DefaultDubboClientObservationConvention;
import org.apache.dubbo.metrics.observation.DubboClientContext;
import org.apache.dubbo.metrics.observation.DubboClientObservationConvention;
import org.apache.dubbo.metrics.observation.DubboObservationDocumentation;
import org.apache.dubbo.rpc.BaseFilter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
/**
* A {@link Filter} that creates an {@link Observation} around the outgoing message.
*/
@Activate(group = CONSUMER, order = -1, onClass = "io.micrometer.observation.NoopObservationRegistry")
public class ObservationSenderFilter implements ClusterFilter, BaseFilter.Listener, ScopeModelAware {
private ObservationRegistry observationRegistry;
private DubboClientObservationConvention clientObservationConvention;
public ObservationSenderFilter(ApplicationModel applicationModel) {
applicationModel.getApplicationConfigManager().getTracing().ifPresent(cfg -> {
if (Boolean.TRUE.equals(cfg.getEnabled())) {
observationRegistry = applicationModel.getBeanFactory().getBean(ObservationRegistry.class);
clientObservationConvention =
applicationModel.getBeanFactory().getBean(DubboClientObservationConvention.class);
}
});
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (observationRegistry == null) {
return invoker.invoke(invocation);
}
final DubboClientContext senderContext = new DubboClientContext(invoker, invocation);
final Observation observation = DubboObservationDocumentation.CLIENT.observation(
this.clientObservationConvention,
DefaultDubboClientObservationConvention.getInstance(),
() -> senderContext,
observationRegistry);
invocation.put(Observation.class, observation.start());
return observation.scoped(() -> invoker.invoke(invocation));
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
final Observation observation = getObservation(invocation);
if (observation == null) {
return;
}
observation.stop();
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
final Observation observation = getObservation(invocation);
if (observation == null) {
return;
}
observation.error(t);
observation.stop();
}
private Observation getObservation(Invocation invocation) {
return (Observation) invocation.get(Observation.class);
}
}
| 7,901 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/ConsumerClassLoaderFilter.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.rpc.cluster.filter.support;
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.RpcException;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
@Activate(group = CONSUMER, order = Integer.MIN_VALUE + 100)
public class ConsumerClassLoaderFilter implements ClusterFilter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader();
try {
Optional.ofNullable(invocation.getServiceModel())
.map(ServiceModel::getClassLoader)
.ifPresent(Thread.currentThread()::setContextClassLoader);
return invoker.invoke(invocation);
} finally {
Thread.currentThread().setContextClassLoader(originClassLoader);
}
}
}
| 7,902 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.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.rpc.cluster.filter.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.metrics.filter.MetricsFilter;
import org.apache.dubbo.rpc.BaseFilter;
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 static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
@Activate(
group = {CONSUMER},
order = Integer.MIN_VALUE + 100)
public class MetricsConsumerFilter extends MetricsFilter implements ClusterFilter, BaseFilter.Listener {
public MetricsConsumerFilter() {}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return super.invoke(invoker, invocation, false);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
super.onResponse(appResponse, invoker, invocation, false);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
super.onError(t, invoker, invocation, false);
}
}
| 7,903 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/interceptor/ClusterInterceptor.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.rpc.cluster.interceptor;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.support.AbstractClusterInvoker;
/**
* Different from {@link Filter}, ClusterInterceptor works at the outmost layer, before one specific address/invoker is picked.
*/
@Deprecated
@SPI
public interface ClusterInterceptor {
void before(AbstractClusterInvoker<?> clusterInvoker, Invocation invocation);
void after(AbstractClusterInvoker<?> clusterInvoker, Invocation invocation);
/**
* Override this method or {@link #before(AbstractClusterInvoker, Invocation)}
* and {@link #after(AbstractClusterInvoker, Invocation)} methods to add your own logic expected to be
* executed before and after invoke.
*
* @param clusterInvoker
* @param invocation
* @return
* @throws RpcException
*/
default Result intercept(AbstractClusterInvoker<?> clusterInvoker, Invocation invocation) throws RpcException {
return clusterInvoker.invoke(invocation);
}
interface Listener {
void onMessage(Result appResponse, AbstractClusterInvoker<?> clusterInvoker, Invocation invocation);
void onError(Throwable t, AbstractClusterInvoker<?> clusterInvoker, Invocation invocation);
}
}
| 7,904 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouterRule.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.rpc.cluster.router;
import java.util.Map;
import static org.apache.dubbo.rpc.cluster.Constants.CONFIG_VERSION_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.DYNAMIC_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.ENABLED_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.KEY_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.PRIORITY_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RAW_RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.SCOPE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.VALID_KEY;
/**
* TODO Extract more code here if necessary
*/
public abstract class AbstractRouterRule {
private String rawRule;
private boolean runtime = true;
private boolean force = false;
private boolean valid = true;
private boolean enabled = true;
private int priority;
private boolean dynamic = false;
private String version;
private String scope;
private String key;
protected void parseFromMap0(Map<String, Object> map) {
setRawRule((String) map.get(RAW_RULE_KEY));
Object runtime = map.get(RUNTIME_KEY);
if (runtime != null) {
setRuntime(Boolean.parseBoolean(runtime.toString()));
}
Object force = map.get(FORCE_KEY);
if (force != null) {
setForce(Boolean.parseBoolean(force.toString()));
}
Object valid = map.get(VALID_KEY);
if (valid != null) {
setValid(Boolean.parseBoolean(valid.toString()));
}
Object enabled = map.get(ENABLED_KEY);
if (enabled != null) {
setEnabled(Boolean.parseBoolean(enabled.toString()));
}
Object priority = map.get(PRIORITY_KEY);
if (priority != null) {
setPriority(Integer.parseInt(priority.toString()));
}
Object dynamic = map.get(DYNAMIC_KEY);
if (dynamic != null) {
setDynamic(Boolean.parseBoolean(dynamic.toString()));
}
setScope((String) map.get(SCOPE_KEY));
setKey((String) map.get(KEY_KEY));
setVersion((String) map.get(CONFIG_VERSION_KEY));
}
public String getRawRule() {
return rawRule;
}
public void setRawRule(String rawRule) {
this.rawRule = rawRule;
}
public boolean isRuntime() {
return runtime;
}
public void setRuntime(boolean runtime) {
this.runtime = runtime;
}
public boolean isForce() {
return force;
}
public void setForce(boolean force) {
this.force = force;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public boolean isDynamic() {
return dynamic;
}
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
| 7,905 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/AbstractRouter.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.rpc.cluster.router;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
public abstract class AbstractRouter implements Router {
private int priority = DEFAULT_PRIORITY;
private boolean force = false;
private URL url;
private GovernanceRuleRepository ruleRepository;
public AbstractRouter(URL url) {
this.ruleRepository = url.getOrDefaultModuleModel()
.getExtensionLoader(GovernanceRuleRepository.class)
.getDefaultExtension();
this.url = url;
}
public AbstractRouter() {}
@Override
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
@Override
public boolean isRuntime() {
return true;
}
@Override
public boolean isForce() {
return force;
}
public void setForce(boolean force) {
this.force = force;
}
@Override
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public GovernanceRuleRepository getRuleRepository() {
return this.ruleRepository;
}
}
| 7,906 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterResult.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.rpc.cluster.router;
import java.util.List;
public class RouterResult<T> {
private final boolean needContinueRoute;
private final List<T> result;
private final String message;
public RouterResult(List<T> result) {
this.needContinueRoute = true;
this.result = result;
this.message = null;
}
public RouterResult(List<T> result, String message) {
this.needContinueRoute = true;
this.result = result;
this.message = message;
}
public RouterResult(boolean needContinueRoute, List<T> result, String message) {
this.needContinueRoute = needContinueRoute;
this.result = result;
this.message = message;
}
public boolean isNeedContinueRoute() {
return needContinueRoute;
}
public List<T> getResult() {
return result;
}
public String getMessage() {
return message;
}
}
| 7,907 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotFilter.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.rpc.cluster.router;
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.BaseFilter;
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.RpcException;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
@Activate(group = {CONSUMER})
public class RouterSnapshotFilter implements ClusterFilter, BaseFilter.Listener {
private final RouterSnapshotSwitcher switcher;
private static final Logger logger = LoggerFactory.getLogger(RouterSnapshotFilter.class);
public RouterSnapshotFilter(FrameworkModel frameworkModel) {
this.switcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (!switcher.isEnable()) {
return invoker.invoke(invocation);
}
if (!logger.isInfoEnabled()) {
return invoker.invoke(invocation);
}
if (!switcher.isEnable(invocation.getServiceModel().getServiceKey())) {
return invoker.invoke(invocation);
}
RpcContext.getServiceContext().setNeedPrintRouterSnapshot(true);
return invoker.invoke(invocation);
}
@Override
public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
RpcContext.getServiceContext().setNeedPrintRouterSnapshot(false);
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
RpcContext.getServiceContext().setNeedPrintRouterSnapshot(false);
}
}
| 7,908 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotNode.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.rpc.cluster.router;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class RouterSnapshotNode<T> {
private final String name;
private final int beforeSize;
private int nodeOutputSize;
private int chainOutputSize;
private String routerMessage;
private final List<Invoker<T>> inputInvokers;
private List<Invoker<T>> nodeOutputInvokers;
private List<Invoker<T>> chainOutputInvokers;
private final List<RouterSnapshotNode<T>> nextNode = new LinkedList<>();
private RouterSnapshotNode<T> parentNode;
public RouterSnapshotNode(String name, List<Invoker<T>> inputInvokers) {
this.name = name;
this.beforeSize = inputInvokers.size();
if (inputInvokers instanceof BitList) {
this.inputInvokers = inputInvokers;
} else {
this.inputInvokers = new ArrayList<>(5);
for (int i = 0; i < Math.min(5, beforeSize); i++) {
this.inputInvokers.add(inputInvokers.get(i));
}
}
this.nodeOutputSize = 0;
}
public String getName() {
return name;
}
public int getBeforeSize() {
return beforeSize;
}
public int getNodeOutputSize() {
return nodeOutputSize;
}
public String getRouterMessage() {
return routerMessage;
}
public void setRouterMessage(String routerMessage) {
this.routerMessage = routerMessage;
}
public List<Invoker<T>> getNodeOutputInvokers() {
return nodeOutputInvokers;
}
public void setNodeOutputInvokers(List<Invoker<T>> outputInvokers) {
this.nodeOutputInvokers = outputInvokers;
this.nodeOutputSize = outputInvokers == null ? 0 : outputInvokers.size();
}
public void setChainOutputInvokers(List<Invoker<T>> outputInvokers) {
this.chainOutputInvokers = outputInvokers;
this.chainOutputSize = outputInvokers == null ? 0 : outputInvokers.size();
}
public int getChainOutputSize() {
return chainOutputSize;
}
public List<Invoker<T>> getChainOutputInvokers() {
return chainOutputInvokers;
}
public List<RouterSnapshotNode<T>> getNextNode() {
return nextNode;
}
public RouterSnapshotNode<T> getParentNode() {
return parentNode;
}
public void appendNode(RouterSnapshotNode<T> nextNode) {
this.nextNode.add(nextNode);
nextNode.parentNode = this;
}
@Override
public String toString() {
return toString(1);
}
public String toString(int level) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append("[ ")
.append(name)
.append(' ')
.append("(Input: ")
.append(beforeSize)
.append(") ")
.append("(Current Node Output: ")
.append(nodeOutputSize)
.append(") ")
.append("(Chain Node Output: ")
.append(chainOutputSize)
.append(')')
.append(routerMessage == null ? "" : " Router message: ")
.append(routerMessage == null ? "" : routerMessage)
.append(" ] ");
if (level == 1) {
stringBuilder
.append("Input: ")
.append(
CollectionUtils.isEmpty(inputInvokers)
? "Empty"
: inputInvokers.subList(0, Math.min(5, inputInvokers.size())).stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.collect(Collectors.joining(",")))
.append(" -> ");
stringBuilder
.append("Chain Node Output: ")
.append(
CollectionUtils.isEmpty(chainOutputInvokers)
? "Empty"
: chainOutputInvokers.subList(0, Math.min(5, chainOutputInvokers.size())).stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.collect(Collectors.joining(",")));
} else {
stringBuilder
.append("Current Node Output: ")
.append(
CollectionUtils.isEmpty(nodeOutputInvokers)
? "Empty"
: nodeOutputInvokers.subList(0, Math.min(5, nodeOutputInvokers.size())).stream()
.map(Invoker::getUrl)
.map(URL::getAddress)
.collect(Collectors.joining(",")));
}
if (nodeOutputInvokers != null && nodeOutputInvokers.size() > 5) {
stringBuilder.append("...");
}
for (RouterSnapshotNode<T> node : nextNode) {
stringBuilder.append("\n");
for (int i = 0; i < level; i++) {
stringBuilder.append(" ");
}
stringBuilder.append(node.toString(level + 1));
}
return stringBuilder.toString();
}
}
| 7,909 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/RouterSnapshotSwitcher.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.rpc.cluster.router;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class RouterSnapshotSwitcher {
private volatile boolean enable;
private final Set<String> enabledService = new ConcurrentHashSet<>();
private static final int MAX_LENGTH = 1 << 5; // 2 ^ 5 = 31
private final AtomicInteger offset = new AtomicInteger(0);
private volatile String[] recentSnapshot = new String[MAX_LENGTH];
public boolean isEnable() {
return enable;
}
public synchronized void addEnabledService(String service) {
enabledService.add(service);
enable = true;
recentSnapshot = new String[MAX_LENGTH];
}
public boolean isEnable(String service) {
return enabledService.contains(service);
}
public synchronized void removeEnabledService(String service) {
enabledService.remove(service);
enable = enabledService.size() > 0;
recentSnapshot = new String[MAX_LENGTH];
}
public synchronized Set<String> getEnabledService() {
return Collections.unmodifiableSet(enabledService);
}
public void setSnapshot(String snapshot) {
if (enable) {
// lock free
recentSnapshot[offset.getAndIncrement() % MAX_LENGTH] = System.currentTimeMillis() + " - " + snapshot;
}
}
public String[] cloneSnapshot() {
String[] clonedSnapshot = new String[MAX_LENGTH];
for (int i = 0; i < MAX_LENGTH; i++) {
clonedSnapshot[i] = recentSnapshot[i];
}
return clonedSnapshot;
}
}
| 7,910 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListenerFactory.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface MeshEnvListenerFactory {
MeshEnvListener getListener();
}
| 7,911 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleCache.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.VsDestinationGroup;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRuleSpec;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.Subset;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.INVALID_APP_NAME;
public class MeshRuleCache<T> {
private final List<String> appList;
private final Map<String, VsDestinationGroup> appToVDGroup;
private final Map<String, Map<String, BitList<Invoker<T>>>> totalSubsetMap;
private final BitList<Invoker<T>> unmatchedInvokers;
private MeshRuleCache(
List<String> appList,
Map<String, VsDestinationGroup> appToVDGroup,
Map<String, Map<String, BitList<Invoker<T>>>> totalSubsetMap,
BitList<Invoker<T>> unmatchedInvokers) {
this.appList = appList;
this.appToVDGroup = appToVDGroup;
this.totalSubsetMap = totalSubsetMap;
this.unmatchedInvokers = unmatchedInvokers;
}
public List<String> getAppList() {
return appList;
}
public Map<String, VsDestinationGroup> getAppToVDGroup() {
return appToVDGroup;
}
public Map<String, Map<String, BitList<Invoker<T>>>> getTotalSubsetMap() {
return totalSubsetMap;
}
public BitList<Invoker<T>> getUnmatchedInvokers() {
return unmatchedInvokers;
}
public VsDestinationGroup getVsDestinationGroup(String appName) {
return appToVDGroup.get(appName);
}
public BitList<Invoker<T>> getSubsetInvokers(String appName, String subset) {
Map<String, BitList<Invoker<T>>> appToSubSets = totalSubsetMap.get(appName);
if (CollectionUtils.isNotEmptyMap(appToSubSets)) {
BitList<Invoker<T>> subsetInvokers = appToSubSets.get(subset);
if (CollectionUtils.isNotEmpty(subsetInvokers)) {
return subsetInvokers;
}
}
return BitList.emptyList();
}
public boolean containsRule() {
return !totalSubsetMap.isEmpty();
}
public static <T> MeshRuleCache<T> build(
String protocolServiceKey,
BitList<Invoker<T>> invokers,
Map<String, VsDestinationGroup> vsDestinationGroupMap) {
if (CollectionUtils.isNotEmptyMap(vsDestinationGroupMap)) {
BitList<Invoker<T>> unmatchedInvokers = new BitList<>(invokers.getOriginList(), true);
Map<String, Map<String, BitList<Invoker<T>>>> totalSubsetMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String remoteApplication = invoker.getUrl().getRemoteApplication();
if (StringUtils.isEmpty(remoteApplication) || INVALID_APP_NAME.equals(remoteApplication)) {
unmatchedInvokers.add(invoker);
continue;
}
VsDestinationGroup vsDestinationGroup = vsDestinationGroupMap.get(remoteApplication);
if (vsDestinationGroup == null) {
unmatchedInvokers.add(invoker);
continue;
}
Map<String, BitList<Invoker<T>>> subsetMap =
totalSubsetMap.computeIfAbsent(remoteApplication, (k) -> new HashMap<>());
boolean matched = false;
for (DestinationRule destinationRule : vsDestinationGroup.getDestinationRuleList()) {
DestinationRuleSpec destinationRuleSpec = destinationRule.getSpec();
List<Subset> subsetList = destinationRuleSpec.getSubsets();
for (Subset subset : subsetList) {
String subsetName = subset.getName();
List<Invoker<T>> subsetInvokers = subsetMap.computeIfAbsent(
subsetName, (k) -> new BitList<>(invokers.getOriginList(), true));
Map<String, String> labels = subset.getLabels();
if (isLabelMatch(invoker.getUrl(), protocolServiceKey, labels)) {
subsetInvokers.add(invoker);
matched = true;
}
}
}
if (!matched) {
unmatchedInvokers.add(invoker);
}
}
return new MeshRuleCache<>(
new LinkedList<>(vsDestinationGroupMap.keySet()),
Collections.unmodifiableMap(vsDestinationGroupMap),
Collections.unmodifiableMap(totalSubsetMap),
unmatchedInvokers);
} else {
return new MeshRuleCache<T>(
Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), invokers);
}
}
public static <T> MeshRuleCache<T> emptyCache() {
return new MeshRuleCache<>(
Collections.emptyList(), Collections.emptyMap(), Collections.emptyMap(), BitList.emptyList());
}
protected static boolean isLabelMatch(URL url, String protocolServiceKey, Map<String, String> inputMap) {
if (inputMap == null || inputMap.size() == 0) {
return true;
}
for (Map.Entry<String, String> entry : inputMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
String originMapValue = url.getOriginalServiceParameter(protocolServiceKey, key);
if (!value.equals(originMapValue)) {
return false;
}
}
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MeshRuleCache<?> ruleCache = (MeshRuleCache<?>) o;
return Objects.equals(appList, ruleCache.appList)
&& Objects.equals(appToVDGroup, ruleCache.appToVDGroup)
&& Objects.equals(totalSubsetMap, ruleCache.totalSubsetMap)
&& Objects.equals(unmatchedInvokers, ruleCache.unmatchedInvokers);
}
@Override
public int hashCode() {
return Objects.hash(appList, appToVDGroup, totalSubsetMap, unmatchedInvokers);
}
}
| 7,912 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshEnvListener.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.rpc.cluster.router.mesh.route;
/**
* Mesh Rule Listener
* Such as Kubernetes, Service Mesh (xDS) environment support define rule in env
*/
public interface MeshEnvListener {
/**
* @return whether current environment support listen
*/
default boolean isEnable() {
return false;
}
void onSubscribe(String appName, MeshAppRuleListener listener);
void onUnSubscribe(String appName);
}
| 7,913 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouterFactory.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
@Activate(order = -50)
public class StandardMeshRuleRouterFactory implements StateRouterFactory {
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
return new StandardMeshRuleRouter<>(url);
}
}
| 7,914 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManager.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.MESH_RULE_DATA_ID_SUFFIX;
public class MeshRuleManager {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleManager.class);
private final ConcurrentHashMap<String, MeshAppRuleListener> APP_RULE_LISTENERS = new ConcurrentHashMap<>();
private final GovernanceRuleRepository ruleRepository;
private final Set<MeshEnvListener> envListeners;
public MeshRuleManager(ModuleModel moduleModel) {
this.ruleRepository = moduleModel.getDefaultExtension(GovernanceRuleRepository.class);
Set<MeshEnvListenerFactory> envListenerFactories =
moduleModel.getExtensionLoader(MeshEnvListenerFactory.class).getSupportedExtensionInstances();
this.envListeners = envListenerFactories.stream()
.map(MeshEnvListenerFactory::getListener)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
private synchronized MeshAppRuleListener subscribeAppRule(String app) {
MeshAppRuleListener meshAppRuleListener = new MeshAppRuleListener(app);
// demo-app.MESHAPPRULE
String appRuleDataId = app + MESH_RULE_DATA_ID_SUFFIX;
// Add listener to rule repository ( dynamic configuration )
try {
String rawConfig = ruleRepository.getRule(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, 5000L);
if (rawConfig != null) {
meshAppRuleListener.receiveConfigInfo(rawConfig);
}
} catch (Throwable throwable) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"failed to get mesh app route rule",
"",
"get MeshRuleManager app rule failed.",
throwable);
}
ruleRepository.addListener(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, meshAppRuleListener);
// Add listener to env ( kubernetes, xDS )
for (MeshEnvListener envListener : envListeners) {
if (envListener.isEnable()) {
envListener.onSubscribe(app, meshAppRuleListener);
}
}
APP_RULE_LISTENERS.put(app, meshAppRuleListener);
return meshAppRuleListener;
}
private synchronized void unsubscribeAppRule(String app, MeshAppRuleListener meshAppRuleListener) {
// demo-app.MESHAPPRULE
String appRuleDataId = app + MESH_RULE_DATA_ID_SUFFIX;
// Remove listener from rule repository ( dynamic configuration )
ruleRepository.removeListener(appRuleDataId, DynamicConfiguration.DEFAULT_GROUP, meshAppRuleListener);
// Remove listener from env ( kubernetes, xDS )
for (MeshEnvListener envListener : envListeners) {
if (envListener.isEnable()) {
envListener.onUnSubscribe(app);
}
}
}
public synchronized <T> void register(String app, MeshRuleListener subscriber) {
MeshAppRuleListener meshAppRuleListener = APP_RULE_LISTENERS.get(app);
if (meshAppRuleListener == null) {
meshAppRuleListener = subscribeAppRule(app);
}
meshAppRuleListener.register(subscriber);
}
public synchronized <T> void unregister(String app, MeshRuleListener subscriber) {
MeshAppRuleListener meshAppRuleListener = APP_RULE_LISTENERS.get(app);
meshAppRuleListener.unregister(subscriber);
if (meshAppRuleListener.isEmpty()) {
unsubscribeAppRule(app, meshAppRuleListener);
APP_RULE_LISTENERS.remove(app);
}
}
/**
* for ut only
*/
@Deprecated
public ConcurrentHashMap<String, MeshAppRuleListener> getAppRuleListeners() {
return APP_RULE_LISTENERS;
}
}
| 7,915 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleConstants.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.rpc.cluster.router.mesh.route;
public class MeshRuleConstants {
public static final String INVALID_APP_NAME = "unknown";
public static final String DESTINATION_RULE_KEY = "DestinationRule";
public static final String VIRTUAL_SERVICE_KEY = "VirtualService";
public static final String KIND_KEY = "kind";
public static final String MESH_RULE_DATA_ID_SUFFIX = ".MESHAPPRULE";
public static final String NAME_KEY = "name";
public static final String METADATA_KEY = "metadata";
public static final String STANDARD_ROUTER_KEY = "standard";
}
| 7,916 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshAppRuleListener.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleDispatcher;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.METADATA_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.NAME_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.STANDARD_ROUTER_KEY;
public class MeshAppRuleListener implements ConfigurationListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshAppRuleListener.class);
private final MeshRuleDispatcher meshRuleDispatcher;
private final String appName;
private volatile Map<String, List<Map<String, Object>>> ruleMapHolder;
public MeshAppRuleListener(String appName) {
this.appName = appName;
this.meshRuleDispatcher = new MeshRuleDispatcher(appName);
}
@SuppressWarnings("unchecked")
public void receiveConfigInfo(String configInfo) {
if (logger.isDebugEnabled()) {
logger.debug(MessageFormat.format("[MeshAppRule] Received rule for app [{0}]: {1}.", appName, configInfo));
}
try {
Map<String, List<Map<String, Object>>> groupMap = new HashMap<>();
Representer representer = new Representer(new DumperOptions());
representer.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()), representer);
Iterable<Object> yamlIterator = yaml.loadAll(configInfo);
for (Object obj : yamlIterator) {
if (obj instanceof Map) {
Map<String, Object> resultMap = (Map<String, Object>) obj;
String ruleType = computeRuleType(resultMap);
if (ruleType != null) {
groupMap.computeIfAbsent(ruleType, (k) -> new LinkedList<>())
.add(resultMap);
} else {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"receive mesh app route rule is invalid",
"",
"Unable to get rule type from raw rule. "
+ "Probably the metadata.name is absent. App Name: " + appName + " RawRule: "
+ configInfo);
}
} else {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"receive mesh app route rule is invalid",
"",
"Rule format is unacceptable. App Name: " + appName + " RawRule: " + configInfo);
}
}
ruleMapHolder = groupMap;
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"failed to receive mesh app route rule",
"",
"[MeshAppRule] parse failed: " + configInfo,
e);
}
if (ruleMapHolder != null) {
meshRuleDispatcher.post(ruleMapHolder);
}
}
@SuppressWarnings("unchecked")
private String computeRuleType(Map<String, Object> rule) {
Object obj = rule.get(METADATA_KEY);
if (obj instanceof Map && CollectionUtils.isNotEmptyMap((Map<String, String>) obj)) {
Map<String, String> metadata = (Map<String, String>) obj;
String name = metadata.get(NAME_KEY);
if (!name.contains(".")) {
return STANDARD_ROUTER_KEY;
} else {
return name.substring(name.indexOf(".") + 1);
}
}
return null;
}
public <T> void register(MeshRuleListener subscriber) {
if (ruleMapHolder != null) {
List<Map<String, Object>> rule = ruleMapHolder.get(subscriber.ruleSuffix());
if (rule != null) {
subscriber.onRuleChange(appName, rule);
}
}
meshRuleDispatcher.register(subscriber);
}
public <T> void unregister(MeshRuleListener subscriber) {
meshRuleDispatcher.unregister(subscriber);
}
@Override
public void process(ConfigChangedEvent event) {
if (event.getChangeType() == ConfigChangeType.DELETED) {
receiveConfigInfo("");
return;
}
receiveConfigInfo(event.getContent());
}
public boolean isEmpty() {
return meshRuleDispatcher.isEmpty();
}
/**
* For ut only
*/
@Deprecated
public MeshRuleDispatcher getMeshRuleDispatcher() {
return meshRuleDispatcher;
}
}
| 7,917 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/StandardMeshRuleRouter.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.STANDARD_ROUTER_KEY;
public class StandardMeshRuleRouter<T> extends MeshRuleRouter<T> {
public StandardMeshRuleRouter(URL url) {
super(url);
}
@Override
public String ruleSuffix() {
return STANDARD_ROUTER_KEY;
}
}
| 7,918 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleRouter.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.rpc.cluster.router.mesh.route;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.PojoUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.VsDestinationGroup;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboMatchRequest;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRoute;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.DubboRouteDetail;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceSpec;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboDestination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboRouteDestination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.util.MeshRuleListener;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RECEIVE_RULE;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.DESTINATION_RULE_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.INVALID_APP_NAME;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.KIND_KEY;
import static org.apache.dubbo.rpc.cluster.router.mesh.route.MeshRuleConstants.VIRTUAL_SERVICE_KEY;
public abstract class MeshRuleRouter<T> extends AbstractStateRouter<T> implements MeshRuleListener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleRouter.class);
private final Map<String, String> sourcesLabels;
private volatile BitList<Invoker<T>> invokerList = BitList.emptyList();
private volatile Set<String> remoteAppName = Collections.emptySet();
protected MeshRuleManager meshRuleManager;
protected Set<TracingContextProvider> tracingContextProviders;
protected volatile MeshRuleCache<T> meshRuleCache = MeshRuleCache.emptyCache();
public MeshRuleRouter(URL url) {
super(url);
sourcesLabels = Collections.unmodifiableMap(new HashMap<>(url.getParameters()));
this.meshRuleManager = url.getOrDefaultModuleModel().getBeanFactory().getBean(MeshRuleManager.class);
this.tracingContextProviders = url.getOrDefaultModuleModel()
.getExtensionLoader(TracingContextProvider.class)
.getSupportedExtensionInstances();
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
MeshRuleCache<T> ruleCache = this.meshRuleCache;
if (!ruleCache.containsRule()) {
if (needToPrintMessage) {
messageHolder.set("MeshRuleCache has not been built. Skip route.");
}
return invokers;
}
BitList<Invoker<T>> result = new BitList<>(invokers.getOriginList(), true, invokers.getTailList());
StringBuilder stringBuilder = needToPrintMessage ? new StringBuilder() : null;
// loop each application
for (String appName : ruleCache.getAppList()) {
// find destination by invocation
List<DubboRouteDestination> routeDestination =
getDubboRouteDestination(ruleCache.getVsDestinationGroup(appName), invocation);
if (routeDestination != null) {
// aggregate target invokers
String subset = randomSelectDestination(ruleCache, appName, routeDestination, invokers);
if (subset != null) {
BitList<Invoker<T>> destination = meshRuleCache.getSubsetInvokers(appName, subset);
result = result.or(destination);
if (stringBuilder != null) {
stringBuilder
.append("Match App: ")
.append(appName)
.append(" Subset: ")
.append(subset)
.append(' ');
}
}
}
}
// result = result.or(ruleCache.getUnmatchedInvokers());
// empty protection
if (result.isEmpty()) {
if (needToPrintMessage) {
messageHolder.set("Empty protection after routed.");
}
return invokers;
}
if (needToPrintMessage) {
messageHolder.set(stringBuilder.toString());
}
return invokers.and(result);
}
/**
* Select RouteDestination by Invocation
*/
protected List<DubboRouteDestination> getDubboRouteDestination(
VsDestinationGroup vsDestinationGroup, Invocation invocation) {
if (vsDestinationGroup != null) {
List<VirtualServiceRule> virtualServiceRuleList = vsDestinationGroup.getVirtualServiceRuleList();
if (CollectionUtils.isNotEmpty(virtualServiceRuleList)) {
for (VirtualServiceRule virtualServiceRule : virtualServiceRuleList) {
// match virtual service (by serviceName)
DubboRoute dubboRoute = getDubboRoute(virtualServiceRule, invocation);
if (dubboRoute != null) {
// match route detail (by params)
return getDubboRouteDestination(dubboRoute, invocation);
}
}
}
}
return null;
}
/**
* Match virtual service (by serviceName)
*/
protected DubboRoute getDubboRoute(VirtualServiceRule virtualServiceRule, Invocation invocation) {
String serviceName = invocation.getServiceName();
VirtualServiceSpec spec = virtualServiceRule.getSpec();
List<DubboRoute> dubboRouteList = spec.getDubbo();
if (CollectionUtils.isNotEmpty(dubboRouteList)) {
for (DubboRoute dubboRoute : dubboRouteList) {
List<StringMatch> stringMatchList = dubboRoute.getServices();
if (CollectionUtils.isEmpty(stringMatchList)) {
return dubboRoute;
}
for (StringMatch stringMatch : stringMatchList) {
if (stringMatch.isMatch(serviceName)) {
return dubboRoute;
}
}
}
}
return null;
}
/**
* Match route detail (by params)
*/
protected List<DubboRouteDestination> getDubboRouteDestination(DubboRoute dubboRoute, Invocation invocation) {
List<DubboRouteDetail> dubboRouteDetailList = dubboRoute.getRoutedetail();
if (CollectionUtils.isNotEmpty(dubboRouteDetailList)) {
for (DubboRouteDetail dubboRouteDetail : dubboRouteDetailList) {
List<DubboMatchRequest> matchRequestList = dubboRouteDetail.getMatch();
if (CollectionUtils.isEmpty(matchRequestList)) {
return dubboRouteDetail.getRoute();
}
if (matchRequestList.stream()
.allMatch(request -> request.isMatch(invocation, sourcesLabels, tracingContextProviders))) {
return dubboRouteDetail.getRoute();
}
}
}
return null;
}
/**
* Find out target invokers from RouteDestination
*/
protected String randomSelectDestination(
MeshRuleCache<T> meshRuleCache,
String appName,
List<DubboRouteDestination> routeDestination,
BitList<Invoker<T>> availableInvokers)
throws RpcException {
// randomly select one DubboRouteDestination from list by weight
int totalWeight = 0;
for (DubboRouteDestination dubboRouteDestination : routeDestination) {
totalWeight += Math.max(dubboRouteDestination.getWeight(), 1);
}
int target = ThreadLocalRandom.current().nextInt(totalWeight);
for (DubboRouteDestination destination : routeDestination) {
target -= Math.max(destination.getWeight(), 1);
if (target <= 0) {
// match weight
String result =
computeDestination(meshRuleCache, appName, destination.getDestination(), availableInvokers);
if (result != null) {
return result;
}
}
}
// fall back
for (DubboRouteDestination destination : routeDestination) {
String result = computeDestination(meshRuleCache, appName, destination.getDestination(), availableInvokers);
if (result != null) {
return result;
}
}
return null;
}
/**
* Compute Destination Subset
*/
protected String computeDestination(
MeshRuleCache<T> meshRuleCache,
String appName,
DubboDestination dubboDestination,
BitList<Invoker<T>> availableInvokers)
throws RpcException {
String subset = dubboDestination.getSubset();
do {
BitList<Invoker<T>> result = meshRuleCache.getSubsetInvokers(appName, subset);
if (CollectionUtils.isNotEmpty(result)
&& !availableInvokers.clone().and(result).isEmpty()) {
return subset;
}
// fall back
DubboRouteDestination dubboRouteDestination = dubboDestination.getFallback();
if (dubboRouteDestination == null) {
break;
}
dubboDestination = dubboRouteDestination.getDestination();
if (dubboDestination == null) {
break;
}
subset = dubboDestination.getSubset();
} while (true);
return null;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
BitList<Invoker<T>> invokerList = invokers == null ? BitList.emptyList() : invokers;
this.invokerList = invokerList.clone();
registerAppRule(invokerList);
computeSubset(this.meshRuleCache.getAppToVDGroup());
}
private void registerAppRule(BitList<Invoker<T>> invokers) {
Set<String> currentApplication = new HashSet<>();
if (CollectionUtils.isNotEmpty(invokers)) {
for (Invoker<T> invoker : invokers) {
String applicationName = invoker.getUrl().getRemoteApplication();
if (StringUtils.isNotEmpty(applicationName) && !INVALID_APP_NAME.equals(applicationName)) {
currentApplication.add(applicationName);
}
}
}
if (!remoteAppName.equals(currentApplication)) {
synchronized (this) {
Set<String> current = new HashSet<>(currentApplication);
Set<String> previous = new HashSet<>(remoteAppName);
previous.removeAll(currentApplication);
current.removeAll(remoteAppName);
for (String app : current) {
meshRuleManager.register(app, this);
}
for (String app : previous) {
meshRuleManager.unregister(app, this);
}
remoteAppName = currentApplication;
}
}
}
@Override
public synchronized void onRuleChange(String appName, List<Map<String, Object>> rules) {
// only update specified app's rule
Map<String, VsDestinationGroup> appToVDGroup = new ConcurrentHashMap<>(this.meshRuleCache.getAppToVDGroup());
try {
VsDestinationGroup vsDestinationGroup = new VsDestinationGroup();
vsDestinationGroup.setAppName(appName);
for (Map<String, Object> rule : rules) {
if (DESTINATION_RULE_KEY.equals(rule.get(KIND_KEY))) {
DestinationRule destinationRule = PojoUtils.mapToPojo(rule, DestinationRule.class);
vsDestinationGroup.getDestinationRuleList().add(destinationRule);
} else if (VIRTUAL_SERVICE_KEY.equals(rule.get(KIND_KEY))) {
VirtualServiceRule virtualServiceRule = PojoUtils.mapToPojo(rule, VirtualServiceRule.class);
vsDestinationGroup.getVirtualServiceRuleList().add(virtualServiceRule);
}
}
if (vsDestinationGroup.isValid()) {
appToVDGroup.put(appName, vsDestinationGroup);
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_RECEIVE_RULE,
"failed to parse mesh route rule",
"",
"Error occurred when parsing rule component.",
t);
}
computeSubset(appToVDGroup);
}
@Override
public synchronized void clearRule(String appName) {
Map<String, VsDestinationGroup> appToVDGroup = new ConcurrentHashMap<>(this.meshRuleCache.getAppToVDGroup());
appToVDGroup.remove(appName);
computeSubset(appToVDGroup);
}
protected void computeSubset(Map<String, VsDestinationGroup> vsDestinationGroupMap) {
this.meshRuleCache =
MeshRuleCache.build(getUrl().getProtocolServiceKey(), this.invokerList, vsDestinationGroupMap);
}
@Override
public void stop() {
for (String app : remoteAppName) {
meshRuleManager.unregister(app, this);
}
}
/**
* for ut only
*/
@Deprecated
public Set<String> getRemoteAppName() {
return remoteAppName;
}
/**
* for ut only
*/
@Deprecated
public BitList<Invoker<T>> getInvokerList() {
return invokerList;
}
/**
* for ut only
*/
@Deprecated
public MeshRuleCache<T> getMeshRuleCache() {
return meshRuleCache;
}
}
| 7,919 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/TracingContextProvider.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.rpc.cluster.router.mesh.util;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
/**
* SPI to get tracing context from 3rd-party tracing utils ( e.g. OpenTracing )
*/
@SPI(scope = ExtensionScope.APPLICATION)
public interface TracingContextProvider {
/**
* Get value from context
*
* @param invocation invocation
* @param key key of value
* @return value (null if absent)
*/
String getValue(Invocation invocation, String key);
}
| 7,920 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleDispatcher.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.rpc.cluster.router.mesh.util;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_RULE_LISTENER;
public class MeshRuleDispatcher {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MeshRuleDispatcher.class);
private final String appName;
private final ConcurrentMap<String, Set<MeshRuleListener>> listenerMap = new ConcurrentHashMap<>();
public MeshRuleDispatcher(String appName) {
this.appName = appName;
}
public synchronized void post(Map<String, List<Map<String, Object>>> ruleMap) {
if (ruleMap.isEmpty()) {
// clear rule
for (Map.Entry<String, Set<MeshRuleListener>> entry : listenerMap.entrySet()) {
for (MeshRuleListener listener : entry.getValue()) {
listener.clearRule(appName);
}
}
} else {
for (Map.Entry<String, List<Map<String, Object>>> entry : ruleMap.entrySet()) {
String ruleType = entry.getKey();
Set<MeshRuleListener> listeners = listenerMap.get(ruleType);
if (CollectionUtils.isNotEmpty(listeners)) {
for (MeshRuleListener listener : listeners) {
listener.onRuleChange(appName, entry.getValue());
}
} else {
logger.warn(
CLUSTER_NO_RULE_LISTENER,
"Receive mesh rule but none of listener has been registered",
"",
"Receive rule but none of listener has been registered. Maybe type not matched. Rule Type: "
+ ruleType);
}
}
// clear rule listener not being notified in this time
for (Map.Entry<String, Set<MeshRuleListener>> entry : listenerMap.entrySet()) {
if (!ruleMap.containsKey(entry.getKey())) {
for (MeshRuleListener listener : entry.getValue()) {
listener.clearRule(appName);
}
}
}
}
}
public synchronized void register(MeshRuleListener listener) {
if (listener == null) {
return;
}
ConcurrentHashMapUtils.computeIfAbsent(listenerMap, listener.ruleSuffix(), (k) -> new ConcurrentHashSet<>())
.add(listener);
}
public synchronized void unregister(MeshRuleListener listener) {
if (listener == null) {
return;
}
Set<MeshRuleListener> listeners = listenerMap.get(listener.ruleSuffix());
if (CollectionUtils.isNotEmpty(listeners)) {
listeners.remove(listener);
}
if (CollectionUtils.isEmpty(listeners)) {
listenerMap.remove(listener.ruleSuffix());
}
}
public boolean isEmpty() {
return listenerMap.isEmpty();
}
/**
* For ut only
*/
@Deprecated
public Map<String, Set<MeshRuleListener>> getListenerMap() {
return listenerMap;
}
}
| 7,921 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/util/MeshRuleListener.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.rpc.cluster.router.mesh.util;
import java.util.List;
import java.util.Map;
public interface MeshRuleListener {
void onRuleChange(String appName, List<Map<String, Object>> rules);
void clearRule(String appName);
String ruleSuffix();
}
| 7,922 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/VsDestinationGroup.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.rpc.cluster.router.mesh.rule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.DestinationRule;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.VirtualServiceRule;
import java.util.LinkedList;
import java.util.List;
public class VsDestinationGroup {
private String appName;
private List<VirtualServiceRule> virtualServiceRuleList = new LinkedList<>();
private List<DestinationRule> destinationRuleList = new LinkedList<>();
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public List<VirtualServiceRule> getVirtualServiceRuleList() {
return virtualServiceRuleList;
}
public void setVirtualServiceRuleList(List<VirtualServiceRule> virtualServiceRuleList) {
this.virtualServiceRuleList = virtualServiceRuleList;
}
public List<DestinationRule> getDestinationRuleList() {
return destinationRuleList;
}
public void setDestinationRuleList(List<DestinationRule> destinationRuleList) {
this.destinationRuleList = destinationRuleList;
}
public boolean isValid() {
return virtualServiceRuleList.size() > 0 && destinationRuleList.size() > 0;
}
}
| 7,923 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/BaseRule.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.rpc.cluster.router.mesh.rule;
import java.util.Map;
public class BaseRule {
private String apiVersion;
private String kind;
private Map<String, String> metadata;
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public Map<String, String> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
@Override
public String toString() {
return "BaseRule{" + "apiVersion='"
+ apiVersion + '\'' + ", kind='"
+ kind + '\'' + ", metadata="
+ metadata + '}';
}
}
| 7,924 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TrafficPolicy.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.rpc.cluster.router.mesh.rule.destination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.destination.loadbalance.LoadBalancerSettings;
public class TrafficPolicy {
private LoadBalancerSettings loadBalancer;
public LoadBalancerSettings getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(LoadBalancerSettings loadBalancer) {
this.loadBalancer = loadBalancer;
}
@Override
public String toString() {
return "TrafficPolicy{" + "loadBalancer=" + loadBalancer + '}';
}
}
| 7,925 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/ConnectionPoolSettings.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.rpc.cluster.router.mesh.rule.destination;
public class ConnectionPoolSettings {}
| 7,926 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRule.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.rpc.cluster.router.mesh.rule.destination;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.BaseRule;
public class DestinationRule extends BaseRule {
private DestinationRuleSpec spec;
public DestinationRuleSpec getSpec() {
return spec;
}
public void setSpec(DestinationRuleSpec spec) {
this.spec = spec;
}
@Override
public String toString() {
return "DestinationRule{" + "base=" + super.toString() + ", spec=" + spec + '}';
}
}
| 7,927 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/Subset.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.rpc.cluster.router.mesh.rule.destination;
import java.util.Map;
public class Subset {
private String name;
private Map<String, String> labels;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getLabels() {
return labels;
}
public void setLabels(Map<String, String> labels) {
this.labels = labels;
}
@Override
public String toString() {
return "Subset{" + "name='" + name + '\'' + ", labels=" + labels + '}';
}
}
| 7,928 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TCPSettings.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.rpc.cluster.router.mesh.rule.destination;
public class TCPSettings {
private int maxConnections;
private int connectTimeout;
private TcpKeepalive tcpKeepalive;
}
| 7,929 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/TcpKeepalive.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.rpc.cluster.router.mesh.rule.destination;
public class TcpKeepalive {
private int probes;
private int time;
private int interval;
}
| 7,930 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/DestinationRuleSpec.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.rpc.cluster.router.mesh.rule.destination;
import java.util.List;
public class DestinationRuleSpec {
private String host;
private List<Subset> subsets;
private TrafficPolicy trafficPolicy;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public List<Subset> getSubsets() {
return subsets;
}
public void setSubsets(List<Subset> subsets) {
this.subsets = subsets;
}
public TrafficPolicy getTrafficPolicy() {
return trafficPolicy;
}
public void setTrafficPolicy(TrafficPolicy trafficPolicy) {
this.trafficPolicy = trafficPolicy;
}
@Override
public String toString() {
return "DestinationRuleSpec{" + "host='"
+ host + '\'' + ", subsets="
+ subsets + ", trafficPolicy="
+ trafficPolicy + '}';
}
}
| 7,931 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/ConsistentHashLB.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.rpc.cluster.router.mesh.rule.destination.loadbalance;
public class ConsistentHashLB {}
| 7,932 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/LoadBalancerSettings.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.rpc.cluster.router.mesh.rule.destination.loadbalance;
public class LoadBalancerSettings {
private SimpleLB simple;
private ConsistentHashLB consistentHash;
public SimpleLB getSimple() {
return simple;
}
public void setSimple(SimpleLB simple) {
this.simple = simple;
}
public ConsistentHashLB getConsistentHash() {
return consistentHash;
}
public void setConsistentHash(ConsistentHashLB consistentHash) {
this.consistentHash = consistentHash;
}
@Override
public String toString() {
return "LoadBalancerSettings{" + "simple=" + simple + ", consistentHash=" + consistentHash + '}';
}
}
| 7,933 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/destination/loadbalance/SimpleLB.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.rpc.cluster.router.mesh.rule.destination.loadbalance;
public enum SimpleLB {
ROUND_ROBIN,
LEAST_CONN,
RANDOM,
PASSTHROUGH
}
| 7,934 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRouteDetail.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.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.destination.DubboRouteDestination;
import java.util.List;
public class DubboRouteDetail {
private String name;
private List<DubboMatchRequest> match;
private List<DubboRouteDestination> route;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DubboMatchRequest> getMatch() {
return match;
}
public void setMatch(List<DubboMatchRequest> match) {
this.match = match;
}
public List<DubboRouteDestination> getRoute() {
return route;
}
public void setRoute(List<DubboRouteDestination> route) {
this.route = route;
}
@Override
public String toString() {
return "DubboRouteDetail{" + "name='" + name + '\'' + ", match=" + match + ", route=" + route + '}';
}
}
| 7,935 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceSpec.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.rpc.cluster.router.mesh.rule.virtualservice;
import java.util.List;
public class VirtualServiceSpec {
private List<String> hosts;
private List<DubboRoute> dubbo;
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public List<DubboRoute> getDubbo() {
return dubbo;
}
public void setDubbo(List<DubboRoute> dubbo) {
this.dubbo = dubbo;
}
@Override
public String toString() {
return "VirtualServiceSpec{" + "hosts=" + hosts + ", dubbo=" + dubbo + '}';
}
}
| 7,936 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/VirtualServiceRule.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.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.BaseRule;
public class VirtualServiceRule extends BaseRule {
private VirtualServiceSpec spec;
public VirtualServiceSpec getSpec() {
return spec;
}
public void setSpec(VirtualServiceSpec spec) {
this.spec = spec;
}
@Override
public String toString() {
return "VirtualServiceRule{" + "base=" + super.toString() + ", spec=" + spec + '}';
}
}
| 7,937 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboMatchRequest.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.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboAttachmentMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.DubboMethodMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Map;
import java.util.Set;
public class DubboMatchRequest {
private String name;
private DubboMethodMatch method;
private Map<String, String> sourceLabels;
private DubboAttachmentMatch attachments;
private Map<String, StringMatch> headers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DubboMethodMatch getMethod() {
return method;
}
public void setMethod(DubboMethodMatch method) {
this.method = method;
}
public Map<String, String> getSourceLabels() {
return sourceLabels;
}
public void setSourceLabels(Map<String, String> sourceLabels) {
this.sourceLabels = sourceLabels;
}
public DubboAttachmentMatch getAttachments() {
return attachments;
}
public void setAttachments(DubboAttachmentMatch attachments) {
this.attachments = attachments;
}
public Map<String, StringMatch> getHeaders() {
return headers;
}
public void setHeaders(Map<String, StringMatch> headers) {
this.headers = headers;
}
@Override
public String toString() {
return "DubboMatchRequest{" + "name='"
+ name + '\'' + ", method="
+ method + ", sourceLabels="
+ sourceLabels + ", attachments="
+ attachments + ", headers="
+ headers + '}';
}
public boolean isMatch(
Invocation invocation, Map<String, String> sourceLabels, Set<TracingContextProvider> contextProviders) {
// Match method
if (getMethod() != null) {
if (!getMethod().isMatch(invocation)) {
return false;
}
}
// Match Source Labels
if (getSourceLabels() != null) {
for (Map.Entry<String, String> entry : getSourceLabels().entrySet()) {
String value = sourceLabels.get(entry.getKey());
if (!entry.getValue().equals(value)) {
return false;
}
}
}
// Match attachment
if (getAttachments() != null) {
return getAttachments().isMatch(invocation, contextProviders);
}
// TODO Match headers
return true;
}
}
| 7,938 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/DubboRoute.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.rpc.cluster.router.mesh.rule.virtualservice;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
import java.util.List;
public class DubboRoute {
private String name;
private List<StringMatch> services;
private List<DubboRouteDetail> routedetail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<StringMatch> getServices() {
return services;
}
public void setServices(List<StringMatch> services) {
this.services = services;
}
public List<DubboRouteDetail> getRoutedetail() {
return routedetail;
}
public void setRoutedetail(List<DubboRouteDetail> routedetail) {
this.routedetail = routedetail;
}
@Override
public String toString() {
return "DubboRoute{" + "name='" + name + '\'' + ", services=" + services + ", routedetail=" + routedetail + '}';
}
}
| 7,939 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodArg.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.rpc.cluster.router.mesh.rule.virtualservice.match;
public class DubboMethodArg {
private int index;
private String type;
private ListStringMatch str_value;
private ListDoubleMatch num_value;
private BoolMatch bool_value;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ListStringMatch getStr_value() {
return str_value;
}
public void setStr_value(ListStringMatch str_value) {
this.str_value = str_value;
}
public ListDoubleMatch getNum_value() {
return num_value;
}
public void setNum_value(ListDoubleMatch num_value) {
this.num_value = num_value;
}
public BoolMatch getBool_value() {
return bool_value;
}
public void setBool_value(BoolMatch bool_value) {
this.bool_value = bool_value;
}
public boolean isMatch(Object input) {
if (str_value != null) {
return input instanceof String && str_value.isMatch((String) input);
} else if (num_value != null) {
return num_value.isMatch(Double.valueOf(input.toString()));
} else if (bool_value != null) {
return input instanceof Boolean && bool_value.isMatch((Boolean) input);
}
return false;
}
@Override
public String toString() {
return "DubboMethodArg{" + "index="
+ index + ", type='"
+ type + '\'' + ", str_value="
+ str_value + ", num_value="
+ num_value + ", bool_value="
+ bool_value + '}';
}
}
| 7,940 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
public class DoubleMatch {
private Double exact;
private DoubleRangeMatch range;
private Double mod;
public Double getExact() {
return exact;
}
public void setExact(Double exact) {
this.exact = exact;
}
public DoubleRangeMatch getRange() {
return range;
}
public void setRange(DoubleRangeMatch range) {
this.range = range;
}
public Double getMod() {
return mod;
}
public void setMod(Double mod) {
this.mod = mod;
}
public boolean isMatch(Double input) {
if (exact != null && mod == null) {
return input.equals(exact);
} else if (range != null) {
return range.isMatch(input);
} else if (exact != null) {
Double result = input % mod;
return result.equals(exact);
}
return false;
}
}
| 7,941 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/AddressMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.net.UnknownHostException;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
import static org.apache.dubbo.common.utils.NetUtils.matchIpExpression;
import static org.apache.dubbo.common.utils.UrlUtils.isMatchGlobPattern;
public class AddressMatch {
public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AddressMatch.class);
private String wildcard;
private String cird;
private String exact;
public String getWildcard() {
return wildcard;
}
public void setWildcard(String wildcard) {
this.wildcard = wildcard;
}
public String getCird() {
return cird;
}
public void setCird(String cird) {
this.cird = cird;
}
public String getExact() {
return exact;
}
public void setExact(String exact) {
this.exact = exact;
}
public boolean isMatch(String input) {
if (getCird() != null && input != null) {
try {
return input.equals(getCird()) || matchIpExpression(getCird(), input);
} catch (UnknownHostException e) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Executing routing rule match expression error.",
"",
String.format(
"Error trying to match cird formatted address %s with input %s in AddressMatch.",
getCird(), input),
e);
}
}
if (getWildcard() != null && input != null) {
if (ANYHOST_VALUE.equals(getWildcard()) || ANY_VALUE.equals(getWildcard())) {
return true;
}
// FIXME
return isMatchGlobPattern(getWildcard(), input);
}
if (getExact() != null && input != null) {
return input.equals(getExact());
}
return false;
}
}
| 7,942 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListDoubleMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.List;
public class ListDoubleMatch {
private List<DoubleMatch> oneof;
public List<DoubleMatch> getOneof() {
return oneof;
}
public void setOneof(List<DoubleMatch> oneof) {
this.oneof = oneof;
}
public boolean isMatch(Double input) {
for (DoubleMatch doubleMatch : oneof) {
if (doubleMatch.isMatch(input)) {
return true;
}
}
return false;
}
}
| 7,943 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/BoolMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
public class BoolMatch {
private Boolean exact;
public Boolean getExact() {
return exact;
}
public void setExact(Boolean exact) {
this.exact = exact;
}
public boolean isMatch(boolean input) {
if (exact != null) {
return input == exact;
}
return false;
}
}
| 7,944 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboAttachmentMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.mesh.util.TracingContextProvider;
import java.util.Map;
import java.util.Set;
public class DubboAttachmentMatch {
private Map<String, StringMatch> tracingContext;
private Map<String, StringMatch> dubboContext;
public Map<String, StringMatch> getTracingContext() {
return tracingContext;
}
public void setTracingContext(Map<String, StringMatch> tracingContext) {
this.tracingContext = tracingContext;
}
public Map<String, StringMatch> getDubboContext() {
return dubboContext;
}
public void setDubboContext(Map<String, StringMatch> dubboContext) {
this.dubboContext = dubboContext;
}
public boolean isMatch(Invocation invocation, Set<TracingContextProvider> contextProviders) {
// Match Dubbo Context
if (dubboContext != null) {
for (Map.Entry<String, StringMatch> entry : dubboContext.entrySet()) {
String key = entry.getKey();
if (!entry.getValue().isMatch(invocation.getAttachment(key))) {
return false;
}
}
}
// Match Tracing Context
if (tracingContext != null) {
for (Map.Entry<String, StringMatch> entry : tracingContext.entrySet()) {
String key = entry.getKey();
boolean match = false;
for (TracingContextProvider contextProvider : contextProviders) {
if (entry.getValue().isMatch(contextProvider.getValue(invocation, key))) {
match = true;
}
}
if (!match) {
return false;
}
}
}
return true;
}
}
| 7,945 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DoubleRangeMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
public class DoubleRangeMatch {
private Double start;
private Double end;
public Double getStart() {
return start;
}
public void setStart(Double start) {
this.start = start;
}
public Double getEnd() {
return end;
}
public void setEnd(Double end) {
this.end = end;
}
public boolean isMatch(Double input) {
if (start != null && end != null) {
return input.compareTo(start) >= 0 && input.compareTo(end) < 0;
} else if (start != null) {
return input.compareTo(start) >= 0;
} else if (end != null) {
return input.compareTo(end) < 0;
} else {
return false;
}
}
}
| 7,946 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.List;
public class ListStringMatch {
private List<StringMatch> oneof;
public List<StringMatch> getOneof() {
return oneof;
}
public void setOneof(List<StringMatch> oneof) {
this.oneof = oneof;
}
public boolean isMatch(String input) {
for (StringMatch stringMatch : oneof) {
if (stringMatch.isMatch(input)) {
return true;
}
}
return false;
}
}
| 7,947 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/DubboMethodMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.List;
import java.util.Map;
public class DubboMethodMatch {
private StringMatch name_match;
private Integer argc;
private List<DubboMethodArg> args;
private List<StringMatch> argp;
private Map<String, StringMatch> headers;
public StringMatch getName_match() {
return name_match;
}
public void setName_match(StringMatch name_match) {
this.name_match = name_match;
}
public Integer getArgc() {
return argc;
}
public void setArgc(Integer argc) {
this.argc = argc;
}
public List<DubboMethodArg> getArgs() {
return args;
}
public void setArgs(List<DubboMethodArg> args) {
this.args = args;
}
public List<StringMatch> getArgp() {
return argp;
}
public void setArgp(List<StringMatch> argp) {
this.argp = argp;
}
public Map<String, StringMatch> getHeaders() {
return headers;
}
public void setHeaders(Map<String, StringMatch> headers) {
this.headers = headers;
}
@Override
public String toString() {
return "DubboMethodMatch{" + "name_match="
+ name_match + ", argc="
+ argc + ", args="
+ args + ", argp="
+ argp + ", headers="
+ headers + '}';
}
public boolean isMatch(Invocation invocation) {
StringMatch nameMatch = getName_match();
if (nameMatch != null && !nameMatch.isMatch(RpcUtils.getMethodName(invocation))) {
return false;
}
Integer argc = getArgc();
Object[] arguments = invocation.getArguments();
if (argc != null
&& ((argc != 0 && (arguments == null || arguments.length == 0)) || (argc != arguments.length))) {
return false;
}
List<StringMatch> argp = getArgp();
Class<?>[] parameterTypes = invocation.getParameterTypes();
if (argp != null && argp.size() > 0) {
if (parameterTypes == null || parameterTypes.length == 0) {
return false;
}
if (argp.size() != parameterTypes.length) {
return false;
}
for (int index = 0; index < argp.size(); index++) {
boolean match = argp.get(index).isMatch(parameterTypes[index].getName())
|| argp.get(index).isMatch(parameterTypes[index].getSimpleName());
if (!match) {
return false;
}
}
}
List<DubboMethodArg> args = getArgs();
if (args != null && args.size() > 0) {
if (arguments == null || arguments.length == 0) {
return false;
}
for (DubboMethodArg dubboMethodArg : args) {
int index = dubboMethodArg.getIndex();
if (index >= arguments.length) {
throw new IndexOutOfBoundsException("DubboMethodArg index >= parameters.length");
}
if (!dubboMethodArg.isMatch(arguments[index])) {
return false;
}
}
}
return true;
}
}
| 7,948 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListBoolMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import java.util.List;
public class ListBoolMatch {
private List<BoolMatch> oneof;
public List<BoolMatch> getOneof() {
return oneof;
}
public void setOneof(List<BoolMatch> oneof) {
this.oneof = oneof;
}
public boolean isMatch(boolean input) {
for (BoolMatch boolMatch : oneof) {
if (boolMatch.isMatch(input)) {
return true;
}
}
return false;
}
}
| 7,949 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/StringMatch.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.rpc.cluster.router.mesh.rule.virtualservice.match;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
public class StringMatch {
private String exact;
private String prefix;
private String regex;
private String noempty;
private String empty;
private String wildcard;
public String getExact() {
return exact;
}
public void setExact(String exact) {
this.exact = exact;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
this.regex = regex;
}
public String getNoempty() {
return noempty;
}
public void setNoempty(String noempty) {
this.noempty = noempty;
}
public String getEmpty() {
return empty;
}
public void setEmpty(String empty) {
this.empty = empty;
}
public String getWildcard() {
return wildcard;
}
public void setWildcard(String wildcard) {
this.wildcard = wildcard;
}
public boolean isMatch(String input) {
if (getExact() != null && input != null) {
return input.equals(getExact());
} else if (getPrefix() != null && input != null) {
return input.startsWith(getPrefix());
} else if (getRegex() != null && input != null) {
return input.matches(getRegex());
} else if (getWildcard() != null && input != null) {
// only supports "*"
return input.equals(getWildcard()) || ANY_VALUE.equals(getWildcard());
} else if (getEmpty() != null) {
return input == null || "".equals(input);
} else if (getNoempty() != null) {
return input != null && input.length() > 0;
} else {
return false;
}
}
@Override
public String toString() {
return "StringMatch{" + "exact='"
+ exact + '\'' + ", prefix='"
+ prefix + '\'' + ", regex='"
+ regex + '\'' + ", noempty='"
+ noempty + '\'' + ", empty='"
+ empty + '\'' + '}';
}
}
| 7,950 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboRouteDestination.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.rpc.cluster.router.mesh.rule.virtualservice.destination;
public class DubboRouteDestination {
private DubboDestination destination;
private int weight;
public DubboDestination getDestination() {
return destination;
}
public void setDestination(DubboDestination destination) {
this.destination = destination;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
| 7,951 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/destination/DubboDestination.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.rpc.cluster.router.mesh.rule.virtualservice.destination;
public class DubboDestination {
private String host;
private String subset;
private int port;
private DubboRouteDestination fallback;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSubset() {
return subset;
}
public void setSubset(String subset) {
this.subset = subset;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public DubboRouteDestination getFallback() {
return fallback;
}
public void setFallback(DubboRouteDestination fallback) {
this.fallback = fallback;
}
}
| 7,952 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/file/FileStateRouterFactory.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.rpc.cluster.router.file;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.utils.IOUtils;
import org.apache.dubbo.rpc.cluster.router.script.ScriptStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
import java.io.FileReader;
import java.io.IOException;
import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
public class FileStateRouterFactory implements StateRouterFactory {
public static final String NAME = "file";
private StateRouterFactory routerFactory;
public void setRouterFactory(StateRouterFactory routerFactory) {
this.routerFactory = routerFactory;
}
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
try {
// Transform File URL into Script Route URL, and Load
// file:///d:/path/to/route.js?router=script ==> script:///d:/path/to/route.js?type=js&rule=<file-content>
String protocol = url.getParameter(
ROUTER_KEY,
ScriptStateRouterFactory.NAME); // Replace original protocol (maybe 'file') with 'script'
String type = null; // Use file suffix to config script type, e.g., js, groovy ...
String path = url.getPath();
if (path != null) {
int i = path.lastIndexOf('.');
if (i > 0) {
type = path.substring(i + 1);
}
}
String rule = IOUtils.read(new FileReader(url.getAbsolutePath()));
// FIXME: this code looks useless
boolean runtime = url.getParameter(RUNTIME_KEY, false);
URL script = URLBuilder.from(url)
.setProtocol(protocol)
.addParameter(TYPE_KEY, type)
.addParameter(RUNTIME_KEY, runtime)
.addParameterAndEncoded(RULE_KEY, rule)
.build();
return routerFactory.getRouter(interfaceClass, script);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
| 7,953 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockInvokersSelector.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.rpc.cluster.router.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.RouterGroupingState;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK;
import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL;
/**
* A specific Router designed to realize mock feature.
* If a request is configured to use mock, then this router guarantees that only the invokers with protocol MOCK appear in final the invoker list, all other invokers will be excluded.
*/
public class MockInvokersSelector<T> extends AbstractStateRouter<T> {
public static final String NAME = "MOCK_ROUTER";
private volatile BitList<Invoker<T>> normalInvokers = BitList.emptyList();
private volatile BitList<Invoker<T>> mockedInvokers = BitList.emptyList();
public MockInvokersSelector(URL url) {
super(url);
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
if (needToPrintMessage) {
messageHolder.set("Empty invokers. Directly return.");
}
return invokers;
}
if (invocation.getObjectAttachments() == null) {
if (needToPrintMessage) {
messageHolder.set("ObjectAttachments from invocation are null. Return normal Invokers.");
}
return invokers.and(normalInvokers);
} else {
String value = (String) invocation.getObjectAttachmentWithoutConvert(INVOCATION_NEED_MOCK);
if (value == null) {
if (needToPrintMessage) {
messageHolder.set("invocation.need.mock not set. Return normal Invokers.");
}
return invokers.and(normalInvokers);
} else if (Boolean.TRUE.toString().equalsIgnoreCase(value)) {
if (needToPrintMessage) {
messageHolder.set("invocation.need.mock is true. Return mocked Invokers.");
}
return invokers.and(mockedInvokers);
}
}
if (needToPrintMessage) {
messageHolder.set("Directly Return. Reason: invocation.need.mock is set but not match true");
}
return invokers;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
cacheMockedInvokers(invokers);
cacheNormalInvokers(invokers);
}
private void cacheMockedInvokers(BitList<Invoker<T>> invokers) {
BitList<Invoker<T>> clonedInvokers = invokers.clone();
clonedInvokers.removeIf((invoker) -> !invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL));
mockedInvokers = clonedInvokers;
}
@SuppressWarnings("rawtypes")
private void cacheNormalInvokers(BitList<Invoker<T>> invokers) {
BitList<Invoker<T>> clonedInvokers = invokers.clone();
clonedInvokers.removeIf((invoker) -> invoker.getUrl().getProtocol().equals(MOCK_PROTOCOL));
normalInvokers = clonedInvokers;
}
@Override
protected String doBuildSnapshot() {
Map<String, BitList<Invoker<T>>> grouping = new HashMap<>();
grouping.put("Mocked", mockedInvokers);
grouping.put("Normal", normalInvokers);
return new RouterGroupingState<>(
this.getClass().getSimpleName(), mockedInvokers.size() + normalInvokers.size(), grouping)
.toString();
}
}
| 7,954 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mock/MockStateRouterFactory.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.rpc.cluster.router.mock;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
*
*/
@Activate(order = -100)
public class MockStateRouterFactory implements StateRouterFactory {
public static final String NAME = "mock";
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
return new MockInvokersSelector<T>(url);
}
}
| 7,955 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/TailStateRouter.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.rpc.cluster.router.state;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
public class TailStateRouter<T> implements StateRouter<T> {
private static final TailStateRouter INSTANCE = new TailStateRouter();
@SuppressWarnings("unchecked")
public static <T> TailStateRouter<T> getInstance() {
return INSTANCE;
}
private TailStateRouter() {}
@Override
public void setNextRouter(StateRouter<T> nextRouter) {}
@Override
public URL getUrl() {
return null;
}
@Override
public BitList<Invoker<T>> route(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder)
throws RpcException {
return invokers;
}
@Override
public boolean isRuntime() {
return false;
}
@Override
public boolean isForce() {
return false;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {}
@Override
public String buildSnapshot() {
return "TailStateRouter End";
}
}
| 7,956 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouterFactory.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.rpc.cluster.router.state;
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.SPI;
@SPI
public interface StateRouterFactory {
/**
* Create state router.
*
* @param url url
* @return router instance
* @since 3.0
*/
@Adaptive(CommonConstants.PROTOCOL_KEY)
<T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url);
}
| 7,957 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/CacheableStateRouterFactory.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.rpc.cluster.router.state;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* If you want to provide a router implementation based on design of v2.7.0, please extend from this abstract class.
* For 2.6.x style router, please implement and use RouterFactory directly.
*/
public abstract class CacheableStateRouterFactory implements StateRouterFactory {
// TODO reuse StateRouter for all routerChain
private final ConcurrentMap<String, StateRouter> routerMap = new ConcurrentHashMap<>();
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
return ConcurrentHashMapUtils.computeIfAbsent(
routerMap, url.getServiceKey(), k -> createRouter(interfaceClass, url));
}
protected abstract <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url);
}
| 7,958 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/BitList.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.rpc.cluster.router.state;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.concurrent.ThreadLocalRandom;
/**
* BitList based on BitMap implementation.
* BitList is consists of `originList`, `rootSet` and `tailList`.
* <p>
* originList: Initial elements of the list. This list will not be changed
* in modification actions (expect clear all).
* rootSet: A bitMap to store the indexes of originList are still exist.
* Most of the modification actions are operated on this bitMap.
* tailList: An additional list for BitList. Worked when adding totally new
* elements to list. These elements will be appended to the last
* of the BitList.
* <p>
* An example of BitList:
* originList: A B C D E (5 elements)
* rootSet: x v x v v
* 0 1 0 1 1 (5 elements)
* tailList: F G H (3 elements)
* resultList: B D E F G H (6 elements)
*
* @param <E>
* @since 3.0
*/
public class BitList<E> extends AbstractList<E> implements Cloneable {
private final BitSet rootSet;
private volatile List<E> originList;
private static final BitList emptyList = new BitList(Collections.emptyList());
private volatile List<E> tailList = null;
public BitList(List<E> originList) {
this(originList, false);
}
public BitList(List<E> originList, boolean empty) {
if (originList instanceof BitList) {
this.originList = ((BitList<E>) originList).getOriginList();
this.tailList = ((BitList<E>) originList).getTailList();
} else {
this.originList = originList;
}
this.rootSet = new BitSet();
if (!empty) {
this.rootSet.set(0, originList.size());
} else {
this.tailList = null;
}
}
public BitList(List<E> originList, boolean empty, List<E> tailList) {
this.originList = originList;
this.rootSet = new BitSet();
if (!empty) {
this.rootSet.set(0, originList.size());
}
this.tailList = tailList;
}
public BitList(List<E> originList, BitSet rootSet, List<E> tailList) {
this.originList = originList;
this.rootSet = rootSet;
this.tailList = tailList;
}
// Provided by BitList only
public List<E> getOriginList() {
return originList;
}
public void addIndex(int index) {
this.rootSet.set(index);
}
public int totalSetSize() {
return this.originList.size();
}
public boolean indexExist(int index) {
return this.rootSet.get(index);
}
public E getByIndex(int index) {
return this.originList.get(index);
}
/**
* And operation between two bitList. Return a new cloned list.
* TailList in source bitList will be totally saved even if it is not appeared in the target bitList.
*
* @param target target bitList
* @return this bitList only contains those elements contain in both two list and source bitList's tailList
*/
public BitList<E> and(BitList<E> target) {
rootSet.and(target.rootSet);
if (target.getTailList() != null) {
target.getTailList().forEach(this::addToTailList);
}
return this;
}
public BitList<E> or(BitList<E> target) {
BitSet resultSet = (BitSet) rootSet.clone();
resultSet.or(target.rootSet);
return new BitList<>(originList, resultSet, tailList);
}
public boolean hasMoreElementInTailList() {
return CollectionUtils.isNotEmpty(tailList);
}
public List<E> getTailList() {
return tailList;
}
public void addToTailList(E e) {
if (tailList == null) {
tailList = new LinkedList<>();
}
tailList.add(e);
}
public E randomSelectOne() {
int originSize = originList.size();
int tailSize = tailList != null ? tailList.size() : 0;
int totalSize = originSize + tailSize;
int cardinality = rootSet.cardinality();
// example 1 : origin size is 1000, cardinality is 50, rate is 1/20. 20 * 2 = 40 < 50, try random select
// example 2 : origin size is 1000, cardinality is 25, rate is 1/40. 40 * 2 = 80 > 50, directly use iterator
int rate = originSize / cardinality;
if (rate <= cardinality * 2) {
int count = rate * 5;
for (int i = 0; i < count; i++) {
int random = ThreadLocalRandom.current().nextInt(totalSize);
if (random < originSize) {
if (rootSet.get(random)) {
return originList.get(random);
}
} else {
return tailList.get(random - originSize);
}
}
}
return get(ThreadLocalRandom.current().nextInt(cardinality + tailSize));
}
@SuppressWarnings("unchecked")
public static <T> BitList<T> emptyList() {
return emptyList;
}
// Provided by JDK List interface
@Override
public int size() {
return rootSet.cardinality() + (CollectionUtils.isNotEmpty(tailList) ? tailList.size() : 0);
}
@Override
public boolean contains(Object o) {
int idx = originList.indexOf(o);
return (idx >= 0 && rootSet.get(idx)) || (CollectionUtils.isNotEmpty(tailList) && tailList.contains(o));
}
@Override
public Iterator<E> iterator() {
return new BitListIterator<>(this, 0);
}
/**
* If the element to added is appeared in originList even if it is not in rootSet,
* directly set its index in rootSet to true. (This may change the order of elements.)
* <p>
* If the element is not contained in originList, allocate tailList and add to tailList.
* <p>
* Notice: It is not recommended adding duplicated element.
*/
@Override
public boolean add(E e) {
int index = originList.indexOf(e);
if (index > -1) {
rootSet.set(index);
return true;
} else {
if (tailList == null) {
tailList = new LinkedList<>();
}
return tailList.add(e);
}
}
/**
* If the element to added is appeared in originList,
* directly set its index in rootSet to false. (This may change the order of elements.)
* <p>
* If the element is not contained in originList, try to remove from tailList.
*/
@Override
public boolean remove(Object o) {
int idx = originList.indexOf(o);
if (idx > -1 && rootSet.get(idx)) {
rootSet.set(idx, false);
return true;
}
if (CollectionUtils.isNotEmpty(tailList)) {
return tailList.remove(o);
}
return false;
}
/**
* Caution: This operation will clear originList for removing references purpose.
* This may change the default behaviour when adding new element later.
*/
@Override
public void clear() {
rootSet.clear();
// to remove references
originList = Collections.emptyList();
if (CollectionUtils.isNotEmpty(tailList)) {
tailList = null;
}
}
@Override
public E get(int index) {
int bitIndex = -1;
if (index < 0) {
throw new IndexOutOfBoundsException();
}
if (index >= rootSet.cardinality()) {
if (CollectionUtils.isNotEmpty(tailList)) {
return tailList.get(index - rootSet.cardinality());
} else {
throw new IndexOutOfBoundsException();
}
} else {
for (int i = 0; i <= index; i++) {
bitIndex = rootSet.nextSetBit(bitIndex + 1);
}
return originList.get(bitIndex);
}
}
@Override
public E remove(int index) {
int bitIndex = -1;
if (index >= rootSet.cardinality()) {
if (CollectionUtils.isNotEmpty(tailList)) {
return tailList.remove(index - rootSet.cardinality());
} else {
throw new IndexOutOfBoundsException();
}
} else {
for (int i = 0; i <= index; i++) {
bitIndex = rootSet.nextSetBit(bitIndex + 1);
}
rootSet.set(bitIndex, false);
return originList.get(bitIndex);
}
}
@Override
public int indexOf(Object o) {
int bitIndex = -1;
for (int i = 0; i < rootSet.cardinality(); i++) {
bitIndex = rootSet.nextSetBit(bitIndex + 1);
if (originList.get(bitIndex).equals(o)) {
return i;
}
}
if (CollectionUtils.isNotEmpty(tailList)) {
int indexInTailList = tailList.indexOf(o);
if (indexInTailList != -1) {
return indexInTailList + rootSet.cardinality();
} else {
return -1;
}
}
return -1;
}
@Override
@SuppressWarnings("unchecked")
public boolean addAll(Collection<? extends E> c) {
if (c instanceof BitList) {
rootSet.or(((BitList<? extends E>) c).rootSet);
if (((BitList<? extends E>) c).hasMoreElementInTailList()) {
for (E e : ((BitList<? extends E>) c).tailList) {
addToTailList(e);
}
}
return true;
}
return super.addAll(c);
}
@Override
public int lastIndexOf(Object o) {
int bitIndex = -1;
int index = -1;
if (CollectionUtils.isNotEmpty(tailList)) {
int indexInTailList = tailList.lastIndexOf(o);
if (indexInTailList > -1) {
return indexInTailList + rootSet.cardinality();
}
}
for (int i = 0; i < rootSet.cardinality(); i++) {
bitIndex = rootSet.nextSetBit(bitIndex + 1);
if (originList.get(bitIndex).equals(o)) {
index = i;
}
}
return index;
}
@Override
public boolean isEmpty() {
return this.rootSet.isEmpty() && CollectionUtils.isEmpty(tailList);
}
@Override
public ListIterator<E> listIterator() {
return new BitListIterator<>(this, 0);
}
@Override
public ListIterator<E> listIterator(int index) {
return new BitListIterator<>(this, index);
}
@Override
public BitList<E> subList(int fromIndex, int toIndex) {
BitSet resultSet = (BitSet) rootSet.clone();
List<E> copiedTailList = tailList == null ? null : new LinkedList<>(tailList);
if (toIndex < size()) {
if (toIndex < rootSet.cardinality()) {
copiedTailList = null;
resultSet.set(toIndex, resultSet.length(), false);
} else {
copiedTailList =
copiedTailList == null ? null : copiedTailList.subList(0, toIndex - rootSet.cardinality());
}
}
if (fromIndex > 0) {
if (fromIndex < rootSet.cardinality()) {
resultSet.set(0, fromIndex, false);
} else {
resultSet.clear();
copiedTailList = copiedTailList == null
? null
: copiedTailList.subList(fromIndex - rootSet.cardinality(), copiedTailList.size());
}
}
return new BitList<>(originList, resultSet, copiedTailList);
}
public static class BitListIterator<E> implements ListIterator<E> {
private BitList<E> bitList;
private int index;
private ListIterator<E> tailListIterator;
private int curBitIndex = -1;
private boolean isInTailList = false;
private int lastReturnedIndex = -1;
public BitListIterator(BitList<E> bitList, int index) {
this.bitList = bitList;
this.index = index - 1;
for (int i = 0; i < index; i++) {
if (!isInTailList) {
curBitIndex = bitList.rootSet.nextSetBit(curBitIndex + 1);
if (curBitIndex == -1) {
if (CollectionUtils.isNotEmpty(bitList.tailList)) {
isInTailList = true;
tailListIterator = bitList.tailList.listIterator();
tailListIterator.next();
} else {
break;
}
}
} else {
tailListIterator.next();
}
}
}
@Override
public boolean hasNext() {
if (isInTailList) {
return tailListIterator.hasNext();
} else {
int nextBit = bitList.rootSet.nextSetBit(curBitIndex + 1);
if (nextBit == -1) {
return bitList.hasMoreElementInTailList();
} else {
return true;
}
}
}
@Override
public E next() {
if (isInTailList) {
if (tailListIterator.hasNext()) {
index += 1;
lastReturnedIndex = index;
}
return tailListIterator.next();
} else {
int nextBitIndex = bitList.rootSet.nextSetBit(curBitIndex + 1);
if (nextBitIndex == -1) {
if (bitList.hasMoreElementInTailList()) {
tailListIterator = bitList.tailList.listIterator();
isInTailList = true;
index += 1;
lastReturnedIndex = index;
return tailListIterator.next();
} else {
throw new NoSuchElementException();
}
} else {
index += 1;
lastReturnedIndex = index;
curBitIndex = nextBitIndex;
return bitList.originList.get(nextBitIndex);
}
}
}
@Override
public boolean hasPrevious() {
if (isInTailList) {
boolean hasPreviousInTailList = tailListIterator.hasPrevious();
if (hasPreviousInTailList) {
return true;
} else {
return bitList.rootSet.previousSetBit(bitList.rootSet.size()) != -1;
}
} else {
return curBitIndex != -1;
}
}
@Override
public E previous() {
if (isInTailList) {
boolean hasPreviousInTailList = tailListIterator.hasPrevious();
if (hasPreviousInTailList) {
lastReturnedIndex = index;
index -= 1;
return tailListIterator.previous();
} else {
int lastIndexInBit = bitList.rootSet.previousSetBit(bitList.rootSet.size());
if (lastIndexInBit == -1) {
throw new NoSuchElementException();
} else {
isInTailList = false;
curBitIndex = bitList.rootSet.previousSetBit(lastIndexInBit - 1);
lastReturnedIndex = index;
index -= 1;
return bitList.originList.get(lastIndexInBit);
}
}
} else {
if (curBitIndex == -1) {
throw new NoSuchElementException();
}
int nextBitIndex = curBitIndex;
curBitIndex = bitList.rootSet.previousSetBit(curBitIndex - 1);
lastReturnedIndex = index;
index -= 1;
return bitList.originList.get(nextBitIndex);
}
}
@Override
public int nextIndex() {
return hasNext() ? index + 1 : index;
}
@Override
public int previousIndex() {
return index;
}
@Override
public void remove() {
if (lastReturnedIndex == -1) {
throw new IllegalStateException();
} else {
if (lastReturnedIndex >= bitList.rootSet.cardinality()) {
tailListIterator.remove();
} else {
int bitIndex = -1;
for (int i = 0; i <= lastReturnedIndex; i++) {
bitIndex = bitList.rootSet.nextSetBit(bitIndex + 1);
}
bitList.rootSet.set(bitIndex, false);
}
}
if (lastReturnedIndex <= index) {
index -= 1;
}
}
@Override
public void set(E e) {
throw new UnsupportedOperationException("Set method is not supported in BitListIterator!");
}
@Override
public void add(E e) {
throw new UnsupportedOperationException("Add method is not supported in BitListIterator!");
}
}
public ArrayList<E> cloneToArrayList() {
if (rootSet.cardinality() == originList.size() && (CollectionUtils.isEmpty(tailList))) {
return new ArrayList<>(originList);
}
ArrayList<E> arrayList = new ArrayList<>(size());
arrayList.addAll(this);
return arrayList;
}
@Override
public BitList<E> clone() {
return new BitList<>(
originList, (BitSet) rootSet.clone(), tailList == null ? null : new LinkedList<>(tailList));
}
}
| 7,959 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/AbstractStateRouter.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.rpc.cluster.router.state;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Constants;
import org.apache.dubbo.rpc.cluster.governance.GovernanceRuleRepository;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.model.ModuleModel;
/***
* The abstract class of StateRoute.
* @since 3.0
*/
public abstract class AbstractStateRouter<T> implements StateRouter<T> {
private volatile boolean force = false;
private volatile URL url;
private volatile StateRouter<T> nextRouter = null;
private final GovernanceRuleRepository ruleRepository;
/**
* Should continue route if current router's result is empty
*/
private final boolean shouldFailFast;
protected ModuleModel moduleModel;
public AbstractStateRouter(URL url) {
moduleModel = url.getOrDefaultModuleModel();
this.ruleRepository =
moduleModel.getExtensionLoader(GovernanceRuleRepository.class).getDefaultExtension();
this.url = url;
this.shouldFailFast = Boolean.parseBoolean(
ConfigurationUtils.getProperty(moduleModel, Constants.SHOULD_FAIL_FAST_KEY, "true"));
}
@Override
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
@Override
public boolean isRuntime() {
return true;
}
@Override
public boolean isForce() {
return force;
}
public void setForce(boolean force) {
this.force = force;
}
public GovernanceRuleRepository getRuleRepository() {
return this.ruleRepository;
}
public StateRouter<T> getNextRouter() {
return nextRouter;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
// default empty implement
}
@Override
public final BitList<Invoker<T>> route(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder)
throws RpcException {
if (needToPrintMessage && (nodeHolder == null || nodeHolder.get() == null)) {
needToPrintMessage = false;
}
RouterSnapshotNode<T> currentNode = null;
RouterSnapshotNode<T> parentNode = null;
Holder<String> messageHolder = null;
// pre-build current node
if (needToPrintMessage) {
parentNode = nodeHolder.get();
currentNode = new RouterSnapshotNode<>(this.getClass().getSimpleName(), invokers.clone());
parentNode.appendNode(currentNode);
// set parent node's output size in the first child invoke
// initial node output size is zero, first child will override it
if (parentNode.getNodeOutputSize() < invokers.size()) {
parentNode.setNodeOutputInvokers(invokers.clone());
}
messageHolder = new Holder<>();
nodeHolder.set(currentNode);
}
BitList<Invoker<T>> routeResult;
routeResult = doRoute(invokers, url, invocation, needToPrintMessage, nodeHolder, messageHolder);
if (routeResult != invokers) {
routeResult = invokers.and(routeResult);
}
// check if router support call continue route by itself
if (!supportContinueRoute()) {
// use current node's result as next node's parameter
if (!shouldFailFast || !routeResult.isEmpty()) {
routeResult = continueRoute(routeResult, url, invocation, needToPrintMessage, nodeHolder);
}
}
// post-build current node
if (needToPrintMessage) {
currentNode.setRouterMessage(messageHolder.get());
if (currentNode.getNodeOutputSize() == 0) {
// no child call
currentNode.setNodeOutputInvokers(routeResult.clone());
}
currentNode.setChainOutputInvokers(routeResult.clone());
nodeHolder.set(parentNode);
}
return routeResult;
}
/**
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
*
* @param invokers all invokers to be routed
* @param url consumerUrl
* @param invocation invocation
* @param needToPrintMessage should current router print message
* @param nodeHolder RouterSnapshotNode In general, router itself no need to care this param, just pass to continueRoute
* @param messageHolder message holder when router should current router print message
* @return routed result
*/
protected abstract BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException;
/**
* Call next router to get result
*
* @param invokers current router filtered invokers
*/
protected final BitList<Invoker<T>> continueRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder) {
if (nextRouter != null) {
return nextRouter.route(invokers, url, invocation, needToPrintMessage, nodeHolder);
} else {
return invokers;
}
}
/**
* Whether current router's implementation support call
* {@link AbstractStateRouter#continueRoute(BitList, URL, Invocation, boolean, Holder)}
* by router itself.
*
* @return support or not
*/
protected boolean supportContinueRoute() {
return false;
}
/**
* Next Router node state is maintained by AbstractStateRouter and this method is not allow to override.
* If a specified router wants to control the behaviour of continue route or not,
* please override {@link AbstractStateRouter#supportContinueRoute()}
*/
@Override
public final void setNextRouter(StateRouter<T> nextRouter) {
this.nextRouter = nextRouter;
}
@Override
public final String buildSnapshot() {
return doBuildSnapshot() + " v \n" + nextRouter.buildSnapshot();
}
protected String doBuildSnapshot() {
return this.getClass().getSimpleName() + " not support\n";
}
}
| 7,960 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/RouterGroupingState.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.rpc.cluster.router.state;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import java.util.Map;
import java.util.stream.Collectors;
public class RouterGroupingState<T> {
private final String routerName;
private final int total;
private final Map<String, BitList<Invoker<T>>> grouping;
public RouterGroupingState(String routerName, int total, Map<String, BitList<Invoker<T>>> grouping) {
this.routerName = routerName;
this.total = total;
this.grouping = grouping;
}
public String getRouterName() {
return routerName;
}
public int getTotal() {
return total;
}
public Map<String, BitList<Invoker<T>>> getGrouping() {
return grouping;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(routerName)
.append(' ')
.append(" Total: ")
.append(total)
.append("\n");
for (Map.Entry<String, BitList<Invoker<T>>> entry : grouping.entrySet()) {
BitList<Invoker<T>> invokers = entry.getValue();
stringBuilder
.append("[ ")
.append(entry.getKey())
.append(" -> ")
.append(
invokers.isEmpty()
? "Empty"
: invokers.stream()
.limit(5)
.map(Invoker::getUrl)
.map(URL::getAddress)
.collect(Collectors.joining(",")))
.append(invokers.size() > 5 ? "..." : "")
.append(" (Total: ")
.append(invokers.size())
.append(") ]")
.append("\n");
}
return stringBuilder.toString();
}
}
| 7,961 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/state/StateRouter.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.rpc.cluster.router.state;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
/**
* State Router. (SPI, Prototype, ThreadSafe)
* <p>
* <a href="http://en.wikipedia.org/wiki/Routing">Routing</a>
*
* It is recommended to implement StateRouter by extending {@link AbstractStateRouter}
*
* @see org.apache.dubbo.rpc.cluster.Cluster#join(Directory, boolean)
* @see AbstractStateRouter
* @see Directory#list(Invocation)
* @since 3.0
*/
public interface StateRouter<T> {
/**
* Get the router url.
*
* @return url
*/
URL getUrl();
/***
* Filter invokers with current routing rule and only return the invokers that comply with the rule.
* Caching address lists in BitMap mode improves routing performance.
* @param invokers invoker bit list
* @param url refer url
* @param invocation invocation
* @param needToPrintMessage whether to print router state. Such as `use router branch a`.
* @return state with route result
* @since 3.0
*/
BitList<Invoker<T>> route(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder)
throws RpcException;
/**
* To decide whether this router need to execute every time an RPC comes or should only execute when addresses or
* rule change.
*
* @return true if the router need to execute every time.
*/
boolean isRuntime();
/**
* To decide whether this router should take effect when none of the invoker can match the router rule, which
* means the {@link #route(BitList, URL, Invocation, boolean, Holder)} would be empty. Most of time, most router implementation would
* default this value to false.
*
* @return true to execute if none of invokers matches the current router
*/
boolean isForce();
/**
* Notify the router the invoker list. Invoker list may change from time to time. This method gives the router a
* chance to prepare before {@link StateRouter#route(BitList, URL, Invocation, boolean, Holder)} gets called.
* No need to notify next node.
*
* @param invokers invoker list
*/
void notify(BitList<Invoker<T>> invokers);
/**
* Build Router's Current State Snapshot for QoS
*
* @return Current State
*/
String buildSnapshot();
default void stop() {
// do nothing by default
}
/**
* Notify next router node to current router.
*
* @param nextRouter next router node
*/
void setNextRouter(StateRouter<T> nextRouter);
}
| 7,962 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouterFactory.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.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
* ScriptRouterFactory
* <p>
* Example URLS used by Script Router Factory:
* <ol>
* <li> script://registryAddress?type=js&rule=xxxx
* <li> script:///path/to/routerfile.js?type=js&rule=xxxx
* <li> script://D:\path\to\routerfile.js?type=js&rule=xxxx
* <li> script://C:/path/to/routerfile.js?type=js&rule=xxxx
* </ol>
* The host value in URL points out the address of the source content of the Script Router,Registry、File etc
*
*/
public class ScriptStateRouterFactory implements StateRouterFactory {
public static final String NAME = "script";
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
return new ScriptStateRouter<>(url);
}
}
| 7,963 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/ScriptStateRouter.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.rpc.cluster.router.script;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.support.RpcUtils;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_SCRIPT_EXCEPTION;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_SCRIPT_TYPE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
/**
* ScriptRouter
*/
public class ScriptStateRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "SCRIPT_ROUTER";
private static final int SCRIPT_ROUTER_DEFAULT_PRIORITY = 0;
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ScriptStateRouter.class);
private static final ConcurrentMap<String, ScriptEngine> ENGINES = new ConcurrentHashMap<>();
private final ScriptEngine engine;
private final String rule;
private CompiledScript function;
private AccessControlContext accessControlContext;
{
// Just give permission of reflect to access member.
Permissions perms = new Permissions();
perms.add(new RuntimePermission("accessDeclaredMembers"));
// Cast to Certificate[] required because of ambiguity:
ProtectionDomain domain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), perms);
accessControlContext = new AccessControlContext(new ProtectionDomain[] {domain});
}
public ScriptStateRouter(URL url) {
super(url);
this.setUrl(url);
engine = getEngine(url);
rule = getRule(url);
try {
Compilable compilable = (Compilable) engine;
function = compilable.compile(rule);
} catch (ScriptException e) {
logger.error(
CLUSTER_SCRIPT_EXCEPTION,
"script route rule invalid",
"",
"script route error, rule has been ignored. rule: " + rule + ", url: "
+ RpcContext.getServiceContext().getUrl(),
e);
}
}
/**
* get rule from url parameters.
*/
private String getRule(URL url) {
String vRule = url.getParameterAndDecoded(RULE_KEY);
if (StringUtils.isEmpty(vRule)) {
throw new IllegalStateException("route rule can not be empty.");
}
return vRule;
}
/**
* create ScriptEngine instance by type from url parameters, then cache it
*/
private ScriptEngine getEngine(URL url) {
String type = url.getParameter(TYPE_KEY, DEFAULT_SCRIPT_TYPE_KEY);
return ConcurrentHashMapUtils.computeIfAbsent(ENGINES, type, t -> {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(type);
if (scriptEngine == null) {
throw new IllegalStateException("unsupported route engine type: " + type);
}
return scriptEngine;
});
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (engine == null || function == null) {
if (needToPrintMessage) {
messageHolder.set("Directly Return. Reason: engine or function is null");
}
return invokers;
}
Bindings bindings = createBindings(invokers, invocation);
return getRoutedInvokers(
invokers,
AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> {
try {
return function.eval(bindings);
} catch (ScriptException e) {
logger.error(
CLUSTER_SCRIPT_EXCEPTION,
"Scriptrouter exec script error",
"",
"Script route error, rule has been ignored. rule: " + rule + ", method:"
+ RpcUtils.getMethodName(invocation) + ", url: "
+ RpcContext.getContext().getUrl(),
e);
return invokers;
}
},
accessControlContext));
}
/**
* get routed invokers from result of script rule evaluation
*/
@SuppressWarnings("unchecked")
protected BitList<Invoker<T>> getRoutedInvokers(BitList<Invoker<T>> invokers, Object obj) {
BitList<Invoker<T>> result = invokers.clone();
if (obj instanceof Invoker[]) {
result.retainAll(Arrays.asList((Invoker<T>[]) obj));
} else if (obj instanceof Object[]) {
result.retainAll(
Arrays.stream((Object[]) obj).map(item -> (Invoker<T>) item).collect(Collectors.toList()));
} else {
result.retainAll((List<Invoker<T>>) obj);
}
return result;
}
/**
* create bindings for script engine
*/
private Bindings createBindings(List<Invoker<T>> invokers, Invocation invocation) {
Bindings bindings = engine.createBindings();
// create a new List of invokers
bindings.put("invokers", new ArrayList<>(invokers));
bindings.put("invocation", invocation);
bindings.put("context", RpcContext.getClientAttachment());
return bindings;
}
@Override
public boolean isRuntime() {
return this.getUrl().getParameter(RUNTIME_KEY, false);
}
@Override
public boolean isForce() {
return this.getUrl().getParameter(FORCE_KEY, false);
}
}
| 7,964 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptStateRouter.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.rpc.cluster.router.script.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.script.ScriptStateRouter;
import org.apache.dubbo.rpc.cluster.router.script.config.model.ScriptRule;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_INVALID;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_SCRIPT_TYPE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY;
public class AppScriptStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AppScriptStateRouter.class);
private static final String RULE_SUFFIX = ".script-router";
private ScriptRule scriptRule;
private ScriptStateRouter<T> scriptRouter;
private String application;
public AppScriptStateRouter(URL url) {
super(url);
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> routerSnapshotNodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (scriptRouter == null || !scriptRule.isValid() || !scriptRule.isEnabled()) {
if (needToPrintMessage) {
messageHolder.set(
"Directly return from script router. Reason: Invokers from previous router is empty or script is not enabled. Script rule is: "
+ (scriptRule == null ? "null" : scriptRule.getRawRule()));
}
return invokers;
}
invokers = scriptRouter.route(invokers, url, invocation, needToPrintMessage, routerSnapshotNodeHolder);
if (needToPrintMessage) {
messageHolder.set(messageHolder.get());
}
return invokers;
}
@Override
public synchronized void process(ConfigChangedEvent event) {
if (logger.isDebugEnabled()) {
logger.debug("Notification of script rule change, type is: " + event.getChangeType() + ", raw rule is:\n "
+ event.getContent());
}
try {
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
this.scriptRule = null;
} else {
this.scriptRule = ScriptRule.parse(event.getContent());
URL scriptUrl = getUrl().addParameter(
TYPE_KEY,
isEmpty(scriptRule.getType()) ? DEFAULT_SCRIPT_TYPE_KEY : scriptRule.getType())
.addParameterAndEncoded(RULE_KEY, scriptRule.getScript())
.addParameter(FORCE_KEY, scriptRule.isForce())
.addParameter(RUNTIME_KEY, scriptRule.isRuntime());
scriptRouter = new ScriptStateRouter<>(scriptUrl);
}
} catch (Exception e) {
logger.error(
CLUSTER_TAG_ROUTE_INVALID,
"Failed to parse the raw tag router rule",
"",
"Failed to parse the raw tag router rule and it will not take effect, please check if the "
+ "rule matches with the template, the raw rule is:\n ",
e);
}
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
if (CollectionUtils.isEmpty(invokers)) {
return;
}
Invoker<T> invoker = invokers.get(0);
URL url = invoker.getUrl();
String providerApplication = url.getRemoteApplication();
if (isEmpty(providerApplication)) {
logger.error(
CLUSTER_TAG_ROUTE_EMPTY,
"tag router get providerApplication is empty",
"",
"TagRouter must getConfig from or subscribe to a specific application, but the application "
+ "in this TagRouter is not specified.");
return;
}
synchronized (this) {
if (!providerApplication.equals(application)) {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
String key = providerApplication + RULE_SUFFIX;
this.getRuleRepository().addListener(key, this);
application = providerApplication;
String rawRule = this.getRuleRepository().getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
}
}
}
}
@Override
public void stop() {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
}
// for testing purpose
public void setScriptRule(ScriptRule scriptRule) {
this.scriptRule = scriptRule;
}
}
| 7,965 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/AppScriptRouterFactory.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.rpc.cluster.router.script.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
@Activate(order = 200)
public class AppScriptRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "script";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new AppScriptStateRouter<>(url);
}
}
| 7,966 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/script/config/model/ScriptRule.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.rpc.cluster.router.script.config.model;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
public class ScriptRule extends AbstractRouterRule {
private static final String TYPE_KEY = "type";
private static final String SCRIPT_KEY = "script";
private String type;
private String script;
public static ScriptRule parse(String rawRule) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
ScriptRule rule = new ScriptRule();
rule.parseFromMap0(map);
rule.setRawRule(rawRule);
Object rawType = map.get(TYPE_KEY);
if (rawType != null) {
rule.setType((String) rawType);
}
Object rawScript = map.get(SCRIPT_KEY);
if (rawScript != null) {
rule.setScript((String) rawScript);
} else {
rule.setValid(false);
}
return rule;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
}
| 7,967 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouter.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.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
import static org.apache.dubbo.rpc.cluster.Constants.FORCE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.RUNTIME_KEY;
/**
* Condition Router directs traffics matching the 'when condition' to a particular address subset determined by the 'then condition'.
* One typical condition rule is like below, with
* 1. the 'when condition' on the left side of '=>' contains matching rule like 'method=sayHello' and 'method=sayHi'
* 2. the 'then condition' on the right side of '=>' contains matching rule like 'region=hangzhou' and 'address=*:20881'
* <p>
* By default, condition router support matching rules like 'foo=bar', 'foo=bar*', 'arguments[0]=bar', 'attachments[foo]=bar', 'attachments[foo]=1~100', etc.
* It's also very easy to add customized matching rules by extending {@link ConditionMatcherFactory}
* and {@link ValuePattern}
* <p>
* ---
* scope: service
* force: true
* runtime: true
* enabled: true
* key: org.apache.dubbo.samples.governance.api.DemoService
* conditions:
* - method=sayHello => region=hangzhou
* - method=sayHi => address=*:20881
* ...
*/
public class ConditionStateRouter<T> extends AbstractStateRouter<T> {
public static final String NAME = "condition";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractStateRouter.class);
protected static final Pattern ROUTE_PATTERN = Pattern.compile("([&!=,]*)\\s*([^&!=,\\s]+)");
protected Map<String, ConditionMatcher> whenCondition;
protected Map<String, ConditionMatcher> thenCondition;
protected List<ConditionMatcherFactory> matcherFactories;
private final boolean enabled;
public ConditionStateRouter(URL url, String rule, boolean force, boolean enabled) {
super(url);
this.setForce(force);
this.enabled = enabled;
matcherFactories =
moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions();
if (enabled) {
this.init(rule);
}
}
public ConditionStateRouter(URL url) {
super(url);
this.setUrl(url);
this.setForce(url.getParameter(FORCE_KEY, false));
matcherFactories =
moduleModel.getExtensionLoader(ConditionMatcherFactory.class).getActivateExtensions();
this.enabled = url.getParameter(ENABLED_KEY, true);
if (enabled) {
init(url.getParameterAndDecoded(RULE_KEY));
}
}
public void init(String rule) {
try {
if (rule == null || rule.trim().length() == 0) {
throw new IllegalArgumentException("Illegal route rule!");
}
rule = rule.replace("consumer.", "").replace("provider.", "");
int i = rule.indexOf("=>");
String whenRule = i < 0 ? null : rule.substring(0, i).trim();
String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
Map<String, ConditionMatcher> when =
StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<>() : parseRule(whenRule);
Map<String, ConditionMatcher> then =
StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
// NOTE: It should be determined on the business level whether the `When condition` can be empty or not.
this.whenCondition = when;
this.thenCondition = then;
} catch (ParseException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private Map<String, ConditionMatcher> parseRule(String rule) throws ParseException {
Map<String, ConditionMatcher> condition = new HashMap<>();
if (StringUtils.isBlank(rule)) {
return condition;
}
// Key-Value pair, stores both match and mismatch conditions
ConditionMatcher matcherPair = null;
// Multiple values
Set<String> values = null;
final Matcher matcher = ROUTE_PATTERN.matcher(rule);
while (matcher.find()) { // Try to match one by one
String separator = matcher.group(1);
String content = matcher.group(2);
// Start part of the condition expression.
if (StringUtils.isEmpty(separator)) {
matcherPair = this.getMatcher(content);
condition.put(content, matcherPair);
}
// The KV part of the condition expression
else if ("&".equals(separator)) {
if (condition.get(content) == null) {
matcherPair = this.getMatcher(content);
condition.put(content, matcherPair);
} else {
matcherPair = condition.get(content);
}
}
// The Value in the KV part.
else if ("=".equals(separator)) {
if (matcherPair == null) {
throw new ParseException(
"Illegal route rule \""
+ rule + "\", The error char '" + separator
+ "' at index " + matcher.start() + " before \""
+ content + "\".",
matcher.start());
}
values = matcherPair.getMatches();
values.add(content);
}
// The Value in the KV part.
else if ("!=".equals(separator)) {
if (matcherPair == null) {
throw new ParseException(
"Illegal route rule \""
+ rule + "\", The error char '" + separator
+ "' at index " + matcher.start() + " before \""
+ content + "\".",
matcher.start());
}
values = matcherPair.getMismatches();
values.add(content);
}
// The Value in the KV part, if Value have more than one items.
else if (",".equals(separator)) { // Should be separated by ','
if (values == null || values.isEmpty()) {
throw new ParseException(
"Illegal route rule \""
+ rule + "\", The error char '" + separator
+ "' at index " + matcher.start() + " before \""
+ content + "\".",
matcher.start());
}
values.add(content);
} else {
throw new ParseException(
"Illegal route rule \"" + rule
+ "\", The error char '" + separator + "' at index "
+ matcher.start() + " before \"" + content + "\".",
matcher.start());
}
}
return condition;
}
@Override
protected BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (!enabled) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: ConditionRouter disabled.");
}
return invokers;
}
if (CollectionUtils.isEmpty(invokers)) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: Invokers from previous router is empty.");
}
return invokers;
}
try {
if (!matchWhen(url, invocation)) {
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: WhenCondition not match.");
}
return invokers;
}
if (thenCondition == null) {
logger.warn(
CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,
"condition state router thenCondition is empty",
"",
"The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost()
+ ", service: " + url.getServiceKey());
if (needToPrintMessage) {
messageHolder.set("Empty return. Reason: ThenCondition is empty.");
}
return BitList.emptyList();
}
BitList<Invoker<T>> result = invokers.clone();
result.removeIf(invoker -> !matchThen(invoker.getUrl(), url));
if (!result.isEmpty()) {
if (needToPrintMessage) {
messageHolder.set("Match return.");
}
return result;
} else if (this.isForce()) {
logger.warn(
CLUSTER_CONDITIONAL_ROUTE_LIST_EMPTY,
"execute condition state router result list is empty. and force=true",
"",
"The route result is empty and force execute. consumer: " + NetUtils.getLocalHost()
+ ", service: " + url.getServiceKey() + ", router: "
+ url.getParameterAndDecoded(RULE_KEY));
if (needToPrintMessage) {
messageHolder.set("Empty return. Reason: Empty result from condition and condition is force.");
}
return result;
}
} catch (Throwable t) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"execute condition state router exception",
"",
"Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: "
+ t.getMessage(),
t);
}
if (needToPrintMessage) {
messageHolder.set("Directly return. Reason: Error occurred ( or result is empty ).");
}
return invokers;
}
@Override
public boolean isRuntime() {
// We always return true for previously defined Router, that is, old Router doesn't support cache anymore.
// return true;
return this.getUrl().getParameter(RUNTIME_KEY, false);
}
private ConditionMatcher getMatcher(String key) {
for (ConditionMatcherFactory factory : matcherFactories) {
if (factory.shouldMatch(key)) {
return factory.createMatcher(key, moduleModel);
}
}
return moduleModel
.getExtensionLoader(ConditionMatcherFactory.class)
.getExtension("param")
.createMatcher(key, moduleModel);
}
boolean matchWhen(URL url, Invocation invocation) {
if (CollectionUtils.isEmptyMap(whenCondition)) {
return true;
}
return doMatch(url, null, invocation, whenCondition, true);
}
private boolean matchThen(URL url, URL param) {
if (CollectionUtils.isEmptyMap(thenCondition)) {
return false;
}
return doMatch(url, param, null, thenCondition, false);
}
private boolean doMatch(
URL url,
URL param,
Invocation invocation,
Map<String, ConditionMatcher> conditions,
boolean isWhenCondition) {
Map<String, String> sample = url.toOriginalMap();
for (Map.Entry<String, ConditionMatcher> entry : conditions.entrySet()) {
ConditionMatcher matchPair = entry.getValue();
if (!matchPair.isMatch(sample, param, invocation, isWhenCondition)) {
return false;
}
}
return true;
}
}
| 7,968 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/ConditionStateRouterFactory.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.rpc.cluster.router.condition;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* ConditionRouterFactory
* Load when "override://" is configured {@link ConditionStateRouter}
*/
public class ConditionStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "condition";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new ConditionStateRouter<T>(url);
}
}
| 7,969 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ListenableStateRouter.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouter;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRouterRule;
import org.apache.dubbo.rpc.cluster.router.condition.config.model.ConditionRuleParser;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.state.TailStateRouter;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RULE_PARSING;
/**
* Abstract router which listens to dynamic configuration
*/
public abstract class ListenableStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
public static final String NAME = "LISTENABLE_ROUTER";
public static final String RULE_SUFFIX = ".condition-router";
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class);
private volatile ConditionRouterRule routerRule;
private volatile List<ConditionStateRouter<T>> conditionRouters = Collections.emptyList();
private final String ruleKey;
public ListenableStateRouter(URL url, String ruleKey) {
super(url);
this.setForce(false);
this.init(ruleKey);
this.ruleKey = ruleKey;
}
@Override
public synchronized void process(ConfigChangedEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Notification of condition rule, change type is: " + event.getChangeType() + ", raw rule is:\n "
+ event.getContent());
}
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
routerRule = null;
conditionRouters = Collections.emptyList();
} else {
try {
routerRule = ConditionRuleParser.parse(event.getContent());
generateConditions(routerRule);
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_RULE_PARSING,
"Failed to parse the raw condition rule",
"",
"Failed to parse the raw condition rule and it will not take effect, please check "
+ "if the condition rule matches with the template, the raw rule is:\n "
+ event.getContent(),
e);
}
}
}
@Override
public BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (CollectionUtils.isEmpty(invokers) || conditionRouters.size() == 0) {
if (needToPrintMessage) {
messageHolder.set(
"Directly return. Reason: Invokers from previous router is empty or conditionRouters is empty.");
}
return invokers;
}
// We will check enabled status inside each router.
StringBuilder resultMessage = null;
if (needToPrintMessage) {
resultMessage = new StringBuilder();
}
for (AbstractStateRouter<T> router : conditionRouters) {
invokers = router.route(invokers, url, invocation, needToPrintMessage, nodeHolder);
if (needToPrintMessage) {
resultMessage.append(messageHolder.get());
}
}
if (needToPrintMessage) {
messageHolder.set(resultMessage.toString());
}
return invokers;
}
@Override
public boolean isForce() {
return (routerRule != null && routerRule.isForce());
}
private boolean isRuleRuntime() {
return routerRule != null && routerRule.isValid() && routerRule.isRuntime();
}
private void generateConditions(ConditionRouterRule rule) {
if (rule != null && rule.isValid()) {
this.conditionRouters = rule.getConditions().stream()
.map(condition ->
new ConditionStateRouter<T>(getUrl(), condition, rule.isForce(), rule.isEnabled()))
.collect(Collectors.toList());
for (ConditionStateRouter<T> conditionRouter : this.conditionRouters) {
conditionRouter.setNextRouter(TailStateRouter.getInstance());
}
}
}
private synchronized void init(String ruleKey) {
if (StringUtils.isEmpty(ruleKey)) {
return;
}
String routerKey = ruleKey + RULE_SUFFIX;
this.getRuleRepository().addListener(routerKey, this);
String rule = this.getRuleRepository().getRule(routerKey, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rule)) {
this.process(new ConfigChangedEvent(routerKey, DynamicConfiguration.DEFAULT_GROUP, rule));
}
}
@Override
public void stop() {
this.getRuleRepository().removeListener(ruleKey + RULE_SUFFIX, this);
}
}
| 7,970 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouter.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_EMPTY;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
/**
* Application level router, "application.condition-router"
*/
public class ProviderAppStateRouter<T> extends ListenableStateRouter<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenableStateRouter.class);
public static final String NAME = "PROVIDER_APP_ROUTER";
private String application;
private final String currentApplication;
public ProviderAppStateRouter(URL url) {
super(url, url.getApplication());
this.currentApplication = url.getApplication();
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
if (CollectionUtils.isEmpty(invokers)) {
return;
}
Invoker<T> invoker = invokers.get(0);
URL url = invoker.getUrl();
String providerApplication = url.getRemoteApplication();
// provider application is empty or equals with the current application
if (isEmpty(providerApplication)) {
logger.warn(
CLUSTER_TAG_ROUTE_EMPTY,
"condition router get providerApplication is empty, will not subscribe to provider app rules.",
"",
"");
return;
}
if (providerApplication.equals(currentApplication)) {
return;
}
synchronized (this) {
if (!providerApplication.equals(application)) {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
String key = providerApplication + RULE_SUFFIX;
this.getRuleRepository().addListener(key, this);
application = providerApplication;
String rawRule = this.getRuleRepository().getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
}
}
}
}
}
| 7,971 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ProviderAppStateRouterFactory.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* Tag router factory
*/
@Activate(order = 145)
public class ProviderAppStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "provider-app";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new ProviderAppStateRouter<>(url);
}
}
| 7,972 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouter.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
/**
* Application level router, "application.condition-router"
*/
public class AppStateRouter<T> extends ListenableStateRouter<T> {
public static final String NAME = "APP_ROUTER";
public AppStateRouter(URL url) {
super(url, url.getApplication());
}
}
| 7,973 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouterFactory.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* Service level router factory
* ServiceRouter should before AppRouter
*/
@Activate(order = 140)
public class ServiceStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "service";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new ServiceStateRouter<T>(url);
}
}
| 7,974 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/AppStateRouterFactory.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory;
/**
* Application level router factory
* AppRouter should after ServiceRouter
*/
@Activate(order = 150)
public class AppStateRouterFactory implements StateRouterFactory {
public static final String NAME = "app";
@SuppressWarnings("rawtypes")
private volatile StateRouter router;
@SuppressWarnings("unchecked")
@Override
public <T> StateRouter<T> getRouter(Class<T> interfaceClass, URL url) {
if (router != null) {
return router;
}
synchronized (this) {
if (router == null) {
router = createRouter(url);
}
}
return router;
}
private <T> StateRouter<T> createRouter(URL url) {
return new AppStateRouter<>(url);
}
}
| 7,975 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/ServiceStateRouter.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.rpc.cluster.router.condition.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
/**
* Service level router, "server-unique-name.condition-router"
*/
public class ServiceStateRouter<T> extends ListenableStateRouter<T> {
public static final String NAME = "SERVICE_ROUTER";
public ServiceStateRouter(URL url) {
super(url, DynamicConfiguration.getRuleKey(url));
}
}
| 7,976 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRouterRule.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.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.cluster.Constants.CONDITIONS_KEY;
public class ConditionRouterRule extends AbstractRouterRule {
private List<String> conditions;
@SuppressWarnings("unchecked")
public static ConditionRouterRule parseFromMap(Map<String, Object> map) {
ConditionRouterRule conditionRouterRule = new ConditionRouterRule();
conditionRouterRule.parseFromMap0(map);
Object conditions = map.get(CONDITIONS_KEY);
if (conditions != null && List.class.isAssignableFrom(conditions.getClass())) {
conditionRouterRule.setConditions(
((List<Object>) conditions).stream().map(String::valueOf).collect(Collectors.toList()));
}
return conditionRouterRule;
}
public ConditionRouterRule() {}
public List<String> getConditions() {
return conditions;
}
public void setConditions(List<String> conditions) {
this.conditions = conditions;
}
}
| 7,977 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/config/model/ConditionRuleParser.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.rpc.cluster.router.condition.config.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/**
* %YAML1.2
*
* scope: application
* runtime: true
* force: false
* conditions:
* - >
* method!=sayHello =>
* - >
* ip=127.0.0.1
* =>
* 1.1.1.1
*/
public class ConditionRuleParser {
public static ConditionRouterRule parse(String rawRule) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
ConditionRouterRule rule = ConditionRouterRule.parseFromMap(map);
rule.setRawRule(rawRule);
if (CollectionUtils.isEmpty(rule.getConditions())) {
rule.setValid(false);
}
return rule;
}
}
| 7,978 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcher.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.rpc.cluster.router.condition.matcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import java.util.Map;
import java.util.Set;
/**
* ConditionMatcher represents a specific match condition of a condition rule.
* <p>
* The following condition rule '=bar&arguments[0]=hello* => region=hangzhou' consists of three ConditionMatchers:
* 1. UrlParamConditionMatcher represented by 'foo=bar'
* 2. ArgumentsConditionMatcher represented by 'arguments[0]=hello*'
* 3. UrlParamConditionMatcher represented by 'region=hangzhou'
* <p>
* It's easy to define your own matcher by extending {@link ConditionMatcherFactory}
*/
public interface ConditionMatcher {
/**
* Determines if the patterns of this matcher matches with request context.
*
* @param sample request context in provider url
* @param param request context in consumer url
* @param invocation request context in invocation, typically, service, method, arguments and attachments
* @param isWhenCondition condition type
* @return the matching result
*/
boolean isMatch(Map<String, String> sample, URL param, Invocation invocation, boolean isWhenCondition);
/**
* match patterns extracted from when condition
*
* @return
*/
Set<String> getMatches();
/**
* mismatch patterns extracted from then condition
*
* @return
*/
Set<String> getMismatches();
}
| 7,979 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/AbstractConditionMatcher.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.rpc.cluster.router.condition.matcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* The abstract implementation of ConditionMatcher, records the match and mismatch patterns of this matcher while at the same time
* provides the common match logics.
*/
public abstract class AbstractConditionMatcher implements ConditionMatcher {
public static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractConditionMatcher.class);
public static final String DOES_NOT_FOUND_VALUE = "dubbo_internal_not_found_argument_condition_value";
final Set<String> matches = new HashSet<>();
final Set<String> mismatches = new HashSet<>();
private final ModuleModel model;
private final List<ValuePattern> valueMatchers;
protected final String key;
public AbstractConditionMatcher(String key, ModuleModel model) {
this.key = key;
this.model = model;
this.valueMatchers = model.getExtensionLoader(ValuePattern.class).getActivateExtensions();
}
public static String getSampleValueFromUrl(
String conditionKey, Map<String, String> sample, URL param, Invocation invocation) {
String sampleValue;
// get real invoked method name from invocation
if (invocation != null && (METHOD_KEY.equals(conditionKey) || METHODS_KEY.equals(conditionKey))) {
sampleValue = RpcUtils.getMethodName(invocation);
} else {
sampleValue = sample.get(conditionKey);
}
return sampleValue;
}
public boolean isMatch(Map<String, String> sample, URL param, Invocation invocation, boolean isWhenCondition) {
String value = getValue(sample, param, invocation);
if (value == null) {
// if key does not present in whichever of url, invocation or attachment based on the matcher type, then
// return false.
return false;
}
if (!matches.isEmpty() && mismatches.isEmpty()) {
for (String match : matches) {
if (doPatternMatch(match, value, param, invocation, isWhenCondition)) {
return true;
}
}
return false;
}
if (!mismatches.isEmpty() && matches.isEmpty()) {
for (String mismatch : mismatches) {
if (doPatternMatch(mismatch, value, param, invocation, isWhenCondition)) {
return false;
}
}
return true;
}
if (!matches.isEmpty() && !mismatches.isEmpty()) {
// when both mismatches and matches contain the same value, then using mismatches first
for (String mismatch : mismatches) {
if (doPatternMatch(mismatch, value, param, invocation, isWhenCondition)) {
return false;
}
}
for (String match : matches) {
if (doPatternMatch(match, value, param, invocation, isWhenCondition)) {
return true;
}
}
return false;
}
return false;
}
@Override
public Set<String> getMatches() {
return matches;
}
@Override
public Set<String> getMismatches() {
return mismatches;
}
// range, equal or other methods
protected boolean doPatternMatch(
String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) {
for (ValuePattern valueMatcher : valueMatchers) {
if (valueMatcher.shouldMatch(pattern)) {
return valueMatcher.match(pattern, value, url, invocation, isWhenCondition);
}
}
// this should never happen.
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Executing condition rule value match expression error.",
"pattern is " + pattern + ", value is " + value + ", condition type "
+ (isWhenCondition ? "when" : "then"),
"There should at least has one ValueMatcher instance that applies to all patterns, will force to use wildcard matcher now.");
ValuePattern paramValueMatcher =
model.getExtensionLoader(ValuePattern.class).getExtension("wildcard");
return paramValueMatcher.match(pattern, value, url, invocation, isWhenCondition);
}
/**
* Used to get value from different places of the request context, for example, url, attachment and invocation.
* This makes condition rule possible to check values in any place of a request.
*/
protected abstract String getValue(Map<String, String> sample, URL url, Invocation invocation);
}
| 7,980 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcherFactory.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.rpc.cluster.router.condition.matcher;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ModuleModel;
/**
* Factory of ConditionMatcher instances.
*/
@SPI
public interface ConditionMatcherFactory {
/**
* Check if the key is of the form of the current matcher type which this factory instance represents..
*
* @param key the key of a particular form
* @return true if matches, otherwise false
*/
boolean shouldMatch(String key);
/**
* Create a matcher instance for the key.
*
* @param key the key value conforms to a specific matcher specification
* @param model module model
* @return the specific matcher instance
*/
ConditionMatcher createMatcher(String key, ModuleModel model);
}
| 7,981 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcher.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.rpc.cluster.router.condition.matcher.argument;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.AbstractConditionMatcher;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* analysis the arguments in the rule.
* Examples would be like this:
* "arguments[0]=1", whenCondition is that the first argument is equal to '1'.
* "arguments[1]=a", whenCondition is that the second argument is equal to 'a'.
*/
@Activate
public class ArgumentConditionMatcher extends AbstractConditionMatcher {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ArgumentConditionMatcher.class);
private static final Pattern ARGUMENTS_PATTERN = Pattern.compile("arguments\\[([0-9]+)\\]");
public ArgumentConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
public String getValue(Map<String, String> sample, URL url, Invocation invocation) {
try {
// split the rule
String[] expressArray = key.split("\\.");
String argumentExpress = expressArray[0];
final Matcher matcher = ARGUMENTS_PATTERN.matcher(argumentExpress);
if (!matcher.find()) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument index
int index = Integer.parseInt(matcher.group(1));
if (index < 0 || index > invocation.getArguments().length) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument value
return String.valueOf(invocation.getArguments()[index]);
} catch (Exception e) {
logger.warn(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Parse argument match condition failed",
"",
"Invalid , will ignore., ",
e);
}
return DOES_NOT_FOUND_VALUE;
}
}
| 7,982 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/argument/ArgumentConditionMatcherFactory.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.rpc.cluster.router.condition.matcher.argument;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.Constants;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
@Activate(order = 300)
public class ArgumentConditionMatcherFactory implements ConditionMatcherFactory {
@Override
public boolean shouldMatch(String key) {
return key.startsWith(Constants.ARGUMENTS);
}
@Override
public ConditionMatcher createMatcher(String key, ModuleModel model) {
return new ArgumentConditionMatcher(key, model);
}
}
| 7,983 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcher.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.rpc.cluster.router.condition.matcher.attachment;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.AbstractConditionMatcher;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* analysis the arguments in the rule.
* Examples would be like this:
* "attachments[foo]=bar", whenCondition is that the attachment value of 'foo' is equal to 'bar'.
*/
@Activate
public class AttachmentConditionMatcher extends AbstractConditionMatcher {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AttachmentConditionMatcher.class);
private static final Pattern ATTACHMENTS_PATTERN = Pattern.compile("attachments\\[(.+)\\]");
public AttachmentConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
protected String getValue(Map<String, String> sample, URL url, Invocation invocation) {
try {
// split the rule
String[] expressArray = key.split("\\.");
String argumentExpress = expressArray[0];
final Matcher matcher = ATTACHMENTS_PATTERN.matcher(argumentExpress);
if (!matcher.find()) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument index
String attachmentKey = matcher.group(1);
if (StringUtils.isEmpty(attachmentKey)) {
return DOES_NOT_FOUND_VALUE;
}
// extract the argument value
return invocation.getAttachment(attachmentKey);
} catch (Exception e) {
logger.warn(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"condition state router attachment match failed",
"",
"Invalid match condition: " + key,
e);
}
return DOES_NOT_FOUND_VALUE;
}
}
| 7,984 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/attachment/AttachmentConditionMatcherFactory.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.rpc.cluster.router.condition.matcher.attachment;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
@Activate(order = 200)
public class AttachmentConditionMatcherFactory implements ConditionMatcherFactory {
private static final String ATTACHMENTS = "attachments";
@Override
public boolean shouldMatch(String key) {
return key.startsWith(ATTACHMENTS);
}
@Override
public ConditionMatcher createMatcher(String key, ModuleModel model) {
return new AttachmentConditionMatcher(key, model);
}
}
| 7,985 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcherFactory.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.rpc.cluster.router.condition.matcher.param;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcher;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.ConditionMatcherFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
// Make sure this is the last matcher being executed.
@Activate(order = Integer.MAX_VALUE)
public class UrlParamConditionMatcherFactory implements ConditionMatcherFactory {
@Override
public boolean shouldMatch(String key) {
return true;
}
@Override
public ConditionMatcher createMatcher(String key, ModuleModel model) {
return new UrlParamConditionMatcher(key, model);
}
}
| 7,986 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/param/UrlParamConditionMatcher.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.rpc.cluster.router.condition.matcher.param;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.AbstractConditionMatcher;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Map;
/**
* This instance will be loaded separately to ensure it always gets executed as the last matcher.
* So we don't put Active annotation here.
*/
public class UrlParamConditionMatcher extends AbstractConditionMatcher {
public UrlParamConditionMatcher(String key, ModuleModel model) {
super(key, model);
}
@Override
protected String getValue(Map<String, String> sample, URL url, Invocation invocation) {
return getSampleValueFromUrl(key, sample, url, invocation);
}
}
| 7,987 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/ValuePattern.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.rpc.cluster.router.condition.matcher.pattern;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
/**
*
*/
@SPI
public interface ValuePattern {
/**
* Is the input pattern of a specific form, for example, range pattern '1~100', wildcard pattern 'hello*', etc.
*
* @param pattern the match or mismatch pattern
* @return true or false
*/
boolean shouldMatch(String pattern);
/**
* Is the pattern matches with the request context
*
* @param pattern pattern value extracted from condition rule
* @param value the real value extracted from request context
* @param url request context in consumer url
* @param invocation request context in invocation
* @param isWhenCondition condition type
* @return true if successfully match
*/
boolean match(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition);
}
| 7,988 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/wildcard/WildcardValuePattern.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.rpc.cluster.router.condition.matcher.pattern.wildcard;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
/**
* Matches with patterns like 'key=hello', 'key=hello*', 'key=*hello', 'key=h*o' or 'key=*'
* <p>
* This pattern evaluator must be the last one being executed.
*/
@Activate(order = Integer.MAX_VALUE)
public class WildcardValuePattern implements ValuePattern {
@Override
public boolean shouldMatch(String key) {
return true;
}
@Override
public boolean match(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) {
return UrlUtils.isMatchGlobPattern(pattern, value, url);
}
}
| 7,989 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/pattern/range/RangeValuePattern.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.rpc.cluster.router.condition.matcher.pattern.range;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.cluster.router.condition.matcher.pattern.ValuePattern;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_EXEC_CONDITION_ROUTER;
/**
* Matches with patterns like 'key=1~100', 'key=~100' or 'key=1~'
*/
@Activate(order = 100)
public class RangeValuePattern implements ValuePattern {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RangeValuePattern.class);
@Override
public boolean shouldMatch(String pattern) {
return pattern.contains("~");
}
@Override
public boolean match(String pattern, String value, URL url, Invocation invocation, boolean isWhenCondition) {
boolean defaultValue = !isWhenCondition;
try {
int intValue = StringUtils.parseInteger(value);
String[] arr = pattern.split("~");
if (arr.length < 2) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"",
"",
"Invalid condition rule " + pattern + " or value " + value + ", will ignore.");
return defaultValue;
}
String rawStart = arr[0];
String rawEnd = arr[1];
if (StringUtils.isEmpty(rawStart) && StringUtils.isEmpty(rawEnd)) {
return defaultValue;
}
if (StringUtils.isEmpty(rawStart)) {
int end = StringUtils.parseInteger(rawEnd);
if (intValue > end) {
return false;
}
} else if (StringUtils.isEmpty(rawEnd)) {
int start = StringUtils.parseInteger(rawStart);
if (intValue < start) {
return false;
}
} else {
int start = StringUtils.parseInteger(rawStart);
int end = StringUtils.parseInteger(rawEnd);
if (intValue < start || intValue > end) {
return false;
}
}
} catch (Exception e) {
logger.error(
CLUSTER_FAILED_EXEC_CONDITION_ROUTER,
"Parse integer error",
"",
"Invalid condition rule " + pattern + " or value " + value + ", will ignore.",
e);
return defaultValue;
}
return true;
}
}
| 7,990 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouterFactory.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.rpc.cluster.router.tag;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.router.state.CacheableStateRouterFactory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
/**
* Tag router factory
*/
@Activate(order = 100)
public class TagStateRouterFactory extends CacheableStateRouterFactory {
public static final String NAME = "tag";
@Override
protected <T> StateRouter<T> createRouter(Class<T> interfaceClass, URL url) {
return new TagStateRouter<T>(url);
}
}
| 7,991 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/TagStateRouter.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.rpc.cluster.router.tag;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.Holder;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotNode;
import org.apache.dubbo.rpc.cluster.router.state.AbstractStateRouter;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRouterRule;
import org.apache.dubbo.rpc.cluster.router.tag.model.TagRuleParser;
import java.util.Set;
import java.util.function.Predicate;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_EMPTY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_TAG_ROUTE_INVALID;
import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG;
/**
* TagRouter, "application.tag-router"
*/
public class TagStateRouter<T> extends AbstractStateRouter<T> implements ConfigurationListener {
public static final String NAME = "TAG_ROUTER";
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TagStateRouter.class);
private static final String RULE_SUFFIX = ".tag-router";
private volatile TagRouterRule tagRouterRule;
private String application;
private volatile BitList<Invoker<T>> invokers = BitList.emptyList();
public TagStateRouter(URL url) {
super(url);
}
@Override
public synchronized void process(ConfigChangedEvent event) {
if (logger.isInfoEnabled()) {
logger.info("Notification of tag rule, change type is: " + event.getChangeType() + ", raw rule is:\n "
+ event.getContent());
}
try {
if (event.getChangeType().equals(ConfigChangeType.DELETED)) {
this.tagRouterRule = null;
} else {
TagRouterRule rule = TagRuleParser.parse(event.getContent());
rule.init(this);
this.tagRouterRule = rule;
}
} catch (Exception e) {
logger.error(
CLUSTER_TAG_ROUTE_INVALID,
"Failed to parse the raw tag router rule",
"",
"Failed to parse the raw tag router rule and it will not take effect, please check if the "
+ "rule matches with the template, the raw rule is:\n ",
e);
}
}
@Override
public BitList<Invoker<T>> doRoute(
BitList<Invoker<T>> invokers,
URL url,
Invocation invocation,
boolean needToPrintMessage,
Holder<RouterSnapshotNode<T>> nodeHolder,
Holder<String> messageHolder)
throws RpcException {
if (CollectionUtils.isEmpty(invokers)) {
if (needToPrintMessage) {
messageHolder.set("Directly Return. Reason: Invokers from previous router is empty.");
}
return invokers;
}
// since the rule can be changed by config center, we should copy one to use.
final TagRouterRule tagRouterRuleCopy = tagRouterRule;
if (tagRouterRuleCopy == null || !tagRouterRuleCopy.isValid() || !tagRouterRuleCopy.isEnabled()) {
if (needToPrintMessage) {
messageHolder.set("Disable Tag Router. Reason: tagRouterRule is invalid or disabled");
}
return filterUsingStaticTag(invokers, url, invocation);
}
BitList<Invoker<T>> result = invokers;
String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY))
? url.getParameter(TAG_KEY)
: invocation.getAttachment(TAG_KEY);
// if we are requesting for a Provider with a specific tag
if (StringUtils.isNotEmpty(tag)) {
Set<String> addresses = tagRouterRuleCopy.getTagnameToAddresses().get(tag);
// filter by dynamic tag group first
if (addresses != null) { // null means tag not set
result = filterInvoker(invokers, invoker -> addressMatches(invoker.getUrl(), addresses));
// if result is not null OR it's null but force=true, return result directly
if (CollectionUtils.isNotEmpty(result) || tagRouterRuleCopy.isForce()) {
if (needToPrintMessage) {
messageHolder.set(
"Use tag " + tag + " to route. Reason: result is not null OR it's null but force=true");
}
return result;
}
} else {
// dynamic tag group doesn't have any item about the requested app OR it's null after filtered by
// dynamic tag group but force=false. check static tag
result = filterInvoker(
invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
}
// If there's no tagged providers that can match the current tagged request. force.tag is set by default
// to false, which means it will invoke any providers without a tag unless it's explicitly disallowed.
if (CollectionUtils.isNotEmpty(result) || isForceUseTag(invocation)) {
if (needToPrintMessage) {
messageHolder.set("Use tag " + tag
+ " to route. Reason: result is not empty or ForceUseTag key is true in invocation");
}
return result;
}
// FAILOVER: return all Providers without any tags.
else {
BitList<Invoker<T>> tmp = filterInvoker(
invokers, invoker -> addressNotMatches(invoker.getUrl(), tagRouterRuleCopy.getAddresses()));
if (needToPrintMessage) {
messageHolder.set("FAILOVER: return all Providers without any tags");
}
return filterInvoker(
tmp, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
} else {
// List<String> addresses = tagRouterRule.filter(providerApp);
// return all addresses in dynamic tag group.
Set<String> addresses = tagRouterRuleCopy.getAddresses();
if (CollectionUtils.isNotEmpty(addresses)) {
result = filterInvoker(invokers, invoker -> addressNotMatches(invoker.getUrl(), addresses));
// 1. all addresses are in dynamic tag group, return empty list.
if (CollectionUtils.isEmpty(result)) {
if (needToPrintMessage) {
messageHolder.set("all addresses are in dynamic tag group, return empty list");
}
return result;
}
// 2. if there are some addresses that are not in any dynamic tag group, continue to filter using the
// static tag group.
}
if (needToPrintMessage) {
messageHolder.set("filter using the static tag group");
}
return filterInvoker(result, invoker -> {
String localTag = invoker.getUrl().getParameter(TAG_KEY);
return StringUtils.isEmpty(localTag);
});
}
}
/**
* If there's no dynamic tag rule being set, use static tag in URL.
* <p>
* A typical scenario is a Consumer using version 2.7.x calls Providers using version 2.6.x or lower,
* the Consumer should always respect the tag in provider URL regardless of whether a dynamic tag rule has been set to it or not.
* <p>
* TODO, to guarantee consistent behavior of interoperability between 2.6- and 2.7+, this method should has the same logic with the TagRouter in 2.6.x.
*
* @param invokers
* @param url
* @param invocation
* @param <T>
* @return
*/
private <T> BitList<Invoker<T>> filterUsingStaticTag(BitList<Invoker<T>> invokers, URL url, Invocation invocation) {
BitList<Invoker<T>> result;
// Dynamic param
String tag = StringUtils.isEmpty(invocation.getAttachment(TAG_KEY))
? url.getParameter(TAG_KEY)
: invocation.getAttachment(TAG_KEY);
// Tag request
if (!StringUtils.isEmpty(tag)) {
result = filterInvoker(
invokers, invoker -> tag.equals(invoker.getUrl().getParameter(TAG_KEY)));
if (CollectionUtils.isEmpty(result) && !isForceUseTag(invocation)) {
result = filterInvoker(
invokers,
invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
} else {
result = filterInvoker(
invokers, invoker -> StringUtils.isEmpty(invoker.getUrl().getParameter(TAG_KEY)));
}
return result;
}
@Override
public boolean isRuntime() {
return tagRouterRule != null && tagRouterRule.isRuntime();
}
@Override
public boolean isForce() {
// FIXME
return tagRouterRule != null && tagRouterRule.isForce();
}
private boolean isForceUseTag(Invocation invocation) {
return Boolean.parseBoolean(
invocation.getAttachment(FORCE_USE_TAG, this.getUrl().getParameter(FORCE_USE_TAG, "false")));
}
private <T> BitList<Invoker<T>> filterInvoker(BitList<Invoker<T>> invokers, Predicate<Invoker<T>> predicate) {
if (invokers.stream().allMatch(predicate)) {
return invokers;
}
BitList<Invoker<T>> newInvokers = invokers.clone();
newInvokers.removeIf(invoker -> !predicate.test(invoker));
return newInvokers;
}
private boolean addressMatches(URL url, Set<String> addresses) {
return addresses != null && checkAddressMatch(addresses, url.getHost(), url.getPort());
}
private boolean addressNotMatches(URL url, Set<String> addresses) {
return addresses == null || !checkAddressMatch(addresses, url.getHost(), url.getPort());
}
private boolean checkAddressMatch(Set<String> addresses, String host, int port) {
for (String address : addresses) {
try {
if (NetUtils.matchIpExpression(address, host, port)) {
return true;
}
if ((ANYHOST_VALUE + ":" + port).equals(address)) {
return true;
}
} catch (Exception e) {
logger.error(
CLUSTER_TAG_ROUTE_INVALID,
"tag route address is invalid",
"",
"The format of ip address is invalid in tag route. Address :" + address,
e);
}
}
return false;
}
public void setApplication(String app) {
this.application = app;
}
@Override
public void notify(BitList<Invoker<T>> invokers) {
this.invokers = invokers;
if (CollectionUtils.isEmpty(invokers)) {
return;
}
Invoker<T> invoker = invokers.get(0);
URL url = invoker.getUrl();
String providerApplication = url.getRemoteApplication();
if (StringUtils.isEmpty(providerApplication)) {
logger.error(
CLUSTER_TAG_ROUTE_EMPTY,
"tag router get providerApplication is empty",
"",
"TagRouter must getConfig from or subscribe to a specific application, but the application "
+ "in this TagRouter is not specified.");
return;
}
synchronized (this) {
if (!providerApplication.equals(application)) {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
String key = providerApplication + RULE_SUFFIX;
this.getRuleRepository().addListener(key, this);
application = providerApplication;
String rawRule = this.getRuleRepository().getRule(key, DynamicConfiguration.DEFAULT_GROUP);
if (StringUtils.isNotEmpty(rawRule)) {
this.process(new ConfigChangedEvent(key, DynamicConfiguration.DEFAULT_GROUP, rawRule));
}
} else {
if (this.tagRouterRule != null) {
TagRouterRule newRule = TagRuleParser.parse(this.tagRouterRule.getRawRule());
newRule.init(this);
this.tagRouterRule = newRule;
}
}
}
}
public BitList<Invoker<T>> getInvokers() {
return invokers;
}
@Override
public void stop() {
if (StringUtils.isNotEmpty(application)) {
this.getRuleRepository().removeListener(application + RULE_SUFFIX, this);
}
}
// for testing purpose
public void setTagRouterRule(TagRouterRule tagRouterRule) {
this.tagRouterRule = tagRouterRule;
}
}
| 7,992 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRouterRule.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.rpc.cluster.router.tag.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.router.AbstractRouterRule;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.cluster.router.tag.TagStateRouter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_VERSION_V30;
import static org.apache.dubbo.rpc.cluster.Constants.TAGS_KEY;
/**
* %YAML1.2
* ---
* force: true
* runtime: false
* enabled: true
* priority: 1
* key: demo-provider
* tags:
* - name: tag1
* addresses: [ip1, ip2]
* - name: tag2
* addresses: [ip3, ip4]
* ...
*/
public class TagRouterRule extends AbstractRouterRule {
private List<Tag> tags;
private final Map<String, Set<String>> addressToTagnames = new HashMap<>();
private final Map<String, Set<String>> tagnameToAddresses = new HashMap<>();
@SuppressWarnings("unchecked")
public static TagRouterRule parseFromMap(Map<String, Object> map) {
TagRouterRule tagRouterRule = new TagRouterRule();
tagRouterRule.parseFromMap0(map);
Object tags = map.get(TAGS_KEY);
if (tags != null && List.class.isAssignableFrom(tags.getClass())) {
tagRouterRule.setTags(((List<Map<String, Object>>) tags)
.stream()
.map(objMap -> Tag.parseFromMap(objMap, tagRouterRule.getVersion()))
.collect(Collectors.toList()));
}
return tagRouterRule;
}
public void init(TagStateRouter<?> router) {
if (!isValid()) {
return;
}
BitList<? extends Invoker<?>> invokers = router.getInvokers();
// for tags with 'addresses` field set and 'match' field not set
tags.stream()
.filter(tag -> CollectionUtils.isNotEmpty(tag.getAddresses()))
.forEach(tag -> {
tagnameToAddresses.put(tag.getName(), new HashSet<>(tag.getAddresses()));
tag.getAddresses().forEach(addr -> {
Set<String> tagNames = addressToTagnames.computeIfAbsent(addr, k -> new HashSet<>());
tagNames.add(tag.getName());
});
});
if (this.getVersion() != null && this.getVersion().startsWith(RULE_VERSION_V30)) {
// for tags with 'match` field set and 'addresses' field not set
if (CollectionUtils.isNotEmpty(invokers)) {
tags.stream()
.filter(tag -> CollectionUtils.isEmpty(tag.getAddresses()))
.forEach(tag -> {
Set<String> addresses = new HashSet<>();
List<ParamMatch> paramMatchers = tag.getMatch();
invokers.forEach(invoker -> {
boolean isMatch = true;
for (ParamMatch matcher : paramMatchers) {
if (!matcher.isMatch(invoker.getUrl().getOriginalParameter(matcher.getKey()))) {
isMatch = false;
break;
}
}
if (isMatch) {
addresses.add(invoker.getUrl().getAddress());
}
});
if (CollectionUtils.isNotEmpty(addresses)) { // null means tag not set
tagnameToAddresses.put(tag.getName(), addresses);
}
});
}
}
}
public Set<String> getAddresses() {
return tagnameToAddresses.entrySet().stream()
.filter(entry -> CollectionUtils.isNotEmpty(entry.getValue()))
.flatMap(entry -> entry.getValue().stream())
.collect(Collectors.toSet());
}
public List<String> getTagNames() {
return tags.stream().map(Tag::getName).collect(Collectors.toList());
}
public Map<String, Set<String>> getAddressToTagnames() {
return addressToTagnames;
}
public Map<String, Set<String>> getTagnameToAddresses() {
return tagnameToAddresses;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
}
| 7,993 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/Tag.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.rpc.cluster.router.tag.model;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.PojoUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_FAILED_RULE_PARSING;
import static org.apache.dubbo.rpc.cluster.Constants.RULE_VERSION_V30;
public class Tag {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Tag.class);
private String name;
private List<ParamMatch> match;
private List<String> addresses;
@SuppressWarnings("unchecked")
public static Tag parseFromMap(Map<String, Object> map, String version) {
Tag tag = new Tag();
tag.setName((String) map.get("name"));
if (version != null && version.startsWith(RULE_VERSION_V30)) {
if (map.get("match") != null) {
tag.setMatch(((List<Map<String, Object>>) map.get("match"))
.stream()
.map((objectMap) -> {
try {
return PojoUtils.mapToPojo(objectMap, ParamMatch.class);
} catch (ReflectiveOperationException e) {
logger.error(
CLUSTER_FAILED_RULE_PARSING,
" Failed to parse tag rule ",
String.valueOf(objectMap),
"Error occurred when parsing rule component.",
e);
}
return null;
})
.collect(Collectors.toList()));
} else {
logger.warn(
CLUSTER_FAILED_RULE_PARSING,
"",
String.valueOf(map),
"It's recommended to use 'match' instead of 'addresses' for v3.0 tag rule.");
}
}
Object addresses = map.get("addresses");
if (addresses != null && List.class.isAssignableFrom(addresses.getClass())) {
tag.setAddresses(
((List<Object>) addresses).stream().map(String::valueOf).collect(Collectors.toList()));
}
return tag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public List<ParamMatch> getMatch() {
return match;
}
public void setMatch(List<ParamMatch> match) {
this.match = match;
}
}
| 7,994 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/ParamMatch.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.rpc.cluster.router.tag.model;
import org.apache.dubbo.rpc.cluster.router.mesh.rule.virtualservice.match.StringMatch;
public class ParamMatch {
private String key;
private StringMatch value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public StringMatch getValue() {
return value;
}
public void setValue(StringMatch value) {
this.value = value;
}
public boolean isMatch(String input) {
if (getValue() != null) {
return getValue().isMatch(input);
}
return false;
}
}
| 7,995 |
0 |
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag
|
Create_ds/dubbo/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/tag/model/TagRuleParser.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.rpc.cluster.router.tag.model;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.Map;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
/**
* Parse raw rule into structured tag rule
*/
public class TagRuleParser {
public static TagRouterRule parse(String rawRule) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
TagRouterRule rule = TagRouterRule.parseFromMap(map);
rule.setRawRule(rawRule);
if (CollectionUtils.isEmpty(rule.getTags())) {
rule.setValid(false);
}
return rule;
}
}
| 7,996 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataMetricsCollectorTest.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.metadata;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metrics.event.MetricsDispatcher;
import org.apache.dubbo.metrics.event.MetricsEvent;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.metadata.collector.MetadataMetricsCollector;
import org.apache.dubbo.metrics.metadata.event.MetadataEvent;
import org.apache.dubbo.metrics.model.TimePair;
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 org.apache.dubbo.metrics.model.sample.MetricSample;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.MetricsConstants.TAG_APPLICATION_NAME;
import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH;
import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE;
import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE;
class MetadataMetricsCollectorTest {
private ApplicationModel applicationModel;
private MetadataMetricsCollector collector;
@BeforeEach
public void setup() {
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
applicationModel = frameworkModel.newApplication();
ApplicationConfig config = new ApplicationConfig();
config.setName("MockMetrics");
applicationModel.getApplicationConfigManager().setApplication(config);
applicationModel.getBeanFactory().getOrRegisterBean(MetricsDispatcher.class);
collector = applicationModel.getBeanFactory().getOrRegisterBean(MetadataMetricsCollector.class);
collector.setCollectEnabled(true);
}
@Test
void testListener() {
MetadataEvent event = MetadataEvent.toPushEvent(applicationModel);
MetricsEvent otherEvent = new MetricsEvent(applicationModel, null, null, null) {};
Assertions.assertTrue(collector.isSupport(event));
Assertions.assertFalse(collector.isSupport(otherEvent));
}
@AfterEach
public void teardown() {
applicationModel.destroy();
}
@Test
void testPushMetrics() {
// MetadataMetricsCollector collector = getCollector();
MetadataEvent pushEvent = MetadataEvent.toPushEvent(applicationModel);
MetricsEventBus.post(pushEvent, () -> {
List<MetricSample> metricSamples = collector.collect();
// push success +1
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size());
Assertions.assertTrue(
metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample));
Assertions.assertTrue(metricSamples.stream()
.anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1));
return null;
});
// push finish rt +1
List<MetricSample> metricSamples = collector.collect();
// App(6) + rt(5) = 7
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size());
long c1 = pushEvent.getTimePair().calc();
pushEvent = MetadataEvent.toPushEvent(applicationModel);
TimePair lastTimePair = pushEvent.getTimePair();
MetricsEventBus.post(
pushEvent,
() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
},
Objects::nonNull);
// push error rt +1
long c2 = lastTimePair.calc();
metricSamples = collector.collect();
// App(6) + rt(5)
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size());
// calc rt
for (MetricSample sample : metricSamples) {
Map<String, String> tags = sample.getTags();
Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName());
}
@SuppressWarnings("rawtypes")
Map<String, Long> sampleMap = metricSamples.stream()
.collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong()));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_PUSH).targetKey()),
lastTimePair.calc());
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_PUSH).targetKey()),
Math.min(c1, c2));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_PUSH).targetKey()),
Math.max(c1, c2));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_PUSH).targetKey()),
(c1 + c2) / 2);
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_PUSH).targetKey()), c1 + c2);
}
@Test
void testSubscribeMetrics() {
// MetadataMetricsCollector collector = getCollector();
MetadataEvent subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel);
MetricsEventBus.post(subscribeEvent, () -> {
List<MetricSample> metricSamples = collector.collect();
// push success +1
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size(), metricSamples.size());
Assertions.assertTrue(
metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample));
Assertions.assertTrue(metricSamples.stream()
.anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1));
return null;
});
long c1 = subscribeEvent.getTimePair().calc();
// push finish rt +1
List<MetricSample> metricSamples = collector.collect();
// App(6) + rt(5) = 7
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size());
subscribeEvent = MetadataEvent.toSubscribeEvent(applicationModel);
TimePair lastTimePair = subscribeEvent.getTimePair();
MetricsEventBus.post(
subscribeEvent,
() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
},
Objects::nonNull);
// push error rt +1
long c2 = lastTimePair.calc();
metricSamples = collector.collect();
// App(6) + rt(5)
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 5, metricSamples.size());
// calc rt
for (MetricSample sample : metricSamples) {
Map<String, String> tags = sample.getTags();
Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName());
}
@SuppressWarnings("rawtypes")
Map<String, Long> sampleMap = metricSamples.stream()
.collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong()));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE).targetKey()),
lastTimePair.calc());
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE).targetKey()),
Math.min(c1, c2));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE).targetKey()),
Math.max(c1, c2));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE).targetKey()),
(c1 + c2) / 2);
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE).targetKey()), c1 + c2);
}
@Test
void testStoreProviderMetadataMetrics() {
// MetadataMetricsCollector collector = getCollector();
String serviceKey = "store.provider.test";
MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey);
MetricsEventBus.post(metadataEvent, () -> {
List<MetricSample> metricSamples = collector.collect();
// App(6) + service success(1)
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 1, metricSamples.size());
Assertions.assertTrue(
metricSamples.stream().allMatch(metricSample -> metricSample instanceof GaugeMetricSample));
Assertions.assertTrue(metricSamples.stream()
.anyMatch(metricSample -> ((GaugeMetricSample) metricSample).applyAsDouble() == 1));
return null;
});
// push finish rt +1
List<MetricSample> metricSamples = collector.collect();
// App(6) + service total/success(2) + rt(5) = 7
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 2 + 5, metricSamples.size());
long c1 = metadataEvent.getTimePair().calc();
metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, serviceKey);
TimePair lastTimePair = metadataEvent.getTimePair();
MetricsEventBus.post(
metadataEvent,
() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
},
Objects::nonNull);
// push error rt +1
long c2 = lastTimePair.calc();
metricSamples = collector.collect();
// App(6) + service total/success/failed(3) + rt(5)
Assertions.assertEquals(MetadataMetricsConstants.APP_LEVEL_KEYS.size() + 3 + 5, metricSamples.size());
// calc rt
for (MetricSample sample : metricSamples) {
Map<String, String> tags = sample.getTags();
Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName());
}
@SuppressWarnings("rawtypes")
Map<String, Long> sampleMap = metricSamples.stream()
.collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong()));
Assertions.assertEquals(
sampleMap.get(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()),
lastTimePair.calc());
Assertions.assertEquals(
sampleMap.get(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()),
Math.min(c1, c2));
Assertions.assertEquals(
sampleMap.get(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()),
Math.max(c1, c2));
Assertions.assertEquals(
sampleMap.get(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()),
(c1 + c2) / 2);
Assertions.assertEquals(
sampleMap.get(
new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_STORE_PROVIDER_INTERFACE).targetKey()),
c1 + c2);
}
@Test
void testMetadataPushNum() {
for (int i = 0; i < 10; i++) {
MetadataEvent event = MetadataEvent.toPushEvent(applicationModel);
if (i % 2 == 0) {
MetricsEventBus.post(event, () -> true, r -> r);
} else {
MetricsEventBus.post(event, () -> false, r -> r);
}
}
List<MetricSample> samples = collector.collect();
GaugeMetricSample<?> totalNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM.getName(), samples);
GaugeMetricSample<?> succeedNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED.getName(), samples);
GaugeMetricSample<?> failedNum = getSample(MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED.getName(), samples);
Assertions.assertEquals(10, totalNum.applyAsLong());
Assertions.assertEquals(5, succeedNum.applyAsLong());
Assertions.assertEquals(5, failedNum.applyAsLong());
}
@Test
void testSubscribeSum() {
for (int i = 0; i < 10; i++) {
MetadataEvent event = MetadataEvent.toSubscribeEvent(applicationModel);
if (i % 2 == 0) {
MetricsEventBus.post(event, () -> true, r -> r);
} else {
MetricsEventBus.post(event, () -> false, r -> r);
}
}
List<MetricSample> samples = collector.collect();
GaugeMetricSample<?> totalNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM.getName(), samples);
GaugeMetricSample<?> succeedNum =
getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED.getName(), samples);
GaugeMetricSample<?> failedNum = getSample(MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED.getName(), samples);
Assertions.assertEquals(10, totalNum.applyAsLong());
Assertions.assertEquals(5, succeedNum.applyAsLong());
Assertions.assertEquals(5, failedNum.applyAsLong());
}
GaugeMetricSample<?> getSample(String name, List<MetricSample> samples) {
return (GaugeMetricSample<?>) samples.stream()
.filter(metricSample -> metricSample.getName().equals(name))
.findFirst()
.orElseThrow(NoSuchElementException::new);
}
}
| 7,997 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/test/java/org/apache/dubbo/metrics/metadata/MetadataStatCompositeTest.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.metadata;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metrics.data.ApplicationStatComposite;
import org.apache.dubbo.metrics.data.BaseStatComposite;
import org.apache.dubbo.metrics.data.RtStatComposite;
import org.apache.dubbo.metrics.data.ServiceStatComposite;
import org.apache.dubbo.metrics.model.ApplicationMetric;
import org.apache.dubbo.metrics.model.Metric;
import org.apache.dubbo.metrics.model.container.LongContainer;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_PUSH;
import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_STORE_PROVIDER_INTERFACE;
import static org.apache.dubbo.metrics.metadata.MetadataMetricsConstants.OP_TYPE_SUBSCRIBE;
public class MetadataStatCompositeTest {
private ApplicationModel applicationModel;
private BaseStatComposite statComposite;
@BeforeEach
public void setup() {
FrameworkModel frameworkModel = FrameworkModel.defaultModel();
applicationModel = frameworkModel.newApplication();
ApplicationConfig application = new ApplicationConfig();
application.setName("App1");
applicationModel.getApplicationConfigManager().setApplication(application);
statComposite = new BaseStatComposite(applicationModel) {
@Override
protected void init(ApplicationStatComposite applicationStatComposite) {
super.init(applicationStatComposite);
applicationStatComposite.init(MetadataMetricsConstants.APP_LEVEL_KEYS);
}
@Override
protected void init(ServiceStatComposite serviceStatComposite) {
super.init(serviceStatComposite);
serviceStatComposite.initWrapper(MetadataMetricsConstants.SERVICE_LEVEL_KEYS);
}
@Override
protected void init(RtStatComposite rtStatComposite) {
super.init(rtStatComposite);
rtStatComposite.init(OP_TYPE_PUSH, OP_TYPE_SUBSCRIBE, OP_TYPE_STORE_PROVIDER_INTERFACE);
}
};
}
@Test
void testInit() {
Assertions.assertEquals(
statComposite
.getApplicationStatComposite()
.getApplicationNumStats()
.size(),
MetadataMetricsConstants.APP_LEVEL_KEYS.size());
// (rt)5 * (push,subscribe,service)3
Assertions.assertEquals(
5 * 3, statComposite.getRtStatComposite().getRtStats().size());
statComposite
.getApplicationStatComposite()
.getApplicationNumStats()
.values()
.forEach((v -> Assertions.assertEquals(v.get(), new AtomicLong(0L).get())));
statComposite.getRtStatComposite().getRtStats().forEach(rtContainer -> {
for (Map.Entry<Metric, ? extends Number> entry : rtContainer.entrySet()) {
Assertions.assertEquals(0L, rtContainer.getValueSupplier().apply(entry.getKey()));
}
});
}
@Test
void testIncrement() {
statComposite.incrementApp(MetricsKey.METADATA_PUSH_METRIC_NUM, 1);
Assertions.assertEquals(
1L,
statComposite
.getApplicationStatComposite()
.getApplicationNumStats()
.get(MetricsKey.METADATA_PUSH_METRIC_NUM)
.get());
}
@Test
void testCalcRt() {
statComposite.calcApplicationRt(OP_TYPE_SUBSCRIBE.getType(), 10L);
Assertions.assertTrue(statComposite.getRtStatComposite().getRtStats().stream()
.anyMatch(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType())));
Optional<LongContainer<? extends Number>> subContainer =
statComposite.getRtStatComposite().getRtStats().stream()
.filter(longContainer -> longContainer.specifyType(OP_TYPE_SUBSCRIBE.getType()))
.findFirst();
subContainer.ifPresent(v -> Assertions.assertEquals(
10L, v.get(new ApplicationMetric(applicationModel)).longValue()));
}
}
| 7,998 |
0 |
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics
|
Create_ds/dubbo/dubbo-metrics/dubbo-metrics-metadata/src/main/java/org/apache/dubbo/metrics/metadata/MetadataMetricsConstants.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.metadata;
import org.apache.dubbo.metrics.model.key.MetricsKey;
import org.apache.dubbo.metrics.model.key.MetricsKeyWrapper;
import org.apache.dubbo.metrics.model.key.MetricsLevel;
import org.apache.dubbo.metrics.model.key.MetricsPlaceValue;
import java.util.Arrays;
import java.util.List;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM_FAILED;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_PUSH_METRIC_NUM_SUCCEED;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_FAILED;
import static org.apache.dubbo.metrics.model.key.MetricsKey.METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED;
import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA;
import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA_FAILED;
import static org.apache.dubbo.metrics.model.key.MetricsKey.STORE_PROVIDER_METADATA_SUCCEED;
public interface MetadataMetricsConstants {
MetricsPlaceValue OP_TYPE_PUSH = MetricsPlaceValue.of("push", MetricsLevel.APP);
MetricsPlaceValue OP_TYPE_SUBSCRIBE = MetricsPlaceValue.of("subscribe", MetricsLevel.APP);
MetricsPlaceValue OP_TYPE_STORE_PROVIDER_INTERFACE =
MetricsPlaceValue.of("store.provider.interface", MetricsLevel.SERVICE);
// App-level
List<MetricsKey> APP_LEVEL_KEYS = Arrays.asList(
METADATA_PUSH_METRIC_NUM,
METADATA_PUSH_METRIC_NUM_SUCCEED,
METADATA_PUSH_METRIC_NUM_FAILED,
METADATA_SUBSCRIBE_METRIC_NUM,
METADATA_SUBSCRIBE_METRIC_NUM_SUCCEED,
METADATA_SUBSCRIBE_METRIC_NUM_FAILED);
// Service-level
List<MetricsKeyWrapper> SERVICE_LEVEL_KEYS = Arrays.asList(
new MetricsKeyWrapper(STORE_PROVIDER_METADATA, OP_TYPE_STORE_PROVIDER_INTERFACE),
new MetricsKeyWrapper(STORE_PROVIDER_METADATA_SUCCEED, OP_TYPE_STORE_PROVIDER_INTERFACE),
new MetricsKeyWrapper(STORE_PROVIDER_METADATA_FAILED, OP_TYPE_STORE_PROVIDER_INTERFACE));
}
| 7,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.