com.alibaba.csp.sentinel.transport.config.TransportConfig Java Examples

The following examples show how to use com.alibaba.csp.sentinel.transport.config.TransportConfig. 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: HeartbeatSenderInitFuncTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrieveInterval() {
    HeartbeatSender sender = mock(HeartbeatSender.class);

    long senderInterval = 5666;
    long configInterval = 6777;

    when(sender.intervalMs()).thenReturn(senderInterval);

    HeartbeatSenderInitFunc func = new HeartbeatSenderInitFunc();
    assertEquals(senderInterval, func.retrieveInterval(sender));

    // Invalid interval.
    SentinelConfig.setConfig(TransportConfig.HEARTBEAT_INTERVAL_MS, "-1");
    assertEquals(senderInterval, func.retrieveInterval(sender));

    SentinelConfig.setConfig(TransportConfig.HEARTBEAT_INTERVAL_MS, String.valueOf(configInterval));
    assertEquals(configInterval, func.retrieveInterval(sender));
}
 
Example #2
Source File: HeartbeatSenderInitFuncTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrieveInterval() {
    HeartbeatSender sender = mock(HeartbeatSender.class);

    long senderInterval = 5666;
    long configInterval = 6777;

    when(sender.intervalMs()).thenReturn(senderInterval);

    HeartbeatSenderInitFunc func = new HeartbeatSenderInitFunc();
    assertEquals(senderInterval, func.retrieveInterval(sender));

    // Invalid interval.
    SentinelConfig.setConfig(TransportConfig.HEARTBEAT_INTERVAL_MS, "-1");
    assertEquals(senderInterval, func.retrieveInterval(sender));

    SentinelConfig.setConfig(TransportConfig.HEARTBEAT_INTERVAL_MS, String.valueOf(configInterval));
    assertEquals(configInterval, func.retrieveInterval(sender));
}
 
Example #3
Source File: SimpleHttpHeartbeatSender.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sendHeartbeat() throws Exception {
    if (TransportConfig.getRuntimePort() <= 0) {
        RecordLog.info("[SimpleHttpHeartbeatSender] Runtime port not initialized, won't send heartbeat");
        return false;
    }
    InetSocketAddress addr = getAvailableAddress();
    if (addr == null) {
        return false;
    }

    SimpleHttpRequest request = new SimpleHttpRequest(addr, HEARTBEAT_PATH);
    request.setParams(heartBeat.generateCurrentMessage());
    try {
        SimpleHttpResponse response = httpClient.post(request);
        if (response.getStatusCode() == OK_STATUS) {
            return true;
        }
    } catch (Exception e) {
        RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addr + " : ", e);
    }
    return false;
}
 
Example #4
Source File: HttpHeartbeatSender.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@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: HttpHeartbeatSender.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@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 #6
Source File: HeartbeatMessage.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public HeartbeatMessage() {
    message.put("hostname", HostNameUtil.getHostName());
    message.put("ip", TransportConfig.getHeartbeatClientIp());
    message.put("app", AppNameUtil.getAppName());
    // Put application type (since 1.6.0).
    message.put("app_type", String.valueOf(SentinelConfig.getAppType()));
    message.put("port", String.valueOf(TransportConfig.getPort()));
}
 
Example #7
Source File: HeartbeatMessage.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
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 #8
Source File: SimpleHttpHeartbeatSender.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public SimpleHttpHeartbeatSender() {
    // Retrieve the list of default addresses.
    List<Tuple2<String, Integer>> newAddrs = TransportConfig.getConsoleServerList();
    if (newAddrs.isEmpty()) {
        RecordLog.warn("[SimpleHttpHeartbeatSender] Dashboard server address not configured or not available");
    } else {
        RecordLog.info("[SimpleHttpHeartbeatSender] Default console address list retrieved: " + newAddrs);
    }
    this.addressList = newAddrs;
}
 
