com.alipay.sofa.rpc.log.LogCodes Java Examples

The following examples show how to use com.alipay.sofa.rpc.log.LogCodes. 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: SofaRegistrySubscribeCallback.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 获得 Sofa Runtime 的日志对象,打印出获得Config Data 信息
 */
private void printConfigData(String dataId, ConfigData configData) {

    StringBuilder sb = new StringBuilder();
    int count = 0;

    if (configData != null && StringUtils.isNotBlank(configData.getData())) {
        final String[] split = StringUtils.split(configData.getData(), CONFIG_SEPARATOR);
        List<String> dataList = Arrays.asList(split);
        for (String provider : dataList) {
            sb.append("  >>> ").append(provider).append("\n");
            count++;
        }
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(LogCodes.getLiteLog(
            "Receive RPC config info: service[{0}]\n  usable config info[{1}]\n{2}",
            dataId, count, sb.toString()));
    }
}
 
Example #2
Source File: Curator4ZookeeperRegistry.java    From spring-cloud-sofastack-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void register(ProviderConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isRegister()) {
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_CONFREG_IGNORE));
        }
        return;
    }

    //发布
    if (config.isRegister()) {
        registerProviderUrls(config);
    }

    if (config.isSubscribe()) {
        // 订阅配置节点
        if (!INTERFACE_CONFIG_CACHE.containsKey(buildConfigPath(rootPath, config))) {
            //订阅接口级配置
            subscribeConfig(config, config.getConfigListener());
        }
    }
}
 
Example #3
Source File: RpcConfigs.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static void init() {
    try {
        // loadDefault
        String json = FileUtils.file2String(RpcConfigs.class, "rpc-config-default.json", "UTF-8");
        Map map = JSON.parseObject(json, Map.class);
        CFG.putAll(map);

        // loadCustom
        loadCustom("sofa-rpc/rpc-config.json");
        loadCustom("META-INF/sofa-rpc/rpc-config.json");

        // load system properties
        CFG.putAll(new HashMap(System.getProperties())); // 注意部分属性可能被覆盖为字符串
    } catch (Exception e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOAD_RPC_CONFIGS), e);
    }
}
 
Example #4
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 #5
Source File: HealthServiceInformer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void watchHealthService() {
    try {
        HealthServicesRequest request = HealthServicesRequest.newBuilder()
                .setTag(tag)
                .setQueryParams(new QueryParams(properties.getWatchTimeout(), currentData.getConsulIndex()))
                .setPassing(true)
                .build();
        Response<List<HealthService>> response = consulClient.getHealthServices(serviceName, request);
        if (response.getConsulIndex().equals(currentData.getConsulIndex())) {
            return;
        }
        this.currentData = response;
        ProviderGroup providerGroup = new ProviderGroup(currentProviders());
        listeners.stream().filter(Objects::nonNull).forEach(l -> l.updateProviders(providerGroup));
    } catch (Exception e) {
        LOGGER.error(LogCodes.getLog(LogCodes.ERROR_WATCH_HEALTH ,"Consul"), e);
    }
}
 
Example #6
Source File: AllConnectConnectionHolder.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通知状态变成可用,主要是:<br>
 * 1.启动成功变成可用时<br>
 * 2.注册中心增加,更新节点后变成可用时<br>
 * 3.重连上从一个可用节点都没有变成有可用节点时
 */
public void notifyStateChangeToAvailable() {
    final List<ConsumerStateListener> onAvailable = consumerConfig.getOnAvailable();
    if (onAvailable != null) {
        AsyncRuntime.getAsyncThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                // 状态变化通知监听器
                final Object proxyIns = consumerConfig.getConsumerBootstrap().getProxyIns();
                for (ConsumerStateListener listener : onAvailable) {
                    try {
                        listener.onAvailable(proxyIns);
                    } catch (Exception e) {
                        LOGGER.warnWithApp(consumerConfig.getAppName(),
                            LogCodes.getLog(LogCodes.WARN_NOTIFY_CONSUMER_STATE, proxyIns.getClass().getName()));
                    }
                }
            }
        });
    }
}
 
