Java源码示例:com.alibaba.csp.sentinel.Constants

示例1
@Override
public boolean sendHeartbeat() throws Exception {
    if (StringUtil.isEmpty(consoleHost)) {
        return false;
    }
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http").setHost(consoleHost).setPort(consolePort)
        .setPath("/registry/machine")
        .setParameter("app", AppNameUtil.getAppName())
        .setParameter("app_type", String.valueOf(SentinelConfig.getAppType()))
        .setParameter("v", Constants.SENTINEL_VERSION)
        .setParameter("version", String.valueOf(System.currentTimeMillis()))
        .setParameter("hostname", HostNameUtil.getHostName())
        .setParameter("ip", TransportConfig.getHeartbeatClientIp())
        .setParameter("port", TransportConfig.getPort())
        .setParameter("pid", String.valueOf(PidUtil.getPid()));

    HttpGet request = new HttpGet(uriBuilder.build());
    request.setConfig(requestConfig);
    // Send heartbeat request.
    CloseableHttpResponse response = client.execute(request);
    response.close();
    return true;
}
 
示例2
public static boolean isValidRule(DegradeRule rule) {
    boolean baseValid = rule != null && !StringUtil.isBlank(rule.getResource())
        && rule.getCount() >= 0 && rule.getTimeWindow() > 0;
    if (!baseValid) {
        return false;
    }
    int maxAllowedRt = Constants.TIME_DROP_VALVE;
    if (rule.getGrade() == RuleConstant.DEGRADE_GRADE_RT) {
        if (rule.getRtSlowRequestAmount() <= 0) {
            return false;
        }
        // Warn for RT mode that exceeds the {@code TIME_DROP_VALVE}.
        if (rule.getCount() > maxAllowedRt) {
            RecordLog.warn(String.format("[DegradeRuleManager] WARN: setting large RT threshold (%.1f ms)"
                    + " in RT mode will not take effect since it exceeds the max allowed value (%d ms)",
                rule.getCount(), maxAllowedRt));
        }
    }

    // Check exception ratio mode.
    if (rule.getGrade() == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
        return rule.getCount() <= 1 && rule.getMinRequestAmount() > 0;
    }
    return true;
}
 
示例3
@Test
public void testSentinelOkHttpInterceptor0() throws Exception {

    String url0 = "http://localhost:" + port + "/okhttp/back";
    SentinelOkHttpConfig.setPrefix("okhttp:");
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new SentinelOkHttpInterceptor())
            .build();
    Request request = new Request.Builder()
            .url(url0)
            .build();
    System.out.println(client.newCall(request).execute().body().string());
    ClusterNode cn = ClusterBuilderSlot.getClusterNode(SentinelOkHttpConfig.getPrefix() + "GET:" + url0);
    assertNotNull(cn);

    Constants.ROOT.removeChildList();
    ClusterBuilderSlot.getClusterNodeMap().clear();
}
 
