Search in sources :

Example 1 with AbstractDataSource

use of com.alibaba.csp.sentinel.datasource.AbstractDataSource in project spring-cloud-alibaba by alibaba.

the class SentinelHealthIndicator method doHealthCheck.

@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    Map<String, Object> detailMap = new HashMap<>();
    // 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<Endpoint> 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.UNKNOWN.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.UNKNOWN.getCode(), e.getMessage()));
        }
    }
    // If Dashboard and DataSource are both OK, the health status is UP
    if (dashboardUp && dataSourceUp) {
        builder.up().withDetails(detailMap);
    } else {
        builder.unknown().withDetails(detailMap);
    }
}
Also used : Status(org.springframework.boot.actuate.health.Status) HashMap(java.util.HashMap) AbstractDataSource(com.alibaba.csp.sentinel.datasource.AbstractDataSource) HeartbeatSender(com.alibaba.csp.sentinel.transport.HeartbeatSender) Endpoint(com.alibaba.csp.sentinel.transport.endpoint.Endpoint) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with AbstractDataSource

use of com.alibaba.csp.sentinel.datasource.AbstractDataSource in project spring-cloud-alibaba by alibaba.

the class SentinelHealthIndicatorTests method testSentinelDataSourceSuccess.

@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);
}
Also used : Status(org.springframework.boot.actuate.health.Status) HashMap(java.util.HashMap) Health(org.springframework.boot.actuate.health.Health) AbstractDataSource(com.alibaba.csp.sentinel.datasource.AbstractDataSource) HashMap(java.util.HashMap) Map(java.util.Map) FileRefreshableDataSource(com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource) Test(org.junit.Test)

Example 3 with AbstractDataSource

use of com.alibaba.csp.sentinel.datasource.AbstractDataSource in project spring-cloud-alibaba by alibaba.

the class SentinelHealthIndicatorTests method testSentinelDataSourceFailed.

@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.UNKNOWN);
    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.UNKNOWN.getCode(), "fileDataSource2 error"));
}
Also used : Status(org.springframework.boot.actuate.health.Status) HashMap(java.util.HashMap) Health(org.springframework.boot.actuate.health.Health) AbstractDataSource(com.alibaba.csp.sentinel.datasource.AbstractDataSource) HashMap(java.util.HashMap) Map(java.util.Map) FileRefreshableDataSource(com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource) Test(org.junit.Test)

Example 4 with AbstractDataSource

use of com.alibaba.csp.sentinel.datasource.AbstractDataSource in project mogu_blog_v2 by moxi624.

the class SentinelHealthIndicator method doHealthCheck.

@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
    Map<String, Object> detailMap = new HashMap<>();
    // 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>> consoleServer = TransportConfig.getConsoleServerList();
    if (consoleServer == null) {
        // 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(), consoleServer + " can't be connected"));
        }
    }
    // 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);
    }
}
Also used : Status(org.springframework.boot.actuate.health.Status) HashMap(java.util.HashMap) AbstractDataSource(com.alibaba.csp.sentinel.datasource.AbstractDataSource) HeartbeatSender(com.alibaba.csp.sentinel.transport.HeartbeatSender) Tuple2(com.alibaba.csp.sentinel.util.function.Tuple2) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with AbstractDataSource

use of com.alibaba.csp.sentinel.datasource.AbstractDataSource in project spring-cloud-alibaba by alibaba.

the class SentinelDataSourceHandler method registerBean.

