Search in sources :

Example 36 with PolarisException

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

the class Validator method validateGetResourcesRequest.

/**
 * 校验获取资源请求
 *
 * @param request 请求对象
 * @throws PolarisException 校验失败
 */
public static void validateGetResourcesRequest(GetResourcesRequest request) throws PolarisException {
    Set<ServiceEventKey> svcEventKeys = request.getSvcEventKeys();
    if (CollectionUtils.isEmpty(svcEventKeys)) {
        return;
    }
    for (ServiceEventKey svcEventKey : svcEventKeys) {
        ServiceKey serviceKey = svcEventKey.getServiceKey();
        ServiceEventKey.EventType eventType = svcEventKey.getEventType();
        if (null == serviceKey || null == eventType) {
            throw new PolarisException(ErrorCode.API_INVALID_ARGUMENT, "missing service key or event type");
        }
        CommonValidator.validateNamespaceService(serviceKey.getNamespace(), serviceKey.getService());
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) ServiceKey(com.tencent.polaris.api.pojo.ServiceKey) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey)

Example 37 with PolarisException

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

the class InMemoryRegistry method loadRemoteValue.

/**
 * 加载资源
 *
 * @param svcEventKey 服务资源名
 * @param notifier    通知器
 * @throws PolarisException 异常
 */
