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-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy.bytebuddy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import net.bytebuddy.ByteBuddy; import net.bytebuddy.description.ByteCodeElement; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.matcher.ElementMatchers; import static org.apache.dubbo.common.constants.CommonConstants.MAX_PROXY_COUNT; public class ByteBuddyProxy { private static final Map<ClassLoader, Map<CacheKey, ByteBuddyProxy>> PROXY_CACHE_MAP = new WeakHashMap<>(); private final Class<?> proxyClass; private final InvocationHandler handler; private ByteBuddyProxy(Class<?> proxyClass, InvocationHandler handler) { this.proxyClass = proxyClass; this.handler = handler; } public static Object newInstance(ClassLoader cl, Class<?>[] interfaces, InvocationHandler handler) { return getProxy(cl, interfaces, handler).newInstance(); } private static ByteBuddyProxy getProxy(ClassLoader cl, Class<?>[] interfaces, InvocationHandler handler) { if (interfaces.length > MAX_PROXY_COUNT) { throw new IllegalArgumentException("interface limit exceeded"); } interfaces = interfaces.clone(); Arrays.sort(interfaces, Comparator.comparing(Class::getName)); CacheKey key = new CacheKey(interfaces); // get cache by class loader. final Map<CacheKey, ByteBuddyProxy> cache; synchronized (PROXY_CACHE_MAP) { cache = PROXY_CACHE_MAP.computeIfAbsent(cl, k -> new ConcurrentHashMap<>()); } ByteBuddyProxy proxy = cache.get(key); if (proxy == null) { synchronized (interfaces[0]) { proxy = cache.get(key); if (proxy == null) { // create ByteBuddyProxy class. proxy = new ByteBuddyProxy(buildProxyClass(cl, interfaces, handler), handler); cache.put(key, proxy); } } } return proxy; } private Object newInstance() { try { Constructor<?> constructor = proxyClass.getDeclaredConstructor(InvocationHandler.class); return constructor.newInstance(handler); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } private static Class<?> buildProxyClass(ClassLoader cl, Class<?>[] ics, InvocationHandler handler) { ElementMatcher.Junction<ByteCodeElement> methodMatcher = Arrays.stream(ics) .map(ElementMatchers::isDeclaredBy) .reduce(ElementMatcher.Junction::or) .orElse(ElementMatchers.none()) .and(ElementMatchers.not(ElementMatchers.isDeclaredBy(Object.class))); return new ByteBuddy() .subclass(Proxy.class) .implement(ics) .method(methodMatcher) .intercept(MethodDelegation.to(new ByteBuddyInterceptor(handler))) .make() .load(cl) .getLoaded(); } private static class CacheKey { private final Class<?>[] classes; private CacheKey(Class<?>[] classes) { this.classes = classes; } public Class<?>[] getClasses() { return classes; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CacheKey that = (CacheKey) o; return Arrays.equals(classes, that.classes); } @Override public int hashCode() { return Arrays.hashCode(classes); } } }
6,000
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy.bytebuddy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import net.bytebuddy.implementation.bind.annotation.AllArguments; import net.bytebuddy.implementation.bind.annotation.Origin; import net.bytebuddy.implementation.bind.annotation.RuntimeType; import net.bytebuddy.implementation.bind.annotation.This; public class ByteBuddyInterceptor { private final InvocationHandler handler; ByteBuddyInterceptor(InvocationHandler handler) { this.handler = handler; } @RuntimeType public Object intercept(@This Object obj, @AllArguments Object[] allArguments, @Origin Method method) throws Throwable { return handler.invoke(obj, method, allArguments); } }
6,001
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy.bytebuddy; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.proxy.AbstractFallbackJdkProxyFactory; import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; /** * ByteBuddyRpcProxyFactory */ public class ByteBuddyProxyFactory extends AbstractFallbackJdkProxyFactory { @Override protected <T> Invoker<T> doGetInvoker(T proxy, Class<T> type, URL url) { return ByteBuddyProxyInvoker.newInstance(proxy, type, url); } @Override @SuppressWarnings("unchecked") protected <T> T doGetProxy(Invoker<T> invoker, Class<?>[] interfaces) { ClassLoader classLoader = invoker.getInterface().getClassLoader(); return (T) ByteBuddyProxy.newInstance(classLoader, interfaces, new InvokerInvocationHandler(invoker)); } }
6,002
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy.wrapper; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.bytecode.Wrapper; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Constructor; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED_EXPORT_SERVICE; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; import static org.apache.dubbo.rpc.Constants.STUB_EVENT_METHODS_KEY; import static org.apache.dubbo.rpc.Constants.STUB_KEY; /** * StubProxyFactoryWrapper */ public class StubProxyFactoryWrapper implements ProxyFactory { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(StubProxyFactoryWrapper.class); private final ProxyFactory proxyFactory; private Protocol protocol; public StubProxyFactoryWrapper(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } public void setProtocol(Protocol protocol) { this.protocol = protocol; } @Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { T proxy = proxyFactory.getProxy(invoker, generic); if (GenericService.class != invoker.getInterface()) { URL url = invoker.getUrl(); String stub = url.getParameter(STUB_KEY, url.getParameter(LOCAL_KEY)); if (ConfigUtils.isNotEmpty(stub)) { Class<?> serviceType = invoker.getInterface(); if (ConfigUtils.isDefault(stub)) { if (url.hasParameter(STUB_KEY)) { stub = serviceType.getName() + "Stub"; } else { stub = serviceType.getName() + "Local"; } } try { Class<?> stubClass = ReflectUtils.forName(stub); if (!serviceType.isAssignableFrom(stubClass)) { throw new IllegalStateException("The stub implementation class " + stubClass.getName() + " not implement interface " + serviceType.getName()); } try { Constructor<?> constructor = ReflectUtils.findConstructor(stubClass, serviceType); proxy = (T) constructor.newInstance(new Object[] {proxy}); // export stub service URLBuilder urlBuilder = URLBuilder.from(url); if (url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT)) { urlBuilder.addParameter( STUB_EVENT_METHODS_KEY, StringUtils.join( Wrapper.getWrapper(proxy.getClass()).getDeclaredMethodNames(), ",")); urlBuilder.addParameter(IS_SERVER_KEY, Boolean.FALSE.toString()); try { export(proxy, invoker.getInterface(), urlBuilder.build()); } catch (Exception e) { LOGGER.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "export a stub service error.", e); } } } catch (NoSuchMethodException e) { throw new IllegalStateException( "No such constructor \"public " + stubClass.getSimpleName() + "(" + serviceType.getName() + ")\" in stub implementation class " + stubClass.getName(), e); } } catch (Throwable t) { LOGGER.error( PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to create stub implementation class " + stub + " in consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", cause: " + t.getMessage(), t); // ignore } } } return proxy; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public <T> T getProxy(Invoker<T> invoker) throws RpcException { return getProxy(invoker, false); } @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { return proxyFactory.getInvoker(proxy, type, url); } private <T> Exporter<T> export(T instance, Class<T> type, URL url) { return protocol.export(proxyFactory.getInvoker(instance, type, url)); } }
6,003
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy.jdk; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.proxy.AbstractProxyFactory; import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker; import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * JdkRpcProxyFactory */ public class JdkProxyFactory extends AbstractProxyFactory { @Override @SuppressWarnings("unchecked") public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) { return (T) Proxy.newProxyInstance( invoker.getInterface().getClassLoader(), interfaces, new InvokerInvocationHandler(invoker)); } @Override public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) { return new AbstractProxyInvoker<T>(proxy, type, url) { @Override protected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { Method method = proxy.getClass().getMethod(methodName, parameterTypes); return method.invoke(proxy, arguments); } }; } }
6,004
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ReferenceCountInvokerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReferenceCountInvokerWrapper<T> implements Invoker<T> { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountInvokerWrapper.class); private final Invoker<T> invoker; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final AtomicBoolean destroyed = new AtomicBoolean(false); public ReferenceCountInvokerWrapper(Invoker<T> invoker) { this.invoker = invoker; } @Override public URL getUrl() { return invoker.getUrl(); } @Override public boolean isAvailable() { return !destroyed.get() && invoker.isAvailable(); } @Override public void destroy() { try { int timeout = ConfigurationUtils.getServerShutdownTimeout(invoker.getUrl().getScopeModel()); boolean locked = lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS); if (!locked) { logger.warn( LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", "Failed to wait for invocation end in " + timeout + "ms."); } destroyed.set(true); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { try { lock.writeLock().unlock(); } catch (IllegalMonitorStateException ignore) { // ignore if lock failed, maybe in a long invoke } catch (Throwable t) { logger.warn( LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", "Unexpected error occurred when releasing write lock, cause: " + t.getMessage(), t); } } invoker.destroy(); } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public Result invoke(Invocation invocation) throws RpcException { try { lock.readLock().lock(); if (destroyed.get()) { logger.warn( LoggerCodeConstants.PROTOCOL_CLOSED_SERVER, "", "", "Remote invoker has been destroyed, and unable to invoke anymore."); throw new RpcException("This invoker has been destroyed!"); } return invoker.invoke(invocation); } finally { lock.readLock().unlock(); } } public Invoker<T> getInvoker() { return invoker; } }
6,005
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; import org.apache.dubbo.common.serialize.support.SerializationOptimizer; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import org.apache.dubbo.rpc.support.ProtocolUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.OPTIMIZER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; /** * abstract ProtocolSupport. */ public abstract class AbstractProtocol implements Protocol, ScopeModelAware { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); protected final Map<String, Exporter<?>> exporterMap = new ConcurrentHashMap<>(); /** * <host:port, ProtocolServer> */ protected final Map<String, ProtocolServer> serverMap = new ConcurrentHashMap<>(); // TODO SoftReference protected final Set<Invoker<?>> invokers = new ConcurrentHashSet<>(); protected FrameworkModel frameworkModel; private final Set<String> optimizers = new ConcurrentHashSet<>(); @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } protected static String serviceKey(URL url) { int port = url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); return serviceKey(port, url.getPath(), url.getVersion(), url.getGroup()); } protected static String serviceKey(int port, String serviceName, String serviceVersion, String serviceGroup) { return ProtocolUtils.serviceKey(port, serviceName, serviceVersion, serviceGroup); } @Override public List<ProtocolServer> getServers() { return Collections.unmodifiableList(new ArrayList<>(serverMap.values())); } protected void loadServerProperties(ProtocolServer server) { // read and hold config before destroy int serverShutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(server.getUrl().getScopeModel()); server.getAttributes().put(SHUTDOWN_WAIT_KEY, serverShutdownTimeout); } protected int getServerShutdownTimeout(ProtocolServer server) { return (int) server.getAttributes().getOrDefault(SHUTDOWN_WAIT_KEY, DEFAULT_SERVER_SHUTDOWN_TIMEOUT); } @Override public void destroy() { for (Invoker<?> invoker : invokers) { if (invoker != null) { try { if (logger.isInfoEnabled()) { logger.info("Destroy reference: " + invoker.getUrl()); } invoker.destroy(); } catch (Throwable t) { logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } } invokers.clear(); exporterMap.forEach((key, exporter) -> { if (exporter != null) { try { if (logger.isInfoEnabled()) { logger.info("Unexport service: " + exporter.getInvoker().getUrl()); } exporter.unexport(); } catch (Throwable t) { logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } }); exporterMap.clear(); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { return protocolBindingRefer(type, url); } @Deprecated protected abstract <T> Invoker<T> protocolBindingRefer(Class<T> type, URL url) throws RpcException; public Map<String, Exporter<?>> getExporterMap() { return exporterMap; } public Collection<Exporter<?>> getExporters() { return Collections.unmodifiableCollection(exporterMap.values()); } protected void optimizeSerialization(URL url) throws RpcException { String className = url.getParameter(OPTIMIZER_KEY, ""); if (StringUtils.isEmpty(className) || optimizers.contains(className)) { return; } logger.info("Optimizing the serialization process for Kryo, FST, etc..."); try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); if (!SerializationOptimizer.class.isAssignableFrom(clazz)) { throw new RpcException("The serialization optimizer " + className + " isn't an instance of " + SerializationOptimizer.class.getName()); } SerializationOptimizer optimizer = (SerializationOptimizer) clazz.newInstance(); if (optimizer.getSerializableClasses() == null) { return; } for (Class c : optimizer.getSerializableClasses()) { SerializableClassRegistry.registerClass(c); } optimizers.add(className); } catch (ClassNotFoundException e) { throw new RpcException("Cannot find the serialization optimizer class: " + className, e); } catch (InstantiationException | IllegalAccessException e) { throw new RpcException("Cannot instantiate the serialization optimizer class: " + className, e); } } protected String getAddr(URL url) { String bindIp = url.getParameter(org.apache.dubbo.remoting.Constants.BIND_IP_KEY, url.getHost()); if (url.getParameter(ANYHOST_KEY, false)) { bindIp = ANYHOST_VALUE; } return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(org.apache.dubbo.remoting.Constants.BIND_PORT_KEY, url.getPort()); } }
6,006
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSerializationWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import java.util.List; import static org.apache.dubbo.rpc.model.ScopeModelUtil.getFrameworkModel; @Activate public class ProtocolSerializationWrapper implements Protocol { private final Protocol protocol; public ProtocolSerializationWrapper(Protocol protocol) { this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { getFrameworkModel(invoker.getUrl().getScopeModel()) .getBeanFactory() .getBean(PermittedSerializationKeeper.class) .registerService(invoker.getUrl()); return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { return protocol.refer(type, url); } @Override public void destroy() { protocol.destroy(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } }
6,007
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractProxyProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; /** * AbstractProxyProtocol */ public abstract class AbstractProxyProtocol extends AbstractProtocol { private final List<Class<?>> rpcExceptions = new CopyOnWriteArrayList<Class<?>>(); protected ProxyFactory proxyFactory; public AbstractProxyProtocol() {} public AbstractProxyProtocol(Class<?>... exceptions) { for (Class<?> exception : exceptions) { addRpcException(exception); } } public void addRpcException(Class<?> exception) { this.rpcExceptions.add(exception); } public ProxyFactory getProxyFactory() { return proxyFactory; } public void setProxyFactory(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } @Override @SuppressWarnings("unchecked") public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException { final String uri = serviceKey(invoker.getUrl()); Exporter<T> exporter = (Exporter<T>) exporterMap.get(uri); if (exporter != null) { // When modifying the configuration through override, you need to re-expose the newly modified service. if (Objects.equals(exporter.getInvoker().getUrl(), invoker.getUrl())) { return exporter; } } final Runnable runnable = doExport(proxyFactory.getProxy(invoker, true), invoker.getInterface(), invoker.getUrl()); exporter = new AbstractExporter<T>(invoker) { @Override public void afterUnExport() { exporterMap.remove(uri); if (runnable != null) { try { runnable.run(); } catch (Throwable t) { logger.warn(PROTOCOL_UNSUPPORTED, "", "", t.getMessage(), t); } } } }; exporterMap.put(uri, exporter); return exporter; } @Override protected <T> Invoker<T> protocolBindingRefer(final Class<T> type, final URL url) throws RpcException { final Invoker<T> target = proxyFactory.getInvoker(doRefer(type, url), type, url); Invoker<T> invoker = new AbstractInvoker<T>(type, url) { @Override protected Result doInvoke(Invocation invocation) throws Throwable { try { Result result = target.invoke(invocation); // FIXME result is an AsyncRpcResult instance. Throwable e = result.getException(); if (e != null) { for (Class<?> rpcException : rpcExceptions) { if (rpcException.isAssignableFrom(e.getClass())) { throw getRpcException(type, url, invocation, e); } } } return result; } catch (RpcException e) { if (e.getCode() == RpcException.UNKNOWN_EXCEPTION) { e.setCode(getErrorCode(e.getCause())); } throw e; } catch (Throwable e) { throw getRpcException(type, url, invocation, e); } } @Override public void destroy() { super.destroy(); target.destroy(); invokers.remove(this); AbstractProxyProtocol.this.destroyInternal(url); } }; invokers.add(invoker); return invoker; } // used to destroy unused clients and other resource protected void destroyInternal(URL url) { // subclass override } protected RpcException getRpcException(Class<?> type, URL url, Invocation invocation, Throwable e) { RpcException re = new RpcException( "Failed to invoke remote service: " + type + ", method: " + invocation.getMethodName() + ", cause: " + e.getMessage(), e); re.setCode(getErrorCode(e)); return re; } protected String getAddr(URL url) { String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); if (url.getParameter(ANYHOST_KEY, false)) { bindIp = ANYHOST_VALUE; } return NetUtils.getIpByHost(bindIp) + ":" + url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); } protected int getErrorCode(Throwable e) { return RpcException.UNKNOWN_EXCEPTION; } protected abstract <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException; protected abstract <T> T doRefer(Class<T> type, URL url) throws RpcException; protected class ProxyProtocolServer implements ProtocolServer { private RemotingServer server; private String address; private Map<String, Object> attributes = new ConcurrentHashMap<>(); public ProxyProtocolServer(RemotingServer server) { this.server = server; } @Override public RemotingServer getRemotingServer() { return server; } @Override public String getAddress() { return StringUtils.isNotEmpty(address) ? address : server.getUrl().getAddress(); } @Override public void setAddress(String address) { this.address = address; } @Override public URL getUrl() { return server.getUrl(); } @Override public void close() { server.close(); } @Override public Map<String, Object> getAttributes() { return attributes; } } protected abstract class RemotingServerAdapter implements RemotingServer { public abstract Object getDelegateServer(); /** * @return */ @Override public boolean isBound() { return false; } @Override public Collection<Channel> getChannels() { return null; } @Override public Channel getChannel(InetSocketAddress remoteAddress) { return null; } @Override public void reset(Parameters parameters) {} @Override public void reset(URL url) {} @Override public URL getUrl() { return null; } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException {} @Override public void close() {} @Override public void close(int timeout) {} @Override public void startClose() {} @Override public boolean isClosed() { return false; } } }
6,008
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.utils.UrlUtils; import java.io.IOException; import java.util.Collection; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.common.BaseServiceMetadata.interfaceFromServiceKey; import static org.apache.dubbo.common.BaseServiceMetadata.versionFromServiceKey; public class PermittedSerializationKeeper { private final ConcurrentMap<String, Set<Byte>> serviceToSerializationId = new ConcurrentHashMap<>(); private final Set<Byte> globalPermittedSerializationIds = new ConcurrentHashSet<>(); public void registerService(URL url) { Set<Byte> set = ConcurrentHashMapUtils.computeIfAbsent( serviceToSerializationId, keyWithoutGroup(url.getServiceKey()), k -> new ConcurrentHashSet<>()); Collection<String> serializations = UrlUtils.allSerializations(url); for (String serialization : serializations) { Byte id = CodecSupport.getIDByName(serialization); if (id != null) { set.add(id); globalPermittedSerializationIds.add(id); } } } public boolean checkSerializationPermitted(String serviceKeyWithoutGroup, Byte id) throws IOException { Set<Byte> set = serviceToSerializationId.get(serviceKeyWithoutGroup); if (set == null) { throw new IOException("Service " + serviceKeyWithoutGroup + " not found, invocation rejected."); } return set.contains(id); } private static String keyWithoutGroup(String serviceKey) { String interfaceName = interfaceFromServiceKey(serviceKey); String version = versionFromServiceKey(serviceKey); if (StringUtils.isEmpty(version)) { return interfaceName; } return interfaceName + CommonConstants.GROUP_CHAR_SEPARATOR + version; } }
6,009
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; /** * InvokerWrapper */ public class InvokerWrapper<T> implements Invoker<T> { protected final Invoker<T> invoker; private final URL url; public InvokerWrapper(Invoker<T> invoker, URL url) { this.invoker = invoker; this.url = url; } @Override public Class<T> getInterface() { return invoker.getInterface(); } @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return invoker.isAvailable(); } @Override public Result invoke(Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void destroy() { invoker.destroy(); } }
6,010
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractExporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; /** * AbstractExporter. */ public abstract class AbstractExporter<T> implements Exporter<T> { protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Invoker<T> invoker; private volatile boolean unexported = false; public AbstractExporter(Invoker<T> invoker) { if (invoker == null) { throw new IllegalStateException("service invoker == null"); } if (invoker.getInterface() == null) { throw new IllegalStateException("service type == null"); } if (invoker.getUrl() == null) { throw new IllegalStateException("service url == null"); } this.invoker = invoker; } @Override public Invoker<T> getInvoker() { return invoker; } @Override public final void unexport() { if (unexported) { return; } unexported = true; getInvoker().destroy(); afterUnExport(); } @Override public void register() {} @Override public void unregister() {} /** * subclasses need to override this method to destroy resources. */ public void afterUnExport() {} @Override public String toString() { return getInvoker().toString(); } }
6,011
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.InvokerListener; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.listener.InjvmExporterListener; import org.apache.dubbo.rpc.listener.ListenerExporterWrapper; import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper; import org.apache.dubbo.rpc.model.ScopeModelUtil; import java.util.Collections; import java.util.List; import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_TYPE_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; /** * ListenerProtocol */ @Activate(order = 200) public class ProtocolListenerWrapper implements Protocol { private final Protocol protocol; public ProtocolListenerWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { if (UrlUtils.isRegistry(invoker.getUrl())) { return protocol.export(invoker); } List<ExporterListener> exporterListeners = ScopeModelUtil.getExtensionLoader( ExporterListener.class, invoker.getUrl().getScopeModel()) .getActivateExtension(invoker.getUrl(), EXPORTER_LISTENER_KEY); if (LOCAL_PROTOCOL.equals(invoker.getUrl().getProtocol())) { exporterListeners.add(invoker.getUrl() .getOrDefaultFrameworkModel() .getBeanFactory() .getBean(InjvmExporterListener.class)); } return new ListenerExporterWrapper<T>( protocol.export(invoker), Collections.unmodifiableList(exporterListeners)); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (UrlUtils.isRegistry(url)) { return protocol.refer(type, url); } Invoker<T> invoker = protocol.refer(type, url); if (StringUtils.isEmpty(url.getParameter(REGISTRY_CLUSTER_TYPE_KEY))) { invoker = new ListenerInvokerWrapper<>( invoker, Collections.unmodifiableList(ScopeModelUtil.getExtensionLoader( InvokerListener.class, invoker.getUrl().getScopeModel()) .getActivateExtension(url, INVOKER_LISTENER_KEY))); } return invoker; } @Override public void destroy() { protocol.destroy(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } }
6,012
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/ProtocolSecurityWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; 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.SerializeSecurityConfigurator; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.model.ServiceModel; import java.util.List; import java.util.Optional; import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR; @Activate(order = 200) public class ProtocolSecurityWrapper implements Protocol { private final Protocol protocol; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ProtocolSecurityWrapper.class); public ProtocolSecurityWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { try { ServiceModel serviceModel = invoker.getUrl().getServiceModel(); ScopeModel scopeModel = invoker.getUrl().getScopeModel(); SerializeSecurityConfigurator serializeSecurityConfigurator = ScopeModelUtil.getModuleModel(scopeModel) .getBeanFactory() .getBean(SerializeSecurityConfigurator.class); serializeSecurityConfigurator.refreshStatus(); serializeSecurityConfigurator.refreshCheck(); Optional.ofNullable(invoker.getInterface()).ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceModel) .map(ServiceDescriptor::getServiceInterfaceClass) .ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceMetadata) .map(ServiceMetadata::getServiceType) .ifPresent(serializeSecurityConfigurator::registerInterface); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "", "", "Failed to register interface for security check", t); } return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { try { ServiceModel serviceModel = url.getServiceModel(); ScopeModel scopeModel = url.getScopeModel(); SerializeSecurityConfigurator serializeSecurityConfigurator = ScopeModelUtil.getModuleModel(scopeModel) .getBeanFactory() .getBean(SerializeSecurityConfigurator.class); serializeSecurityConfigurator.refreshStatus(); serializeSecurityConfigurator.refreshCheck(); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceModel) .map(ServiceDescriptor::getServiceInterfaceClass) .ifPresent(serializeSecurityConfigurator::registerInterface); Optional.ofNullable(serviceModel) .map(ServiceModel::getServiceMetadata) .map(ServiceMetadata::getServiceType) .ifPresent(serializeSecurityConfigurator::registerInterface); serializeSecurityConfigurator.registerInterface(type); } catch (Throwable t) { logger.error(INTERNAL_ERROR, "", "", "Failed to register interface for security check", t); } return protocol.refer(type, url); } @Override public void destroy() { protocol.destroy(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } }
6,013
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/AbstractInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; import org.apache.dubbo.common.Node; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.InvokeMode; 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.RpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_VERSION; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; /** * This Invoker works on Consumer side. */ public abstract class AbstractInvoker<T> implements Invoker<T> { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractInvoker.class); /** * Service interface type */ private final Class<T> type; /** * {@link Node} url */ private final URL url; /** * {@link Invoker} default attachment */ private final Map<String, Object> attachment; protected final String version; /** * {@link Node} available */ private volatile boolean available = true; /** * {@link Node} destroy */ private volatile boolean destroyed = false; /** * Whether set future to Thread Local when invocation mode is sync */ private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); // -- Constructor public AbstractInvoker(Class<T> type, URL url) { this(type, url, (Map<String, Object>) null); } public AbstractInvoker(Class<T> type, URL url, String[] keys) { this(type, url, convertAttachment(url, keys)); } public AbstractInvoker(Class<T> type, URL url, Map<String, Object> attachment) { if (type == null) { throw new IllegalArgumentException("service type == null"); } if (url == null) { throw new IllegalArgumentException("service url == null"); } this.type = type; this.url = url; this.attachment = attachment == null ? null : Collections.unmodifiableMap(attachment); this.version = url.getVersion(DEFAULT_VERSION); } private static Map<String, Object> convertAttachment(URL url, String[] keys) { if (ArrayUtils.isEmpty(keys)) { return null; } Map<String, Object> attachment = new HashMap<>(keys.length); for (String key : keys) { String value = url.getParameter(key); if (value != null && value.length() > 0) { attachment.put(key, value); } } return attachment; } // -- Public api @Override public Class<T> getInterface() { return type; } @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return available; } @Override public void destroy() { this.destroyed = true; setAvailable(false); } protected void setAvailable(boolean available) { this.available = available; } public boolean isDestroyed() { return destroyed; } @Override public String toString() { return getInterface() + " -> " + (getUrl() == null ? "" : getUrl().getAddress()); } @Override public Result invoke(Invocation inv) throws RpcException { // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed if (isDestroyed()) { logger.warn( PROTOCOL_FAILED_REQUEST, "", "", "Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); } RpcInvocation invocation = (RpcInvocation) inv; // prepare rpc invocation prepareInvocation(invocation); // do invoke rpc invocation and return async result AsyncRpcResult asyncResult = doInvokeAndReturn(invocation); // wait rpc result if sync waitForResultIfSync(asyncResult, invocation); return asyncResult; } private void prepareInvocation(RpcInvocation inv) { inv.setInvoker(this); addInvocationAttachments(inv); inv.setInvokeMode(RpcUtils.getInvokeMode(url, inv)); RpcUtils.attachInvocationIdIfAsync(getUrl(), inv); attachInvocationSerializationId(inv); } /** * Attach Invocation Serialization id * <p> * <ol> * <li>Obtain the value from <code>prefer_serialization</code></li> * <li>If the preceding information is not obtained, obtain the value from <code>serialization</code></li> * <li>If neither is obtained, use the default value</li> * </ol> * </p> * * @param inv inv */ private void attachInvocationSerializationId(RpcInvocation inv) { Byte serializationId = UrlUtils.serializationId(getUrl()); if (serializationId != null) { inv.put(SERIALIZATION_ID_KEY, serializationId); } } private void addInvocationAttachments(RpcInvocation invocation) { // invoker attachment if (CollectionUtils.isNotEmptyMap(attachment)) { invocation.addObjectAttachmentsIfAbsent(attachment); } // client context attachment Map<String, Object> clientContextAttachments = RpcContext.getClientAttachment().getObjectAttachments(); if (CollectionUtils.isNotEmptyMap(clientContextAttachments)) { invocation.addObjectAttachmentsIfAbsent(clientContextAttachments); } } private AsyncRpcResult doInvokeAndReturn(RpcInvocation invocation) { AsyncRpcResult asyncResult; try { asyncResult = (AsyncRpcResult) doInvoke(invocation); } catch (InvocationTargetException e) { Throwable te = e.getTargetException(); if (te != null) { // if biz exception if (te instanceof RpcException) { ((RpcException) te).setCode(RpcException.BIZ_EXCEPTION); } asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, te, invocation); } else { asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } } catch (RpcException e) { // if biz exception if (e.isBiz()) { asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } else { throw e; } } catch (Throwable e) { asyncResult = AsyncRpcResult.newDefaultAsyncResult(null, e, invocation); } if (setFutureWhenSync || invocation.getInvokeMode() != InvokeMode.SYNC) { // set server context RpcContext.getServiceContext().setFuture(new FutureAdapter<>(asyncResult.getResponseFuture())); } return asyncResult; } private void waitForResultIfSync(AsyncRpcResult asyncResult, RpcInvocation invocation) { if (InvokeMode.SYNC != invocation.getInvokeMode()) { return; } try { /* * NOTICE! * must call {@link java.util.concurrent.CompletableFuture#get(long, TimeUnit)} because * {@link java.util.concurrent.CompletableFuture#get()} was proved to have serious performance drop. */ Object timeoutKey = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY); long timeout = RpcUtils.convertToNumber(timeoutKey, Integer.MAX_VALUE); asyncResult.get(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RpcException( "Interrupted unexpectedly while waiting for remote result to return! method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (ExecutionException e) { Throwable rootCause = e.getCause(); if (rootCause instanceof TimeoutException) { throw new RpcException( RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } else if (rootCause instanceof RemotingException) { throw new RpcException( RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } else if (rootCause instanceof SerializationException) { throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, "Invoke remote method failed cause by serialization error. remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } else { throw new RpcException( RpcException.UNKNOWN_EXCEPTION, "Fail to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } } catch (java.util.concurrent.TimeoutException e) { throw new RpcException( RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (Throwable e) { throw new RpcException(e.getMessage(), e); } } // -- Protected api protected ExecutorService getCallbackExecutor(URL url, Invocation inv) { if (InvokeMode.SYNC == RpcUtils.getInvokeMode(getUrl(), inv)) { return new ThreadlessExecutor(); } return ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .getExecutor(url); } /** * Specific implementation of the {@link #invoke(Invocation)} method */ protected abstract Result doInvoke(Invocation invocation) throws Throwable; }
6,014
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/InvokerCountWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol; 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.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.RpcException; @Activate(order = Integer.MIN_VALUE + 1000) public class InvokerCountWrapper implements Protocol { private final Protocol protocol; public InvokerCountWrapper(Protocol protocol) { this.protocol = protocol; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { if (UrlUtils.isRegistry(url)) { return protocol.refer(type, url); } return new ReferenceCountInvokerWrapper<>(protocol.refer(type, url)); } @Override public void destroy() { protocol.destroy(); } }
6,015
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/FutureAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.dubbo; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * This is the type of the Future instance users get in an async call: * 1. unwrap AppResponse in appResponseFuture and convert to plain biz result represented by FutureAdapter. * 2. customized behaviors meaningful for RPC, for example, {@link #cancel(boolean)} */ public class FutureAdapter<V> extends CompletableFuture<V> { private final CompletableFuture<AppResponse> appResponseFuture; public FutureAdapter(CompletableFuture<AppResponse> future) { this.appResponseFuture = future; future.whenComplete((appResponse, t) -> { if (t != null) { if (t instanceof CompletionException) { t = t.getCause(); } this.completeExceptionally(t); } else { if (appResponse.hasException()) { this.completeExceptionally(appResponse.getException()); } else { this.complete((V) appResponse.getValue()); } } }); } // TODO figure out the meaning of cancel in DefaultFuture. @Override public boolean cancel(boolean mayInterruptIfRunning) { // Invocation invocation = invocationSoftReference.get(); // if (invocation != null) { // invocation.getInvoker().invoke(cancel); // } return appResponseFuture.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return appResponseFuture.isCancelled(); } @Override public boolean isDone() { return super.isDone(); } @Override @SuppressWarnings("unchecked") public V get() throws InterruptedException, ExecutionException { try { return super.get(); } catch (ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } @Override @SuppressWarnings("unchecked") public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return super.get(timeout, unit); } catch (TimeoutException | ExecutionException | InterruptedException e) { throw e; } catch (Throwable e) { throw new RpcException(e); } } }
6,016
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * {@link org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter} was in dubbo-rpc-dubbo module, * considering some users will use this class directly, keep the package not changed. */ package org.apache.dubbo.rpc.protocol.dubbo;
6,017
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; 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.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.InvokeMode; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.TimeoutCountDown; import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_TIMEOUT_COUNTDOWN_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY_LOWER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; import static org.apache.dubbo.rpc.Constants.$ECHO; import static org.apache.dubbo.rpc.Constants.$ECHO_PARAMETER_DESC; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY; import static org.apache.dubbo.rpc.Constants.ID_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_KEY; /** * RpcUtils */ public class RpcUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(RpcUtils.class); private static final AtomicLong INVOKE_ID = new AtomicLong(0); public static Class<?> getReturnType(Invocation invocation) { try { if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName().startsWith("$")) { String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); return method == null ? null : method.getReturnType(); } } } catch (Throwable t) { logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", t.getMessage(), t); } return null; } public static Type[] getReturnTypes(Invocation invocation) { try { if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName().startsWith("$")) { Type[] returnTypes = null; if (invocation instanceof RpcInvocation) { returnTypes = ((RpcInvocation) invocation).getReturnTypes(); if (returnTypes != null) { return returnTypes; } } String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); if (method != null) { returnTypes = ReflectUtils.getReturnTypes(method); } } if (returnTypes != null) { return returnTypes; } } } catch (Throwable t) { logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", t.getMessage(), t); } return null; } public static Long getInvocationId(Invocation inv) { String id = inv.getAttachment(ID_KEY); return id == null ? null : new Long(id); } /** * Idempotent operation: invocation id will be added in async operation by default * * @param url * @param inv */ public static void attachInvocationIdIfAsync(URL url, Invocation inv) { if (isAttachInvocationId(url, inv) && getInvocationId(inv) == null && inv instanceof RpcInvocation) { inv.setAttachment(ID_KEY, String.valueOf(INVOKE_ID.getAndIncrement())); } } private static boolean isAttachInvocationId(URL url, Invocation invocation) { String value = url.getMethodParameter(invocation.getMethodName(), AUTO_ATTACH_INVOCATIONID_KEY); if (value == null) { // add invocationid in async operation by default return isAsync(url, invocation); } return Boolean.TRUE.toString().equalsIgnoreCase(value); } public static String getMethodName(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) && invocation.getArguments() != null && invocation.getArguments().length > 0 && invocation.getArguments()[0] instanceof String) { return (String) invocation.getArguments()[0]; } return invocation.getMethodName(); } public static Object[] getArguments(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) && invocation.getArguments() != null && invocation.getArguments().length > 2 && invocation.getArguments()[2] instanceof Object[]) { return (Object[]) invocation.getArguments()[2]; } return invocation.getArguments(); } public static Class<?>[] getParameterTypes(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) && invocation.getArguments() != null && invocation.getArguments().length > 1 && invocation.getArguments()[1] instanceof String[]) { String[] types = (String[]) invocation.getArguments()[1]; if (types == null) { return new Class<?>[0]; } Class<?>[] parameterTypes = new Class<?>[types.length]; for (int i = 0; i < types.length; i++) { parameterTypes[i] = ReflectUtils.forName(types[i]); } return parameterTypes; } return invocation.getParameterTypes(); } public static boolean isAsync(URL url, Invocation inv) { boolean isAsync; if (inv instanceof RpcInvocation) { RpcInvocation rpcInvocation = (RpcInvocation) inv; if (rpcInvocation.getInvokeMode() != null) { return rpcInvocation.getInvokeMode() == InvokeMode.ASYNC; } } if (Boolean.TRUE.toString().equals(inv.getAttachment(ASYNC_KEY))) { isAsync = true; } else { isAsync = url.getMethodParameter(getMethodName(inv), ASYNC_KEY, false); } return isAsync; } public static boolean isReturnTypeFuture(Invocation inv) { Class<?> clazz; if (inv instanceof RpcInvocation) { clazz = ((RpcInvocation) inv).getReturnType(); } else { clazz = getReturnType(inv); } return (clazz != null && CompletableFuture.class.isAssignableFrom(clazz)) || isGenericAsync(inv); } public static boolean isGenericAsync(Invocation inv) { return $INVOKE_ASYNC.equals(inv.getMethodName()); } // check parameterTypesDesc to fix CVE-2020-1948 public static boolean isGenericCall(String parameterTypesDesc, String method) { return ($INVOKE.equals(method) || $INVOKE_ASYNC.equals(method)) && GENERIC_PARAMETER_DESC.equals(parameterTypesDesc); } // check parameterTypesDesc to fix CVE-2020-1948 public static boolean isEcho(String parameterTypesDesc, String method) { return $ECHO.equals(method) && $ECHO_PARAMETER_DESC.equals(parameterTypesDesc); } public static InvokeMode getInvokeMode(URL url, Invocation inv) { if (inv instanceof RpcInvocation) { RpcInvocation rpcInvocation = (RpcInvocation) inv; if (rpcInvocation.getInvokeMode() != null) { return rpcInvocation.getInvokeMode(); } } if (isReturnTypeFuture(inv)) { return InvokeMode.FUTURE; } else if (isAsync(url, inv)) { return InvokeMode.ASYNC; } else { return InvokeMode.SYNC; } } public static boolean isOneway(URL url, Invocation inv) { boolean isOneway; if (Boolean.FALSE.toString().equals(inv.getAttachment(RETURN_KEY))) { isOneway = true; } else { isOneway = !url.getMethodParameter(getMethodName(inv), RETURN_KEY, true); } return isOneway; } private static Method getMethodByService(Invocation invocation, String service) throws NoSuchMethodException { Class<?> invokerInterface = invocation.getInvoker().getInterface(); Class<?> cls = invokerInterface != null ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) : ReflectUtils.forName(service); Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); if (method.getReturnType() == void.class) { return null; } return method; } public static long getTimeout(Invocation invocation, long defaultTimeout) { long timeout = defaultTimeout; Object genericTimeout = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_ATTACHMENT_KEY); if (genericTimeout == null) { genericTimeout = invocation.getObjectAttachmentWithoutConvert(TIMEOUT_ATTACHMENT_KEY_LOWER); } if (genericTimeout != null) { timeout = convertToNumber(genericTimeout, defaultTimeout); } return timeout; } public static long getTimeout( URL url, String methodName, RpcContext context, Invocation invocation, long defaultTimeout) { long timeout = defaultTimeout; Object timeoutFromContext = context.getObjectAttachment(TIMEOUT_KEY); Object timeoutFromInvocation = invocation.getObjectAttachment(TIMEOUT_KEY); if (timeoutFromContext != null) { timeout = convertToNumber(timeoutFromContext, defaultTimeout); } else if (timeoutFromInvocation != null) { timeout = convertToNumber(timeoutFromInvocation, defaultTimeout); } else if (url != null) { timeout = url.getMethodPositiveParameter(methodName, TIMEOUT_KEY, defaultTimeout); } return timeout; } public static int calculateTimeout(URL url, Invocation invocation, String methodName, long defaultTimeout) { Object countdown = RpcContext.getClientAttachment().getObjectAttachment(TIME_COUNTDOWN_KEY); int timeout = (int) defaultTimeout; if (countdown == null) { if (url != null) { timeout = (int) RpcUtils.getTimeout( url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); if (url.getMethodParameter(methodName, ENABLE_TIMEOUT_COUNTDOWN_KEY, false)) { // pass timeout to remote server invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout); } } } else { TimeoutCountDown timeoutCountDown = (TimeoutCountDown) countdown; timeout = (int) timeoutCountDown.timeRemaining(TimeUnit.MILLISECONDS); // pass timeout to remote server invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout); } invocation.getObjectAttachments().remove(TIME_COUNTDOWN_KEY); return timeout; } public static Long convertToNumber(Object obj, long defaultTimeout) { Long timeout = convertToNumber(obj); return timeout == null ? defaultTimeout : timeout; } public static Long convertToNumber(Object obj) { Long timeout = null; try { if (obj instanceof String) { timeout = Long.parseLong((String) obj); } else if (obj instanceof Number) { timeout = ((Number) obj).longValue(); } else { timeout = Long.parseLong(obj.toString()); } } catch (Exception e) { // ignore } return timeout; } }
6,018
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/Dubbo2RpcExceptionUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.lang.reflect.Constructor; public class Dubbo2RpcExceptionUtils { private static final Class<? extends org.apache.dubbo.rpc.RpcException> RPC_EXCEPTION_CLASS; private static final Constructor<? extends org.apache.dubbo.rpc.RpcException> RPC_EXCEPTION_CONSTRUCTOR_I_S_T; static { RPC_EXCEPTION_CLASS = loadClass(); RPC_EXCEPTION_CONSTRUCTOR_I_S_T = loadConstructor(int.class, String.class, Throwable.class); } @SuppressWarnings("unchecked") private static Class<? extends org.apache.dubbo.rpc.RpcException> loadClass() { try { Class<?> clazz = Class.forName("com.alibaba.dubbo.rpc.RpcException"); if (org.apache.dubbo.rpc.RpcException.class.isAssignableFrom(clazz)) { return (Class<? extends org.apache.dubbo.rpc.RpcException>) clazz; } else { return null; } } catch (Throwable e) { return null; } } private static Constructor<? extends org.apache.dubbo.rpc.RpcException> loadConstructor( Class<?>... parameterTypes) { if (RPC_EXCEPTION_CLASS == null) { return null; } try { return RPC_EXCEPTION_CLASS.getConstructor(parameterTypes); } catch (Throwable e) { return null; } } public static boolean isRpcExceptionClassLoaded() { return RPC_EXCEPTION_CLASS != null && RPC_EXCEPTION_CONSTRUCTOR_I_S_T != null; } public static Class<? extends org.apache.dubbo.rpc.RpcException> getRpcExceptionClass() { return RPC_EXCEPTION_CLASS; } public static org.apache.dubbo.rpc.RpcException newRpcException(int code, String message, Throwable cause) { if (RPC_EXCEPTION_CONSTRUCTOR_I_S_T == null) { return null; } try { return RPC_EXCEPTION_CONSTRUCTOR_I_S_T.newInstance(code, message, cause); } catch (Throwable e) { return null; } } }
6,019
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.AbstractProtocol; /** * MockProtocol is used for generating a mock invoker by URL and type on consumer side */ public final class MockProtocol extends AbstractProtocol { @Override public int getDefaultPort() { return 0; } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { throw new UnsupportedOperationException(); } @Override public <T> Invoker<T> protocolBindingRefer(Class<T> type, URL url) throws RpcException { return new MockInvoker<>(url, type); } }
6,020
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/AccessLogData.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.common.utils.ToStringUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * AccessLogData is a container for log event data. In internally uses map and store each field of log as value. It * does not generate any dynamic value e.g. time stamp, local jvm machine host address etc. It does not allow any null * or empty key. */ public final class AccessLogData { private static final String MESSAGE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSSS"; private static final DateTimeFormatter MESSAGE_DATE_FORMATTER = DateTimeFormatter.ofPattern(MESSAGE_DATE_FORMAT); private static final String VERSION = "version"; private static final String GROUP = "group"; private static final String SERVICE = "service"; private static final String METHOD_NAME = "method-name"; private static final String INVOCATION_TIME = "invocation-time"; private static final String OUT_TIME = "out-time"; private static final String TYPES = "types"; private static final String ARGUMENTS = "arguments"; private static final String REMOTE_HOST = "remote-host"; private static final String REMOTE_PORT = "remote-port"; private static final String LOCAL_HOST = "localhost"; private static final String LOCAL_PORT = "local-port"; /** * This is used to store log data in key val format. */ private final Map<String, Object> data; /** * Default constructor. */ private AccessLogData() { RpcContext context = RpcContext.getServiceContext(); data = new HashMap<>(); setLocalHost(context.getLocalHost()); setLocalPort(context.getLocalPort()); setRemoteHost(context.getRemoteHost()); setRemotePort(context.getRemotePort()); } /** * Get new instance of log data. * * @return instance of AccessLogData */ public static AccessLogData newLogData() { return new AccessLogData(); } /** * Add version information. * * @param version */ public void setVersion(String version) { set(VERSION, version); } /** * Add service name. * * @param serviceName */ public void setServiceName(String serviceName) { set(SERVICE, serviceName); } /** * Add group name * * @param group */ public void setGroup(String group) { set(GROUP, group); } /** * Set the invocation date. As an argument it accept date string. * * @param invocationTime */ public void setInvocationTime(Date invocationTime) { set(INVOCATION_TIME, invocationTime); } /** * Set the out date. As an argument it accept date string. * * @param outTime */ public void setOutTime(Date outTime) { set(OUT_TIME, outTime); } /** * Set caller remote host * * @param remoteHost */ private void setRemoteHost(String remoteHost) { set(REMOTE_HOST, remoteHost); } /** * Set caller remote port. * * @param remotePort */ private void setRemotePort(Integer remotePort) { set(REMOTE_PORT, remotePort); } /** * Set local host * * @param localHost */ private void setLocalHost(String localHost) { set(LOCAL_HOST, localHost); } /** * Set local port of exported service * * @param localPort */ private void setLocalPort(Integer localPort) { set(LOCAL_PORT, localPort); } /** * Set target method name. * * @param methodName */ public void setMethodName(String methodName) { set(METHOD_NAME, methodName); } /** * Set invocation's method's input parameter's types * * @param types */ public void setTypes(Class[] types) { set(TYPES, types != null ? Arrays.copyOf(types, types.length) : null); } /** * Sets invocation arguments * * @param arguments */ public void setArguments(Object[] arguments) { set(ARGUMENTS, arguments != null ? Arrays.copyOf(arguments, arguments.length) : null); } /** * Return gthe service of access log entry * * @return */ public String getServiceName() { return get(SERVICE).toString(); } public String getLogMessage() { StringBuilder sn = new StringBuilder(); sn.append("[") .append(LocalDateTime.ofInstant(getInvocationTime().toInstant(), ZoneId.systemDefault()) .format(MESSAGE_DATE_FORMATTER)) .append("] ") .append("-> ") .append("[") .append(LocalDateTime.ofInstant(getOutTime().toInstant(), ZoneId.systemDefault()) .format(MESSAGE_DATE_FORMATTER)) .append("] ") .append(get(REMOTE_HOST)) .append(':') .append(get(REMOTE_PORT)) .append(" -> ") .append(get(LOCAL_HOST)) .append(':') .append(get(LOCAL_PORT)) .append(" - "); String group = get(GROUP) != null ? get(GROUP).toString() : ""; if (StringUtils.isNotEmpty(group)) { sn.append(group).append('/'); } sn.append(get(SERVICE)); String version = get(VERSION) != null ? get(VERSION).toString() : ""; if (StringUtils.isNotEmpty(version)) { sn.append(':').append(version); } sn.append(' '); sn.append(get(METHOD_NAME)); sn.append('('); Class<?>[] types = get(TYPES) != null ? (Class<?>[]) get(TYPES) : new Class[0]; boolean first = true; for (Class<?> type : types) { if (first) { first = false; } else { sn.append(','); } sn.append(type.getName()); } sn.append(") "); Object[] args = get(ARGUMENTS) != null ? (Object[]) get(ARGUMENTS) : null; if (args != null && args.length > 0) { sn.append(ToStringUtils.printToString(args)); } return sn.toString(); } private Date getInvocationTime() { return (Date) get(INVOCATION_TIME); } private Date getOutTime() { return (Date) get(OUT_TIME); } /** * Return value of key * * @param key * @return */ private Object get(String key) { return data.get(key); } /** * Add log key along with his value. * * @param key Any not null or non empty string * @param value Any object including null. */ private void set(String key, Object value) { data.put(key, value); } public void buildAccessLogData(Invoker<?> invoker, Invocation inv) { setServiceName(invoker.getInterface().getName()); setMethodName(RpcUtils.getMethodName(inv)); setVersion(invoker.getUrl().getVersion()); setGroup(invoker.getUrl().getGroup()); setInvocationTime(new Date()); setTypes(inv.getParameterTypes()); setArguments(inv.getArguments()); } }
6,021
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionDirector; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX; import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX; import static org.apache.dubbo.rpc.Constants.MOCK_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_KEY; import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX; import static org.apache.dubbo.rpc.Constants.THROW_PREFIX; public final class MockInvoker<T> implements Invoker<T> { private final ProxyFactory proxyFactory; private static final Map<String, Invoker<?>> MOCK_MAP = new ConcurrentHashMap<String, Invoker<?>>(); private static final Map<String, Throwable> THROWABLE_MAP = new ConcurrentHashMap<String, Throwable>(); private final URL url; private final Class<T> type; public MockInvoker(URL url, Class<T> type) { this.url = url; this.type = type; this.proxyFactory = url.getOrDefaultFrameworkModel() .getExtensionLoader(ProxyFactory.class) .getAdaptiveExtension(); } public static Object parseMockValue(String mock) throws Exception { return parseMockValue(mock, null); } public static Object parseMockValue(String mock, Type[] returnTypes) throws Exception { Object value; if ("empty".equals(mock)) { value = ReflectUtils.getEmptyObject( returnTypes != null && returnTypes.length > 0 ? (Class<?>) returnTypes[0] : null); } else if ("null".equals(mock)) { value = null; } else if ("true".equals(mock)) { value = true; } else if ("false".equals(mock)) { value = false; } else if (mock.length() >= 2 && (mock.startsWith("\"") && mock.endsWith("\"") || mock.startsWith("\'") && mock.endsWith("\'"))) { value = mock.subSequence(1, mock.length() - 1); } else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) { value = mock; } else if (StringUtils.isNumeric(mock, false)) { value = JsonUtils.toJavaObject(mock, Object.class); } else if (mock.startsWith("{")) { value = JsonUtils.toJavaObject(mock, Map.class); } else if (mock.startsWith("[")) { value = JsonUtils.toJavaList(mock, Object.class); } else { value = mock; } if (ArrayUtils.isNotEmpty(returnTypes)) { value = PojoUtils.realize(value, (Class<?>) returnTypes[0], returnTypes.length > 1 ? returnTypes[1] : null); } return value; } @Override public Result invoke(Invocation invocation) throws RpcException { if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(this); } String mock = getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY); if (StringUtils.isBlank(mock)) { throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url)); } mock = normalizeMock(URL.decode(mock)); if (mock.startsWith(RETURN_PREFIX)) { mock = mock.substring(RETURN_PREFIX.length()).trim(); try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value = parseMockValue(mock, returnTypes); return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } catch (Exception ew) { throw new RpcException( "mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: " + url, ew); } } else if (mock.startsWith(THROW_PREFIX)) { mock = mock.substring(THROW_PREFIX.length()).trim(); if (StringUtils.isBlank(mock)) { throw new RpcException("mocked exception for service degradation."); } else { // user customized class Throwable t = getThrowable(mock); throw new RpcException(RpcException.BIZ_EXCEPTION, t); } } else { // impl mock try { Invoker<T> invoker = getInvoker(mock); return invoker.invoke(invocation); } catch (Throwable t) { throw new RpcException("Failed to create mock implementation class " + mock, t); } } } public static Throwable getThrowable(String throwstr) { Throwable throwable = THROWABLE_MAP.get(throwstr); if (throwable != null) { return throwable; } try { Throwable t; Class<?> bizException = ReflectUtils.forName(throwstr); Constructor<?> constructor; constructor = ReflectUtils.findConstructor(bizException, String.class); t = (Throwable) constructor.newInstance(new Object[] {"mocked exception for service degradation."}); if (THROWABLE_MAP.size() < 1000) { THROWABLE_MAP.put(throwstr, t); } return t; } catch (Exception e) { throw new RpcException("mock throw error :" + throwstr + " argument error.", e); } } @SuppressWarnings("unchecked") private Invoker<T> getInvoker(String mock) { Class<T> serviceType = (Class<T>) ReflectUtils.forName(url.getServiceInterface()); String mockService = ConfigUtils.isDefault(mock) ? serviceType.getName() + "Mock" : mock; Invoker<T> invoker = (Invoker<T>) MOCK_MAP.get(mockService); if (invoker != null) { return invoker; } T mockObject = (T) getMockObject(url.getOrDefaultApplicationModel().getExtensionDirector(), mock, serviceType); invoker = proxyFactory.getInvoker(mockObject, serviceType, url); if (MOCK_MAP.size() < 10000) { MOCK_MAP.put(mockService, invoker); } return invoker; } @SuppressWarnings("unchecked") public static Object getMockObject(ExtensionDirector extensionDirector, String mockService, Class serviceType) { boolean isDefault = ConfigUtils.isDefault(mockService); if (isDefault) { mockService = serviceType.getName() + "Mock"; } Class<?> mockClass; try { mockClass = ReflectUtils.forName(mockService); } catch (Exception e) { if (!isDefault) { // does not check Spring bean if it is default config. ExtensionInjector extensionFactory = extensionDirector .getExtensionLoader(ExtensionInjector.class) .getAdaptiveExtension(); Object obj = extensionFactory.getInstance(serviceType, mockService); if (obj != null) { return obj; } } throw new IllegalStateException( "Did not find mock class or instance " + mockService + ", please check if there's mock class or instance implementing interface " + serviceType.getName(), e); } if (mockClass == null || !serviceType.isAssignableFrom(mockClass)) { throw new IllegalStateException( "The mock class " + mockClass.getName() + " not implement interface " + serviceType.getName()); } try { return mockClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } /** * Normalize mock string: * * <ol> * <li>return => return null</li> * <li>fail => default</li> * <li>force => default</li> * <li>fail:throw/return foo => throw/return foo</li> * <li>force:throw/return foo => throw/return foo</li> * </ol> * * @param mock mock string * @return normalized mock string */ public static String normalizeMock(String mock) { if (mock == null) { return mock; } mock = mock.trim(); if (mock.length() == 0) { return mock; } if (RETURN_KEY.equalsIgnoreCase(mock)) { return RETURN_PREFIX + "null"; } if (ConfigUtils.isDefault(mock) || "fail".equalsIgnoreCase(mock) || "force".equalsIgnoreCase(mock)) { return "default"; } if (mock.startsWith(FAIL_PREFIX)) { mock = mock.substring(FAIL_PREFIX.length()).trim(); } if (mock.startsWith(FORCE_PREFIX)) { mock = mock.substring(FORCE_PREFIX.length()).trim(); } if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX)) { mock = mock.replace('`', '"'); } return mock; } @Override public URL getUrl() { return this.url; } @Override public boolean isAvailable() { return true; } @Override public void destroy() { // do nothing } @Override public Class<T> getInterface() { return type; } }
6,022
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubProxyFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.ServerService; /** * Stub proxy factory is used to generate non-reflection invoker and proxy. It relies on Dubbo3 * Triple compiler. */ public class StubProxyFactory implements ProxyFactory { @Override public <T> T getProxy(Invoker<T> invoker) throws RpcException { return StubSuppliers.createStub(invoker.getUrl().getServiceInterface(), invoker); } @Override public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException { return getProxy(invoker); } @Override @SuppressWarnings("all") public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException { return ((ServerService) proxy).getInvoker(url); } }
6,023
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import java.util.concurrent.CompletableFuture; /** * A generic methodHandler for stub invocation * * @param <T> Request Type * @param <R> Response Type */ public interface StubMethodHandler<T, R> { /** * Invoke method * * @param arguments may contain {@link org.apache.dubbo.common.stream.StreamObserver} or just * single request instance. * @return an Async or Sync future */ CompletableFuture<?> invoke(Object[] arguments); }
6,024
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker; import java.util.Map; public class StubInvoker<T> extends AbstractProxyInvoker<T> { private final Map<String, StubMethodHandler<?, ?>> handlers; public StubInvoker(T proxy, URL url, Class<T> type, Map<String, StubMethodHandler<?, ?>> handlers) { super(proxy, type, url); this.handlers = handlers; } @Override protected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable { return handlers.get(methodName).invoke(arguments); } }
6,025
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; public class FutureToObserverAdaptor<T> implements StreamObserver<T> { private final CompletableFuture<T> future; public FutureToObserverAdaptor(CompletableFuture<T> future) { this.future = future; } @Override public void onNext(T data) { if (future.isDone() || future.isCancelled() || future.isCompletedExceptionally()) { throw new IllegalStateException("Too many response for unary method"); } future.complete(data); } @Override public void onError(Throwable throwable) { if (future.isDone() || future.isCancelled() || future.isCompletedExceptionally()) { throw new IllegalStateException("Too many response for unary method"); } future.completeExceptionally(throwable); } @Override public void onCompleted() { if (future.isDone() || future.isCancelled() || future.isCompletedExceptionally()) { return; } throw new IllegalStateException("Completed without value or exception "); } }
6,026
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/StubSuppliers.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; public class StubSuppliers { private static final Map<String, Function<Invoker<?>, Object>> STUB_SUPPLIERS = new ConcurrentHashMap<>(); private static final Map<String, ServiceDescriptor> SERVICE_DESCRIPTOR_MAP = new ConcurrentHashMap<>(); public static void addDescriptor(String interfaceName, ServiceDescriptor serviceDescriptor) { SERVICE_DESCRIPTOR_MAP.put(interfaceName, serviceDescriptor); } public static void addSupplier(String interfaceName, Function<Invoker<?>, Object> supplier) { STUB_SUPPLIERS.put(interfaceName, supplier); } public static <T> T createStub(String interfaceName, Invoker<T> invoker) { // TODO DO not hack here if (!STUB_SUPPLIERS.containsKey(interfaceName)) { ReflectUtils.forName(stubClassName(interfaceName)); if (!STUB_SUPPLIERS.containsKey(interfaceName)) { throw new IllegalStateException("Can not find any stub supplier for " + interfaceName); } } return (T) STUB_SUPPLIERS.get(interfaceName).apply(invoker); } private static String stubClassName(String interfaceName) { int idx = interfaceName.lastIndexOf('.'); String pkg = interfaceName.substring(0, idx + 1); String name = interfaceName.substring(idx + 1); return pkg + "Dubbo" + name + "Triple"; } public static ServiceDescriptor getServiceDescriptor(String interfaceName) { // TODO DO not hack here if (!SERVICE_DESCRIPTOR_MAP.containsKey(interfaceName)) { ReflectUtils.forName(stubClassName(interfaceName)); if (!SERVICE_DESCRIPTOR_MAP.containsKey(interfaceName)) { throw new IllegalStateException("Can not find any stub supplier for " + interfaceName); } } return SERVICE_DESCRIPTOR_MAP.get(interfaceName); } }
6,027
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/UnaryStubMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; public class UnaryStubMethodHandler<T, R> implements StubMethodHandler<T, R> { private final BiConsumer<T, StreamObserver<R>> func; public UnaryStubMethodHandler(BiConsumer<T, StreamObserver<R>> func) { this.func = func; } @Override public CompletableFuture<R> invoke(Object[] arguments) { T request = (T) arguments[0]; CompletableFuture<R> future = new CompletableFuture<>(); StreamObserver<R> responseObserver = new FutureToObserverAdaptor<>(future); try { func.accept(request, responseObserver); } catch (Throwable e) { future.completeExceptionally(e); } return future; } }
6,028
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; public class ServerStreamMethodHandler<T, R> implements StubMethodHandler<T, R> { private final BiConsumer<T, StreamObserver<R>> func; public ServerStreamMethodHandler(BiConsumer<T, StreamObserver<R>> func) { this.func = func; } @Override public CompletableFuture<?> invoke(Object[] arguments) { T request = (T) arguments[0]; StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[1]; func.accept(request, responseObserver); return CompletableFuture.completedFuture(null); } }
6,029
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; import java.util.function.Function; public class BiStreamMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<StreamObserver<R>, StreamObserver<T>> func; public BiStreamMethodHandler(Function<StreamObserver<R>, StreamObserver<T>> func) { this.func = func; } @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = func.apply(responseObserver); return CompletableFuture.completedFuture(requestObserver); } }
6,030
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.constants.LoggerCodeConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.json.GsonUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ScopeModelAware; import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_PROTOBUF; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericInvokerFilter. */ @Activate(group = CommonConstants.PROVIDER, order = -20000) public class GenericFilter implements Filter, Filter.Listener, ScopeModelAware { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericFilter.class); private ApplicationModel applicationModel; private final Map<ClassLoader, Map<String, Class<?>>> classCache = new ConcurrentHashMap<>(); @Override public void setApplicationModel(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { String name = ((String) inv.getArguments()[0]).trim(); String[] types = (String[]) inv.getArguments()[1]; Object[] args = (Object[]) inv.getArguments()[2]; try { Method method = findMethodByMethodSignature(invoker.getInterface(), name, types, inv.getServiceModel()); Class<?>[] params = method.getParameterTypes(); if (args == null) { args = new Object[params.length]; } if (types == null) { types = new String[params.length]; } if (args.length != types.length) { throw new RpcException( "GenericFilter#invoke args.length != types.length, please check your " + "params"); } String generic = inv.getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = getGenericValueFromRpcContext(); } if (StringUtils.isEmpty(generic) || ProtocolUtils.isDefaultGenericSerialization(generic) || ProtocolUtils.isGenericReturnRawResult(generic)) { try { args = PojoUtils.realize(args, params, method.getGenericParameterTypes()); } catch (Exception e) { logger.error( LoggerCodeConstants.PROTOCOL_ERROR_DESERIALIZE, "", "", "Deserialize generic invocation failed. ServiceKey: " + inv.getTargetServiceUniqueName(), e); throw new RpcException(e); } } else if (ProtocolUtils.isGsonGenericSerialization(generic)) { args = getGsonGenericArgs(args, method.getGenericParameterTypes()); } else if (ProtocolUtils.isJavaGenericSerialization(generic)) { Configuration configuration = ApplicationModel.ofNullable(applicationModel) .modelEnvironment() .getConfiguration(); if (!configuration.getBoolean(CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, false)) { String notice = "Trigger the safety barrier! " + "Native Java Serializer is not allowed by default." + "This means currently maybe being attacking by others. " + "If you are sure this is a mistake, " + "please set `" + CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE + "` enable in configuration! " + "Before doing so, please make sure you have configure JEP290 to prevent serialization attack."; logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", notice); throw new RpcException(new IllegalStateException(notice)); } for (int i = 0; i < args.length; i++) { if (byte[].class == args[i].getClass()) { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) { args[i] = applicationModel .getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) .deserialize(null, is) .readObject(); } catch (Exception e) { throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e); } } else { throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + "] only support message type " + byte[].class + " and your message type is " + args[i].getClass()); } } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { for (int i = 0; i < args.length; i++) { if (args[i] != null) { if (args[i] instanceof JavaBeanDescriptor) { args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]); } else { throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_BEAN + "] only support message type " + JavaBeanDescriptor.class.getName() + " and your message type is " + args[i].getClass().getName()); } } } } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { // as proto3 only accept one protobuf parameter if (args.length == 1 && args[0] instanceof String) { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(((String) args[0]).getBytes())) { args[0] = applicationModel .getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_PROTOBUF) .deserialize(null, is) .readObject(method.getParameterTypes()[0]); } catch (Exception e) { throw new RpcException("Deserialize argument failed.", e); } } else { throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] only support one " + String.class.getName() + " argument and your message size is " + args.length + " and type is" + args[0].getClass().getName()); } } RpcInvocation rpcInvocation = new RpcInvocation( inv.getTargetServiceUniqueName(), invoker.getUrl().getServiceModel(), method.getName(), invoker.getInterface().getName(), invoker.getUrl().getProtocolServiceKey(), method.getParameterTypes(), args, inv.getObjectAttachments(), inv.getInvoker(), inv.getAttributes(), inv instanceof RpcInvocation ? ((RpcInvocation) inv).getInvokeMode() : null); return invoker.invoke(rpcInvocation); } catch (NoSuchMethodException | ClassNotFoundException e) { throw new RpcException(e.getMessage(), e); } } return invoker.invoke(inv); } private Object[] getGsonGenericArgs(final Object[] args, Type[] types) { return IntStream.range(0, args.length) .mapToObj(i -> { if (args[i] == null) { return null; } if (!(args[i] instanceof String)) { throw new RpcException( "When using GSON to deserialize generic dubbo request arguments, the arguments must be of type String"); } String str = args[i].toString(); try { return GsonUtils.fromJson(str, types[i]); } catch (RuntimeException ex) { throw new RpcException(ex.getMessage()); } }) .toArray(); } private String getGenericValueFromRpcContext() { String generic = RpcContext.getServerAttachment().getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = RpcContext.getClientAttachment().getAttachment(GENERIC_KEY); } return generic; } public Method findMethodByMethodSignature( Class<?> clazz, String methodName, String[] parameterTypes, ServiceModel serviceModel) throws NoSuchMethodException, ClassNotFoundException { Method method; if (parameterTypes == null) { List<Method> finded = new ArrayList<>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format( "Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { ClassLoader classLoader = ClassUtils.getClassLoader(); Map<String, Class<?>> cacheMap = classCache.get(classLoader); if (cacheMap == null) { cacheMap = new ConcurrentHashMap<>(); classCache.putIfAbsent(classLoader, cacheMap); cacheMap = classCache.get(classLoader); } types[i] = cacheMap.get(parameterTypes[i]); if (types[i] == null) { types[i] = ReflectUtils.name2class(parameterTypes[i]); cacheMap.put(parameterTypes[i], types[i]); } } if (serviceModel != null) { MethodDescriptor methodDescriptor = serviceModel.getServiceModel().getMethod(methodName, types); if (methodDescriptor == null) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } method = methodDescriptor.getMethod(); } else { method = clazz.getMethod(methodName, types); } } return method; } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation inv) { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { String generic = inv.getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = getGenericValueFromRpcContext(); } if (appResponse.hasException() && Dubbo2CompactUtils.isEnabled() && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded()) { Throwable appException = appResponse.getException(); if (appException instanceof GenericException) { GenericException tmp = (GenericException) appException; GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException( tmp.getMessage(), tmp.getCause(), tmp.getExceptionClass(), tmp.getExceptionMessage()); if (recreated != null) { appException = recreated; } appException.setStackTrace(tmp.getStackTrace()); } if (!(Dubbo2GenericExceptionUtils.getGenericExceptionClass() .isAssignableFrom(appException.getClass()))) { GenericException recreated = Dubbo2GenericExceptionUtils.newGenericException(appException); if (recreated != null) { appException = recreated; } } appResponse.setException(appException); } if (ProtocolUtils.isJavaGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); applicationModel .getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) .serialize(null, os) .writeObject(appResponse.getValue()); appResponse.setValue(os.toByteArray()); } catch (IOException e) { throw new RpcException( "Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + "] serialize result failed.", e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { appResponse.setValue(JavaBeanSerializeUtil.serialize(appResponse.getValue(), JavaBeanAccessor.METHOD)); } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); applicationModel .getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_PROTOBUF) .serialize(null, os) .writeObject(appResponse.getValue()); appResponse.setValue(os.toString()); } catch (IOException e) { throw new RpcException( "Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", e); } } else if (ProtocolUtils.isGenericReturnRawResult(generic)) { return; } else { appResponse.setValue(PojoUtils.generalize(appResponse.getValue())); } } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} }
6,031
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TimeoutFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; 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.Filter; 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.TimeoutCountDown; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST; /** * Log any invocation timeout, but don't stop server from running */ @Activate(group = CommonConstants.PROVIDER) public class TimeoutFilter implements Filter, Filter.Listener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TimeoutFilter.class); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { Object obj = RpcContext.getServerAttachment().getObjectAttachment(TIME_COUNTDOWN_KEY); if (obj != null) { TimeoutCountDown countDown = (TimeoutCountDown) obj; if (countDown.isExpired()) { if (logger.isWarnEnabled()) { logger.warn( PROXY_TIMEOUT_REQUEST, "", "", "invoke timed out. method: " + RpcUtils.getMethodName(invocation) + " url is " + invoker.getUrl() + ", invoke elapsed " + countDown.elapsedMillis() + " ms."); } } } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} }
6,032
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/DeprecatedFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; 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.ConcurrentHashSet; 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.support.RpcUtils; import java.util.Set; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_UNSUPPORTED_INVOKER; import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY; /** * DeprecatedFilter logs error message if a invoked method has been marked as deprecated. To check whether a method * is deprecated or not it looks for <b>deprecated</b> attribute value and consider it is deprecated it value is <b>true</b> * * @see Filter */ @Activate(group = CommonConstants.CONSUMER, value = DEPRECATED_KEY) public class DeprecatedFilter implements Filter { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(DeprecatedFilter.class); private static final Set<String> LOGGED = new ConcurrentHashSet<String>(); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation); if (!LOGGED.contains(key)) { LOGGED.add(key); if (invoker.getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), DEPRECATED_KEY, false)) { LOGGER.error( COMMON_UNSUPPORTED_INVOKER, "", "", "The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); } } return invoker.invoke(invocation); } private String getMethodSignature(Invocation invocation) { StringBuilder buf = new StringBuilder(RpcUtils.getMethodName(invocation)); buf.append('('); Class<?>[] types = invocation.getParameterTypes(); if (types != null && types.length > 0) { boolean first = true; for (Class<?> type : types) { if (first) { first = false; } else { buf.append(", "); } buf.append(type.getSimpleName()); } } buf.append(')'); return buf.toString(); } }
6,033
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ContextFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; 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.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; 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.model.ApplicationModel; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TAG_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_ATTACHMENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIME_COUNTDOWN_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.ASYNC_KEY; import static org.apache.dubbo.rpc.Constants.FORCE_USE_TAG; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * ContextFilter set the provider RpcContext with invoker, invocation, local port it is using and host for * current execution thread. * * @see RpcContext */ @Activate(group = PROVIDER, order = Integer.MIN_VALUE) public class ContextFilter implements Filter, Filter.Listener { private final Set<PenetrateAttachmentSelector> supportedSelectors; public ContextFilter(ApplicationModel applicationModel) { ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader = applicationModel.getExtensionLoader(PenetrateAttachmentSelector.class); supportedSelectors = selectorExtensionLoader.getSupportedExtensionInstances(); } private static final Set<String> UNLOADING_KEYS; static { UNLOADING_KEYS = new HashSet<>(16); UNLOADING_KEYS.add(PATH_KEY); UNLOADING_KEYS.add(INTERFACE_KEY); UNLOADING_KEYS.add(GROUP_KEY); UNLOADING_KEYS.add(VERSION_KEY); UNLOADING_KEYS.add(DUBBO_VERSION_KEY); UNLOADING_KEYS.add(TOKEN_KEY); UNLOADING_KEYS.add(TIMEOUT_KEY); UNLOADING_KEYS.add(TIMEOUT_ATTACHMENT_KEY); // Remove async property to avoid being passed to the following invoke chain. UNLOADING_KEYS.add(ASYNC_KEY); UNLOADING_KEYS.add(TAG_KEY); UNLOADING_KEYS.add(FORCE_USE_TAG); } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, Object> attachments = invocation.getObjectAttachments(); if (attachments != null) { Map<String, Object> newAttach = new HashMap<>(attachments.size()); for (Map.Entry<String, Object> entry : attachments.entrySet()) { String key = entry.getKey(); if (!UNLOADING_KEYS.contains(key)) { newAttach.put(key, entry.getValue()); } } attachments = newAttach; } RpcContext.getServiceContext().setInvoker(invoker).setInvocation(invocation); RpcContext context = RpcContext.getServerAttachment(); // .setAttachments(attachments) // merged from dubbox if (context.getLocalAddress() == null) { context.setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); } String remoteApplication = invocation.getAttachment(REMOTE_APPLICATION_KEY); if (StringUtils.isNotEmpty(remoteApplication)) { RpcContext.getServiceContext().setRemoteApplicationName(remoteApplication); } else { RpcContext.getServiceContext().setRemoteApplicationName(context.getAttachment(REMOTE_APPLICATION_KEY)); } long timeout = RpcUtils.getTimeout(invocation, -1); if (timeout != -1) { // pass to next hop RpcContext.getServerAttachment() .setObjectAttachment( TIME_COUNTDOWN_KEY, TimeoutCountDown.newCountDown(timeout, TimeUnit.MILLISECONDS)); } // merged from dubbox // we may already add some attachments into RpcContext before this filter (e.g. in rest protocol) if (CollectionUtils.isNotEmptyMap(attachments)) { if (context.getObjectAttachments().size() > 0) { context.getObjectAttachments().putAll(attachments); } else { context.setObjectAttachments(attachments); } } if (invocation instanceof RpcInvocation) { RpcInvocation rpcInvocation = (RpcInvocation) invocation; rpcInvocation.setInvoker(invoker); } try { context.clearAfterEachInvoke(false); return invoker.invoke(invocation); } finally { context.clearAfterEachInvoke(true); if (context.isAsyncStarted()) { removeContext(); } } } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { // pass attachments to result if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (PenetrateAttachmentSelector supportedSelector : supportedSelectors) { Map<String, Object> selected = supportedSelector.selectReverse( invocation, RpcContext.getClientResponseContext(), RpcContext.getServerResponseContext()); if (CollectionUtils.isNotEmptyMap(selected)) { appResponse.addObjectAttachments(selected); } } } else { appResponse.addObjectAttachments( RpcContext.getClientResponseContext().getObjectAttachments()); } appResponse.addObjectAttachments(RpcContext.getServerResponseContext().getObjectAttachments()); removeContext(); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { removeContext(); } private void removeContext() { RpcContext.removeServerAttachment(); RpcContext.removeClientAttachment(); RpcContext.removeServiceContext(); RpcContext.removeClientResponseContext(); RpcContext.removeServerResponseContext(); } }
6,034
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenHeaderFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.rpc.HeaderFilter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.apache.dubbo.rpc.RpcException.FORBIDDEN_EXCEPTION; @Activate public class TokenHeaderFilter implements HeaderFilter { @Override public RpcInvocation invoke(Invoker<?> invoker, RpcInvocation invocation) throws RpcException { String token = invoker.getUrl().getParameter(TOKEN_KEY); if (ConfigUtils.isNotEmpty(token)) { Class<?> serviceType = invoker.getInterface(); String remoteToken = (String) invocation.getObjectAttachmentWithoutConvert(TOKEN_KEY); if (!token.equals(remoteToken)) { throw new RpcException( FORBIDDEN_EXCEPTION, "Forbid invoke remote service " + serviceType + " method " + RpcUtils.getMethodName(invocation) + "() from consumer " + RpcContext.getServiceContext().getRemoteHost() + " to provider " + RpcContext.getServiceContext().getLocalHost() + ", consumer incorrect token is " + remoteToken); } } return invocation; } }
6,035
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TokenFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ConfigUtils; 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.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * Perform check whether given provider token is matching with remote token or not. If it does not match * it will not allow invoking remote method. * * @see Filter */ @Activate(group = CommonConstants.PROVIDER, value = TOKEN_KEY) public class TokenFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { String token = invoker.getUrl().getParameter(TOKEN_KEY); if (ConfigUtils.isNotEmpty(token)) { Class<?> serviceType = invoker.getInterface(); String remoteToken = (String) inv.getObjectAttachmentWithoutConvert(TOKEN_KEY); if (!token.equals(remoteToken)) { throw new RpcException("Invalid token! Forbid invoke remote service " + serviceType + " method " + RpcUtils.getMethodName(inv) + "() from consumer " + RpcContext.getServiceContext().getRemoteHost() + " to provider " + RpcContext.getServiceContext().getLocalHost() + ", consumer incorrect token is " + remoteToken); } } return invoker.invoke(inv); } }
6,036
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderCallbackFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.WORKING_CLASSLOADER_KEY; /** * Switch thread context class loader on filter callback. */ @Activate(group = CommonConstants.PROVIDER, order = Integer.MAX_VALUE) public class ClassLoaderCallbackFilter implements Filter, BaseFilter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { setClassLoader(invoker, invocation); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { setClassLoader(invoker, invocation); } private void setClassLoader(Invoker<?> invoker, Invocation invocation) { ClassLoader workingClassLoader = (ClassLoader) invocation.get(WORKING_CLASSLOADER_KEY); if (workingClassLoader != null) { Thread.currentThread().setContextClassLoader(workingClassLoader); } } }
6,037
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/RpcExceptionFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; /** * RpcExceptionFilter * <p> * Functions: * <ol> * <li> The RpcException will be rethrown on consumer side.</li> * </ol> */ @Activate(group = CommonConstants.CONSUMER) public class RpcExceptionFilter implements Filter, Filter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { if (appResponse.hasException()) { Throwable exception = appResponse.getException(); // directly throw if it's RpcException if ((exception instanceof RpcException)) { throw (RpcException) exception; } } } @Override public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {} }
6,038
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/EchoFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.rpc.Constants.$ECHO; /** * Dubbo provided default Echo echo service, which is available for all dubbo provider service interface. */ @Activate(group = CommonConstants.PROVIDER, order = -110000) public class EchoFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals($ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) { return AsyncRpcResult.newDefaultAsyncResult(inv.getArguments()[0], inv); } return invoker.invoke(inv); } }
6,039
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/GenericImplFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.compact.Dubbo2GenericExceptionUtils; import org.apache.dubbo.common.constants.CommonConstants; 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.DefaultSerializeClassChecker; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.rpc.Constants; 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.RpcInvocation; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_PARAMETER_DESC; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericImplInvokerFilter */ @Activate(group = CommonConstants.CONSUMER, value = GENERIC_KEY, order = 20000) public class GenericImplFilter implements Filter, Filter.Listener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(GenericImplFilter.class); private static final Class<?>[] GENERIC_PARAMETER_TYPES = new Class<?>[] {String.class, String[].class, Object[].class}; private static final String GENERIC_IMPL_MARKER = "GENERIC_IMPL"; private final ModuleModel moduleModel; public GenericImplFilter(ModuleModel moduleModel) { this.moduleModel = moduleModel; } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { String generic = invoker.getUrl().getParameter(GENERIC_KEY); // calling a generic impl service if (isCallingGenericImpl(generic, invocation)) { RpcInvocation invocation2 = new RpcInvocation(invocation); /** * Mark this invocation as a generic impl call, this value will be removed automatically before passing on the wire. * See {@link RpcUtils#sieveUnnecessaryAttachments(Invocation)} */ invocation2.put(GENERIC_IMPL_MARKER, true); String methodName = invocation2.getMethodName(); Class<?>[] parameterTypes = invocation2.getParameterTypes(); Object[] arguments = invocation2.getArguments(); String[] types = new String[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.getName(parameterTypes[i]); } Object[] args; if (ProtocolUtils.isBeanGenericSerialization(generic)) { args = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD); } } else { args = PojoUtils.generalize(arguments); } if (RpcUtils.isReturnTypeFuture(invocation)) { invocation2.setMethodName($INVOKE_ASYNC); } else { invocation2.setMethodName($INVOKE); } invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES); invocation2.setParameterTypesDesc(GENERIC_PARAMETER_DESC); invocation2.setArguments(new Object[] {methodName, types, args}); return invoker.invoke(invocation2); } // making a generic call to a normal service else if (isMakingGenericCall(generic, invocation)) { Object[] args = (Object[]) invocation.getArguments()[2]; if (ProtocolUtils.isJavaGenericSerialization(generic)) { for (Object arg : args) { if (byte[].class != arg.getClass()) { error(generic, byte[].class.getName(), arg.getClass().getName()); } } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { for (Object arg : args) { if (arg != null && !(arg instanceof JavaBeanDescriptor)) { error( generic, JavaBeanDescriptor.class.getName(), arg.getClass().getName()); } } } invocation.setAttachment(GENERIC_KEY, invoker.getUrl().getParameter(GENERIC_KEY)); } return invoker.invoke(invocation); } private void error(String generic, String expected, String actual) throws RpcException { throw new RpcException("Generic serialization [" + generic + "] only support message type " + expected + " and your message type is " + actual); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { String generic = invoker.getUrl().getParameter(GENERIC_KEY); String methodName = invocation.getMethodName(); Class<?>[] parameterTypes = invocation.getParameterTypes(); Object genericImplMarker = invocation.get(GENERIC_IMPL_MARKER); if (genericImplMarker != null && (boolean) invocation.get(GENERIC_IMPL_MARKER)) { if (!appResponse.hasException()) { Object value = appResponse.getValue(); try { Class<?> invokerInterface = invoker.getInterface(); if (!$INVOKE.equals(methodName) && !$INVOKE_ASYNC.equals(methodName) && invokerInterface.isAssignableFrom(GenericService.class)) { try { // find the real interface from url String realInterface = invoker.getUrl().getParameter(Constants.INTERFACE); invokerInterface = ReflectUtils.forName(realInterface); } catch (Exception e) { // ignore } } Method method = invokerInterface.getMethod(methodName, parameterTypes); if (ProtocolUtils.isBeanGenericSerialization(generic)) { if (value == null) { appResponse.setValue(value); } else if (value instanceof JavaBeanDescriptor) { appResponse.setValue(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value)); } else { throw new RpcException("The type of result value is " + value.getClass().getName() + " other than " + JavaBeanDescriptor.class.getName() + ", and the result is " + value); } } else { Type[] types = ReflectUtils.getReturnTypes(method); appResponse.setValue(PojoUtils.realize(value, (Class<?>) types[0], types[1])); } } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } } else if (Dubbo2CompactUtils.isEnabled() && Dubbo2GenericExceptionUtils.isGenericExceptionClassLoaded() && Dubbo2GenericExceptionUtils.getGenericExceptionClass() .isAssignableFrom(appResponse.getException().getClass())) { // TODO we should cast if is apache GenericException or not? org.apache.dubbo.rpc.service.GenericException exception = (org.apache.dubbo.rpc.service.GenericException) appResponse.getException(); try { String className = exception.getExceptionClass(); DefaultSerializeClassChecker classChecker = moduleModel .getApplicationModel() .getFrameworkModel() .getBeanFactory() .getBean(DefaultSerializeClassChecker.class); Class<?> clazz = classChecker.loadClass(Thread.currentThread().getContextClassLoader(), className); Throwable targetException = null; Throwable lastException = null; try { targetException = (Throwable) clazz.getDeclaredConstructor().newInstance(); } catch (Throwable e) { lastException = e; for (Constructor<?> constructor : clazz.getConstructors()) { try { targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]); break; } catch (Throwable e1) { lastException = e1; } } } if (targetException != null) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); if (!field.isAccessible()) { field.setAccessible(true); } field.set(targetException, exception.getExceptionMessage()); } catch (Throwable e) { logger.warn(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", e.getMessage(), e); } appResponse.setException(targetException); } else if (lastException != null) { throw lastException; } } catch (Throwable e) { throw new RpcException( "Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e); } } } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} private boolean isCallingGenericImpl(String generic, Invocation invocation) { return ProtocolUtils.isGeneric(generic) && (!$INVOKE.equals(invocation.getMethodName()) && !$INVOKE_ASYNC.equals(invocation.getMethodName())) && invocation instanceof RpcInvocation; } private boolean isMakingGenericCall(String generic, Invocation invocation) { return (invocation.getMethodName().equals($INVOKE) || invocation.getMethodName().equals($INVOKE_ASYNC)) && invocation.getArguments() != null && invocation.getArguments().length == 3 && ProtocolUtils.isGeneric(generic); } }
6,040
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExceptionFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; 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.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; /** * ExceptionInvokerFilter * <p> * Functions: * <ol> * <li>unexpected exception will be logged in ERROR level on provider side. Unexpected exception are unchecked * exception not declared on the interface</li> * <li>Wrap the exception not introduced in API package into RuntimeException. Framework will serialize the outer exception but stringnize its cause in order to avoid of possible serialization problem on client side</li> * </ol> */ @Activate(group = CommonConstants.PROVIDER) public class ExceptionFilter implements Filter, Filter.Listener { private ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExceptionFilter.class); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { if (appResponse.hasException() && GenericService.class != invoker.getInterface()) { try { Throwable exception = appResponse.getException(); // directly throw if it's checked exception if (!(exception instanceof RuntimeException) && (exception instanceof Exception)) { return; } // directly throw if the exception appears in the signature try { Method method = invoker.getInterface() .getMethod(RpcUtils.getMethodName(invocation), invocation.getParameterTypes()); Class<?>[] exceptionClasses = method.getExceptionTypes(); for (Class<?> exceptionClass : exceptionClasses) { if (exception.getClass().equals(exceptionClass)) { return; } } } catch (NoSuchMethodException e) { return; } // for the exception not found in method's signature, print ERROR message in server's log. logger.error( CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); // directly throw if exception class and interface class are in the same jar file. String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)) { return; } // directly throw if it's JDK exception String className = exception.getClass().getName(); if (className.startsWith("java.") || className.startsWith("javax.") || className.startsWith("jakarta.")) { return; } // directly throw if it's dubbo exception if (exception instanceof RpcException) { return; } // otherwise, wrap with RuntimeException and throw back to the client appResponse.setException(new RuntimeException(StringUtils.toString(exception))); } catch (Throwable e) { logger.warn( CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Fail to ExceptionFilter when called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); } } } @Override public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) { logger.error( CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Got unchecked and undeclared exception which called by " + RpcContext.getServiceContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); } // For test purpose public void setLogger(ErrorTypeAwareLogger logger) { this.logger = logger; } }
6,041
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AdaptiveLoadBalanceFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.LoadbalanceRules; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.resource.GlobalResourcesRepository; import org.apache.dubbo.common.threadlocal.NamedInternalThreadFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.AdaptiveMetrics; import org.apache.dubbo.rpc.Constants; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; /** * if the load balance is adaptive ,set attachment to get the metrics of the server * @see org.apache.dubbo.rpc.Filter * @see org.apache.dubbo.rpc.RpcContext */ @Activate( group = CONSUMER, order = -200000, value = {"loadbalance:adaptive"}) public class AdaptiveLoadBalanceFilter implements Filter, Filter.Listener { /** * uses a single worker thread operating off an bounded queue */ private volatile ThreadPoolExecutor executor = null; private final AdaptiveMetrics adaptiveMetrics; public AdaptiveLoadBalanceFilter(ApplicationModel scopeModel) { adaptiveMetrics = scopeModel.getBeanFactory().getBean(AdaptiveMetrics.class); } private ThreadPoolExecutor getExecutor() { if (null == executor) { synchronized (this) { if (null == executor) { executor = new ThreadPoolExecutor( 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), new NamedInternalThreadFactory("Dubbo-framework-loadbalance-adaptive", true), new ThreadPoolExecutor.DiscardOldestPolicy()); GlobalResourcesRepository.getInstance().registerDisposable(() -> this.executor.shutdown()); } } } return executor; } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } private String buildServiceKey(Invocation invocation) { StringBuilder sb = new StringBuilder(128); sb.append(invocation.getInvoker().getUrl().getAddress()).append(":").append(invocation.getProtocolServiceKey()); return sb.toString(); } private String getServiceKey(Invocation invocation) { String key = (String) invocation.getAttributes().get(invocation.getInvoker()); if (StringUtils.isNotEmpty(key)) { return key; } key = buildServiceKey(invocation); invocation.getAttributes().put(invocation.getInvoker(), key); return key; } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { try { String loadBalance = (String) invocation.getAttributes().get(LOADBALANCE_KEY); if (StringUtils.isEmpty(loadBalance) || !LoadbalanceRules.ADAPTIVE.equals(loadBalance)) { return; } adaptiveMetrics.addConsumerSuccess(getServiceKey(invocation)); String attachment = appResponse.getAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY); if (StringUtils.isNotEmpty(attachment)) { String[] parties = COMMA_SPLIT_PATTERN.split(attachment); if (parties.length == 0) { return; } Map<String, String> metricsMap = new HashMap<>(); for (String party : parties) { String[] groups = party.split(":"); if (groups.length != 2) { continue; } metricsMap.put(groups[0], groups[1]); } Long startTime = (Long) invocation.getAttributes().get(Constants.ADAPTIVE_LOADBALANCE_START_TIME); if (null != startTime) { metricsMap.put("rt", String.valueOf(System.currentTimeMillis() - startTime)); } getExecutor().execute(() -> { adaptiveMetrics.setProviderMetrics(getServiceKey(invocation), metricsMap); }); } } finally { appResponse.getAttachments().remove(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY); } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { String loadBalance = (String) invocation.getAttributes().get(LOADBALANCE_KEY); if (StringUtils.isNotEmpty(loadBalance) && LoadbalanceRules.ADAPTIVE.equals(loadBalance)) { getExecutor().execute(() -> { adaptiveMetrics.addErrorReq(getServiceKey(invocation)); }); } } }
6,042
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ActiveLimitFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.rpc.Constants.ACTIVES_KEY; /** * ActiveLimitFilter restrict the concurrent client invocation for a service or service's method from client side. * To use active limit filter, configured url with <b>actives</b> and provide valid >0 integer value. * <pre> * e.g. <dubbo:reference id="demoService" check="false" interface="org.apache.dubbo.demo.DemoService" "actives"="2"/> * In the above example maximum 2 concurrent invocation is allowed. * If there are more than configured (in this example 2) is trying to invoke remote method, then rest of invocation * will wait for configured timeout(default is 0 second) before invocation gets kill by dubbo. * </pre> * * @see Filter */ @Activate(group = CONSUMER, value = ACTIVES_KEY) public class ActiveLimitFilter implements Filter, Filter.Listener { private static final String ACTIVE_LIMIT_FILTER_START_TIME = "active_limit_filter_start_time"; @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = RpcUtils.getMethodName(invocation); int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); final RpcStatus rpcStatus = RpcStatus.getStatus(invoker.getUrl(), RpcUtils.getMethodName(invocation)); if (!RpcStatus.beginCount(url, methodName, max)) { long timeout = invoker.getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), TIMEOUT_KEY, 0); long start = System.currentTimeMillis(); long remain = timeout; synchronized (rpcStatus) { while (!RpcStatus.beginCount(url, methodName, max)) { try { rpcStatus.wait(remain); } catch (InterruptedException e) { // ignore } long elapsed = System.currentTimeMillis() - start; remain = timeout - elapsed; if (remain <= 0) { throw new RpcException( RpcException.LIMIT_EXCEEDED_EXCEPTION, "Waiting concurrent invoke timeout in client-side for service: " + invoker.getInterface().getName() + ", method: " + RpcUtils.getMethodName(invocation) + ", elapsed: " + elapsed + ", timeout: " + timeout + ". concurrent invokes: " + rpcStatus.getActive() + ". max concurrent invoke limit: " + max); } } } } invocation.put(ACTIVE_LIMIT_FILTER_START_TIME, System.currentTimeMillis()); return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { String methodName = RpcUtils.getMethodName(invocation); URL url = invoker.getUrl(); int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); RpcStatus.endCount(url, methodName, getElapsed(invocation), true); notifyFinish(RpcStatus.getStatus(url, methodName), max); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { String methodName = RpcUtils.getMethodName(invocation); URL url = invoker.getUrl(); int max = invoker.getUrl().getMethodParameter(methodName, ACTIVES_KEY, 0); if (t instanceof RpcException) { RpcException rpcException = (RpcException) t; if (rpcException.isLimitExceed()) { return; } } RpcStatus.endCount(url, methodName, getElapsed(invocation), false); notifyFinish(RpcStatus.getStatus(url, methodName), max); } private long getElapsed(Invocation invocation) { Object beginTime = invocation.get(ACTIVE_LIMIT_FILTER_START_TIME); return beginTime != null ? System.currentTimeMillis() - (Long) beginTime : 0; } private void notifyFinish(final RpcStatus rpcStatus, int max) { if (max > 0) { synchronized (rpcStatus) { rpcStatus.notifyAll(); } } } }
6,043
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/TpsLimitFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.filter.tps.DefaultTPSLimiter; import org.apache.dubbo.rpc.filter.tps.TPSLimiter; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; /** * TpsLimitFilter limit the TPS (transaction per second) for all method of a service or a particular method. * Service or method url can define <b>tps</b> or <b>tps.interval</b> to control this control.It use {@link DefaultTPSLimiter} * as it limit checker. If a provider service method is configured with <b>tps</b>(optionally with <b>tps.interval</b>),then * if invocation count exceed the configured <b>tps</b> value (default is -1 which means unlimited) then invocation will get * RpcException. */ @Activate(group = CommonConstants.PROVIDER, value = TPS_LIMIT_RATE_KEY) public class TpsLimitFilter implements Filter { private final TPSLimiter tpsLimiter = new DefaultTPSLimiter(); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (!tpsLimiter.isAllowable(invoker.getUrl(), invocation)) { return AsyncRpcResult.newDefaultAsyncResult( new RpcException( "Failed to invoke service " + invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation) + " because exceed max service tps."), invocation); } return invoker.invoke(invocation); } }
6,044
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.RpcUtils; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.rpc.Constants.EXECUTES_KEY; /** * The maximum parallel execution request count per method per service for the provider.If the max configured * <b>executes</b> is set to 10 and if invoke request where it is already 10 then it will throw exception. It * continues the same behaviour un till it is <10. */ @Activate(group = CommonConstants.PROVIDER, value = EXECUTES_KEY) public class ExecuteLimitFilter implements Filter, Filter.Listener { private static final String EXECUTE_LIMIT_FILTER_START_TIME = "execute_limit_filter_start_time"; @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { URL url = invoker.getUrl(); String methodName = RpcUtils.getMethodName(invocation); int max = url.getMethodParameter(methodName, EXECUTES_KEY, 0); if (!RpcStatus.beginCount(url, methodName, max)) { throw new RpcException( RpcException.LIMIT_EXCEEDED_EXCEPTION, "Failed to invoke method " + RpcUtils.getMethodName(invocation) + " in provider " + url + ", cause: The service using threads greater than <dubbo:service executes=\"" + max + "\" /> limited."); } invocation.put(EXECUTE_LIMIT_FILTER_START_TIME, System.currentTimeMillis()); try { return invoker.invoke(invocation); } catch (Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new RpcException("unexpected exception when ExecuteLimitFilter", t); } } } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { RpcStatus.endCount(invoker.getUrl(), getRealMethodName(invoker, invocation), getElapsed(invocation), true); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { if (t instanceof RpcException) { RpcException rpcException = (RpcException) t; if (rpcException.isLimitExceed()) { return; } } RpcStatus.endCount(invoker.getUrl(), getRealMethodName(invoker, invocation), getElapsed(invocation), false); } private String getRealMethodName(Invoker<?> invoker, Invocation invocation) { if ((invocation.getMethodName().equals($INVOKE) || invocation.getMethodName().equals($INVOKE_ASYNC)) && invocation.getArguments() != null && invocation.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { return ((String) invocation.getArguments()[0]).trim(); } return invocation.getMethodName(); } private long getElapsed(Invocation invocation) { Object beginTime = invocation.get(EXECUTE_LIMIT_FILTER_START_TIME); return beginTime != null ? System.currentTimeMillis() - (Long) beginTime : 0; } }
6,045
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ProfilerServerFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; 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.profiler.Profiler; import org.apache.dubbo.common.profiler.ProfilerEntry; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Constants; 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.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_RESPONSE; @Activate(group = PROVIDER, order = Integer.MIN_VALUE) public class ProfilerServerFilter implements Filter, BaseFilter.Listener { private static final String CLIENT_IP_KEY = "client_ip"; private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ProfilerServerFilter.class); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { if (ProfilerSwitch.isEnableSimpleProfiler()) { ProfilerEntry bizProfiler; Object localInvokeProfiler = invocation.get(Profiler.PROFILER_KEY); if (localInvokeProfiler instanceof ProfilerEntry) { bizProfiler = Profiler.enter( (ProfilerEntry) localInvokeProfiler, "Receive request. Local server invoke begin."); } else { bizProfiler = Profiler.start("Receive request. Server invoke begin."); } invocation.put(Profiler.PROFILER_KEY, bizProfiler); invocation.put(CLIENT_IP_KEY, RpcContext.getServiceContext().getRemoteAddressString()); } return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { afterInvoke(invoker, invocation); addAdaptiveResponse(appResponse, invocation); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { afterInvoke(invoker, invocation); } private void afterInvoke(Invoker<?> invoker, Invocation invocation) { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); if (fromInvocation instanceof ProfilerEntry) { ProfilerEntry profiler = Profiler.release((ProfilerEntry) fromInvocation); invocation.put(Profiler.PROFILER_KEY, profiler); dumpIfNeed(invoker, invocation, (ProfilerEntry) fromInvocation); } } } private void addAdaptiveResponse(Result appResponse, Invocation invocation) { String adaptiveLoadAttachment = invocation.getAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY); if (StringUtils.isNotEmpty(adaptiveLoadAttachment)) { OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); StringBuilder sb = new StringBuilder(64); sb.append("curTime:").append(System.currentTimeMillis()); sb.append(COMMA_SEPARATOR) .append("load:") .append(operatingSystemMXBean.getSystemLoadAverage() * 100 / operatingSystemMXBean.getAvailableProcessors()); appResponse.setAttachment(Constants.ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY, sb.toString()); } } private void dumpIfNeed(Invoker<?> invoker, Invocation invocation, ProfilerEntry profiler) { Long timeout = RpcUtils.convertToNumber(invocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY)); if (timeout == null) { timeout = (long) invoker.getUrl() .getMethodPositiveParameter(RpcUtils.getMethodName(invocation), TIMEOUT_KEY, DEFAULT_TIMEOUT); } long usage = profiler.getEndTime() - profiler.getStartTime(); if (((usage / (1000_000L * ProfilerSwitch.getWarnPercent())) > timeout) && timeout != -1) { StringBuilder attachment = new StringBuilder(); invocation.foreachAttachment((entry) -> { attachment .append(entry.getKey()) .append("=") .append(entry.getValue()) .append(";\n"); }); logger.warn( PROXY_TIMEOUT_RESPONSE, "", "", String.format( "[Dubbo-Provider] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n" + "client: %s\n" + "invocation context:\n%s" + "thread info: \n%s", invocation.getTargetServiceUniqueName(), RpcUtils.getMethodName(invocation), usage / 1000_000, usage % 1000_000, timeout, invocation.get(CLIENT_IP_KEY), attachment, Profiler.buildDetail(profiler))); } } }
6,046
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.BaseFilter; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import static org.apache.dubbo.common.constants.CommonConstants.STAGED_CLASSLOADER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.WORKING_CLASSLOADER_KEY; /** * Set the current execution thread class loader to service interface's class loader. */ @Activate(group = CommonConstants.PROVIDER, order = -30000) public class ClassLoaderFilter implements Filter, BaseFilter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { ClassLoader stagedClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader effectiveClassLoader; if (invocation.getServiceModel() != null) { effectiveClassLoader = invocation.getServiceModel().getClassLoader(); } else { effectiveClassLoader = invoker.getClass().getClassLoader(); } if (effectiveClassLoader != null) { invocation.put(STAGED_CLASSLOADER_KEY, stagedClassLoader); invocation.put(WORKING_CLASSLOADER_KEY, effectiveClassLoader); Thread.currentThread().setContextClassLoader(effectiveClassLoader); } try { return invoker.invoke(invocation); } finally { Thread.currentThread().setContextClassLoader(stagedClassLoader); } } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { resetClassLoader(invoker, invocation); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { resetClassLoader(invoker, invocation); } private void resetClassLoader(Invoker<?> invoker, Invocation invocation) { ClassLoader stagedClassLoader = (ClassLoader) invocation.get(STAGED_CLASSLOADER_KEY); if (stagedClassLoader != null) { Thread.currentThread().setContextClassLoader(stagedClassLoader); } } }
6,047
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/CompatibleFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CompatibleTypeUtils; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.remoting.utils.UrlUtils; 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 java.lang.reflect.Method; import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; /** * CompatibleFilter make the remote method's return value compatible to invoker's version of object. * To make return object compatible it does * <pre> * 1)If the url contain serialization key of type <b>json</b> or <b>fastjson</b> then transform * the return value to instance of {@link java.util.Map} * 2)If the return value is not a instance of invoked method's return type available at * local jvm then POJO conversion. * 3)If return value is other than above return value as it is. * </pre> * * @see Filter */ public class CompatibleFilter implements Filter, Filter.Listener { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CompatibleFilter.class); @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { if (!invocation.getMethodName().startsWith("$") && !appResponse.hasException()) { Object value = appResponse.getValue(); if (value != null) { try { Method method = invoker.getInterface() .getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class<?> type = method.getReturnType(); Object newValue; String serialization = UrlUtils.serializationOrDefault(invoker.getUrl()); if ("json".equals(serialization) || "fastjson".equals(serialization)) { // If the serialization key is json or fastjson Type gtype = method.getGenericReturnType(); newValue = PojoUtils.realize(value, type, gtype); } else if (!type.isInstance(value)) { // if local service interface's method's return type is not instance of return value newValue = PojoUtils.isPojo(type) ? PojoUtils.realize(value, type) : CompatibleTypeUtils.compatibleTypeConvert(value, type); } else { newValue = value; } if (newValue != value) { appResponse.setValue(newValue); } } catch (Throwable t) { logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", t.getMessage(), t); } } } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {} }
6,048
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/AccessLogFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; 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.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Constants; 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.support.AccessLogData; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.VULNERABILITY_WARNING; import static org.apache.dubbo.rpc.Constants.ACCESS_LOG_FIXED_PATH_KEY; /** * Record access log for the service. * <p> * Logger key is <code><b>dubbo.accesslog</b></code>. * In order to configure access log appear in the specified appender only, additivity need to be configured in log4j's * config file, for example: * <code> * <pre> * &lt;logger name="<b>dubbo.accesslog</b>" <font color="red">additivity="false"</font>&gt; * &lt;level value="info" /&gt; * &lt;appender-ref ref="foo" /&gt; * &lt;/logger&gt; * </pre></code> */ @Activate(group = PROVIDER) public class AccessLogFilter implements Filter { public static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AccessLogFilter.class); private static final String LOG_KEY = "dubbo.accesslog"; private static final int LOG_MAX_BUFFER = 5000; private static long LOG_OUTPUT_INTERVAL = 5000; private static final String FILE_DATE_FORMAT = "yyyyMMdd"; // It's safe to declare it as singleton since it runs on single thread only private final DateFormat fileNameFormatter = new SimpleDateFormat(FILE_DATE_FORMAT); private final ConcurrentMap<String, Queue<AccessLogData>> logEntries = new ConcurrentHashMap<>(); private final AtomicBoolean scheduled = new AtomicBoolean(); private ScheduledFuture<?> future; private static final String LINE_SEPARATOR = "line.separator"; /** * Default constructor initialize demon thread for writing into access log file with names with access log key * defined in url <b>accesslog</b> */ public AccessLogFilter() {} /** * This method logs the access log for service method invocation call. * * @param invoker service * @param inv Invocation service method. * @return Result from service method. * @throws RpcException */ @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { String accessLogKey = invoker.getUrl().getParameter(Constants.ACCESS_LOG_KEY); boolean isFixedPath = invoker.getUrl().getParameter(ACCESS_LOG_FIXED_PATH_KEY, true); if (StringUtils.isEmpty(accessLogKey)) { // Notice that disable accesslog of one service may cause the whole application to stop collecting // accesslog. // It's recommended to use application level configuration to enable or disable accesslog if dynamically // configuration is needed . if (future != null && !future.isCancelled()) { future.cancel(true); logger.info("Access log task cancelled ..."); } return invoker.invoke(inv); } if (scheduled.compareAndSet(false, true)) { future = inv.getModuleModel() .getApplicationModel() .getFrameworkModel() .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedScheduledExecutor() .scheduleWithFixedDelay( new AccesslogRefreshTask(isFixedPath), LOG_OUTPUT_INTERVAL, LOG_OUTPUT_INTERVAL, TimeUnit.MILLISECONDS); logger.info("Access log task started ..."); } Optional<AccessLogData> optionalAccessLogData = Optional.empty(); try { optionalAccessLogData = Optional.of(buildAccessLogData(invoker, inv)); } catch (Throwable t) { logger.warn( CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "Exception in AccessLogFilter of service(" + invoker + " -> " + inv + ")", t); } try { return invoker.invoke(inv); } finally { String finalAccessLogKey = accessLogKey; optionalAccessLogData.ifPresent(logData -> { logData.setOutTime(new Date()); log(finalAccessLogKey, logData, isFixedPath); }); } } private void log(String accessLog, AccessLogData accessLogData, boolean isFixedPath) { Queue<AccessLogData> logQueue = ConcurrentHashMapUtils.computeIfAbsent(logEntries, accessLog, k -> new ConcurrentLinkedQueue<>()); if (logQueue.size() < LOG_MAX_BUFFER) { logQueue.add(accessLogData); } else { logger.warn( CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", "AccessLog buffer is full. Do a force writing to file to clear buffer."); // just write current logSet to file. writeLogSetToFile(accessLog, logQueue, isFixedPath); // after force writing, add accessLogData to current logSet logQueue.add(accessLogData); } } private void writeLogSetToFile(String accessLog, Queue<AccessLogData> logSet, boolean isFixedPath) { try { if (ConfigUtils.isDefault(accessLog)) { processWithServiceLogger(logSet); } else { if (isFixedPath) { logger.warn( VULNERABILITY_WARNING, "Change of accesslog file path not allowed. ", "", "Will write to the default location, \" +\n" + " \"please enable this feature by setting 'accesslog.fixed.path=true' and restart the process. \" +\n" + " \"We highly recommend to not enable this feature in production for security concerns, \" +\n" + " \"please be fully aware of the potential risks before doing so!"); processWithServiceLogger(logSet); } else { logger.warn( VULNERABILITY_WARNING, "Accesslog file path changed to " + accessLog + ", be aware of possible vulnerabilities!", "", ""); File file = new File(accessLog); createIfLogDirAbsent(file); if (logger.isDebugEnabled()) { logger.debug("Append log to " + accessLog); } renameFile(file); processWithAccessKeyLogger(logSet, file); } } } catch (Exception e) { logger.error(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e); } } private void processWithAccessKeyLogger(Queue<AccessLogData> logQueue, File file) throws IOException { FileWriter writer = new FileWriter(file, true); try { while (!logQueue.isEmpty()) { writer.write(logQueue.poll().getLogMessage()); writer.write(System.getProperty(LINE_SEPARATOR)); } } finally { writer.flush(); writer.close(); } } private AccessLogData buildAccessLogData(Invoker<?> invoker, Invocation inv) { AccessLogData logData = AccessLogData.newLogData(); logData.setServiceName(invoker.getInterface().getName()); logData.setMethodName(RpcUtils.getMethodName(inv)); logData.setVersion(invoker.getUrl().getVersion()); logData.setGroup(invoker.getUrl().getGroup()); logData.setInvocationTime(new Date()); logData.setTypes(inv.getParameterTypes()); logData.setArguments(inv.getArguments()); return logData; } private void processWithServiceLogger(Queue<AccessLogData> logQueue) { while (!logQueue.isEmpty()) { AccessLogData logData = logQueue.poll(); LoggerFactory.getLogger(LOG_KEY + "." + logData.getServiceName()).info(logData.getLogMessage()); } } private void createIfLogDirAbsent(File file) { File dir = file.getParentFile(); if (null != dir && !dir.exists()) { dir.mkdirs(); } } private void renameFile(File file) { if (file.exists()) { String now = fileNameFormatter.format(new Date()); String last = fileNameFormatter.format(new Date(file.lastModified())); if (!now.equals(last)) { File archive = new File(file.getAbsolutePath() + "." + now); file.renameTo(archive); } } } class AccesslogRefreshTask implements Runnable { private final boolean isFixedPath; public AccesslogRefreshTask(boolean isFixedPath) { this.isFixedPath = isFixedPath; } @Override public void run() { if (!AccessLogFilter.this.logEntries.isEmpty()) { for (Map.Entry<String, Queue<AccessLogData>> entry : AccessLogFilter.this.logEntries.entrySet()) { String accessLog = entry.getKey(); Queue<AccessLogData> logSet = entry.getValue(); writeLogSetToFile(accessLog, logSet, isFixedPath); } } } } // test purpose only public static void setInterval(long interval) { LOG_OUTPUT_INTERVAL = interval; } // test purpose only public static long getInterval() { return LOG_OUTPUT_INTERVAL; } // test purpose only public void destroy() { future.cancel(true); } }
6,049
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/TPSLimiter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter.tps; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; /** * Provide boolean information whether a invocation of a provider service's methods or a particular method * is allowed within a last invocation and current invocation. * <pre> * e.g. if tps for a method m1 is 5 for a minute then if 6th call is made within the span of 1 minute then 6th * should not be allowed <b>isAllowable</b> will return false. * </pre> */ public interface TPSLimiter { /** * judge if the current invocation is allowed by TPS rule * * @param url url * @param invocation invocation * @return true allow the current invocation, otherwise, return false */ boolean isAllowable(URL url, Invocation invocation); }
6,050
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/StatItem.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter.tps; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Judge whether a particular invocation of service provider method should be allowed within a configured time interval. * As a state it contain name of key ( e.g. method), last invocation time, interval and rate count. */ class StatItem { private final String name; private final AtomicLong lastResetTime; private final long interval; private final AtomicInteger token; private final int rate; StatItem(String name, int rate, long interval) { this.name = name; this.rate = rate; this.interval = interval; this.lastResetTime = new AtomicLong(System.currentTimeMillis()); this.token = new AtomicInteger(rate); } public boolean isAllowable() { long now = System.currentTimeMillis(); if (now > lastResetTime.get() + interval) { token.set(rate); lastResetTime.set(now); } return token.decrementAndGet() >= 0; } public long getInterval() { return interval; } public int getRate() { return rate; } long getLastResetTime() { return lastResetTime.get(); } int getToken() { return token.get(); } @Override public String toString() { return "StatItem " + "[name=" + name + ", " + "rate = " + rate + ", " + "interval = " + interval + ']'; } }
6,051
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter.tps; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.apache.dubbo.rpc.Constants.DEFAULT_TPS_LIMIT_INTERVAL; import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY; import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY; /** * DefaultTPSLimiter is a default implementation for tps filter. It is an in memory based implementation for storing * tps information. It internally use * * @see org.apache.dubbo.rpc.filter.TpsLimitFilter */ public class DefaultTPSLimiter implements TPSLimiter { private final ConcurrentMap<String, StatItem> stats = new ConcurrentHashMap<String, StatItem>(); @Override public boolean isAllowable(URL url, Invocation invocation) { int rate = url.getMethodParameter(RpcUtils.getMethodName(invocation), TPS_LIMIT_RATE_KEY, -1); long interval = url.getMethodParameter( RpcUtils.getMethodName(invocation), TPS_LIMIT_INTERVAL_KEY, DEFAULT_TPS_LIMIT_INTERVAL); String serviceKey = url.getServiceKey(); if (rate > 0) { StatItem statItem = stats.get(serviceKey); if (statItem == null) { stats.putIfAbsent(serviceKey, new StatItem(serviceKey, rate, interval)); statItem = stats.get(serviceKey); } else { // rate or interval has changed, rebuild if (statItem.getRate() != rate || statItem.getInterval() != interval) { stats.put(serviceKey, new StatItem(serviceKey, rate, interval)); statItem = stats.get(serviceKey); } } return statItem.isAllowable(); } else { StatItem statItem = stats.get(serviceKey); if (statItem != null) { stats.remove(serviceKey); } } return true; } }
6,052
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/TriRpcStatusTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.rpc.TriRpcStatus.Code; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.RpcException.FORBIDDEN_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.METHOD_NOT_FOUND; import static org.apache.dubbo.rpc.RpcException.TIMEOUT_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.UNKNOWN_EXCEPTION; import static org.junit.jupiter.api.Assertions.fail; class TriRpcStatusTest { @Test void fromCode() { Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.fromCode(2).code); try { TriRpcStatus.fromCode(1000); fail(); } catch (Throwable t) { // pass } } @Test void testFromCode() { Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.fromCode(Code.UNKNOWN).code); } @Test void getStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException).code); } @Test void testGetStatus() { StatusRpcException rpcException = new StatusRpcException(TriRpcStatus.INTERNAL); Assertions.assertEquals(TriRpcStatus.INTERNAL.code, TriRpcStatus.getStatus(rpcException, null).code); Assertions.assertEquals( TriRpcStatus.DEADLINE_EXCEEDED.code, TriRpcStatus.getStatus(new RpcException(RpcException.TIMEOUT_EXCEPTION), null).code); Assertions.assertEquals( TriRpcStatus.DEADLINE_EXCEEDED.code, TriRpcStatus.getStatus(new TimeoutException(true, null, null), null).code); } @Test void rpcExceptionCodeToGrpcCode() { Assertions.assertEquals(Code.DEADLINE_EXCEEDED, TriRpcStatus.dubboCodeToTriCode(2)); } @Test void limitSizeTo1KB() { String a = "a"; for (int i = 0; i < 11; i++) { a += a; } Assertions.assertEquals(1024, TriRpcStatus.limitSizeTo1KB(a).length()); Assertions.assertEquals(1, TriRpcStatus.limitSizeTo1KB("a").length()); } @Test void decodeMessage() { String message = "😯"; Assertions.assertEquals(message, TriRpcStatus.decodeMessage(TriRpcStatus.encodeMessage(message))); Assertions.assertTrue(TriRpcStatus.decodeMessage("").isEmpty()); Assertions.assertTrue(TriRpcStatus.decodeMessage(null).isEmpty()); } @Test void httpStatusToGrpcCode() { Assertions.assertEquals(Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(404)); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.BAD_GATEWAY.code())); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.TOO_MANY_REQUESTS.code())); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.SERVICE_UNAVAILABLE.code())); Assertions.assertEquals( Code.UNAVAILABLE, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.GATEWAY_TIMEOUT.code())); Assertions.assertEquals(Code.INTERNAL, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.CONTINUE.code())); Assertions.assertEquals( Code.INTERNAL, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code())); Assertions.assertEquals(Code.UNKNOWN, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.ACCEPTED.code())); Assertions.assertEquals( Code.PERMISSION_DENIED, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.FORBIDDEN.code())); Assertions.assertEquals( Code.UNIMPLEMENTED, TriRpcStatus.httpStatusToGrpcCode(HttpResponseStatus.NOT_FOUND.code())); } @Test void isOk() { Assertions.assertTrue(TriRpcStatus.OK.isOk()); Assertions.assertFalse(TriRpcStatus.NOT_FOUND.isOk()); } @Test void withCause() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withCause = origin.withCause(new IllegalStateException("test")); Assertions.assertNull(origin.cause); Assertions.assertTrue(withCause.cause.getMessage().contains("test")); } @Test void withDescription() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withDesc = origin.withDescription("desc"); Assertions.assertNull(origin.description); Assertions.assertTrue(withDesc.description.contains("desc")); } @Test void appendDescription() { TriRpcStatus origin = TriRpcStatus.NOT_FOUND; TriRpcStatus withDesc = origin.appendDescription("desc0"); TriRpcStatus withDesc2 = withDesc.appendDescription("desc1"); Assertions.assertNull(origin.description); Assertions.assertTrue(withDesc2.description.contains("desc1")); Assertions.assertTrue(withDesc2.description.contains("desc0")); } @Test void asException() { StatusRpcException exception = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .asException(); Assertions.assertEquals(Code.NOT_FOUND, exception.getStatus().code); } @Test void toEncodedMessage() { String message = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .toEncodedMessage(); Assertions.assertTrue(message.contains("desc")); Assertions.assertTrue(message.contains("test")); } @Test void toMessageWithoutCause() { String message = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .toMessageWithoutCause(); Assertions.assertTrue(message.contains("desc")); Assertions.assertFalse(message.contains("test")); } @Test void toMessage() { String message = TriRpcStatus.NOT_FOUND .withDescription("desc") .withCause(new IllegalStateException("test")) .toMessage(); Assertions.assertTrue(message.contains("desc")); Assertions.assertTrue(message.contains("test")); } @Test void encodeMessage() { Assertions.assertTrue(TriRpcStatus.encodeMessage(null).isEmpty()); Assertions.assertTrue(TriRpcStatus.encodeMessage("").isEmpty()); } @Test void fromMessage() { String origin = "haha test 😊"; final String encoded = TriRpcStatus.encodeMessage(origin); Assertions.assertNotEquals(origin, encoded); final String decoded = TriRpcStatus.decodeMessage(encoded); Assertions.assertEquals(origin, decoded); } @Test void toMessage2() { String content = "\t\ntest with whitespace\r\nand Unicode BMP ☺ and non-BMP 😈\t\n"; final TriRpcStatus status = TriRpcStatus.INTERNAL.withDescription(content); Assertions.assertEquals(content, status.toMessage()); } @Test void triCodeToDubboCode() { Assertions.assertEquals(TIMEOUT_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.DEADLINE_EXCEEDED)); Assertions.assertEquals(FORBIDDEN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.PERMISSION_DENIED)); Assertions.assertEquals(METHOD_NOT_FOUND, TriRpcStatus.triCodeToDubboCode(Code.UNIMPLEMENTED)); Assertions.assertEquals(UNKNOWN_EXCEPTION, TriRpcStatus.triCodeToDubboCode(Code.UNKNOWN)); } }
6,053
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/StatusRpcExceptionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class StatusRpcExceptionTest { @Test void getStatus() { Assertions.assertEquals( TriRpcStatus.INTERNAL, ((StatusRpcException) TriRpcStatus.INTERNAL.asException()).getStatus()); } }
6,054
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DeadlineFutureTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.StatusRpcException; import org.apache.dubbo.rpc.TriRpcStatus; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class DeadlineFutureTest { @Test void test() throws InterruptedException, ExecutionException { String service = "service"; String method = "method"; String address = "localhost:12201"; DeadlineFuture timeout = DeadlineFuture.newFuture(service, method, address, 10, ImmediateEventExecutor.INSTANCE); TimeUnit.MILLISECONDS.sleep(20); AppResponse timeoutResponse = timeout.get(); Assertions.assertTrue(timeoutResponse.getException() instanceof StatusRpcException); DeadlineFuture success = DeadlineFuture.newFuture(service, method, address, 1000, ImmediateEventExecutor.INSTANCE); AppResponse response = new AppResponse(); success.received(TriRpcStatus.OK, response); AppResponse response1 = success.get(); Assertions.assertEquals(response, response1); } }
6,055
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/DescriptorService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; public interface DescriptorService { CompletableFuture<String> unaryFuture(); void noParameterMethod(); /** * unray return protobuf class * * @return protobuf class */ HelloReply noParameterAndReturnProtobufMethod(); /** * unray return java class * * @return */ String noParameterAndReturnJavaClassMethod(); /** * bi stream need wrapper * * @param streamObserver * @return */ StreamObserver<String> wrapBidirectionalStream(StreamObserver<String> streamObserver); /** * no need wrapper bi stream * * @param streamObserver * @return */ StreamObserver<HelloReply> bidirectionalStream(StreamObserver<HelloReply> streamObserver); /** * only for test. * * @param reply * @return */ HelloReply sayHello(HelloReply reply); void sayHelloServerStream(HelloReply request, StreamObserver<HelloReply> reply); void sayHelloServerStream2(Object request, StreamObserver<Object> reply); /***********************grpc******************************/ java.util.Iterator<HelloReply> iteratorServerStream(HelloReply request); reactor.core.publisher.Mono<HelloReply> reactorMethod(HelloReply reactorRequest); reactor.core.publisher.Mono<HelloReply> reactorMethod2(reactor.core.publisher.Mono<HelloReply> reactorRequest); io.reactivex.Single<HelloReply> rxJavaMethod(io.reactivex.Single<HelloReply> replySingle); /**********************test error*****************/ void testMultiProtobufParameters(HelloReply reply1, HelloReply reply2); String testDiffParametersAndReturn(HelloReply reply1); HelloReply testDiffParametersAndReturn2(String reply1); void testErrorServerStream(StreamObserver<HelloReply> reply, HelloReply request); void testErrorServerStream2(HelloReply request, HelloReply request2, StreamObserver<HelloReply> reply); void testErrorServerStream3(String aa, StreamObserver<HelloReply> reply); void testErrorServerStream4(String aa, String bb, StreamObserver<String> reply); StreamObserver<HelloReply> testErrorBiStream(HelloReply reply, StreamObserver<HelloReply> observer); StreamObserver<HelloReply> testErrorBiStream2(String reply, StreamObserver<HelloReply> observer); StreamObserver<String> testErrorBiStream3(StreamObserver<HelloReply> observer); StreamObserver<String> testErrorBiStream4(StreamObserver<HelloReply> observer, String str); }
6,056
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TriplePathResolverTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.PathResolver; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class TriplePathResolverTest { private static final PathResolver PATH_RESOLVER = ExtensionLoader.getExtensionLoader(PathResolver.class).getDefaultExtension(); private static final Invoker<Object> INVOKER = new Invoker<Object>() { @Override public URL getUrl() { return null; } @Override public boolean isAvailable() { return false; } @Override public void destroy() {} @Override public Class<Object> getInterface() { return null; } @Override public Result invoke(Invocation invocation) throws RpcException { return null; } }; @BeforeEach public void init() { PATH_RESOLVER.add("/abc", INVOKER); } @AfterEach public void destroy() { PATH_RESOLVER.destroy(); } @Test void testResolve() { Assertions.assertEquals(INVOKER, getInvokerByPath("/abc")); } @Test void testRemove() { Assertions.assertEquals(INVOKER, getInvokerByPath("/abc")); PATH_RESOLVER.remove("/abc"); Assertions.assertNull(getInvokerByPath("/abc")); } @Test void testNative() { String path = "path"; Assertions.assertFalse(PATH_RESOLVER.hasNativeStub(path)); PATH_RESOLVER.addNativeStub(path); Assertions.assertTrue(PATH_RESOLVER.hasNativeStub(path)); } @Test void testDestroy() { Assertions.assertEquals(INVOKER, getInvokerByPath("/abc")); { PATH_RESOLVER.add("/bcd", INVOKER); Assertions.assertEquals(INVOKER, getInvokerByPath("/bcd")); } PATH_RESOLVER.destroy(); Assertions.assertNull(getInvokerByPath("/abc")); Assertions.assertNull(getInvokerByPath("/bcd")); } private Invoker getInvokerByPath(String path) { return PATH_RESOLVER.resolve(path); } }
6,057
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.remoting.api.connection.ConnectionManager; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.call.ClientCall; import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall; import org.apache.dubbo.rpc.protocol.tri.compressor.Identity; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import java.util.HashSet; import java.util.concurrent.ExecutorService; import io.netty.channel.Channel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; class TripleInvokerTest { @Test void testNewCall() throws NoSuchMethodException { URL url = URL.valueOf("tri://127.0.0.1:9103/" + IGreeter.class.getName()); Channel channel = Mockito.mock(Channel.class); AbstractConnectionClient connectionClient = Mockito.mock(AbstractConnectionClient.class); ConnectionManager connectionManager = Mockito.mock(ConnectionManager.class); when(connectionManager.connect(any(URL.class), any(ChannelHandler.class))) .thenReturn(connectionClient); when(connectionClient.getChannel(true)).thenReturn(channel); when(connectionClient.isConnected()).thenReturn(true); ExecutorService executorService = ExecutorRepository.getInstance(url.getOrDefaultApplicationModel()) .createExecutorIfAbsent(url); TripleClientCall call = Mockito.mock(TripleClientCall.class); StreamObserver streamObserver = Mockito.mock(StreamObserver.class); when(call.start(any(RequestMetadata.class), any(ClientCall.Listener.class))) .thenReturn(streamObserver); RpcInvocation invocation = new RpcInvocation(); invocation.setMethodName("test"); invocation.setArguments(new Object[] {streamObserver, streamObserver}); TripleInvoker<IGreeter> invoker = new TripleInvoker<>( IGreeter.class, url, Identity.MESSAGE_ENCODING, connectionClient, new HashSet<>(), executorService); MethodDescriptor echoMethod = new ReflectionMethodDescriptor(IGreeter.class.getDeclaredMethod("echo", String.class)); Assertions.assertTrue(invoker.isAvailable()); invoker.invokeUnary(echoMethod, invocation, call, new ThreadlessExecutor()); invoker.destroy(); Assertions.assertFalse(invoker.isAvailable()); } }
6,058
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWapperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.triple.TripleWrapper; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import com.google.protobuf.ByteString; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TripleCustomerProtocolWapperTest { @Test void testVarInt() { int seed = 3; while (seed < Integer.MAX_VALUE && seed > 0) { byte[] varIntBytes = TripleCustomerProtocolWapper.varIntEncode(seed); ByteBuffer buffer = ByteBuffer.wrap(varIntBytes); int numDecodeFromVarIntByte = TripleCustomerProtocolWapper.readRawVarint32(buffer); Assertions.assertEquals(seed, numDecodeFromVarIntByte); seed = seed * 7; } } @Test void testRangeViaInt() { for (int index = 0; index < 100000; index++) { byte[] varIntBytes = TripleCustomerProtocolWapper.varIntEncode(index); ByteBuffer buffer = ByteBuffer.wrap(varIntBytes); int numDecodeFromVarIntByte = TripleCustomerProtocolWapper.readRawVarint32(buffer); Assertions.assertEquals(index, numDecodeFromVarIntByte); } } @Test void testTripleRequestWrapperWithOnlySerializeType() { String serialize = "hession"; TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize).build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder().setSerializeType(serialize); Assertions.assertArrayEquals( tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); } @Test void testTripleRequestWrapperBuild() { byte[] firstArg = "i am first arg".getBytes(StandardCharsets.UTF_8); byte[] secondArg = "i am second arg".getBytes(StandardCharsets.UTF_8); String serialize = "hession"; TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(firstArg) .addArgs(secondArg) .build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() .setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(ByteString.copyFrom(firstArg)) .addArgs(ByteString.copyFrom(secondArg)); Assertions.assertArrayEquals( tripleRequestWrapper.toByteArray(), pbbuilder.build().toByteArray()); } @Test void testTripleRequestWrapperParseFrom() { byte[] firstArg = "i am first arg".getBytes(StandardCharsets.UTF_8); byte[] secondArg = "i am second arg".getBytes(StandardCharsets.UTF_8); String serialize = "hession4"; TripleCustomerProtocolWapper.TripleRequestWrapper.Builder builder = TripleCustomerProtocolWapper.TripleRequestWrapper.Builder.newBuilder(); TripleCustomerProtocolWapper.TripleRequestWrapper tripleRequestWrapper = builder.setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(firstArg) .addArgs(secondArg) .build(); final TripleWrapper.TripleRequestWrapper.Builder pbbuilder = TripleWrapper.TripleRequestWrapper.newBuilder() .setSerializeType(serialize) .addArgTypes("com.google.protobuf.ByteString") .addArgTypes("org.apache.dubbo.common.URL") .addArgs(ByteString.copyFrom(firstArg)) .addArgs(ByteString.copyFrom(secondArg)); TripleCustomerProtocolWapper.TripleRequestWrapper parseFrom = TripleCustomerProtocolWapper.TripleRequestWrapper.parseFrom( pbbuilder.build().toByteArray()); Assertions.assertEquals(parseFrom.getSerializeType(), tripleRequestWrapper.getSerializeType()); Assertions.assertArrayEquals( parseFrom.getArgs().toArray(), tripleRequestWrapper.getArgs().toArray()); Assertions.assertArrayEquals( parseFrom.getArgTypes().toArray(), tripleRequestWrapper.getArgTypes().toArray()); } @Test void testTripleResponseWrapperWithNullData() { String serializeType = "hession4"; String type = "String"; TripleCustomerProtocolWapper.TripleResponseWrapper.Builder builder = TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder(); TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = builder.setSerializeType(serializeType).setType(type).build(); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder().setType(type).setSerializeType(serializeType); Assertions.assertArrayEquals(pbBuilder.build().toByteArray(), tripleResponseWrapper.toByteArray()); } @Test void testTripleResponseWrapper() { String serializeType = "hession4"; String type = "String"; String data = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + " * contributor license agreements. See the NOTICE file distributed with\n" + " * this work for additional information regarding copyright ownership.\n" + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + " * (the \"License\"); you may not use this file except in compliance with\n" + " * the License. You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); TripleCustomerProtocolWapper.TripleResponseWrapper.Builder builder = TripleCustomerProtocolWapper.TripleResponseWrapper.Builder.newBuilder(); TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = builder.setSerializeType( serializeType) .setType(type) .setData(dataBytes) .build(); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() .setType(type) .setData(ByteString.copyFrom(dataBytes)) .setSerializeType(serializeType); Assertions.assertArrayEquals(pbBuilder.build().toByteArray(), tripleResponseWrapper.toByteArray()); } @Test void testTripleResponseParseFrom() { String serializeType = "hession4"; String type = "String"; String data = "/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n" + " * contributor license agreements. See the NOTICE file distributed with\n" + " * this work for additional information regarding copyright ownership.\n" + " * The ASF licenses this file to You under the Apache License, Version 2.0\n" + " * (the \"License\"); you may not use this file except in compliance with\n" + " * the License. You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " */"; byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); TripleWrapper.TripleResponseWrapper.Builder pbBuilder = TripleWrapper.TripleResponseWrapper.newBuilder() .setType(type) .setData(ByteString.copyFrom(dataBytes)) .setSerializeType(serializeType); byte[] pbRawBytes = pbBuilder.build().toByteArray(); TripleCustomerProtocolWapper.TripleResponseWrapper tripleResponseWrapper = TripleCustomerProtocolWapper.TripleResponseWrapper.parseFrom(pbRawBytes); Assertions.assertArrayEquals(pbRawBytes, tripleResponseWrapper.toByteArray()); Assertions.assertArrayEquals(dataBytes, tripleResponseWrapper.getData()); Assertions.assertEquals(serializeType, tripleResponseWrapper.getSerializeType()); Assertions.assertEquals(type, tripleResponseWrapper.getType()); } }
6,059
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ExceptionUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.*; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter2; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter2Impl; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ExceptionUtilsTest { private IllegalStateException exception = new IllegalStateException("Exception0"); @Test void getStackTrace() { Assertions.assertTrue(ExceptionUtils.getStackTrace(exception).contains("Exception0")); } @Test void getStackFrameString() { String str = ExceptionUtils.getStackFrameString(Arrays.stream(exception.getStackTrace()) .map(StackTraceElement::toString) .collect(Collectors.toList())); Assertions.assertTrue(str.contains("ExceptionUtilsTest")); } @Test void getStackFrames() { StackTraceElement[] traces = exception.getStackTrace(); List<String> frames = Arrays.stream(traces).map(StackTraceElement::toString).collect(Collectors.toList()); String str = ExceptionUtils.getStackFrameString(frames); List<String> stackFrames = Arrays.stream(ExceptionUtils.getStackFrames(str)).collect(Collectors.toList()); Assertions.assertEquals(frames, stackFrames); } @Test void testGetStackFrames() { String[] stackFrames = ExceptionUtils.getStackFrames(exception); Assertions.assertNotEquals(0, stackFrames.length); } @Test void getStackFrameList() { List<String> stackFrameList = ExceptionUtils.getStackFrameList(exception, 10); Assertions.assertEquals(10, stackFrameList.size()); } @Test void testGetStackFrameList() { List<String> stackFrameList = ExceptionUtils.getStackFrameList(exception); Assertions.assertNotEquals(10, stackFrameList.size()); } @Test void testSelfDefineException() throws Exception { IGreeter2 serviceImpl = new IGreeter2Impl(); int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()) .addParameter(CommonConstants.TIMEOUT_KEY, 10000); ; ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter2.class); ProviderModel providerModel = new ProviderModel( providerUrl.getServiceKey(), serviceImpl, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter2.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel()); ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker<IGreeter2> invoker = proxy.getInvoker(serviceImpl, IGreeter2.class, providerUrl); Exporter<IGreeter2> export = protocol.export(invoker); URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter2.class.getName()) .addParameter(CommonConstants.TIMEOUT_KEY, 10000); ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter2 greeterProxy = proxy.getProxy(protocol.refer(IGreeter2.class, consumerUrl)); Thread.sleep(1000); // 1. test unaryStream String REQUEST_MSG = "hello world"; String EXPECT_RESPONSE_MSG = "I am self define exception"; try { greeterProxy.echo(REQUEST_MSG); } catch (IGreeterException e) { Assertions.assertEquals(EXPECT_RESPONSE_MSG, e.getMessage()); } Exception e = greeterProxy.echoException(REQUEST_MSG); Assertions.assertEquals(EXPECT_RESPONSE_MSG, e.getMessage()); export.unexport(); protocol.destroy(); // resource recycle. serviceRepository.destroy(); System.out.println("serviceRepository destroyed"); } }
6,060
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/TripleProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.support.IGreeterImpl; import org.apache.dubbo.rpc.protocol.tri.support.MockStreamObserver; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.protocol.tri.support.IGreeter.SERVER_MSG; class TripleProtocolTest { @Test void testDemoProtocol() throws Exception { IGreeter serviceImpl = new IGreeterImpl(); int availablePort = NetUtils.getAvailablePort(); ApplicationModel applicationModel = ApplicationModel.defaultModel(); URL providerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); ModuleServiceRepository serviceRepository = applicationModel.getDefaultModule().getServiceRepository(); ServiceDescriptor serviceDescriptor = serviceRepository.registerService(IGreeter.class); ProviderModel providerModel = new ProviderModel( providerUrl.getServiceKey(), serviceImpl, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(IGreeter.class)); serviceRepository.registerProvider(providerModel); providerUrl = providerUrl.setServiceModel(providerModel); Protocol protocol = new TripleProtocol(providerUrl.getOrDefaultFrameworkModel()); ProxyFactory proxy = applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Invoker<IGreeter> invoker = proxy.getInvoker(serviceImpl, IGreeter.class, providerUrl); Exporter<IGreeter> export = protocol.export(invoker); URL consumerUrl = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + IGreeter.class.getName()); ConsumerModel consumerModel = new ConsumerModel(consumerUrl.getServiceKey(), null, serviceDescriptor, null, null, null); consumerUrl = consumerUrl.setServiceModel(consumerModel); IGreeter greeterProxy = proxy.getProxy(protocol.refer(IGreeter.class, consumerUrl)); Thread.sleep(1000); // 1. test unaryStream String REQUEST_MSG = "hello world"; Assertions.assertEquals(REQUEST_MSG, greeterProxy.echo(REQUEST_MSG)); Assertions.assertEquals(REQUEST_MSG, serviceImpl.echoAsync(REQUEST_MSG).get()); // 2. test serverStream MockStreamObserver outboundMessageSubscriber1 = new MockStreamObserver(); greeterProxy.serverStream(REQUEST_MSG, outboundMessageSubscriber1); outboundMessageSubscriber1.getLatch().await(3000, TimeUnit.MILLISECONDS); Assertions.assertEquals(outboundMessageSubscriber1.getOnNextData(), REQUEST_MSG); Assertions.assertTrue(outboundMessageSubscriber1.isOnCompleted()); // 3. test bidirectionalStream MockStreamObserver outboundMessageSubscriber2 = new MockStreamObserver(); StreamObserver<String> inboundMessageObserver = greeterProxy.bidirectionalStream(outboundMessageSubscriber2); inboundMessageObserver.onNext(REQUEST_MSG); inboundMessageObserver.onCompleted(); outboundMessageSubscriber2.getLatch().await(3000, TimeUnit.MILLISECONDS); // verify client Assertions.assertEquals(outboundMessageSubscriber2.getOnNextData(), SERVER_MSG); Assertions.assertTrue(outboundMessageSubscriber2.isOnCompleted()); // verify server MockStreamObserver serverOutboundMessageSubscriber = (MockStreamObserver) ((IGreeterImpl) serviceImpl).getMockStreamObserver(); serverOutboundMessageSubscriber.getLatch().await(1000, TimeUnit.MILLISECONDS); Assertions.assertEquals(REQUEST_MSG, serverOutboundMessageSubscriber.getOnNextData()); Assertions.assertTrue(serverOutboundMessageSubscriber.isOnCompleted()); export.unexport(); protocol.destroy(); // resource recycle. serviceRepository.destroy(); System.out.println("serviceRepository destroyed"); } }
6,061
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/HelloReply.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import com.google.protobuf.Message; public final class HelloReply extends com.google.protobuf.GeneratedMessageV3 { @Override protected FieldAccessorTable internalGetFieldAccessorTable() { return null; } @Override protected Message.Builder newBuilderForType(BuilderParent builderParent) { return null; } @Override public Message.Builder newBuilderForType() { return null; } @Override public Message.Builder toBuilder() { return null; } @Override public Message getDefaultInstanceForType() { return null; } }
6,062
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/Http2ProtocolDetectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.Http2CodecUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * {@link Http2ProtocolDetector} */ class Http2ProtocolDetectorTest { @Test void testDetect() { ProtocolDetector detector = new Http2ProtocolDetector(); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); ByteBuf connectionPrefaceBuf = Http2CodecUtil.connectionPrefaceBuf(); ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(); ChannelBuffer in = new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer()); ProtocolDetector.Result result = detector.detect(in); Assertions.assertEquals(result, ProtocolDetector.Result.UNRECOGNIZED); byteBuf.writeBytes(connectionPrefaceBuf); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); Assertions.assertEquals(result, ProtocolDetector.Result.RECOGNIZED); byteBuf.clear(); byteBuf.writeBytes(connectionPrefaceBuf, 0, 1); result = detector.detect(new ByteBufferBackedChannelBuffer(byteBuf.nioBuffer())); Assertions.assertEquals(result, ProtocolDetector.Result.NEED_MORE_DATA); } }
6,063
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/SingleProtobufUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.triple.TripleWrapper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import com.google.protobuf.BoolValue; import com.google.protobuf.BytesValue; import com.google.protobuf.DoubleValue; import com.google.protobuf.Empty; import com.google.protobuf.EnumValue; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.google.protobuf.ListValue; import com.google.protobuf.Message; import com.google.protobuf.Parser; import com.google.protobuf.StringValue; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link SingleProtobufUtils} */ class SingleProtobufUtilsTest { @Test void test() throws IOException { Assertions.assertFalse(SingleProtobufUtils.isSupported(SingleProtobufUtilsTest.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(Empty.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(BoolValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(Int32Value.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(Int64Value.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(FloatValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(DoubleValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(BytesValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(StringValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(EnumValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(ListValue.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(HealthCheckResponse.class)); Assertions.assertTrue(SingleProtobufUtils.isSupported(HealthCheckRequest.class)); Message message = SingleProtobufUtils.defaultInst(HealthCheckRequest.class); Assertions.assertNotNull(message); Parser<HealthCheckRequest> parser = SingleProtobufUtils.getParser(HealthCheckRequest.class); Assertions.assertNotNull(parser); TripleWrapper.TripleRequestWrapper requestWrapper = TripleWrapper.TripleRequestWrapper.newBuilder() .setSerializeType("hessian4") .build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SingleProtobufUtils.serialize(requestWrapper, bos); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); TripleWrapper.TripleRequestWrapper tripleRequestWrapper = SingleProtobufUtils.deserialize(bis, TripleWrapper.TripleRequestWrapper.class); Assertions.assertEquals(tripleRequestWrapper.getSerializeType(), "hessian4"); } }
6,064
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/CancelableStreamObserverTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.rpc.CancellationContext; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class CancelableStreamObserverTest { @Test void setCancellationContext() { CancelableStreamObserver<Object> observer = new CancelableStreamObserver<Object>() { @Override public void onNext(Object data) {} @Override public void onError(Throwable throwable) {} @Override public void onCompleted() {} }; CancellationContext cancellationContext = new CancellationContext(); observer.setCancellationContext(cancellationContext); observer.cancel(new IllegalStateException()); Assertions.assertTrue(cancellationContext.isCancelled()); } @Test void cancel() {} }
6,065
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ClassLoadUtilTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.junit.jupiter.api.Test; class ClassLoadUtilTest { @Test void switchContextLoader() { ClassLoadUtil.switchContextLoader(Thread.currentThread().getContextClassLoader()); } }
6,066
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/PbUnpackTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import java.io.IOException; import io.grpc.health.v1.HealthCheckRequest; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class PbUnpackTest { @Test void unpack() throws IOException { HealthCheckRequest req = HealthCheckRequest.newBuilder().setService("service").build(); PbUnpack<HealthCheckRequest> unpack = new PbUnpack<>(HealthCheckRequest.class); HealthCheckRequest obj = (HealthCheckRequest) unpack.unpack(req.toByteArray()); Assertions.assertEquals("service", obj.getService()); } }
6,067
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/ReflectionPackableMethodTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.util.concurrent.CompletableFuture; import io.reactivex.Single; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class ReflectionPackableMethodTest { @Test void testUnaryFuture() throws Exception { Method method = DescriptorService.class.getMethod("unaryFuture"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals(CompletableFuture.class, descriptor.getReturnClass()); assertEquals(String.class, descriptor.getReturnTypes()[0]); } @Test void testMethodWithNoParameters() throws Exception { Method method = DescriptorService.class.getMethod("noParameterMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Assertions.assertEquals(0, descriptor.getParameterClasses().length); } @Test void testMethodWithNoParametersAndReturnProtobuf() throws Exception { Method method = DescriptorService.class.getMethod("noParameterAndReturnProtobufMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Assertions.assertEquals(0, descriptor.getParameterClasses().length); assertFalse(needWrap(descriptor)); } @Test void testMethodWithNoParametersAndReturnJava() throws Exception { Method method = DescriptorService.class.getMethod("noParameterAndReturnJavaClassMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); assertEquals("", descriptor.getParamDesc()); Assertions.assertEquals(0, descriptor.getParameterClasses().length); assertTrue(needWrap(descriptor)); } @Test void testWrapperBiStream() throws Exception { Method method = DescriptorService.class.getMethod("wrapBidirectionalStream", StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(1, descriptor.getParameterClasses().length); assertEquals(MethodDescriptor.RpcType.BI_STREAM, descriptor.getRpcType()); assertTrue(needWrap(descriptor)); } @Test void testBiStream() throws Exception { Method method = DescriptorService.class.getMethod("bidirectionalStream", StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(1, descriptor.getParameterClasses().length); assertSame(descriptor.getRpcType(), MethodDescriptor.RpcType.BI_STREAM); assertFalse(needWrap(descriptor)); } @Test void testIsStream() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("noParameterMethod"); ReflectionMethodDescriptor md1 = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, md1.getRpcType()); method = DescriptorService.class.getMethod("sayHello", HelloReply.class); ReflectionMethodDescriptor md2 = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, md2.getRpcType()); } @Test void testIsUnary() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("noParameterMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, descriptor.getRpcType()); method = DescriptorService.class.getMethod("sayHello", HelloReply.class); ReflectionMethodDescriptor md2 = new ReflectionMethodDescriptor(method); Assertions.assertEquals(MethodDescriptor.RpcType.UNARY, md2.getRpcType()); } @Test void testIsServerStream() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("sayHelloServerStream", HelloReply.class, StreamObserver.class); ReflectionMethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); Method method2 = DescriptorService.class.getMethod("sayHelloServerStream2", Object.class, StreamObserver.class); ReflectionMethodDescriptor descriptor2 = new ReflectionMethodDescriptor(method2); Assertions.assertTrue(needWrap(descriptor2)); } @Test void testIsNeedWrap() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("noParameterMethod"); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertTrue(needWrap(descriptor)); method = DescriptorService.class.getMethod("sayHello", HelloReply.class); descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); } @Test void testIgnoreMethod() throws NoSuchMethodException { Method method = DescriptorService.class.getMethod("iteratorServerStream", HelloReply.class); MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); Assertions.assertFalse(needWrap(descriptor)); Method method2 = DescriptorService.class.getMethod("reactorMethod", HelloReply.class); MethodDescriptor descriptor2 = new ReflectionMethodDescriptor(method2); Assertions.assertFalse(needWrap(descriptor2)); Method method3 = DescriptorService.class.getMethod("reactorMethod2", Mono.class); MethodDescriptor descriptor3 = new ReflectionMethodDescriptor(method3); Assertions.assertFalse(needWrap(descriptor3)); Method method4 = DescriptorService.class.getMethod("rxJavaMethod", Single.class); MethodDescriptor descriptor4 = new ReflectionMethodDescriptor(method4); Assertions.assertFalse(needWrap(descriptor4)); } @Test void testMultiProtoParameter() throws Exception { Method method = DescriptorService.class.getMethod("testMultiProtobufParameters", HelloReply.class, HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); } @Test void testDiffParametersAndReturn() throws Exception { Method method = DescriptorService.class.getMethod("testDiffParametersAndReturn", HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); Method method2 = DescriptorService.class.getMethod("testDiffParametersAndReturn2", String.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); } @Test void testErrorServerStream() throws Exception { Method method = DescriptorService.class.getMethod("testErrorServerStream", StreamObserver.class, HelloReply.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); Method method2 = DescriptorService.class.getMethod( "testErrorServerStream2", HelloReply.class, HelloReply.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); Method method3 = DescriptorService.class.getMethod("testErrorServerStream3", String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method3); needWrap(descriptor); }); Method method4 = DescriptorService.class.getMethod( "testErrorServerStream4", String.class, String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method4); needWrap(descriptor); }); } @Test void testErrorBiStream() throws Exception { Method method = DescriptorService.class.getMethod("testErrorBiStream", HelloReply.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method); needWrap(descriptor); }); Method method2 = DescriptorService.class.getMethod("testErrorBiStream2", String.class, StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method2); needWrap(descriptor); }); Method method3 = DescriptorService.class.getMethod("testErrorBiStream3", StreamObserver.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method3); needWrap(descriptor); }); Method method4 = DescriptorService.class.getMethod("testErrorBiStream4", StreamObserver.class, String.class); assertThrows(IllegalStateException.class, () -> { MethodDescriptor descriptor = new ReflectionMethodDescriptor(method4); needWrap(descriptor); }); } public boolean needWrap(MethodDescriptor method) { Class<?>[] actualRequestTypes; Class<?> actualResponseType; switch (method.getRpcType()) { case CLIENT_STREAM: case BI_STREAM: actualRequestTypes = new Class<?>[] { (Class<?>) ((ParameterizedType) method.getMethod().getGenericReturnType()).getActualTypeArguments()[0] }; actualResponseType = (Class<?>) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[0]) .getActualTypeArguments()[0]; break; case SERVER_STREAM: actualRequestTypes = method.getMethod().getParameterTypes(); actualResponseType = (Class<?>) ((ParameterizedType) method.getMethod().getGenericParameterTypes()[1]) .getActualTypeArguments()[0]; break; case UNARY: actualRequestTypes = method.getParameterClasses(); actualResponseType = method.getReturnClass(); break; default: throw new IllegalStateException("Can not reach here"); } return ReflectionPackableMethod.needWrap(method, actualRequestTypes, actualResponseType); } }
6,068
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/AbstractH2TransportListenerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.transport; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2Headers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static io.netty.handler.codec.http.HttpScheme.HTTPS; class AbstractH2TransportListenerTest { @Test void headersToMap() { AbstractH2TransportListener listener = new AbstractH2TransportListener() { @Override public void onHeader(Http2Headers headers, boolean endStream) {} @Override public void onData(ByteBuf data, boolean endStream) {} @Override public void cancelByRemote(long errorCode) {} }; DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.scheme(HTTPS.name()).path("/foo.bar").method(HttpMethod.POST.asciiName()); headers.set("foo", "bar"); final Map<String, Object> map = listener.headersToMap(headers, () -> null); Assertions.assertEquals(4, map.size()); } @Test void filterReservedHeaders() {} }
6,069
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueueTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.transport; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.command.CancelQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; import org.apache.dubbo.rpc.protocol.tri.command.TextDataQueueCommand; import org.apache.dubbo.rpc.protocol.tri.stream.TripleStreamChannelFuture; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.Channel; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultEventLoop; import io.netty.channel.EventLoop; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2Error; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import static org.apache.dubbo.rpc.protocol.tri.transport.WriteQueue.DEQUE_CHUNK_SIZE; /** * {@link WriteQueue} */ class WriteQueueTest { private final AtomicInteger writeMethodCalledTimes = new AtomicInteger(0); private Channel channel; @BeforeEach public void init() { channel = Mockito.mock(Channel.class); Channel parent = Mockito.mock(Channel.class); ChannelPromise promise = Mockito.mock(ChannelPromise.class); EventLoop eventLoop = new DefaultEventLoop(); Mockito.when(parent.eventLoop()).thenReturn(eventLoop); Mockito.when(channel.parent()).thenReturn(parent); Mockito.when(channel.eventLoop()).thenReturn(eventLoop); Mockito.when(channel.isActive()).thenReturn(true); Mockito.when(channel.newPromise()).thenReturn(promise); Mockito.when(channel.write(Mockito.any(), Mockito.any())) .thenAnswer((Answer<ChannelPromise>) invocationOnMock -> { writeMethodCalledTimes.incrementAndGet(); return promise; }); writeMethodCalledTimes.set(0); } @Test @Disabled void test() throws Exception { WriteQueue writeQueue = new WriteQueue(); EmbeddedChannel embeddedChannel = new EmbeddedChannel(); TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel); writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) .channel(channel)); writeQueue.enqueue(DataQueueCommand.create(tripleStreamChannelFuture, new byte[0], false, 0) .channel(channel)); TriRpcStatus status = TriRpcStatus.UNKNOWN.withCause(new RpcException()).withDescription("Encode Response data error"); writeQueue.enqueue(CancelQueueCommand.createCommand(tripleStreamChannelFuture, Http2Error.CANCEL) .channel(channel)); writeQueue.enqueue(TextDataQueueCommand.createCommand(tripleStreamChannelFuture, status.description, true) .channel(channel)); while (writeMethodCalledTimes.get() != 4) { Thread.sleep(50); } ArgumentCaptor<QueuedCommand> commandArgumentCaptor = ArgumentCaptor.forClass(QueuedCommand.class); ArgumentCaptor<ChannelPromise> promiseArgumentCaptor = ArgumentCaptor.forClass(ChannelPromise.class); Mockito.verify(channel, Mockito.times(4)) .write(commandArgumentCaptor.capture(), promiseArgumentCaptor.capture()); List<QueuedCommand> queuedCommands = commandArgumentCaptor.getAllValues(); Assertions.assertEquals(queuedCommands.size(), 4); Assertions.assertTrue(queuedCommands.get(0) instanceof HeaderQueueCommand); Assertions.assertTrue(queuedCommands.get(1) instanceof DataQueueCommand); Assertions.assertTrue(queuedCommands.get(2) instanceof CancelQueueCommand); Assertions.assertTrue(queuedCommands.get(3) instanceof TextDataQueueCommand); } @Test @Disabled void testChunk() throws Exception { WriteQueue writeQueue = new WriteQueue(); // test deque chunk size EmbeddedChannel embeddedChannel = new EmbeddedChannel(); TripleStreamChannelFuture tripleStreamChannelFuture = new TripleStreamChannelFuture(embeddedChannel); writeMethodCalledTimes.set(0); for (int i = 0; i < DEQUE_CHUNK_SIZE; i++) { writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) .channel(channel)); } writeQueue.enqueue(HeaderQueueCommand.createHeaders(tripleStreamChannelFuture, new DefaultHttp2Headers()) .channel(channel)); while (writeMethodCalledTimes.get() != (DEQUE_CHUNK_SIZE + 1)) { Thread.sleep(50); } Mockito.verify(channel, Mockito.times(DEQUE_CHUNK_SIZE + 1)).write(Mockito.any(), Mockito.any()); } }
6,070
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/transport/TripleHttp2ClientResponseHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.transport; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; import io.netty.handler.codec.http2.DefaultHttp2ResetFrame; import io.netty.handler.codec.http2.Http2Error; import io.netty.handler.codec.http2.Http2GoAwayFrame; import io.netty.handler.codec.http2.Http2Headers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; /** * {@link TripleHttp2ClientResponseHandler } */ class TripleHttp2ClientResponseHandlerTest { private TripleHttp2ClientResponseHandler handler; private ChannelHandlerContext ctx; private AbstractH2TransportListener transportListener; @BeforeEach public void init() { transportListener = Mockito.mock(AbstractH2TransportListener.class); handler = new TripleHttp2ClientResponseHandler(transportListener); ctx = Mockito.mock(ChannelHandlerContext.class); Channel channel = Mockito.mock(Channel.class); Mockito.when(ctx.channel()).thenReturn(channel); } @Test void testUserEventTriggered() throws Exception { // test Http2GoAwayFrame Http2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame( Http2Error.NO_ERROR, ByteBufUtil.writeAscii(ByteBufAllocator.DEFAULT, "app_requested")); handler.userEventTriggered(ctx, goAwayFrame); Mockito.verify(ctx, Mockito.times(1)).close(); // test Http2ResetFrame DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(Http2Error.CANCEL); handler.userEventTriggered(ctx, resetFrame); Mockito.verify(ctx, Mockito.times(2)).close(); } @Test void testChannelRead0() throws Exception { final Http2Headers headers = new DefaultHttp2Headers(true); DefaultHttp2HeadersFrame headersFrame = new DefaultHttp2HeadersFrame(headers, true); handler.channelRead0(ctx, headersFrame); Mockito.verify(transportListener, Mockito.times(1)).onHeader(headers, true); } @Test void testExceptionCaught() { RuntimeException exception = new RuntimeException(); handler.exceptionCaught(ctx, exception); Mockito.verify(ctx).close(); Mockito.verify(transportListener).cancelByRemote(Http2Error.INTERNAL_ERROR.code()); } }
6,071
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/SnappyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.compressor; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * test for snappy */ class SnappyTest { private static final String TEST_STR; static { StringBuilder builder = new StringBuilder(); int charNum = 1000000; for (int i = 0; i < charNum; i++) { builder.append("a"); } TEST_STR = builder.toString(); } @ValueSource(strings = {"snappy"}) @ParameterizedTest void compression(String compressorName) { Compressor compressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(Compressor.class) .getExtension(compressorName); String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); DeCompressor deCompressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(DeCompressor.class) .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); } }
6,072
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/Bzip2Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.compressor; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * test for Bzip2 */ class Bzip2Test { private static final String TEST_STR; static { StringBuilder builder = new StringBuilder(); int charNum = 1000000; for (int i = 0; i < charNum; i++) { builder.append("a"); } TEST_STR = builder.toString(); } @ValueSource(strings = {"bzip2"}) @ParameterizedTest void compression(String compressorName) { Compressor compressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(Compressor.class) .getExtension(compressorName); String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); DeCompressor deCompressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(DeCompressor.class) .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); } }
6,073
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/GzipTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.compressor; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class GzipTest { private static final String TEST_STR; static { StringBuilder builder = new StringBuilder(); int charNum = 1000000; for (int i = 0; i < charNum; i++) { builder.append("a"); } TEST_STR = builder.toString(); } @ValueSource(strings = {"gzip"}) @ParameterizedTest void compression(String compressorName) { Compressor compressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(Compressor.class) .getExtension(compressorName); String loadByStatic = Compressor.getCompressor(new FrameworkModel(), compressorName).getMessageEncoding(); Assertions.assertEquals(loadByStatic, compressor.getMessageEncoding()); byte[] compressedByteArr = compressor.compress(TEST_STR.getBytes()); DeCompressor deCompressor = ApplicationModel.defaultModel() .getDefaultModule() .getExtensionLoader(DeCompressor.class) .getExtension(compressorName); byte[] decompressedByteArr = deCompressor.decompress(compressedByteArr); Assertions.assertEquals(new String(decompressedByteArr), TEST_STR); } }
6,074
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/compressor/IdentityTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.compressor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class IdentityTest { @Test void getMessageEncoding() { Assertions.assertEquals("identity", Identity.IDENTITY.getMessageEncoding()); } @Test void compress() { byte[] input = new byte[] {1, 2, 3, 4, 5}; final byte[] compressed = Identity.IDENTITY.compress(input); Assertions.assertEquals(input, compressed); } @Test void decompress() { byte[] input = new byte[] {1, 2, 3, 4, 5}; final byte[] decompressed = Identity.IDENTITY.decompress(input); Assertions.assertEquals(input, decompressed); } }
6,075
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/MockClientStreamListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.stream; import org.apache.dubbo.rpc.TriRpcStatus; import java.util.Map; public class MockClientStreamListener implements ClientStream.Listener { public TriRpcStatus status; public byte[] message; public boolean started; @Override public void onStart() { started = true; } @Override public void onComplete(TriRpcStatus status, Map<String, Object> attachments) { this.status = status; } @Override public void onMessage(byte[] message, boolean isNeedReturnException) { this.message = message; } @Override public void onCancelByRemote(TriRpcStatus status) {} }
6,076
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/StreamUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.stream; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import io.netty.handler.codec.http2.DefaultHttp2Headers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class StreamUtilsTest { @Test void encodeBase64ASCII() { String content = "😯"; Assertions.assertArrayEquals( content.getBytes(StandardCharsets.UTF_8), StreamUtils.decodeASCIIByte(StreamUtils.encodeBase64ASCII(content.getBytes(StandardCharsets.UTF_8)))); } @Test void testConvertAttachment() throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(10); DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.add("key", "value"); Map<String, Object> attachments = new HashMap<>(); attachments.put(TripleHeaderEnum.PATH_KEY.getHeader(), "value"); attachments.put("key1111", "value"); attachments.put("Upper", "Upper"); attachments.put("obj", new Object()); StreamUtils.convertAttachment(headers, attachments, false); Assertions.assertNull(headers.get(TripleHeaderEnum.PATH_KEY.getHeader())); Assertions.assertNull(headers.get("Upper")); Assertions.assertNull(headers.get("obj")); headers = new DefaultHttp2Headers(); headers.add("key", "value"); StreamUtils.convertAttachment(headers, attachments, true); Assertions.assertNull(headers.get(TripleHeaderEnum.PATH_KEY.getHeader())); Assertions.assertNull(headers.get("Upper")); Assertions.assertNull(headers.get("obj")); String jsonRaw = headers.get(TripleHeaderEnum.TRI_HEADER_CONVERT.getHeader()).toString(); String json = TriRpcStatus.decodeMessage(jsonRaw); System.out.println(jsonRaw + "---" + json); Map<String, String> upperMap = JsonUtils.toJavaObject(json, Map.class); Assertions.assertArrayEquals( "Upper".getBytes(StandardCharsets.UTF_8), upperMap.get("upper").getBytes(StandardCharsets.UTF_8)); int count = 10000; CountDownLatch latch = new CountDownLatch(count); for (int i = 0; i < count; i++) { String randomKey = "key" + i; String randomValue = "value" + i; Map<String, Object> attachments2 = new HashMap<>(); attachments2.put(TripleHeaderEnum.PATH_KEY.getHeader(), "value"); attachments2.put("key1111", "value"); attachments2.put("Upper", "Upper"); attachments2.put("obj", new Object()); attachments2.put(randomKey, randomValue); executorService.execute(() -> { DefaultHttp2Headers headers2 = new DefaultHttp2Headers(); headers2.add("key", "value"); StreamUtils.convertAttachment(headers2, attachments2, true); if (headers2.get(TripleHeaderEnum.PATH_KEY.getHeader()) != null) { return; } if (headers2.get("Upper") != null) { return; } if (headers2.get("obj") != null) { return; } if (!headers2.get(randomKey).toString().equals(randomValue)) { return; } latch.countDown(); }); } latch.await(10, TimeUnit.SECONDS); Assertions.assertEquals(0, latch.getCount()); executorService.shutdown(); } }
6,077
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/stream/TripleClientStreamTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.stream; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.RequestMetadata; import org.apache.dubbo.rpc.protocol.tri.TripleConstant; import org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum; import org.apache.dubbo.rpc.protocol.tri.command.CancelQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.CreateStreamQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.DataQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.EndStreamQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.HeaderQueueCommand; import org.apache.dubbo.rpc.protocol.tri.command.QueuedCommand; import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import org.apache.dubbo.rpc.protocol.tri.transport.H2TransportListener; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; import java.util.concurrent.Executor; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpScheme; import io.netty.handler.codec.http2.DefaultHttp2Headers; import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class TripleClientStreamTest { @Test void progress() { final URL url = URL.valueOf("tri://127.0.0.1:8080/foo.bar.service"); final ModuleServiceRepository repo = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); repo.registerService(IGreeter.class); final ServiceDescriptor serviceDescriptor = repo.getService(IGreeter.class.getName()); final MethodDescriptor methodDescriptor = serviceDescriptor.getMethod("echo", new Class<?>[] {String.class}); MockClientStreamListener listener = new MockClientStreamListener(); TripleWriteQueue writeQueue = mock(TripleWriteQueue.class); final EmbeddedChannel channel = new EmbeddedChannel(); when(writeQueue.enqueueFuture(any(QueuedCommand.class), any(Executor.class))) .thenReturn(channel.newPromise()); Http2StreamChannel http2StreamChannel = mock(Http2StreamChannel.class); when(http2StreamChannel.isActive()).thenReturn(true); when(http2StreamChannel.newSucceededFuture()).thenReturn(channel.newSucceededFuture()); when(http2StreamChannel.eventLoop()).thenReturn(new NioEventLoopGroup().next()); when(http2StreamChannel.newPromise()).thenReturn(channel.newPromise()); when(http2StreamChannel.parent()).thenReturn(channel); TripleClientStream stream = new TripleClientStream( url.getOrDefaultFrameworkModel(), ImmediateEventExecutor.INSTANCE, writeQueue, listener, http2StreamChannel); verify(writeQueue).enqueue(any(CreateStreamQueueCommand.class)); final RequestMetadata requestMetadata = new RequestMetadata(); requestMetadata.method = methodDescriptor; requestMetadata.scheme = TripleConstant.HTTP_SCHEME; requestMetadata.compressor = Compressor.NONE; requestMetadata.acceptEncoding = Compressor.NONE.getMessageEncoding(); requestMetadata.address = url.getAddress(); requestMetadata.service = url.getPath(); requestMetadata.group = url.getGroup(); requestMetadata.version = url.getVersion(); stream.sendHeader(requestMetadata.toHeaders()); verify(writeQueue).enqueueFuture(any(HeaderQueueCommand.class), any(Executor.class)); // no other commands verify(writeQueue).enqueue(any(QueuedCommand.class)); stream.sendMessage(new byte[0], 0, false); verify(writeQueue).enqueueFuture(any(DataQueueCommand.class), any(Executor.class)); verify(writeQueue, times(2)).enqueueFuture(any(QueuedCommand.class), any(Executor.class)); stream.halfClose(); verify(writeQueue).enqueueFuture(any(EndStreamQueueCommand.class), any(Executor.class)); verify(writeQueue, times(3)).enqueueFuture(any(QueuedCommand.class), any(Executor.class)); stream.cancelByLocal(TriRpcStatus.CANCELLED); verify(writeQueue, times(1)).enqueue(any(CancelQueueCommand.class)); verify(writeQueue, times(3)).enqueueFuture(any(QueuedCommand.class), any(Executor.class)); H2TransportListener transportListener = stream.createTransportListener(); DefaultHttp2Headers headers = new DefaultHttp2Headers(); headers.scheme(HttpScheme.HTTP.name()).status(HttpResponseStatus.OK.codeAsText()); headers.set(TripleHeaderEnum.STATUS_KEY.getHeader(), TriRpcStatus.OK.code.code + ""); headers.set(TripleHeaderEnum.CONTENT_TYPE_KEY.getHeader(), TripleHeaderEnum.CONTENT_PROTO.getHeader()); transportListener.onHeader(headers, false); Assertions.assertTrue(listener.started); stream.request(2); byte[] data = new byte[] {0, 0, 0, 0, 1, 1}; final ByteBuf buf = Unpooled.wrappedBuffer(data); transportListener.onData(buf, false); Assertions.assertEquals(1, listener.message.length); } }
6,078
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/RecordListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.frame; public class RecordListener implements TriDecoder.Listener { byte[] lastData; int dataCount; boolean close; @Override public void onRawMessage(byte[] data) { dataCount += 1; lastData = data; } @Override public void close() { close = true; } }
6,079
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/frame/TriDecoderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.frame; import org.apache.dubbo.rpc.protocol.tri.compressor.DeCompressor; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TriDecoderTest { @Test void decode() { final RecordListener listener = new RecordListener(); TriDecoder decoder = new TriDecoder(DeCompressor.NONE, listener); final ByteBuf buf = Unpooled.buffer(); buf.writeByte(0); buf.writeInt(1); buf.writeByte(2); decoder.deframe(buf); final ByteBuf buf2 = Unpooled.buffer(); buf2.writeByte(0); buf2.writeInt(2); buf2.writeByte(2); buf2.writeByte(3); decoder.deframe(buf2); Assertions.assertEquals(0, listener.dataCount); decoder.request(1); Assertions.assertEquals(1, listener.dataCount); Assertions.assertEquals(1, listener.lastData.length); decoder.request(1); Assertions.assertEquals(2, listener.dataCount); Assertions.assertEquals(2, listener.lastData.length); decoder.close(); } }
6,080
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/StubServerCallTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.call; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.MethodDescriptor.RpcType; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.stream.TripleServerStream; import java.util.Collections; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; class StubServerCallTest { @Test void doStartCall() throws Exception { Invoker<?> invoker = Mockito.mock(Invoker.class); TripleServerStream tripleServerStream = Mockito.mock(TripleServerStream.class); ProviderModel providerModel = Mockito.mock(ProviderModel.class); ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); StubMethodDescriptor methodDescriptor = Mockito.mock(StubMethodDescriptor.class); URL url = Mockito.mock(URL.class); when(invoker.getUrl()).thenReturn(url); when(url.getServiceModel()).thenReturn(providerModel); when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); when(serviceDescriptor.getMethods(anyString())).thenReturn(Collections.singletonList(methodDescriptor)); when(methodDescriptor.getRpcType()).thenReturn(RpcType.UNARY); when(methodDescriptor.parseRequest(any(byte[].class))).thenReturn("test"); String service = "testService"; String method = "method"; StubAbstractServerCall call = new StubAbstractServerCall( invoker, tripleServerStream, new FrameworkModel(), "", service, method, ImmediateEventExecutor.INSTANCE); call.onHeader(Collections.emptyMap()); call.onMessage(new byte[0], false); call.onComplete(); } }
6,081
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ReflectionServerCallTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.call; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ReflectionMethodDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.tri.DescriptorService; import org.apache.dubbo.rpc.protocol.tri.HelloReply; import org.apache.dubbo.rpc.protocol.tri.stream.TripleServerStream; import java.lang.reflect.Method; import java.util.Collections; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; class ReflectionServerCallTest { @Test void doStartCall() throws NoSuchMethodException { Invoker<?> invoker = Mockito.mock(Invoker.class); TripleServerStream serverStream = Mockito.mock(TripleServerStream.class); ProviderModel providerModel = Mockito.mock(ProviderModel.class); ServiceMetadata serviceMetadata = new ServiceMetadata(); Method method = DescriptorService.class.getMethod("sayHello", HelloReply.class); MethodDescriptor methodDescriptor = new ReflectionMethodDescriptor(method); URL url = Mockito.mock(URL.class); when(invoker.getUrl()).thenReturn(url); when(url.getServiceModel()).thenReturn(providerModel); when(providerModel.getServiceMetadata()).thenReturn(serviceMetadata); String service = "testService"; String methodName = "method"; try { ReflectionAbstractServerCall call = new ReflectionAbstractServerCall( invoker, serverStream, new FrameworkModel(), "", service, methodName, Collections.emptyList(), ImmediateEventExecutor.INSTANCE); fail(); } catch (Exception e) { // pass } ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); when(serviceDescriptor.getMethods(anyString())).thenReturn(Collections.singletonList(methodDescriptor)); when(providerModel.getServiceModel()).thenReturn(serviceDescriptor); ReflectionAbstractServerCall call2 = new ReflectionAbstractServerCall( invoker, serverStream, new FrameworkModel(), "", service, methodName, Collections.emptyList(), ImmediateEventExecutor.INSTANCE); call2.onHeader(Collections.emptyMap()); call2.onMessage(new byte[0], false); call2.onComplete(); } }
6,082
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/call/ClientCallTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.call; class ClientCallTest {}
6,083
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/MockStreamObserver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CountDownLatch; /** * Usually use it to simulate a outboundMessageSubscriber */ public class MockStreamObserver implements StreamObserver<String> { private String onNextData; private Throwable onErrorThrowable; private boolean onCompleted; private CountDownLatch latch = new CountDownLatch(1); @Override public void onNext(String data) { onNextData = data; } @Override public void onError(Throwable throwable) { onErrorThrowable = throwable; } @Override public void onCompleted() { onCompleted = true; latch.countDown(); } public String getOnNextData() { return onNextData; } public Throwable getOnErrorThrowable() { return onErrorThrowable; } public boolean isOnCompleted() { return onCompleted; } public CountDownLatch getLatch() { return latch; } }
6,084
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.support; public interface IGreeter2 { String SERVER_MSG = "HELLO WORLD"; /** * Use request to respond */ String echo(String request) throws IGreeterException; Exception echoException(String request); }
6,085
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.support; public class IGreeterException extends Exception { private String message; public IGreeterException(String message) { super(message); this.message = message; } public IGreeterException(String message, Throwable cause) { super(message, cause); } }
6,086
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; import java.util.concurrent.CompletableFuture; public interface IGreeter { String SERVER_MSG = "HELLO WORLD"; /** * Use request to respond */ String echo(String request); default CompletableFuture<String> echoAsync(String request) { return CompletableFuture.supplyAsync(() -> echo(request)); } void serverStream(String str, StreamObserver<String> observer); StreamObserver<String> bidirectionalStream(StreamObserver<String> observer); }
6,087
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeter2Impl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.support; public class IGreeter2Impl implements IGreeter2 { @Override public String echo(String request) throws IGreeterException { throw new IGreeterException("I am self define exception"); } @Override public Exception echoException(String request) { return new IGreeterException("I am self define exception"); } }
6,088
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/support/IGreeterImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.support; import org.apache.dubbo.common.stream.StreamObserver; public class IGreeterImpl implements IGreeter { private StreamObserver<String> mockStreamObserver; @Override public String echo(String request) { return request; } @Override public void serverStream(String str, StreamObserver<String> observer) { System.out.println("server stream data=" + str); observer.onNext(str); observer.onCompleted(); } @Override public StreamObserver<String> bidirectionalStream(StreamObserver<String> observer) { System.out.println("bi stream"); mockStreamObserver = new MockStreamObserver() { @Override public void onNext(String data) { super.onNext(data); observer.onNext(SERVER_MSG); } @Override public void onCompleted() { super.onCompleted(); observer.onCompleted(); } }; return mockStreamObserver; // This will serve as the server's outboundMessageSubscriber } public StreamObserver<String> getMockStreamObserver() { return mockStreamObserver; } }
6,089
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriBuiltinServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.service; import org.apache.dubbo.rpc.PathResolver; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.stub.StubSuppliers; import io.grpc.health.v1.DubboHealthTriple; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link TriBuiltinService} */ class TriBuiltinServiceTest { @Test void testDefaultNotEnable() { FrameworkModel frameworkModel = new FrameworkModel(); TriBuiltinService triBuiltinService = new TriBuiltinService(frameworkModel); Assertions.assertFalse(triBuiltinService.enable()); Assertions.assertNull(triBuiltinService.getHealthStatusManager()); } @Test void testForceEnable() { FrameworkModel frameworkModel = new FrameworkModel(); TriBuiltinService triBuiltinService = new TriBuiltinService(frameworkModel); triBuiltinService.init(); String serviceName = DubboHealthTriple.SERVICE_NAME; Assertions.assertNotNull(triBuiltinService.getHealthStatusManager()); PathResolver pathResolver = frameworkModel.getExtensionLoader(PathResolver.class).getDefaultExtension(); Assertions.assertNotNull(pathResolver.resolve(serviceName)); ModuleServiceRepository repository = frameworkModel.getInternalApplicationModel().getInternalModule().getServiceRepository(); Assertions.assertFalse(repository.getAllServices().isEmpty()); Assertions.assertNotNull(StubSuppliers.getServiceDescriptor(serviceName)); } }
6,090
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/TriHealthImplTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.service; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.IdentityHashMap; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import io.grpc.health.v1.HealthCheckResponse.ServingStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link TriHealthImpl} */ class TriHealthImplTest { @Test void testCheck() { TriHealthImpl triHealth = new TriHealthImpl(); HealthCheckRequest request = HealthCheckRequest.newBuilder().build(); HealthCheckResponse response = triHealth.check(request); Assertions.assertEquals(response.getStatus(), HealthCheckResponse.ServingStatus.SERVING); HealthCheckRequest badRequest = HealthCheckRequest.newBuilder().setService("test").build(); Assertions.assertThrows(RpcException.class, () -> triHealth.check(badRequest)); } @Test void testWatch() throws Exception { TriHealthImpl triHealth = new TriHealthImpl(); HealthCheckRequest request = HealthCheckRequest.newBuilder().setService("testWatch").build(); triHealth.setStatus(request.getService(), ServingStatus.SERVING); StreamObserver<HealthCheckResponse> streamObserver = new MockStreamObserver(); RpcContext.removeCancellationContext(); // test watch triHealth.watch(request, streamObserver); Assertions.assertNotNull(RpcContext.getCancellationContext().getListeners()); HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> watches = getWatches(triHealth); Assertions.assertTrue(watches.containsKey(request.getService())); Assertions.assertTrue(watches.get(request.getService()).containsKey(streamObserver)); Assertions.assertTrue(watches.get(request.getService()).get(streamObserver)); MockStreamObserver mockStreamObserver = (MockStreamObserver) streamObserver; Assertions.assertEquals(mockStreamObserver.getCount(), 1); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVING); // test setStatus triHealth.setStatus(request.getService(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); Assertions.assertEquals(mockStreamObserver.getCount(), 2); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); triHealth.enterTerminalState(); Assertions.assertEquals(mockStreamObserver.getCount(), 3); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.NOT_SERVING); // test clearStatus turnOffTerminal(triHealth); triHealth.clearStatus(request.getService()); Assertions.assertEquals(mockStreamObserver.getCount(), 4); Assertions.assertEquals( mockStreamObserver.getResponse().getStatus(), HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); // test listener RpcContext.getCancellationContext().close(); Assertions.assertTrue(watches.isEmpty()); } private void turnOffTerminal(TriHealthImpl triHealth) throws NoSuchFieldException, IllegalAccessException { Field terminalField = triHealth.getClass().getDeclaredField("terminal"); terminalField.setAccessible(true); terminalField.set(triHealth, false); } private HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> getWatches( TriHealthImpl triHealth) throws Exception { Field watchersField = triHealth.getClass().getDeclaredField("watchers"); watchersField.setAccessible(true); HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>> watches = (HashMap<String, IdentityHashMap<StreamObserver<HealthCheckResponse>, Boolean>>) watchersField.get(triHealth); return watches; } class MockStreamObserver implements StreamObserver<HealthCheckResponse> { private int count = 0; private HealthCheckResponse response; @Override public void onNext(HealthCheckResponse data) { count++; response = data; } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() {} public int getCount() { return count; } public HealthCheckResponse getResponse() { return response; } } }
6,091
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/protocol/tri/service/HealthStatusManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri.service; import org.apache.dubbo.rpc.StatusRpcException; import org.apache.dubbo.rpc.TriRpcStatus.Code; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse.ServingStatus; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; class HealthStatusManagerTest { private final TriHealthImpl health = new TriHealthImpl(); private final HealthStatusManager manager = new HealthStatusManager(health); @Test void getHealthService() { Assertions.assertNotNull(manager.getHealthService()); } @Test void setStatus() { String service = "serv0"; manager.setStatus(service, ServingStatus.SERVING); ServingStatus stored = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); } @Test void clearStatus() { String service = "serv1"; manager.setStatus(service, ServingStatus.SERVING); ServingStatus stored = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); manager.clearStatus(service); try { manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()); fail(); } catch (StatusRpcException e) { Assertions.assertEquals(Code.NOT_FOUND, e.getStatus().code); } } @Test void enterTerminalState() { String service = "serv2"; manager.setStatus(service, ServingStatus.SERVING); ServingStatus stored = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.SERVING, stored); manager.enterTerminalState(); ServingStatus stored2 = manager.getHealthService() .check(HealthCheckRequest.newBuilder().setService(service).build()) .getStatus(); Assertions.assertEquals(ServingStatus.NOT_SERVING, stored2); } }
6,092
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/test/java/org/apache/dubbo/rpc/stub/StubInvocationUtilTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.stub; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.tri.support.IGreeter; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; class StubInvocationUtilTest { private Invoker<IGreeter> invoker; private MethodDescriptor method; private String request = "request"; private String response = "response"; private Result result; private Invoker<IGreeter> createMockInvoker(URL url) { Invoker<IGreeter> invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); when(invoker.getInterface()).thenReturn(IGreeter.class); return invoker; } private URL createMockURL(ConsumerModel consumerModel) { URL url = Mockito.mock(URL.class); when(url.getServiceModel()).thenReturn(consumerModel); when(url.getServiceInterface()).thenReturn(IGreeter.class.getName()); when(url.getProtocolServiceKey()).thenReturn(IGreeter.class.getName()); return url; } private ConsumerModel createMockConsumerModel(ServiceDescriptor serviceDescriptor) { ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); when(consumerModel.getServiceModel()).thenReturn(serviceDescriptor); return consumerModel; } private Result createMockResult(String response) throws Throwable { Result result = Mockito.mock(Result.class); when(result.recreate()).thenReturn(response); return result; } private MethodDescriptor createMockMethodDescriptor() { MethodDescriptor method = Mockito.mock(MethodDescriptor.class); when(method.getParameterClasses()).thenReturn(new Class[] {String.class}); when(method.getMethodName()).thenReturn("sayHello"); return method; } @BeforeEach void init() throws Throwable { ServiceDescriptor serviceDescriptor = Mockito.mock(ServiceDescriptor.class); ConsumerModel consumerModel = createMockConsumerModel(serviceDescriptor); URL url = createMockURL(consumerModel); invoker = createMockInvoker(url); result = createMockResult("response"); method = createMockMethodDescriptor(); } @Test void unaryCall() { when(invoker.invoke(any(Invocation.class))).thenReturn(result); Object ret = StubInvocationUtil.unaryCall(invoker, method, request); Assertions.assertEquals(response, ret); } @Test void unaryCall2() { when(invoker.invoke(any(Invocation.class))) .thenThrow(new RuntimeException("a")) .thenThrow(new Error("b")); try { StubInvocationUtil.unaryCall(invoker, method, request); fail(); } catch (Throwable t) { // pass } try { StubInvocationUtil.unaryCall(invoker, method, request); fail(); } catch (Throwable t) { // pass } } @Test void testUnaryCall() throws Throwable { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> result); CountDownLatch latch = new CountDownLatch(1); AtomicReference<Object> atomicReference = new AtomicReference<>(); StreamObserver<Object> responseObserver = new StreamObserver<Object>() { @Override public void onNext(Object data) { atomicReference.set(data); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { latch.countDown(); } }; StubInvocationUtil.unaryCall(invoker, method, request, responseObserver); latch.await(1, TimeUnit.SECONDS); Assertions.assertEquals(response, atomicReference.get()); } @Test void biOrClientStreamCall() throws InterruptedException { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> { Invocation invocation = (Invocation) invocationOnMock.getArguments()[0]; StreamObserver<Object> observer = (StreamObserver<Object>) invocation.getArguments()[0]; observer.onNext(response); observer.onCompleted(); when(result.recreate()).then(invocationOnMock1 -> new StreamObserver<Object>() { @Override public void onNext(Object data) { observer.onNext(data); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { observer.onCompleted(); } }); return result; }); CountDownLatch latch = new CountDownLatch(11); StreamObserver<Object> responseObserver = new StreamObserver<Object>() { @Override public void onNext(Object data) { latch.countDown(); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { latch.countDown(); } }; StreamObserver<Object> observer = StubInvocationUtil.biOrClientStreamCall(invoker, method, responseObserver); for (int i = 0; i < 10; i++) { observer.onNext(request); } observer.onCompleted(); Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS)); } @Test void serverStreamCall() throws InterruptedException { when(invoker.invoke(any(Invocation.class))).then(invocationOnMock -> { Invocation invocation = (Invocation) invocationOnMock.getArguments()[0]; StreamObserver<Object> observer = (StreamObserver<Object>) invocation.getArguments()[1]; for (int i = 0; i < 10; i++) { observer.onNext(response); } observer.onCompleted(); return result; }); CountDownLatch latch = new CountDownLatch(11); StreamObserver<Object> responseObserver = new StreamObserver<Object>() { @Override public void onNext(Object data) { latch.countDown(); } @Override public void onError(Throwable throwable) {} @Override public void onCompleted() { latch.countDown(); } }; StubInvocationUtil.serverStreamCall(invoker, method, request, responseObserver); Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS)); } }
6,093
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/StatusRpcException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public class StatusRpcException extends RpcException { public TriRpcStatus getStatus() { return status; } private final TriRpcStatus status; public StatusRpcException(TriRpcStatus status) { super(TriRpcStatus.triCodeToDubboCode(status.code), status.toMessageWithoutCause(), status.cause); this.status = status; } }
6,094
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/TriRpcStatus.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.TimeoutException; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.QueryStringEncoder; import static org.apache.dubbo.rpc.RpcException.FORBIDDEN_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.LIMIT_EXCEEDED_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.METHOD_NOT_FOUND; import static org.apache.dubbo.rpc.RpcException.NETWORK_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.SERIALIZATION_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.TIMEOUT_EXCEPTION; import static org.apache.dubbo.rpc.RpcException.TIMEOUT_TERMINATE; import static org.apache.dubbo.rpc.RpcException.UNKNOWN_EXCEPTION; /** * See https://github.com/grpc/grpc/blob/master/doc/statuscodes.md */ public class TriRpcStatus { public static final TriRpcStatus OK = fromCode(Code.OK); public static final TriRpcStatus UNKNOWN = fromCode(Code.UNKNOWN); public static final TriRpcStatus INTERNAL = fromCode(Code.INTERNAL); public static final TriRpcStatus NOT_FOUND = fromCode(Code.NOT_FOUND); public static final TriRpcStatus CANCELLED = fromCode(Code.CANCELLED); public static final TriRpcStatus UNAVAILABLE = fromCode(Code.UNAVAILABLE); public static final TriRpcStatus UNIMPLEMENTED = fromCode(Code.UNIMPLEMENTED); public static final TriRpcStatus DEADLINE_EXCEEDED = fromCode(Code.DEADLINE_EXCEEDED); public final Code code; public final Throwable cause; public final String description; public TriRpcStatus(Code code, Throwable cause, String description) { this.code = code; this.cause = cause; this.description = description; } public static TriRpcStatus fromCode(int code) { return fromCode(Code.fromCode(code)); } public static TriRpcStatus fromCode(Code code) { return new TriRpcStatus(code, null, null); } /** * todo The remaining exceptions are converted to status */ public static TriRpcStatus getStatus(Throwable throwable) { return getStatus(throwable, null); } public static TriRpcStatus getStatus(Throwable throwable, String description) { if (throwable instanceof StatusRpcException) { return ((StatusRpcException) throwable).getStatus(); } if (throwable instanceof RpcException) { RpcException rpcException = (RpcException) throwable; Code code = dubboCodeToTriCode(rpcException.getCode()); return new TriRpcStatus(code, throwable, description); } if (throwable instanceof TimeoutException) { return new TriRpcStatus(Code.DEADLINE_EXCEEDED, throwable, description); } return new TriRpcStatus(Code.UNKNOWN, throwable, description); } public static int triCodeToDubboCode(Code triCode) { int code; switch (triCode) { case DEADLINE_EXCEEDED: code = TIMEOUT_EXCEPTION; break; case PERMISSION_DENIED: code = FORBIDDEN_EXCEPTION; break; case UNAVAILABLE: code = NETWORK_EXCEPTION; break; case UNIMPLEMENTED: code = METHOD_NOT_FOUND; break; default: code = UNKNOWN_EXCEPTION; } return code; } public static Code dubboCodeToTriCode(int rpcExceptionCode) { Code code; switch (rpcExceptionCode) { case TIMEOUT_EXCEPTION: case TIMEOUT_TERMINATE: code = Code.DEADLINE_EXCEEDED; break; case FORBIDDEN_EXCEPTION: code = Code.PERMISSION_DENIED; break; case LIMIT_EXCEEDED_EXCEPTION: case NETWORK_EXCEPTION: code = Code.UNAVAILABLE; break; case METHOD_NOT_FOUND: code = Code.NOT_FOUND; break; case SERIALIZATION_EXCEPTION: code = Code.INTERNAL; break; default: code = Code.UNKNOWN; break; } return code; } public static String limitSizeTo1KB(String desc) { if (desc.length() < 1024) { return desc; } else { return desc.substring(0, 1024); } } public static String decodeMessage(String raw) { if (StringUtils.isEmpty(raw)) { return ""; } return QueryStringDecoder.decodeComponent(raw); } public static String encodeMessage(String raw) { if (StringUtils.isEmpty(raw)) { return ""; } return encodeComponent(raw); } private static String encodeComponent(String raw) { QueryStringEncoder encoder = new QueryStringEncoder(""); encoder.addParam("", raw); // ?= return encoder.toString().substring(2); } public static Code httpStatusToGrpcCode(int httpStatusCode) { if (httpStatusCode >= 100 && httpStatusCode < 200) { return Code.INTERNAL; } if (httpStatusCode == HttpResponseStatus.BAD_REQUEST.code() || httpStatusCode == HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.code()) { return Code.INTERNAL; } else if (httpStatusCode == HttpResponseStatus.UNAUTHORIZED.code()) { return Code.UNAUTHENTICATED; } else if (httpStatusCode == HttpResponseStatus.FORBIDDEN.code()) { return Code.PERMISSION_DENIED; } else if (httpStatusCode == HttpResponseStatus.NOT_FOUND.code()) { return Code.UNIMPLEMENTED; } else if (httpStatusCode == HttpResponseStatus.BAD_GATEWAY.code() || httpStatusCode == HttpResponseStatus.TOO_MANY_REQUESTS.code() || httpStatusCode == HttpResponseStatus.SERVICE_UNAVAILABLE.code() || httpStatusCode == HttpResponseStatus.GATEWAY_TIMEOUT.code()) { return Code.UNAVAILABLE; } else { return Code.UNKNOWN; } } public boolean isOk() { return Code.isOk(code.code); } public TriRpcStatus withCause(Throwable cause) { return new TriRpcStatus(this.code, cause, this.description); } public TriRpcStatus withDescription(String description) { return new TriRpcStatus(code, cause, description); } public TriRpcStatus appendDescription(String description) { if (this.description == null) { return withDescription(description); } else { String newDescription = this.description + "\n" + description; return withDescription(newDescription); } } public StatusRpcException asException() { return new StatusRpcException(this); } public String toEncodedMessage() { String output = limitSizeTo1KB(toMessage()); return encodeComponent(output); } public String toMessageWithoutCause() { if (description != null) { return String.format("%s : %s", code, description); } else { return code.toString(); } } public String toMessage() { String msg = ""; if (cause == null) { msg += description; } else { String placeHolder = description == null ? "" : description; msg += StringUtils.toString(placeHolder, cause); } return msg; } public enum Code { OK(0), CANCELLED(1), UNKNOWN(2), INVALID_ARGUMENT(3), DEADLINE_EXCEEDED(4), NOT_FOUND(5), ALREADY_EXISTS(6), PERMISSION_DENIED(7), RESOURCE_EXHAUSTED(8), FAILED_PRECONDITION(9), ABORTED(10), OUT_OF_RANGE(11), UNIMPLEMENTED(12), INTERNAL(13), UNAVAILABLE(14), DATA_LOSS(15), /** * The request does not have valid authentication credentials for the operation. */ UNAUTHENTICATED(16); public final int code; Code(int code) { this.code = code; } public static boolean isOk(Integer status) { return status == OK.code; } public static Code fromCode(int code) { for (Code value : Code.values()) { if (value.code == code) { return value; } } throw new IllegalStateException("Can not find status for code: " + code); } } }
6,095
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.config.Configuration; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.remoting.api.connection.AbstractConnectionClient; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.CancellationContext; import org.apache.dubbo.rpc.FutureContext; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.InvokeMode; 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.RpcInvocation; import org.apache.dubbo.rpc.TriRpcStatus; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.PackableMethod; import org.apache.dubbo.rpc.model.PackableMethodFactory; import org.apache.dubbo.rpc.model.ScopeModelUtil; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.protocol.tri.call.ClientCall; import org.apache.dubbo.rpc.protocol.tri.call.ObserverToClientCallListenerAdapter; import org.apache.dubbo.rpc.protocol.tri.call.TripleClientCall; import org.apache.dubbo.rpc.protocol.tri.call.UnaryClientCallListener; import org.apache.dubbo.rpc.protocol.tri.compressor.Compressor; import org.apache.dubbo.rpc.protocol.tri.compressor.Identity; import org.apache.dubbo.rpc.protocol.tri.observer.ClientCallToObserverAdapter; import org.apache.dubbo.rpc.protocol.tri.transport.TripleWriteQueue; import org.apache.dubbo.rpc.service.ServiceDescriptorInternalCache; import org.apache.dubbo.rpc.support.RpcUtils; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.ReentrantLock; import io.netty.util.AsciiString; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PACKABLE_METHOD_FACTORY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.Constants.COMPRESSOR_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.apache.dubbo.rpc.model.MethodDescriptor.RpcType.UNARY; /** * TripleInvoker */ public class TripleInvoker<T> extends AbstractInvoker<T> { private static final ErrorTypeAwareLogger LOGGER = LoggerFactory.getErrorTypeAwareLogger(TripleInvoker.class); private final AbstractConnectionClient connectionClient; private final ReentrantLock destroyLock = new ReentrantLock(); private final Set<Invoker<?>> invokers; private final ExecutorService streamExecutor; private final String acceptEncodings; private final TripleWriteQueue writeQueue = new TripleWriteQueue(256); private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); private final PackableMethodFactory packableMethodFactory; private final Map<MethodDescriptor, PackableMethod> packableMethodCache = new ConcurrentHashMap<>(); public TripleInvoker( Class<T> serviceType, URL url, String acceptEncodings, AbstractConnectionClient connectionClient, Set<Invoker<?>> invokers, ExecutorService streamExecutor) { super(serviceType, url, new String[] {INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); this.invokers = invokers; this.connectionClient = connectionClient; this.acceptEncodings = acceptEncodings; this.streamExecutor = streamExecutor; this.packableMethodFactory = url.getOrDefaultFrameworkModel() .getExtensionLoader(PackableMethodFactory.class) .getExtension(ConfigurationUtils.getGlobalConfiguration(url.getApplicationModel()) .getString(DUBBO_PACKABLE_METHOD_FACTORY, DEFAULT_KEY)); } private static AsciiString getSchemeFromUrl(URL url) { boolean ssl = url.getParameter(CommonConstants.SSL_ENABLED_KEY, false); return ssl ? TripleConstant.HTTPS_SCHEME : TripleConstant.HTTP_SCHEME; } private static Compressor getCompressorFromEnv() { Configuration configuration = ConfigurationUtils.getEnvConfiguration(ApplicationModel.defaultModel()); String compressorKey = configuration.getString(COMPRESSOR_KEY, Identity.MESSAGE_ENCODING); return Compressor.getCompressor( ScopeModelUtil.getFrameworkModel(ApplicationModel.defaultModel()), compressorKey); } @Override protected Result doInvoke(final Invocation invocation) { if (!connectionClient.isConnected()) { CompletableFuture<AppResponse> future = new CompletableFuture<>(); RpcException exception = TriRpcStatus.UNAVAILABLE .withDescription(String.format("upstream %s is unavailable", getUrl().getAddress())) .asException(); future.completeExceptionally(exception); return new AsyncRpcResult(future, invocation); } ConsumerModel consumerModel = (ConsumerModel) (invocation.getServiceModel() != null ? invocation.getServiceModel() : getUrl().getServiceModel()); ServiceDescriptor serviceDescriptor = consumerModel.getServiceModel(); final MethodDescriptor methodDescriptor; boolean genericCall = RpcUtils.isGenericCall( ReflectUtils.getDesc(invocation.getParameterTypes()), invocation.getMethodName()); if (!genericCall) { methodDescriptor = serviceDescriptor.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); } else { methodDescriptor = ServiceDescriptorInternalCache.genericService() .getMethod(invocation.getMethodName(), invocation.getParameterTypes()); } ExecutorService callbackExecutor = isSync(methodDescriptor, invocation) ? new ThreadlessExecutor() : streamExecutor; ClientCall call = new TripleClientCall( connectionClient, callbackExecutor, getUrl().getOrDefaultFrameworkModel(), writeQueue); AsyncRpcResult result; try { switch (methodDescriptor.getRpcType()) { case UNARY: result = invokeUnary(methodDescriptor, invocation, call, callbackExecutor); break; case SERVER_STREAM: result = invokeServerStream(methodDescriptor, invocation, call); break; case CLIENT_STREAM: case BI_STREAM: result = invokeBiOrClientStream(methodDescriptor, invocation, call); break; default: throw new IllegalStateException("Can not reach here"); } return result; } catch (Throwable t) { final TriRpcStatus status = TriRpcStatus.INTERNAL.withCause(t).withDescription("Call aborted cause client exception"); RpcException e = status.asException(); try { call.cancelByLocal(e); } catch (Throwable t1) { LOGGER.error(PROTOCOL_FAILED_REQUEST, "", "", "Cancel triple request failed", t1); } CompletableFuture<AppResponse> future = new CompletableFuture<>(); future.completeExceptionally(e); return new AsyncRpcResult(future, invocation); } } private static boolean isSync(MethodDescriptor methodDescriptor, Invocation invocation) { if (!(invocation instanceof RpcInvocation)) { return false; } RpcInvocation rpcInvocation = (RpcInvocation) invocation; MethodDescriptor.RpcType rpcType = methodDescriptor.getRpcType(); return UNARY.equals(rpcType) && InvokeMode.SYNC.equals(rpcInvocation.getInvokeMode()); } AsyncRpcResult invokeServerStream(MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call) { RequestMetadata request = createRequest(methodDescriptor, invocation, null); StreamObserver<Object> responseObserver = (StreamObserver<Object>) invocation.getArguments()[1]; final StreamObserver<Object> requestObserver = streamCall(call, request, responseObserver); requestObserver.onNext(invocation.getArguments()[0]); requestObserver.onCompleted(); return new AsyncRpcResult(CompletableFuture.completedFuture(new AppResponse()), invocation); } AsyncRpcResult invokeBiOrClientStream(MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call) { final AsyncRpcResult result; RequestMetadata request = createRequest(methodDescriptor, invocation, null); StreamObserver<Object> responseObserver = (StreamObserver<Object>) invocation.getArguments()[0]; final StreamObserver<Object> requestObserver = streamCall(call, request, responseObserver); result = new AsyncRpcResult(CompletableFuture.completedFuture(new AppResponse(requestObserver)), invocation); return result; } StreamObserver<Object> streamCall( ClientCall call, RequestMetadata metadata, StreamObserver<Object> responseObserver) { ObserverToClientCallListenerAdapter listener = new ObserverToClientCallListenerAdapter(responseObserver); StreamObserver<Object> streamObserver = call.start(metadata, listener); if (responseObserver instanceof CancelableStreamObserver) { final CancellationContext context = new CancellationContext(); CancelableStreamObserver<Object> cancelableStreamObserver = (CancelableStreamObserver<Object>) responseObserver; cancelableStreamObserver.setCancellationContext(context); context.addListener(context1 -> call.cancelByLocal(new IllegalStateException("Canceled by app"))); listener.setOnStartConsumer(dummy -> cancelableStreamObserver.startRequest()); cancelableStreamObserver.beforeStart((ClientCallToObserverAdapter<Object>) streamObserver); } return streamObserver; } AsyncRpcResult invokeUnary( MethodDescriptor methodDescriptor, Invocation invocation, ClientCall call, ExecutorService callbackExecutor) { int timeout = RpcUtils.calculateTimeout(getUrl(), invocation, RpcUtils.getMethodName(invocation), 3000); if (timeout <= 0) { return AsyncRpcResult.newDefaultAsyncResult( new RpcException( RpcException.TIMEOUT_TERMINATE, "No time left for making the following call: " + invocation.getServiceName() + "." + RpcUtils.getMethodName(invocation) + ", terminate directly."), invocation); } invocation.setAttachment(TIMEOUT_KEY, String.valueOf(timeout)); final AsyncRpcResult result; DeadlineFuture future = DeadlineFuture.newFuture( getUrl().getPath(), methodDescriptor.getMethodName(), getUrl().getAddress(), timeout, callbackExecutor); RequestMetadata request = createRequest(methodDescriptor, invocation, timeout); final Object pureArgument; if (methodDescriptor instanceof StubMethodDescriptor) { pureArgument = invocation.getArguments()[0]; } else { if (methodDescriptor.isGeneric()) { Object[] args = new Object[3]; args[0] = RpcUtils.getMethodName(invocation); args[1] = Arrays.stream(RpcUtils.getParameterTypes(invocation)) .map(Class::getName) .toArray(String[]::new); args[2] = RpcUtils.getArguments(invocation); pureArgument = args; } else { pureArgument = invocation.getArguments(); } } result = new AsyncRpcResult(future, invocation); if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) { FutureContext.getContext().setCompatibleFuture(future); } result.setExecutor(callbackExecutor); ClientCall.Listener callListener = new UnaryClientCallListener(future); final StreamObserver<Object> requestObserver = call.start(request, callListener); requestObserver.onNext(pureArgument); requestObserver.onCompleted(); return result; } RequestMetadata createRequest(MethodDescriptor methodDescriptor, Invocation invocation, Integer timeout) { final String methodName = RpcUtils.getMethodName(invocation); Objects.requireNonNull( methodDescriptor, "MethodDescriptor not found for" + methodName + " params:" + Arrays.toString(invocation.getCompatibleParamSignatures())); final RequestMetadata meta = new RequestMetadata(); final URL url = getUrl(); if (methodDescriptor instanceof PackableMethod) { meta.packableMethod = (PackableMethod) methodDescriptor; } else { meta.packableMethod = packableMethodCache.computeIfAbsent( methodDescriptor, (md) -> packableMethodFactory.create(md, url, TripleConstant.CONTENT_PROTO)); } meta.convertNoLowerHeader = TripleProtocol.CONVERT_NO_LOWER_HEADER; meta.ignoreDefaultVersion = TripleProtocol.IGNORE_1_0_0_VERSION; meta.method = methodDescriptor; meta.scheme = getSchemeFromUrl(url); meta.compressor = getCompressorFromEnv(); meta.cancellationContext = RpcContext.getCancellationContext(); meta.address = url.getAddress(); meta.service = url.getPath(); meta.group = url.getGroup(); meta.version = url.getVersion(); meta.acceptEncoding = acceptEncodings; if (timeout != null) { meta.timeout = timeout + "m"; } String application = (String) invocation.getObjectAttachmentWithoutConvert(CommonConstants.APPLICATION_KEY); if (application == null) { application = (String) invocation.getObjectAttachmentWithoutConvert(CommonConstants.REMOTE_APPLICATION_KEY); } meta.application = application; meta.attachments = invocation.getObjectAttachments(); return meta; } @Override public boolean isAvailable() { if (!super.isAvailable()) { return false; } return connectionClient.isConnected(); } @Override public void destroy() { // in order to avoid closing a client multiple times, a counter is used in case of connection per jvm, every // time when client.close() is called, counter counts down once, and when counter reaches zero, client will be // closed. if (!super.isDestroyed()) { // double check to avoid dup close destroyLock.lock(); try { if (super.isDestroyed()) { return; } super.destroy(); if (invokers != null) { invokers.remove(this); } try { connectionClient.release(); } catch (Throwable t) { logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", t.getMessage(), t); } } finally { destroyLock.unlock(); } } } }
6,096
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/PbArrayPacker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.rpc.model.Pack; import com.google.protobuf.Message; public class PbArrayPacker implements Pack { private static final Pack PB_PACK = o -> ((Message) o).toByteArray(); private final boolean singleArgument; public PbArrayPacker(boolean singleArgument) { this.singleArgument = singleArgument; } @Override public byte[] pack(Object obj) throws Exception { if (!singleArgument) { obj = ((Object[]) obj)[0]; } return PB_PACK.pack(obj); } }
6,097
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TriplePingPongHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http2.DefaultHttp2PingFrame; import io.netty.handler.codec.http2.Http2PingFrame; import io.netty.handler.timeout.IdleStateEvent; public class TriplePingPongHandler extends ChannelDuplexHandler { private final long pingAckTimeout; private ScheduledFuture<?> pingAckTimeoutFuture; public TriplePingPongHandler(long pingAckTimeout) { this.pingAckTimeout = pingAckTimeout; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof Http2PingFrame) || pingAckTimeoutFuture == null) { super.channelRead(ctx, msg); return; } // cancel task when read anything, include http2 ping ack pingAckTimeoutFuture.cancel(true); pingAckTimeoutFuture = null; } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (!(evt instanceof IdleStateEvent)) { ctx.fireUserEventTriggered(evt); return; } ctx.writeAndFlush(new DefaultHttp2PingFrame(0)); if (pingAckTimeoutFuture == null) { pingAckTimeoutFuture = ctx.executor().schedule(new CloseChannelTask(ctx), pingAckTimeout, TimeUnit.MILLISECONDS); } // not null means last ping ack not received } private static class CloseChannelTask implements Runnable { private final ChannelHandlerContext ctx; public CloseChannelTask(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void run() { ctx.close(); } } }
6,098
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleHeaderEnum.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.protocol.tri; import org.apache.dubbo.common.constants.CommonConstants; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import io.netty.handler.codec.http2.Http2Headers; public enum TripleHeaderEnum { AUTHORITY_KEY(":authority"), PATH_KEY(":path"), HTTP_STATUS_KEY("http-status"), STATUS_KEY("grpc-status"), MESSAGE_KEY("grpc-message"), STATUS_DETAIL_KEY("grpc-status-details-bin"), TIMEOUT("grpc-timeout"), CONTENT_TYPE_KEY("content-type"), CONTENT_PROTO("application/grpc+proto"), APPLICATION_GRPC("application/grpc"), GRPC_ENCODING("grpc-encoding"), GRPC_ACCEPT_ENCODING("grpc-accept-encoding"), CONSUMER_APP_NAME_KEY("tri-consumer-appname"), SERVICE_VERSION("tri-service-version"), SERVICE_GROUP("tri-service-group"), TRI_HEADER_CONVERT("tri-header-convert"), TRI_EXCEPTION_CODE("tri-exception-code"), ; static final Map<String, TripleHeaderEnum> enumMap = new HashMap<>(); static final Set<String> excludeAttachmentsSet = new HashSet<>(); static { for (TripleHeaderEnum item : TripleHeaderEnum.values()) { enumMap.put(item.getHeader(), item); } excludeAttachmentsSet.add(CommonConstants.GROUP_KEY); excludeAttachmentsSet.add(CommonConstants.INTERFACE_KEY); excludeAttachmentsSet.add(CommonConstants.PATH_KEY); excludeAttachmentsSet.add(CommonConstants.REMOTE_APPLICATION_KEY); excludeAttachmentsSet.add(CommonConstants.APPLICATION_KEY); excludeAttachmentsSet.add(TripleConstant.SERIALIZATION_KEY); excludeAttachmentsSet.add(TripleConstant.TE_KEY); for (Http2Headers.PseudoHeaderName value : Http2Headers.PseudoHeaderName.values()) { excludeAttachmentsSet.add(value.value().toString()); } } private final String header; TripleHeaderEnum(String header) { this.header = header; } public static boolean containsExcludeAttachments(String key) { return excludeAttachmentsSet.contains(key) || enumMap.containsKey(key); } public String getHeader() { return header; } }
6,099