druid-admin监控集群环境下的druid

This commit is contained in:
yaolinqi
2020-09-23 10:30:59 +08:00
parent 322d65692b
commit 089b8ae726
57 changed files with 6061 additions and 0 deletions
@@ -0,0 +1,33 @@
package com.alibaba.druid.admin;
import com.alibaba.druid.admin.config.MonitorProperties;
import com.alibaba.druid.admin.servlet.MonitorViewServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableConfigurationProperties(MonitorProperties.class)
public class DruidAdminApplication {
public static void main(String[] args) {
SpringApplication.run(DruidAdminApplication.class, args);
}
@Bean
public ServletRegistrationBean statViewServletRegistrationBean(MonitorProperties properties) {
ServletRegistrationBean registrationBean = new ServletRegistrationBean();
registrationBean.setServlet(new MonitorViewServlet());
registrationBean.addUrlMappings("/druid/*");
if (properties.getLoginUsername() != null) {
registrationBean.addInitParameter("loginUsername", properties.getLoginUsername());
}
if (properties.getLoginPassword() != null) {
registrationBean.addInitParameter("loginPassword", properties.getLoginPassword());
}
return registrationBean;
}
}
@@ -0,0 +1,45 @@
package com.alibaba.druid.admin.config;
import com.ecwid.consul.transport.TLSConfig;
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.consul.ConsulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* @author linchtech
* @date 2020-09-20 19:56
**/
@Configuration
@ConditionalOnConsulEnabled
public class MonitorConsulConfig {
@Bean
@ConditionalOnProperty(value = "spring.cloud.consul.enabled")
public ConsulProperties consulProperties() {
return new ConsulProperties();
}
@Bean
@ConditionalOnProperty(value = "spring.cloud.consul.enabled")
public ConsulClient consulClient(ConsulProperties consulProperties) {
final int agentPort = consulProperties.getPort();
final String agentHost = !StringUtils.isEmpty(consulProperties.getScheme())
? consulProperties.getScheme() + "://" + consulProperties.getHost()
: consulProperties.getHost();
if (consulProperties.getTls() != null) {
ConsulProperties.TLSConfig tls = consulProperties.getTls();
TLSConfig tlsConfig = new TLSConfig(tls.getKeyStoreInstanceType(),
tls.getCertificatePath(), tls.getCertificatePassword(),
tls.getKeyStorePath(), tls.getKeyStorePassword());
return new ConsulClient(agentHost, agentPort, tlsConfig);
}
return new ConsulClient(agentHost, agentPort);
}
}
@@ -0,0 +1,34 @@
package com.alibaba.druid.admin.config;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author linchtech
* @date 2020-09-22 12:02
**/
@Configuration
@ConditionalOnProperty(value = "eureka.client.enabled")
public class MonitorEurekaConfig {
private final EurekaClient eurekaClient;
private final EurekaClientConfig clientConfig;
public MonitorEurekaConfig(EurekaClient eurekaClient,
EurekaClientConfig clientConfig) {
this.clientConfig = clientConfig;
this.eurekaClient = eurekaClient;
}
@Bean
public DiscoveryClient discoveryClient(EurekaClient client,
EurekaClientConfig clientConfig) {
return new EurekaDiscoveryClient(client, clientConfig);
}
}
@@ -0,0 +1,23 @@
package com.alibaba.druid.admin.config;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author linchtech
* @date 2020-09-20 22:29
**/
@Configuration
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled")
public class MonitorNacosConfig {
@Bean
public DiscoveryClient nacosDiscoveryClient(NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosDiscoveryClient(nacosDiscoveryProperties);
}
}
@@ -0,0 +1,29 @@
package com.alibaba.druid.admin.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
/**
* @author 107
* @date 2020-09-16 17:10
**/
@Data
@ConfigurationProperties(prefix = "monitor")
public class MonitorProperties {
/**
* 需要监控的服务
*/
private List<String> applications;
/**
* 登录用户名
*/
private String loginUsername;
/**
* 登录密码
*/
private String loginPassword;
}
@@ -0,0 +1,20 @@
package com.alibaba.druid.admin.model;
import lombok.Data;
/**
* @author linchtech
* @date 2020-09-16 14:08
**/
@Data
public class ServiceNode {
private String id;
private Integer port;
private String address;
private String serviceName;
}
@@ -0,0 +1,50 @@
package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-21 9:26
**/
@NoArgsConstructor
@Data
public class ConnectionResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private List<ContentBean> Content;
@NoArgsConstructor
@Data
public static class ContentBean {
@JSONField(name = "id")
private int id;
@JSONField(name = "connectionId")
private int connectionId;
@JSONField(name = "useCount")
private int useCount;
@JSONField(name = "lastActiveTime")
private String lastActiveTime;
@JSONField(name = "connectTime")
private String connectTime;
@JSONField(name = "holdability")
private int holdability;
@JSONField(name = "transactionIsolation")
private int transactionIsolation;
@JSONField(name = "autoCommit")
private boolean autoCommit;
@JSONField(name = "readoOnly")
private boolean readoOnly;
@JSONField(name = "keepAliveCheckCount")
private int keepAliveCheckCount;
@JSONField(name = "pscache")
private List<?> pscache;
}
}
@@ -0,0 +1,165 @@
package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-16 18:32
**/
@Data
@NoArgsConstructor
public class DataSourceResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private List<ContentBean> Content;
@NoArgsConstructor
@Data
public static class ContentBean {
private String serviceId;
@JSONField(name = "Identity")
private int Identity;
@JSONField(name = "Name")
private String Name;
@JSONField(name = "DbType")
private String DbType;
@JSONField(name = "DriverClassName")
private String DriverClassName;
@JSONField(name = "URL")
private String URL;
@JSONField(name = "UserName")
private String UserName;
@JSONField(name = "WaitThreadCount")
private int WaitThreadCount;
@JSONField(name = "NotEmptyWaitCount")
private int NotEmptyWaitCount;
@JSONField(name = "NotEmptyWaitMillis")
private int NotEmptyWaitMillis;
@JSONField(name = "PoolingCount")
private int PoolingCount;
@JSONField(name = "PoolingPeak")
private int PoolingPeak;
@JSONField(name = "PoolingPeakTime")
private String PoolingPeakTime;
@JSONField(name = "ActiveCount")
private int ActiveCount;
@JSONField(name = "ActivePeak")
private int ActivePeak;
@JSONField(name = "ActivePeakTime")
private String ActivePeakTime;
@JSONField(name = "InitialSize")
private int InitialSize;
@JSONField(name = "MinIdle")
private int MinIdle;
@JSONField(name = "MaxActive")
private int MaxActive;
@JSONField(name = "QueryTimeout")
private int QueryTimeout;
@JSONField(name = "TransactionQueryTimeout")
private int TransactionQueryTimeout;
@JSONField(name = "LoginTimeout")
private int LoginTimeout;
@JSONField(name = "ValidConnectionCheckerClassName")
private String ValidConnectionCheckerClassName;
@JSONField(name = "ExceptionSorterClassName")
private String ExceptionSorterClassName;
@JSONField(name = "TestOnBorrow")
private boolean TestOnBorrow;
@JSONField(name = "TestOnReturn")
private boolean TestOnReturn;
@JSONField(name = "TestWhileIdle")
private boolean TestWhileIdle;
@JSONField(name = "DefaultAutoCommit")
private boolean DefaultAutoCommit;
@JSONField(name = "DefaultReadOnly")
private Object DefaultReadOnly;
@JSONField(name = "DefaultTransactionIsolation")
private Object DefaultTransactionIsolation;
@JSONField(name = "LogicConnectCount")
private int LogicConnectCount;
@JSONField(name = "LogicCloseCount")
private int LogicCloseCount;
@JSONField(name = "LogicConnectErrorCount")
private int LogicConnectErrorCount;
@JSONField(name = "PhysicalConnectCount")
private int PhysicalConnectCount;
@JSONField(name = "PhysicalCloseCount")
private int PhysicalCloseCount;
@JSONField(name = "PhysicalConnectErrorCount")
private int PhysicalConnectErrorCount;
@JSONField(name = "ExecuteCount")
private int ExecuteCount;
@JSONField(name = "ExecuteUpdateCount")
private int ExecuteUpdateCount;
@JSONField(name = "ExecuteQueryCount")
private int ExecuteQueryCount;
@JSONField(name = "ExecuteBatchCount")
private int ExecuteBatchCount;
@JSONField(name = "ErrorCount")
private int ErrorCount;
@JSONField(name = "CommitCount")
private int CommitCount;
@JSONField(name = "RollbackCount")
private int RollbackCount;
@JSONField(name = "PSCacheAccessCount")
private int PSCacheAccessCount;
@JSONField(name = "PSCacheHitCount")
private int PSCacheHitCount;
@JSONField(name = "PSCacheMissCount")
private int PSCacheMissCount;
@JSONField(name = "StartTransactionCount")
private int StartTransactionCount;
@JSONField(name = "RemoveAbandoned")
private boolean RemoveAbandoned;
@JSONField(name = "ClobOpenCount")
private int ClobOpenCount;
@JSONField(name = "BlobOpenCount")
private int BlobOpenCount;
@JSONField(name = "KeepAliveCheckCount")
private int KeepAliveCheckCount;
@JSONField(name = "KeepAlive")
private boolean KeepAlive;
@JSONField(name = "FailFast")
private boolean FailFast;
@JSONField(name = "MaxWait")
private int MaxWait;
@JSONField(name = "MaxWaitThreadCount")
private int MaxWaitThreadCount;
@JSONField(name = "PoolPreparedStatements")
private boolean PoolPreparedStatements;
@JSONField(name = "MaxPoolPreparedStatementPerConnectionSize")
private int MaxPoolPreparedStatementPerConnectionSize;
@JSONField(name = "MinEvictableIdleTimeMillis")
private int MinEvictableIdleTimeMillis;
@JSONField(name = "MaxEvictableIdleTimeMillis")
private int MaxEvictableIdleTimeMillis;
@JSONField(name = "LogDifferentThread")
private boolean LogDifferentThread;
@JSONField(name = "RecycleErrorCount")
private int RecycleErrorCount;
@JSONField(name = "PreparedStatementOpenCount")
private int PreparedStatementOpenCount;
@JSONField(name = "PreparedStatementClosedCount")
private int PreparedStatementClosedCount;
@JSONField(name = "UseUnfairLock")
private boolean UseUnfairLock;
@JSONField(name = "InitGlobalVariants")
private boolean InitGlobalVariants;
@JSONField(name = "InitVariants")
private boolean InitVariants;
@JSONField(name = "FilterClassNames")
private List<String> FilterClassNames;
@JSONField(name = "TransactionHistogram")
private List<Integer> TransactionHistogram;
@JSONField(name = "ConnectionHoldTimeHistogram")
private List<Integer> ConnectionHoldTimeHistogram;
}
}
@@ -0,0 +1,120 @@
package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-16 16:18
**/
@NoArgsConstructor
@Data
public class SqlDetailResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private ContentBean Content;
@NoArgsConstructor
@Data
public static class ContentBean {
@JSONField(name = "ExecuteAndResultSetHoldTime")
private int ExecuteAndResultSetHoldTime;
@JSONField(name = "LastErrorMessage")
private Object LastErrorMessage;
@JSONField(name = "InputStreamOpenCount")
private int InputStreamOpenCount;
@JSONField(name = "BatchSizeTotal")
private int BatchSizeTotal;
@JSONField(name = "FetchRowCountMax")
private int FetchRowCountMax;
@JSONField(name = "ErrorCount")
private int ErrorCount;
@JSONField(name = "BatchSizeMax")
private int BatchSizeMax;
@JSONField(name = "URL")
private Object URL;
@JSONField(name = "Name")
private Object Name;
@JSONField(name = "LastErrorTime")
private Object LastErrorTime;
@JSONField(name = "ReaderOpenCount")
private int ReaderOpenCount;
@JSONField(name = "parsedRelationships")
private String parsedRelationships;
@JSONField(name = "EffectedRowCountMax")
private int EffectedRowCountMax;
@JSONField(name = "LastErrorClass")
private Object LastErrorClass;
@JSONField(name = "InTransactionCount")
private int InTransactionCount;
@JSONField(name = "LastErrorStackTrace")
private Object LastErrorStackTrace;
@JSONField(name = "ResultSetHoldTime")
private int ResultSetHoldTime;
@JSONField(name = "TotalTime")
private int TotalTime;
@JSONField(name = "ID")
private int ID;
@JSONField(name = "ConcurrentMax")
private int ConcurrentMax;
@JSONField(name = "RunningCount")
private int RunningCount;
@JSONField(name = "FetchRowCount")
private int FetchRowCount;
@JSONField(name = "parsedFields")
private String parsedFields;
@JSONField(name = "MaxTimespanOccurTime")
private String MaxTimespanOccurTime;
@JSONField(name = "LastSlowParameters")
private Object LastSlowParameters;
@JSONField(name = "ReadBytesLength")
private int ReadBytesLength;
@JSONField(name = "formattedSql")
private String formattedSql;
@JSONField(name = "DbType")
private String DbType;
@JSONField(name = "DataSource")
private Object DataSource;
@JSONField(name = "SQL")
private String SQL;
@JSONField(name = "HASH")
private long HASH;
@JSONField(name = "LastError")
private Object LastError;
@JSONField(name = "MaxTimespan")
private int MaxTimespan;
@JSONField(name = "parsedTable")
private String parsedTable;
@JSONField(name = "parsedOrderbycolumns")
private String parsedOrderbycolumns;
@JSONField(name = "BlobOpenCount")
private int BlobOpenCount;
@JSONField(name = "ExecuteCount")
private int ExecuteCount;
@JSONField(name = "EffectedRowCount")
private int EffectedRowCount;
@JSONField(name = "ReadStringLength")
private int ReadStringLength;
@JSONField(name = "File")
private Object File;
@JSONField(name = "ClobOpenCount")
private int ClobOpenCount;
@JSONField(name = "LastTime")
private String LastTime;
@JSONField(name = "parsedConditions")
private String parsedConditions;
@JSONField(name = "EffectedRowCountHistogram")
private List<Integer> EffectedRowCountHistogram;
@JSONField(name = "Histogram")
private List<Integer> Histogram;
@JSONField(name = "ExecuteAndResultHoldTimeHistogram")
private List<Integer> ExecuteAndResultHoldTimeHistogram;
@JSONField(name = "FetchRowCountHistogram")
private List<Integer> FetchRowCountHistogram;
}
}
@@ -0,0 +1,114 @@
package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-16 14:37
**/
@NoArgsConstructor
@Data
public class SqlListResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private List<ContentBean> Content;
@NoArgsConstructor
@Data
public static class ContentBean {
private String serviceId;
private String address;
private Integer port;
@JSONField(name = "ExecuteAndResultSetHoldTime")
private int ExecuteAndResultSetHoldTime;
@JSONField(name = "LastErrorMessage")
private Object LastErrorMessage;
@JSONField(name = "InputStreamOpenCount")
private int InputStreamOpenCount;
@JSONField(name = "BatchSizeTotal")
private int BatchSizeTotal;
@JSONField(name = "FetchRowCountMax")
private int FetchRowCountMax;
@JSONField(name = "ErrorCount")
private int ErrorCount;
@JSONField(name = "BatchSizeMax")
private int BatchSizeMax;
@JSONField(name = "URL")
private Object URL;
@JSONField(name = "Name")
private Object Name;
@JSONField(name = "LastErrorTime")
private Object LastErrorTime;
@JSONField(name = "ReaderOpenCount")
private int ReaderOpenCount;
@JSONField(name = "EffectedRowCountMax")
private int EffectedRowCountMax;
@JSONField(name = "LastErrorClass")
private Object LastErrorClass;
@JSONField(name = "InTransactionCount")
private int InTransactionCount;
@JSONField(name = "LastErrorStackTrace")
private Object LastErrorStackTrace;
@JSONField(name = "ResultSetHoldTime")
private int ResultSetHoldTime;
@JSONField(name = "TotalTime")
private int TotalTime;
@JSONField(name = "ID")
private int ID;
@JSONField(name = "ConcurrentMax")
private int ConcurrentMax;
@JSONField(name = "RunningCount")
private int RunningCount;
@JSONField(name = "FetchRowCount")
private int FetchRowCount;
@JSONField(name = "MaxTimespanOccurTime")
private String MaxTimespanOccurTime;
@JSONField(name = "LastSlowParameters")
private Object LastSlowParameters;
@JSONField(name = "ReadBytesLength")
private int ReadBytesLength;
@JSONField(name = "DbType")
private String DbType;
@JSONField(name = "DataSource")
private Object DataSource;
@JSONField(name = "SQL")
private String SQL;
@JSONField(name = "HASH")
private long HASH;
@JSONField(name = "LastError")
private Object LastError;
@JSONField(name = "MaxTimespan")
private int MaxTimespan;
@JSONField(name = "BlobOpenCount")
private int BlobOpenCount;
@JSONField(name = "ExecuteCount")
private int ExecuteCount;
@JSONField(name = "EffectedRowCount")
private int EffectedRowCount;
@JSONField(name = "ReadStringLength")
private int ReadStringLength;
@JSONField(name = "File")
private Object File;
@JSONField(name = "ClobOpenCount")
private int ClobOpenCount;
@JSONField(name = "LastTime")
private String LastTime;
@JSONField(name = "EffectedRowCountHistogram")
private List<Integer> EffectedRowCountHistogram;
@JSONField(name = "Histogram")
private List<Integer> Histogram;
@JSONField(name = "ExecuteAndResultHoldTimeHistogram")
private List<Integer> ExecuteAndResultHoldTimeHistogram;
@JSONField(name = "FetchRowCountHistogram")
private List<Integer> FetchRowCountHistogram;
}
}
@@ -0,0 +1,119 @@
package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-17 18:18
**/
@Data
@NoArgsConstructor
public class WallResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private ContentBean Content = new ContentBean();
@NoArgsConstructor
@Data
public static class ContentBean {
@JSONField(name = "checkCount")
private int checkCount;
@JSONField(name = "hardCheckCount")
private int hardCheckCount;
@JSONField(name = "violationCount")
private int violationCount;
@JSONField(name = "violationEffectRowCount")
private int violationEffectRowCount;
@JSONField(name = "blackListHitCount")
private int blackListHitCount;
@JSONField(name = "blackListSize")
private int blackListSize;
@JSONField(name = "whiteListHitCount")
private int whiteListHitCount;
@JSONField(name = "whiteListSize")
private int whiteListSize;
@JSONField(name = "syntaxErrorCount")
private int syntaxErrorCount;
@JSONField(name = "tables")
private List<TablesBean> tables = new ArrayList<>();
@JSONField(name = "functions")
private List<FunctionsBean> functions = new ArrayList<>();
@JSONField(name = "blackList")
private List<Object> blackList = new ArrayList<>();
@JSONField(name = "whiteList")
private List<WhiteListBean> whiteList = new ArrayList<>();
@NoArgsConstructor
@Data
public static class TablesBean {
@JSONField(name = "name")
private String name;
@JSONField(name = "selectCount")
private int selectCount;
@JSONField(name = "fetchRowCount")
private int fetchRowCount;
@JSONField(name = "fetchRowCountHistogram")
private List<Integer> fetchRowCountHistogram;
}
@NoArgsConstructor
@Data
public static class FunctionsBean {
@JSONField(name = "name")
private String name;
@JSONField(name = "invokeCount")
private int invokeCount;
}
@NoArgsConstructor
@Data
public static class WhiteListBean {
@JSONField(name = "sql")
private String sql;
@JSONField(name = "sample")
private String sample;
@JSONField(name = "executeCount")
private int executeCount;
@JSONField(name = "fetchRowCount")
private int fetchRowCount;
}
}
/**
* 累加结果
*
* @param wallResult 需要累加的对象
* @param sumResult 累加后的对象
*/
public void sum(WallResult wallResult, WallResult sumResult) {
sumResult.getContent().setCheckCount(sumResult.getContent().getCheckCount() + wallResult.getContent().getCheckCount());
sumResult.getContent().setHardCheckCount(sumResult.getContent().getHardCheckCount() + wallResult.getContent().getHardCheckCount());
sumResult.getContent().setViolationCount(sumResult.getContent().getViolationCount() + wallResult.getContent().getViolationCount());
sumResult.getContent().setViolationEffectRowCount(sumResult.getContent().getViolationEffectRowCount() + wallResult.getContent().getViolationEffectRowCount());
sumResult.getContent().setBlackListHitCount(sumResult.getContent().getBlackListHitCount() + wallResult.getContent().getBlackListHitCount());
sumResult.getContent().setBlackListSize(sumResult.getContent().getBlackListSize() + wallResult.getContent().getBlackListSize());
sumResult.getContent().setWhiteListHitCount(sumResult.getContent().getWhiteListHitCount() + wallResult.getContent().getWhiteListHitCount());
sumResult.getContent().setWhiteListSize(sumResult.getContent().getWhiteListSize() + wallResult.getContent().getWhiteListSize());
sumResult.getContent().setSyntaxErrorCount(sumResult.getContent().getSyntaxErrorCount() + wallResult.getContent().getSyntaxErrorCount());
sumResult.getContent().getTables().addAll(wallResult.getContent().getTables() == null ? Collections.emptyList() : wallResult.getContent().getTables());
sumResult.getContent().getFunctions().addAll(wallResult.getContent().getFunctions() == null ? Collections.emptyList() :
wallResult.getContent().getFunctions());
sumResult.getContent().getBlackList().addAll(wallResult.getContent().getBlackList() == null ? Collections.emptyList() :
wallResult.getContent().getBlackList());
sumResult.getContent().getWhiteList().addAll(wallResult.getContent().getWhiteList() == null ? Collections.emptyList() : wallResult.getContent().getWhiteList());
}
}
@@ -0,0 +1,76 @@
package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-17 18:27
**/
@NoArgsConstructor
@Data
public class WebResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private List<ContentBean> Content;
@NoArgsConstructor
@Data
public static class ContentBean {
@JSONField(name = "URI")
private String URI;
@JSONField(name = "RunningCount")
private int RunningCount;
@JSONField(name = "ConcurrentMax")
private int ConcurrentMax;
@JSONField(name = "RequestCount")
private int RequestCount;
@JSONField(name = "RequestTimeMillis")
private int RequestTimeMillis;
@JSONField(name = "ErrorCount")
private int ErrorCount;
@JSONField(name = "LastAccessTime")
private String LastAccessTime;
@JSONField(name = "JdbcCommitCount")
private int JdbcCommitCount;
@JSONField(name = "JdbcRollbackCount")
private int JdbcRollbackCount;
@JSONField(name = "JdbcExecuteCount")
private int JdbcExecuteCount;
@JSONField(name = "JdbcExecuteErrorCount")
private int JdbcExecuteErrorCount;
@JSONField(name = "JdbcExecutePeak")
private int JdbcExecutePeak;
@JSONField(name = "JdbcExecuteTimeMillis")
private int JdbcExecuteTimeMillis;
@JSONField(name = "JdbcFetchRowCount")
private int JdbcFetchRowCount;
@JSONField(name = "JdbcFetchRowPeak")
private int JdbcFetchRowPeak;
@JSONField(name = "JdbcUpdateCount")
private int JdbcUpdateCount;
@JSONField(name = "JdbcUpdatePeak")
private int JdbcUpdatePeak;
@JSONField(name = "JdbcPoolConnectionOpenCount")
private int JdbcPoolConnectionOpenCount;
@JSONField(name = "JdbcPoolConnectionCloseCount")
private int JdbcPoolConnectionCloseCount;
@JSONField(name = "JdbcResultSetOpenCount")
private int JdbcResultSetOpenCount;
@JSONField(name = "JdbcResultSetCloseCount")
private int JdbcResultSetCloseCount;
@JSONField(name = "RequestTimeMillisMax")
private int RequestTimeMillisMax;
@JSONField(name = "RequestTimeMillisMaxOccurTime")
private String RequestTimeMillisMaxOccurTime;
@JSONField(name = "Histogram")
private List<Integer> Histogram;
@JSONField(name = "Profiles")
private List<?> Profiles;
}
}
@@ -0,0 +1,84 @@
package com.alibaba.druid.admin.service;
import com.alibaba.druid.admin.model.ServiceNode;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;
import com.alibaba.druid.admin.config.MonitorProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author linchtech
* @date 2020-09-22 11:14
**/
@Component
@Slf4j
@ConditionalOnProperty(value = "spring.cloud.consul.enabled")
public class ConsulMonitorStatService extends MonitorStatService {
@Autowired
private ConsulClient consulClient;
@Autowired
private MonitorProperties monitorProperties;
@Override
public Map<String, ServiceNode> getAllServiceNodeMap() {
Response<Map<String, Service>> agentServices = consulClient.getAgentServices();
Map<String, Service> value = agentServices.getValue();
List<ServiceNode> serviceNodes = new ArrayList<>();
for (String key : value.keySet()) {
Service service = value.get(key);
String address = service.getAddress();
Integer port = service.getPort();
String id = service.getId();
String serviceName = id.substring(0, id.lastIndexOf("-"));
// 根据前端参数采集指定的服务
if (monitorProperties.getApplications().contains(serviceName)) {
ServiceNode serviceNode = new ServiceNode();
serviceNode.setId(id);
serviceNode.setPort(port);
serviceNode.setAddress(address);
serviceNode.setServiceName(serviceName);
serviceNodes.add(serviceNode);
serviceIdMap.put(id, serviceNode);
}
}
return serviceNodes.parallelStream().collect(Collectors.toMap(i -> i.getServiceName() + "-" + i.getAddress() + "-" + i.getPort(),
Function.identity(), (v1, v2) -> v2));
}
@Override
public Map<String, ServiceNode> getServiceAllNodeMap(Map<String, String> parameters) {
String requestServiceName = parameters.get("serviceName");
Response<Map<String, Service>> agentServices = consulClient.getAgentServices();
Map<String, Service> value = agentServices.getValue();
List<ServiceNode> serviceNodes = new ArrayList<>();
for (String key : value.keySet()) {
Service service = value.get(key);
String address = service.getAddress();
Integer port = service.getPort();
String id = service.getId();
String serviceName = id.substring(0, id.lastIndexOf("-"));
if (serviceName.equals(requestServiceName)) {
ServiceNode serviceNode = new ServiceNode();
serviceNode.setPort(port);
serviceNode.setId(id);
serviceNode.setAddress(address);
serviceNode.setServiceName(serviceName);
serviceNodes.add(serviceNode);
serviceIdMap.put(id, serviceNode);
}
}
return serviceNodes.parallelStream().collect(Collectors.toMap(i -> i.getServiceName() + "-" + i.getAddress() + "-" + i.getPort(),
Function.identity(), (v1, v2) -> v2));
}
}
@@ -0,0 +1,77 @@
package com.alibaba.druid.admin.service;
import com.alibaba.druid.admin.model.ServiceNode;
import com.alibaba.druid.admin.config.MonitorProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author linchtech
* @date 2020-09-22 13:52
**/
@Component
@Slf4j
@ConditionalOnProperty(value = "eureka.client.enabled")
public class EurekaMonitorStatService extends MonitorStatService {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private MonitorProperties monitorProperties;
@Override
public Map<String, ServiceNode> getAllServiceNodeMap() {
List<String> services = discoveryClient.getServices();
List<ServiceNode> serviceNodes = new ArrayList<>();
for (String serviceId : services) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
for (ServiceInstance serviceInstance : instances) {
if (monitorProperties.getApplications().contains(serviceId)) {
ServiceNode serviceNode = new ServiceNode();
serviceNode.setId(serviceInstance.getInstanceId());
serviceNode.setPort(serviceInstance.getPort());
serviceNode.setAddress(serviceInstance.getHost());
serviceNode.setServiceName(serviceId);
serviceNodes.add(serviceNode);
serviceIdMap.put(serviceInstance.getInstanceId(), serviceNode);
}
}
}
return serviceNodes.parallelStream().collect(Collectors.toMap(i -> i.getServiceName() + "-" + i.getAddress() + "-" + i.getPort(),
Function.identity(), (v1, v2) -> v2));
}
@Override
public Map<String, ServiceNode> getServiceAllNodeMap(Map<String, String> parameters) {
String requestServiceName = parameters.get("serviceName");
List<String> services = discoveryClient.getServices();
List<ServiceNode> serviceNodes = new ArrayList<>();
for (String serviceId : services) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
for (ServiceInstance serviceInstance : instances) {
if (requestServiceName.equals(serviceId)) {
ServiceNode serviceNode = new ServiceNode();
serviceNode.setId(serviceInstance.getInstanceId());
serviceNode.setPort(serviceInstance.getPort());
serviceNode.setAddress(serviceInstance.getHost());
serviceNode.setServiceName(serviceId);
serviceNodes.add(serviceNode);
serviceIdMap.put(serviceInstance.getInstanceId(), serviceNode);
}
}
}
return serviceNodes.parallelStream().collect(Collectors.toMap(i -> i.getServiceName() + "-" + i.getAddress() + "-" + i.getPort(),
Function.identity(), (v1, v2) -> v2));
}
}
@@ -0,0 +1,433 @@
package com.alibaba.druid.admin.service;
import com.alibaba.druid.admin.config.MonitorProperties;
import com.alibaba.druid.admin.model.ServiceNode;
import com.alibaba.druid.admin.model.dto.ConnectionResult;
import com.alibaba.druid.admin.model.dto.SqlDetailResult;
import com.alibaba.druid.admin.util.HttpUtil;
import com.alibaba.druid.stat.DruidStatServiceMBean;
import com.alibaba.druid.support.http.stat.WebAppStatManager;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.support.spring.stat.SpringStatManager;
import com.alibaba.druid.util.MapComparator;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.druid.admin.model.dto.DataSourceResult;
import com.alibaba.druid.admin.model.dto.SqlListResult;
import com.alibaba.druid.admin.model.dto.WallResult;
import com.alibaba.druid.admin.model.dto.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author linchtech
* @date 2020-09-16 11:12
**/
@Slf4j
public abstract class MonitorStatService implements DruidStatServiceMBean {
public final static int RESULT_CODE_SUCCESS = 1;
public final static int RESULT_CODE_ERROR = -1;
private final static int DEFAULT_PAGE = 1;
private final static int DEFAULT_PER_PAGE_COUNT = Integer.MAX_VALUE;
private static final String ORDER_TYPE_DESC = "desc";
private static final String ORDER_TYPE_ASC = "asc";
private static final String DEFAULT_ORDER_TYPE = ORDER_TYPE_ASC;
private static final String DEFAULT_ORDERBY = "SQL";
/**
* 以consul注册的服务的id为key,value为某个微服务节点
*/
public static Map<String, ServiceNode> serviceIdMap = new HashMap<>();
@Autowired
private MonitorProperties monitorProperties;
/**
* 获取所有服务信息
*
* @return
*/
public abstract Map<String, ServiceNode> getAllServiceNodeMap();
/**
* 获取指定服务名的所有节点
*
* @param parameters
* @return
*/
public abstract Map<String, ServiceNode> getServiceAllNodeMap(Map<String, String> parameters);
@Override
public String service(String url) {
Map<String, String> parameters = getParameters(url);
if (url.endsWith("serviceList.json")) {
return JSON.toJSONString(monitorProperties.getApplications());
}
if (url.equals("/datasource.json")) {
String serviceName = StringUtils.subString(url, "serviceName=", "&sql-");
Integer id = StringUtils.subStringToInteger(url, "datasource-", ".");
return getDataSourceStatData();
}
if (url.startsWith("/datasource-")) {
String serviceName = StringUtils.subString(url, "serviceName=", "&sql-");
Integer id = StringUtils.subStringToInteger(url, "datasource-", ".");
Object result = getDataSourceStatData();
return returnJSONResult(result == null ? RESULT_CODE_ERROR : RESULT_CODE_SUCCESS, result);
}
// 活跃连接数查看
if (url.startsWith("/connectionInfo-") && url.endsWith(".json")) {
String serviceId = StringUtils.subString(url, "&serviceId=", ".json");
Integer id = StringUtils.subStringToInteger(url, "connectionInfo-", "&");
return getPoolingConnectionInfoByDataSourceId(id, serviceId);
}
// SQL监控列表
if (url.startsWith("/sql.json")) {
return getSqlStatDataList(parameters);
}
// SQL防火墙
if (url.startsWith("/wall.json")) {
return getWallStatMap(parameters);
}
// SQL详情
if (url.startsWith("/serviceId") && url.indexOf(".json") > 0) {
String serviceId = StringUtils.subString(url, "serviceId=", "&");
Integer id = StringUtils.subStringToInteger(url, "sql-", ".json");
return getSqlStat(id, serviceId);
}
if (url.startsWith("/weburi.json")) {
return getWebURIStatDataList(parameters);
}
if (url.startsWith("/weburi-") && url.indexOf(".json") > 0) {
String uri = StringUtils.subString(url, "weburi-", ".json", true);
return returnJSONResult(RESULT_CODE_SUCCESS, getWebURIStatData(uri));
}
if (url.startsWith("/webapp.json")) {
return returnJSONResult(RESULT_CODE_SUCCESS, getWebAppStatDataList(parameters));
}
if (url.startsWith("/websession.json")) {
return returnJSONResult(RESULT_CODE_SUCCESS, getWebSessionStatDataList(parameters));
}
if (url.startsWith("/websession-") && url.indexOf(".json") > 0) {
String id = StringUtils.subString(url, "websession-", ".json");
return returnJSONResult(RESULT_CODE_SUCCESS, getWebSessionStatData(id));
}
if (url.startsWith("/spring.json")) {
return returnJSONResult(RESULT_CODE_SUCCESS, getSpringStatDataList(parameters));
}
if (url.startsWith("/spring-detail.json")) {
String clazz = parameters.get("class");
String method = parameters.get("method");
return returnJSONResult(RESULT_CODE_SUCCESS, getSpringMethodStatData(clazz, method));
}
return returnJSONResult(RESULT_CODE_ERROR, "Do not support this request, please contact with administrator.");
}
public static String returnJSONResult(int resultCode, Object content) {
Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
dataMap.put("ResultCode", resultCode);
dataMap.put("Content", content);
return JSONUtils.toJSONString(dataMap);
}
public String getWallStatMap(Map<String, String> parameters) {
Map<String, ServiceNode> allNodeMap = getServiceAllNodeMap(parameters);
List<WallResult> countResult = new ArrayList<>();
for (String nodeKey : allNodeMap.keySet()) {
ServiceNode serviceNode = allNodeMap.get(nodeKey);
String url = getRequestUrl(parameters, serviceNode, "/druid/wall.json");
WallResult wallResult = HttpUtil.get(url, WallResult.class);
countResult.add(wallResult);
}
WallResult lastCount = new WallResult();
for (WallResult wallResult : countResult) {
lastCount.sum(wallResult, lastCount);
}
return JSON.toJSONString(lastCount);
}
private List<Map<String, Object>> getSpringStatDataList(Map<String, String> parameters) {
List<Map<String, Object>> array = SpringStatManager.getInstance().getMethodStatData();
return comparatorOrderBy(array, parameters);
}
@SuppressWarnings("unchecked")
private String getWebURIStatDataList(Map<String, String> parameters) {
Map<String, ServiceNode> allNodeMap = getServiceAllNodeMap(parameters);
List<Map<String, Object>> arrayMap = new ArrayList<>();
for (String nodeKey : allNodeMap.keySet()) {
ServiceNode serviceNode = allNodeMap.get(nodeKey);
String url = getRequestUrl(parameters, serviceNode, "/druid/weburi.json");
WebResult dataSourceResult = HttpUtil.get(url, WebResult.class);
if (dataSourceResult != null) {
List<WebResult.ContentBean> nodeContent = dataSourceResult.getContent();
if (nodeContent != null) {
for (WebResult.ContentBean contentBean : nodeContent) {
Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(contentBean), Map.class);
arrayMap.add(map);
}
}
}
}
List<Map<String, Object>> maps = comparatorOrderBy(arrayMap, parameters);
String jsonString = JSON.toJSONString(maps);
JSONArray objects = JSON.parseArray(jsonString);
JSONObject jsonObject = new JSONObject();
jsonObject.put("ResultCode", RESULT_CODE_SUCCESS);
jsonObject.put("Content", objects);
return jsonObject.toJSONString();
}
private Map<String, Object> getWebURIStatData(String uri) {
return WebAppStatManager.getInstance().getURIStatData(uri);
}
private Map<String, Object> getWebSessionStatData(String sessionId) {
return WebAppStatManager.getInstance().getSessionStat(sessionId);
}
private Map<String, Object> getSpringMethodStatData(String clazz, String method) {
return SpringStatManager.getInstance().getMethodStatData(clazz, method);
}
private List<Map<String, Object>> getWebSessionStatDataList(Map<String, String> parameters) {
List<Map<String, Object>> array = WebAppStatManager.getInstance().getSessionStatData();
return comparatorOrderBy(array, parameters);
}
private List<Map<String, Object>> getWebAppStatDataList(Map<String, String> parameters) {
List<Map<String, Object>> array = WebAppStatManager.getInstance().getWebAppStatData();
return comparatorOrderBy(array, parameters);
}
/**
* 获取sql详情
*
* @param id
* @param serviceId consul获取的服务id
* @return
*/
private String getSqlStat(Integer id, String serviceId) {
log.info("serviceId:{}", serviceId);
ServiceNode serviceNode = serviceIdMap.get(serviceId);
String url = "http://" + serviceNode.getAddress() + ":" + serviceNode.getPort() + "/druid/sql-" + id + ".json";
SqlDetailResult sqlDetailResult = HttpUtil.get(url, SqlDetailResult.class);
return JSON.toJSONString(sqlDetailResult);
}
public String getPoolingConnectionInfoByDataSourceId(Integer id, String serviceId) {
getAllServiceNodeMap();
ServiceNode serviceNode = serviceIdMap.get(serviceId);
String url = "http://" + serviceNode.getAddress() + ":" + serviceNode.getPort() + "/druid/connectionInfo-" + id + ".json";
ConnectionResult connectionResult = HttpUtil.get(url, ConnectionResult.class);
return JSON.toJSONString(connectionResult);
}
/**
* SQL监控列表
*
* @param parameters
* @return
*/
@SuppressWarnings("unchecked")
public String getSqlStatDataList(Map<String, String> parameters) {
Map<String, ServiceNode> serviceAllNodeMap = getServiceAllNodeMap(parameters);
List<Map<String, Object>> arrayMap = new ArrayList<>();
for (String nodeKey : serviceAllNodeMap.keySet()) {
ServiceNode serviceNode = serviceAllNodeMap.get(nodeKey);
String serviceName = serviceNode.getServiceName();
String url = getRequestUrl(parameters, serviceNode, "/druid/sql.json");
SqlListResult sqlListResult = HttpUtil.get(url, SqlListResult.class);
if (sqlListResult != null) {
List<SqlListResult.ContentBean> nodeContent = sqlListResult.getContent();
if (nodeContent != null) {
for (SqlListResult.ContentBean contentBean : nodeContent) {
contentBean.setName(serviceName);
contentBean.setAddress(serviceNode.getAddress());
contentBean.setPort(serviceNode.getPort());
contentBean.setServiceId(serviceNode.getId());
Map map = JSONObject.parseObject(JSONObject.toJSONString(contentBean), Map.class);
arrayMap.add(map);
}
}
}
}
List<Map<String, Object>> maps = comparatorOrderBy(arrayMap, parameters);
String jsonString = JSON.toJSONString(maps);
JSONArray objects = JSON.parseArray(jsonString);
JSONObject jsonObject = new JSONObject();
jsonObject.put("ResultCode", RESULT_CODE_SUCCESS);
jsonObject.put("Content", objects);
return jsonObject.toJSONString();
}
/**
* 数据源监控
*
* @param
* @return
*/
public String getDataSourceStatData() {
Map<String, ServiceNode> allNodeMap = getAllServiceNodeMap();
DataSourceResult lastResult = new DataSourceResult();
List<DataSourceResult.ContentBean> contentBeans = new ArrayList<>();
for (String nodeKey : allNodeMap.keySet()) {
ServiceNode serviceNode = allNodeMap.get(nodeKey);
String serviceName = serviceNode.getServiceName();
String url = "http://" + serviceNode.getAddress() + ":" + serviceNode.getPort() + "/druid/datasource.json";
DataSourceResult dataSourceResult = HttpUtil.get(url, lastResult.getClass());
if (dataSourceResult != null) {
List<DataSourceResult.ContentBean> nodeContent = dataSourceResult.getContent();
if (nodeContent != null) {
for (DataSourceResult.ContentBean contentBean : nodeContent) {
contentBean.setName(serviceName);
contentBean.setServiceId(serviceNode.getId());
}
contentBeans.addAll(nodeContent);
}
}
}
lastResult.setContent(contentBeans);
return JSON.toJSONString(lastResult);
}
/**
* 拼接url
*
* @param parameters
* @param serviceNode
* @param prefix
* @return
*/
private String getRequestUrl(Map<String, String> parameters, ServiceNode serviceNode, String prefix) {
StringBuilder stringBuilder = new StringBuilder("http://");
stringBuilder.append(serviceNode.getAddress());
stringBuilder.append(":");
stringBuilder.append(serviceNode.getPort());
stringBuilder.append(prefix);
stringBuilder.append("?orderBy=");
stringBuilder.append(parameters.get("orderBy"));
stringBuilder.append("&orderType=");
stringBuilder.append(parameters.get("orderType"));
stringBuilder.append("&page=");
stringBuilder.append(parameters.get("page"));
stringBuilder.append("&perPageCount=");
stringBuilder.append(parameters.get("perPageCount"));
stringBuilder.append("&");
return stringBuilder.toString();
}
/**
* 处理请求参数
*
* @param url
* @return
*/
public static Map<String, String> getParameters(String url) {
if (url == null || (url = url.trim()).length() == 0) {
return Collections.<String, String>emptyMap();
}
String parametersStr = StringUtils.subString(url, "?", null);
if (parametersStr == null || parametersStr.length() == 0) {
return Collections.<String, String>emptyMap();
}
String[] parametersArray = parametersStr.split("&");
Map<String, String> parameters = new LinkedHashMap<String, String>();
for (String parameterStr : parametersArray) {
int index = parameterStr.indexOf("=");
if (index <= 0) {
continue;
}
String name = parameterStr.substring(0, index);
String value = parameterStr.substring(index + 1);
parameters.put(name, value);
}
return parameters;
}
private List<Map<String, Object>> comparatorOrderBy(List<Map<String, Object>> array, Map<String, String> parameters) {
// when open the stat page before executing some sql
if (array == null || array.isEmpty()) {
return null;
}
// when parameters is null
String orderBy, orderType = null;
Integer page = DEFAULT_PAGE;
Integer perPageCount = DEFAULT_PER_PAGE_COUNT;
if (parameters == null) {
orderBy = DEFAULT_ORDERBY;
orderType = DEFAULT_ORDER_TYPE;
page = DEFAULT_PAGE;
perPageCount = DEFAULT_PER_PAGE_COUNT;
} else {
orderBy = parameters.get("orderBy");
orderType = parameters.get("orderType");
String pageParam = parameters.get("page");
if (pageParam != null && pageParam.length() != 0) {
page = Integer.parseInt(pageParam);
}
String pageCountParam = parameters.get("perPageCount");
if (pageCountParam != null && pageCountParam.length() > 0) {
perPageCount = Integer.parseInt(pageCountParam);
}
}
// others,such as order
orderBy = orderBy == null ? DEFAULT_ORDERBY : orderBy;
orderType = orderType == null ? DEFAULT_ORDER_TYPE : orderType;
if (!ORDER_TYPE_DESC.equals(orderType)) {
orderType = ORDER_TYPE_ASC;
}
// orderby the statData array
if (orderBy.trim().length() != 0) {
Collections.sort(array, new MapComparator<String, Object>(orderBy, ORDER_TYPE_DESC.equals(orderType)));
}
// page
int fromIndex = (page - 1) * perPageCount;
int toIndex = page * perPageCount;
if (toIndex > array.size()) {
toIndex = array.size();
}
return array.subList(fromIndex, toIndex);
}
}
@@ -0,0 +1,79 @@
package com.alibaba.druid.admin.service;
import com.alibaba.druid.admin.config.MonitorProperties;
import com.alibaba.druid.admin.model.ServiceNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author linchtech
* @date 2020-09-22 11:18
**/
@Slf4j
@Component
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled")
public class NacosMonitorStatService extends MonitorStatService {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private MonitorProperties monitorProperties;
@Override
public Map<String, ServiceNode> getAllServiceNodeMap() {
List<String> services = discoveryClient.getServices();
List<ServiceNode> serviceNodes = new ArrayList<>();
for (String serviceId : services) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
for (ServiceInstance serviceInstance : instances) {
if (monitorProperties.getApplications().contains(serviceId)) {
ServiceNode serviceNode = new ServiceNode();
serviceNode.setId(serviceInstance.getInstanceId());
serviceNode.setPort(serviceInstance.getPort());
serviceNode.setAddress(serviceInstance.getHost());
serviceNode.setServiceName(serviceId);
serviceNodes.add(serviceNode);
serviceIdMap.put(serviceInstance.getInstanceId(), serviceNode);
}
}
}
return serviceNodes.parallelStream().collect(Collectors.toMap(i -> i.getServiceName() + "-" + i.getAddress() + "-" + i.getPort(),
Function.identity(), (v1, v2) -> v2));
}
@Override
public Map<String, ServiceNode> getServiceAllNodeMap(Map<String, String> parameters) {
String requestServiceName = parameters.get("serviceName");
List<String> services = discoveryClient.getServices();
List<ServiceNode> serviceNodes = new ArrayList<>();
for (String serviceId : services) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
for (ServiceInstance serviceInstance : instances) {
if (requestServiceName.equals(serviceId)) {
ServiceNode serviceNode = new ServiceNode();
// nacos节点id格式:ip#port#DEFAULT#DEFAULT_GROUP@@name
String id = serviceInstance.getMetadata().get("nacos.instanceId");
serviceNode.setId(id.replaceAll("#","-").replaceAll("@@","-"));
serviceNode.setPort(serviceInstance.getPort());
serviceNode.setAddress(serviceInstance.getHost());
serviceNode.setServiceName(serviceId);
serviceNodes.add(serviceNode);
serviceIdMap.put(serviceNode.getId(), serviceNode);
}
}
}
return serviceNodes.parallelStream().collect(Collectors.toMap(i -> i.getServiceName() + "-" + i.getAddress() + "-" + i.getPort(),
Function.identity(), (v1, v2) -> v2));
}
}
@@ -0,0 +1,34 @@
package com.alibaba.druid.admin.servlet;
import com.alibaba.druid.admin.util.SpringContextUtils;
import com.alibaba.druid.support.http.ResourceServlet;
import com.alibaba.druid.admin.service.MonitorStatService;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletException;
/**
* @author linchtech
* @date 2020-09-16 11:10
**/
@Slf4j
public class MonitorViewServlet extends ResourceServlet {
private MonitorStatService monitorStatService;
public MonitorViewServlet() {
super("support/http/resources");
}
public void init() throws ServletException {
log.info("init MonitorViewServlet");
super.init();
monitorStatService = SpringContextUtils.getBean(MonitorStatService.class);
}
@Override
protected String process(String url) {
return monitorStatService.service(url);
}
}
@@ -0,0 +1,38 @@
package com.alibaba.druid.admin.util;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @author linchtech
* @date 2020-09-16 16:12
**/
public class HttpUtil {
public static <T> T get(String url, Class<T> resultType) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json");
CloseableHttpResponse response;
try {
response = httpClient.execute(httpGet);
String result;
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
return JSON.parseObject(result, resultType);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@@ -0,0 +1,45 @@
package com.alibaba.druid.admin.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author linchtech
* @date 2020-09-22 11:18
**/
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return (T) applicationContext.getBean(clz);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}