Search in sources :

Example 1 with PolarisException

use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.

the class PluginConfigImpl method getPluginConfigs.

@Override
public Map<String, Verifier> getPluginConfigs() throws PolarisException {
    synchronized (lock) {
        Map<String, Verifier> values = new HashMap<>();
        if (plugin.size() == 0) {
            return values;
        }
        for (Map.Entry<String, Map<?, ?>> entry : plugin.entrySet()) {
            Map<?, ?> properties = entry.getValue();
            if (MapUtils.isEmpty(properties)) {
                continue;
            }
            String pluginName = entry.getKey();
            Class<? extends Verifier> clazz = PluginConfigImpl.pluginConfigClazz.get(pluginName);
            if (null == clazz) {
                // String.format("unknown plugin config type for plugin %s", pluginName));
                continue;
            }
            try {
                Verifier result = mapper.convertValue(properties, clazz);
                values.put(pluginName, result);
            } catch (IllegalArgumentException e) {
                throw new PolarisException(ErrorCode.INVALID_CONFIG, String.format("fail to deserialize properties %s to clazz %s for plugin %s", properties, clazz.getCanonicalName(), pluginName), e);
            }
        }
        return values;
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) HashMap(java.util.HashMap) Verifier(com.tencent.polaris.api.config.verify.Verifier) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with PolarisException

use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.

the class ConfigAPIFactory method loadConfig.

/**
 * 通过配置文件加载配置对象
 *
 * @param configStream 配置文件流
 * @return 配置对象
 * @throws PolarisException 文件加载异常
 */
public static Configuration loadConfig(InputStream configStream) throws PolarisException {
    YAMLFactory yamlFactory = new YAMLFactory();
    ObjectMapper mapper = new ObjectMapper();
    try {
        YAMLParser yamlParser = yamlFactory.createParser(configStream);
        final JsonNode node = mapper.readTree(yamlParser);
        TreeTraversingParser treeTraversingParser = new TreeTraversingParser(node);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(treeTraversingParser, ConfigurationImpl.class);
    } catch (Exception e) {
        throw new PolarisException(ErrorCode.INVALID_CONFIG, "fail to load config from stream", e);
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) TreeTraversingParser(com.fasterxml.jackson.databind.node.TreeTraversingParser) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) YAMLParser(com.fasterxml.jackson.dataformat.yaml.YAMLParser) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PolarisException(com.tencent.polaris.api.exception.PolarisException)

Example 3 with PolarisException

use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.

the class CacheObject method onEventUpdate.

@Override
public boolean onEventUpdate(ServerEvent event) {
    ServiceEventKey serviceEventKey = event.getServiceEventKey();
    PolarisException error = event.getError();
    remoteUpdated.set(true);
    boolean svcDeleted = false;
    Collection<ResourceEventListener> resourceEventListeners = registry.getResourceEventListeners();
    if (null != error) {
        // 收取消息有出错
        RegistryCacheValue registryCacheValue = loadValue(false);
        // 没有服务信息直接删除
        if (error.getCode() == ErrorCode.SERVICE_NOT_FOUND) {
            if (deleted.compareAndSet(false, true)) {
                registry.removeCache(serviceEventKey);
                for (ResourceEventListener listener : resourceEventListeners) {
                    listener.onResourceDeleted(svcEventKey, registryCacheValue);
                }
                svcDeleted = true;
            }
        } else {
            LOG.error(String.format("received error notify for service %s", serviceEventKey), error);
        }
    } else {
        Object message = event.getValue();
        RegistryCacheValue cachedValue = value.get();
        CachedStatus cachedStatus = cacheHandler.compareMessage(cachedValue, message);
        if (cachedStatus == CachedStatus.CacheChanged || cachedStatus == CachedStatus.CacheNotExists) {
            LOG.info("OnServiceUpdate: cache {} is pending to update", svcEventKey);
            this.registry.saveMessageToFile(serviceEventKey, (Message) message);
            RegistryCacheValue newCachedValue = cacheHandler.messageToCacheValue(cachedValue, message, false);
            setValue(newCachedValue);
            if (cachedStatus == CachedStatus.CacheChanged) {
                for (ResourceEventListener listener : resourceEventListeners) {
                    listener.onResourceUpdated(svcEventKey, cachedValue, newCachedValue);
                }
            }
        } else if (cachedStatus == CachedStatus.CacheEmptyButNoData) {
            LOG.error("OnServiceUpdate: {} is empty, but discover returns no data", svcEventKey);
        }
        boolean newRemoteCache = null == cachedValue || cachedValue.isLoadedFromFile();
        if (newRemoteCache && serviceEventKey.getEventType() == EventType.INSTANCE) {
            // 设置就绪状态
            registry.setServerServiceReady(serviceEventKey);
        }
    }
    synchronized (lock) {
        if (error != null && ErrorCode.SERVICE_NOT_FOUND.equals(error.getCode())) {
            notifyEvent(null);
        }
        notifyEvent(error);
    }
    return svcDeleted;
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) RegistryCacheValue(com.tencent.polaris.api.pojo.RegistryCacheValue) CachedStatus(com.tencent.polaris.api.plugin.registry.CacheHandler.CachedStatus) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) ResourceEventListener(com.tencent.polaris.api.plugin.registry.ResourceEventListener)