示例4
@Test
public void testGetHello() {
    String url = "/test/hello";
    String resourceName = "GET:" + url;
    Response response = given().get(url);
    response.then().statusCode(200).body(equalTo(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);
}
 
示例5
@Test
public void testAsyncGetHello() {
    String url = "/test/async-hello";
    String resourceName = "GET:" + url;
    Response response = given().get(url);
    response.then().statusCode(200).body(equalTo(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);
}
 
示例6
@Test
public void testCommonFilterMiscellaneous() throws Exception {
    String url = "/hello";
    this.mvc.perform(get(url))
            .andExpect(status().isOk())
            .andExpect(content().string(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);
    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals(url, context);
}
 
示例7
@Test
public void testGetHello() {
    String url = "/test/hello";
    String resourceName = "GET:" + url;
    Response response = given().get(url);
    response.then().statusCode(200).body(equalTo(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);
}
 
示例8
@Test
public void testAsyncGetHello() {
    String url = "/test/async-hello";
    String resourceName = "GET:" + url;
    Response response = given().get(url);
    response.then().statusCode(200).body(equalTo(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);
}
 
示例9
@AfterClass
public static void shutdown() {
    ctx.close();

    Context context = ContextUtil.getContext();
    if (context != null) {
        context.setCurEntry(null);
        ContextUtil.exit();
    }

    Constants.ROOT.removeChildList();

    ClusterBuilderSlot.getClusterNodeMap().clear();

    // Clear chainMap in CtSph
    try {
        Method resetChainMapMethod = CtSph.class.getDeclaredMethod("resetChainMap");
        resetChainMapMethod.setAccessible(true);
        resetChainMapMethod.invoke(null);
    } catch (Exception e) {
        // Empty
    }
}
 
示例10
/**
 * Clean up resources.
 */
protected static void cleanUpAll() {
    Context context = ContextUtil.getContext();
    if (context != null) {
        context.setCurEntry(null);
        ContextUtil.exit();
    }

    Constants.ROOT.removeChildList();

    ClusterBuilderSlot.getClusterNodeMap().clear();

    // Clear chainMap in CtSph
    try {
        Method resetChainMapMethod = CtSph.class.getDeclaredMethod("resetChainMap");
        resetChainMapMethod.setAccessible(true);
        resetChainMapMethod.invoke(null);
    } catch (Exception e) {
        // Empty
    }
}
 
示例11
/**
 * add current cpu usage and load to the metric list.
 *
 * @param list metric list, should not be null
 */
private void addCpuUsageAndLoad(List<MetricNode> list) {
    long time = TimeUtil.currentTimeMillis() / 1000 * 1000;
    double load = SystemRuleManager.getCurrentSystemAvgLoad();
    double usage = SystemRuleManager.getCurrentCpuUsage();
    if (load > 0) {
        MetricNode loadNode = toNode(load, time, Constants.SYSTEM_LOAD_RESOURCE_NAME);
        list.add(loadNode);
    }
    if (usage > 0) {
        MetricNode usageNode = toNode(usage, time, Constants.CPU_USAGE_RESOURCE_NAME);
        list.add(usageNode);
    }
}
 
示例12
@Override
public CommandResponse<String> handle(CommandRequest request) {

    Map<String, Object> systemStatus = new HashMap<String, Object>();

    systemStatus.put("rqps", Constants.ENTRY_NODE.successQps());
    systemStatus.put("qps", Constants.ENTRY_NODE.passQps());
    systemStatus.put("b", Constants.ENTRY_NODE.blockQps());
    systemStatus.put("r", Constants.ENTRY_NODE.avgRt());
    systemStatus.put("t", Constants.ENTRY_NODE.curThreadNum());

    return CommandResponse.ofSuccess(JSONObject.toJSONString(systemStatus));
}
 
示例13
public Map<String, String> generateCurrentMessage() {
    // Version of Sentinel.
    message.put("v", Constants.SENTINEL_VERSION);
    // Actually timestamp.
    message.put("version", String.valueOf(TimeUtil.currentTimeMillis()));
    message.put("port", String.valueOf(TransportConfig.getPort()));
    return message;
}
 
示例14
/**
 * {@link com.alibaba.csp.sentinel.command.handler.VersionCommandHandler}
 */
@Test
public void testVersionCommand() {
    String httpRequestStr = "GET /version HTTP/1.1" + CRLF
                          + "Host: localhost:8719" + CRLF
                          + CRLF;
    String expectedBody = Constants.SENTINEL_VERSION;

    processSuccess(httpRequestStr, expectedBody);
}
 
示例15
@Test
public void testTransformMonoWithSentinelContextEnter() {
    String resourceName = createResourceName("testTransformMonoWithSentinelContextEnter");
    String contextName = "test_reactive_context";
    String origin = "originA";
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0).setLimitApp(origin).as(FlowRule.class)
    ));
    StepVerifier.create(Mono.just(2)
        .transform(new SentinelReactorTransformer<>(
            // Customized context with origin.
            new EntryConfig(resourceName, EntryType.OUT, new ContextConfig(contextName, origin))))
    )
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());
    assertTrue(Constants.ROOT.getChildList()
        .stream()
        .filter(node -> node instanceof EntranceNode)
        .map(e -> (EntranceNode)e)
        .anyMatch(e -> e.getId().getName().equals(contextName))
    );

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
示例16
@Override
public long minRt() {
    data.currentWindow();
    long rt = Constants.TIME_DROP_VALVE;
    List<MetricBucket> list = data.values();
    for (MetricBucket window : list) {
        if (window.minRt() < rt) {
            rt = window.minRt();
        }
    }

    return Math.max(1, rt);
}
 
示例17
@Override
public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
    DefaultNode node = (DefaultNode)context.getCurNode();

    if (context.getCurEntry().getError() == null) {
        // Calculate response time (max RT is TIME_DROP_VALVE).
        long rt = TimeUtil.currentTimeMillis() - context.getCurEntry().getCreateTime();
        if (rt > Constants.TIME_DROP_VALVE) {
            rt = Constants.TIME_DROP_VALVE;
        }

        // Record response time and success count.
        node.addRtAndSuccess(rt, count);
        if (context.getCurEntry().getOriginNode() != null) {
            context.getCurEntry().getOriginNode().addRtAndSuccess(rt, count);
        }

        node.decreaseThreadNum();

        if (context.getCurEntry().getOriginNode() != null) {
            context.getCurEntry().getOriginNode().decreaseThreadNum();
        }

        if (resourceWrapper.getType() == EntryType.IN) {
            Constants.ENTRY_NODE.addRtAndSuccess(rt, count);
            Constants.ENTRY_NODE.decreaseThreadNum();
        }
    } else {
        // Error may happen.
    }

    // Handle exit event with registered exit callback handlers.
    Collection<ProcessorSlotExitCallback> exitCallbacks = StatisticSlotCallbackRegistry.getExitCallbacks();
    for (ProcessorSlotExitCallback handler : exitCallbacks) {
        handler.onExit(context, resourceWrapper, count, args);
    }

    fireExit(context, resourceWrapper, count);
}
 
示例18
@Override
public void run() {
    try {
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        currentLoad = osBean.getSystemLoadAverage();
        /**
         * Java Doc copied from {@link OperatingSystemMXBean#getSystemCpuLoad()}:</br>
         * Returns the "recent cpu usage" for the whole system. This value is a double in the [0.0,1.0] interval.
         * A value of 0.0 means that all CPUs were idle during the recent period of time observed, while a value
         * of 1.0 means that all CPUs were actively running 100% of the time during the recent period being
         * observed. All values betweens 0.0 and 1.0 are possible depending of the activities going on in the
         * system. If the system recent cpu usage is not available, the method returns a negative value.
         */
        currentCpuUsage = osBean.getSystemCpuLoad();

        StringBuilder sb = new StringBuilder();
        if (currentLoad > SystemRuleManager.getHighestSystemLoad()) {
            sb.append("load:").append(currentLoad).append(";");
            sb.append("cpu:").append(currentCpuUsage).append(";");
            sb.append("qps:").append(Constants.ENTRY_NODE.passQps()).append(";");
            sb.append("rt:").append(Constants.ENTRY_NODE.avgRt()).append(";");
            sb.append("thread:").append(Constants.ENTRY_NODE.curThreadNum()).append(";");
            sb.append("success:").append(Constants.ENTRY_NODE.successQps()).append(";");
            sb.append("minRt:").append(Constants.ENTRY_NODE.minRt()).append(";");
            sb.append("maxSuccess:").append(Constants.ENTRY_NODE.maxSuccessQps()).append(";");
            RecordLog.info(sb.toString());
        }

    } catch (Throwable e) {
        RecordLog.info("could not get system error ", e);
    }
}
 
示例19
private static boolean checkBbr(int currentThread) {
    if (currentThread > 1 &&
        currentThread > Constants.ENTRY_NODE.maxSuccessQps() * Constants.ENTRY_NODE.minRt() / 1000) {
        return false;
    }
    return true;
}
 
示例20
protected static Context trueEnter(String name, String origin) {
    Context context = contextHolder.get();
    if (context == null) {
        Map<String, DefaultNode> localCacheNameMap = contextNameNodeMap;
        DefaultNode node = localCacheNameMap.get(name);
        if (node == null) {
            if (localCacheNameMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
                setNullContext();
                return NULL_CONTEXT;
            } else {
                try {
                    LOCK.lock();
                    node = contextNameNodeMap.get(name);
                    if (node == null) {
                        if (contextNameNodeMap.size() > Constants.MAX_CONTEXT_NAME_SIZE) {
                            setNullContext();
                            return NULL_CONTEXT;
                        } else {
                            node = new EntranceNode(new StringResourceWrapper(name, EntryType.IN), null);
                            // Add entrance node.
                            Constants.ROOT.addChild(node);

                            Map<String, DefaultNode> newMap = new HashMap<>(contextNameNodeMap.size() + 1);
                            newMap.putAll(contextNameNodeMap);
                            newMap.put(name, node);
                            contextNameNodeMap = newMap;
                        }
                    }
                } finally {
                    LOCK.unlock();
                }
            }
        }
        context = new Context(node, name);
        context.setOrigin(origin);
        contextHolder.set(context);
    }

    return context;
}
 
示例21
private static void setNullContext() {
    contextHolder.set(NULL_CONTEXT);
    // Don't need to be thread-safe.
    if (shouldWarn) {
        RecordLog.warn("[SentinelStatusChecker] WARN: Amount of context exceeds the threshold "
            + Constants.MAX_CONTEXT_NAME_SIZE + ". Entries in new contexts will NOT take effect!");
        shouldWarn = false;
    }
}
 
示例22
@Test
public void testDefaultContextWhenExceedsThreshold() {
    fillContext();
    try {
        ContextUtil.trueEnter(Constants.CONTEXT_DEFAULT_NAME, "");
        Context curContext = ContextUtil.getContext();
        assertEquals(Constants.CONTEXT_DEFAULT_NAME, curContext.getName());
        assertNotNull(curContext.getEntranceNode());
    } finally {
        ContextUtil.exit();
        resetContextMap();
    }
}
 
示例23
/**
 * add current cpu usage and load to the metric list.
 *
 * @param list metric list, should not be null
 */
private void addCpuUsageAndLoad(List<MetricNode> list) {
    long time = TimeUtil.currentTimeMillis() / 1000 * 1000;
    double load = SystemRuleManager.getCurrentSystemAvgLoad();
    double usage = SystemRuleManager.getCurrentCpuUsage();
    if (load > 0) {
        MetricNode loadNode = toNode(load, time, Constants.SYSTEM_LOAD_RESOURCE_NAME);
        list.add(loadNode);
    }
    if (usage > 0) {
        MetricNode usageNode = toNode(usage, time, Constants.CPU_USAGE_RESOURCE_NAME);
        list.add(usageNode);
    }
}
 
示例24
@Override
public CommandResponse<String> handle(CommandRequest request) {

    Map<String, Object> systemStatus = new HashMap<String, Object>();

    systemStatus.put("rqps", Constants.ENTRY_NODE.successQps());
    systemStatus.put("qps", Constants.ENTRY_NODE.passQps());
    systemStatus.put("b", Constants.ENTRY_NODE.blockQps());
    systemStatus.put("r", Constants.ENTRY_NODE.avgRt());
    systemStatus.put("t", Constants.ENTRY_NODE.curThreadNum());

    return CommandResponse.ofSuccess(JSONObject.toJSONString(systemStatus));
}
 
示例25
public Map<String, String> generateCurrentMessage() {
    // Version of Sentinel.
    message.put("v", Constants.SENTINEL_VERSION);
    // Actually timestamp.
    message.put("version", String.valueOf(TimeUtil.currentTimeMillis()));
    message.put("port", String.valueOf(TransportConfig.getPort()));
    return message;
}
 
示例26
@Override
public boolean sendHeartbeat() throws Exception {
    if (StringUtil.isEmpty(consoleHost)) {
        return false;
    }
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http").setHost(consoleHost).setPort(consolePort)
        .setPath(TransportConfig.getHeartbeatApiPath())
        .setParameter("app", AppNameUtil.getAppName())
        .setParameter("app_type", String.valueOf(SentinelConfig.getAppType()))
        .setParameter("v", Constants.SENTINEL_VERSION)
        .setParameter("version", String.valueOf(System.currentTimeMillis()))
        .setParameter("hostname", HostNameUtil.getHostName())
        .setParameter("ip", TransportConfig.getHeartbeatClientIp())
        .setParameter("port", TransportConfig.getPort())
        .setParameter("pid", String.valueOf(PidUtil.getPid()));

    HttpGet request = new HttpGet(uriBuilder.build());
    request.setConfig(requestConfig);
    // Send heartbeat request.
    CloseableHttpResponse response = client.execute(request);
    response.close();
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == OK_STATUS) {
        return true;
    } else if (clientErrorCode(statusCode) || serverErrorCode(statusCode)) {
        RecordLog.warn("[HttpHeartbeatSender] Failed to send heartbeat to "
            + consoleHost + ":" + consolePort + ", http status code: " + statusCode);
    }

    return false;
}
 
