Search in sources :

Example 21 with ProviderConfig

use of com.alipay.sofa.rpc.config.ProviderConfig in project sofa-rpc by sofastack.

the class BoltServerProcessor method handleRequest.

@Override
public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, SofaRequest request) {
    // RPC内置上下文
    RpcInternalContext context = RpcInternalContext.getContext();
    context.setProviderSide(true);
    String appName = request.getTargetAppName();
    if (appName == null) {
        // 默认全局appName
        appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
    }
    // 是否链路异步化中
    boolean isAsyncChain = false;
    try {
        // 这个 try-finally 为了保证Context一定被清理
        // 统计值加1
        processingCount.incrementAndGet();
        // 远程地址
        context.setRemoteAddress(bizCtx.getRemoteHost(), bizCtx.getRemotePort());
        // 远程返回的通道
        context.setAttachment(RpcConstants.HIDDEN_KEY_ASYNC_CONTEXT, asyncCtx);
        InvokeContext boltInvokeCtx = bizCtx.getInvokeContext();
        if (RpcInternalContext.isAttachmentEnable()) {
            if (boltInvokeCtx != null) {
                // rpc线程池等待时间 Long
                putToContextIfNotNull(boltInvokeCtx, InvokeContext.BOLT_PROCESS_WAIT_TIME, context, RpcConstants.INTERNAL_KEY_PROCESS_WAIT_TIME);
            }
        }
        putToContext(boltInvokeCtx);
        if (EventBus.isEnable(ServerReceiveEvent.class)) {
            EventBus.post(new ServerReceiveEvent(request));
        }
        // 开始处理
        // 响应,用于返回
        SofaResponse response = null;
        // 异常,用于记录
        Throwable throwable = null;
        ProviderConfig providerConfig = null;
        String serviceName = request.getTargetServiceUniqueName();
        try {
            // 这个try-catch 保证一定有Response
            invoke: {
                if (!boltServer.isStarted()) {
                    // 服务端已关闭
                    throwable = new SofaRpcException(RpcErrorType.SERVER_CLOSED, LogCodes.getLog(LogCodes.WARN_PROVIDER_STOPPED, SystemInfo.getLocalHost() + ":" + boltServer.serverConfig.getPort()));
                    response = MessageBuilder.buildSofaErrorResponse(throwable.getMessage());
                    break invoke;
                }
                if (bizCtx.isRequestTimeout()) {
                    // 加上丢弃超时的请求的逻辑
                    throwable = clientTimeoutWhenReceiveRequest(appName, serviceName, bizCtx.getRemoteAddress());
                    break invoke;
                }
                // 查找服务
                Invoker invoker = boltServer.findInvoker(serviceName);
                if (invoker == null) {
                    throwable = cannotFoundService(appName, serviceName);
                    response = MessageBuilder.buildSofaErrorResponse(throwable.getMessage());
                    break invoke;
                }
                if (invoker instanceof ProviderProxyInvoker) {
                    providerConfig = ((ProviderProxyInvoker) invoker).getProviderConfig();
                    // 找到服务后,打印服务的appName
                    appName = providerConfig != null ? providerConfig.getAppName() : null;
                }
                // 查找方法
                String methodName = request.getMethodName();
                Method serviceMethod = ReflectCache.getOverloadMethodCache(serviceName, methodName, request.getMethodArgSigs());
                if (serviceMethod == null) {
                    throwable = cannotFoundServiceMethod(appName, methodName, serviceName);
                    response = MessageBuilder.buildSofaErrorResponse(throwable.getMessage());
                    break invoke;
                } else {
                    request.setMethod(serviceMethod);
                }
                // 真正调用
                response = doInvoke(serviceName, invoker, request);
                if (bizCtx.isRequestTimeout()) {
                    // 加上丢弃超时的响应的逻辑
                    throwable = clientTimeoutWhenSendResponse(appName, serviceName, bizCtx.getRemoteAddress());
                    break invoke;
                }
            }
        } catch (Exception e) {
            // 服务端异常,不管是啥异常
            LOGGER.errorWithApp(appName, "Server Processor Error!", e);
            throwable = e;
            response = MessageBuilder.buildSofaErrorResponse(e.getMessage());
        }
        // Response不为空,代表需要返回给客户端
        if (response != null) {
            RpcInvokeContext invokeContext = RpcInvokeContext.peekContext();
            isAsyncChain = CommonUtils.isTrue(invokeContext != null ? (Boolean) invokeContext.remove(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN) : null);
            // 如果是服务端异步代理模式,特殊处理,因为该模式是在业务代码自主异步返回的
            if (!isAsyncChain) {
                // 其它正常请求
                try {
                    // 这个try-catch 保证一定要记录tracer
                    asyncCtx.sendResponse(response);
                } finally {
                    if (EventBus.isEnable(ServerSendEvent.class)) {
                        EventBus.post(new ServerSendEvent(request, response, throwable));
                    }
                }
            }
        }
    } catch (Throwable e) {
        // 可能有返回时的异常
        if (LOGGER.isErrorEnabled(appName)) {
            LOGGER.errorWithApp(appName, e.getMessage(), e);
        }
    } finally {
        processingCount.decrementAndGet();
        if (!isAsyncChain) {
            if (EventBus.isEnable(ServerEndHandleEvent.class)) {
                EventBus.post(new ServerEndHandleEvent());
            }
        }
        RpcInvokeContext.removeContext();
        RpcInternalContext.removeAllContext();
    }
}
Also used : InvokeContext(com.alipay.remoting.InvokeContext) RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) RpcInvokeContext(com.alipay.sofa.rpc.context.RpcInvokeContext) ServerSendEvent(com.alipay.sofa.rpc.event.ServerSendEvent) ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) RpcInternalContext(com.alipay.sofa.rpc.context.RpcInternalContext) ServerEndHandleEvent(com.alipay.sofa.rpc.event.ServerEndHandleEvent) Method(java.lang.reflect.Method) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) ProviderProxyInvoker(com.alipay.sofa.rpc.server.ProviderProxyInvoker) Invoker(com.alipay.sofa.rpc.invoke.Invoker) ProviderProxyInvoker(com.alipay.sofa.rpc.server.ProviderProxyInvoker) ServerReceiveEvent(com.alipay.sofa.rpc.event.ServerReceiveEvent) SofaResponse(com.alipay.sofa.rpc.core.response.SofaResponse)