Example #7
Source File: ConsulRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void checkPass(NewService service) {
    try {
        consulClient.agentCheckPass("service:" + service.getId(), "TTL check passing by SOFA RPC");
    } catch (Exception e) {
        LOGGER.error(LogCodes.getLog(LogCodes.ERROR_CHECK_PASS ,"Consul"), e);
    }
}
 
Example #8
Source File: AllConnectConnectionHolder.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通知状态变成不可用,主要是:<br>
 * 1.注册中心删除,更新节点后变成不可用时<br>
 * 2.连接断线后(心跳+调用),如果是可用节点为空
 */
public void notifyStateChangeToUnavailable() {
    final List<ConsumerStateListener> onAvailable = consumerConfig.getOnAvailable();
    if (onAvailable != null) {
        AsyncRuntime.getAsyncThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                // 状态变化通知监听器
                final Object proxyIns = consumerConfig.getConsumerBootstrap().getProxyIns();
                for (ConsumerStateListener listener : onAvailable) {
                    try {
                        listener.onUnavailable(proxyIns);
                    } catch (Exception e) {
                        LOGGER.errorWithApp(consumerConfig.getAppName(),
                            LogCodes.getLog(LogCodes.ERROR_NOTIFY_CONSUMER_STATE_UN, proxyIns.getClass().getName()));
                    }
                }
            }
        });
    }
}
 
Example #9
Source File: BytebuddyProxy.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@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);
    }

}
 
Example #10
Source File: ConsulRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void unSubscribe(ConsumerConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isSubscribe()) {
        // 注册中心不订阅
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(config.getAppName(), LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
    }

    if (!config.isSubscribe()) {
        return;
    }
    String uniqueName = buildUniqueName(config, config.getProtocol());
    HealthServiceInformer informer = healthServiceInformers.get(uniqueName);
    if (informer == null) {
        return;
    }
    informer.removeListener(config.getProviderInfoListener());
    if (informer.getListenerSize() == 0) {
        healthServiceInformers.remove(uniqueName);
        informer.shutdown();
    }
}
 
Example #11
Source File: TraceClientRequestFilter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    try {

        if (RpcInternalContext.isAttachmentEnable()) {
            // 补充客户端request长度
            RpcInternalContext context = RpcInternalContext.getContext();
            context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE,
                requestContext.getHeaderString(HttpHeaders.CONTENT_LENGTH));

        }

        RestTracerAdapter.beforeSend(requestContext);
    } catch (Exception e) {
        logger.error(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "filter", "rest", "client"), e);
    }
}
 
Example #12
Source File: LocalRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 注册单条服务信息
 *
 * @param appName      应用名
 * @param serviceName  服务关键字
 * @param providerInfo 服务提供者数据
 */
protected void doRegister(String appName, String serviceName, ProviderInfo providerInfo) {
    if (LOGGER.isInfoEnabled(appName)) {
        LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB, serviceName));
    }
    //{service : [provider...]}
    ProviderGroup oldGroup = memoryCache.get(serviceName);
    if (oldGroup != null) { // 存在老的key
        oldGroup.add(providerInfo);
    } else { // 没有老的key,第一次加入
        List<ProviderInfo> news = new ArrayList<ProviderInfo>();
        news.add(providerInfo);
        memoryCache.put(serviceName, new ProviderGroup(news));
    }
    // 备份到文件 改为定时写
    needBackup = true;
    doWriteFile();

    if (subscribe) {
        notifyConsumerListeners(serviceName, memoryCache.get(serviceName));
    }
}
 
Example #13
Source File: RestServer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void unRegisterProcessor(ProviderConfig providerConfig, boolean closeIfNoEntry) {
    if (!isStarted()) {
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Unregister jaxrs service to port {} and base path is {}", serverConfig.getPort(),
            serverConfig.getContextPath());
    }
    try {
        httpServer.getDeployment().getRegistry()
            .removeRegistrations(providerConfig.getRef().getClass(), serverConfig.getContextPath());
        invokerCnt.decrementAndGet();
    } catch (Exception e) {
        LOGGER.error(LogCodes.getLog(LogCodes.ERROR_UNREG_PROCESSOR, "jaxrs"), e);
    }
    // 如果最后一个需要关闭,则关闭
    if (closeIfNoEntry && invokerCnt.get() == 0) {
        stop();
    }
}
 
