Search in sources :

Example 11 with SofaRpcRuntimeException

use of com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException in project sofa-rpc by sofastack.

the class AbstractHttp2ServerTransport method start.

@Override
public boolean start() {
    if (serverBootstrap != null) {
        return true;
    }
    synchronized (this) {
        if (serverBootstrap != null) {
            return true;
        }
        boolean flag = false;
        SslContext sslCtx = SslContextBuilder.build();
        // Configure the server.
        EventLoopGroup bossGroup = NettyHelper.getServerBossEventLoopGroup(transportConfig);
        HttpServerHandler httpServerHandler = (HttpServerHandler) transportConfig.getServerHandler();
        bizGroup = NettyHelper.getServerBizEventLoopGroup(transportConfig, httpServerHandler.getBizThreadPool());
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, bizGroup).channel(transportConfig.isUseEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, transportConfig.getBacklog()).option(ChannelOption.SO_REUSEADDR, transportConfig.isReuseAddr()).option(ChannelOption.RCVBUF_ALLOCATOR, NettyHelper.getRecvByteBufAllocator()).option(ChannelOption.ALLOCATOR, NettyHelper.getByteBufAllocator()).childOption(ChannelOption.SO_KEEPALIVE, transportConfig.isKeepAlive()).childOption(ChannelOption.TCP_NODELAY, transportConfig.isTcpNoDelay()).childOption(ChannelOption.SO_RCVBUF, 8192 * 128).childOption(ChannelOption.SO_SNDBUF, 8192 * 128).handler(new LoggingHandler(LogLevel.DEBUG)).childOption(ChannelOption.ALLOCATOR, NettyHelper.getByteBufAllocator()).childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(transportConfig.getBufferMin(), transportConfig.getBufferMax())).childHandler(new Http2ServerChannelInitializer(bizGroup, sslCtx, httpServerHandler, transportConfig.getPayload()));
        // 绑定到全部网卡 或者 指定网卡
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(transportConfig.getHost(), transportConfig.getPort()));
        ChannelFuture channelFuture = future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("HTTP/2 Server bind to {}:{} success!", transportConfig.getHost(), transportConfig.getPort());
                    }
                } else {
                    LOGGER.error(LogCodes.getLog(LogCodes.ERROR_HTTP2_BIND, transportConfig.getHost(), transportConfig.getPort()));
                    stop();
                }
            }
        });
        try {
            channelFuture.await();
            if (channelFuture.isSuccess()) {
                flag = Boolean.TRUE;
            } else {
                throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_START_SERVER, "HTTP/2"), future.cause());
            }
        } catch (InterruptedException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return flag;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) WriteBufferWaterMark(io.netty.channel.WriteBufferWaterMark) SslContext(io.netty.handler.ssl.SslContext) HttpServerHandler(com.alipay.sofa.rpc.server.http.HttpServerHandler)

Example 12 with SofaRpcRuntimeException

use of com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException in project sofa-rpc by sofastack.

the class JavassistProxy method getProxy.