Example 22 with ProviderConfig

use of com.alipay.sofa.rpc.config.ProviderConfig in project sofa-rpc by sofastack.

the class ZookeeperRegistryTest method testProviderObserver.

/**
 * 测试Zookeeper Provider Observer
 *
 * @throws Exception
 */
@Test
public void testProviderObserver() throws Exception {
    int timeoutPerSub = 2000;
    ServerConfig serverConfig = new ServerConfig().setProtocol("bolt").setHost("0.0.0.0").setPort(12200);
    ProviderConfig<?> provider = new ProviderConfig();
    provider.setInterfaceId(TEST_SERVICE_NAME).setUniqueId("unique123Id").setApplication(new ApplicationConfig().setAppName("test-server")).setProxy("javassist").setRegister(true).setRegistry(registryConfig).setSerialization("hessian2").setServer(serverConfig).setWeight(222).setTimeout(3000);
    // 注册
    registry.register(provider);
    ConsumerConfig<?> consumer = new ConsumerConfig();
    consumer.setInterfaceId(TEST_SERVICE_NAME).setUniqueId("unique123Id").setApplication(new ApplicationConfig().setAppName("test-server")).setProxy("javassist").setSubscribe(true).setSerialization("java").setInvokeType("sync").setTimeout(4444);
    // 订阅
    CountDownLatch latch = new CountDownLatch(1);
    MockProviderInfoListener providerInfoListener = new MockProviderInfoListener();
    providerInfoListener.setCountDownLatch(latch);
    consumer.setProviderInfoListener(providerInfoListener);
    List<ProviderGroup> all = registry.subscribe(consumer);
    providerInfoListener.updateAllProviders(all);
    Map<String, ProviderInfo> ps = providerInfoListener.getData();
    Assert.assertEquals("after register: 1", 1, ps.size());
    // 订阅 错误的uniqueId
    ConsumerConfig<?> consumerNoUniqueId = new ConsumerConfig();
    consumerNoUniqueId.setInterfaceId(TEST_SERVICE_NAME).setApplication(new ApplicationConfig().setAppName("test-server")).setProxy("javassist").setSubscribe(true).setSerialization("java").setInvokeType("sync").setTimeout(4444);
    latch = new CountDownLatch(1);
    MockProviderInfoListener providerInfoListener3 = new MockProviderInfoListener();
    providerInfoListener3.setCountDownLatch(latch);
    consumerNoUniqueId.setProviderInfoListener(providerInfoListener3);
    all = registry.subscribe(consumerNoUniqueId);
    providerInfoListener3.updateAllProviders(all);
    Map<String, ProviderInfo> ps3 = providerInfoListener3.getData();
    Assert.assertEquals("wrong uniqueId: 0", 0, ps3.size());
    // 反注册
    latch = new CountDownLatch(1);
    providerInfoListener.setCountDownLatch(latch);
    registry.unRegister(provider);
    latch.await(timeoutPerSub, TimeUnit.MILLISECONDS);
    Assert.assertEquals("after unregister: 0", 0, ps.size());
    // 一次发2个端口的再次注册
    latch = new CountDownLatch(2);
    providerInfoListener.setCountDownLatch(latch);
    provider.getServer().add(new ServerConfig().setProtocol("bolt").setHost("0.0.0.0").setPort(12201));
    registry.register(provider);
    latch.await(timeoutPerSub * 2, TimeUnit.MILLISECONDS);
    Assert.assertEquals("after register two servers: 2", 2, ps.size());
    // 重复订阅
    ConsumerConfig<?> consumer2 = new ConsumerConfig();
    consumer2.setInterfaceId(TEST_SERVICE_NAME).setUniqueId("unique123Id").setApplication(new ApplicationConfig().setAppName("test-server")).setProxy("javassist").setSubscribe(true).setSerialization("java").setInvokeType("sync").setTimeout(4444);
    CountDownLatch latch2 = new CountDownLatch(1);
    MockProviderInfoListener providerInfoListener2 = new MockProviderInfoListener();
    providerInfoListener2.setCountDownLatch(latch2);
    consumer2.setProviderInfoListener(providerInfoListener2);
    providerInfoListener2.updateAllProviders(registry.subscribe(consumer2));
    latch2.await(timeoutPerSub, TimeUnit.MILLISECONDS);
    Map<String, ProviderInfo> ps2 = providerInfoListener2.getData();
    Assert.assertEquals("after register duplicate: 2", 2, ps2.size());
    // 取消订阅者1
    registry.unSubscribe(consumer);
    // 批量反注册,判断订阅者2的数据
    latch = new CountDownLatch(2);
    providerInfoListener2.setCountDownLatch(latch);
    List<ProviderConfig> providerConfigList = new ArrayList<ProviderConfig>();
    providerConfigList.add(provider);
    registry.batchUnRegister(providerConfigList);
    latch.await(timeoutPerSub * 2, TimeUnit.MILLISECONDS);
    Assert.assertEquals("after unregister: 0", 0, ps2.size());
    // 批量取消订阅
    List<ConsumerConfig> consumerConfigList = new ArrayList<ConsumerConfig>();
    consumerConfigList.add(consumer2);
    registry.batchUnSubscribe(consumerConfigList);
}
Also used : ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) ServerConfig(com.alipay.sofa.rpc.config.ServerConfig) ProviderInfo(com.alipay.sofa.rpc.client.ProviderInfo) ApplicationConfig(com.alipay.sofa.rpc.config.ApplicationConfig) ConsumerConfig(com.alipay.sofa.rpc.config.ConsumerConfig) ProviderGroup(com.alipay.sofa.rpc.client.ProviderGroup) BaseZkTest(com.alipay.sofa.rpc.registry.zk.base.BaseZkTest) Test(org.junit.Test)

