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-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/ParamParseException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception; public class ParamParseException extends RestException { public ParamParseException(String message) { super(message); } }
5,800
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/CodeStyleNotSupportException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception; /** * only support spring mvc & jaxrs annotation */ public class CodeStyleNotSupportException extends RestException { public CodeStyleNotSupportException(String message) { super(message); } }
5,801
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/UnSupportContentTypeException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception; import org.apache.dubbo.metadata.rest.media.MediaType; public class UnSupportContentTypeException extends MediaTypeUnSupportException { public UnSupportContentTypeException(String message) { super("Current Support content type: " + MediaType.getAllContentType() + "; Do not support content type" + message); } }
5,802
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/PathNoFoundException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception; /** * response code : 404 path no found exception */ public class PathNoFoundException extends RestException { public PathNoFoundException(String message) { super(message); } }
5,803
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception.mapper; public interface ExceptionHandler<E extends Throwable> { Object result(E exception); default int status() { return 200; } }
5,804
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionHandlerResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception.mapper; public class ExceptionHandlerResult { private int status; private Object entity; public ExceptionHandlerResult() {} public ExceptionHandlerResult setStatus(int status) { this.status = status; return this; } public ExceptionHandlerResult setEntity(Object entity) { this.entity = entity; return this; } public static ExceptionHandlerResult build() { return new ExceptionHandlerResult(); } public int getStatus() { return status; } public Object getEntity() { return entity; } @Override public String toString() { return "ExceptionHandlerResult{" + "status=" + status + ", entity=" + entity + '}'; } }
5,805
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/RestEasyExceptionMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception.mapper; import org.apache.dubbo.rpc.protocol.rest.util.ReflectUtils; import javax.ws.rs.core.Response; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * for rest easy exception mapper extension */ public class RestEasyExceptionMapper extends ExceptionMapper { private final Map<Class<?>, javax.ws.rs.ext.ExceptionMapper> exceptionMappers = new ConcurrentHashMap<>(); protected List<Method> getExceptionHandlerMethods(Class<?> exceptionHandler) { if (!javax.ws.rs.ext.ExceptionMapper.class.isAssignableFrom(exceptionHandler)) { return super.getExceptionHandlerMethods(exceptionHandler); } // resolve Java_Zulu_jdk/17.0.6-10/x64 param is not throwable List<Method> methods = ReflectUtils.getMethodByNameList(exceptionHandler, "toResponse"); return methods; } protected Map getExceptionHandlerMap(Object handler) { if (handler instanceof ExceptionHandler) { return super.getExceptionHandlerMap(handler); } return exceptionMappers; } public ExceptionHandlerResult exceptionToResult(Object throwable) { Object exceptionMapper = getExceptionHandler(throwable.getClass()); if (exceptionMapper == null || exceptionMapper instanceof ExceptionHandler) { return super.exceptionToResult(throwable); } Response response = ((javax.ws.rs.ext.ExceptionMapper) exceptionMapper).toResponse((Throwable) throwable); return ExceptionHandlerResult.build().setStatus(response.getStatus()).setEntity(response.getEntity()); } }
5,806
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/exception/mapper/ExceptionMapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.exception.mapper; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.protocol.rest.util.ReflectUtils; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class ExceptionMapper { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Map<Class<?>, ExceptionHandler> exceptionHandlerMap = new ConcurrentHashMap<>(); private final Map allExceptionHandlers = new ConcurrentHashMap<>(); public ExceptionHandlerResult exceptionToResult(Object throwable) { ExceptionHandler exceptionHandler = (ExceptionHandler) getExceptionHandler(throwable.getClass()); Object result = exceptionHandler.result((Throwable) throwable); return ExceptionHandlerResult.build().setEntity(result).setStatus(exceptionHandler.status()); } public Object getExceptionHandler(Class causeClass) { return getExceptionHandler(allExceptionHandlers, causeClass); } public Object getExceptionHandler(Map exceptionHandlerMap, Class causeClass) { Object exceptionHandler = null; while (causeClass != null) { exceptionHandler = exceptionHandlerMap.get(causeClass); if (exceptionHandler != null) { break; } // When the exception handling class cannot be obtained, it should recursively search the base class causeClass = causeClass.getSuperclass(); } return exceptionHandler; } public boolean hasExceptionMapper(Object throwable) { if (throwable == null) { return false; } return allExceptionHandlers.containsKey(throwable.getClass()); } public void registerMapper(Class<?> exceptionHandler) { try { List<Method> methods = getExceptionHandlerMethods(exceptionHandler); if (methods == null || methods.isEmpty()) { return; } Set<Class<?>> exceptions = new HashSet<>(); for (Method method : methods) { Class<?> parameterType = method.getParameterTypes()[0]; // param type isAssignableFrom throwable if (!Throwable.class.isAssignableFrom(parameterType)) { continue; } exceptions.add(parameterType); } ArrayList<Class<?>> classes = new ArrayList<>(exceptions); // if size==1 so ,exception handler for Throwable if (classes.size() != 1) { // else remove throwable exceptions.remove(Throwable.class); } List<Constructor<?>> constructors = ReflectUtils.getConstructList(exceptionHandler); if (constructors.isEmpty()) { throw new RuntimeException( "dubbo rest exception mapper register mapper need exception handler exist no construct declare, current class is: " + exceptionHandler); } // if exceptionHandler is inner class , no arg construct don`t appear , so newInstance don`t use // noArgConstruct Object handler = constructors .get(0) .newInstance(new Object[constructors.get(0).getParameterCount()]); putExtensionToMap(exceptions, handler); } catch (Exception e) { throw new RuntimeException("dubbo rest protocol exception mapper register error ", e); } } protected void putExtensionToMap(Set<Class<?>> exceptions, Object handler) { Map exceptionHandlerMaps = getExceptionHandlerMap(handler); for (Class<?> exception : exceptions) { // put to instance map exceptionHandlerMaps.put(exception, handler); // put to all map allExceptionHandlers.put(exception, handler); } } protected Map getExceptionHandlerMap(Object handler) { return exceptionHandlerMap; } protected List<Method> getExceptionHandlerMethods(Class<?> exceptionHandler) { if (!ExceptionHandler.class.isAssignableFrom(exceptionHandler)) { return null; } // resolve Java_Zulu_jdk/17.0.6-10/x64 param is not throwable List<Method> methods = ReflectUtils.getMethodByNameList(exceptionHandler, "result"); return methods; } public void registerMapper(String exceptionMapper) { try { registerMapper(ReflectUtils.findClass(exceptionMapper)); } catch (Exception e) { logger.warn( "", e.getMessage(), "", "dubbo rest protocol exception mapper register error ,and current exception mapper is :" + exceptionMapper); } } public void unRegisterMapper(Class<?> exception) { exceptionHandlerMap.remove(exception); } public static boolean isSupport(Class<?> exceptionHandler) { try { return ExceptionHandler.class.isAssignableFrom(exceptionHandler) || ReflectUtils.findClassTryException("javax.ws.rs.ext.ExceptionMapper") .isAssignableFrom(exceptionHandler); } catch (Exception e) { return false; } } }
5,807
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/MessageCodecResultPair.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.pair; import org.apache.dubbo.metadata.rest.media.MediaType; /** * for http message codec result */ public class MessageCodecResultPair { /** * has coded */ boolean coded; /** * codec type */ MediaType mediaType; public MessageCodecResultPair(boolean coded, MediaType mediaType) { this.coded = coded; this.mediaType = mediaType; } public boolean isCoded() { return coded; } public MediaType getMediaType() { return mediaType; } public static MessageCodecResultPair pair(boolean coded, MediaType mediaType) { return new MessageCodecResultPair(coded, mediaType); } }
5,808
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-rest/src/main/java/org/apache/dubbo/rpc/protocol/rest/pair/InvokerAndRestMethodMetadataPair.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rest.pair; import org.apache.dubbo.metadata.rest.RestMethodMetadata; import org.apache.dubbo.rpc.Invoker; import java.lang.reflect.Method; import java.util.Arrays; /** * for invoker & restMethodMetadata pair */ public class InvokerAndRestMethodMetadataPair { Invoker invoker; RestMethodMetadata restMethodMetadata; public InvokerAndRestMethodMetadataPair(Invoker invoker, RestMethodMetadata restMethodMetadata) { this.invoker = invoker; this.restMethodMetadata = restMethodMetadata; } public Invoker getInvoker() { return invoker; } public RestMethodMetadata getRestMethodMetadata() { return restMethodMetadata; } public static InvokerAndRestMethodMetadataPair pair(Invoker invoker, RestMethodMetadata restMethodMetadata) { return new InvokerAndRestMethodMetadataPair(invoker, restMethodMetadata); } /** * same interface & same method desc * * @param beforeMetadata * @return */ public boolean compareServiceMethod(InvokerAndRestMethodMetadataPair beforeMetadata) { Class currentServiceInterface = this.invoker.getInterface(); Class<?> beforeServiceInterface = beforeMetadata.getInvoker().getInterface(); if (!currentServiceInterface.equals(beforeServiceInterface)) { return false; } Method beforeServiceMethod = beforeMetadata.getRestMethodMetadata().getReflectMethod(); Method currentReflectMethod = this.restMethodMetadata.getReflectMethod(); if (beforeServiceMethod.getName().equals(currentReflectMethod.getName()) // method name // method param types && Arrays.toString(beforeServiceMethod.getParameterTypes()) .equals(Arrays.toString(currentReflectMethod.getParameterTypes()))) { return true; } return false; } }
5,809
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/MultiThreadTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class MultiThreadTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterEach public void after() { ProtocolUtils.closeAll(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .destroy(); } @Test void testDubboMultiThreadInvoke() throws Exception { ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService("TestService", DemoService.class); int port = NetUtils.getAvailablePort(); Exporter<?> rpcExporter = protocol.export(proxy.getInvoker( new DemoServiceImpl(), DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/TestService"))); final AtomicInteger counter = new AtomicInteger(); final DemoService service = proxy.getProxy( protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/TestService"))); Assertions.assertEquals(service.getSize(new String[] {"123", "456", "789"}), 3); final StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1024 * 64 + 32; i++) sb.append('A'); Assertions.assertEquals(sb.toString(), service.echo(sb.toString())); ExecutorService exec = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { final int fi = i; exec.execute(new Runnable() { public void run() { for (int i = 0; i < 30; i++) { System.out.println(fi + ":" + counter.getAndIncrement()); Assertions.assertEquals(service.echo(sb.toString()), sb.toString()); } } }); } exec.shutdown(); exec.awaitTermination(10, TimeUnit.SECONDS); rpcExporter.unexport(); } }
5,810
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvokerAvailableTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import java.lang.reflect.Field; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; /** * Check available status for dubboInvoker */ class DubboInvokerAvailableTest { private static DubboProtocol protocol; private static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @BeforeAll public static void setUpBeforeClass() {} @BeforeEach public void setUp() throws Exception { protocol = new DubboProtocol(FrameworkModel.defaultModel()); } @AfterAll public static void tearDownAfterClass() { ProtocolUtils.closeAll(); } @Test void test_Normal_available() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); invoker.destroy(); Assertions.assertFalse(invoker.isAvailable()); } @Test void test_Normal_ChannelReadOnly() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); getClients(invoker)[0].setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertFalse(invoker.isAvailable()); // reset status since connection is shared among invokers getClients(invoker)[0].removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); } @Disabled @Test void test_normal_channel_close_wait_gracefully() { int testPort = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + testPort + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?scope=true&lazy=false"); Exporter<IDemoService> exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Exporter<IDemoService> exporter0 = ProtocolUtils.export(new DemoServiceImpl0(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); long start = System.currentTimeMillis(); try { System.setProperty(SHUTDOWN_WAIT_KEY, "2000"); protocol.destroy(); } finally { System.getProperties().remove(SHUTDOWN_WAIT_KEY); } long waitTime = System.currentTimeMillis() - start; Assertions.assertTrue(waitTime >= 2000); Assertions.assertFalse(invoker.isAvailable()); } @Test void test_NoInvokers() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?connections=1"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); DubboInvoker<?> invoker = (DubboInvoker<?>) protocol.protocolBindingRefer(IDemoService.class, url); ExchangeClient[] clients = getClients(invoker); clients[0].close(); Assertions.assertFalse(invoker.isAvailable()); } @Test void test_Lazy_ChannelReadOnly() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Invoker<?> invoker = protocol.refer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); ExchangeClient exchangeClient = getClients((DubboInvoker<?>) invoker)[0]; Assertions.assertFalse(exchangeClient.isClosed()); exchangeClient.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); // invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); Assertions.assertFalse(invoker.isAvailable()); exchangeClient.removeAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY); Assertions.assertTrue(invoker.isAvailable()); exchangeClient.setAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY, Boolean.TRUE); Assertions.assertFalse(invoker.isAvailable()); } /** * The test prefer serialization * * @throws Exception Exception */ @Test public void testPreferSerialization() throws Exception { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf( "dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?lazy=true&connections=1&timeout=10000&serialization=fastjson&prefer_serialization=fastjson2,hessian2"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); Invoker<?> invoker = protocol.refer(IDemoService.class, url); Assertions.assertTrue(invoker.isAvailable()); ExchangeClient exchangeClient = getClients((DubboInvoker<?>) invoker)[0]; Assertions.assertFalse(exchangeClient.isClosed()); // invoke method --> init client IDemoService service = (IDemoService) proxy.getProxy(invoker); Assertions.assertEquals("ok", service.get()); } private ExchangeClient[] getClients(DubboInvoker<?> invoker) throws Exception { Field field = DubboInvoker.class.getDeclaredField("clientsProvider"); field.setAccessible(true); ClientsProvider clientsProvider = (ClientsProvider) field.get(invoker); List<? extends ExchangeClient> clients = clientsProvider.getClients(); Assertions.assertEquals(1, clients.size()); return clients.toArray(new ExchangeClient[0]); } public class DemoServiceImpl implements IDemoService { public String get() { return "ok"; } } public class DemoServiceImpl0 implements IDemoService { public String get() { return "ok"; } } }
5,811
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.DubboCodec.DUBBO_VERSION; /** * {@link DecodeableRpcInvocation} */ class DecodeableRpcInvocationTest { @Test void test() throws Exception { // Simulate the data called by the client(The called data is stored in invocation and written to the buffer) URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); RpcInvocation inv = new RpcInvocation( null, "sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new String[] {"yug"}); inv.setObjectAttachment(PATH_KEY, url.getPath()); inv.setObjectAttachment(VERSION_KEY, url.getVersion()); inv.setObjectAttachment(DUBBO_VERSION_KEY, DUBBO_VERSION); inv.setObjectAttachment("k1", "v1"); inv.setObjectAttachment("k2", "v2"); inv.setTargetServiceUniqueName(url.getServiceKey()); // Write the data of inv to the buffer Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); ChannelBuffer buffer = writeBuffer(url, inv, proto); FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel .getDefaultModule() .getServiceRepository() .registerService(DemoService.class.getName(), DemoService.class); frameworkModel .getBeanFactory() .getBean(PermittedSerializationKeeper.class) .registerService(url); // Simulate the server to decode Channel channel = new MockChannel(); Request request = new Request(1); ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); DecodeableRpcInvocation decodeableRpcInvocation = new DecodeableRpcInvocation(frameworkModel, channel, request, is, proto); decodeableRpcInvocation.decode(); // Verify that the decodeableRpcInvocation data decoded by the server is consistent with the invocation data of // the client Assertions.assertEquals(request.getVersion(), DUBBO_VERSION); Assertions.assertEquals(decodeableRpcInvocation.getObjectAttachment(DUBBO_VERSION_KEY), DUBBO_VERSION); Assertions.assertEquals( decodeableRpcInvocation.getObjectAttachment(VERSION_KEY), inv.getObjectAttachment(VERSION_KEY)); Assertions.assertEquals( decodeableRpcInvocation.getObjectAttachment(PATH_KEY), inv.getObjectAttachment(PATH_KEY)); Assertions.assertEquals(decodeableRpcInvocation.getMethodName(), inv.getMethodName()); Assertions.assertEquals(decodeableRpcInvocation.getParameterTypesDesc(), inv.getParameterTypesDesc()); Assertions.assertArrayEquals(decodeableRpcInvocation.getParameterTypes(), inv.getParameterTypes()); Assertions.assertArrayEquals(decodeableRpcInvocation.getArguments(), inv.getArguments()); Assertions.assertTrue( CollectionUtils.mapEquals(decodeableRpcInvocation.getObjectAttachments(), inv.getObjectAttachments())); Assertions.assertEquals(decodeableRpcInvocation.getTargetServiceUniqueName(), inv.getTargetServiceUniqueName()); frameworkModel.destroy(); } private ChannelBuffer writeBuffer(URL url, RpcInvocation inv, Byte proto) throws IOException { Serialization serialization = CodecSupport.getSerializationById(proto); ChannelBuffer buffer = ChannelBuffers.buffer(1024); ChannelBufferOutputStream outputStream = new ChannelBufferOutputStream(buffer); ObjectOutput out = serialization.serialize(url, outputStream); out.writeUTF(inv.getAttachment(DUBBO_VERSION_KEY)); // dubbo version out.writeUTF(inv.getAttachment(PATH_KEY)); // path out.writeUTF(inv.getAttachment(VERSION_KEY)); // version out.writeUTF(inv.getMethodName()); // methodName out.writeUTF(inv.getParameterTypesDesc()); // parameterTypesDesc Object[] args = inv.getArguments(); if (args != null) { for (int i = 0; i < args.length; i++) { out.writeObject(args[i]); // args } } out.writeAttachments(inv.getObjectAttachments()); // attachments out.flushBuffer(); outputStream.close(); return buffer; } }
5,812
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/FutureFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.rpc.AppResponse; 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.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.protocol.dubbo.filter.FutureFilter; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * EventFilterTest.java * TODO rely on callback integration test for now */ class FutureFilterTest { private static RpcInvocation invocation; private ClusterFilter eventFilter = new FutureFilter(); @BeforeAll public static void setUp() { invocation = new RpcInvocation(); invocation.setMethodName("echo"); invocation.setParameterTypes(new Class<?>[] {Enum.class}); invocation.setArguments(new Object[] {"hello"}); } @Test void testSyncCallback() { @SuppressWarnings("unchecked") Invoker<DemoService> invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); given(invoker.getUrl()).willReturn(url); Result filterResult = eventFilter.invoke(invoker, invocation); assertEquals("High", filterResult.getValue()); } @Test void testSyncCallbackHasException() throws RpcException, Throwable { Assertions.assertThrows(RuntimeException.class, () -> { @SuppressWarnings("unchecked") Invoker<DemoService> invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setException(new RuntimeException()); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&onthrow.method=echo"); given(invoker.getUrl()).willReturn(url); eventFilter.invoke(invoker, invocation).recreate(); }); } }
5,813
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResultTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.serialize.support.DefaultSerializationSelector; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Result; 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.FrameworkModel; 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.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import java.io.IOException; import java.io.InputStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; import static org.apache.dubbo.rpc.RpcException.BIZ_EXCEPTION; import static org.apache.dubbo.rpc.protocol.dubbo.DubboCodec.RESPONSE_VALUE_WITH_ATTACHMENTS; import static org.apache.dubbo.rpc.protocol.dubbo.DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS; /** * {@link DecodeableRpcResult} */ class DecodeableRpcResultTest { private ModuleServiceRepository repository; @BeforeEach public void setUp() { repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); } @AfterEach public void tearDown() { FrameworkModel.destroyAll(); } @Test void test() throws Exception { // Mock a rpcInvocation, this rpcInvocation is usually generated by the client request, and stored in // Request#data Byte proto = CodecSupport.getIDByName(DefaultSerializationSelector.getDefaultRemotingSerialization()); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9103, DemoService.class.getName(), VERSION_KEY, "1.0.0"); ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ProviderModel providerModel = new ProviderModel(url.getServiceKey(), new DemoServiceImpl(), serviceDescriptor, null, null); RpcInvocation rpcInvocation = new RpcInvocation( providerModel, "echo", DemoService.class.getName(), "", new Class<?>[] {String.class}, new String[] { "yug" }); rpcInvocation.put(SERIALIZATION_ID_KEY, proto); // Mock a response result returned from the server and write to the buffer Channel channel = new MockChannel(); Response response = new Response(1); Result result = new AppResponse(); result.setValue("yug"); response.setResult(result); ChannelBuffer buffer = writeBuffer(url, response, proto, false); // The client reads and decode the buffer InputStream is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); DecodeableRpcResult decodeableRpcResult = new DecodeableRpcResult(channel, response, is, rpcInvocation, proto); decodeableRpcResult.decode(); // Verify RESPONSE_VALUE_WITH_ATTACHMENTS // Verify that the decodeableRpcResult decoded by the client is consistent with the response returned by the // server Assertions.assertEquals(decodeableRpcResult.getValue(), result.getValue()); Assertions.assertTrue( CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), result.getObjectAttachments())); // Verify RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS Response exResponse = new Response(2); Result exResult = new AppResponse(); exResult.setException(new RpcException(BIZ_EXCEPTION)); exResponse.setResult(exResult); buffer = writeBuffer(url, exResponse, proto, true); is = new ChannelBufferInputStream(buffer, buffer.readableBytes()); decodeableRpcResult = new DecodeableRpcResult(channel, response, is, rpcInvocation, proto); decodeableRpcResult.decode(); Assertions.assertEquals( ((RpcException) decodeableRpcResult.getException()).getCode(), ((RpcException) exResult.getException()).getCode()); Assertions.assertTrue( CollectionUtils.mapEquals(decodeableRpcResult.getObjectAttachments(), exResult.getObjectAttachments())); } private ChannelBuffer writeBuffer(URL url, Response response, Byte proto, boolean writeEx) throws IOException { Serialization serialization = CodecSupport.getSerializationById(proto); ChannelBuffer buffer = ChannelBuffers.buffer(1024 * 10); ChannelBufferOutputStream outputStream = new ChannelBufferOutputStream(buffer); ObjectOutput out = serialization.serialize(url, outputStream); Result result = (Result) response.getResult(); if (!writeEx) { out.writeByte(RESPONSE_VALUE_WITH_ATTACHMENTS); out.writeObject(result.getValue()); } else { out.writeByte(RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS); out.writeThrowable(result.getException()); } result.getObjectAttachments().put(DUBBO_VERSION_KEY, Version.getProtocolVersion()); result.getObjectAttachments().put("k1", "v1"); out.writeAttachments(result.getObjectAttachments()); out.flushBuffer(); outputStream.close(); return buffer; } }
5,814
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ArgumentCallbackTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; 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.protocol.dubbo.support.ProtocolUtils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.junit.jupiter.api.AfterEach; 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 static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; class ArgumentCallbackTest { protected Exporter<IDemoService> exporter = null; protected Exporter<IHelloService> hello_exporter = null; protected Invoker<IDemoService> reference = null; protected URL serviceURL = null; protected URL consumerUrl = null; // ============================A gorgeous line of segmentation================================================ IDemoService demoProxy = null; @AfterEach public void tearDown() { destroyService(); ProtocolUtils.closeAll(); } public void exportService() { // export one service first, to test connection sharing serviceURL = serviceURL.addParameter("connections", 1); URL hellourl = serviceURL.setPath(IHelloService.class.getName()); ModuleServiceRepository serviceRepository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); serviceRepository.registerService(IDemoService.class); serviceRepository.registerService(IHelloService.class); hello_exporter = ProtocolUtils.export(new HelloServiceImpl(), IHelloService.class, hellourl); exporter = ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, serviceURL); } void referService() { ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(IDemoService.class); demoProxy = (IDemoService) ProtocolUtils.refer(IDemoService.class, consumerUrl); } @BeforeEach public void setUp() {} public void initOrResetUrl(int callbacks, int timeout) { int port = NetUtils.getAvailablePort(); consumerUrl = serviceURL = URL.valueOf( "dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=test" + "&xxx.0.callback=true" + "&xxx2.0.callback=true" + "&unxxx2.0.callback=false" + "&timeout=" + timeout + "&retries=0" + "&" + CALLBACK_INSTANCES_LIMIT_KEY + "=" + callbacks) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()) .setServiceModel(new ConsumerModel( IDemoService.class.getName(), null, null, ApplicationModel.defaultModel().getDefaultModule(), null, null, ClassUtils.getClassLoader(IDemoService.class))); // uncomment is unblock invoking // serviceURL = serviceURL.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); // consumerUrl = consumerUrl.addParameter("yyy."+Constants.ASYNC_KEY,String.valueOf(true)); } public void initOrResetService() { destroyService(); exportService(); referService(); } public void destroyService() { ApplicationModel.defaultModel().getApplicationServiceRepository().destroy(); demoProxy = null; try { if (exporter != null) exporter.unexport(); if (hello_exporter != null) hello_exporter.unexport(); if (reference != null) reference.destroy(); } catch (Exception e) { } } @Test void TestCallbackNormalWithBindPort() throws Exception { initOrResetUrl(1, 10000000); consumerUrl = serviceURL.addParameter(Constants.BIND_PORT_KEY, "7653"); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { System.out.println("Received callback: " + msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); System.out.println("Async..."); assertCallbackCount(10, 100, count); destroyService(); } @Test void TestCallbackNormal() throws Exception { initOrResetUrl(1, 10000000); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { System.out.println("Received callback: " + msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); System.out.println("Async..."); // Thread.sleep(10000000); assertCallbackCount(10, 100, count); destroyService(); } @Test void TestCallbackMultiInstans() throws Exception { initOrResetUrl(2, 3000); initOrResetService(); IDemoCallback callback = new IDemoCallback() { public String yyy(String msg) { System.out.println("callback1:" + msg); return "callback1 onChanged ," + msg; } }; IDemoCallback callback2 = new IDemoCallback() { public String yyy(String msg) { System.out.println("callback2:" + msg); return "callback2 onChanged ," + msg; } }; { demoProxy.xxx2(callback); Assertions.assertEquals(1, demoProxy.getCallbackCount()); Thread.sleep(500); demoProxy.unxxx2(callback); Assertions.assertEquals(0, demoProxy.getCallbackCount()); demoProxy.xxx2(callback2); Assertions.assertEquals(1, demoProxy.getCallbackCount()); Thread.sleep(500); demoProxy.unxxx2(callback2); Assertions.assertEquals(0, demoProxy.getCallbackCount()); demoProxy.xxx2(callback); Thread.sleep(500); Assertions.assertEquals(1, demoProxy.getCallbackCount()); demoProxy.unxxx2(callback); Assertions.assertEquals(0, demoProxy.getCallbackCount()); } { demoProxy.xxx2(callback); Assertions.assertEquals(1, demoProxy.getCallbackCount()); demoProxy.xxx2(callback); Assertions.assertEquals(1, demoProxy.getCallbackCount()); demoProxy.xxx2(callback2); Assertions.assertEquals(2, demoProxy.getCallbackCount()); } destroyService(); } @Test void TestCallbackConsumerLimit() { Assertions.assertThrows(RpcException.class, () -> { initOrResetUrl(1, 1000); // URL cannot be transferred automatically from the server side to the client side by using API, instead, // it needs manually specified. initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { System.out.println("Received callback: " + msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { System.out.println("Received callback: " + msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); destroyService(); }); } @Test void TestCallbackProviderLimit() { Assertions.assertThrows(RpcException.class, () -> { initOrResetUrl(1, 1000); // URL cannot be transferred automatically from the server side to the client side by using API, instead, // it needs manually specified. serviceURL = serviceURL.addParameter(CALLBACK_INSTANCES_LIMIT_KEY, 1 + ""); initOrResetService(); final AtomicInteger count = new AtomicInteger(0); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { System.out.println("Received callback: " + msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); demoProxy.xxx( new IDemoCallback() { public String yyy(String msg) { System.out.println("Received callback: " + msg); count.incrementAndGet(); return "ok"; } }, "other custom args", 10, 100); destroyService(); }); } private void assertCallbackCount(int runs, int sleep, AtomicInteger count) throws InterruptedException { int last = count.get(); for (int i = 0; i < runs; i++) { if (last > runs) break; Thread.sleep(sleep * 2); System.out.println(count.get() + " " + last); Assertions.assertTrue(count.get() > last); last = count.get(); } // has one sync callback Assertions.assertEquals(runs + 1, count.get()); } @Disabled("need start with separate process") @Test void startProvider() throws Exception { exportService(); synchronized (ArgumentCallbackTest.class) { ArgumentCallbackTest.class.wait(); } } interface IDemoCallback { String yyy(String msg); } interface IHelloService { String sayHello(); } interface IDemoService { String get(); int getCallbackCount(); void xxx(IDemoCallback callback, String arg1, int runs, int sleep); void xxx2(IDemoCallback callback); void unxxx2(IDemoCallback callback); } class HelloServiceImpl implements IHelloService { public String sayHello() { return "hello"; } } class DemoServiceImpl implements IDemoService { private List<IDemoCallback> callbacks = new ArrayList<IDemoCallback>(); private volatile Thread t = null; private volatile Lock lock = new ReentrantLock(); public String get() { return "ok"; } public void xxx(final IDemoCallback callback, String arg1, final int runs, final int sleep) { callback.yyy("Sync callback msg .This is callback data. arg1:" + arg1); Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < runs; i++) { String ret = callback.yyy("server invoke callback : arg:" + System.currentTimeMillis()); System.out.println("callback result is :" + ret); try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.setDaemon(true); t.start(); System.out.println("xxx invoke complete"); } public int getCallbackCount() { return callbacks.size(); } public void xxx2(IDemoCallback callback) { if (!callbacks.contains(callback)) { callbacks.add(callback); } startThread(); } private void startThread() { if (t == null || callbacks.size() == 0) { try { lock.lock(); t = new Thread(new Runnable() { public void run() { while (callbacks.size() > 0) { try { List<IDemoCallback> callbacksCopy = new ArrayList<IDemoCallback>(callbacks); for (IDemoCallback callback : callbacksCopy) { try { callback.yyy("this is callback msg,current time is :" + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); callbacks.remove(callback); } } Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.setDaemon(true); t.start(); } finally { lock.unlock(); } } } public void unxxx2(IDemoCallback callback) { if (!callbacks.contains(callback)) { throw new IllegalStateException("callback instance not found"); } callbacks.remove(callback); } } }
5,815
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/RpcFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.apache.dubbo.rpc.service.EchoService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RpcFilterTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterEach public void after() { ProtocolUtils.closeAll(); } @Test void testRpcFilter() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.support.DemoService?service.filter=echo"); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(DemoService.class); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(service, DemoService.class, url)); service = proxy.getProxy(protocol.refer(DemoService.class, url)); Assertions.assertEquals("123", service.echo("123")); // cast to EchoService EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, url)); Assertions.assertEquals(echo.$echo("test"), "test"); Assertions.assertEquals(echo.$echo("abcdefg"), "abcdefg"); Assertions.assertEquals(echo.$echo(1234), 1234); } }
5,816
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboLazyConnectTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; /** * dubbo protocol lazy connect test */ class DubboLazyConnectTest { @BeforeAll public static void setUpBeforeClass() {} @BeforeEach public void setUp() {} @AfterAll public static void tearDownAfterClass() { ProtocolUtils.closeAll(); } @Test void testSticky1() { Assertions.assertThrows(RpcException.class, () -> { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService"); ProtocolUtils.refer(IDemoService.class, url); }); } @Test void testSticky2() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); ProtocolUtils.refer(IDemoService.class, url); } @Test void testSticky3() { Assertions.assertThrows(IllegalStateException.class, () -> { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true"); IDemoService service = ProtocolUtils.refer(IDemoService.class, url); service.get(); }); } @Test void testSticky4() { int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.dubbo.IDemoService?" + LAZY_CONNECT_KEY + "=true&timeout=20000"); ProtocolUtils.export(new DemoServiceImpl(), IDemoService.class, url); IDemoService service = ProtocolUtils.refer(IDemoService.class, url); Assertions.assertEquals("ok", service.get()); } public class DemoServiceImpl implements IDemoService { public String get() { return "ok"; } } }
5,817
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; 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 org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.cluster.support.FailfastCluster; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized; import org.apache.dubbo.rpc.protocol.dubbo.support.ProtocolUtils; import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteService; import org.apache.dubbo.rpc.protocol.dubbo.support.RemoteServiceImpl; import org.apache.dubbo.rpc.protocol.dubbo.support.Type; import org.apache.dubbo.rpc.service.EchoService; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; /** * <code>ProxiesTest</code> */ class DubboProtocolTest { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @AfterAll public static void after() { ProtocolUtils.closeAll(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .unregisterService(DemoService.class); } @BeforeAll public static void setup() { ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(DemoService.class); } @Test void testDemoProtocol() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); assertEquals(service.getSize(new String[] {"", "", ""}), 3); } @Test void testDubboProtocol() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) .addParameter("timeout", 3000L))); assertEquals(service.enumlength(new Type[] {}), Type.Lower); assertEquals(service.getSize(null), -1); assertEquals(service.getSize(new String[] {"", "", ""}), 3); Map<String, String> map = new HashMap<String, String>(); map.put("aa", "bb"); Set<String> set = service.keys(map); assertEquals(set.size(), 1); assertEquals(set.iterator().next(), "aa"); service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty") .addParameter("timeout", 3000L))); // test netty client StringBuffer buf = new StringBuffer(); for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A'); System.out.println(service.stringLength(buf.toString())); // cast to EchoService EchoService echo = proxy.getProxy(protocol.refer( EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?client=netty") .addParameter("timeout", 3000L))); assertEquals(echo.$echo(buf.toString()), buf.toString()); assertEquals(echo.$echo("test"), "test"); assertEquals(echo.$echo("abcdefg"), "abcdefg"); assertEquals(echo.$echo(1234), 1234); } // @Test // public void testDubboProtocolWithMina() throws Exception { // DemoService service = new DemoServiceImpl(); // int port = NetUtils.getAvailablePort(); // protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" // + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + // DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", // 3000L))); // for (int i = 0; i < 10; i++) { // assertEquals(service.enumlength(new Type[]{}), Type.Lower); // assertEquals(service.getSize(null), -1); // assertEquals(service.getSize(new String[]{"", "", ""}), 3); // } // Map<String, String> map = new HashMap<String, String>(); // map.put("aa", "bb"); // for (int i = 0; i < 10; i++) { // Set<String> set = service.keys(map); // assertEquals(set.size(), 1); // assertEquals(set.iterator().next(), "aa"); // service.invoke("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); // } // // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + // DemoService.class.getName() + "?client=mina").addParameter("timeout", // 3000L))); // // test netty client // StringBuffer buf = new StringBuffer(); // for (int i = 0; i < 1024 * 32 + 32; i++) // buf.append('A'); // System.out.println(service.stringLength(buf.toString())); // // // cast to EchoService // EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:" + // port + "/" + DemoService.class.getName() + "?client=mina").addParameter("timeout", // 3000L))); // for (int i = 0; i < 10; i++) { // assertEquals(echo.$echo(buf.toString()), buf.toString()); // assertEquals(echo.$echo("test"), "test"); // assertEquals(echo.$echo("abcdefg"), "abcdefg"); // assertEquals(echo.$echo(1234), 1234); // } // } @Test void testDubboProtocolMultiService() throws Exception { // DemoService service = new DemoServiceImpl(); // protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + // DemoService.class.getName()))); // service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + // DemoService.class.getName()).addParameter("timeout", // 3000L))); RemoteService remote = new RemoteServiceImpl(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(RemoteService.class); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + RemoteService.class.getName()) .addParameter("timeout", 3000L); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(remote, RemoteService.class, url)); remote = proxy.getProxy(protocol.refer(RemoteService.class, url)); // service.sayHello("world"); // test netty client // assertEquals("world", service.echo("world")); assertEquals("hello world@" + RemoteServiceImpl.class.getName(), remote.sayHello("world")); // can't find target service addresses EchoService remoteEcho = (EchoService) remote; assertEquals(remoteEcho.$echo("ok"), "ok"); } @Test void testPerm() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) service.getSize(new String[] {"", "", ""}); System.out.println("take:" + (System.currentTimeMillis() - start)); } @Test @Disabled public void testNonSerializedParameter() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); try { service.nonSerializedParameter(new NonSerialized()); Assertions.fail(); } catch (RpcException e) { Assertions.assertTrue( e.getMessage() .contains( "org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } @Test @Disabled public void testReturnNonSerialized() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L))); try { service.returnNonSerialized(); Assertions.fail(); } catch (RpcException e) { Assertions.assertTrue( e.getMessage() .contains( "org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); } } @Test void testRemoteApplicationName() throws Exception { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); URL url = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange") .addParameter("timeout", 3000L) .addParameter("application", "consumer"); url = url.setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); protocol.export(proxy.getInvoker(service, DemoService.class, url)); Invoker<DemoService> invoker = protocol.refer(DemoService.class, url); Invocation invocation = new RpcInvocation( "getRemoteApplicationName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]); List<Invoker<DemoService>> invokers = Arrays.asList(invoker); Directory<DemoService> dic = Mockito.mock(Directory.class); Mockito.when(dic.list(invocation)).thenReturn(invokers); Mockito.when(dic.getUrl()).thenReturn(url); Mockito.when(dic.getConsumerUrl()).thenReturn(url); FailfastCluster cluster = new FailfastCluster(); Invoker<DemoService> clusterInvoker = cluster.join(dic, true); Result result = clusterInvoker.invoke(invocation); Thread.sleep(10); assertEquals(result.getValue(), "consumer"); } @Test void testPayloadOverException() { DemoService service = new DemoServiceImpl(); int port = NetUtils.getAvailablePort(); protocol.export(proxy.getInvoker( service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) .addParameter("payload", 10 * 1024))); service = proxy.getProxy(protocol.refer( DemoService.class, URL.valueOf("dubbo://127.0.0.1:" + port + "/" + DemoService.class.getName()) .addParameter("timeout", 6000L) .addParameter("payload", 160))); try { service.download(300); Assertions.fail(); } catch (Exception expected) { Assertions.assertTrue(expected.getMessage().contains("Data length too large")); } } }
5,818
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodecTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.rpc.Constants.INPUT_KEY; import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; class DubboCountCodecTest { @Test void test() throws Exception { DubboCountCodec dubboCountCodec = new DubboCountCodec(FrameworkModel.defaultModel()); ChannelBuffer buffer = ChannelBuffers.buffer(2048); Channel channel = new MockChannel(); Assertions.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT, dubboCountCodec.decode(channel, buffer)); List<DefaultFuture> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { Request request = new Request(i); futures.add(DefaultFuture.newFuture(channel, request, 1000, null)); RpcInvocation rpcInvocation = new RpcInvocation( null, "echo", DemoService.class.getName(), "", new Class<?>[] {String.class}, new String[] {"yug"}); request.setData(rpcInvocation); dubboCountCodec.encode(channel, buffer, request); } for (int i = 0; i < 10; i++) { Response response = new Response(i); AppResponse appResponse = new AppResponse(i); response.setResult(appResponse); dubboCountCodec.encode(channel, buffer, response); } MultiMessage multiMessage = (MultiMessage) dubboCountCodec.decode(channel, buffer); Assertions.assertEquals(20, multiMessage.size()); int requestCount = 0; int responseCount = 0; Iterator iterator = multiMessage.iterator(); while (iterator.hasNext()) { Object result = iterator.next(); if (result instanceof Request) { requestCount++; Object bytes = ((RpcInvocation) ((Request) result).getData()).getObjectAttachment(INPUT_KEY); Assertions.assertNotNull(bytes); } else if (result instanceof Response) { responseCount++; Object bytes = ((AppResponse) ((Response) result).getResult()).getObjectAttachment(OUTPUT_KEY); Assertions.assertNotNull(bytes); } } Assertions.assertEquals(requestCount, 10); Assertions.assertEquals(responseCount, 10); futures.forEach(DefaultFuture::cancel); } }
5,819
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/IDemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public interface IDemoService { String get(); }
5,820
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClientTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.DubboAppender; import org.apache.dubbo.common.utils.LogUtil; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.exchange.ExchangeClient; 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.protocol.dubbo.support.ProtocolUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WARNING_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; class ReferenceCountExchangeClientTest { public static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Exporter<?> demoExporter; Exporter<?> helloExporter; Invoker<IDemoService> demoServiceInvoker; Invoker<IHelloService> helloServiceInvoker; IDemoService demoService; IHelloService helloService; ExchangeClient demoClient; ExchangeClient helloClient; String errorMsg = "safe guard client , should not be called ,must have a bug"; @BeforeAll public static void setUpBeforeClass() throws Exception {} @AfterAll public static void tearDownAfterClass() { ProtocolUtils.closeAll(); } public static Invoker<?> referInvoker(Class<?> type, URL url) { return DubboProtocol.getDubboProtocol().refer(type, url); } public static <T> Exporter<T> export(T instance, Class<T> type, String url) { return export(instance, type, URL.valueOf(url)); } public static <T> Exporter<T> export(T instance, Class<T> type, URL url) { return ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(proxy.getInvoker(instance, type, url)); } @BeforeEach public void setUp() throws Exception {} /** * test connection sharing */ @Test void test_share_connect() { init(0, 1); Assertions.assertEquals(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertEquals(demoClient, helloClient); destroy(); } /** * test connection not sharing */ @Test void test_not_share_connect() { init(1, 1); Assertions.assertNotSame(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertNotSame(demoClient, helloClient); destroy(); } /** * test using multiple shared connections */ @Test void test_multi_share_connect() { // here a three shared connection is established between a consumer process and a provider process. final int shareConnectionNum = 3; init(0, shareConnectionNum); List<ReferenceCountExchangeClient> helloReferenceClientList = getReferenceClientList(helloServiceInvoker); Assertions.assertEquals(shareConnectionNum, helloReferenceClientList.size()); List<ReferenceCountExchangeClient> demoReferenceClientList = getReferenceClientList(demoServiceInvoker); Assertions.assertEquals(shareConnectionNum, demoReferenceClientList.size()); // because helloServiceInvoker and demoServiceInvoker use share connect, so client list must be equal Assertions.assertEquals(helloReferenceClientList, demoReferenceClientList); Assertions.assertEquals(demoClient.getLocalAddress(), helloClient.getLocalAddress()); Assertions.assertEquals(demoClient, helloClient); destroy(); } /** * test counter won't count down incorrectly when invoker is destroyed for multiple times */ @Test void test_multi_destroy() { init(0, 1); DubboAppender.doStart(); DubboAppender.clear(); demoServiceInvoker.destroy(); demoServiceInvoker.destroy(); Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(0, LogUtil.findMessage(errorMsg), "should not warning message"); LogUtil.checkNoError(); DubboAppender.doStop(); destroy(); } /** * Test against invocation still succeed even if counter has error */ @Test void test_counter_error() { init(0, 1); DubboAppender.doStart(); DubboAppender.clear(); // because the two interfaces are initialized, the ReferenceCountExchangeClient reference counter is 2 ReferenceCountExchangeClient client = getReferenceClient(helloServiceInvoker); // close once, counter counts down from 2 to 1, no warning occurs client.close(); Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(0, LogUtil.findMessage(errorMsg), "should not warning message"); // close twice, counter counts down from 1 to 0, no warning occurs client.close(); // wait close done. try { Thread.sleep(1000); } catch (InterruptedException e) { Assertions.fail(); } // client has been replaced with lazy client, close status is false because a new lazy client's exchange client // is null. Assertions.assertFalse(client.isClosed(), "client status close"); // invoker status is available because the default value of associated lazy client's initial state is true. Assertions.assertTrue(helloServiceInvoker.isAvailable(), "invoker status unavailable"); // due to the effect of LazyConnectExchangeClient, the client will be "revived" whenever there is a call. Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(1, LogUtil.findMessage(errorMsg), "should warning message"); // output one error every 5000 invocations. Assertions.assertEquals("hello", helloService.hello()); Assertions.assertEquals(1, LogUtil.findMessage(errorMsg), "should warning message"); DubboAppender.doStop(); /** * This is the third time to close the same client. Under normal circumstances, * a client value should be closed once (that is, the shutdown operation is irreversible). * After closing, the value of the reference counter of the client has become -1. * * But this is a bit special, because after the client is closed twice, there are several calls to helloService, * that is, the client inside the ReferenceCountExchangeClient is actually active, so the third shutdown here is still effective, * let the resurrection After the client is really closed. */ client.close(); // close status is false because the lazy client's exchange client is null again after close(). Assertions.assertFalse(client.isClosed(), "client status close"); // invoker status is available because the default value of associated lazy client's initial state is true. Assertions.assertTrue(helloServiceInvoker.isAvailable(), "invoker status unavailable"); // revive: initial the lazy client's exchange client again. Assertions.assertEquals("hello", helloService.hello()); destroy(); } @SuppressWarnings("unchecked") private void init(int connections, int shareConnections) { Assertions.assertTrue(connections >= 0); Assertions.assertTrue(shareConnections >= 1); int port = NetUtils.getAvailablePort(); String params = CONNECTIONS_KEY + "=" + connections + "&" + SHARE_CONNECTIONS_KEY + "=" + shareConnections + "&" + LAZY_REQUEST_WITH_WARNING_KEY + "=" + "true"; URL demoUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/demo?" + params); URL helloUrl = URL.valueOf("dubbo://127.0.0.1:" + port + "/hello?" + params); demoExporter = export(new DemoServiceImpl(), IDemoService.class, demoUrl); helloExporter = export(new HelloServiceImpl(), IHelloService.class, helloUrl); demoServiceInvoker = (Invoker<IDemoService>) referInvoker(IDemoService.class, demoUrl); demoService = proxy.getProxy(demoServiceInvoker); Assertions.assertEquals("demo", demoService.demo()); helloServiceInvoker = (Invoker<IHelloService>) referInvoker(IHelloService.class, helloUrl); helloService = proxy.getProxy(helloServiceInvoker); Assertions.assertEquals("hello", helloService.hello()); demoClient = getClient(demoServiceInvoker); helloClient = getClient(helloServiceInvoker); } private void destroy() { demoServiceInvoker.destroy(); helloServiceInvoker.destroy(); demoExporter.getInvoker().destroy(); helloExporter.getInvoker().destroy(); } private ExchangeClient getClient(Invoker<?> invoker) { if (invoker.getUrl().getParameter(CONNECTIONS_KEY, 1) == 1) { return getInvokerClient(invoker); } else { ReferenceCountExchangeClient client = getReferenceClient(invoker); try { Field clientField = ReferenceCountExchangeClient.class.getDeclaredField("client"); clientField.setAccessible(true); return (ExchangeClient) clientField.get(client); } catch (Exception e) { e.printStackTrace(); Assertions.fail(e.getMessage()); throw new RuntimeException(e); } } } private ReferenceCountExchangeClient getReferenceClient(Invoker<?> invoker) { return getReferenceClientList(invoker).get(0); } private List<ReferenceCountExchangeClient> getReferenceClientList(Invoker<?> invoker) { List<ExchangeClient> invokerClientList = getInvokerClientList(invoker); List<ReferenceCountExchangeClient> referenceCountExchangeClientList = new ArrayList<>(invokerClientList.size()); for (ExchangeClient exchangeClient : invokerClientList) { Assertions.assertTrue(exchangeClient instanceof ReferenceCountExchangeClient); referenceCountExchangeClientList.add((ReferenceCountExchangeClient) exchangeClient); } return referenceCountExchangeClientList; } private ExchangeClient getInvokerClient(Invoker<?> invoker) { return getInvokerClientList(invoker).get(0); } private List<ExchangeClient> getInvokerClientList(Invoker<?> invoker) { @SuppressWarnings("rawtypes") DubboInvoker dInvoker = (DubboInvoker) invoker; try { Field clientField = DubboInvoker.class.getDeclaredField("clientsProvider"); clientField.setAccessible(true); ClientsProvider clientsProvider = (ClientsProvider) clientField.get(dInvoker); List<? extends ExchangeClient> clients = clientsProvider.getClients(); List<ExchangeClient> clientList = new ArrayList<ExchangeClient>(clients.size()); for (ExchangeClient client : clients) { clientList.add(client); } // sorting makes it easy to compare between lists Collections.sort(clientList, Comparator.comparing(c -> Integer.valueOf(Objects.hashCode(c)))); return clientList; } catch (Exception e) { e.printStackTrace(); Assertions.fail(e.getMessage()); throw new RuntimeException(e); } } public interface IDemoService { String demo(); } public interface IHelloService { String hello(); } public class DemoServiceImpl implements IDemoService { public String demo() { return "demo"; } } public class HelloServiceImpl implements IHelloService { public String hello() { return "hello"; } } }
5,821
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.decode.MockChannel; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; /** * {@link ServerStatusChecker} */ class ServerStatusCheckerTest { @Test void test() { ServerStatusChecker serverStatusChecker = new ServerStatusChecker(); Status status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.UNKNOWN); DubboProtocol dubboProtocol = Mockito.mock(DubboProtocol.class); ProtocolServer protocolServer = Mockito.mock(ProtocolServer.class); RemotingServer remotingServer = Mockito.mock(RemotingServer.class); List<ProtocolServer> servers = Arrays.asList(protocolServer); Mockito.when(dubboProtocol.getServers()).thenReturn(servers); Mockito.when(protocolServer.getRemotingServer()).thenReturn(remotingServer); Mockito.when(remotingServer.isBound()).thenReturn(true); Mockito.when(remotingServer.getLocalAddress()) .thenReturn(InetSocketAddress.createUnresolved("127.0.0.1", 9999)); Mockito.when(remotingServer.getChannels()).thenReturn(Arrays.asList(new MockChannel())); try (MockedStatic<DubboProtocol> mockDubboProtocol = Mockito.mockStatic(DubboProtocol.class)) { mockDubboProtocol.when(() -> DubboProtocol.getDubboProtocol()).thenReturn(dubboProtocol); status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.OK); // In JDK 17 : 127.0.0.1/<unresolved>:9999(clients:1) Assertions.assertTrue(status.getMessage().contains("127.0.0.1")); Assertions.assertTrue(status.getMessage().contains("9999(clients:1)")); Mockito.when(remotingServer.isBound()).thenReturn(false); status = serverStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.ERROR); // In JDK 17 : 127.0.0.1/<unresolved>:9999 Assertions.assertTrue(status.getMessage().contains("127.0.0.1")); Assertions.assertTrue(status.getMessage().contains("9999")); } } }
5,822
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link ThreadPoolStatusChecker} */ class ThreadPoolStatusCheckerTest { @Test void test() { DataStore dataStore = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension(); ExecutorService executorService1 = Executors.newFixedThreadPool(1); ExecutorService executorService2 = Executors.newFixedThreadPool(10); dataStore.put(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8888", executorService1); dataStore.put(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8889", executorService2); ThreadPoolStatusChecker threadPoolStatusChecker = new ThreadPoolStatusChecker(ApplicationModel.defaultModel()); Status status = threadPoolStatusChecker.check(); Assertions.assertEquals(status.getLevel(), Status.Level.WARN); Assertions.assertEquals( status.getMessage(), "Pool status:WARN, max:1, core:1, largest:0, active:0, task:0, service port: 8888;" + "Pool status:OK, max:10, core:10, largest:0, active:0, task:0, service port: 8889"); // reset executorService1.shutdown(); executorService2.shutdown(); dataStore.remove(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8888"); dataStore.remove(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY, "8889"); } }
5,823
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.remoting.ChannelHandler; import java.util.function.Consumer; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; public class MockHandler extends ChannelDuplexHandler { private final Consumer consumer; private final ChannelHandler handler; public MockHandler(Consumer consumer, ChannelHandler handler) { this.consumer = consumer; this.handler = handler; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { this.handler.received(new MockChannel(consumer), msg); } }
5,824
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.util.Collections; import java.util.Set; public class MockChannelHandler implements ChannelHandler { // ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>(); @Override public void connected(Channel channel) throws RemotingException { channels.add(channel); } @Override public void disconnected(Channel channel) throws RemotingException { channels.remove(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { channel.send(message); } @Override public void received(Channel channel, Object message) throws RemotingException { // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); } public Set<Channel> getChannels() { return Collections.unmodifiableSet(channels); } }
5,825
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/DubboTelnetDecodeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; import org.apache.dubbo.remoting.transport.DecodeHandler; import org.apache.dubbo.remoting.transport.MultiMessageHandler; import org.apache.dubbo.remoting.transport.netty4.NettyBackedChannelBuffer; import org.apache.dubbo.remoting.transport.netty4.NettyCodecAdapter; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.protocol.dubbo.DecodeableRpcInvocation; import org.apache.dubbo.rpc.protocol.dubbo.DubboCodec; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * These junit tests aim to test unpack and stick pack of dubbo and telnet */ class DubboTelnetDecodeTest { private static AtomicInteger dubbo = new AtomicInteger(0); private static AtomicInteger telnet = new AtomicInteger(0); private static AtomicInteger telnetDubbo = new AtomicInteger(0); private static AtomicInteger dubboDubbo = new AtomicInteger(0); private static AtomicInteger dubboTelnet = new AtomicInteger(0); private static AtomicInteger telnetTelnet = new AtomicInteger(0); @BeforeAll public static void setup() { ModuleServiceRepository serviceRepository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); serviceRepository.registerService(DemoService.class); } @AfterAll public static void teardown() { FrameworkModel.defaultModel().destroy(); } /** * just dubbo request * * @throws InterruptedException */ @Test void testDubboDecode() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( null, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { dubbo.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(dubboByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(1, dubbo.get()); } /** * just telnet request * * @throws InterruptedException */ @Test void testTelnetDecode() throws InterruptedException { ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("test\r\n".getBytes()); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { telnet.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(telnetByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(1, telnet.get()); } /** * telnet and dubbo request * * <p> * First ByteBuf: * +--------------------------------------------------+ * | telnet(incomplete) | * +--------------------------------------------------+ * <p> * * Second ByteBuf: * +--------------------------++----------------------+ * | telnet(the remaining) || dubbo(complete) | * +--------------------------++----------------------+ * || * Magic Code * * @throws InterruptedException */ @Test void testTelnetDubboDecoded() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("test\r".getBytes()); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { telnetDubbo.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { telnetDubbo.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(telnetByteBuf); ch.writeInbound(Unpooled.wrappedBuffer(Unpooled.wrappedBuffer("\n".getBytes()), dubboByteBuf)); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, telnetDubbo.get()); } /** * NOTE: This test case actually will fail, but the probability of this case is very small, * and users should use telnet in new QOS port(default port is 22222) since dubbo 2.5.8, * so we could ignore this problem. * * <p> * telnet and telnet request * * <p> * First ByteBuf (firstByteBuf): * +--------------------------------------------------+ * | telnet(incomplete) | * +--------------------------------------------------+ * <p> * * Second ByteBuf (secondByteBuf): * +--------------------------------------------------+ * | telnet(the remaining) | telnet(complete) | * +--------------------------------------------------+ * * @throws InterruptedException */ @Disabled @Test void testTelnetTelnetDecoded() throws InterruptedException { ByteBuf firstByteBuf = Unpooled.wrappedBuffer("ls\r".getBytes()); ByteBuf secondByteBuf = Unpooled.wrappedBuffer("\nls\r\n".getBytes()); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { telnetTelnet.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstByteBuf); ch.writeInbound(secondByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, telnetTelnet.get()); } /** * dubbo and dubbo request * * <p> * First ByteBuf (firstDubboByteBuf): * ++-------------------------------------------------+ * || dubbo(incomplete) | * ++-------------------------------------------------+ * || * Magic Code * <p> * * <p> * Second ByteBuf (secondDubboByteBuf): * +-------------------------++-----------------------+ * | dubbo(the remaining) || dubbo(complete) | * +-------------------------++-----------------------+ * || * Magic Code * * @throws InterruptedException */ @Test void testDubboDubboDecoded() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50); ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes() - 50); ByteBuf secondDubboByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, dubboByteBuf); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( null, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { dubboDubbo.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstDubboByteBuf); ch.writeInbound(secondDubboByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, dubboDubbo.get()); } /** * dubbo and telnet request * * <p> * First ByteBuf: * ++-------------------------------------------------+ * || dubbo(incomplete) | * ++-------------------------------------------------+ * || * Magic Code * * <p> * Second ByteBuf: * +--------------------------------------------------+ * | dubbo(the remaining) | telnet(complete) | * +--------------------------------------------------+ * * @throws InterruptedException */ @Test void testDubboTelnetDecoded() throws InterruptedException, IOException { ByteBuf dubboByteBuf = createDubboByteBuf(); ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50); ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes()); ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("\r\n".getBytes()); ByteBuf secondByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, telnetByteBuf); EmbeddedChannel ch = null; try { Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo"); URL url = new ServiceConfigURL("dubbo", "localhost", 22226); NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler()); MockHandler mockHandler = new MockHandler( (msg) -> { if (checkTelnetDecoded(msg)) { dubboTelnet.incrementAndGet(); } }, new MultiMessageHandler(new DecodeHandler( new HeaderExchangeHandler(new ExchangeHandlerAdapter(FrameworkModel.defaultModel()) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) { if (checkDubboDecoded(msg)) { dubboTelnet.incrementAndGet(); } return getDefaultFuture(); } })))); ch = new LocalEmbeddedChannel(); ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler); ch.writeInbound(firstDubboByteBuf); ch.writeInbound(secondByteBuf); } catch (Exception e) { e.printStackTrace(); } finally { if (ch != null) { ch.close().await(200, TimeUnit.MILLISECONDS); } } TimeUnit.MILLISECONDS.sleep(100); Assertions.assertEquals(2, dubboTelnet.get()); } private ByteBuf createDubboByteBuf() throws IOException { Request request = new Request(); RpcInvocation rpcInvocation = new RpcInvocation(); rpcInvocation.setMethodName("sayHello"); rpcInvocation.setParameterTypes(new Class[] {String.class}); rpcInvocation.setParameterTypesDesc(ReflectUtils.getDesc(new Class[] {String.class})); rpcInvocation.setArguments(new String[] {"dubbo"}); rpcInvocation.setAttachment("path", DemoService.class.getName()); rpcInvocation.setAttachment("interface", DemoService.class.getName()); rpcInvocation.setAttachment("version", "0.0.0"); request.setData(rpcInvocation); request.setVersion("2.0.2"); ByteBuf dubboByteBuf = Unpooled.buffer(); ChannelBuffer buffer = new NettyBackedChannelBuffer(dubboByteBuf); DubboCodec dubboCodec = new DubboCodec(FrameworkModel.defaultModel()); dubboCodec.encode(new MockChannel(), buffer, request); // register // frameworkModel.getServiceRepository().registerProviderUrl(); FrameworkModel.defaultModel() .getBeanFactory() .getBean(PermittedSerializationKeeper.class) .registerService( URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName() + "?version=0.0.0")); return dubboByteBuf; } private static boolean checkTelnetDecoded(Object msg) { if (msg instanceof String && !msg.toString().contains("Unsupported command:")) { return true; } return false; } private static boolean checkDubboDecoded(Object msg) { if (msg instanceof DecodeableRpcInvocation) { DecodeableRpcInvocation invocation = (DecodeableRpcInvocation) msg; if ("sayHello".equals(invocation.getMethodName()) && invocation.getParameterTypes().length == 1 && String.class.equals(invocation.getParameterTypes()[0]) && invocation.getArguments().length == 1 && "dubbo".equals(invocation.getArguments()[0]) && DemoService.class.getName().equals(invocation.getAttachment("path")) && DemoService.class.getName().equals(invocation.getAttachment("interface")) && "0.0.0".equals(invocation.getAttachment("version"))) { return true; } } return false; } private static CompletableFuture<Object> getDefaultFuture() { CompletableFuture<Object> future = new CompletableFuture<>(); AppResponse result = new AppResponse(); result.setValue("default result"); future.complete(result); return future; } }
5,826
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/LocalEmbeddedChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.utils.NetUtils; import java.net.InetSocketAddress; import java.net.SocketAddress; import io.netty.channel.embedded.EmbeddedChannel; public class LocalEmbeddedChannel extends EmbeddedChannel { public SocketAddress localAddress() { return new InetSocketAddress(20883); } @Override protected SocketAddress remoteAddress0() { return new InetSocketAddress(NetUtils.getAvailablePort()); } }
5,827
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/MockChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.function.Consumer; public class MockChannel implements Channel { private Consumer consumer; public MockChannel() {} public MockChannel(Consumer consumer) { this.consumer = consumer; } @Override public InetSocketAddress getRemoteAddress() { return new InetSocketAddress(NetUtils.getAvailablePort()); } @Override public boolean isConnected() { return false; } @Override public boolean hasAttribute(String key) { return false; } @Override public Object getAttribute(String key) { return null; } @Override public void setAttribute(String key, Object value) {} @Override public void removeAttribute(String key) {} @Override public URL getUrl() { return new ServiceConfigURL("dubbo", "localhost", 20880); } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return new InetSocketAddress(20883); } @Override public void send(Object message) throws RemotingException { if (consumer != null) { consumer.accept(message); } } @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; } }
5,828
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/decode/telnet/TestTelnetHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.decode.telnet; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; /** * ListTelnetHandler handler list services and its methods details. */ @Activate @Help(summary = "test telnet command.", detail = "test telnet command.") public class TestTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { return "TestTelnetHandler"; } }
5,829
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.rmi.Remote; import java.rmi.RemoteException; public interface RemoteService extends Remote { String sayHello(String name) throws RemoteException; String getThreadName() throws RemoteException; }
5,830
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Type.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; public enum Type { High, Normal, Lower }
5,831
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/CustomArgument.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.io.Serializable; @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; public CustomArgument() {} public CustomArgument(Type type, String name) { super(); this.type = type; this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
5,832
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/EnumBak.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.NetUtils; 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.service.GenericService; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; public class EnumBak { private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); @Test public void testNormal() { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk" + "&interface=" + DemoService.class.getName() + "&timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService("test", DemoService.class); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); URL consumerurl = serviceurl; Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); // System.out.println(demoProxy.getThreadName()); System.out.println(demoProxy.getInt(Integer.MIN_VALUE)); Assertions.assertEquals(Integer.MIN_VALUE, demoProxy.getInt(Integer.MIN_VALUE)); // invoker.destroy(); reference.destroy(); } @Disabled @Test public void testExportService() throws InterruptedException { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk&timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); synchronized (EnumBak.class) { EnumBak.class.wait(); } // URL consumerurl = serviceurl; // Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); // DemoService demoProxy = (DemoService)proxyFactory.createProxy(reference); //// System.out.println(demoProxy.getThreadName()); // System.out.println("byte:"+demoProxy.getbyte((byte)-128)); // // invoker.destroy(); // reference.destroy(); } @Test public void testNormalEnum() { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService("test", DemoService.class); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); URL consumerurl = serviceurl; Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); Type type = demoProxy.enumlength(Type.High); System.out.println(type); Assertions.assertEquals(Type.High, type); invoker.destroy(); reference.destroy(); } // verify compatibility when 2.0.5 invokes 2.0.3 @Disabled @Test public void testEnumCompat() { int port = NetUtils.getAvailablePort(); URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); ApplicationModel.defaultModel() .getDefaultModule() .getServiceRepository() .registerService(DemoService.class); Invoker<DemoService> reference = protocol.refer(DemoService.class, consumerurl); DemoService demoProxy = (DemoService) proxy.getProxy(reference); Type type = demoProxy.enumlength(Type.High); System.out.println(type); Assertions.assertEquals(Type.High, type); reference.destroy(); } // verify compatibility when 2.0.5 invokes 2.0.3 @Disabled @Test public void testGenricEnumCompat() { int port = NetUtils.getAvailablePort(); URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); Invoker<GenericService> reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); Object obj = demoProxy.$invoke( "enumlength", new String[] {Type[].class.getName()}, new Object[] {new Type[] {Type.High, Type.High}}); System.out.println("obj---------->" + obj); reference.destroy(); } // verify compatibility when 2.0.5 invokes 2.0.3, enum in custom parameter @Disabled @Test public void testGenricCustomArg() { int port = NetUtils.getAvailablePort(); URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=2000000"); Invoker<GenericService> reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); Map<String, Object> arg = new HashMap<String, Object>(); arg.put("type", "High"); arg.put("name", "hi"); Object obj = demoProxy.$invoke("get", new String[] {"org.apache.dubbo.rpc.CustomArgument"}, new Object[] {arg}); System.out.println("obj---------->" + obj); reference.destroy(); } @Disabled @Test public void testGenericExport() throws InterruptedException { int port = NetUtils.getAvailablePort(); // port = 20880; URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); // SERVER Thread.sleep(Integer.MAX_VALUE); } @Test public void testGenericEnum() throws InterruptedException { int port = NetUtils.getAvailablePort(); URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE); DemoService demo = new DemoServiceImpl(); Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.class, serviceurl); protocol.export(invoker); URL consumerurl = serviceurl; Invoker<GenericService> reference = protocol.refer(GenericService.class, consumerurl); GenericService demoProxy = (GenericService) proxy.getProxy(reference); Object obj = demoProxy.$invoke( "enumlength", new String[] {Type[].class.getName()}, new Object[] {new Type[] {Type.High, Type.High}}); System.out.println("obj---------->" + obj); invoker.destroy(); reference.destroy(); } }
5,833
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Man.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.io.Serializable; /** * Man.java */ public class Man implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
5,834
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/ProtocolUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.common.URL; 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.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; /** * TODO Comment of ProtocolUtils */ public class ProtocolUtils { public static <T> T refer(Class<T> type, String url) { return refer(type, URL.valueOf(url)); } public static <T> T refer(Class<T> type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return proxy.getProxy(protocol.refer(type, url)); } public static Invoker<?> referInvoker(Class<?> type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return (Invoker<?>) protocol.refer(type, url); } public static <T> Exporter<T> export(T instance, Class<T> type, String url) { return export(instance, type, URL.valueOf(url)); } public static <T> Exporter<T> export(T instance, Class<T> type, URL url) { FrameworkModel frameworkModel = url.getOrDefaultFrameworkModel(); ProxyFactory proxy = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = frameworkModel.getExtensionLoader(Protocol.class).getAdaptiveExtension(); return protocol.export(proxy.getInvoker(instance, type, url)); } public static void closeAll() { DubboProtocol.getDubboProtocol().destroy(); FrameworkModel.destroyAll(); } }
5,835
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.rpc.RpcContext; import java.util.Arrays; import java.util.Map; import java.util.Set; /** * DemoServiceImpl */ public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); } public void sayHello(String name) { System.out.println("hello " + name); } public String echo(String text) { return text; } public Map echo(Map map) { return map; } public long timestamp() { return System.currentTimeMillis(); } public String getThreadName() { return Thread.currentThread().getName(); } public int getSize(String[] strs) { if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { if (types.length == 0) return Type.Lower; return types[0]; } public Type getType(Type type) { return type; } public int stringLength(String str) { return str.length(); } public String get(CustomArgument arg1) { return arg1.toString(); } public int getInt(int arg) { return arg; } public Person gerPerson(Person person) { return person; } public Set<String> keys(Map<String, String> map) { return map == null ? null : map.keySet(); } public void nonSerializedParameter(NonSerialized ns) {} public NonSerialized returnNonSerialized() { return new NonSerialized(); } public long add(int a, long b) { return a + b; } @Override public int getPerson(Person person) { return person.getAge(); } @Override public int getPerson(Person person1, Person perso2) { return person1.getAge() + perso2.getAge(); } @Override public String getPerson(Man man) { return man.getName(); } @Override public String getRemoteApplicationName() { return RpcContext.getServiceContext().getRemoteApplicationName(); } @Override public byte[] download(int size) { byte[] bytes = new byte[size]; Arrays.fill(bytes, (byte) 0); return bytes; } }
5,836
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/RemoteServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import org.apache.dubbo.rpc.RpcContext; import java.rmi.RemoteException; public class RemoteServiceImpl implements RemoteService { public String getThreadName() throws RemoteException { System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); return Thread.currentThread().getName(); } public String sayHello(String name) throws RemoteException { return "hello " + name + "@" + RemoteServiceImpl.class.getName(); } }
5,837
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/Person.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.io.Serializable; /** * Person.java */ public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
5,838
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.io.Serializable; /** * TestRequest. */ class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; private String mServiceName; private String mMethodName; private Class<?>[] mParameterTypes; private Object[] mArguments; public DemoRequest(String serviceName, String methodName, Class<?>[] parameterTypes, Object[] args) { mServiceName = serviceName; mMethodName = methodName; mParameterTypes = parameterTypes; mArguments = args; } public String getServiceName() { return mServiceName; } public String getMethodName() { return mMethodName; } public Class<?>[] getParameterTypes() { return mParameterTypes; } public Object[] getArguments() { return mArguments; } }
5,839
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/NonSerialized.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; /** * NonSerialized */ public class NonSerialized {}
5,840
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/support/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.support; import java.util.Map; import java.util.Set; /** * <code>TestService</code> */ public interface DemoService { void sayHello(String name); Set<String> keys(Map<String, String> map); String echo(String text); Map echo(Map map); long timestamp(); String getThreadName(); int getSize(String[] strs); int getSize(Object[] os); Object invoke(String service, String method) throws Exception; int stringLength(String str); Type enumlength(Type... types); Type getType(Type type); String get(CustomArgument arg1); int getInt(int arg); void nonSerializedParameter(NonSerialized ns); NonSerialized returnNonSerialized(); long add(int a, long b); int getPerson(Person person); int getPerson(Person person1, Person perso2); String getPerson(Man man); String getRemoteApplicationName(); byte[] download(int size); }
5,841
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.protocol.dubbo.support.DemoService; import java.lang.reflect.Field; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class TraceFilterTest { private MockChannel mockChannel; private static final String TRACE_MAX = "trace.max"; private static final String TRACE_COUNT = "trace.count"; private static final String TRACERS_FIELD_NAME = "TRACERS"; @BeforeEach public void setUp() { URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo"); mockChannel = new MockChannel(url); } @AfterEach public void tearDown() { mockChannel.close(); } @Test void testAddAndRemoveTracer() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 100); Assertions.assertEquals(100, mockChannel.getAttribute(TRACE_MAX)); Assertions.assertTrue(mockChannel.getAttribute(TRACE_COUNT) instanceof AtomicInteger); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> o = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Assertions.assertTrue(o.containsKey(key)); Set<Channel> channels = o.get(key); Assertions.assertNotNull(channels); Assertions.assertTrue(channels.contains(mockChannel)); // remove tracer TraceFilter.removeTracer(type, method, mockChannel); Assertions.assertNull(mockChannel.getAttribute(TRACE_MAX)); Assertions.assertNull(mockChannel.getAttribute(TRACE_COUNT)); Assertions.assertFalse(channels.contains(mockChannel)); } @Test void testInvoke() throws Exception { String method = "sayHello"; Class<?> type = DemoService.class; String key = type.getName() + "." + method; // add tracer TraceFilter.addTracer(type, method, mockChannel, 2); Invoker<DemoService> mockInvoker = mock(Invoker.class); Invocation mockInvocation = mock(Invocation.class); Result mockResult = mock(Result.class); TraceFilter filter = new TraceFilter(); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvocation.getMethodName()).willReturn(method); given(mockInvocation.getArguments()).willReturn(new Object[0]); given(mockInvoker.invoke(mockInvocation)).willReturn(mockResult); given(mockResult.getValue()).willReturn("result"); // test invoke filter.invoke(mockInvoker, mockInvocation); String message = listToString(mockChannel.getReceivedObjects()); String expectMessage = "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.sayHello([]) -> \"result\""; System.out.println("actual message: " + message); Assertions.assertTrue(message.contains(expectMessage)); Assertions.assertTrue(message.contains("elapsed:")); AtomicInteger traceCount = (AtomicInteger) mockChannel.getAttribute(TRACE_COUNT); Assertions.assertEquals(1, traceCount.get()); // test remove channel when count >= max - 1 filter.invoke(mockInvoker, mockInvocation); Field tracers = TraceFilter.class.getDeclaredField(TRACERS_FIELD_NAME); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> o = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Assertions.assertTrue(o.containsKey(key)); Set<Channel> channels = o.get(key); Assertions.assertNotNull(channels); Assertions.assertFalse(channels.contains(mockChannel)); } private static String listToString(List<Object> objectList) { StringBuilder sb = new StringBuilder(); if (CollectionUtils.isEmpty(objectList)) { return ""; } objectList.forEach(o -> { sb.append(o.toString()); }); return sb.toString(); } }
5,842
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/filter/MockChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.filter; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class MockChannel implements Channel { private Map<String, Object> attributes = new HashMap<>(); private List<Object> receivedObjects = new LinkedList<>(); private URL url; public MockChannel() {} public MockChannel(URL url) { this.url = url; } @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public boolean isConnected() { return true; } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Object getAttribute(String key) { return attributes.getOrDefault(key, null); } @Override public void setAttribute(String key, Object value) { attributes.put(key, value); } @Override public void removeAttribute(String key) { attributes.remove(key); } @Override public URL getUrl() { return url; } @Override public ChannelHandler getChannelHandler() { return null; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException { receivedObjects.add(message); } @Override public void send(Object message, boolean sent) throws RemotingException { receivedObjects.add(message); } @Override public void close() {} @Override public void close(int timeout) {} @Override public void startClose() {} @Override public boolean isClosed() { return false; } public List<Object> getReceivedObjects() { return receivedObjects; } }
5,843
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannelHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.util.Collections; import java.util.Set; public class MockedChannelHandler implements ChannelHandler { // ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>(); ConcurrentHashSet<Channel> channels = new ConcurrentHashSet<Channel>(); @Override public void connected(Channel channel) throws RemotingException { channels.add(channel); } @Override public void disconnected(Channel channel) throws RemotingException { channels.remove(channel); } @Override public void sent(Channel channel, Object message) throws RemotingException { channel.send(message); } @Override public void received(Channel channel, Object message) throws RemotingException { // echo channel.send(message); } @Override public void caught(Channel channel, Throwable exception) throws RemotingException { throw new RemotingException(channel, exception); } public Set<Channel> getChannels() { return Collections.unmodifiableSet(channels); } }
5,844
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ConnectChannelHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.remoting.ExecutionException; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; class ConnectChannelHandlerTest extends WrappedChannelHandlerTest { @BeforeEach public void setUp() throws Exception { url = url.setScopeModel(ApplicationModel.defaultModel()); handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); } @Test void testConnectBlocked() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); Assertions.assertEquals(1, executor.getMaximumPoolSize()); int runs = 20; int taskCount = runs * 2; for (int i = 0; i < runs; i++) { handler.connected(new MockedChannel()); handler.disconnected(new MockedChannel()); Assertions.assertTrue(executor.getActiveCount() <= 1, executor.getActiveCount() + " must <=1"); } // queue.size Assertions.assertEquals(taskCount - 1, executor.getQueue().size()); for (int i = 0; i < taskCount; i++) { if (executor.getCompletedTaskCount() < taskCount) { sleep(100); } } Assertions.assertEquals(taskCount, executor.getCompletedTaskCount()); } @Test // biz error should not throw and affect biz thread. public void testConnectBizError() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); handler.connected(new MockedChannel()); } @Test // biz error should not throw and affect biz thread. public void testDisconnectBizError() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(true), url); handler.disconnected(new MockedChannel()); } @Test void testConnectExecuteError() throws RemotingException { Assertions.assertThrows(ExecutionException.class, () -> { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); executor.shutdown(); handler.connected(new MockedChannel()); }); } @Test void testDisconnectExecuteError() throws RemotingException { Assertions.assertThrows(ExecutionException.class, () -> { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "connectionExecutor", 1); executor.shutdown(); handler.disconnected(new MockedChannel()); }); } // throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception @Test // (expected = RemotingException.class) public void testMessageReceivedBizError() throws RemotingException { handler.received(new MockedChannel(), ""); } // throw ChannelEventRunnable.runtimeExeception(int logger) not in execute exception @Test void testCaughtBizError() throws RemotingException { handler.caught(new MockedChannel(), new BizException()); } @Test @Disabled("FIXME") public void testReceivedInvokeInExecutor() throws RemotingException { Assertions.assertThrows(ExecutionException.class, () -> { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "SHARED_EXECUTOR", 1); executor.shutdown(); executor = (ThreadPoolExecutor) getField(handler, "executor", 1); executor.shutdown(); handler.received(new MockedChannel(), ""); }); } /** * Events do not pass through the thread pool and execute directly on the IO */ @SuppressWarnings("deprecation") @Disabled("Heartbeat is processed in HeartbeatHandler not WrappedChannelHandler.") @Test void testReceivedEventInvokeDirect() throws RemotingException { handler = new ConnectionOrderedChannelHandler(new BizChannelHandler(false), url); ThreadPoolExecutor executor = (ThreadPoolExecutor) getField(handler, "SHARED_EXECUTOR", 1); executor.shutdown(); executor = (ThreadPoolExecutor) getField(handler, "executor", 1); executor.shutdown(); Request req = new Request(); req.setHeartbeat(true); final AtomicInteger count = new AtomicInteger(0); handler.received( new MockedChannel() { @Override public void send(Object message) throws RemotingException { Assertions.assertTrue(((Response) message).isHeartbeat(), "response.heartbeat"); count.incrementAndGet(); } }, req); Assertions.assertEquals(1, count.get(), "channel.send must be invoke"); } }
5,845
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.transport.MultiMessageHandler; import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ChannelHandlersTest { @Test void test() { ChannelHandlers instance1 = ChannelHandlers.getInstance(); ChannelHandlers instance2 = ChannelHandlers.getInstance(); Assertions.assertEquals(instance1, instance2); ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9999); ChannelHandler wrappedHandler = ChannelHandlers.wrap(channelHandler, url); Assertions.assertTrue(wrappedHandler instanceof MultiMessageHandler); MultiMessageHandler multiMessageHandler = (MultiMessageHandler) wrappedHandler; ChannelHandler handler = multiMessageHandler.getHandler(); Assertions.assertEquals(channelHandler, handler); } }
5,846
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/WrappedChannelHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.threadpool.ThreadlessExecutor; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.DefaultFuture; import org.apache.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Field; import java.util.concurrent.ExecutorService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.fail; class WrappedChannelHandlerTest { WrappedChannelHandler handler; URL url = URL.valueOf("dubbo://10.20.30.40:1234"); @BeforeEach public void setUp() throws Exception { url = url.setScopeModel(ApplicationModel.defaultModel()); handler = new WrappedChannelHandler(new BizChannelHandler(true), url); } @Test void test_Execute_Error() throws RemotingException {} protected Object getField(Object obj, String fieldName, int parentdepth) { try { Class<?> clazz = obj.getClass(); Field field = null; for (int i = 0; i <= parentdepth && field == null; i++) { Field[] fields = clazz.getDeclaredFields(); for (Field f : fields) { if (f.getName().equals(fieldName)) { field = f; break; } } clazz = clazz.getSuperclass(); } if (field != null) { field.setAccessible(true); return field.get(obj); } else { throw new NoSuchFieldException(); } } catch (Exception e) { throw new IllegalStateException(e); } } protected void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Test void testConnectBizError() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> handler.connected(new MockedChannel())); } @Test void testDisconnectBizError() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> handler.disconnected(new MockedChannel())); } @Test void testMessageReceivedBizError() throws RemotingException { Assertions.assertThrows(RemotingException.class, () -> handler.received(new MockedChannel(), "")); } @Test void testCaughtBizError() throws RemotingException { try { handler.caught(new MockedChannel(), new BizException()); fail(); } catch (Exception e) { Assertions.assertEquals(BizException.class, e.getCause().getClass()); } } @Test void testGetExecutor() { ExecutorService sharedExecutorService = handler.getSharedExecutorService(); Assertions.assertNotNull(sharedExecutorService); ExecutorService preferredExecutorService = handler.getPreferredExecutorService(new Object()); Assertions.assertEquals(preferredExecutorService, sharedExecutorService); Response response = new Response(10); preferredExecutorService = handler.getPreferredExecutorService(response); Assertions.assertEquals(preferredExecutorService, sharedExecutorService); Channel channel = new MockedChannel(); Request request = new Request(10); ExecutorService sharedExecutor = ExtensionLoader.getExtensionLoader(ExecutorRepository.class) .getDefaultExtension() .createExecutorIfAbsent(url); DefaultFuture future = DefaultFuture.newFuture(channel, request, 1000, null); preferredExecutorService = handler.getPreferredExecutorService(response); Assertions.assertEquals(preferredExecutorService, sharedExecutor); future.cancel(); ThreadlessExecutor executor = new ThreadlessExecutor(); future = DefaultFuture.newFuture(channel, request, 1000, executor); preferredExecutorService = handler.getPreferredExecutorService(response); Assertions.assertEquals(preferredExecutorService, executor); future.cancel(); } class BizChannelHandler extends MockedChannelHandler { private boolean invokeWithBizError; public BizChannelHandler(boolean invokeWithBizError) { super(); this.invokeWithBizError = invokeWithBizError; } public BizChannelHandler() { super(); } @Override public void connected(Channel channel) throws RemotingException { if (invokeWithBizError) { throw new RemotingException(channel, "test connect biz error"); } sleep(20); } @Override public void disconnected(Channel channel) throws RemotingException { if (invokeWithBizError) { throw new RemotingException(channel, "test disconnect biz error"); } sleep(20); } @Override public void received(Channel channel, Object message) throws RemotingException { if (invokeWithBizError) { throw new RemotingException(channel, "test received biz error"); } sleep(20); } } class BizException extends RuntimeException { private static final long serialVersionUID = -7541893754900723624L; } }
5,847
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/MockedChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.managemode; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; public class MockedChannel implements Channel { private boolean isClosed; private volatile boolean closing = false; private URL url; private ChannelHandler handler; private Map<String, Object> map = new HashMap<String, Object>(); public MockedChannel() { super(); } @Override public URL getUrl() { return url; } @Override public ChannelHandler getChannelHandler() { return this.handler; } @Override public InetSocketAddress getLocalAddress() { return null; } @Override public void send(Object message) throws RemotingException {} @Override public void send(Object message, boolean sent) throws RemotingException { this.send(message); } @Override public void close() { isClosed = true; } @Override public void close(int timeout) { this.close(); } @Override public void startClose() { closing = true; } @Override public boolean isClosed() { return isClosed; } @Override public InetSocketAddress getRemoteAddress() { return null; } @Override public boolean isConnected() { return false; } @Override public boolean hasAttribute(String key) { return map.containsKey(key); } @Override public Object getAttribute(String key) { return map.get(key); } @Override public void setAttribute(String key, Object value) { map.put(key, value); } @Override public void removeAttribute(String key) { map.remove(key); } }
5,848
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodecSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import static org.apache.dubbo.rpc.Constants.INVOCATION_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; public class DubboCodecSupport { public static Serialization getRequestSerialization(URL url, Invocation invocation) { Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { return CodecSupport.getSerializationById((byte) serializationTypeObj); } return url.getOrDefaultFrameworkModel() .getExtensionLoader(Serialization.class) .getExtension(UrlUtils.serializationOrDefault(url)); } public static Serialization getResponseSerialization(URL url, AppResponse appResponse) { Object invocationObj = appResponse.getAttribute(INVOCATION_KEY); if (invocationObj != null) { Invocation invocation = (Invocation) invocationObj; Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { return CodecSupport.getSerializationById((byte) serializationTypeObj); } } return url.getOrDefaultFrameworkModel() .getExtensionLoader(Serialization.class) .getExtension(UrlUtils.serializationOrDefault(url)); } }
5,849
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocolServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.ProtocolServer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DubboProtocolServer implements ProtocolServer { private final RemotingServer server; private String address; private final Map<String, Object> attributes = new ConcurrentHashMap<>(); public DubboProtocolServer(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 reset(URL url) { server.reset(url); } @Override public void close() { server.close(); } @Override public Map<String, Object> getAttributes() { return attributes; } }
5,850
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.executor.AbstractIsolationExecutorSupport; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceModel; public class DubboIsolationExecutorSupport extends AbstractIsolationExecutorSupport { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboIsolationExecutorSupport.class); private final FrameworkServiceRepository frameworkServiceRepository; private final DubboProtocol dubboProtocol; public DubboIsolationExecutorSupport(URL url) { super(url); frameworkServiceRepository = url.getOrDefaultFrameworkModel().getServiceRepository(); dubboProtocol = DubboProtocol.getDubboProtocol(url.getOrDefaultFrameworkModel()); } @Override protected ProviderModel getProviderModel(Object data) { if (!(data instanceof Request)) { return null; } Request request = (Request) data; if (!(request.getData() instanceof DecodeableRpcInvocation)) { return null; } try { ((DecodeableRpcInvocation) request.getData()).fillInvoker(dubboProtocol); } catch (RemotingException e) { // ignore here, and this exception will being rethrow in DubboProtocol } ServiceModel serviceModel = ((Invocation) request.getData()).getServiceModel(); if (serviceModel instanceof ProviderModel) { return (ProviderModel) serviceModel; } String targetServiceUniqueName = ((Invocation) request.getData()).getTargetServiceUniqueName(); if (StringUtils.isNotEmpty(targetServiceUniqueName)) { return frameworkServiceRepository.lookupExportedService(targetServiceUniqueName); } return null; } }
5,851
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboGracefulShutdown.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Version; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.rpc.GracefulShutdown; import org.apache.dubbo.rpc.ProtocolServer; import java.nio.channels.ClosedChannelException; import java.util.Collection; import static org.apache.dubbo.common.constants.CommonConstants.READONLY_EVENT; import static org.apache.dubbo.common.constants.CommonConstants.WRITEABLE_EVENT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE_STREAM; public class DubboGracefulShutdown implements GracefulShutdown { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboGracefulShutdown.class); private final DubboProtocol dubboProtocol; public DubboGracefulShutdown(DubboProtocol dubboProtocol) { this.dubboProtocol = dubboProtocol; } @Override public void readonly() { sendEvent(READONLY_EVENT); } @Override public void writeable() { sendEvent(WRITEABLE_EVENT); } private void sendEvent(String event) { try { for (ProtocolServer server : dubboProtocol.getServers()) { Collection<Channel> channels = server.getRemotingServer().getChannels(); Request request = new Request(); request.setEvent(event); request.setTwoWay(false); request.setVersion(Version.getProtocolVersion()); for (Channel channel : channels) { try { if (channel.isConnected()) { channel.send( request, channel.getUrl().getParameter(Constants.CHANNEL_READONLYEVENT_SENT_KEY, true)); } } catch (RemotingException e) { if (e.getCause() instanceof ClosedChannelException) { // ignore ClosedChannelException which means the connection has been closed. continue; } logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "send cannot write message error.", e); } } } } catch (Throwable e) { logger.warn(TRANSPORT_FAILED_CLOSE_STREAM, "", "", "send cannot write message error.", e); } } }
5,852
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.serialize.SerializationException; import org.apache.dubbo.common.utils.AtomicPositiveInteger; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; 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.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; 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.PAYLOAD; import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; /** * DubboInvoker */ public class DubboInvoker<T> extends AbstractInvoker<T> { private final ClientsProvider clientsProvider; private final AtomicPositiveInteger index = new AtomicPositiveInteger(); private final ReentrantLock destroyLock = new ReentrantLock(); private final Set<Invoker<?>> invokers; private final int serverShutdownTimeout; private static final boolean setFutureWhenSync = Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true")); public DubboInvoker(Class<T> serviceType, URL url, ClientsProvider clientsProvider) { this(serviceType, url, clientsProvider, null); } public DubboInvoker(Class<T> serviceType, URL url, ClientsProvider clientsProvider, Set<Invoker<?>> invokers) { super(serviceType, url, new String[] {INTERFACE_KEY, GROUP_KEY, TOKEN_KEY}); this.clientsProvider = clientsProvider; this.invokers = invokers; this.serverShutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(getUrl().getScopeModel()); } @Override protected Result doInvoke(final Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; final String methodName = RpcUtils.getMethodName(invocation); inv.setAttachment(PATH_KEY, getUrl().getPath()); inv.setAttachment(VERSION_KEY, version); ExchangeClient currentClient; List<? extends ExchangeClient> exchangeClients = clientsProvider.getClients(); if (exchangeClients.size() == 1) { currentClient = exchangeClients.get(0); } else { currentClient = exchangeClients.get(index.getAndIncrement() % exchangeClients.size()); } try { boolean isOneway = RpcUtils.isOneway(getUrl(), invocation); int timeout = RpcUtils.calculateTimeout(getUrl(), invocation, methodName, DEFAULT_TIMEOUT); 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)); Integer payload = getUrl().getParameter(PAYLOAD, Integer.class); Request request = new Request(); if (payload != null) { request.setPayload(payload); } request.setData(inv); request.setVersion(Version.getProtocolVersion()); if (isOneway) { boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); request.setTwoWay(false); currentClient.send(request, isSent); return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { request.setTwoWay(true); ExecutorService executor = getCallbackExecutor(getUrl(), inv); CompletableFuture<AppResponse> appResponseFuture = currentClient.request(request, timeout, executor).thenApply(AppResponse.class::cast); // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) { FutureContext.getContext().setCompatibleFuture(appResponseFuture); } AsyncRpcResult result = new AsyncRpcResult(appResponseFuture, inv); result.setExecutor(executor); return result; } } catch (TimeoutException e) { throw new RpcException( RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + RpcUtils.getMethodName(invocation) + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (RemotingException e) { String remoteExpMsg = "Failed to invoke remote method: " + RpcUtils.getMethodName(invocation) + ", provider: " + getUrl() + ", cause: " + e.getMessage(); if (e.getCause() instanceof IOException && e.getCause().getCause() instanceof SerializationException) { throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, remoteExpMsg, e); } else { throw new RpcException(RpcException.NETWORK_EXCEPTION, remoteExpMsg, e); } } } @Override public boolean isAvailable() { if (!super.isAvailable()) { return false; } for (ExchangeClient client : clientsProvider.getClients()) { if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) { // cannot write == not Available ? return true; } } return false; } @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); } clientsProvider.close(ConfigurationUtils.reCalShutdownTime(serverShutdownTimeout)); } finally { destroyLock.unlock(); } } } }
5,853
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.config.Configuration; 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.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Type; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_SECURITY_CHECK_KEY; public class DecodeableRpcResult extends AppResponse implements Codec, Decodeable { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcResult.class); private final Channel channel; private final byte serializationType; private final InputStream inputStream; private final Response response; private final Invocation invocation; private volatile boolean hasDecoded; public DecodeableRpcResult(Channel channel, Response response, InputStream is, Invocation invocation, byte id) { Assert.notNull(channel, "channel == null"); Assert.notNull(response, "response == null"); Assert.notNull(is, "inputStream == null"); this.channel = channel; this.response = response; this.inputStream = is; this.invocation = invocation; this.serializationType = id; } @Override public void encode(Channel channel, OutputStream output, Object message) throws IOException { throw new UnsupportedOperationException(); } @Override public Object decode(Channel channel, InputStream input) throws IOException { if (log.isDebugEnabled()) { Thread thread = Thread.currentThread(); log.debug("Decoding in thread -- [" + thread.getName() + "#" + thread.getId() + "]"); } int contentLength = input.available(); setAttribute(Constants.CONTENT_LENGTH_KEY, contentLength); // switch TCCL if (invocation != null && invocation.getServiceModel() != null) { Thread.currentThread() .setContextClassLoader(invocation.getServiceModel().getClassLoader()); } ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input); byte flag = in.readByte(); switch (flag) { case DubboCodec.RESPONSE_NULL_VALUE: break; case DubboCodec.RESPONSE_VALUE: handleValue(in); break; case DubboCodec.RESPONSE_WITH_EXCEPTION: handleException(in); break; case DubboCodec.RESPONSE_NULL_VALUE_WITH_ATTACHMENTS: handleAttachment(in); break; case DubboCodec.RESPONSE_VALUE_WITH_ATTACHMENTS: handleValue(in); handleAttachment(in); break; case DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS: handleException(in); handleAttachment(in); break; default: throw new IOException("Unknown result flag, expect '0' '1' '2' '3' '4' '5', but received: " + flag); } if (in instanceof Cleanable) { ((Cleanable) in).cleanup(); } return this; } @Override public void decode() throws Exception { if (!hasDecoded && channel != null && inputStream != null) { try { if (invocation != null) { Configuration systemConfiguration = null; try { systemConfiguration = ConfigurationUtils.getSystemConfiguration( channel.getUrl().getScopeModel()); } catch (Exception e) { // Because the Environment may be destroyed during the offline process, the configuration cannot // be obtained. // Exceptions are ignored here, and normal decoding is guaranteed. } if (systemConfiguration == null || systemConfiguration.getBoolean(SERIALIZATION_SECURITY_CHECK_KEY, true)) { Object serializationTypeObj = invocation.get(SERIALIZATION_ID_KEY); if (serializationTypeObj != null) { if ((byte) serializationTypeObj != serializationType) { throw new IOException("Unexpected serialization id:" + serializationType + " received from network, please check if the peer send the right id."); } } } } decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc result failed: " + e.getMessage(), e); } response.setStatus(Response.CLIENT_ERROR); response.setErrorMessage(StringUtils.toString(e)); } finally { hasDecoded = true; } } } private void handleValue(ObjectInput in) throws IOException { try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value; if (ArrayUtils.isEmpty(returnTypes)) { // happens when generic invoke or void return value = in.readObject(); } else if (returnTypes.length == 1) { value = in.readObject((Class<?>) returnTypes[0]); } else { value = in.readObject((Class<?>) returnTypes[0], returnTypes[1]); } setValue(value); } catch (ClassNotFoundException e) { rethrow(e); } } private void handleException(ObjectInput in) throws IOException { try { setException(in.readThrowable()); } catch (ClassNotFoundException e) { rethrow(e); } } private void handleAttachment(ObjectInput in) throws IOException { try { addObjectAttachments(in.readAttachments()); } catch (ClassNotFoundException e) { rethrow(e); } } private void rethrow(Exception e) throws IOException { throw new IOException(StringUtils.toString("Read response data failed.", e)); } }
5,854
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboIsolationExecutorSupportFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.rpc.executor.ExecutorSupport; import org.apache.dubbo.rpc.executor.IsolationExecutorSupportFactory; public class DubboIsolationExecutorSupportFactory implements IsolationExecutorSupportFactory { @Override public ExecutorSupport createIsolationExecutorSupport(URL url) { return new DubboIsolationExecutorSupport(url); } }
5,855
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/LazyConnectExchangeClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Parameters; 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.NetUtils; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.rpc.RpcException; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.remoting.Constants.SEND_RECONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_LAZY_REQUEST_WITH_WARNING; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_REQUEST_WITH_WARNING_KEY; /** * dubbo protocol support class. */ @SuppressWarnings("deprecation") final class LazyConnectExchangeClient implements ExchangeClient { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(LazyConnectExchangeClient.class); private final boolean requestWithWarning; private final URL url; private final ExchangeHandler requestHandler; private final Lock connectLock = new ReentrantLock(); private static final int warningPeriod = 5000; private final boolean needReconnect; private volatile ExchangeClient client; private final AtomicLong warningCount = new AtomicLong(0); public LazyConnectExchangeClient(URL url, ExchangeHandler requestHandler) { // lazy connect, need set send.reconnect = true, to avoid channel bad status. this.url = url.addParameter(LAZY_CONNECT_KEY, true); this.needReconnect = url.getParameter(SEND_RECONNECT_KEY, false); this.requestHandler = requestHandler; this.requestWithWarning = url.getParameter(LAZY_REQUEST_WITH_WARNING_KEY, DEFAULT_LAZY_REQUEST_WITH_WARNING); } private void initClient() throws RemotingException { if (client != null) { return; } if (logger.isInfoEnabled()) { logger.info("Lazy connect to " + url); } connectLock.lock(); try { if (client != null) { return; } this.client = Exchangers.connect(url, requestHandler); } finally { connectLock.unlock(); } } @Override public CompletableFuture<Object> request(Object request) throws RemotingException { warning(); checkClient(); return client.request(request); } @Override public URL getUrl() { return url; } @Override public InetSocketAddress getRemoteAddress() { if (client == null) { return InetSocketAddress.createUnresolved(url.getHost(), url.getPort()); } else { return client.getRemoteAddress(); } } @Override public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException { warning(); checkClient(); return client.request(request, timeout); } @Override public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException { warning(); checkClient(); return client.request(request, executor); } @Override public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException { warning(); checkClient(); return client.request(request, timeout, executor); } /** * If {@link Constants.LAZY_REQUEST_WITH_WARNING_KEY} is configured, then warn once every 5000 invocations. */ private void warning() { if (requestWithWarning) { if (warningCount.get() % warningPeriod == 0) { logger.warn( PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); } warningCount.incrementAndGet(); } } @Override public ChannelHandler getChannelHandler() { checkClient(); return client.getChannelHandler(); } @Override public boolean isConnected() { if (client == null) { // Before the request arrives, LazyConnectExchangeClient always exists in a normal connection state // to prevent ReconnectTask from initiating a reconnection action. return true; } else { return client.isConnected(); } } @Override public InetSocketAddress getLocalAddress() { if (client == null) { return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0); } else { return client.getLocalAddress(); } } @Override public ExchangeHandler getExchangeHandler() { return requestHandler; } @Override public void send(Object message) throws RemotingException { checkClient(); client.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { checkClient(); client.send(message, sent); } @Override public boolean isClosed() { if (client != null) { return client.isClosed(); } else { return false; } } @Override public void close() { if (client != null) { client.close(); client = null; } } @Override public void close(int timeout) { if (client != null) { client.close(timeout); client = null; } } @Override public void startClose() { if (client != null) { client.startClose(); } } @Override public void reset(URL url) { checkClient(); client.reset(url); } @Override @Deprecated public void reset(Parameters parameters) { reset(getUrl().addParameters(parameters.getParameters())); } @Override public void reconnect() throws RemotingException { checkClient(); client.reconnect(); } @Override public Object getAttribute(String key) { if (client == null) { return null; } else { return client.getAttribute(key); } } @Override public void setAttribute(String key, Object value) { checkClient(); client.setAttribute(key, value); } @Override public void removeAttribute(String key) { checkClient(); client.removeAttribute(key); } @Override public boolean hasAttribute(String key) { if (client == null) { return false; } else { return client.hasAttribute(key); } } private void checkClient() { try { initClient(); } catch (Exception e) { throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e); } if (!isConnected() && !needReconnect) { throw new IllegalStateException("LazyConnectExchangeClient is not connected normally, " + "and send.reconnect is configured as false, the request fails quickly" + url); } } }
5,856
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Version; import org.apache.dubbo.common.io.Bytes; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.serialize.ObjectOutput; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.threadpool.manager.ExecutorRepository; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.HeartBeatRequest; import org.apache.dubbo.remoting.exchange.HeartBeatResponse; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.codec.ExchangeCodec; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.CommonConstants.BYTE_ACCESSOR_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION; 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.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_DECODE_IN_IO_THREAD; /** * Dubbo codec. */ public class DubboCodec extends ExchangeCodec { public static final String NAME = "dubbo"; public static final String DUBBO_VERSION = Version.getProtocolVersion(); public static final byte RESPONSE_WITH_EXCEPTION = 0; public static final byte RESPONSE_VALUE = 1; public static final byte RESPONSE_NULL_VALUE = 2; public static final byte RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS = 3; public static final byte RESPONSE_VALUE_WITH_ATTACHMENTS = 4; public static final byte RESPONSE_NULL_VALUE_WITH_ATTACHMENTS = 5; public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0]; private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DubboCodec.class); private static final AtomicBoolean decodeInUserThreadLogged = new AtomicBoolean(false); private final CallbackServiceCodec callbackServiceCodec; private final FrameworkModel frameworkModel; private final ByteAccessor customByteAccessor; private static final String DECODE_IN_IO_THREAD_KEY = "decode.in.io.thread"; public DubboCodec(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; callbackServiceCodec = new CallbackServiceCodec(frameworkModel); customByteAccessor = Optional.ofNullable(System.getProperty(BYTE_ACCESSOR_KEY)) .filter(StringUtils::isNotBlank) .map(key -> frameworkModel.getExtensionLoader(ByteAccessor.class).getExtension(key)) .orElse(null); } @Override protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); // get request id. long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { // decode response. Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(true); } // get status. byte status = header[3]; res.setStatus(status); try { if (status == Response.OK) { Object data; if (res.isEvent()) { byte[] eventPayload = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat(eventPayload, proto)) { // heart beat response data is always null; data = null; } else { ObjectInput in = CodecSupport.deserialize( channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); data = decodeEventData(channel, in, eventPayload); } } else { DecodeableRpcResult result; Invocation inv = (Invocation) getRequestData(channel, res, id); if (channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD)) { if (customByteAccessor != null) { result = customByteAccessor.getRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } else { result = new DecodeableRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } result.decode(); } else { if (customByteAccessor != null) { result = customByteAccessor.getRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } else { result = new DecodeableRpcResult( channel, res, new UnsafeByteArrayInputStream(readMessageData(is)), inv, proto); } } data = result; } res.setResult(data); } else { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); res.setErrorMessage(in.readUTF()); } } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode response failed: " + t.getMessage(), t); } res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { // decode request. Request req; try { Object data; if ((flag & FLAG_EVENT) != 0) { byte[] eventPayload = CodecSupport.getPayload(is); if (CodecSupport.isHeartBeat(eventPayload, proto)) { // heart beat response data is always null; req = new HeartBeatRequest(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); ((HeartBeatRequest) req).setProto(proto); data = null; } else { req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); ObjectInput in = CodecSupport.deserialize( channel.getUrl(), new ByteArrayInputStream(eventPayload), proto); data = decodeEventData(channel, in, eventPayload); } req.setEvent(true); } else { req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); // get data length. int len = Bytes.bytes2int(header, 12); req.setPayload(len); DecodeableRpcInvocation inv; if (isDecodeDataInIoThread(channel)) { if (customByteAccessor != null) { inv = customByteAccessor.getRpcInvocation( channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } else { inv = new DecodeableRpcInvocation( frameworkModel, channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } inv.decode(); } else { if (customByteAccessor != null) { inv = customByteAccessor.getRpcInvocation( channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } else { inv = new DecodeableRpcInvocation( frameworkModel, channel, req, new UnsafeByteArrayInputStream(readMessageData(is)), proto); } } data = inv; } req.setData(data); } catch (Throwable t) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode request failed: " + t.getMessage(), t); } // bad request req = new HeartBeatRequest(id); req.setBroken(true); req.setData(t); } return req; } } private boolean isDecodeDataInIoThread(Channel channel) { Object obj = channel.getAttribute(DECODE_IN_IO_THREAD_KEY); if (obj instanceof Boolean) { return (Boolean) obj; } String mode = ExecutorRepository.getMode(channel.getUrl().getOrDefaultApplicationModel()); boolean isIsolated = EXECUTOR_MANAGEMENT_MODE_ISOLATION.equals(mode); if (isIsolated && !decodeInUserThreadLogged.compareAndSet(false, true)) { channel.setAttribute(DECODE_IN_IO_THREAD_KEY, true); return true; } boolean decodeDataInIoThread = channel.getUrl().getParameter(DECODE_IN_IO_THREAD_KEY, DEFAULT_DECODE_IN_IO_THREAD); if (isIsolated && !decodeDataInIoThread) { log.info("Because thread pool isolation is enabled on the dubbo protocol, the body can only be decoded " + "on the io thread, and the parameter[" + DECODE_IN_IO_THREAD_KEY + "] will be ignored"); // Why? because obtaining the isolated thread pool requires the serviceKey of the service, // and this part must be decoded before it can be obtained (more see DubboExecutorSupport) channel.setAttribute(DECODE_IN_IO_THREAD_KEY, true); return true; } channel.setAttribute(DECODE_IN_IO_THREAD_KEY, decodeDataInIoThread); return decodeDataInIoThread; } private byte[] readMessageData(InputStream is) throws IOException { if (is.available() > 0) { byte[] result = new byte[is.available()]; is.read(result); return result; } return new byte[] {}; } @Override protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeRequestData(channel, out, data, DUBBO_VERSION); } @Override protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { encodeResponseData(channel, out, data, DUBBO_VERSION); } @Override protected void encodeRequestData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { RpcInvocation inv = (RpcInvocation) data; out.writeUTF(version); // https://github.com/apache/dubbo/issues/6138 String serviceName = inv.getAttachment(INTERFACE_KEY); if (serviceName == null) { serviceName = inv.getAttachment(PATH_KEY); } out.writeUTF(serviceName); out.writeUTF(inv.getAttachment(VERSION_KEY)); out.writeUTF(inv.getMethodName()); out.writeUTF(inv.getParameterTypesDesc()); Object[] args = inv.getArguments(); if (args != null) { for (int i = 0; i < args.length; i++) { out.writeObject(callbackServiceCodec.encodeInvocationArgument(channel, inv, i)); } } out.writeAttachments(inv.getObjectAttachments()); } @Override protected void encodeResponseData(Channel channel, ObjectOutput out, Object data, String version) throws IOException { Result result = (Result) data; // currently, the version value in Response records the version of Request boolean attach = Version.isSupportResponseAttachment(version); Throwable th = result.getException(); if (th == null) { Object ret = result.getValue(); if (ret == null) { out.writeByte(attach ? RESPONSE_NULL_VALUE_WITH_ATTACHMENTS : RESPONSE_NULL_VALUE); } else { out.writeByte(attach ? RESPONSE_VALUE_WITH_ATTACHMENTS : RESPONSE_VALUE); out.writeObject(ret); } } else { out.writeByte(attach ? RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS : RESPONSE_WITH_EXCEPTION); out.writeThrowable(th); } if (attach) { // returns current version of Response to consumer side. result.getObjectAttachments().put(DUBBO_VERSION_KEY, Version.getProtocolVersion()); out.writeAttachments(result.getObjectAttachments()); } } @Override protected Serialization getSerialization(Channel channel, Request req) { if (!(req.getData() instanceof Invocation)) { return super.getSerialization(channel, req); } return DubboCodecSupport.getRequestSerialization(channel.getUrl(), (Invocation) req.getData()); } @Override protected Serialization getSerialization(Channel channel, Response res) { if (res instanceof HeartBeatResponse) { return CodecSupport.getSerializationById(((HeartBeatResponse) res).getProto()); } if (!(res.getResult() instanceof AppResponse)) { return super.getSerialization(channel, res); } return DubboCodecSupport.getResponseSerialization(channel.getUrl(), (AppResponse) res.getResult()); } }
5,857
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboExporter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.AbstractExporter; import java.util.Map; /** * DubboExporter */ public class DubboExporter<T> extends AbstractExporter<T> { private final String key; private final Map<String, Exporter<?>> exporterMap; public DubboExporter(Invoker<T> invoker, String key, Map<String, Exporter<?>> exporterMap) { super(invoker); this.key = key; this.exporterMap = exporterMap; exporterMap.put(key, this); } @Override public void afterUnExport() { exporterMap.remove(key, this); } }
5,858
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ByteAccessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.extension.SPI; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.rpc.Invocation; import java.io.InputStream; import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK; /** * Extension of Byte Accessor, holding attributes as RpcInvocation objects * so that the decoded service can be used more flexibly * @since 3.2.0 */ @SPI(scope = FRAMEWORK) public interface ByteAccessor { /** * Get an enhanced DecodeableRpcInvocation subclass to allow custom decode. * The parameters are the same as {@link DecodeableRpcInvocation} */ DecodeableRpcInvocation getRpcInvocation(Channel channel, Request req, InputStream is, byte proto); /** * Get an enhanced DecodeableRpcResult subclass to allow custom decode. * The parameters are the same as {@link DecodeableRpcResult} */ DecodeableRpcResult getRpcResult(Channel channel, Response res, InputStream is, Invocation invocation, byte proto); }
5,859
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/SharedClientsProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.config.ConfigurationUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.CollectionUtils; import java.util.List; import java.util.Objects; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class SharedClientsProvider implements ClientsProvider { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SharedClientsProvider.class); private final DubboProtocol dubboProtocol; private final String addressKey; private final List<ReferenceCountExchangeClient> clients; public SharedClientsProvider( DubboProtocol dubboProtocol, String addressKey, List<ReferenceCountExchangeClient> clients) { this.dubboProtocol = dubboProtocol; this.addressKey = addressKey; this.clients = clients; } @Override public List<ReferenceCountExchangeClient> getClients() { return clients; } public synchronized boolean increaseCount() { if (checkClientCanUse(clients)) { batchClientRefIncr(clients); return true; } return false; } @Override public synchronized void close(int timeout) { for (ReferenceCountExchangeClient client : clients) { try { client.close(timeout); } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } if (!checkClientCanUse(clients)) { dubboProtocol.scheduleRemoveSharedClient(addressKey, this); } } public synchronized void forceClose() { for (ReferenceCountExchangeClient client : clients) { closeReferenceCountExchangeClient(client); } } /** * Check if the client list is all available * * @param referenceCountExchangeClients * @return true-available,false-unavailable */ private boolean checkClientCanUse(List<ReferenceCountExchangeClient> referenceCountExchangeClients) { if (CollectionUtils.isEmpty(referenceCountExchangeClients)) { return false; } // As long as one client is not available, you need to replace the unavailable client with the available one. return referenceCountExchangeClients.stream() .noneMatch(referenceCountExchangeClient -> referenceCountExchangeClient == null || referenceCountExchangeClient.getCount() <= 0 || referenceCountExchangeClient.isClosed()); } /** * Increase the reference Count if we create new invoker shares same connection, the connection will be closed without any reference. * * @param referenceCountExchangeClients */ private void batchClientRefIncr(List<ReferenceCountExchangeClient> referenceCountExchangeClients) { if (CollectionUtils.isEmpty(referenceCountExchangeClients)) { return; } referenceCountExchangeClients.stream() .filter(Objects::nonNull) .forEach(ReferenceCountExchangeClient::incrementAndGetCount); } /** * close ReferenceCountExchangeClient * * @param client */ private void closeReferenceCountExchangeClient(ReferenceCountExchangeClient client) { if (client == null) { return; } try { if (logger.isInfoEnabled()) { logger.info("Close dubbo connect: " + client.getLocalAddress() + "-->" + client.getRemoteAddress()); } client.close(ConfigurationUtils.reCalShutdownTime(client.getShutdownWaitTime())); // TODO /* * At this time, ReferenceCountExchangeClient#client has been replaced with LazyConnectExchangeClient. * Do you need to call client.close again to ensure that LazyConnectExchangeClient is also closed? */ } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } }
5,860
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ExclusiveClientsProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.exchange.ExchangeClient; import java.util.List; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_CLIENT; public class ExclusiveClientsProvider implements ClientsProvider { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ExclusiveClientsProvider.class); private final List<ExchangeClient> clients; public ExclusiveClientsProvider(List<ExchangeClient> clients) { this.clients = clients; } @Override public List<ExchangeClient> getClients() { return clients; } @Override public void close(int timeout) { for (ExchangeClient client : clients) { try { client.close(timeout); } catch (Throwable t) { logger.warn(PROTOCOL_ERROR_CLOSE_CLIENT, "", "", t.getMessage(), t); } } } }
5,861
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/CallbackServiceCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.BaseServiceMetadata; import org.apache.dubbo.common.URL; 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.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; 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.support.RpcUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CALLBACK_INSTANCES; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; 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.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_LOAD_MODEL; import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_PROXY_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CHANNEL_CALLBACK_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; /** * callback service helper */ public class CallbackServiceCodec { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(CallbackServiceCodec.class); private static final byte CALLBACK_NONE = 0x0; private static final byte CALLBACK_CREATE = 0x1; private static final byte CALLBACK_DESTROY = 0x2; private static final String INV_ATT_CALLBACK_KEY = "sys_callback_arg-"; private final ProxyFactory proxyFactory; private final Protocol protocolSPI; private final FrameworkModel frameworkModel; private final DubboProtocol dubboProtocol; public CallbackServiceCodec(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; proxyFactory = frameworkModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); protocolSPI = frameworkModel.getExtensionLoader(Protocol.class).getExtension(DUBBO_PROTOCOL); dubboProtocol = (DubboProtocol) frameworkModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); } private static byte isCallBack(URL url, String protocolServiceKey, String methodName, int argIndex) { // parameter callback rule: method-name.parameter-index(starting from 0).callback byte isCallback = CALLBACK_NONE; if (url != null && url.hasServiceMethodParameter(protocolServiceKey, methodName)) { String callback = url.getServiceParameter(protocolServiceKey, methodName + "." + argIndex + ".callback"); if (callback != null) { if ("true".equalsIgnoreCase(callback)) { isCallback = CALLBACK_CREATE; } else if ("false".equalsIgnoreCase(callback)) { isCallback = CALLBACK_DESTROY; } } } return isCallback; } /** * export or unexport callback service on client side * * @param channel * @param url * @param clazz * @param inst * @param export * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes"}) private String exportOrUnexportCallbackService( Channel channel, RpcInvocation inv, URL url, Class clazz, Object inst, Boolean export) throws IOException { int instid = System.identityHashCode(inst); Map<String, String> params = new HashMap<>(3); // no need to new client again params.put(IS_SERVER_KEY, Boolean.FALSE.toString()); // mark it's a callback, for troubleshooting params.put(IS_CALLBACK_SERVICE, Boolean.TRUE.toString()); String group = (inv == null ? null : (String) inv.getObjectAttachmentWithoutConvert(GROUP_KEY)); if (group != null && group.length() > 0) { params.put(GROUP_KEY, group); } // add method, for verifying against method, automatic fallback (see dubbo protocol) params.put(METHODS_KEY, StringUtils.join(ClassUtils.getDeclaredMethodNames(clazz), ",")); Map<String, String> tmpMap = new HashMap<>(); if (url != null) { Map<String, String> parameters = url.getParameters(); if (parameters != null && !parameters.isEmpty()) { tmpMap.putAll(parameters); } } tmpMap.putAll(params); tmpMap.remove(VERSION_KEY); // doesn't need to distinguish version for callback tmpMap.remove(Constants.BIND_PORT_KEY); // callback doesn't needs bind.port tmpMap.put(INTERFACE_KEY, clazz.getName()); URL exportUrl = new ServiceConfigURL( DubboProtocol.NAME, channel.getLocalAddress().getAddress().getHostAddress(), channel.getLocalAddress().getPort(), clazz.getName() + "." + instid, tmpMap); // no need to generate multiple exporters for different channel in the same JVM, cache key cannot collide. String cacheKey = getClientSideCallbackServiceCacheKey(instid); String countKey = getClientSideCountKey(clazz.getName()); if (export) { // one channel can have multiple callback instances, no need to re-export for different instance. if (!channel.hasAttribute(cacheKey)) { if (!isInstancesOverLimit(channel, url, clazz.getName(), instid, false)) { ModuleModel moduleModel; if (inv.getServiceModel() == null) { // TODO should get scope model from url? moduleModel = ApplicationModel.defaultModel().getDefaultModule(); logger.error( PROTOCOL_FAILED_LOAD_MODEL, "", "", "Unable to get Service Model from Invocation. Please check if your invocation failed! " + "This error only happen in UT cases! Invocation:" + inv); } else { moduleModel = inv.getServiceModel().getModuleModel(); } ServiceDescriptor serviceDescriptor = moduleModel.getServiceRepository().registerService(clazz); ServiceMetadata serviceMetadata = new ServiceMetadata( clazz.getName() + "." + instid, exportUrl.getGroup(), exportUrl.getVersion(), clazz); String serviceKey = BaseServiceMetadata.buildServiceKey(exportUrl.getPath(), group, exportUrl.getVersion()); ProviderModel providerModel = new ProviderModel( serviceKey, inst, serviceDescriptor, moduleModel, serviceMetadata, ClassUtils.getClassLoader(clazz)); moduleModel.getServiceRepository().registerProvider(providerModel); exportUrl = exportUrl.setScopeModel(moduleModel); exportUrl = exportUrl.setServiceModel(providerModel); Invoker<?> invoker = proxyFactory.getInvoker(inst, clazz, exportUrl); // should destroy resource? Exporter<?> exporter = protocolSPI.export(invoker); // this is used for tracing if instid has published service or not. channel.setAttribute(cacheKey, exporter); logger.info("Export a callback service :" + exportUrl + ", on " + channel + ", url is: " + url); increaseInstanceCount(channel, countKey); } } } else { if (channel.hasAttribute(cacheKey)) { Exporter<?> exporter = (Exporter<?>) channel.getAttribute(cacheKey); exporter.unexport(); channel.removeAttribute(cacheKey); decreaseInstanceCount(channel, countKey); } } return String.valueOf(instid); } /** * refer or destroy callback service on server side * * @param url */ @SuppressWarnings("unchecked") private Object referOrDestroyCallbackService( Channel channel, URL url, Class<?> clazz, Invocation inv, int instid, boolean isRefer) { Object proxy; String invokerCacheKey = getServerSideCallbackInvokerCacheKey(channel, clazz.getName(), instid); String proxyCacheKey = getServerSideCallbackServiceCacheKey(channel, clazz.getName(), instid); proxy = channel.getAttribute(proxyCacheKey); String countkey = getServerSideCountKey(channel, clazz.getName()); if (isRefer) { if (proxy == null) { URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + INTERFACE_KEY + "=" + clazz.getName()); referurl = referurl.addParametersIfAbsent(url.getParameters()) .removeParameter(METHODS_KEY) .addParameter(SIDE_KEY, CONSUMER_SIDE); if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) { url.getOrDefaultApplicationModel() .getDefaultModule() .getServiceRepository() .registerService(clazz); @SuppressWarnings("rawtypes") Invoker<?> invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid)); FilterChainBuilder builder = getFilterChainBuilder(url); invoker = builder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CONSUMER); invoker = builder.buildInvokerChain(invoker, REFERENCE_FILTER_KEY, CommonConstants.CALLBACK); proxy = proxyFactory.getProxy(invoker); channel.setAttribute(proxyCacheKey, proxy); channel.setAttribute(invokerCacheKey, invoker); increaseInstanceCount(channel, countkey); // convert error fail fast . // ignore concurrent problem. Set<Invoker<?>> callbackInvokers = (Set<Invoker<?>>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers == null) { callbackInvokers = new ConcurrentHashSet<>(1); channel.setAttribute(CHANNEL_CALLBACK_KEY, callbackInvokers); } callbackInvokers.add(invoker); logger.info("method " + RpcUtils.getMethodName(inv) + " include a callback service :" + invoker.getUrl() + ", a proxy :" + invoker + " has been created."); } } } else { if (proxy != null) { Invoker<?> invoker = (Invoker<?>) channel.getAttribute(invokerCacheKey); try { Set<Invoker<?>> callbackInvokers = (Set<Invoker<?>>) channel.getAttribute(CHANNEL_CALLBACK_KEY); if (callbackInvokers != null) { callbackInvokers.remove(invoker); } invoker.destroy(); } catch (Exception e) { logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); } // cancel refer, directly remove from the map channel.removeAttribute(proxyCacheKey); channel.removeAttribute(invokerCacheKey); decreaseInstanceCount(channel, countkey); } } return proxy; } private FilterChainBuilder getFilterChainBuilder(URL url) { return ScopeModelUtil.getExtensionLoader(FilterChainBuilder.class, url.getScopeModel()) .getDefaultExtension(); } private static String getClientSideCallbackServiceCacheKey(int instid) { return CALLBACK_SERVICE_KEY + "." + instid; } private static String getServerSideCallbackServiceCacheKey(Channel channel, String interfaceClass, int instid) { return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + instid; } private static String getServerSideCallbackInvokerCacheKey(Channel channel, String interfaceClass, int instid) { return getServerSideCallbackServiceCacheKey(channel, interfaceClass, instid) + "." + "invoker"; } private static String getClientSideCountKey(String interfaceClass) { return CALLBACK_SERVICE_KEY + "." + interfaceClass + ".COUNT"; } private static String getServerSideCountKey(Channel channel, String interfaceClass) { return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + ".COUNT"; } private static boolean isInstancesOverLimit( Channel channel, URL url, String interfaceClass, int instid, boolean isServer) { Integer count = (Integer) channel.getAttribute( isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass)); int limit = url.getParameter(CALLBACK_INSTANCES_LIMIT_KEY, DEFAULT_CALLBACK_INSTANCES); if (count != null && count >= limit) { // client side error throw new IllegalStateException("interface " + interfaceClass + " `s callback instances num exceed providers limit :" + limit + " ,current num: " + (count + 1) + ". The new callback service will not work !!! you can cancle the callback service which exported before. channel :" + channel); } else { return false; } } private static void increaseInstanceCount(Channel channel, String countkey) { try { // ignore concurrent problem? Integer count = (Integer) channel.getAttribute(countkey); if (count == null) { count = 1; } else { count++; } channel.setAttribute(countkey, count); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", e.getMessage(), e); } } private static void decreaseInstanceCount(Channel channel, String countkey) { try { Integer count = (Integer) channel.getAttribute(countkey); if (count == null || count <= 0) { return; } else { count--; } channel.setAttribute(countkey, count); } catch (Exception e) { logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", e.getMessage(), e); } } public Object encodeInvocationArgument(Channel channel, RpcInvocation inv, int paraIndex) throws IOException { // get URL directly URL url = inv.getInvoker() == null ? null : inv.getInvoker().getUrl(); byte callbackStatus = isCallBack(url, inv.getProtocolServiceKey(), RpcUtils.getMethodName(inv), paraIndex); Object[] args = inv.getArguments(); Class<?>[] pts = inv.getParameterTypes(); switch (callbackStatus) { case CallbackServiceCodec.CALLBACK_CREATE: inv.setAttachment( INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], true)); return null; case CallbackServiceCodec.CALLBACK_DESTROY: inv.setAttachment( INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, inv, url, pts[paraIndex], args[paraIndex], false)); return null; default: return args[paraIndex]; } } public Object decodeInvocationArgument( Channel channel, RpcInvocation inv, Class<?>[] pts, int paraIndex, Object inObject) throws IOException { // if it's a callback, create proxy on client side, callback interface on client side can be invoked through // channel // need get URL from channel and env when decode URL url = null; try { url = dubboProtocol.getInvoker(channel, inv).getUrl(); } catch (RemotingException e) { if (logger.isInfoEnabled()) { logger.info(e.getMessage(), e); } return inObject; } byte callbackstatus = isCallBack(url, inv.getProtocolServiceKey(), RpcUtils.getMethodName(inv), paraIndex); switch (callbackstatus) { case CallbackServiceCodec.CALLBACK_CREATE: try { return referOrDestroyCallbackService( channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), true); } catch (Exception e) { logger.error(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", e.getMessage(), e); throw new IOException(StringUtils.toString(e)); } case CallbackServiceCodec.CALLBACK_DESTROY: try { return referOrDestroyCallbackService( channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), false); } catch (Exception e) { throw new IOException(StringUtils.toString(e)); } default: return inObject; } } }
5,862
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboCountCodec.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.remoting.Channel; import org.apache.dubbo.remoting.Codec2; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.Response; import org.apache.dubbo.remoting.exchange.support.MultiMessage; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.FrameworkModel; import java.io.IOException; import static org.apache.dubbo.rpc.Constants.INPUT_KEY; import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY; public final class DubboCountCodec implements Codec2 { private final DubboCodec codec; public DubboCountCodec(FrameworkModel frameworkModel) { codec = new DubboCodec(frameworkModel); } @Override public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException { if (msg instanceof MultiMessage) { MultiMessage multiMessage = (MultiMessage) msg; for (Object singleMessage : multiMessage) { codec.encode(channel, buffer, singleMessage); } } else { codec.encode(channel, buffer, msg); } } @Override public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { int save = buffer.readerIndex(); MultiMessage result = MultiMessage.create(); do { Object obj = codec.decode(channel, buffer); if (Codec2.DecodeResult.NEED_MORE_INPUT == obj) { buffer.readerIndex(save); break; } else { result.addMessage(obj); logMessageLength(obj, buffer.readerIndex() - save); save = buffer.readerIndex(); } } while (true); if (result.isEmpty()) { return Codec2.DecodeResult.NEED_MORE_INPUT; } if (result.size() == 1) { return result.get(0); } return result; } private void logMessageLength(Object result, int bytes) { if (bytes <= 0) { return; } if (result instanceof Request) { try { ((RpcInvocation) ((Request) result).getData()).setAttachment(INPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } } else if (result instanceof Response) { try { ((AppResponse) ((Response) result).getResult()).setAttachment(OUTPUT_KEY, String.valueOf(bytes)); } catch (Throwable e) { /* ignore */ } } } }
5,863
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DubboProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.URLBuilder; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository; import org.apache.dubbo.common.url.component.ServiceConfigURL; 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.RemotingException; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.remoting.Transporter; import org.apache.dubbo.remoting.exchange.ExchangeChannel; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import org.apache.dubbo.remoting.exchange.ExchangeServer; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.remoting.exchange.PortUnificationExchanger; import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; import org.apache.dubbo.remoting.utils.UrlUtils; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; 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.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModel; import org.apache.dubbo.rpc.protocol.AbstractProtocol; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; 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.LAZY_CONNECT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_ERROR_CLOSE_SERVER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED; import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; import static org.apache.dubbo.remoting.Constants.CODEC_KEY; import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; import static org.apache.dubbo.remoting.Constants.DEFAULT_HEARTBEAT; import static org.apache.dubbo.remoting.Constants.DEFAULT_REMOTING_CLIENT; import static org.apache.dubbo.remoting.Constants.HEARTBEAT_KEY; import static org.apache.dubbo.remoting.Constants.SERVER_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_REMOTING_SERVER; 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.STUB_EVENT_METHODS_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.DEFAULT_SHARE_CONNECTIONS; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_CONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ON_DISCONNECT_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.SHARE_CONNECTIONS_KEY; /** * dubbo protocol support. */ public class DubboProtocol extends AbstractProtocol { public static final String NAME = "dubbo"; public static final int DEFAULT_PORT = 20880; private static final String IS_CALLBACK_SERVICE_INVOKE = "_isCallBackServiceInvoke"; /** * <host:port,Exchanger> * Map<String, List<ReferenceCountExchangeClient> */ private final Map<String, SharedClientsProvider> referenceClientMap = new ConcurrentHashMap<>(); private final AtomicBoolean destroyed = new AtomicBoolean(); private final ExchangeHandler requestHandler; public DubboProtocol(FrameworkModel frameworkModel) { requestHandler = new ExchangeHandlerAdapter(frameworkModel) { @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object message) throws RemotingException { if (!(message instanceof Invocation)) { throw new RemotingException( channel, "Unsupported request: " + (message == null ? null : (message.getClass().getName() + ": " + message)) + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress()); } Invocation inv = (Invocation) message; Invoker<?> invoker = inv.getInvoker() == null ? getInvoker(channel, inv) : inv.getInvoker(); // switch TCCL if (invoker.getUrl().getServiceModel() != null) { Thread.currentThread() .setContextClassLoader( invoker.getUrl().getServiceModel().getClassLoader()); } // need to consider backward-compatibility if it's a callback if (Boolean.TRUE.toString().equals(inv.getObjectAttachmentWithoutConvert(IS_CALLBACK_SERVICE_INVOKE))) { String methodsStr = invoker.getUrl().getParameters().get("methods"); boolean hasMethod = false; if (methodsStr == null || !methodsStr.contains(",")) { hasMethod = inv.getMethodName().equals(methodsStr); } else { String[] methods = methodsStr.split(","); for (String method : methods) { if (inv.getMethodName().equals(method)) { hasMethod = true; break; } } } if (!hasMethod) { logger.warn( PROTOCOL_FAILED_REFER_INVOKER, "", "", new IllegalStateException("The methodName " + inv.getMethodName() + " not found in callback service interface ,invoke will be ignored." + " please update the api interface. url is:" + invoker.getUrl()) + " ,invocation is :" + inv); return null; } } RpcContext.getServiceContext().setRemoteAddress(channel.getRemoteAddress()); Result result = invoker.invoke(inv); return result.thenApply(Function.identity()); } @Override public void received(Channel channel, Object message) throws RemotingException { if (message instanceof Invocation) { reply((ExchangeChannel) channel, message); } else { super.received(channel, message); } } @Override public void connected(Channel channel) throws RemotingException { invoke(channel, ON_CONNECT_KEY); } @Override public void disconnected(Channel channel) throws RemotingException { if (logger.isDebugEnabled()) { logger.debug("disconnected from " + channel.getRemoteAddress() + ",url:" + channel.getUrl()); } invoke(channel, ON_DISCONNECT_KEY); } private void invoke(Channel channel, String methodKey) { Invocation invocation = createInvocation(channel, channel.getUrl(), methodKey); if (invocation != null) { try { if (Boolean.TRUE.toString().equals(invocation.getAttachment(STUB_EVENT_KEY))) { tryToGetStubService(channel, invocation); } received(channel, invocation); } catch (Throwable t) { logger.warn( PROTOCOL_FAILED_REFER_INVOKER, "", "", "Failed to invoke event method " + invocation.getMethodName() + "(), cause: " + t.getMessage(), t); } } } private void tryToGetStubService(Channel channel, Invocation invocation) throws RemotingException { try { Invoker<?> invoker = getInvoker(channel, invocation); } catch (RemotingException e) { String serviceKey = serviceKey( 0, (String) invocation.getObjectAttachmentWithoutConvert(PATH_KEY), (String) invocation.getObjectAttachmentWithoutConvert(VERSION_KEY), (String) invocation.getObjectAttachmentWithoutConvert(GROUP_KEY)); throw new RemotingException( channel, "The stub service[" + serviceKey + "] is not found, it may not be exported yet"); } } /** * FIXME channel.getUrl() always binds to a fixed service, and this service is random. * we can choose to use a common service to carry onConnect event if there's no easy way to get the specific * service this connection is binding to. * @param channel * @param url * @param methodKey * @return */ private Invocation createInvocation(Channel channel, URL url, String methodKey) { String method = url.getParameter(methodKey); if (method == null || method.length() == 0) { return null; } RpcInvocation invocation = new RpcInvocation( url.getServiceModel(), method, url.getParameter(INTERFACE_KEY), "", new Class<?>[0], new Object[0]); invocation.setAttachment(PATH_KEY, url.getPath()); invocation.setAttachment(GROUP_KEY, url.getGroup()); invocation.setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY)); invocation.setAttachment(VERSION_KEY, url.getVersion()); if (url.getParameter(STUB_EVENT_KEY, false)) { invocation.setAttachment(STUB_EVENT_KEY, Boolean.TRUE.toString()); } return invocation; } }; this.frameworkModel = frameworkModel; this.frameworkModel.getBeanFactory().registerBean(new DubboGracefulShutdown(this)); } /** * @deprecated Use {@link DubboProtocol#getDubboProtocol(ScopeModel)} instead */ @Deprecated public static DubboProtocol getDubboProtocol() { return (DubboProtocol) FrameworkModel.defaultModel() .getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME, false); } public static DubboProtocol getDubboProtocol(ScopeModel scopeModel) { return (DubboProtocol) scopeModel.getExtensionLoader(Protocol.class).getExtension(DubboProtocol.NAME, false); } private boolean isClientSide(Channel channel) { InetSocketAddress address = channel.getRemoteAddress(); URL url = channel.getUrl(); return url.getPort() == address.getPort() && NetUtils.filterLocalHost(channel.getUrl().getIp()) .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); } Invoker<?> getInvoker(Channel channel, Invocation inv) throws RemotingException { boolean isCallBackServiceInvoke; boolean isStubServiceInvoke; int port = channel.getLocalAddress().getPort(); String path = (String) inv.getObjectAttachmentWithoutConvert(PATH_KEY); // if it's stub service on client side(after enable stubevent, usually is set up onconnect or ondisconnect // method) isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getObjectAttachmentWithoutConvert(STUB_EVENT_KEY)); if (isStubServiceInvoke) { // when a stub service export to local, it usually can't be exposed to port port = 0; } // if it's callback service on client side isCallBackServiceInvoke = isClientSide(channel) && !isStubServiceInvoke; if (isCallBackServiceInvoke) { path += "." + inv.getObjectAttachmentWithoutConvert(CALLBACK_SERVICE_KEY); inv.setObjectAttachment(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); } String serviceKey = serviceKey(port, path, (String) inv.getObjectAttachmentWithoutConvert(VERSION_KEY), (String) inv.getObjectAttachmentWithoutConvert(GROUP_KEY)); DubboExporter<?> exporter = (DubboExporter<?>) exporterMap.get(serviceKey); if (exporter == null) { throw new RemotingException( channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + getInvocationWithoutData(inv)); } Invoker<?> invoker = exporter.getInvoker(); inv.setServiceModel(invoker.getUrl().getServiceModel()); return invoker; } public Collection<Invoker<?>> getInvokers() { return Collections.unmodifiableCollection(invokers); } @Override public int getDefaultPort() { return DEFAULT_PORT; } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { checkDestroyed(); URL url = invoker.getUrl(); // export service. String key = serviceKey(url); DubboExporter<T> exporter = new DubboExporter<T>(invoker, key, exporterMap); // export a stub service for dispatching event boolean isStubSupportEvent = url.getParameter(STUB_EVENT_KEY, DEFAULT_STUB_EVENT); boolean isCallbackService = url.getParameter(IS_CALLBACK_SERVICE, false); if (isStubSupportEvent && !isCallbackService) { String stubServiceMethods = url.getParameter(STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0) { if (logger.isWarnEnabled()) { logger.warn( PROTOCOL_UNSUPPORTED, "", "", "consumer [" + url.getParameter(INTERFACE_KEY) + "], has set stub proxy support event ,but no stub methods founded."); } } } openServer(url); optimizeSerialization(url); return exporter; } private void openServer(URL url) { checkDestroyed(); // find server. String key = url.getAddress(); // client can export a service which only for server to invoke boolean isServer = url.getParameter(IS_SERVER_KEY, true); if (isServer) { ProtocolServer server = serverMap.get(key); if (server == null) { synchronized (this) { server = serverMap.get(key); if (server == null) { serverMap.put(key, createServer(url)); return; } } } // server supports reset, use together with override server.reset(url); } } private void checkDestroyed() { if (destroyed.get()) { throw new IllegalStateException(getClass().getSimpleName() + " is destroyed"); } } private ProtocolServer createServer(URL url) { url = URLBuilder.from(url) // send readonly event when server closes, it's enabled by default .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()) // enable heartbeat by default .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT)) .addParameter(CODEC_KEY, DubboCodec.NAME) .build(); String transporter = url.getParameter(SERVER_KEY, DEFAULT_REMOTING_SERVER); if (StringUtils.isNotEmpty(transporter) && !url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .hasExtension(transporter)) { throw new RpcException("Unsupported server type: " + transporter + ", url: " + url); } ExchangeServer server; try { server = Exchangers.bind(url, requestHandler); } catch (RemotingException e) { throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); } transporter = url.getParameter(CLIENT_KEY); if (StringUtils.isNotEmpty(transporter) && !url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .hasExtension(transporter)) { throw new RpcException("Unsupported client type: " + transporter); } DubboProtocolServer protocolServer = new DubboProtocolServer(server); loadServerProperties(protocolServer); return protocolServer; } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { checkDestroyed(); return protocolBindingRefer(type, url); } @Override public <T> Invoker<T> protocolBindingRefer(Class<T> serviceType, URL url) throws RpcException { checkDestroyed(); optimizeSerialization(url); // create rpc invoker. DubboInvoker<T> invoker = new DubboInvoker<T>(serviceType, url, getClients(url), invokers); invokers.add(invoker); return invoker; } private ClientsProvider getClients(URL url) { int connections = url.getParameter(CONNECTIONS_KEY, 0); // whether to share connection // if not configured, connection is shared, otherwise, one connection for one service if (connections == 0) { /* * The xml configuration should have a higher priority than properties. */ String shareConnectionsStr = StringUtils.isBlank(url.getParameter(SHARE_CONNECTIONS_KEY, (String) null)) ? ConfigurationUtils.getProperty( url.getOrDefaultApplicationModel(), SHARE_CONNECTIONS_KEY, DEFAULT_SHARE_CONNECTIONS) : url.getParameter(SHARE_CONNECTIONS_KEY, (String) null); connections = Integer.parseInt(shareConnectionsStr); return getSharedClient(url, connections); } List<ExchangeClient> clients = IntStream.range(0, connections).mapToObj((i) -> initClient(url)).collect(Collectors.toList()); return new ExclusiveClientsProvider(clients); } /** * Get shared connection * * @param url * @param connectNum connectNum must be greater than or equal to 1 */ @SuppressWarnings("unchecked") private SharedClientsProvider getSharedClient(URL url, int connectNum) { String key = url.getAddress(); // connectNum must be greater than or equal to 1 int expectedConnectNum = Math.max(connectNum, 1); return referenceClientMap.compute(key, (originKey, originValue) -> { if (originValue != null && originValue.increaseCount()) { return originValue; } else { return new SharedClientsProvider( this, originKey, buildReferenceCountExchangeClientList(url, expectedConnectNum)); } }); } protected void scheduleRemoveSharedClient(String key, SharedClientsProvider sharedClient) { this.frameworkModel .getBeanFactory() .getBean(FrameworkExecutorRepository.class) .getSharedExecutor() .submit(() -> referenceClientMap.remove(key, sharedClient)); } /** * Bulk build client * * @param url * @param connectNum * @return */ private List<ReferenceCountExchangeClient> buildReferenceCountExchangeClientList(URL url, int connectNum) { List<ReferenceCountExchangeClient> clients = new ArrayList<>(); for (int i = 0; i < connectNum; i++) { clients.add(buildReferenceCountExchangeClient(url)); } return clients; } /** * Build a single client * * @param url * @return */ private ReferenceCountExchangeClient buildReferenceCountExchangeClient(URL url) { ExchangeClient exchangeClient = initClient(url); ReferenceCountExchangeClient client = new ReferenceCountExchangeClient(exchangeClient, DubboCodec.NAME); // read configs int shutdownTimeout = ConfigurationUtils.getServerShutdownTimeout(url.getScopeModel()); client.setShutdownWaitTime(shutdownTimeout); return client; } /** * Create new connection * * @param url */ private ExchangeClient initClient(URL url) { /* * Instance of url is InstanceAddressURL, so addParameter actually adds parameters into ServiceInstance, * which means params are shared among different services. Since client is shared among services this is currently not a problem. */ String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT)); // BIO is not allowed since it has severe performance issue. if (StringUtils.isNotEmpty(str) && !url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .hasExtension(str)) { throw new RpcException("Unsupported client type: " + str + "," + " supported client type is " + StringUtils.join( url.getOrDefaultFrameworkModel() .getExtensionLoader(Transporter.class) .getSupportedExtensions(), " ")); } try { ScopeModel scopeModel = url.getScopeModel(); int heartbeat = UrlUtils.getHeartbeat(url); // Replace InstanceAddressURL with ServiceConfigURL. url = new ServiceConfigURL( DubboCodec.NAME, url.getUsername(), url.getPassword(), url.getHost(), url.getPort(), url.getPath(), url.getAllParameters()); url = url.addParameter(CODEC_KEY, DubboCodec.NAME); // enable heartbeat by default url = url.addParameterIfAbsent(HEARTBEAT_KEY, Integer.toString(heartbeat)); url = url.setScopeModel(scopeModel); // connection should be lazy return url.getParameter(LAZY_CONNECT_KEY, false) ? new LazyConnectExchangeClient(url, requestHandler) : Exchangers.connect(url, requestHandler); } catch (RemotingException e) { throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e); } } @Override @SuppressWarnings("unchecked") public void destroy() { if (!destroyed.compareAndSet(false, true)) { return; } if (logger.isInfoEnabled()) { logger.info("Destroying protocol [" + this.getClass().getSimpleName() + "] ..."); } for (String key : new ArrayList<>(serverMap.keySet())) { ProtocolServer protocolServer = serverMap.remove(key); if (protocolServer == null) { continue; } RemotingServer server = protocolServer.getRemotingServer(); try { if (logger.isInfoEnabled()) { logger.info("Closing dubbo server: " + server.getLocalAddress()); } server.close(ConfigurationUtils.reCalShutdownTime(getServerShutdownTimeout(protocolServer))); } catch (Throwable t) { logger.warn( PROTOCOL_ERROR_CLOSE_SERVER, "", "", "Close dubbo server [" + server.getLocalAddress() + "] failed: " + t.getMessage(), t); } } serverMap.clear(); for (String key : new ArrayList<>(referenceClientMap.keySet())) { SharedClientsProvider clients = referenceClientMap.remove(key); clients.forceClose(); } PortUnificationExchanger.close(); referenceClientMap.clear(); super.destroy(); } /** * only log body in debugger mode for size & security consideration. * * @param invocation * @return */ private Invocation getInvocationWithoutData(Invocation invocation) { if (logger.isDebugEnabled()) { return invocation; } if (invocation instanceof RpcInvocation) { RpcInvocation rpcInvocation = (RpcInvocation) invocation; rpcInvocation.setArguments(null); return rpcInvocation; } return invocation; } }
5,864
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ClientsProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.remoting.exchange.ExchangeClient; import java.util.List; public interface ClientsProvider { List<? extends ExchangeClient> getClients(); void close(int timeout); }
5,865
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ChannelWrappedInvoker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.TimeoutException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.exchange.support.header.HeaderExchangeClient; import org.apache.dubbo.remoting.transport.ClientDelegate; import org.apache.dubbo.rpc.AppResponse; import org.apache.dubbo.rpc.AsyncRpcResult; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.protocol.AbstractInvoker; import org.apache.dubbo.rpc.support.RpcUtils; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.remoting.Constants.SENT_KEY; import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY; /** * Server push uses this Invoker to continuously push data to client. * Wrap the existing invoker on the channel. */ class ChannelWrappedInvoker<T> extends AbstractInvoker<T> { private final Channel channel; private final String serviceKey; private final ExchangeClient currentClient; ChannelWrappedInvoker(Class<T> serviceType, Channel channel, URL url, String serviceKey) { super(serviceType, url, new String[] {GROUP_KEY, TOKEN_KEY}); this.channel = channel; this.serviceKey = serviceKey; this.currentClient = new HeaderExchangeClient(new ChannelWrapper(this.channel), false); } @Override @SuppressWarnings("deprecation") protected Result doInvoke(Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; // use interface's name as service path to export if it's not found on client side inv.setAttachment(PATH_KEY, getInterface().getName()); inv.setAttachment(CALLBACK_SERVICE_KEY, serviceKey); Integer payload = getUrl().getParameter(PAYLOAD, Integer.class); Request request = new Request(); if (payload != null) { request.setPayload(payload); } request.setData(inv); request.setVersion(Version.getProtocolVersion()); try { if (RpcUtils.isOneway(getUrl(), inv)) { // may have concurrency issue currentClient.send( request, getUrl().getMethodParameter(RpcUtils.getMethodName(invocation), SENT_KEY, false)); return AsyncRpcResult.newDefaultAsyncResult(invocation); } else { CompletableFuture<AppResponse> appResponseFuture = currentClient.request(request).thenApply(AppResponse.class::cast); return new AsyncRpcResult(appResponseFuture, inv); } } catch (RpcException e) { throw e; } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, e.getMessage(), e); } catch (RemotingException e) { throw new RpcException(RpcException.NETWORK_EXCEPTION, e.getMessage(), e); } catch (Throwable e) { // here is non-biz exception, wrap it. throw new RpcException(e.getMessage(), e); } } @Override public void destroy() { // super.destroy(); // try { // channel.close(); // } catch (Throwable t) { // logger.warn(t.getMessage(), t); // } } public static class ChannelWrapper extends ClientDelegate { private final Channel channel; private final URL url; ChannelWrapper(Channel channel) { this.channel = channel; this.url = channel.getUrl().addParameter("codec", DubboCodec.NAME); } @Override public URL getUrl() { return url; } @Override public ChannelHandler getChannelHandler() { return channel.getChannelHandler(); } @Override public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } @Override public void close() { channel.close(); } @Override public boolean isClosed() { return channel == null || channel.isClosed(); } @Override public void reset(URL url) { throw new RpcException("ChannelInvoker can not reset."); } @Override public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } @Override public boolean isConnected() { return channel != null && channel.isConnected(); } @Override public boolean hasAttribute(String key) { return channel.hasAttribute(key); } @Override public Object getAttribute(String key) { return channel.getAttribute(key); } @Override public void setAttribute(String key, Object value) { channel.setAttribute(key, value); } @Override public void removeAttribute(String key) { channel.removeAttribute(key); } @Override public void reconnect() throws RemotingException {} @Override public void send(Object message) throws RemotingException { channel.send(message); } @Override public void send(Object message, boolean sent) throws RemotingException { channel.send(message, sent); } } }
5,866
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.serialize.Cleanable; import org.apache.dubbo.common.serialize.ObjectInput; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.CacheableSupplier; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.Codec; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.remoting.Decodeable; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.Request; import org.apache.dubbo.remoting.transport.CodecSupport; import org.apache.dubbo.remoting.transport.ExceedPayloadLimitException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.MethodDescriptor; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper; import org.apache.dubbo.rpc.support.RpcUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.Map; import java.util.function.Supplier; import static org.apache.dubbo.common.BaseServiceMetadata.keyWithoutGroup; import static org.apache.dubbo.common.URL.buildKey; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PAYLOAD; import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DECODE; import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_EXCEED_PAYLOAD_LIMIT; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_ID_KEY; import static org.apache.dubbo.rpc.Constants.SERIALIZATION_SECURITY_CHECK_KEY; public class DecodeableRpcInvocation extends RpcInvocation implements Codec, Decodeable { protected static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(DecodeableRpcInvocation.class); protected final transient Channel channel; protected final byte serializationType; protected final transient InputStream inputStream; protected final transient Request request; protected volatile boolean hasDecoded; protected final FrameworkModel frameworkModel; protected final transient Supplier<CallbackServiceCodec> callbackServiceCodecFactory; private static final boolean CHECK_SERIALIZATION = Boolean.parseBoolean(System.getProperty(SERIALIZATION_SECURITY_CHECK_KEY, "true")); public DecodeableRpcInvocation( FrameworkModel frameworkModel, Channel channel, Request request, InputStream is, byte id) { this.frameworkModel = frameworkModel; Assert.notNull(channel, "channel == null"); Assert.notNull(request, "request == null"); Assert.notNull(is, "inputStream == null"); this.channel = channel; this.request = request; this.inputStream = is; this.serializationType = id; this.callbackServiceCodecFactory = CacheableSupplier.newSupplier(() -> new CallbackServiceCodec(frameworkModel)); } @Override public void decode() throws Exception { if (!hasDecoded && channel != null && inputStream != null) { try { decode(channel, inputStream); } catch (Throwable e) { if (log.isWarnEnabled()) { log.warn(PROTOCOL_FAILED_DECODE, "", "", "Decode rpc invocation failed: " + e.getMessage(), e); } request.setBroken(true); request.setData(e); } finally { hasDecoded = true; } } } @Override public void encode(Channel channel, OutputStream output, Object message) throws IOException { throw new UnsupportedOperationException(); } @Override public Object decode(Channel channel, InputStream input) throws IOException { int contentLength = input.available(); getAttributes().put(Constants.CONTENT_LENGTH_KEY, contentLength); ObjectInput in = CodecSupport.getSerialization(serializationType).deserialize(channel.getUrl(), input); this.put(SERIALIZATION_ID_KEY, serializationType); String dubboVersion = in.readUTF(); request.setVersion(dubboVersion); setAttachment(DUBBO_VERSION_KEY, dubboVersion); String path = in.readUTF(); setAttachment(PATH_KEY, path); String version = in.readUTF(); setAttachment(VERSION_KEY, version); // Do provider-level payload checks. String keyWithoutGroup = keyWithoutGroup(path, version); checkPayload(keyWithoutGroup); setMethodName(in.readUTF()); String desc = in.readUTF(); setParameterTypesDesc(desc); ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); try { if (CHECK_SERIALIZATION) { PermittedSerializationKeeper keeper = frameworkModel.getBeanFactory().getBean(PermittedSerializationKeeper.class); if (!keeper.checkSerializationPermitted(keyWithoutGroup, serializationType)) { throw new IOException("Unexpected serialization id:" + serializationType + " received from network, please check if the peer send the right id."); } } Object[] args = DubboCodec.EMPTY_OBJECT_ARRAY; Class<?>[] pts = DubboCodec.EMPTY_CLASS_ARRAY; if (desc.length() > 0) { pts = drawPts(path, version, desc, pts); if (pts == DubboCodec.EMPTY_CLASS_ARRAY) { if (RpcUtils.isGenericCall(desc, getMethodName())) { // Should recreate here for each invocation because the parameterTypes may be changed by user. pts = new Class<?>[] {String.class, String[].class, Object[].class}; } else if (RpcUtils.isEcho(desc, getMethodName())) { pts = new Class<?>[] {Object.class}; } else { throw new IllegalArgumentException("Service not found:" + path + ", " + getMethodName()); } } args = drawArgs(in, pts); } setParameterTypes(pts); Map<String, Object> map = in.readAttachments(); if (CollectionUtils.isNotEmptyMap(map)) { addObjectAttachments(map); } decodeArgument(channel, pts, args); } catch (ClassNotFoundException e) { throw new IOException(StringUtils.toString("Read invocation data failed.", e)); } finally { Thread.currentThread().setContextClassLoader(originClassLoader); if (in instanceof Cleanable) { ((Cleanable) in).cleanup(); } } return this; } protected void decodeArgument(Channel channel, Class<?>[] pts, Object[] args) throws IOException { CallbackServiceCodec callbackServiceCodec = callbackServiceCodecFactory.get(); for (int i = 0; i < args.length; i++) { args[i] = callbackServiceCodec.decodeInvocationArgument(channel, this, pts, i, args[i]); } setArguments(args); String targetServiceName = buildKey(getAttachment(PATH_KEY), getAttachment(GROUP_KEY), getAttachment(VERSION_KEY)); setTargetServiceUniqueName(targetServiceName); } protected Class<?>[] drawPts(String path, String version, String desc, Class<?>[] pts) { FrameworkServiceRepository repository = frameworkModel.getServiceRepository(); List<ProviderModel> providerModels = repository.lookupExportedServicesWithoutGroup(keyWithoutGroup(path, version)); ServiceDescriptor serviceDescriptor = null; if (CollectionUtils.isNotEmpty(providerModels)) { for (ProviderModel providerModel : providerModels) { serviceDescriptor = providerModel.getServiceModel(); if (serviceDescriptor != null) { break; } } } if (serviceDescriptor == null) { // Unable to find ProviderModel from Exported Services for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { for (ModuleModel moduleModel : applicationModel.getModuleModels()) { serviceDescriptor = moduleModel.getServiceRepository().lookupService(path); if (serviceDescriptor != null) { break; } } } } if (serviceDescriptor != null) { MethodDescriptor methodDescriptor = serviceDescriptor.getMethod(getMethodName(), desc); if (methodDescriptor != null) { pts = methodDescriptor.getParameterClasses(); this.setReturnTypes(methodDescriptor.getReturnTypes()); // switch TCCL if (CollectionUtils.isNotEmpty(providerModels)) { if (providerModels.size() == 1) { Thread.currentThread() .setContextClassLoader(providerModels.get(0).getClassLoader()); } else { // try all providerModels' classLoader can load pts, use the first one for (ProviderModel providerModel : providerModels) { ClassLoader classLoader = providerModel.getClassLoader(); boolean match = true; for (Class<?> pt : pts) { try { if (!pt.equals(classLoader.loadClass(pt.getName()))) { match = false; } } catch (ClassNotFoundException e) { match = false; } } if (match) { Thread.currentThread().setContextClassLoader(classLoader); break; } } } } } } return pts; } protected Object[] drawArgs(ObjectInput in, Class<?>[] pts) throws IOException, ClassNotFoundException { Object[] args; args = new Object[pts.length]; for (int i = 0; i < args.length; i++) { args[i] = in.readObject(pts[i]); } return args; } private void checkPayload(String serviceKey) throws IOException { ProviderModel providerModel = frameworkModel.getServiceRepository().lookupExportedServiceWithoutGroup(serviceKey); if (providerModel != null) { String payloadStr = (String) providerModel.getServiceMetadata().getAttachments().get(PAYLOAD); if (payloadStr != null) { int payload = Integer.parseInt(payloadStr); if (payload <= 0) { return; } if (request.getPayload() > payload) { ExceedPayloadLimitException e = new ExceedPayloadLimitException("Data length too large: " + request.getPayload() + ", max payload: " + payload + ", channel: " + channel); log.error(TRANSPORT_EXCEED_PAYLOAD_LIMIT, "", "", e.getMessage(), e); throw e; } } } } protected void fillInvoker(DubboProtocol dubboProtocol) throws RemotingException { this.setInvoker(dubboProtocol.getInvoker(channel, this)); } }
5,867
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/ReferenceCountExchangeClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.Parameters; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.ExchangeHandler; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; /** * dubbo protocol support class. */ @SuppressWarnings("deprecation") final class ReferenceCountExchangeClient implements ExchangeClient { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceCountExchangeClient.class); private final URL url; private final AtomicInteger referenceCount = new AtomicInteger(0); private final AtomicInteger disconnectCount = new AtomicInteger(0); private static final Integer warningPeriod = 50; private ExchangeClient client; private int shutdownWaitTime = DEFAULT_SERVER_SHUTDOWN_TIMEOUT; public ReferenceCountExchangeClient(ExchangeClient client, String codec) { this.client = client; this.referenceCount.incrementAndGet(); this.url = client.getUrl(); } @Override public void reset(URL url) { client.reset(url); } @Override public CompletableFuture<Object> request(Object request) throws RemotingException { return client.request(request); } @Override public URL getUrl() { return client.getUrl(); } @Override public InetSocketAddress getRemoteAddress() { return client.getRemoteAddress(); } @Override public ChannelHandler getChannelHandler() { return client.getChannelHandler(); } @Override public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException { return client.request(request, timeout); } @Override public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException { return client.request(request, executor); } @Override public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException { return client.request(request, timeout, executor); } @Override public boolean isConnected() { return client.isConnected(); } @Override public void reconnect() throws RemotingException { client.reconnect(); } @Override public InetSocketAddress getLocalAddress() { return client.getLocalAddress(); } @Override public boolean hasAttribute(String key) { return client.hasAttribute(key); } @Override public void reset(Parameters parameters) { client.reset(parameters); } @Override public void send(Object message) throws RemotingException { client.send(message); } @Override public ExchangeHandler getExchangeHandler() { return client.getExchangeHandler(); } @Override public Object getAttribute(String key) { return client.getAttribute(key); } @Override public void send(Object message, boolean sent) throws RemotingException { client.send(message, sent); } @Override public void setAttribute(String key, Object value) { client.setAttribute(key, value); } @Override public void removeAttribute(String key) { client.removeAttribute(key); } /** * close() is not idempotent any longer */ @Override public void close() { close(0); } @Override public void close(int timeout) { if (referenceCount.decrementAndGet() <= 0) { if (timeout == 0) { client.close(); } else { client.close(timeout); } replaceWithLazyClient(); } } @Override public void startClose() { client.startClose(); } /** * when closing the client, the client needs to be set to LazyConnectExchangeClient, and if a new call is made, * the client will "resurrect". * * @return */ private void replaceWithLazyClient() { // start warning at second replaceWithLazyClient() if (disconnectCount.getAndIncrement() % warningPeriod == 1) { logger.warn( PROTOCOL_FAILED_REQUEST, "", "", url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug."); } // the order of judgment in the if statement cannot be changed. if (!(client instanceof LazyConnectExchangeClient)) { client = new LazyConnectExchangeClient(url, client.getExchangeHandler()); } } @Override public boolean isClosed() { return client.isClosed(); } /** * The reference count of current ExchangeClient, connection will be closed if all invokers destroyed. */ public void incrementAndGetCount() { referenceCount.incrementAndGet(); } public int getCount() { return referenceCount.get(); } public int getShutdownWaitTime() { return shutdownWaitTime; } public void setShutdownWaitTime(int shutdownWaitTime) { this.shutdownWaitTime = shutdownWaitTime; } }
5,868
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.rpc.protocol.dubbo; /** * */ public interface Constants { String SHARE_CONNECTIONS_KEY = "shareconnections"; /** * By default, a consumer JVM instance and a provider JVM instance share a long TCP connection (except when connections are set), * which can set the number of long TCP connections shared to avoid the bottleneck of sharing a single long TCP connection. */ String DEFAULT_SHARE_CONNECTIONS = "1"; String DECODE_IN_IO_THREAD_KEY = "decode.in.io"; boolean DEFAULT_DECODE_IN_IO_THREAD = false; /** * callback inst id */ String CALLBACK_SERVICE_KEY = "callback.service.instid"; String CALLBACK_SERVICE_PROXY_KEY = "callback.service.proxy"; String IS_CALLBACK_SERVICE = "is_callback_service"; /** * Invokers in channel's callback */ String CHANNEL_CALLBACK_KEY = "channel.callback.invokers.key"; /** * when this warning rises from invocation, program probably have a bug. */ String LAZY_REQUEST_WITH_WARNING_KEY = "lazyclient_request_with_warning"; boolean DEFAULT_LAZY_REQUEST_WITH_WARNING = false; String ON_CONNECT_KEY = "onconnect"; String ON_DISCONNECT_KEY = "ondisconnect"; String ASYNC_METHOD_INFO = "async-method-info"; }
5,869
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ServerStatusChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.remoting.RemotingServer; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import java.util.List; /** * ServerStatusChecker */ @Activate public class ServerStatusChecker implements StatusChecker { @Override public Status check() { List<ProtocolServer> servers = DubboProtocol.getDubboProtocol().getServers(); if (servers == null || servers.isEmpty()) { return new Status(Status.Level.UNKNOWN); } Status.Level level = Status.Level.OK; StringBuilder buf = new StringBuilder(); for (ProtocolServer protocolServer : servers) { RemotingServer server = protocolServer.getRemotingServer(); if (!server.isBound()) { level = Status.Level.ERROR; buf.setLength(0); buf.append(server.getLocalAddress()); break; } if (buf.length() > 0) { buf.append(','); } buf.append(server.getLocalAddress()); buf.append("(clients:"); buf.append(server.getChannels().size()); buf.append(')'); } return new Status(level, buf.toString()); } }
5,870
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/status/ThreadPoolStatusChecker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.status; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.common.status.StatusChecker; import org.apache.dubbo.common.store.DataStore; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; /** * ThreadPoolStatusChecker */ @Activate public class ThreadPoolStatusChecker implements StatusChecker { private final ApplicationModel applicationModel; public ThreadPoolStatusChecker(ApplicationModel applicationModel) { this.applicationModel = applicationModel; } @Override public Status check() { DataStore dataStore = applicationModel.getExtensionLoader(DataStore.class).getDefaultExtension(); Map<String, Object> executors = dataStore.get(CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY); StringBuilder msg = new StringBuilder(); Status.Level level = Status.Level.OK; for (Map.Entry<String, Object> entry : executors.entrySet()) { String port = entry.getKey(); ExecutorService executor = (ExecutorService) entry.getValue(); if (executor instanceof ThreadPoolExecutor) { ThreadPoolExecutor tp = (ThreadPoolExecutor) executor; boolean ok = tp.getActiveCount() < tp.getMaximumPoolSize() - 1; Status.Level lvl = Status.Level.OK; if (!ok) { level = Status.Level.WARN; lvl = Status.Level.WARN; } if (msg.length() > 0) { msg.append(';'); } msg.append("Pool status:") .append(lvl) .append(", max:") .append(tp.getMaximumPoolSize()) .append(", core:") .append(tp.getCorePoolSize()) .append(", largest:") .append(tp.getLargestPoolSize()) .append(", active:") .append(tp.getActiveCount()) .append(", task:") .append(tp.getTaskCount()) .append(", service port: ") .append(port); } } return msg.length() == 0 ? new Status(Status.Level.UNKNOWN) : new Status(level, msg.toString()); } }
5,871
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboDetector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.pu; import org.apache.dubbo.remoting.api.ProtocolDetector; import org.apache.dubbo.remoting.buffer.ByteBufferBackedChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffer; import org.apache.dubbo.remoting.buffer.ChannelBuffers; import java.nio.ByteBuffer; import static java.lang.Math.min; public class DubboDetector implements ProtocolDetector { private final ChannelBuffer Preface = new ByteBufferBackedChannelBuffer(ByteBuffer.wrap(new byte[] {(byte) 0xda, (byte) 0xbb})); @Override public Result detect(ChannelBuffer in) { int prefaceLen = Preface.readableBytes(); int bytesRead = min(in.readableBytes(), prefaceLen); if (bytesRead == 0 || !ChannelBuffers.prefixEquals(in, Preface, bytesRead)) { return Result.UNRECOGNIZED; } if (bytesRead == prefaceLen) { return Result.RECOGNIZED; } return Result.NEED_MORE_DATA; } }
5,872
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/pu/DubboWireProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.pu; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.api.AbstractWireProtocol; import org.apache.dubbo.remoting.api.pu.ChannelOperator; import java.util.ArrayList; import java.util.List; @Activate public class DubboWireProtocol extends AbstractWireProtocol { public DubboWireProtocol() { super(new DubboDetector()); } @Override public void configServerProtocolHandler(URL url, ChannelOperator operator) { List<ChannelHandler> handlers = new ArrayList<>(); // operator(for now nettyOperator)'s duties // 1. config codec2 for the protocol(load by extension loader) // 2. config handlers passed by wire protocol // ( for triple, some h2 netty handler and logic handler to handle connection; // for dubbo, nothing, an empty handlers is used to trigger operator logic) // 3. config Dubbo Inner handler(for dubbo protocol, this handler handles connection) operator.configChannelHandler(handlers); } }
5,873
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/FutureFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.ClusterFilter; import org.apache.dubbo.rpc.model.AsyncMethodInfo; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ServiceModel; import org.apache.dubbo.rpc.support.RpcUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REQUEST; import static org.apache.dubbo.rpc.protocol.dubbo.Constants.ASYNC_METHOD_INFO; /** * EventFilter */ @Activate(group = CommonConstants.CONSUMER) public class FutureFilter implements ClusterFilter, ClusterFilter.Listener { protected static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(FutureFilter.class); @Override public Result invoke(final Invoker<?> invoker, final Invocation invocation) throws RpcException { fireInvokeCallback(invoker, invocation); // need to configure if there's return value before the invocation in order to help invoker to judge if it's // necessary to return future. return invoker.invoke(invocation); } @Override public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) { if (result.hasException()) { fireThrowCallback(invoker, invocation, result.getException()); } else { fireReturnCallback(invoker, invocation, result.getValue()); } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { fireThrowCallback(invoker, invocation, t); } private void fireInvokeCallback(final Invoker<?> invoker, final Invocation invocation) { final AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onInvokeMethod = asyncMethodInfo.getOninvokeMethod(); final Object onInvokeInst = asyncMethodInfo.getOninvokeInstance(); if (onInvokeMethod == null && onInvokeInst == null) { return; } if (onInvokeMethod == null || onInvokeInst == null) { throw new IllegalStateException( "service:" + invoker.getUrl().getServiceKey() + " has a oninvoke callback config , but no such " + (onInvokeMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onInvokeMethod.isAccessible()) { onInvokeMethod.setAccessible(true); } Object[] params = invocation.getArguments(); try { onInvokeMethod.invoke(onInvokeInst, params); } catch (InvocationTargetException e) { fireThrowCallback(invoker, invocation, e.getTargetException()); } catch (Throwable e) { fireThrowCallback(invoker, invocation, e); } } private void fireReturnCallback(final Invoker<?> invoker, final Invocation invocation, final Object result) { final AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onReturnMethod = asyncMethodInfo.getOnreturnMethod(); final Object onReturnInst = asyncMethodInfo.getOnreturnInstance(); // not set onreturn callback if (onReturnMethod == null && onReturnInst == null) { return; } if (onReturnMethod == null || onReturnInst == null) { throw new IllegalStateException( "service:" + invoker.getUrl().getServiceKey() + " has a onreturn callback config , but no such " + (onReturnMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onReturnMethod.isAccessible()) { onReturnMethod.setAccessible(true); } Object[] args = invocation.getArguments(); Object[] params; Class<?>[] rParaTypes = onReturnMethod.getParameterTypes(); if (rParaTypes.length > 1) { if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = result; params[1] = args; } else { params = new Object[args.length + 1]; params[0] = result; System.arraycopy(args, 0, params, 1, args.length); } } else { params = new Object[] {result}; } try { onReturnMethod.invoke(onReturnInst, params); } catch (InvocationTargetException e) { fireThrowCallback(invoker, invocation, e.getTargetException()); } catch (Throwable e) { fireThrowCallback(invoker, invocation, e); } } private void fireThrowCallback(final Invoker<?> invoker, final Invocation invocation, final Throwable exception) { final AsyncMethodInfo asyncMethodInfo = getAsyncMethodInfo(invoker, invocation); if (asyncMethodInfo == null) { return; } final Method onthrowMethod = asyncMethodInfo.getOnthrowMethod(); final Object onthrowInst = asyncMethodInfo.getOnthrowInstance(); // onthrow callback not configured if (onthrowMethod == null && onthrowInst == null) { return; } if (onthrowMethod == null || onthrowInst == null) { throw new IllegalStateException( "service:" + invoker.getUrl().getServiceKey() + " has a onthrow callback config , but no such " + (onthrowMethod == null ? "method" : "instance") + " found. url:" + invoker.getUrl()); } if (!onthrowMethod.isAccessible()) { onthrowMethod.setAccessible(true); } Class<?>[] rParaTypes = onthrowMethod.getParameterTypes(); if (rParaTypes[0].isAssignableFrom(exception.getClass())) { try { Object[] args = invocation.getArguments(); Object[] params; if (rParaTypes.length > 1) { if (rParaTypes.length == 2 && rParaTypes[1].isAssignableFrom(Object[].class)) { params = new Object[2]; params[0] = exception; params[1] = args; } else { params = new Object[args.length + 1]; params[0] = exception; System.arraycopy(args, 0, params, 1, args.length); } } else { params = new Object[] {exception}; } onthrowMethod.invoke(onthrowInst, params); } catch (Throwable e) { logger.error( PROTOCOL_FAILED_REQUEST, "", "", RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), e); } } else { logger.error( PROTOCOL_FAILED_REQUEST, "", "", RpcUtils.getMethodName(invocation) + ".call back method invoke error . callback method :" + onthrowMethod + ", url:" + invoker.getUrl(), exception); } } private AsyncMethodInfo getAsyncMethodInfo(Invoker<?> invoker, Invocation invocation) { AsyncMethodInfo asyncMethodInfo = (AsyncMethodInfo) invocation.get(ASYNC_METHOD_INFO); if (asyncMethodInfo != null) { return asyncMethodInfo; } ServiceModel serviceModel = invocation.getServiceModel(); if (!(serviceModel instanceof ConsumerModel)) { return null; } String methodName = RpcUtils.getMethodName(invocation); return ((ConsumerModel) serviceModel).getAsyncInfo(methodName); } }
5,874
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-dubbo/src/main/java/org/apache/dubbo/rpc/protocol/dubbo/filter/TraceFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.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.CollectionUtils; import org.apache.dubbo.common.utils.ConcurrentHashSet; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.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.util.ArrayList; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_PARSE; /** * TraceFilter */ @Activate(group = CommonConstants.PROVIDER) public class TraceFilter implements Filter { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(TraceFilter.class); private static final String TRACE_MAX = "trace.max"; private static final String TRACE_COUNT = "trace.count"; private static final ConcurrentMap<String, Set<Channel>> TRACERS = new ConcurrentHashMap<>(); public static void addTracer(Class<?> type, String method, Channel channel, int max) { channel.setAttribute(TRACE_MAX, max); channel.setAttribute(TRACE_COUNT, new AtomicInteger()); String key = StringUtils.isNotEmpty(method) ? type.getName() + "." + method : type.getName(); Set<Channel> channels = TRACERS.computeIfAbsent(key, k -> new ConcurrentHashSet<>()); channels.add(channel); } public static void removeTracer(Class<?> type, String method, Channel channel) { channel.removeAttribute(TRACE_MAX); channel.removeAttribute(TRACE_COUNT); String key = StringUtils.isNotEmpty(method) ? type.getName() + "." + method : type.getName(); Set<Channel> channels = TRACERS.get(key); if (channels != null) { channels.remove(channel); } } @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { long start = System.currentTimeMillis(); Result result = invoker.invoke(invocation); long end = System.currentTimeMillis(); if (TRACERS.size() > 0) { String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation); Set<Channel> channels = TRACERS.get(key); if (CollectionUtils.isEmpty(channels)) { key = invoker.getInterface().getName(); channels = TRACERS.get(key); } if (CollectionUtils.isNotEmpty(channels)) { for (Channel channel : new ArrayList<>(channels)) { if (channel.isConnected()) { try { int max = 1; Integer m = (Integer) channel.getAttribute(TRACE_MAX); if (m != null) { max = m; } int count; AtomicInteger c = (AtomicInteger) channel.getAttribute(TRACE_COUNT); if (c == null) { c = new AtomicInteger(); channel.setAttribute(TRACE_COUNT, c); } count = c.getAndIncrement(); if (count < max) { String prompt = channel.getUrl().getParameter(Constants.PROMPT_KEY, Constants.DEFAULT_PROMPT); channel.send( "\r\n" + RpcContext.getServiceContext().getRemoteAddress() + " -> " + invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation) + "(" + JsonUtils.toJson(invocation.getArguments()) + ")" + " -> " + JsonUtils.toJson(result.getValue()) + "\r\nelapsed: " + (end - start) + " ms." + "\r\n\r\n" + prompt); } if (count >= max - 1) { channels.remove(channel); } } catch (Throwable e) { channels.remove(channel); logger.warn(PROTOCOL_FAILED_PARSE, "", "", e.getMessage(), e); } } else { channels.remove(channel); } } } } return result; } }
5,875
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RpcContextTest { @Test void testGetContext() { RpcContext rpcContext = RpcContext.getClientAttachment(); Assertions.assertNotNull(rpcContext); RpcContext.removeClientAttachment(); // if null, will return the initialize value. // Assertions.assertNull(RpcContext.getContext()); Assertions.assertNotNull(RpcContext.getClientAttachment()); Assertions.assertNotEquals(rpcContext, RpcContext.getClientAttachment()); RpcContext serverRpcContext = RpcContext.getServerContext(); Assertions.assertNotNull(serverRpcContext); RpcContext.removeServerContext(); Assertions.assertNotEquals(serverRpcContext, RpcContext.getServerContext()); } @Test void testAddress() { RpcContext context = RpcContext.getServiceContext(); context.setLocalAddress("127.0.0.1", 20880); Assertions.assertEquals(20880, context.getLocalAddress().getPort()); Assertions.assertEquals("127.0.0.1:20880", context.getLocalAddressString()); context.setRemoteAddress("127.0.0.1", 20880); Assertions.assertEquals(20880, context.getRemoteAddress().getPort()); Assertions.assertEquals("127.0.0.1:20880", context.getRemoteAddressString()); context.setRemoteAddress("127.0.0.1", -1); context.setLocalAddress("127.0.0.1", -1); Assertions.assertEquals(0, context.getRemoteAddress().getPort()); Assertions.assertEquals(0, context.getLocalAddress().getPort()); Assertions.assertEquals("127.0.0.1", context.getRemoteHostName()); Assertions.assertEquals("127.0.0.1", context.getLocalHostName()); } @Test void testCheckSide() { RpcContext context = RpcContext.getServiceContext(); // TODO fix npe // context.isProviderSide(); context.setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1")); Assertions.assertFalse(context.isConsumerSide()); Assertions.assertTrue(context.isProviderSide()); context.setUrl(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&side=consumer")); Assertions.assertTrue(context.isConsumerSide()); Assertions.assertFalse(context.isProviderSide()); } @Test void testAttachments() { RpcContext context = RpcContext.getClientAttachment(); Map<String, Object> map = new HashMap<>(); map.put("_11", "1111"); map.put("_22", "2222"); map.put(".33", "3333"); context.setObjectAttachments(map); Assertions.assertEquals(map, context.getObjectAttachments()); Assertions.assertEquals("1111", context.getAttachment("_11")); context.setAttachment("_11", "11.11"); Assertions.assertEquals("11.11", context.getAttachment("_11")); context.setAttachment(null, "22222"); context.setAttachment("_22", null); Assertions.assertEquals("22222", context.getAttachment(null)); Assertions.assertNull(context.getAttachment("_22")); Assertions.assertNull(context.getAttachment("_33")); Assertions.assertEquals("3333", context.getAttachment(".33")); context.clearAttachments(); Assertions.assertNull(context.getAttachment("_11")); } @Test void testObject() { RpcContext context = RpcContext.getClientAttachment(); Map<String, Object> map = new HashMap<String, Object>(); map.put("_11", "1111"); map.put("_22", "2222"); map.put(".33", "3333"); map.forEach(context::set); Assertions.assertEquals(map, context.get()); Assertions.assertEquals("1111", context.get("_11")); context.set("_11", "11.11"); Assertions.assertEquals("11.11", context.get("_11")); context.set(null, "22222"); context.set("_22", null); Assertions.assertEquals("22222", context.get(null)); Assertions.assertNull(context.get("_22")); Assertions.assertNull(context.get("_33")); Assertions.assertEquals("3333", context.get(".33")); map.keySet().forEach(context::remove); Assertions.assertNull(context.get("_11")); RpcContext.removeContext(); } @Test void testAsync() { RpcContext rpcContext = RpcContext.getServiceContext(); Assertions.assertFalse(rpcContext.isAsyncStarted()); AsyncContext asyncContext = RpcContext.startAsync(); Assertions.assertTrue(rpcContext.isAsyncStarted()); asyncContext.write(new Object()); Assertions.assertTrue( ((AsyncContextImpl) asyncContext).getInternalFuture().isDone()); rpcContext.stopAsync(); Assertions.assertTrue(rpcContext.isAsyncStarted()); RpcContext.removeContext(); } @Test void testAsyncCall() { CompletableFuture<String> rpcFuture = RpcContext.getClientAttachment().asyncCall(() -> { throw new NullPointerException(); }); rpcFuture.whenComplete((rpcResult, throwable) -> { System.out.println(throwable.toString()); Assertions.assertNull(rpcResult); Assertions.assertTrue(throwable instanceof RpcException); Assertions.assertTrue(throwable.getCause() instanceof NullPointerException); }); Assertions.assertThrows(ExecutionException.class, rpcFuture::get); rpcFuture = rpcFuture.exceptionally(throwable -> "mock success"); Assertions.assertEquals("mock success", rpcFuture.join()); } @Test void testObjectAttachment() { RpcContext rpcContext = RpcContext.getClientAttachment(); rpcContext.setAttachment("objectKey1", "value1"); rpcContext.setAttachment("objectKey2", "value2"); rpcContext.setAttachment("objectKey3", 1); // object Assertions.assertEquals("value1", rpcContext.getObjectAttachment("objectKey1")); Assertions.assertEquals("value2", rpcContext.getAttachment("objectKey2")); Assertions.assertNull(rpcContext.getAttachment("objectKey3")); Assertions.assertEquals(1, rpcContext.getObjectAttachment("objectKey3")); Assertions.assertEquals(3, rpcContext.getObjectAttachments().size()); rpcContext.clearAttachments(); Assertions.assertEquals(0, rpcContext.getObjectAttachments().size()); HashMap<String, Object> map = new HashMap<>(); map.put("mapKey1", 1); map.put("mapKey2", "mapValue2"); rpcContext.setObjectAttachments(map); Assertions.assertEquals(map, rpcContext.getObjectAttachments()); } @Test public void say() { final String key = "user-attachment"; final String value = "attachment-value"; RpcContext.getServerContext().setObjectAttachment(key, value); final String returned = (String) RpcContext.getServerContext().getObjectAttachment(key); System.out.println(returned); RpcContext.getServerContext().remove(key); } @Test void testRestore() {} @Test public void testRpcServerContextAttachment() { RpcContextAttachment attachment = RpcContext.getServerContext(); attachment.setAttachment("key_1", "value_1"); attachment.setAttachment("key_2", "value_2"); Assertions.assertEquals("value_1", attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("aaa")); attachment.removeAttachment("key_1"); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals("value_2", attachment.getAttachment("key_2")); Object obj = new Object(); attachment.setObjectAttachment("key_3", obj); Assertions.assertEquals(obj, attachment.getObjectAttachment("key_3")); attachment.removeAttachment("key_3"); Assertions.assertEquals(null, attachment.getObjectAttachment("key_3")); Assertions.assertThrows(RuntimeException.class, () -> attachment.copyOf(true)); Assertions.assertThrows(RuntimeException.class, attachment::isValid); Map<String, String> map = new HashMap<>(); map.put("key_4", "value_4"); map.put("key_5", "value_5"); attachment.setAttachments(map); Assertions.assertEquals(attachment.getAttachments(), attachment.getObjectAttachments()); Assertions.assertEquals(attachment.getAttachments(), attachment.get()); Map<String, String> map1 = attachment.getAttachments(); Assertions.assertEquals("value_4", map1.get("key_4")); Assertions.assertEquals("value_5", map1.get("key_5")); attachment.clearAttachments(); Assertions.assertEquals(attachment, attachment.removeAttachment("key_4")); Assertions.assertEquals(attachment, attachment.removeAttachment("key_5")); attachment.set("key_6", "value_6"); Assertions.assertEquals("value_6", attachment.get("key_6")); attachment.clearAttachments(); Map<String, Object> objectMap = new HashMap<>(); objectMap.put("key_7", "value_7"); objectMap.put("key_8", "value_8"); attachment.setObjectAttachments(objectMap); Map<String, String> objectMap1 = attachment.getAttachments(); Assertions.assertEquals("value_7", objectMap1.get("key_7")); Assertions.assertEquals("value_8", objectMap1.get("key_8")); attachment.clearAttachments(); } @Test public void testRpcServerContextClearAttachment() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); attachment.setAttachment("key_1", "value_1"); attachment.setAttachment("key_2", "value_2"); attachment.setAttachment("key_3", "value_3"); attachment.clearAttachments(); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("key_2")); Assertions.assertEquals(null, attachment.getAttachment("key_3")); attachment.setObjectAttachment("key_1", "value_1"); attachment.setObjectAttachment("key_2", "value_2"); attachment.setObjectAttachment("key_3", "value_3"); attachment.clearAttachments(); Assertions.assertEquals(null, attachment.getAttachment("key_1")); Assertions.assertEquals(null, attachment.getAttachment("key_2")); Assertions.assertEquals(null, attachment.getAttachment("key_3")); } @Test public void testAsyncContext() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); AsyncContext asyncContext = new AsyncContextImpl(); attachment.setAsyncContext(asyncContext); asyncContext.start(); Assertions.assertTrue(attachment.isAsyncStarted()); Assertions.assertEquals(asyncContext, attachment.getAsyncContext()); Assertions.assertTrue(attachment.stopAsync()); } @Test public void testObjectAttachmentMap() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put("key_1", "value_1"); Set<String> keySet = objectAttachmentMap.keySet(); Assertions.assertEquals(true, keySet.contains("key_1")); Collection<Object> valueSet = objectAttachmentMap.values(); Assertions.assertEquals(true, valueSet.contains("value_1")); Set<Map.Entry<String, Object>> entrySet = objectAttachmentMap.entrySet(); Map.Entry<String, Object> entry = entrySet.iterator().next(); Assertions.assertEquals("key_1", entry.getKey()); Assertions.assertEquals("value_1", entry.getValue()); Assertions.assertEquals(true, objectAttachmentMap.containsKey("key_1")); Assertions.assertEquals(true, objectAttachmentMap.containsValue("value_1")); Assertions.assertEquals("value_1", objectAttachmentMap.get("key_1")); Assertions.assertEquals(null, objectAttachmentMap.get("key_2")); objectAttachmentMap.remove("key_1"); Assertions.assertEquals(null, objectAttachmentMap.get("key_1")); Map<String, String> map = new HashMap<>(); map.put("key_3", "value_3"); map.put("key_4", "value_4"); objectAttachmentMap.putAll(map); Assertions.assertEquals("value_3", objectAttachmentMap.get("key_3")); Assertions.assertEquals("value_4", objectAttachmentMap.get("key_4")); Assertions.assertEquals(null, objectAttachmentMap.remove(new Object())); objectAttachmentMap.clear(); } @Test public void testClearAttachmentMap() { RpcServerContextAttachment attachment = new RpcServerContextAttachment(); RpcServerContextAttachment.ObjectAttachmentMap objectAttachmentMap = new RpcServerContextAttachment.ObjectAttachmentMap(attachment); objectAttachmentMap.put("key_1", "value_1"); objectAttachmentMap.put("key_2", "value_2"); objectAttachmentMap.put("key_3", "value_3"); Assertions.assertEquals(3, objectAttachmentMap.size()); objectAttachmentMap.clear(); Assertions.assertEquals(null, objectAttachmentMap.get(new Object())); Assertions.assertEquals(0, objectAttachmentMap.size()); Assertions.assertEquals(true, objectAttachmentMap.isEmpty()); } }
5,876
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcStatusTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.URL; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.rpc.support.DemoService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link RpcStatus} */ class RpcStatusTest { @Test void testBeginCountEndCount() { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91031, DemoService.class.getName()); String methodName = "testBeginCountEndCount"; int max = 2; boolean flag = RpcStatus.beginCount(url, methodName, max); RpcStatus urlRpcStatus = RpcStatus.getStatus(url); RpcStatus methodRpcStatus = RpcStatus.getStatus(url, methodName); Assertions.assertTrue(flag); Assertions.assertNotNull(urlRpcStatus); Assertions.assertNotNull(methodRpcStatus); Assertions.assertEquals(urlRpcStatus.getActive(), 1); Assertions.assertEquals(methodRpcStatus.getActive(), 1); RpcStatus.endCount(url, methodName, 1000, true); Assertions.assertEquals(urlRpcStatus.getActive(), 0); Assertions.assertEquals(methodRpcStatus.getActive(), 0); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertTrue(flag); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertTrue(flag); flag = RpcStatus.beginCount(url, methodName, max); Assertions.assertFalse(flag); } @Test void testBeginCountEndCountInMultiThread() throws Exception { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91032, DemoService.class.getName()); String methodName = "testBeginCountEndCountInMultiThread"; int max = 50; int threadNum = 10; AtomicInteger successCount = new AtomicInteger(); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch endLatch = new CountDownLatch(threadNum); List<Thread> threadList = new ArrayList<>(threadNum); for (int i = 0; i < threadNum; i++) { Thread thread = new Thread(() -> { try { startLatch.await(); for (int j = 0; j < 100; j++) { boolean flag = RpcStatus.beginCount(url, methodName, max); if (flag) { successCount.incrementAndGet(); } } endLatch.countDown(); } catch (Exception e) { // ignore } }); threadList.add(thread); } threadList.forEach(Thread::start); startLatch.countDown(); endLatch.await(); Assertions.assertEquals(successCount.get(), max); } @Test void testStatistics() { URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 91033, DemoService.class.getName()); String methodName = "testStatistics"; int max = 0; RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.beginCount(url, methodName, max); RpcStatus.endCount(url, methodName, 1000, true); RpcStatus.endCount(url, methodName, 2000, true); RpcStatus.endCount(url, methodName, 3000, false); RpcStatus.endCount(url, methodName, 4000, false); RpcStatus urlRpcStatus = RpcStatus.getStatus(url); RpcStatus methodRpcStatus = RpcStatus.getStatus(url, methodName); for (RpcStatus rpcStatus : Arrays.asList(urlRpcStatus, methodRpcStatus)) { Assertions.assertEquals(rpcStatus.getActive(), 0); Assertions.assertEquals(rpcStatus.getTotal(), 4); Assertions.assertEquals(rpcStatus.getTotalElapsed(), 10000); Assertions.assertEquals(rpcStatus.getMaxElapsed(), 4000); Assertions.assertEquals(rpcStatus.getAverageElapsed(), 2500); Assertions.assertEquals(rpcStatus.getAverageTps(), 0); Assertions.assertEquals(rpcStatus.getSucceeded(), 2); Assertions.assertEquals(rpcStatus.getSucceededElapsed(), 3000); Assertions.assertEquals(rpcStatus.getSucceededMaxElapsed(), 2000); Assertions.assertEquals(rpcStatus.getSucceededAverageElapsed(), 1500); Assertions.assertEquals(rpcStatus.getFailed(), 2); Assertions.assertEquals(rpcStatus.getFailedElapsed(), 7000); Assertions.assertEquals(rpcStatus.getFailedMaxElapsed(), 4000); Assertions.assertEquals(rpcStatus.getFailedAverageElapsed(), 3500); } } }
5,877
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/RpcInvocationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.Arrays; import java.util.HashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class RpcInvocationTest { @Test void testAttachment() { RpcInvocation invocation = new RpcInvocation(); invocation.setAttachment("objectKey1", "value1"); invocation.setAttachment("objectKey2", "value2"); invocation.setAttachment("objectKey3", 1); // object Assertions.assertEquals("value1", invocation.getObjectAttachment("objectKey1")); Assertions.assertEquals("value2", invocation.getAttachment("objectKey2")); Assertions.assertNull(invocation.getAttachment("objectKey3")); Assertions.assertEquals(1, invocation.getObjectAttachment("objectKey3")); Assertions.assertEquals(3, invocation.getObjectAttachments().size()); HashMap<String, Object> map = new HashMap<>(); map.put("mapKey1", 1); map.put("mapKey2", "mapValue2"); invocation.setObjectAttachments(map); Assertions.assertEquals(map, invocation.getObjectAttachments()); } @Test void testInvokers() { RpcInvocation rpcInvocation = new RpcInvocation(); Invoker invoker1 = Mockito.mock(Invoker.class); Invoker invoker2 = Mockito.mock(Invoker.class); Invoker invoker3 = Mockito.mock(Invoker.class); rpcInvocation.addInvokedInvoker(invoker1); rpcInvocation.addInvokedInvoker(invoker2); rpcInvocation.addInvokedInvoker(invoker3); rpcInvocation.addInvokedInvoker(invoker3); Assertions.assertEquals( Arrays.asList(invoker1, invoker2, invoker3, invoker3), rpcInvocation.getInvokedInvokers()); } }
5,878
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CancellationContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.concurrent.CountDownLatch; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link CancellationContext} */ class CancellationContextTest { @Test void test() throws Exception { CancellationContext cancellationContext = new CancellationContext(); CountDownLatch latch = new CountDownLatch(2); cancellationContext.addListener(rpcServiceContext -> { latch.countDown(); }); cancellationContext.addListener(rpcServiceContext -> { latch.countDown(); }); RuntimeException runtimeException = new RuntimeException(); cancellationContext.cancel(runtimeException); latch.await(); Assertions.assertNull(cancellationContext.getListeners()); Assertions.assertTrue(cancellationContext.isCancelled()); Assertions.assertEquals(cancellationContext.getCancellationCause(), runtimeException); } @Test void testAddListenerAfterCancel() throws Exception { CancellationContext cancellationContext = new CancellationContext(); cancellationContext.cancel(null); CountDownLatch latch = new CountDownLatch(1); cancellationContext.addListener(rpcServiceContext -> { latch.countDown(); }); latch.await(); } }
5,879
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/TimeoutCountDownTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class TimeoutCountDownTest { @Test void testTimeoutCountDown() throws InterruptedException { TimeoutCountDown timeoutCountDown = TimeoutCountDown.newCountDown(5, TimeUnit.SECONDS); Assertions.assertEquals(5 * 1000, timeoutCountDown.getTimeoutInMilli()); Assertions.assertFalse(timeoutCountDown.isExpired()); Assertions.assertTrue(timeoutCountDown.timeRemaining(TimeUnit.SECONDS) > 0); Assertions.assertTrue(timeoutCountDown.elapsedMillis() < TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); Thread.sleep(6 * 1000); Assertions.assertTrue(timeoutCountDown.isExpired()); Assertions.assertTrue(timeoutCountDown.timeRemaining(TimeUnit.SECONDS) <= 0); Assertions.assertTrue(timeoutCountDown.elapsedMillis() > TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); } }
5,880
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/CustomArgument.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rpc.support.Type; import java.io.Serializable; @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; public CustomArgument() {} public CustomArgument(Type type, String name) { super(); this.type = type; this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
5,881
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/AppResponseTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.HashMap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assumptions.assumeFalse; class AppResponseTest { @Test void testAppResponseWithNormalException() { NullPointerException npe = new NullPointerException(); AppResponse appResponse = new AppResponse(npe); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length > 1); } /** * please run this test in Run mode */ @Test void testAppResponseWithEmptyStackTraceException() { Throwable throwable = buildEmptyStackTraceException(); assumeFalse(throwable == null); AppResponse appResponse = new AppResponse(throwable); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertEquals(0, stackTrace.length); } @Test void testSetExceptionWithNormalException() { NullPointerException npe = new NullPointerException(); AppResponse appResponse = new AppResponse(); appResponse.setException(npe); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertTrue(stackTrace.length > 1); } /** * please run this test in Run mode */ @Test void testSetExceptionWithEmptyStackTraceException() { Throwable throwable = buildEmptyStackTraceException(); assumeFalse(throwable == null); AppResponse appResponse = new AppResponse(); appResponse.setException(throwable); StackTraceElement[] stackTrace = appResponse.getException().getStackTrace(); Assertions.assertNotNull(stackTrace); Assertions.assertEquals(0, stackTrace.length); } private Throwable buildEmptyStackTraceException() { // begin to construct a NullPointerException with empty stackTrace Throwable throwable = null; Long begin = System.currentTimeMillis(); while (System.currentTimeMillis() - begin < 60000) { try { ((Object) null).getClass(); } catch (Exception e) { if (e.getStackTrace().length == 0) { throwable = e; break; } } } /** * maybe there is -XX:-OmitStackTraceInFastThrow or run in Debug mode */ if (throwable == null) { System.out.println("###buildEmptyStackTraceException fail to construct NPE"); return null; } // end construct a NullPointerException with empty stackTrace return throwable; } @Test void testObjectAttachment() { AppResponse response = new AppResponse(); response.setAttachment("objectKey1", "value1"); response.setAttachment("objectKey2", "value2"); response.setAttachment("objectKey3", 1); // object Assertions.assertEquals("value1", response.getObjectAttachment("objectKey1")); Assertions.assertEquals("value2", response.getAttachment("objectKey2")); Assertions.assertNull(response.getAttachment("objectKey3")); Assertions.assertEquals(1, response.getObjectAttachment("objectKey3")); Assertions.assertEquals(3, response.getObjectAttachments().size()); HashMap<String, Object> map = new HashMap<>(); map.put("mapKey1", 1); map.put("mapKey2", "mapValue2"); response.setObjectAttachments(map); Assertions.assertEquals(map, response.getObjectAttachments()); } }
5,882
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/FutureContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * */ class FutureContextTest { @Test void testFutureContext() throws Exception { Thread thread1 = new Thread(() -> { FutureContext.getContext().setFuture(CompletableFuture.completedFuture("future from thread1")); try { Thread.sleep(500); Assertions.assertEquals( "future from thread1", FutureContext.getContext().getCompletableFuture().get()); } catch (Exception e) { e.printStackTrace(); } }); thread1.start(); Thread.sleep(100); Thread thread2 = new Thread(() -> { CompletableFuture future = FutureContext.getContext().getCompletableFuture(); Assertions.assertNull(future); FutureContext.getContext().setFuture(CompletableFuture.completedFuture("future from thread2")); }); thread2.start(); Thread.sleep(1000); } }
5,883
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/PenetrateAttachmentSelectorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.extension.ExtensionLoader; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * {@link PenetrateAttachmentSelector} */ class PenetrateAttachmentSelectorTest { @Test void test() { ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader = ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); Set<String> supportedSelectors = selectorExtensionLoader.getSupportedExtensions(); Map<String, Object> allSelected = new HashMap<>(); if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (String supportedSelector : supportedSelectors) { Map<String, Object> selected = selectorExtensionLoader.getExtension(supportedSelector).select(null, null, null); allSelected.putAll(selected); } } Assertions.assertEquals(allSelected.get("testKey"), "testVal"); } @Test public void testSelectReverse() { ExtensionLoader<PenetrateAttachmentSelector> selectorExtensionLoader = ApplicationModel.defaultModel().getExtensionLoader(PenetrateAttachmentSelector.class); Set<String> supportedSelectors = selectorExtensionLoader.getSupportedExtensions(); Map<String, Object> allSelected = new HashMap<>(); if (CollectionUtils.isNotEmpty(supportedSelectors)) { for (String supportedSelector : supportedSelectors) { Map<String, Object> selected = selectorExtensionLoader.getExtension(supportedSelector).selectReverse(null, null, null); allSelected.putAll(selected); } } Assertions.assertEquals(allSelected.get("reverseKey"), "reverseVal"); } }
5,884
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/DemoRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.Serializable; /** * TestRequest. */ class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; private String mServiceName; private String mMethodName; private Class<?>[] mParameterTypes; private Object[] mArguments; public DemoRequest(String serviceName, String methodName, Class<?>[] parameterTypes, Object[] args) { mServiceName = serviceName; mMethodName = methodName; mParameterTypes = parameterTypes; mArguments = args; } public String getServiceName() { return mServiceName; } public String getMethodName() { return mMethodName; } public Class<?>[] getParameterTypes() { return mParameterTypes; } public Object[] getArguments() { return mArguments; } }
5,885
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.rmi.Remote; import java.rmi.RemoteException; public interface RemoteService extends Remote { String sayHello(String name) throws RemoteException; String getThreadName() throws RemoteException; }
5,886
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/Type.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public enum Type { High, Normal, Lower }
5,887
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import java.lang.reflect.Method; 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.mockito.Mockito.when; class InvokerInvocationHandlerTest { private Invoker<?> invoker; private InvokerInvocationHandler invokerInvocationHandler; @BeforeEach public void setUp() { URL url = URL.valueOf("mock://localhost:8080/FooService?group=mock&version=1.0.0"); invoker = Mockito.mock(Invoker.class); when(invoker.getUrl()).thenReturn(url); invokerInvocationHandler = new InvokerInvocationHandler(invoker); } @Test void testInvokeToString() throws Throwable { String methodName = "toString"; when(invoker.toString()).thenReturn(methodName); Method method = invoker.getClass().getMethod(methodName); Object result = invokerInvocationHandler.invoke(null, method, new Object[] {}); Assertions.assertEquals(methodName, result); } }
5,888
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.rpc.RpcContext; /** * DemoServiceImpl */ public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); } public void sayHello(String name) { System.out.println("hello " + name); } public String echo(String text) { return text; } public long timestamp() { return System.currentTimeMillis(); } public String getThreadName() { return Thread.currentThread().getName(); } public int getSize(String[] strs) { if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { if (types.length == 0) return Type.Lower; return types[0]; } public int stringLength(String str) { return str.length(); } }
5,889
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/RemoteServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.rpc.RpcContext; import java.rmi.RemoteException; public class RemoteServiceImpl implements RemoteService { public String getThreadName() throws RemoteException { System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); return Thread.currentThread().getName(); } public String sayHello(String name) throws RemoteException { return "hello " + name + "@" + RemoteServiceImpl.class.getName(); } public String sayHello(String name, String arg2) { return "hello " + name + "@" + RemoteServiceImpl.class.getName() + ", arg2 " + arg2; } }
5,890
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.io.Serializable; /** * TestRequest. */ class DemoRequest implements Serializable { private static final long serialVersionUID = -2579095288792344869L; private String mServiceName; private String mMethodName; private Class<?>[] mParameterTypes; private Object[] mArguments; public DemoRequest(String serviceName, String methodName, Class<?>[] parameterTypes, Object[] args) { mServiceName = serviceName; mMethodName = methodName; mParameterTypes = parameterTypes; mArguments = args; } public String getServiceName() { return mServiceName; } public String getMethodName() { return mMethodName; } public Class<?>[] getParameterTypes() { return mParameterTypes; } public Object[] getArguments() { return mArguments; } }
5,891
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; public interface DemoService { void sayHello(String name); String echo(String text); long timestamp(); String getThreadName(); int getSize(String[] strs); int getSize(Object[] os); Object invoke(String service, String method) throws Exception; int stringLength(String str); Type enumlength(Type... types); }
5,892
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/AbstractProxyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import org.apache.dubbo.common.URL; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.service.Destroyable; import org.apache.dubbo.rpc.service.EchoService; import org.apache.dubbo.rpc.support.DemoService; import org.apache.dubbo.rpc.support.DemoServiceImpl; import org.apache.dubbo.rpc.support.MyInvoker; import java.util.Arrays; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public abstract class AbstractProxyTest { public static ProxyFactory factory; @Test void testGetProxy() { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); MyInvoker<DemoService> invoker = new MyInvoker<>(url); DemoService proxy = factory.getProxy(invoker); Assertions.assertNotNull(proxy); Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(DemoService.class)); Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(Destroyable.class)); Assertions.assertTrue(Arrays.asList(proxy.getClass().getInterfaces()).contains(EchoService.class)); Assertions.assertEquals( invoker.invoke(new RpcInvocation( "echo", DemoService.class.getName(), DemoService.class.getName() + ":dubbo", new Class[] {String.class}, new Object[] {"aa"})) .getValue(), proxy.echo("aa")); Destroyable destroyable = (Destroyable) proxy; destroyable.$destroy(); Assertions.assertTrue(invoker.isDestroyed()); } @Test void testGetInvoker() { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); DemoService origin = new DemoServiceImpl(); Invoker<DemoService> invoker = factory.getInvoker(new DemoServiceImpl(), DemoService.class, url); Assertions.assertEquals(invoker.getInterface(), DemoService.class); Assertions.assertEquals( invoker.invoke(new RpcInvocation( "echo", DemoService.class.getName(), DemoService.class.getName() + ":dubbo", new Class[] {String.class}, new Object[] {"aa"})) .getValue(), origin.echo("aa")); } }
5,893
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/MethodInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Map; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertInstanceOf; class MethodInvokerTest { @Test void testNewInstance() throws Throwable { String singleMethodName = "getThreadName"; String overloadMethodName = "sayHello"; MethodInvoker methodInvoker = MethodInvoker.newInstance(RemoteServiceImpl.class); assertInstanceOf(MethodInvoker.CompositeMethodInvoker.class, methodInvoker); MethodInvoker.CompositeMethodInvoker compositeMethodInvoker = (MethodInvoker.CompositeMethodInvoker) methodInvoker; Map<String, MethodInvoker> invokers = compositeMethodInvoker.getInvokers(); MethodInvoker getThreadNameMethodInvoker = invokers.get(singleMethodName); assertInstanceOf(MethodInvoker.SingleMethodInvoker.class, getThreadNameMethodInvoker); MethodInvoker sayHelloMethodInvoker = invokers.get(overloadMethodName); assertInstanceOf(MethodInvoker.OverloadMethodInvoker.class, sayHelloMethodInvoker); RemoteServiceImpl remoteService = Mockito.mock(RemoteServiceImpl.class); // invoke success, SingleMethodInvoker does not check parameter types methodInvoker.invoke(remoteService, singleMethodName, new Class[0], new Object[0]); methodInvoker.invoke( remoteService, singleMethodName, new Class[] {Object.class, Object.class, Object.class}, new Object[0]); Mockito.verify(remoteService, Mockito.times(2)).getThreadName(); methodInvoker.invoke( remoteService, overloadMethodName, new Class[] {String.class}, new Object[] {"Hello arg1"}); Mockito.verify(remoteService, Mockito.times(1)).sayHello("Hello arg1"); methodInvoker.invoke(remoteService, overloadMethodName, new Class[] {String.class, String.class}, new Object[] { "Hello arg1", "Hello arg2" }); Mockito.verify(remoteService, Mockito.times(1)).sayHello("Hello arg1", "Hello arg2"); } }
5,894
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.javassist; import org.apache.dubbo.rpc.proxy.AbstractProxyTest; class JavassistProxyFactoryTest extends AbstractProxyTest { static { factory = new JavassistProxyFactory(); } }
5,895
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rpc.proxy.AbstractProxyTest; class ByteBuddyProxyFactoryTest extends AbstractProxyTest { static { factory = new ByteBuddyProxyFactory(); } }
5,896
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.rpc.proxy.InvokerInvocationHandler; import org.apache.dubbo.rpc.proxy.RemoteService; import java.lang.reflect.Proxy; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.mockito.ArgumentMatchers.any; class ByteBuddyProxyTest { @Test void testNewInstance() throws Throwable { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InvokerInvocationHandler handler = Mockito.mock(InvokerInvocationHandler.class); Object proxy = ByteBuddyProxy.newInstance(cl, new Class<?>[] {RemoteService.class}, handler); assertInstanceOf(RemoteService.class, proxy); assertInstanceOf(Proxy.class, proxy); RemoteService remoteService = (RemoteService) proxy; remoteService.getThreadName(); remoteService.sayHello("test"); Mockito.verify(handler, Mockito.times(2)).invoke(any(), any(), any()); } }
5,897
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvokerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.proxy.RemoteService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ByteBuddyProxyInvokerTest { @Test void testNewInstance() throws Throwable { URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1"); RemoteService proxy = Mockito.mock(RemoteService.class); ByteBuddyProxyInvoker<RemoteService> invoker = ByteBuddyProxyInvoker.newInstance(proxy, RemoteService.class, url); invoker.doInvoke(proxy, "sayHello", new Class[] {String.class}, new Object[] {"test"}); Mockito.verify(proxy, Mockito.times(1)).sayHello("test"); Assertions.assertThrows( IllegalArgumentException.class, () -> invoker.doInvoke(proxy, "equals", new Class[] {String.class}, new Object[] {"test", "test2"})); } }
5,898
0
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy
Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyInterceptorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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 java.lang.reflect.Proxy; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ByteBuddyInterceptorTest { @AfterEach public void after() { Mockito.clearAllCaches(); } @Test void testIntercept() throws Throwable { InvocationHandler handler = Mockito.mock(InvocationHandler.class); ByteBuddyInterceptor interceptor = new ByteBuddyInterceptor(handler); Method method = Mockito.mock(Method.class); Proxy proxy = Mockito.mock(Proxy.class); Object[] args = new Object[0]; interceptor.intercept(proxy, args, method); // 'intercept' method will call 'invoke' method directly Mockito.verify(handler, Mockito.times(1)).invoke(proxy, method, args); } }
5,899