Example #14
Source File: LogPrintDegradeStrategy.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void degrade(MeasureResultDetail measureResultDetail) {
    InvocationStatDimension statDimension = measureResultDetail.getInvocationStatDimension();
    String appName = statDimension.getAppName();
    if (LOGGER.isInfoEnabled(appName)) {
        String service = statDimension.getService();
        long timeWindow = measureResultDetail.getTimeWindow();
        long windowCount = measureResultDetail.getWindowCount();
        double abnormalRate = measureResultDetail.getAbnormalRate();
        double averageAbnormalRate = measureResultDetail.getAverageAbnormalRate();
        String ip = statDimension.getIp();

        LOGGER.infoWithApp(appName,
            LogCodes.getLog(LogCodes.INFO_REGULATION_ABNORMAL, timeWindow, service, appName,
                windowCount, abnormalRate, averageAbnormalRate, ip));
    }
}
 
Example #15
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 #16
Source File: AbstractCluster.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 通知状态变成可用,主要是:<br>
 * 1.启动成功变成可用时<br>
 * 2.注册中心增加,更新节点后变成可用时<br>
 * 3.重连上从一个可用节点都没有-->有可用节点时
 */
public void notifyStateChangeToAvailable() {
    final List<ConsumerStateListener> onprepear = consumerConfig.getOnAvailable();
    if (onprepear != null) {
        AsyncRuntime.getAsyncThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                // 状态变化通知监听器
                final Object proxyIns = consumerBootstrap.getProxyIns();
                for (ConsumerStateListener listener : onprepear) {
                    try {
                        listener.onAvailable(proxyIns);
                    } catch (Exception e) {
                        LOGGER.warn(LogCodes.getLog(LogCodes.WARN_NOTIFY_CONSUMER_STATE, proxyIns.getClass()
                            .getName()));
                    }
                }
            }
        });
    }
}
 
Example #17
Source File: ServiceHorizontalMeasureStrategy.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 根据Invocation的实际权重计算该Invocation的实际最小窗口调用次数 如果目标地址原始权重为0,或者地址已经被剔除则返回-1。
 *
 * @param invocationStat InvocationStat
 * @param weight weight
 * @param leastWindowCount original least Window count
 * @return leastWindowCount
 */
private long getInvocationLeastWindowCount(InvocationStat invocationStat, Integer weight, long leastWindowCount) {
    InvocationStatDimension statDimension = invocationStat.getDimension();
    Integer originWeight = statDimension.getOriginWeight();
    if (originWeight == 0) {
        LOGGER.errorWithApp(statDimension.getAppName(),
            LogCodes.getLog(LogCodes.ERROR_ORIGIN_WEIGHT_ZERO, statDimension.getService(), statDimension.getIp()));
        return -1;
    } else if (weight == null) { //如果地址还未被调控过或者已经恢复。
        return leastWindowCount;
    } else if (weight == -1) { //如果地址被剔除
        return -1;
    }

    double rate = CalculateUtils.divide(weight, originWeight);
    long invocationLeastWindowCount = CalculateUtils.multiply(leastWindowCount, rate);
    return invocationLeastWindowCount < LEGAL_LEAST_WINDOW_COUNT ? LEGAL_LEAST_WINDOW_COUNT
        : invocationLeastWindowCount;
}
 
Example #18
Source File: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 得到实例
 *
 * @param alias 别名
 * @return 扩展实例(已判断是否单例)
 */
public T getExtension(String alias) {
    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();
                        factory.put(alias, t);
                    }
                }
            }
            return t;
        } else {
            return extensionClass.getExtInstance();
        }
    }
}
 
Example #19
Source File: NacosRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void unSubscribe(ConsumerConfig config) {
    if (config.isSubscribe()) {
        String serviceName = NacosRegistryHelper.buildServiceName(config, config.getProtocol());
        try {
            EventListener eventListener = consumerListeners.remove(config);
            if (null != eventListener) {
                namingService.unsubscribe(serviceName, defaultCluster, eventListener);
            }
        } catch (Exception e) {
            if (!RpcRunningState.isShuttingDown()) {

                if (e instanceof SofaRpcRuntimeException) {
                    throw (SofaRpcRuntimeException) e;
                } else {
                    throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_UNSUB_LISTENER, EXT_NAME), e);
                }
            }
        }

        providerObserver.removeProviderListener(config);
    }
}
 
Example #20
Source File: HttpTransportUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 根据序列化名称获得序列化类型
 *
 * @param serialization 序列化类型名称
 * @return 序列化编码
 */
public static byte getSerializeTypeByName(String serialization) throws SofaRpcException {
    String sz = serialization.toLowerCase();
    Byte code;
    if (RpcConstants.SERIALIZE_HESSIAN2.equals(sz) || RpcConstants.SERIALIZE_HESSIAN.equals(sz)) {
        code = SerializerFactory.getCodeByAlias(RpcConstants.SERIALIZE_HESSIAN2);
    } else {
        code = SerializerFactory.getCodeByAlias(serialization);
    }
    if (code != null) {
        return code;
    } else {
        throw new SofaRpcException(RpcErrorType.SERVER_DESERIALIZE, LogCodes.getLog(
            LogCodes.ERROR_UNSUPPORTED_SERIALIZE_TYPE, serialization));
    }
}
 
Example #21
Source File: ServerFactory.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 关闭全部服务端
 */
public static void destroyAll() {
    if (CommonUtils.isEmpty(SERVER_MAP)) {
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Destroy all server now!");
    }
    for (Map.Entry<String, Server> entry : SERVER_MAP.entrySet()) {
        String key = entry.getKey();
        Server server = entry.getValue();
        try {
            server.destroy();
        } catch (Exception e) {
            LOGGER.error(LogCodes.getLog(LogCodes.ERROR_DESTROY_SERVER, key), e);
        }
    }
    SERVER_MAP.clear();
}
 
Example #22
Source File: DefaultProviderBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * for check fields and parameters of consumer config
 */
protected void checkParameters() {
    // 检查注入的ref是否接口实现类
    Class proxyClass = providerConfig.getProxyClass();
    String key = providerConfig.buildKey();
    T ref = providerConfig.getRef();
    if (!proxyClass.isInstance(ref)) {
        String name = ref == null ? "null" : ref.getClass().getName();
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_REFERENCE_AND_INTERFACE, name,
            providerConfig.getInterfaceId(), key));
    }
    // server 不能为空
    if (CommonUtils.isEmpty(providerConfig.getServer())) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_SERVER_EMPTY, key));
    }
    checkMethods(proxyClass);
}
 
Example #23
Source File: AbstractHttpServer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void registerProcessor(ProviderConfig providerConfig, Invoker instance) {
    // 缓存Invoker对象
    String serviceName = getUniqueName(providerConfig);
    serverHandler.getInvokerMap().put(serviceName, instance);
    // 解析方法,不支持方法重载
    Class itfClass = providerConfig.getProxyClass();
    HashMap<String, Method> methodsLimit = new HashMap<String, Method>(16);
    for (Method method : itfClass.getMethods()) {
        String methodName = method.getName();
        if (methodsLimit.containsKey(methodName)) {
            // 重名的方法
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_OVERLOADING_METHOD,
                itfClass.getName(), methodName));
        }
        methodsLimit.put(methodName, method);
    }

    for (Map.Entry<String, Method> entry : methodsLimit.entrySet()) {
        // 缓存接口的方法
        ReflectCache.putMethodCache(serviceName, entry.getValue());
        ReflectCache.putMethodSigsCache(serviceName, entry.getKey(),
            ClassTypeUtils.getTypeStrs(entry.getValue().getParameterTypes(), true));
    }
}
 