Example 4 with PolarisException

use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.

the class MetadataRouter method router.

@Override
public RouteResult router(RouteInfo routeInfo, ServiceInstances instances) throws PolarisException {
    FailOverType failOverType = config.getMetadataFailOverType();
    Map<String, String> svcMetadata = instances.getMetadata();
    if (MapUtils.isNotEmpty(svcMetadata)) {
        if (svcMetadata.containsKey(KEY_METADATA_FAILOVER_TYPE)) {
            String value = svcMetadata.get(KEY_METADATA_FAILOVER_TYPE);
            if (valueToFailoverType.containsKey(value)) {
                failOverType = valueToFailoverType.get(value);
            }
        }
    }
    MetadataFailoverType metadataFailoverType = routeInfo.getMetadataFailoverType();
    if (null != metadataFailoverType) {
        failOverType = inputToFailoverType.get(metadataFailoverType);
    }
    boolean availableInsFlag;
    Map<String, String> reqMetadata = routeInfo.getDestService().getMetadata();
    List<Instance> instanceList = new ArrayList<>();
    for (Instance ins : instances.getInstances()) {
        availableInsFlag = true;
        // 要满足请求中的metadata K-V全部存在于实例的metadata中
        for (Map.Entry<String, String> entry : reqMetadata.entrySet()) {
            if (ins.getMetadata().containsKey(entry.getKey()) && ins.getMetadata().get(entry.getKey()).equals(entry.getValue())) {
                continue;
            }
            availableInsFlag = false;
            break;
        }
        if (availableInsFlag) {
            instanceList.add(ins);
        }
    }
    if (!CollectionUtils.isEmpty(instanceList)) {
        return new RouteResult(instanceList, RouteResult.State.Next);
    }
    switch(failOverType) {
        case all:
            return new RouteResult(instances.getInstances(), RouteResult.State.Next);
        case others:
            return new RouteResult(addNotContainKeyIns(instances, reqMetadata), RouteResult.State.Next);
        default:
            // 默认不降级
            throw new PolarisException(ErrorCode.METADATA_MISMATCH, String.format("can not find any instance by service %s", routeInfo.getDestService()));
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) Instance(com.tencent.polaris.api.pojo.Instance) RouteResult(com.tencent.polaris.api.plugin.route.RouteResult) MetadataFailoverType(com.tencent.polaris.api.rpc.MetadataFailoverType) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with PolarisException

use of com.tencent.polaris.api.exception.PolarisException in project polaris-java by polarismesh.

the class NearbyRouter method ensureLocationReady.

/**
 * 校验是否严格校验地域信息
 */
public void ensureLocationReady() throws PolarisException {
    if (!this.config.isStrictNearby()) {
        return;
    }
    try {
        this.valueContext.waitForLocationReady(this.locationReadyTimeout);
        refreshLocationInfo();
    } catch (InterruptedException e) {
        throw new PolarisException(ErrorCode.LOCATION_MISMATCH, "caller location not ready,and strict nearby is true.", e);
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException)

Aggregations

PolarisException (com.tencent.polaris.api.exception.PolarisException)39 HashMap (java.util.HashMap)8 Test (org.junit.Test)8 RetriableException (com.tencent.polaris.api.exception.RetriableException)7 ServiceKey (com.tencent.polaris.api.pojo.ServiceKey)7 ConsumerAPI (com.tencent.polaris.api.core.ConsumerAPI)6 InstancesResponse (com.tencent.polaris.api.rpc.InstancesResponse)6 Configuration (com.tencent.polaris.api.config.Configuration)5 GetOneInstanceRequest (com.tencent.polaris.api.rpc.GetOneInstanceRequest)5 ServiceCallResult (com.tencent.polaris.api.rpc.ServiceCallResult)5 CommonProviderRequest (com.tencent.polaris.api.plugin.server.CommonProviderRequest)3 Instance (com.tencent.polaris.api.pojo.Instance)3 ServiceEventKey (com.tencent.polaris.api.pojo.ServiceEventKey)3 PolarisGRPCGrpc (com.tencent.polaris.client.pb.PolarisGRPCGrpc)3 ResponseProto (com.tencent.polaris.client.pb.ResponseProto)3 Map (java.util.Map)3 CircuitBreakerConfig (com.tencent.polaris.api.config.consumer.CircuitBreakerConfig)2 OutlierDetectionConfig (com.tencent.polaris.api.config.consumer.OutlierDetectionConfig)2 Verifier (com.tencent.polaris.api.config.verify.Verifier)2 Plugin (com.tencent.polaris.api.plugin.Plugin)2