Java Code Examples for com.alipay.sofa.rpc.log.LogCodes#getLog()

The following examples show how to use com.alipay.sofa.rpc.log.LogCodes#getLog() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RpcBindingAdapter.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
/**
 * post unout binding
 *
 * @param contract           binding contract
 * @param binding            binding object
 * @param target             binding target
 * @param sofaRuntimeContext sofa runtime context
 */
@Override
public void postUnoutBinding(Object contract, RpcBinding binding, Object target,
                             SofaRuntimeContext sofaRuntimeContext) {
    ProviderConfig metadata = SpringBridge.getProviderConfigHelper().getProviderConfig((Contract) contract,
        binding, target);
    try {
        String key = SpringBridge.getProviderConfigContainer().createUniqueName((Contract) contract, binding);
        List<ServerConfig> servers = SpringBridge.getProviderConfigContainer().getProviderConfig(key).getServer();
        for (ServerConfig server : servers) {
            server.getServer().unRegisterProcessor(metadata, false);
        }
        SpringBridge.getProviderConfigContainer().removeProviderConfig(key);
    } catch (Exception e) {
        throw new ServiceRuntimeException(
            LogCodes.getLog(LogCodes.ERROR_PROXY_POST_UNPUBLISH_FAIL), e);
    }
}
 
Example 2
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized boolean start() {
    if (zkClient == null) {
        LOGGER.warn("Start zookeeper registry must be do init first!");
        return false;
    }
    if (zkClient.getState() == CuratorFrameworkState.STARTED) {
        return true;
    }
    try {
        zkClient.start();
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_ZOOKEEPER_CLIENT_START), e);
    }
    return zkClient.getState() == CuratorFrameworkState.STARTED;
}
 
Example 3
Source File: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 得到实例
 *
 * @param alias    别名
 * @param argTypes 扩展初始化需要的参数类型
 * @param args     扩展初始化需要的参数
 * @return 扩展实例(已判断是否单例)
 */
public T getExtension(String alias, Class[] argTypes, Object[] args) {
    ExtensionClass<T> extensionClass = getExtensionClass(alias);
    if (extensionClass == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_EXTENSION_NOT_FOUND, interfaceName, alias));
    } else {
        if (extensible.singleton() && factory != null) {
            T t = factory.get(alias);
            if (t == null) {
                synchronized (this) {
                    t = factory.get(alias);
                    if (t == null) {
                        t = extensionClass.getExtInstance(argTypes, args);
                        factory.put(alias, t);
                    }
                }
            }
            return t;
        } else {
            return extensionClass.getExtInstance(argTypes, args);
        }
    }
}
 
Example 4
Source File: AloneBoltClientConnectionManager.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通过配置获取长连接
 *
 * @param rpcClient       bolt客户端
 * @param transportConfig 传输层配置
 * @param url             传输层地址
 * @return 长连接
 */
public Connection getConnection(RpcClient rpcClient, ClientTransportConfig transportConfig, Url url) {
    if (rpcClient == null || transportConfig == null || url == null) {
        return null;
    }
    Connection connection;
    try {
        connection = rpcClient.getConnection(url, url.getConnectTimeout());
    } catch (InterruptedException | RemotingException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_GET_CONNECTION),e);
    }
    if (connection == null) {
        return null;
    }

    return connection;
}
 
Example 5
Source File: RpcBindingAdapter.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
/**
 * out binding, out binding means provide service
 *
 * @param contract           binding contract
 * @param binding            binding object
 * @param target             binding target
 * @param sofaRuntimeContext sofa runtime context
 * @return binding result
 */