示例27
/**
 * {@link com.alibaba.csp.sentinel.command.handler.VersionCommandHandler}
 */
@Test
public void testVersionCommand() {
    String httpRequestStr = "GET /version HTTP/1.1" + CRLF
                          + "Host: localhost:8719" + CRLF
                          + CRLF;
    String expectedBody = Constants.SENTINEL_VERSION;

    processSuccess(httpRequestStr, expectedBody);
}
 
示例28
@Test
public void testTransformMonoWithSentinelContextEnter() {
    String resourceName = createResourceName("testTransformMonoWithSentinelContextEnter");
    String contextName = "test_reactive_context";
    String origin = "originA";
    FlowRuleManager.loadRules(Collections.singletonList(
        new FlowRule(resourceName).setCount(0).setLimitApp(origin).as(FlowRule.class)
    ));
    StepVerifier.create(Mono.just(2)
        .transform(new SentinelReactorTransformer<>(
            // Customized context with origin.
            new EntryConfig(resourceName, EntryType.OUT, new ContextConfig(contextName, origin))))
    )
        .expectError(BlockException.class)
        .verify();

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(0, cn.passQps(), 0.01);
    assertEquals(1, cn.blockRequest());
    assertTrue(Constants.ROOT.getChildList()
        .stream()
        .filter(node -> node instanceof EntranceNode)
        .map(e -> (EntranceNode)e)
        .anyMatch(e -> e.getId().getName().equals(contextName))
    );

    FlowRuleManager.loadRules(new ArrayList<>());
}
 