Example #9
Source File: SimpleHttpHeartbeatSender.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public boolean sendHeartbeat() throws Exception {
    if (TransportConfig.getRuntimePort() <= 0) {
        RecordLog.info("[SimpleHttpHeartbeatSender] Command server port not initialized, won't send heartbeat");
        return false;
    }
    Tuple2<String, Integer> addrInfo = getAvailableAddress();
    if (addrInfo == null) {
        return false;
    }

    InetSocketAddress addr = new InetSocketAddress(addrInfo.r1, addrInfo.r2);
    SimpleHttpRequest request = new SimpleHttpRequest(addr, TransportConfig.getHeartbeatApiPath());
    request.setParams(heartBeat.generateCurrentMessage());
    try {
        SimpleHttpResponse response = httpClient.post(request);
        if (response.getStatusCode() == OK_STATUS) {
            return true;
        } else if (clientErrorCode(response.getStatusCode()) || serverErrorCode(response.getStatusCode())) {
            RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addr
                + ", http status code: " + response.getStatusCode());
        }
    } catch (Exception e) {
        RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addr, e);
    }
    return false;
}
 
Example #10
Source File: SimpleHttpCommandCenter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() throws Exception {
    if (socketReference != null) {
        try {
            socketReference.close();
        } catch (IOException e) {
            CommandCenterLog.warn("Error when releasing the server socket", e);
        }
    }
    bizExecutor.shutdownNow();
    executor.shutdownNow();
    TransportConfig.setRuntimePort(PORT_UNINITIALIZED);
    handlerMap.clear();
}
 
Example #11
Source File: HttpHeartbeatSender.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public HttpHeartbeatSender() {
    this.client = HttpClients.createDefault();
    List<Tuple2<String, Integer>> dashboardList = TransportConfig.getConsoleServerList();
    if (dashboardList == null || dashboardList.isEmpty()) {
        RecordLog.info("[NettyHttpHeartbeatSender] No dashboard server available");
        consoleHost = null;
        consolePort = -1;
    } else {
        consoleHost = dashboardList.get(0).r1;
        consolePort = dashboardList.get(0).r2;
        RecordLog.info(
            "[NettyHttpHeartbeatSender] Dashboard address parsed: <" + consoleHost + ':' + consolePort + ">");
    }
}
 
Example #12
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDataSourceFailed() throws Exception {
	when(sentinelProperties.isEnabled()).thenReturn(true);
	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
	when(heartbeatSender.sendHeartbeat()).thenReturn(true);

	Map<String, AbstractDataSource> dataSourceMap = new HashMap<>();

	FileRefreshableDataSource fileDataSource1 = mock(FileRefreshableDataSource.class);
	dataSourceMap.put("ds1-sentinel-file-datasource", fileDataSource1);

	FileRefreshableDataSource fileDataSource2 = mock(FileRefreshableDataSource.class);
	when(fileDataSource2.loadConfig())
			.thenThrow(new RuntimeException("fileDataSource2 error"));
	dataSourceMap.put("ds2-sentinel-file-datasource", fileDataSource2);

	when(beanFactory.getBeansOfType(AbstractDataSource.class))
			.thenReturn(dataSourceMap);

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.DOWN);
	Map<String, Status> dataSourceDetailMap = (Map<String, Status>) health
			.getDetails().get("dataSource");
	assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource"))
			.isEqualTo(Status.UP);
	assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource"))
			.isEqualTo(new Status(Status.DOWN.getCode(), "fileDataSource2 error"));
}
 
Example #13
Source File: SentinelEndpoint.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@ReadOperation
public Map<String, Object> invoke() {
	final Map<String, Object> result = new HashMap<>();
	if (sentinelProperties.isEnabled()) {

		result.put("appName", AppNameUtil.getAppName());
		result.put("logDir", LogBase.getLogBaseDir());
		result.put("logUsePid", LogBase.isLogNameUsePid());
		result.put("blockPage", SentinelConfig.getConfig(BLOCK_PAGE_URL_CONF_KEY));
		result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
		result.put("metricsFileCharset", SentinelConfig.charset());
		result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
		result.put("consoleServer", TransportConfig.getConsoleServerList());
		result.put("clientIp", TransportConfig.getHeartbeatClientIp());
		result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
		result.put("clientPort", TransportConfig.getPort());
		result.put("coldFactor", sentinelProperties.getFlow().getColdFactor());
		result.put("filter", sentinelProperties.getFilter());
		result.put("datasource", sentinelProperties.getDatasource());

		final Map<String, Object> rules = new HashMap<>();
		result.put("rules", rules);
		rules.put("flowRules", FlowRuleManager.getRules());
		rules.put("degradeRules", DegradeRuleManager.getRules());
		rules.put("systemRules", SystemRuleManager.getRules());
		rules.put("authorityRule", AuthorityRuleManager.getRules());
		rules.put("paramFlowRule", ParamFlowRuleManager.getRules());
	}
	return result;
}
 
