All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.springframework.boxes.jmetric.starter.configure.BoxesMetricAutoConfiguration Maven / Gradle / Ivy

There is a newer version: 2.0.9
Show newest version
package com.springframework.boxes.jmetric.starter.configure;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.springframework.boxes.jmetric.starter.BoxesMetricCollector;
import com.springframework.boxes.jmetric.starter.BoxesMetricPipeline;
import com.springframework.boxes.jmetric.starter.BoxesMetricPipelineProxy;
import com.springframework.boxes.jmetric.starter.collector.method.JMethodCollector;
import com.springframework.boxes.jmetric.starter.interceptor.JMetricMethodInterceptor;
import com.springframework.boxes.jmetric.starter.pipeline.*;
import com.springframework.boxes.jmetric.starter.collector.jvm.JMXBeanCollector;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Configuration
@EnableConfigurationProperties({BoxesMetricProperties.class})
public class BoxesMetricAutoConfiguration {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric", value = "enabled", havingValue = "true")
    public ScheduledExecutorService scheduledExecutorService() {
        return Executors.newScheduledThreadPool(1, new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r, "metric-Scheduled-" + threadNumber.getAndIncrement());
                if (t.isDaemon())
                    t.setDaemon(false);
                if (t.getPriority() != Thread.NORM_PRIORITY)
                    t.setPriority(Thread.NORM_PRIORITY);
                return t;
            }
        });
    }


    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric", value = "enabled", havingValue = "true")
    public BoxesMetricPipelineProxy metricPipelineProxy(BoxesMetricProperties boxesMetricProperties) {
        // load collectors
        List collectors = getAllCollector();

        // load pipelines
        List pipelines = getAllPipeline();

        final BoxesMetricPipelineProxy proxy = new BoxesMetricPipelineProxy(pipelines);

        // collector
        ScheduledExecutorService scheduledExecutorService = scheduledExecutorService();
        log.info("MetricProperties:{}", JSON.toJSONString(boxesMetricProperties));
        if (null != scheduledExecutorService) {
            scheduledExecutorService.scheduleAtFixedRate(() -> {
                log.debug("[Metric]:" + LocalDateTime.now(ZoneId.systemDefault()));
                Optional.of(collectors).orElse(Lists.newArrayList()).forEach(
                        x -> {
                            x.collect(proxy);
                        }
                );
            }, boxesMetricProperties.getInitialDelay(), boxesMetricProperties.getPeriodSeconds(), TimeUnit.SECONDS);

        }
        return proxy;
    }


    private List getAllCollector() {
        List collectors = Lists.newArrayList();
        Map collectorMap = applicationContext.getBeansOfType(BoxesMetricCollector.class);
        log.info("collectorMap:{}", JSON.toJSONString(collectorMap));
        Optional.of(collectorMap).orElse(Maps.newHashMap()).entrySet().forEach(x -> {
            collectors.add(x.getValue());
        });
        return collectors;
    }

    private List getAllPipeline() {
        List collectors = Lists.newArrayList();
        Map pipelineMap = applicationContext.getBeansOfType(BoxesMetricPipeline.class);
        log.info("pipelineMap:{}", JSON.toJSONString(pipelineMap));
        Optional.of(pipelineMap).orElse(Maps.newHashMap()).entrySet().forEach(x -> {
            collectors.add(x.getValue());
        });
        return collectors;
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.pipeline", value = "logger", havingValue = "true")
    public LoggerPipeline loggerPipeline() {
        log.debug("[Logger Pipeline init]");
        return new LoggerPipeline();
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.pipeline", value = "system", havingValue = "true")
    public SystemPipeline systemPipeline() {
        log.debug("[System Pipeline init]");
        return new SystemPipeline();
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.pipeline", value = "falcon", havingValue = "true")
    public FalconPipeline falconPipeline(BoxesMetricProperties metricProperties) {
        BoxesMetricProperties.Pipeline.FalconMeta falconPipeline = metricProperties.getPipeline().getFalconMeta();
        if (null == falconPipeline) {
            throw new IllegalArgumentException("empty falcon pipeline meta config");
        }
        log.debug("[Falcon Pipeline init]");
        return new FalconPipeline(falconPipeline.getUrl(), falconPipeline.getTags(), falconPipeline.getStep());
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.pipeline", value = "elastic", havingValue = "true")
    public RestHighLevelClient elasticPipelineRestHighLevelClient(BoxesMetricProperties boxesMetricProperties) {
        BoxesMetricProperties.Pipeline.ElasticMeta elasticMeta = boxesMetricProperties.getPipeline().getElasticMeta();
        if (null == elasticMeta || StringUtils.isBlank(elasticMeta.getEndpoints())) {
            throw new IllegalArgumentException("empty elastic pipeline meta config");
        }
        String[] https = StringUtils.split(elasticMeta.getEndpoints(), ",");
        List list = Lists.newArrayList();
        for (String http : https) {
            list.add(HttpHost.create(http));
        }
        RestClientBuilder restClientBuilder = RestClient.builder(list.toArray(new HttpHost[list.size()]));
        if (StringUtils.isNotBlank(elasticMeta.getUsername()) && StringUtils.isNotBlank(elasticMeta.getPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticMeta.getUsername(), elasticMeta.getPassword()));
            restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }
        return new RestHighLevelClient(restClientBuilder);
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.pipeline", value = "elastic", havingValue = "true")
    public ElasticPipeline elasticPipeline(BoxesMetricProperties boxesMetricProperties) {
        BoxesMetricProperties.Pipeline.ElasticMeta elasticMeta = boxesMetricProperties.getPipeline().getElasticMeta();
        if (null == elasticMeta || StringUtils.isBlank(elasticMeta.getEndpoints())) {
            throw new IllegalArgumentException("empty elastic pipeline meta config");
        }
        RestHighLevelClient restHighLevelClient = elasticPipelineRestHighLevelClient(boxesMetricProperties);
        log.debug("[Elastic Pipeline init] restHighLevelClient init:{}", null != restHighLevelClient);
        return new ElasticPipeline(elasticMeta.getIndexName(), restHighLevelClient);
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.pipeline", value = "mysql", havingValue = "true")
    public MySQLPipeline mysqlPipeline() {
        JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
        log.debug("[MySQL Pipeline init] jdbcTemplate init:{}", true);
        return new MySQLPipeline(jdbcTemplate);
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.collector", value = "method", havingValue = "true")
    public JMethodCollector jMethodCollector() {
        return new JMethodCollector();
    }

    @Bean
    @ConditionalOnProperty(prefix = "spring.boxes.metric.collector", value = "jvm", havingValue = "true")
    public JMXBeanCollector jmxBeanCollector() {
        return new JMXBeanCollector();
    }

    @Bean(name = "metricMethodPointcutAdvisor")
    @ConditionalOnProperty(prefix = "spring.boxes.metric.collector", value = "method", havingValue = "true")
    public DefaultPointcutAdvisor metricMethodPointcutAdvisor() {
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("@annotation(com.springframework.boxes.metric.starter.interceptor.JMetric)");
        advisor.setPointcut(pointcut);
        advisor.setAdvice(new JMetricMethodInterceptor());
        return advisor;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy