com.alibaba.csp.sentinel.Constants Java Examples
The following examples show how to use
com.alibaba.csp.sentinel.Constants.
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: CommonFilterContextTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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); }
Example #2
Source File: SentinelJaxRsQuarkusAdapterTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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); }
Example #3
Source File: SentinelJaxRsQuarkusAdapterTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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); }
Example #4
Source File: HttpHeartbeatSender.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 6 votes |
@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; }
Example #5
Source File: SentinelOkHttpInterceptorTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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(); }
Example #6
Source File: BaseTest.java From Sentinel with Apache License 2.0 | 6 votes |
/** * 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 } }
Example #7
Source File: DegradeRuleManager.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 6 votes |
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; }
Example #8
Source File: ProviderFilterTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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); }
Example #9
Source File: ProviderFilterTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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); }
Example #10
Source File: ClientFilterTest.java From Sentinel with Apache License 2.0 | 6 votes |
@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 } }
Example #11
Source File: HeartbeatMessage.java From Sentinel with Apache License 2.0 | 5 votes |
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; }
Example #12
Source File: StatisticSlot.java From Sentinel with Apache License 2.0 | 5 votes |
@Override public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) { Node node = context.getCurNode(); if (context.getCurEntry().getBlockError() == null) { // Calculate response time (use completeStatTime as the time of completion). long completeStatTime = TimeUtil.currentTimeMillis(); context.getCurEntry().setCompleteTimestamp(completeStatTime); long rt = completeStatTime - context.getCurEntry().getCreateTimestamp(); Throwable error = context.getCurEntry().getError(); // Record response time and success count. recordCompleteFor(node, count, rt, error); recordCompleteFor(context.getCurEntry().getOriginNode(), count, rt, error); if (resourceWrapper.getEntryType() == EntryType.IN) { recordCompleteFor(Constants.ENTRY_NODE, count, rt, error); } } // 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); }
Example #13
Source File: ContextTest.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
@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(); } }
Example #14
Source File: ClientFilterTest.java From Sentinel with Apache License 2.0 | 5 votes |
@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); }
Example #15
Source File: SendMetricCommandHandler.java From Sentinel with Apache License 2.0 | 5 votes |
/** * 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); } }
Example #16
Source File: FetchSystemStatusCommandHandler.java From Sentinel with Apache License 2.0 | 5 votes |
@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)); }
Example #17
Source File: ContextUtil.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
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; } }
Example #18
Source File: HttpHeartbeatSender.java From Sentinel with Apache License 2.0 | 5 votes |
@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; }
Example #19
Source File: HttpServerHandlerTest.java From Sentinel with Apache License 2.0 | 5 votes |
/** * {@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); }
Example #20
Source File: MonoSentinelOperatorIntegrationTest.java From Sentinel with Apache License 2.0 | 5 votes |
@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<>()); }
Example #21
Source File: CommonFilterTest.java From Sentinel with Apache License 2.0 | 5 votes |
@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(); }
Example #22
Source File: ArrayMetric.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
@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); }
Example #23
Source File: FetchSystemStatusCommandHandler.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
@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)); }
Example #24
Source File: SendMetricCommandHandler.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
/** * 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); } }
Example #25
Source File: ContextTest.java From Sentinel with Apache License 2.0 | 5 votes |
@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(); } }
Example #26
Source File: HeartbeatMessage.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
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; }
Example #27
Source File: HttpServerHandlerTest.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
/** * {@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); }
Example #28
Source File: ContextUtil.java From Sentinel with Apache License 2.0 | 5 votes |
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; } }
Example #29
Source File: MonoSentinelOperatorIntegrationTest.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
@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<>()); }
Example #30
Source File: ContextUtil.java From Sentinel with Apache License 2.0 | 5 votes |
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 { LOCK.lock(); try { 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; }