Example #24
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 #25
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void register(ProviderConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isRegister()) {
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return;
    }

    //发布
    if (config.isRegister()) {
        registerProviderUrls(config);
    }

    if (config.isSubscribe()) {
        // 订阅配置节点
        if (!INTERFACE_CONFIG_CACHE.containsKey(buildConfigPath(rootPath, config))) {
            //订阅接口级配置
            subscribeConfig(config, config.getConfigListener());
        }
    }
}
 
Example #26
Source File: LocalRegistryHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
static Map<String, ProviderGroup> loadBackupFileToCache(String address) {

        Map<String, ProviderGroup> memoryCache = new ConcurrentHashMap<String, ProviderGroup>();
        // 从文件夹下读取指定文件
        File regFile = new File(address);
        if (!regFile.exists()) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Load backup file failure cause by can't found file: {}", regFile.getAbsolutePath());
            }
        } else {
            try {
                String content = FileUtils.file2String(regFile);
                Map<String, ProviderGroup> tmp = unMarshal(content);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Load backup file from {}", regFile.getAbsolutePath());
                }
                // 加载到内存中
                if (tmp != null) {
                    memoryCache.putAll(tmp);
                }
            } catch (IOException e) {
                throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_READ_BACKUP_FILE,
                    regFile.getAbsolutePath()), e);
            }
        }
        return memoryCache;
    }
 
Example #27
Source File: ConsulRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void unRegister(ProviderConfig config) {
    String appName = config.getAppName();

    if (!registryConfig.isRegister()) {
        // 注册中心不注册
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return;
    }
    // 反注册服务端节点
    if (!config.isRegister()) {
        return;
    }
    try {
        List<String> ids = buildServiceIds(config);
        if (CommonUtils.isNotEmpty(ids)) {
            ids.forEach(this::deregisterConsulService);
            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_UNPUB,
                        config.getInterfaceId(), ids.size()));
            }
        }
    } catch (Exception e) {
        if (!RpcRunningState.isShuttingDown()) {
            if ( e instanceof SofaRpcRuntimeException){
                throw e;
            }else{
            throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_UNREG_PROVIDER ,EXT_NAME), e);
        }}
    }
}
 
Example #28
Source File: LocalRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void register(ProviderConfig config) {
    String appName = config.getAppName();
    if (!registryConfig.isRegister()) {
        if (LOGGER.isInfoEnabled(appName)) {
            LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
        }
        return;
    }
    if (!config.isRegister()) { // 注册中心不注册或者服务不注册
        return;
    }
    List<ServerConfig> serverConfigs = config.getServer();
    if (CommonUtils.isNotEmpty(serverConfigs)) {
        for (ServerConfig server : serverConfigs) {
            String serviceName = LocalRegistryHelper.buildListDataId(config, server.getProtocol());
            ProviderInfo providerInfo = LocalRegistryHelper.convertProviderToProviderInfo(config, server);
            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB_START, serviceName));
            }
            doRegister(appName, serviceName, providerInfo);

            if (LOGGER.isInfoEnabled(appName)) {
                LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_PUB_OVER, serviceName));
            }
        }
        if (EventBus.isEnable(ProviderPubEvent.class)) {
            ProviderPubEvent event = new ProviderPubEvent(config);
            EventBus.post(event);
        }

    }
}
 
Example #29
Source File: TimeWindowRegulator.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    measureCounter.incrementAndGet();
    for (MeasureModel measureModel : measureModels) {
        try {
            if (isArriveTimeWindow(measureModel)) {
                MeasureResult measureResult = measureStrategy.measure(measureModel);
                regulationExecutor.submit(new RegulationRunnable(measureResult));
            }
        } catch (Exception e) {
            LOGGER.errorWithApp(measureModel.getAppName(),
                LogCodes.getLog(LogCodes.ERROR_WHEN_DO_MEASURE, e.getMessage()), e);
        }
    }
}
 
Example #30
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);
}