Example 23 with ProviderConfig

use of com.alipay.sofa.rpc.config.ProviderConfig in project sofa-rpc by sofastack.

the class BeanIdMatchFilterTest method testIsMatch.

@Test
public void testIsMatch() {
    TestCustomizeFilter testCustomizeFilter = new TestCustomizeFilter();
    Assert.assertTrue(testCustomizeFilter.isMatch(""));
    testCustomizeFilter = new TestCustomizeFilter();
    testCustomizeFilter.setIdRule("AAA,BBB");
    AbstractInterfaceConfig configA = new ProviderConfig();
    configA.setInterfaceId(Serializer.class.getName());
    configA.setId("AAA");
    FilterInvoker filterInvokerA = new FilterInvoker(null, null, configA);
    Assert.assertEquals(true, testCustomizeFilter.needToLoad(filterInvokerA));
}
Also used : ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) AbstractInterfaceConfig(com.alipay.sofa.rpc.config.AbstractInterfaceConfig) Serializer(com.alipay.sofa.rpc.codec.Serializer) Test(org.junit.Test)

Example 24 with ProviderConfig

use of com.alipay.sofa.rpc.config.ProviderConfig in project sofa-rpc by sofastack.

the class BeanIdMatchFilterTest method testBeanIdMatch.

@Test
public void testBeanIdMatch() {
    TestCustomizeFilter testCustomizeFilter = new TestCustomizeFilter();
    testCustomizeFilter.setIdRule("AAA,!BBB");
    Assert.assertEquals("AAA,!BBB", testCustomizeFilter.getIdRule());
    AbstractInterfaceConfig configA = new ProviderConfig();
    configA.setInterfaceId(Serializer.class.getName());
    configA.setId("AAA");
    FilterInvoker filterInvokerA = new FilterInvoker(null, null, configA);
    AbstractInterfaceConfig configB = new ProviderConfig();
    configB.setInterfaceId(Serializer.class.getName());
    configB.setId("BBB");
    FilterInvoker filterInvokerB = new FilterInvoker(null, null, configB);
    AbstractInterfaceConfig configC = new ProviderConfig();
    configC.setInterfaceId(Serializer.class.getName());
    configC.setId("CCC");
    FilterInvoker filterInvokerC = new FilterInvoker(null, null, configC);
    Assert.assertEquals(true, testCustomizeFilter.needToLoad(filterInvokerA));
    Assert.assertEquals(false, testCustomizeFilter.needToLoad(filterInvokerB));
    Assert.assertEquals(true, testCustomizeFilter.needToLoad(filterInvokerC));
}
Also used : ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) AbstractInterfaceConfig(com.alipay.sofa.rpc.config.AbstractInterfaceConfig) Serializer(com.alipay.sofa.rpc.codec.Serializer) Test(org.junit.Test)