Example #14
Source File: SentinelAutoConfigurationTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelSystemProperties() {
	assertThat(LogBase.isLogNameUsePid()).isEqualTo(true);
	assertThat(TransportConfig.getConsoleServerList().toString()).isEqualTo(
			Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081))
					.toString());
	assertThat(TransportConfig.getPort()).isEqualTo("9999");
	assertThat(TransportConfig.getHeartbeatIntervalMs().longValue())
			.isEqualTo(20000L);
	assertThat(TransportConfig.getHeartbeatClientIp()).isEqualTo("1.1.1.1");
	assertThat(SentinelConfig.singleMetricFileSize()).isEqualTo(9999);
	assertThat(SentinelConfig.totalMetricFileCount()).isEqualTo(100);
	assertThat(SentinelConfig.charset()).isEqualTo("UTF-8");
	assertThat(SentinelConfig.getConfig(BLOCK_PAGE_URL_CONF_KEY)).isEqualTo("/error");
}
 
Example #15
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	beanFactory = mock(DefaultListableBeanFactory.class);
	sentinelProperties = mock(SentinelProperties.class);
	sentinelHealthIndicator = new SentinelHealthIndicator(beanFactory,
			sentinelProperties);

	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "");

	heartbeatSender = mock(HeartbeatSender.class);
	Field heartbeatSenderField = ReflectionUtils
			.findField(HeartbeatSenderProvider.class, "heartbeatSender");
	heartbeatSenderField.setAccessible(true);
	ReflectionUtils.setField(heartbeatSenderField, null, heartbeatSender);
}
 
Example #16
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDashboardConfiguredSuccess() throws Exception {
	when(sentinelProperties.isEnabled()).thenReturn(true);
	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
	when(heartbeatSender.sendHeartbeat()).thenReturn(true);

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.UP);
}
 
Example #17
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDashboardConfiguredFailed() throws Exception {
	when(sentinelProperties.isEnabled()).thenReturn(true);
	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
	when(heartbeatSender.sendHeartbeat()).thenReturn(false);

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.DOWN);
	assertThat(health.getDetails().get("dashboard")).isEqualTo(
			new Status(Status.DOWN.getCode(), "localhost:8080 can't be connected"));
}
 
Example #18
Source File: SentinelHealthIndicatorTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testSentinelDataSourceSuccess() throws Exception {
	when(sentinelProperties.isEnabled()).thenReturn(true);
	SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080");
	when(heartbeatSender.sendHeartbeat()).thenReturn(true);

	Map<String, AbstractDataSource> dataSourceMap = new HashMap<>();

	FileRefreshableDataSource fileDataSource1 = mock(FileRefreshableDataSource.class);
	dataSourceMap.put("ds1-sentinel-file-datasource", fileDataSource1);

	FileRefreshableDataSource fileDataSource2 = mock(FileRefreshableDataSource.class);
	dataSourceMap.put("ds2-sentinel-file-datasource", fileDataSource2);

	when(beanFactory.getBeansOfType(AbstractDataSource.class))
			.thenReturn(dataSourceMap);

	Health health = sentinelHealthIndicator.health();

	assertThat(health.getStatus()).isEqualTo(Status.UP);
	Map<String, Status> dataSourceDetailMap = (Map<String, Status>) health
			.getDetails().get("dataSource");
	assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource"))
			.isEqualTo(Status.UP);
	assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource"))
			.isEqualTo(Status.UP);
}
 
Example #19
Source File: HeartbeatSenderInitFunc.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
long retrieveInterval(/*@NonNull*/ HeartbeatSender sender) {
    Long intervalInConfig = TransportConfig.getHeartbeatIntervalMs();
    if (isValidHeartbeatInterval(intervalInConfig)) {
        RecordLog.info("[HeartbeatSenderInitFunc] Using heartbeat interval "
            + "in Sentinel config property: " + intervalInConfig);
        return intervalInConfig;
    } else {
        long senderInterval = sender.intervalMs();
        RecordLog.info("[HeartbeatSenderInit] Heartbeat interval not configured in "
            + "config property or invalid, using sender default: " + senderInterval);
        return senderInterval;
    }
}
 
Example #20
Source File: HeartbeatSenderInitFunc.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
long retrieveInterval(/*@NonNull*/ HeartbeatSender sender) {
    Long intervalInConfig = TransportConfig.getHeartbeatIntervalMs();
    if (isValidHeartbeatInterval(intervalInConfig)) {
        RecordLog.info("[HeartbeatSenderInitFunc] Using heartbeat interval "
            + "in Sentinel config property: " + intervalInConfig);
        return intervalInConfig;
    } else {
        long senderInterval = sender.intervalMs();
        RecordLog.info("[HeartbeatSenderInit] Heartbeat interval not configured in "
            + "config property or invalid, using sender default: " + senderInterval);
        return senderInterval;
    }
}
 
Example #21
Source File: HeartbeatMessage.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public HeartbeatMessage() {
    message.put("hostname", HostNameUtil.getHostName());
    message.put("ip", TransportConfig.getHeartbeatClientIp());
    message.put("app", AppNameUtil.getAppName());
    // Put application type (since 1.6.0).
    message.put("app_type", String.valueOf(SentinelConfig.getAppType()));
    message.put("port", String.valueOf(TransportConfig.getPort()));
}
 
Example #22
Source File: HttpHeartbeatSender.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
protected static List<Tuple2<String, Integer>> parseDashboardList() {
    List<Tuple2<String, Integer>> list = new ArrayList<Tuple2<String, Integer>>();
    try {
        String ipsStr = TransportConfig.getConsoleServer();
        if (StringUtil.isBlank(ipsStr)) {
            RecordLog.warn("[NettyHttpHeartbeatSender] Dashboard server address is not configured");
            return list;
        }

        for (String ipPortStr : ipsStr.split(",")) {
            if (ipPortStr.trim().length() == 0) {
                continue;
            }
            ipPortStr = ipPortStr.trim();
            if (ipPortStr.startsWith("http://")) {
                ipPortStr = ipPortStr.substring(7);
            }
            if (ipPortStr.startsWith(":")) {
                continue;
            }
            String[] ipPort = ipPortStr.trim().split(":");
            int port = 80;
            if (ipPort.length > 1) {
                port = Integer.parseInt(ipPort[1].trim());
            }
            list.add(Tuple2.of(ipPort[0].trim(), port));
        }
    } catch (Exception ex) {
        RecordLog.warn("[NettyHttpHeartbeatSender] Parse dashboard list failed, current address list: " + list, ex);
        ex.printStackTrace();
    }
    return list;
}
 
Example #23
Source File: SimpleHttpCommandCenter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() throws Exception {
    if (socketReference != null) {
        try {
            socketReference.close();
        } catch (IOException e) {
            CommandCenterLog.warn("Error when releasing the server socket", e);
        }
    }
    bizExecutor.shutdownNow();
    executor.shutdownNow();
    TransportConfig.setRuntimePort(PORT_UNINITIALIZED);
    handlerMap.clear();
}
 
Example #24
Source File: HeartbeatMessage.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: SimpleHttpHeartbeatSender.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private List<InetSocketAddress> getDefaultConsoleIps() {
    List<InetSocketAddress> newAddrs = new ArrayList<InetSocketAddress>();
    try {
        String ipsStr = TransportConfig.getConsoleServer();
        if (StringUtil.isEmpty(ipsStr)) {
            RecordLog.warn("[SimpleHttpHeartbeatSender] Dashboard server address not configured");
            return newAddrs;
        }

        for (String ipPortStr : ipsStr.split(",")) {
            if (ipPortStr.trim().length() == 0) {
                continue;
            }
            if (ipPortStr.startsWith("http://")) {
                ipPortStr = ipPortStr.trim().substring(7);
            }
            String[] ipPort = ipPortStr.trim().split(":");
            int port = 80;
            if (ipPort.length > 1) {
                port = Integer.parseInt(ipPort[1].trim());
            }
            newAddrs.add(new InetSocketAddress(ipPort[0].trim(), port));
        }
    } catch (Exception ex) {
        RecordLog.warn("[SimpleHeartbeatSender] Parse dashboard list failed, current address list: " + newAddrs, ex);
        ex.printStackTrace();
    }
    return newAddrs;
}
 
Example #26
Source File: DemoClusterInitFunc.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private String getCurrentMachineId() {
    // Note: this may not work well for container-based env.
    return HostNameUtil.getIp() + SEPARATOR + TransportConfig.getRuntimePort();
}
 
Example #27
Source File: HeartbeatSenderInitFunc.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private void setIntervalIfNotExists(long interval) {
    SentinelConfig.setConfig(TransportConfig.HEARTBEAT_INTERVAL_MS, String.valueOf(interval));
}
 
Example #28
Source File: HeartbeatSenderInitFuncTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    SentinelConfig.removeConfig(TransportConfig.HEARTBEAT_INTERVAL_MS);
}
 
Example #29
Source File: HeartbeatSenderInitFuncTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() throws Exception {
    SentinelConfig.removeConfig(TransportConfig.HEARTBEAT_INTERVAL_MS);
}
 
Example #30
Source File: SentinelHealthIndicator.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	Map<String, Object> detailMap = new HashMap<>();

	// If sentinel isn't enabled, set the status up and set the enabled to false in
	// detail
	if (!sentinelProperties.isEnabled()) {
		detailMap.put("enabled", false);
		builder.up().withDetails(detailMap);
		return;
	}

	detailMap.put("enabled", true);

	// Check health of Dashboard
	boolean dashboardUp = true;
	List<Tuple2<String, Integer>> consoleServerList = TransportConfig
			.getConsoleServerList();
	if (CollectionUtils.isEmpty(consoleServerList)) {
		// If Dashboard isn't configured, it's OK and mark the status of Dashboard
		// with UNKNOWN.
		detailMap.put("dashboard",
				new Status(Status.UNKNOWN.getCode(), "dashboard isn't configured"));
	}
	else {
		// If Dashboard is configured, send a heartbeat message to it and check the
		// result
		HeartbeatSender heartbeatSender = HeartbeatSenderProvider
				.getHeartbeatSender();
		boolean result = heartbeatSender.sendHeartbeat();
		if (result) {
			detailMap.put("dashboard", Status.UP);
		}
		else {
			// If failed to send heartbeat message, means that the Dashboard is DOWN
			dashboardUp = false;
			detailMap.put("dashboard",
					new Status(Status.DOWN.getCode(), String.format(
							"the dashboard servers [%s] one of them can't be connected",
							consoleServerList)));
		}
	}

	// Check health of DataSource
	boolean dataSourceUp = true;
	Map<String, Object> dataSourceDetailMap = new HashMap<>();
	detailMap.put("dataSource", dataSourceDetailMap);

	// Get all DataSources and each call loadConfig to check if it's OK
	// If no Exception thrown, it's OK
	// Note:
	// Even if the dynamic config center is down, the loadConfig() might return
	// successfully
	// e.g. for Nacos client, it might retrieve from the local cache)
	// But in most circumstances it's okay
	Map<String, AbstractDataSource> dataSourceMap = beanFactory
			.getBeansOfType(AbstractDataSource.class);
	for (Map.Entry<String, AbstractDataSource> dataSourceMapEntry : dataSourceMap
			.entrySet()) {
		String dataSourceBeanName = dataSourceMapEntry.getKey();
		AbstractDataSource dataSource = dataSourceMapEntry.getValue();
		try {
			dataSource.loadConfig();
			dataSourceDetailMap.put(dataSourceBeanName, Status.UP);
		}
		catch (Exception e) {
			// If one DataSource failed to loadConfig, means that the DataSource is
			// DOWN
			dataSourceUp = false;
			dataSourceDetailMap.put(dataSourceBeanName,
					new Status(Status.DOWN.getCode(), e.getMessage()));
		}
	}

	// If Dashboard and DataSource are both OK, the health status is UP
	if (dashboardUp && dataSourceUp) {
		builder.up().withDetails(detailMap);
	}
	else {
		builder.down().withDetails(detailMap);
	}
}