private void registerBean(final AbstractDataSourceProperties dataSourceProperties, String dataSourceName) {
    Map<String, Object> propertyMap = Arrays.stream(dataSourceProperties.getClass().getDeclaredFields()).collect(HashMap::new, (m, v) -> {
        try {
            v.setAccessible(true);
            m.put(v.getName(), v.get(dataSourceProperties));
        } catch (IllegalAccessException e) {
            log.error("[Sentinel Starter] DataSource " + dataSourceName + " field: " + v.getName() + " invoke error");
            throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName + " field: " + v.getName() + " invoke error", e);
        }
    }, HashMap::putAll);
    propertyMap.put(CONVERTER_CLASS_FIELD, dataSourceProperties.getConverterClass());
    propertyMap.put(DATA_TYPE_FIELD, dataSourceProperties.getDataType());
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(dataSourceProperties.getFactoryBeanName());
    propertyMap.forEach((propertyName, propertyValue) -> {
        Field field = ReflectionUtils.findField(dataSourceProperties.getClass(), propertyName);
        if (null == field) {
            return;
        }
        if (DATA_TYPE_FIELD.equals(propertyName)) {
            String dataType = StringUtils.trimAllWhitespace(propertyValue.toString());
            if (CUSTOM_DATA_TYPE.equals(dataType)) {
                try {
                    if (StringUtils.isEmpty(dataSourceProperties.getConverterClass())) {
                        throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName + "dataType is custom, please set converter-class " + "property");
                    }
                    // construct custom Converter with 'converterClass'
                    // configuration and register
                    String customConvertBeanName = "sentinel-" + dataSourceProperties.getConverterClass();
                    if (!this.beanFactory.containsBean(customConvertBeanName)) {
                        this.beanFactory.registerBeanDefinition(customConvertBeanName, BeanDefinitionBuilder.genericBeanDefinition(Class.forName(dataSourceProperties.getConverterClass())).getBeanDefinition());
                    }
                    builder.addPropertyReference("converter", customConvertBeanName);
                } catch (ClassNotFoundException e) {
                    log.error("[Sentinel Starter] DataSource " + dataSourceName + " handle " + dataSourceProperties.getClass().getSimpleName() + " error, class name: " + dataSourceProperties.getConverterClass());
                    throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName + " handle " + dataSourceProperties.getClass().getSimpleName() + " error, class name: " + dataSourceProperties.getConverterClass(), e);
                }
            } else {
                if (!dataTypeList.contains(StringUtils.trimAllWhitespace(propertyValue.toString()))) {
                    throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName + " dataType: " + propertyValue + " is not support now. please using these types: " + dataTypeList.toString());
                }
                // converter type now support xml or json.
                // The bean name of these converters wrapped by
                // 'sentinel-{converterType}-{ruleType}-converter'
                builder.addPropertyReference("converter", "sentinel-" + propertyValue.toString() + "-" + dataSourceProperties.getRuleType().getName() + "-converter");
            }
        } else if (CONVERTER_CLASS_FIELD.equals(propertyName)) {
            return;
        } else {
            // wired properties
            Optional.ofNullable(propertyValue).ifPresent(v -> builder.addPropertyValue(propertyName, v));
        }
    });
    this.beanFactory.registerBeanDefinition(dataSourceName, builder.getBeanDefinition());
    // init in Spring
    AbstractDataSource newDataSource = (AbstractDataSource) this.beanFactory.getBean(dataSourceName);
    // register property in RuleManager
    dataSourceProperties.postRegister(newDataSource);
}
Also used : Arrays(java.util.Arrays) JsonConverter(com.alibaba.cloud.sentinel.datasource.converter.JsonConverter) Logger(org.slf4j.Logger) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) LoggerFactory(org.slf4j.LoggerFactory) SentinelProperties(com.alibaba.cloud.sentinel.SentinelProperties) HashMap(java.util.HashMap) Field(java.lang.reflect.Field) XmlConverter(com.alibaba.cloud.sentinel.datasource.converter.XmlConverter) SmartInitializingSingleton(org.springframework.beans.factory.SmartInitializingSingleton) AbstractDataSource(com.alibaba.csp.sentinel.datasource.AbstractDataSource) List(java.util.List) ReadableDataSource(com.alibaba.csp.sentinel.datasource.ReadableDataSource) Environment(org.springframework.core.env.Environment) ReflectionUtils(org.springframework.util.ReflectionUtils) Map(java.util.Map) Optional(java.util.Optional) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) AbstractDataSourceProperties(com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties) StringUtils(org.springframework.util.StringUtils) Field(java.lang.reflect.Field) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) HashMap(java.util.HashMap) AbstractDataSource(com.alibaba.csp.sentinel.datasource.AbstractDataSource)

Aggregations

AbstractDataSource (com.alibaba.csp.sentinel.datasource.AbstractDataSource)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 Status (org.springframework.boot.actuate.health.Status)4 FileRefreshableDataSource (com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource)2 HeartbeatSender (com.alibaba.csp.sentinel.transport.HeartbeatSender)2 Test (org.junit.Test)2 Health (org.springframework.boot.actuate.health.Health)2 SentinelProperties (com.alibaba.cloud.sentinel.SentinelProperties)1 AbstractDataSourceProperties (com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties)1 JsonConverter (com.alibaba.cloud.sentinel.datasource.converter.JsonConverter)1 XmlConverter (com.alibaba.cloud.sentinel.datasource.converter.XmlConverter)1 ReadableDataSource (com.alibaba.csp.sentinel.datasource.ReadableDataSource)1 Endpoint (com.alibaba.csp.sentinel.transport.endpoint.Endpoint)1 Tuple2 (com.alibaba.csp.sentinel.util.function.Tuple2)1 Field (java.lang.reflect.Field)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Optional (java.util.Optional)1 Logger (org.slf4j.Logger)1