@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) {
    StringBuilder debug = null;
    if (LOGGER.isDebugEnabled()) {
        debug = new StringBuilder();
    }
    try {
        Class clazz = PROXY_CLASS_MAP.get(interfaceClass);
        if (clazz == null) {
            // 生成代理类
            String interfaceName = ClassTypeUtils.getTypeStr(interfaceClass);
            ClassPool mPool = ClassPool.getDefault();
            mPool.appendClassPath(new LoaderClassPath(ClassLoaderUtils.getClassLoader(JavassistProxy.class)));
            CtClass mCtc = mPool.makeClass(interfaceName + "_proxy_" + counter.getAndIncrement());
            if (interfaceClass.isInterface()) {
                mCtc.addInterface(mPool.get(interfaceName));
            } else {
                throw new IllegalArgumentException(interfaceClass.getName() + " is not an interface");
            }
            // 继承 java.lang.reflect.Proxy
            mCtc.setSuperclass(mPool.get(java.lang.reflect.Proxy.class.getName()));
            CtConstructor constructor = new CtConstructor(null, mCtc);
            constructor.setModifiers(Modifier.PUBLIC);
            constructor.setBody("{super(new " + UselessInvocationHandler.class.getName() + "());}");
            mCtc.addConstructor(constructor);
            List<String> fieldList = new ArrayList<String>();
            List<String> methodList = new ArrayList<String>();
            fieldList.add("public " + Invoker.class.getCanonicalName() + " proxyInvoker = null;");
            createMethod(interfaceClass, fieldList, methodList);
            for (String fieldStr : fieldList) {
                if (LOGGER.isDebugEnabled()) {
                    debug.append(fieldStr).append("\n");
                }
                mCtc.addField(CtField.make(fieldStr, mCtc));
            }
            for (String methodStr : methodList) {
                if (LOGGER.isDebugEnabled()) {
                    debug.append(methodStr).append("\n");
                }
                mCtc.addMethod(CtMethod.make(methodStr, mCtc));
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("javassist proxy of interface: {} \r\n{}", interfaceClass, debug != null ? debug.toString() : "");
            }
            clazz = mCtc.toClass();
            PROXY_CLASS_MAP.put(interfaceClass, clazz);
        }
        Object instance = clazz.newInstance();
        clazz.getField("proxyInvoker").set(instance, proxyInvoker);
        return (T) instance;
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("javassist proxy of interface: {} \r\n{}", interfaceClass, debug != null ? debug.toString() : "");
        }
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSTRUCT, "javassist"), e);
    }
}
Also used : ClassPool(javassist.ClassPool) ArrayList(java.util.ArrayList) LoaderClassPath(javassist.LoaderClassPath) SofaRpcException(com.alipay.sofa.rpc.core.exception.SofaRpcException) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) Invoker(com.alipay.sofa.rpc.invoke.Invoker) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) CtClass(javassist.CtClass)

Example 13 with SofaRpcRuntimeException

use of com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException in project sofa-rpc by sofastack.

the class BytebuddyProxy method getProxy.

@Override
public <T> T getProxy(Class<T> interfaceClass, Invoker proxyInvoker) {
    Class<? extends T> cls = PROXY_CLASS_MAP.get(interfaceClass);
    if (cls == null) {
        cls = new ByteBuddy().subclass(interfaceClass).method(ElementMatchers.isDeclaredBy(interfaceClass).or(ElementMatchers.isEquals()).or(ElementMatchers.isToString().or(ElementMatchers.isHashCode()))).intercept(MethodDelegation.to(new BytebuddyInvocationHandler(proxyInvoker), "handler")).make().load(interfaceClass.getClassLoader(), ClassLoadingStrategy.Default.INJECTION).getLoaded();
        PROXY_CLASS_MAP.put(interfaceClass, cls);
    }
    try {
        return cls.newInstance();
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_CONSTRUCT, "bytebuddy"), t);
    }
}
Also used : SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) ByteBuddy(net.bytebuddy.ByteBuddy)

Example 14 with SofaRpcRuntimeException

use of com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException in project sofa-rpc by sofastack.

the class ExceptionUtilsTest method buildRuntime.

@Test
public void buildRuntime() throws Exception {
    SofaRpcRuntimeException exception = ExceptionUtils.buildRuntime("xxx111", "222");
    Assert.assertTrue(exception.getMessage().contains("xxx111"));
    Assert.assertTrue(exception.getMessage().contains("222"));
}
Also used : SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) Test(org.junit.Test)

Example 15 with SofaRpcRuntimeException

use of com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException in project sofa-rpc by sofastack.

the class TripleServer method registerProcessor.