示例29
@Test
public void testCommonFilterMiscellaneous() throws Exception {
    Constants.ROOT.removeChildList();
    String url = "/hello";
    this.mvc.perform(get(url))
        .andExpect(status().isOk())
        .andExpect(content().string(HELLO_STR));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(url);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);

    testCommonBlockAndRedirectBlockPage(url, cn);

    // Test for url cleaner.
    testUrlCleaner();
    testUrlExclusion();
    testCustomOriginParser();
}
 
示例30
@Test
public void testClientGetHello() {
    final String url = "/test/hello";
    String resourceName = "GET:" + url;
    Response response = SentinelJaxRsClientTemplate.execute(resourceName, new Supplier<Response>() {

        @Override
        public Response get() {
            return client.target(host).path(url).request()
                    .get();
        }
    });
    assertEquals(200, response.getStatus());
    assertEquals(HELLO_STR, response.readEntity(String.class));

    ClusterNode cn = ClusterBuilderSlot.getClusterNode(resourceName);
    assertNotNull(cn);
    assertEquals(1, cn.passQps(), 0.01);

    String context = "";
    for (Node n : Constants.ROOT.getChildList()) {
        if (n instanceof EntranceNode) {
            String id = ((EntranceNode) n).getId().getName();
            if (url.equals(id)) {
                context = ((EntranceNode) n).getId().getName();
            }
        }
    }
    assertEquals("", context);
}