Example 25 with ProviderConfig

use of com.alipay.sofa.rpc.config.ProviderConfig in project sofa-rpc by sofastack.

the class RestTracerTest method testRestTracer.

@Test
public void testRestTracer() throws InterruptedException, IOException {
    Reporter clientReporter = reflectToTracer();
    memoryReporter = (MemoryReporterImpl) clientReporter;
    ServerConfig restServer = new ServerConfig().setPort(8583).setProtocol(RpcConstants.PROTOCOL_TYPE_REST);
    List<ServerConfig> servers = new ArrayList<ServerConfig>(2);
    servers.add(restServer);
    ProviderConfig<RestService> providerConfig = new ProviderConfig<RestService>().setInterfaceId(RestService.class.getName()).setRef(new RestServiceImpl()).setRegister(false).setServer(servers);
    providerConfig.export();
    // rest服务
    ConsumerConfig<RestService> consumerConfigRest = new ConsumerConfig<RestService>().setInterfaceId(RestService.class.getName()).setProtocol(RpcConstants.PROTOCOL_TYPE_REST).setDirectUrl("rest://127.0.0.1:8583").setTimeout(1000).setApplication(new ApplicationConfig().setAppName("TestClientRest"));
    final RestService restServiceRest = consumerConfigRest.refer();
    restServiceRest.get("test");
    final int times = 10;
    final CountDownLatch latch = new CountDownLatch(times);
    final AtomicInteger success = new AtomicInteger(0);
    for (int i = 0; i < times; i++) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (int j = 0; j < times; j++) {
                        final String ok_rest = restServiceRest.get("ok_rest");
                        Assert.assertEquals("serverok_rest", ok_rest);
                        success.incrementAndGet();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        }).start();
    }
    latch.await();
    Assert.assertEquals(times * times, success.get());
    TimeUnit.SECONDS.sleep(5);
    List<String> clientDigestContents = memoryReporter.getClientDigestHolder();
    List<String> serverDigestContents = memoryReporter.getServerDigestHolder();
    List<JSONObject> clientDigest = TracerChecker.convertContents2Json(clientDigestContents);
    List<String> clientTraceIds = readTraceId(clientDigest);
    List<JSONObject> serverDigest = TracerChecker.convertContents2Json(serverDigestContents);
    List<String> serverTraceIds = readTraceId(serverDigest);
    Assert.assertTrue(CommonUtils.isNotEmpty(clientTraceIds));
    Assert.assertTrue(CommonUtils.isNotEmpty(serverTraceIds));
    HashSet<String> hashSet = new HashSet<String>(200);
    for (String clientTraceId : clientTraceIds) {
        // will not duplicate
        Assert.assertTrue(!hashSet.contains(clientTraceId));
        hashSet.add(clientTraceId);
        Assert.assertTrue(serverTraceIds.contains(clientTraceId));
    }
    // validate one rpc server and rpc client field
    boolean result = TracerChecker.validateTracerDigest(clientDigest.get(0), "client", RpcConstants.PROTOCOL_TYPE_REST);
    Assert.assertTrue(result);
    result = TracerChecker.validateTracerDigest(serverDigest.get(0), "server", RpcConstants.PROTOCOL_TYPE_REST);
    Assert.assertTrue(result);
}
Also used : ProviderConfig(com.alipay.sofa.rpc.config.ProviderConfig) Reporter(com.alipay.common.tracer.core.reporter.facade.Reporter) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) ServerConfig(com.alipay.sofa.rpc.config.ServerConfig) JSONObject(com.alibaba.fastjson.JSONObject) ApplicationConfig(com.alipay.sofa.rpc.config.ApplicationConfig) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashSet(java.util.HashSet) Test(org.junit.Test) ActivelyDestroyTest(com.alipay.sofa.rpc.test.ActivelyDestroyTest)