@Override
public void registerProcessor(ProviderConfig providerConfig, Invoker instance) {
    Object ref = providerConfig.getRef();
    this.lock.lock();
    try {
        // wrap invoker to support unique id
        UniqueIdInvoker oldInvoker = this.invokerMap.putIfAbsent(providerConfig.getInterfaceId(), new UniqueIdInvoker());
        if (null != oldInvoker) {
            // we only need register given invoker into unique id invoker.
            if (!oldInvoker.registerInvoker(providerConfig, instance)) {
                throw new IllegalStateException("Can not expose service with interface:" + providerConfig.getInterfaceId() + " and unique id: " + providerConfig.getUniqueId());
            }
            return;
        }
        UniqueIdInvoker uniqueIdInvoker = this.invokerMap.get(providerConfig.getInterfaceId());
        if (!uniqueIdInvoker.registerInvoker(providerConfig, instance)) {
            throw new IllegalStateException("Can not expose service with interface:" + providerConfig.getInterfaceId() + " and unique id: " + providerConfig.getUniqueId());
        }
        // create service definition
        ServerServiceDefinition serviceDef;
        if (SofaProtoUtils.isProtoClass(ref)) {
            // refer is BindableService
            this.setBindableProxiedImpl(providerConfig, uniqueIdInvoker);
            BindableService bindableService = (BindableService) providerConfig.getRef();
            serviceDef = bindableService.bindService();
        } else {
            GenericServiceImpl genericService = new GenericServiceImpl(uniqueIdInvoker, providerConfig.getProxyClass());
            genericService.setProxiedImpl(genericService);
            serviceDef = buildSofaServiceDef(genericService, providerConfig);
        }
        List<TripleServerInterceptor> interceptorList = buildInterceptorChain(serviceDef);
        ServerServiceDefinition serviceDefinition = ServerInterceptors.intercept(serviceDef, interceptorList);
        this.serviceInfo.put(providerConfig, serviceDefinition);
        ServerServiceDefinition ssd = this.handlerRegistry.addService(serviceDefinition);
        if (ssd != null) {
            throw new IllegalStateException("Can not expose service with same name:" + serviceDefinition.getServiceDescriptor().getName());
        }
        this.invokerCnt.incrementAndGet();
    } catch (Exception e) {
        String msg = "Register triple service error";
        LOGGER.error(msg, e);
        this.serviceInfo.remove(providerConfig);
        throw new SofaRpcRuntimeException(msg, e);
    } finally {
        this.lock.unlock();
    }
}
Also used : SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) TripleServerInterceptor(com.alipay.sofa.rpc.interceptor.TripleServerInterceptor) ServerServiceDefinition(io.grpc.ServerServiceDefinition) SofaRpcRuntimeException(com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException) BindableService(io.grpc.BindableService)

Aggregations

SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)64 Method (java.lang.reflect.Method)10 KeeperException (org.apache.zookeeper.KeeperException)7 ProviderGroup (com.alipay.sofa.rpc.client.ProviderGroup)6 RegistryConfig (com.alipay.sofa.rpc.config.RegistryConfig)6 NacosException (com.alibaba.nacos.api.exception.NacosException)5 ProviderInfo (com.alipay.sofa.rpc.client.ProviderInfo)4 PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)4 Instance (com.alibaba.nacos.api.naming.pojo.Instance)3 ConsumerSubEvent (com.alipay.sofa.rpc.event.ConsumerSubEvent)3 ProviderPubEvent (com.alipay.sofa.rpc.event.ProviderPubEvent)3 ProviderInfoListener (com.alipay.sofa.rpc.listener.ProviderInfoListener)3 SslContext (io.netty.handler.ssl.SslContext)3 File (java.io.File)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 CuratorFramework (org.apache.curator.framework.CuratorFramework)3 Test (org.junit.Test)3 EventListener (com.alibaba.nacos.api.naming.listener.EventListener)2 ServerConfig (com.alipay.sofa.rpc.config.ServerConfig)2 SofaRpcException (com.alipay.sofa.rpc.core.exception.SofaRpcException)2