Search in sources :

Example 11 with PolarisException

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

the class HttpHealthChecker method detectInstance.

@Override
public DetectResult detectInstance(Instance instance) throws PolarisException {
    try {
        // TODO 从配置读取
        String pattern = "/detect";
        String path = String.format("http://%s:%d%s", instance.getHost(), instance.getPort(), pattern);
        java.net.URL url = new java.net.URL(path);
        java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // 连接超时
        conn.setConnectTimeout(3 * 1000);
        // 读取超时
        conn.setReadTimeout(3 * 1000);
        if (conn.getResponseCode() == EXPECT_CODE) {
            return new DetectResult(RetStatus.RetSuccess);
        }
        return new DetectResult(RetStatus.RetFail);
    } catch (Exception e) {
        LOG.error("http detect exception, service:{}, host:{}, port:{}, e:{}", instance.getService(), instance.getHost(), instance.getPort(), e);
        return new DetectResult(RetStatus.RetFail);
    }
}
Also used : DetectResult(com.tencent.polaris.api.pojo.DetectResult) PolarisException(com.tencent.polaris.api.exception.PolarisException)

Example 12 with PolarisException

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

the class UdpHealthChecker method detectInstance.

@Override
public DetectResult detectInstance(Instance instance) throws PolarisException {
    DatagramSocket socket = null;
    try {
        // TODO 从配置中读取
        String sendStr = "detect";
        InetAddress inet = InetAddress.getByName(instance.getHost());
        byte[] sendBytes = sendStr.getBytes("UTF8");
        socket = new DatagramSocket();
        // 两秒接收不到数据认为超时,防止获取不到连接一直在receive阻塞
        socket.setSoTimeout(2000);
        // 发送数据
        DatagramPacket sendPacket = new DatagramPacket(sendBytes, sendBytes.length, inet, instance.getPort());
        socket.send(sendPacket);
        byte[] recvBuf = new byte[1024];
        DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
        socket.receive(recvPacket);
        socket.close();
        String expectRecvStr = "ok";
        byte[] expectRecvBytes = expectRecvStr.getBytes("UTF8");
        if (!Arrays.equals(Arrays.copyOfRange(recvBuf, 0, expectRecvBytes.length), expectRecvBytes)) {
            return new DetectResult(RetStatus.RetFail);
        }
        return new DetectResult(RetStatus.RetSuccess);
    } catch (Exception e) {
        LOG.error("udp detect instance exception, host:{}, port:{}, e:{}", instance.getHost(), instance.getPort(), e);
        return null;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}
Also used : DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) DetectResult(com.tencent.polaris.api.pojo.DetectResult) InetAddress(java.net.InetAddress) PolarisException(com.tencent.polaris.api.exception.PolarisException)

Example 13 with PolarisException

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

the class WeightedRandomBalance method chooseInstance.

@Override
public Instance chooseInstance(Criteria criteria, ServiceInstances svcInstances) throws PolarisException {
    int totalWeight = svcInstances.getTotalWeight();
    if (totalWeight <= 0) {
        totalWeight = sumTotalWeight(svcInstances);
    }
    if (totalWeight == 0) {
        throw new PolarisException(ErrorCode.INSTANCE_NOT_FOUND, String.format("all instances weight 0 for %s:%s", svcInstances.getNamespace(), svcInstances.getService()));
    }
    // 进行权重区间分配
    List<Instance> instances = svcInstances.getInstances();
    int randomValue = Math.abs(random.nextInt() % totalWeight);
    int start = 0;
    int end = 0;
    for (Instance instance : instances) {
        end = end + instance.getWeight();
        if (randomValue >= start && randomValue < end) {
            return instance;
        }
        start = end;
    }
    // 全都分配不到,则随机获取一个
    return instances.get(totalWeight % instances.size());
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) Instance(com.tencent.polaris.api.pojo.Instance)

Example 14 with PolarisException

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

the class ConsecutiveCircuitBreaker method init.

@Override
public void init(InitContext ctx) throws PolarisException {
    CircuitBreakerConfig circuitBreakerConfig = ctx.getConfig().getConsumer().getCircuitBreaker();
    OutlierDetectionConfig outlierDetection = ctx.getConfig().getConsumer().getOutlierDetection();
    HalfOpenConfig halfOpenConfig = new HalfOpenConfig(circuitBreakerConfig, outlierDetection);
    Config cfg = circuitBreakerConfig.getPluginConfig(getName(), Config.class);
    if (cfg == null) {
        throw new PolarisException(ErrorCode.INVALID_CONFIG, String.format("plugin %s config is missing", getName()));
    }
    ConfigSet<Config> configSet = new ConfigSet<>(StatusDimension.Level.SERVICE, false, halfOpenConfig, cfg);
    configGroup = new ConfigGroup<>(configSet);
    stateMachine = new StateMachineImpl(configGroup, id, this);
    flowControlParam = new DefaultFlowControlParam(ctx.getConfig().getGlobal().getAPI());
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) OutlierDetectionConfig(com.tencent.polaris.api.config.consumer.OutlierDetectionConfig) DefaultFlowControlParam(com.tencent.polaris.client.flow.DefaultFlowControlParam) HalfOpenConfig(com.tencent.polaris.plugins.circuitbreaker.common.HalfOpenConfig) ConsecutiveErrConfig(com.tencent.polaris.client.pb.CircuitBreakerProto.CbPolicy.ConsecutiveErrConfig) OutlierDetectionConfig(com.tencent.polaris.api.config.consumer.OutlierDetectionConfig) RecoverConfig(com.tencent.polaris.client.pb.CircuitBreakerProto.RecoverConfig) CircuitBreakerConfig(com.tencent.polaris.api.config.consumer.CircuitBreakerConfig) HalfOpenConfig(com.tencent.polaris.plugins.circuitbreaker.common.HalfOpenConfig) CircuitBreakerConfig(com.tencent.polaris.api.config.consumer.CircuitBreakerConfig) ConfigSet(com.tencent.polaris.plugins.circuitbreaker.common.ConfigSet)

Example 15 with PolarisException

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

the class MetadataRouterTest method testFailoverNoneScene.

@Test
public void testFailoverNoneScene() {
    Configuration configuration = TestUtils.configWithEnvAddress();
    try (ConsumerAPI consumer = DiscoveryAPIFactory.createConsumerAPIByConfig(configuration)) {
        // 该服务下有四个实例,只有一个80端口实例满足metadata路由,但是不健康,降级策略采用默认不降级
        for (int i = 0; i < 10; i++) {
            GetOneInstanceRequest getInstances2 = new GetOneInstanceRequest();
            getInstances2.setNamespace(NAMESPACE_PRODUCTION);
            getInstances2.setService(METADATA_SERVICE);
            Map<String, String> map = new HashMap<>();
            map.put("Env-set", "1-1");
            getInstances2.setMetadata(map);
            InstancesResponse ins = null;
            try {
                ins = consumer.getOneInstance(getInstances2);
            } catch (PolarisException e) {
                Assert.assertEquals(ErrorCode.METADATA_MISMATCH, e.getCode());
            }
        }
    }
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) Configuration(com.tencent.polaris.api.config.Configuration) HashMap(java.util.HashMap) GetOneInstanceRequest(com.tencent.polaris.api.rpc.GetOneInstanceRequest) ConsumerAPI(com.tencent.polaris.api.core.ConsumerAPI) InstancesResponse(com.tencent.polaris.api.rpc.InstancesResponse) Test(org.junit.Test)

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