Aggregations

ProviderConfig (com.alipay.sofa.rpc.config.ProviderConfig)121 ServerConfig (com.alipay.sofa.rpc.config.ServerConfig)88 Test (org.junit.Test)73 ApplicationConfig (com.alipay.sofa.rpc.config.ApplicationConfig)52 ConsumerConfig (com.alipay.sofa.rpc.config.ConsumerConfig)47 HelloService (com.alipay.sofa.rpc.test.HelloService)33 HelloServiceImpl (com.alipay.sofa.rpc.test.HelloServiceImpl)33 ActivelyDestroyTest (com.alipay.sofa.rpc.test.ActivelyDestroyTest)28 RegistryConfig (com.alipay.sofa.rpc.config.RegistryConfig)21 CountDownLatch (java.util.concurrent.CountDownLatch)19 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)17 ProviderGroup (com.alipay.sofa.rpc.client.ProviderGroup)10 Filter (com.alipay.sofa.rpc.filter.Filter)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)10 EchoService (com.alipay.sofa.rpc.test.EchoService)9 ArrayList (java.util.ArrayList)9 ProviderInfo (com.alipay.sofa.rpc.client.ProviderInfo)8 EchoServiceImpl (com.alipay.sofa.rpc.test.EchoServiceImpl)8 MethodConfig (com.alipay.sofa.rpc.config.MethodConfig)7 RpcInvokeContext (com.alipay.sofa.rpc.context.RpcInvokeContext)7