@Override
public Object outBinding(Object contract, RpcBinding binding, Object target, SofaRuntimeContext sofaRuntimeContext) {

    String uniqueName = SpringBridge.getProviderConfigContainer().createUniqueName((Contract) contract, binding);
    ProviderConfig providerConfig = SpringBridge.getProviderConfigContainer().getProviderConfig(uniqueName);

    if (providerConfig == null) {
        throw new ServiceRuntimeException(LogCodes.getLog(LogCodes.INFO_SERVICE_METADATA_IS_NULL, uniqueName));
    }

    try {
        providerConfig.export();
    } catch (Exception e) {
        throw new ServiceRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROXY_PUBLISH_FAIL), e);
    }

    if (SpringBridge.getProviderConfigContainer().isAllowPublish()) {
        providerConfig.setRegister(true);
        List<RegistryConfig> registrys = providerConfig.getRegistry();
        for (RegistryConfig registryConfig : registrys) {
            Registry registry = RegistryFactory.getRegistry(registryConfig);
            registry.init();
            registry.start();
            registry.register(providerConfig);
        }
    }
    return Boolean.TRUE;
}
 
Example 6
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets boolean value.
 *
 * @param primaryKey the primary key
 * @return the boolean value
 */
public static boolean getBooleanValue(String primaryKey) {
    Object val = CFG.get(primaryKey);
    if (val == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey));
    } else {
        return Boolean.valueOf(val.toString());
    }
}
 
Example 7
Source File: SofaBootRpcSpringUtil.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
/**
 * 使用指定的classloader实例化某个类
 *
 * @param clazz 全类名
 * @param loader 类加载器
 * @return 类实例
 */
public static Object newInstance(String clazz, ClassLoader loader, String appName) {
    if (!StringUtils.hasText(clazz)) {
        return null;
    }
    try {
        return Class.forName(clazz, true, loader).newInstance();
    } catch (Exception e) {
        LOGGER.error("new instance failed. clazz[" + clazz + "];classLoader[" + loader + "];appName[" + appName +
            "]", e);
        throw new RuntimeException(LogCodes.getLog(
            LogCodes.ERROR_PROXY_BINDING_CLASS_CANNOT_FOUND, clazz), e);
    }
}
 
Example 8
Source File: HttpResponseFuture.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
protected TimeoutException clientTimeoutException() {
    throw new SofaTimeOutException(LogCodes.getLog(LogCodes.ERROR_INVOKE_TIMEOUT,
        SerializerFactory.getAliasByCode(request.getSerializeType()),
        request.getTargetServiceUniqueName(),
        request.getMethodName(), "",
        StringUtils.objectsToString(request.getMethodArgs()), timeout));
}
 
Example 9
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets enum value.
 *
 * @param <T>        the type parameter
 * @param primaryKey the primary key
 * @param enumClazz  the enum clazz
 * @return the enum value
 */
public static <T extends Enum<T>> T getEnumValue(String primaryKey, Class<T> enumClazz) {
    String val = (String) CFG.get(primaryKey);
    if (val == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey));
    } else {
        return Enum.valueOf(enumClazz, val);
    }
}
 
Example 10
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets string value.
 *
 * @param primaryKey the primary key
 * @return the string value
 */
public static String getStringValue(String primaryKey) {
    String val = (String) CFG.get(primaryKey);
    if (val == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_NOT_FOUND_KEY, primaryKey));
    } else {
        return val;
    }
}
 
Example 11
Source File: ProtostuffHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 加载protobuf接口里方法的参数和返回值类型到缓存,不需要传递
 *
 * @param key        缓存的key
 * @param clazz      接口名
 * @param methodName 方法名
 */
private void loadProtoClassToCache(String key, Class clazz, String methodName) {
    Method pbMethod = null;
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        if (methodName.equals(method.getName())) {
            pbMethod = method;
            break;
        }
    }
    if (pbMethod == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_METHOD_NOT_FOUND, clazz.getName(),
            methodName));
    }
    Class[] parameterTypes = pbMethod.getParameterTypes();
    if (parameterTypes == null
        || parameterTypes.length != 1) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_ONLY_ONE_PARAM, "protobuf",
            clazz.getName()));
    }
    Class reqClass = parameterTypes[0];
    requestClassCache.put(key, reqClass);
    Class resClass = pbMethod.getReturnType();
    if (resClass == void.class) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_PROTOBUF_RETURN, clazz.getName()));
    }
    responseClassCache.put(key, resClass);
}
 