private void loadRemoteValue(ServiceEventKey svcEventKey, EventCompleteNotifier notifier) throws PolarisException {
    checkDestroyed();
    CacheHandler handler = cacheHandlers.get(svcEventKey.getEventType());
    if (null == handler) {
        throw new PolarisException(ErrorCode.INTERNAL_ERROR, String.format("[LocalRegistry] unRegistered resource type %s", svcEventKey.getEventType()));
    }
    CacheObject cacheObject = resourceMap.computeIfAbsent(svcEventKey, serviceEventKey -> new CacheObject(handler, svcEventKey, InMemoryRegistry.this));
    // 添加监听器
    cacheObject.addNotifier(notifier);
    // 触发往serverConnector注册
    if (cacheObject.startRegister()) {
        LOG.info("[LocalRegistry]start to register service handler for {}", svcEventKey);
        try {
            connector.registerServiceHandler(enhanceServiceEventHandler(new ServiceEventHandler(svcEventKey, cacheObject)));
        } catch (Throwable e) {
            PolarisException polarisException;
            if (e instanceof PolarisException) {
                polarisException = (PolarisException) e;
            } else {
                polarisException = new PolarisException(ErrorCode.INTERNAL_ERROR, String.format("exception occurs while registering service handler for %s", svcEventKey));
            }
            cacheObject.resumeUnRegistered(polarisException);
            throw polarisException;
        }
        if (svcEventKey.getEventType() == EventType.INSTANCE) {
            // 注册了监听后,认为是被用户需要的服务,加入serviceSet
            services.put(svcEventKey.getServiceKey(), true);
        }
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) CacheHandler(com.tencent.polaris.api.plugin.registry.CacheHandler) ServiceEventHandler(com.tencent.polaris.api.plugin.server.ServiceEventHandler)

Example 38 with PolarisException

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

the class NearbyRouter method router.

@Override
public RouteResult router(RouteInfo routeInfo, ServiceInstances serviceInstances) throws PolarisException {
    // 先获取最低可用就近级别
    LocationLevel minAvailableLevel = config.getMatchLevel();
    if (null == minAvailableLevel) {
        minAvailableLevel = defaultMinLevel;
    }
    LocationLevel minLevel = minAvailableLevel;
    if (null != routeInfo.getNextRouterInfo()) {
        if (null != routeInfo.getNextRouterInfo().getLocationLevel()) {
            minLevel = routeInfo.getNextRouterInfo().getLocationLevel();
        }
        if (null != routeInfo.getNextRouterInfo().getMinAvailableLevel()) {
            minAvailableLevel = routeInfo.getNextRouterInfo().getMinAvailableLevel();
        }
    }
    LocationLevel maxLevel = config.getMaxMatchLevel();
    if (null == maxLevel) {
        maxLevel = LocationLevel.all;
    }
    Map<LocationLevel, String> clientLocationInfo = locationInfo.get();
    if (minLevel.ordinal() >= maxLevel.ordinal()) {
        List<Instance> instances = selectInstances(serviceInstances, minAvailableLevel, clientLocationInfo);
        if (CollectionUtils.isEmpty(instances)) {
            throw new PolarisException(ErrorCode.LOCATION_MISMATCH, String.format("can not find any instance by level %s", minLevel.name()));
        }
        // 已经循环了一圈
        return new RouteResult(selectInstances(serviceInstances, minAvailableLevel, clientLocationInfo), RouteResult.State.Next);
    }
    CheckResult checkResult = new CheckResult();
    for (int i = minLevel.ordinal(); i <= maxLevel.ordinal(); i++) {
        LocationLevel curLevel = LocationLevel.values()[i];
        checkResult = hasHealthyInstances(serviceInstances, routeInfo.getStatusDimensions(), curLevel, clientLocationInfo);
        checkResult.curLevel = curLevel;
        if (!CollectionUtils.isEmpty(checkResult.instances)) {
            break;
        } else {
            minAvailableLevel = curLevel;
        }
    }
    if (CollectionUtils.isEmpty(checkResult.instances)) {
        throw new PolarisException(ErrorCode.LOCATION_MISMATCH, String.format("can not find any instance by level %s", checkResult.curLevel.name()));
    }
    if (!config.isEnableDegradeByUnhealthyPercent() || checkResult.curLevel == LocationLevel.all) {
        return new RouteResult(checkResult.instances, RouteResult.State.Next);
    }
    int healthyInstanceCount = checkResult.healthyInstanceCount;
    double actualHealthyPercent = (double) healthyInstanceCount / (double) serviceInstances.getInstances().size();
    if (actualHealthyPercent <= healthyPercentToDegrade) {
        LOG.debug("[shouldDegrade] enableDegradeByUnhealthyPercent = {},unhealthyPercentToDegrade={}," + "healthyPercent={},isStrict={},matchLevel={}", config.isEnableDegradeByUnhealthyPercent(), config.getUnhealthyPercentToDegrade(), actualHealthyPercent, config.isStrictNearby(), checkResult.curLevel);
        RouteResult result = new RouteResult(checkResult.instances, RouteResult.State.Retry);
        result.getNextRouterInfo().setLocationLevel(nextLevel(checkResult.curLevel));
        result.getNextRouterInfo().setMinAvailableLevel(minAvailableLevel);
        return result;
    }
    return new RouteResult(checkResult.instances, RouteResult.State.Next);
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) Utils.isHealthyInstance(com.tencent.polaris.client.util.Utils.isHealthyInstance) Instance(com.tencent.polaris.api.pojo.Instance) RouteResult(com.tencent.polaris.api.plugin.route.RouteResult) LocationLevel(com.tencent.polaris.api.plugin.route.LocationLevel)

Example 39 with PolarisException

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

the class PolarisServiceRegistry method heartbeat.

private void heartbeat() {
    String host = polarisProperties.getHost();
    Integer port = polarisProperties.getPort();
    InstanceHeartbeatRequest heartbeatRequest = new InstanceHeartbeatRequest();
    heartbeatRequest.setNamespace(polarisProperties.getNamespace());
    heartbeatRequest.setService(polarisProperties.getService());
    heartbeatRequest.setHost(host);
    heartbeatRequest.setPort(port);
    try {
        heartbeatExecutor.scheduleWithFixedDelay(() -> {
            PolarisAPIFactory.getProviderApi().heartbeat(heartbeatRequest);
            log.info("heartbeat instance, address is {}:{}", host, port);
        }, ttl, ttl, TimeUnit.SECONDS);
    } catch (PolarisException e) {
        log.error(e.getMessage());
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) InstanceHeartbeatRequest(com.tencent.polaris.api.rpc.InstanceHeartbeatRequest)

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