Example 12
Source File: DynamicConfigManagerFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 得到动态配置管理
 *
 * @param alias 别名
 * @return DynamicManager 实现
 */
public static synchronized DynamicConfigManager getDynamicManager(String appName, String alias) {
    if (ALL_DYNAMICS.size() > 3) { // 超过3次 是不是配错了?
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Size of dynamic manager is greater than 3, Please check it!");
        }
    }
    try {
        // 注意:RegistryConfig重写了equals方法,如果多个RegistryConfig属性一样,则认为是一个对象
        DynamicConfigManager registry = ALL_DYNAMICS.get(alias);
        if (registry == null) {
            ExtensionClass<DynamicConfigManager> ext = ExtensionLoaderFactory.getExtensionLoader(
                DynamicConfigManager.class)
                .getExtensionClass(alias);
            if (ext == null) {
                throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOAD_EXT, "DynamicConfigManager",
                    alias));
            }
            registry = ext.getExtInstance(new Class[] { String.class }, new Object[] { appName });
            ALL_DYNAMICS.put(alias, registry);
        }
        return registry;
    } catch (Throwable e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOAD_EXT, "DynamicConfigManager", alias),
            e);
    }
}
 
Example 13
Source File: DefaultConsumerBootstrap.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public T refer() {
    if (proxyIns != null) {
        return proxyIns;
    }
    synchronized (this) {
        if (proxyIns != null) {
            return proxyIns;
        }
        String key = consumerConfig.buildKey();
        String appName = consumerConfig.getAppName();
        // 检查参数
        checkParameters();
        // 提前检查接口类
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, "Refer consumer config : {} with bean id {}", key, consumerConfig.getId());
        }

        // 注意同一interface,同一tags,同一protocol情况
        AtomicInteger cnt = REFERRED_KEYS.get(key); // 计数器
        if (cnt == null) { // 没有发布过
            cnt = CommonUtils.putToConcurrentMap(REFERRED_KEYS, key, new AtomicInteger(0));
        }
        int c = cnt.incrementAndGet();
        int maxProxyCount = consumerConfig.getRepeatedReferLimit();
        if (maxProxyCount > 0) {
            if (c > maxProxyCount) {
                cnt.decrementAndGet();
                // 超过最大数量,直接抛出异常
                throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_DUPLICATE_CONSUMER_CONFIG, key,
                    maxProxyCount));
            } else if (c > 1) {
                if (LOGGER.isInfoEnabled(appName)) {
                    LOGGER.infoWithApp(appName, "Duplicate consumer config with key {} has been referred!"
                        + " Maybe it's wrong config, please check it."
                        + " Ignore this if you did that on purpose!", key);
                }
            }
        }

        try {
            // build cluster
            cluster = ClusterFactory.getCluster(this);
            // build listeners
            consumerConfig.setConfigListener(buildConfigListener(this));
            consumerConfig.setProviderInfoListener(buildProviderInfoListener(this));
            // init cluster
            cluster.init();
            // 构造Invoker对象(执行链)
            proxyInvoker = buildClientProxyInvoker(this);
            // 创建代理类
            proxyIns = (T) ProxyFactory.buildProxy(consumerConfig.getProxy(), consumerConfig.getProxyClass(),
                proxyInvoker);

            //动态配置
            final String dynamicAlias = consumerConfig.getParameter(DynamicConfigKeys.DYNAMIC_ALIAS);
            if (StringUtils.isNotBlank(dynamicAlias)) {
                final DynamicConfigManager dynamicManager = DynamicConfigManagerFactory.getDynamicManager(
                    consumerConfig.getAppName(), dynamicAlias);
                dynamicManager.initServiceConfiguration(consumerConfig.getInterfaceId());
            }
        } catch (Exception e) {
            if (cluster != null) {
                cluster.destroy();
                cluster = null;
            }
            consumerConfig.setConfigListener(null);
            consumerConfig.setProviderInfoListener(null);
            cnt.decrementAndGet(); // 发布失败不计数
            if (e instanceof SofaRpcRuntimeException) {
                throw (SofaRpcRuntimeException) e;
            } else {
                throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_BUILD_CONSUMER_PROXY), e);
            }
        }
        if (consumerConfig.getOnAvailable() != null && cluster != null) {
            cluster.checkStateChange(false); // 状态变化通知监听器
        }
        RpcRuntimeContext.cacheConsumerConfig(this);
        return proxyIns;
    }
}
 
Example 14
Source File: JavassistProxy.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 15
Source File: AbstractSerializer.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
protected SofaRpcException buildDeserializeError(String message, Throwable throwable) {
    return new SofaRpcException(getErrorCode(false), LogCodes.getLog(LogCodes.ERROR_SERIALIZER, message), throwable);
}
 
Example 16
Source File: AsyncRuntime.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 得到callback用的线程池
 *
 * @param build 没有时是否构建
 * @return callback用的线程池
 */
public static ThreadPoolExecutor getAsyncThreadPool(boolean build) {
    if (asyncThreadPool == null && build) {
        synchronized (AsyncRuntime.class) {
            if (asyncThreadPool == null && build) {
                // 一些系统参数,可以从配置或者注册中心获取。
                int coresize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_CORE);
                int maxsize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_MAX);
                int queuesize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_QUEUE);
                int keepAliveTime = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_TIME);

                BlockingQueue<Runnable> queue = ThreadPoolUtils.buildQueue(queuesize);
                NamedThreadFactory threadFactory = new NamedThreadFactory("RPC-CB", true);

                RejectedExecutionHandler handler = new RejectedExecutionHandler() {
                    private int i = 1;

                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        if (i++ % 7 == 0) {
                            i = 1;
                            if (LOGGER.isWarnEnabled()) {
                                LOGGER.warn("Task:{} has been reject because of threadPool exhausted!" +
                                    " pool:{}, active:{}, queue:{}, taskcnt: {}", r,
                                    executor.getPoolSize(),
                                    executor.getActiveCount(),
                                    executor.getQueue().size(),
                                    executor.getTaskCount());
                            }
                        }
                        throw new RejectedExecutionException(
                            LogCodes.getLog(LogCodes.ERROR_ASYNC_THREAD_POOL_REJECT));
                    }
                };
                asyncThreadPool = ThreadPoolUtils.newCachedThreadPool(
                    coresize, maxsize, keepAliveTime, queue, threadFactory, handler);
            }
        }
    }
    return asyncThreadPool;
}
 
Example 17
Source File: AbstractSerializer.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
protected SofaRpcException buildSerializeError(String message, Throwable throwable) {
    return new SofaRpcException(getErrorCode(true), LogCodes.getLog(LogCodes.ERROR_SERIALIZER, message), throwable);
}
 
Example 18
Source File: AbstractSerializer.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
protected SofaRpcException buildSerializeError(String message) {
    return new SofaRpcException(getErrorCode(true), LogCodes.getLog(LogCodes.ERROR_SERIALIZER, message));
}
 
Example 19
Source File: AbstractHttpServerTask.java    From sofa-rpc with Apache License 2.0 3 votes vote down vote up
/**
 * 找不到服务方法
 *
 * @param appName     应用
 * @param serviceName 服务
 * @param methodName  方法名
 * @return 找不到服务方法的异常
 */
private SofaRpcException cannotFoundServiceMethod(String appName, String serviceName, String methodName) {
    String errorMsg = LogCodes.getLog(
        LogCodes.ERROR_PROVIDER_SERVICE_METHOD_CANNOT_FOUND, methodName, serviceName);
    LOGGER.errorWithApp(appName, errorMsg);
    return new SofaRpcException(RpcErrorType.SERVER_NOT_FOUND_INVOKER, errorMsg);
}
 
Example 20
Source File: AbstractCluster.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 指定地址不可用
 *
 * @param serviceKey 服务关键字
 * @return 服务端
 */
protected SofaRouteException unavailableProviderException(String serviceKey, String providerInfo) {
    return new SofaRouteException(LogCodes.getLog(LogCodes.ERROR_TARGET_URL_INVALID, serviceKey, providerInfo));
}