diff --git a/alerter/src/main/java/org/apache/hertzbeat/alert/calculate/CalculateAlarm.java b/alerter/src/main/java/org/apache/hertzbeat/alert/calculate/CalculateAlarm.java index 960f88974e1..f18738b3cce 100644 --- a/alerter/src/main/java/org/apache/hertzbeat/alert/calculate/CalculateAlarm.java +++ b/alerter/src/main/java/org/apache/hertzbeat/alert/calculate/CalculateAlarm.java @@ -329,8 +329,7 @@ private boolean execAlertExpression(Map fieldValueMap, String ex } }); match = (Boolean) expression.execute(fieldValueMap); - } catch (CompileExpressionErrorException | - ExpressionSyntaxErrorException compileException) { + } catch (CompileExpressionErrorException | ExpressionSyntaxErrorException compileException) { log.error("Alert Define Rule: {} Compile Error: {}.", expr, compileException.getMessage()); throw compileException; } catch (ExpressionRuntimeException expressionRuntimeException) { diff --git a/alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java b/alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java index c5db7e4c3ac..60fa156ea00 100644 --- a/alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java +++ b/alerter/src/main/java/org/apache/hertzbeat/alert/controller/AlertSilencesController.java @@ -67,7 +67,7 @@ public ResponseEntity>> getAlertSilences( Specification specification = (root, query, criteriaBuilder) -> { List andList = new ArrayList<>(); if (ids != null && !ids.isEmpty()) { - CriteriaBuilder.In inPredicate= criteriaBuilder.in(root.get("id")); + CriteriaBuilder.In inPredicate = criteriaBuilder.in(root.get("id")); for (long id : ids) { inPredicate.value(id); } diff --git a/alerter/src/main/java/org/apache/hertzbeat/alert/dao/AlertDefineDao.java b/alerter/src/main/java/org/apache/hertzbeat/alert/dao/AlertDefineDao.java index 4e453f364fe..8a13bee6658 100644 --- a/alerter/src/main/java/org/apache/hertzbeat/alert/dao/AlertDefineDao.java +++ b/alerter/src/main/java/org/apache/hertzbeat/alert/dao/AlertDefineDao.java @@ -59,8 +59,8 @@ public interface AlertDefineDao extends JpaRepository, JpaSpe * @param metrics metrics * @return Alarm Definition List */ - @Query("select define from AlertDefine define join AlertDefineMonitorBind bind on bind.alertDefineId = define.id " + - "where bind.monitorId = :monitorId and define.app = :app and define.metric = :metrics and define.enable = true and define.preset = false") + @Query("select define from AlertDefine define join AlertDefineMonitorBind bind on bind.alertDefineId = define.id " + + "where bind.monitorId = :monitorId and define.app = :app and define.metric = :metrics and define.enable = true and define.preset = false") List queryAlertDefinesByMonitor(@Param(value = "monitorId") Long monitorId, @Param(value = "app") String app, @Param(value = "metrics") String metrics); diff --git a/alerter/src/main/java/org/apache/hertzbeat/alert/reduce/AlarmSilenceReduce.java b/alerter/src/main/java/org/apache/hertzbeat/alert/reduce/AlarmSilenceReduce.java index 6f9e146287e..8a807a003cf 100644 --- a/alerter/src/main/java/org/apache/hertzbeat/alert/reduce/AlarmSilenceReduce.java +++ b/alerter/src/main/java/org/apache/hertzbeat/alert/reduce/AlarmSilenceReduce.java @@ -87,10 +87,8 @@ public boolean filterSilence(Alert alert) { LocalDateTime nowDate = LocalDateTime.now(); if (alertSilence.getType() == 0) { // once time - boolean startMatch = alertSilence.getPeriodStart() == null || - nowDate.isAfter(alertSilence.getPeriodStart().toLocalDateTime()); - boolean endMatch = alertSilence.getPeriodEnd() == null || - nowDate.isBefore(alertSilence.getPeriodEnd().toLocalDateTime()); + boolean startMatch = alertSilence.getPeriodStart() == null || nowDate.isAfter(alertSilence.getPeriodStart().toLocalDateTime()); + boolean endMatch = alertSilence.getPeriodEnd() == null || nowDate.isBefore(alertSilence.getPeriodEnd().toLocalDateTime()); if (startMatch && endMatch) { int times = Optional.ofNullable(alertSilence.getTimes()).orElse(0); alertSilence.setTimes(times + 1); @@ -104,10 +102,8 @@ public boolean filterSilence(Alert alert) { boolean dayMatch = alertSilence.getDays().stream().anyMatch(item -> item == currentDayOfWeek); if (dayMatch) { LocalTime nowTime = nowDate.toLocalTime(); - boolean startMatch = alertSilence.getPeriodStart() == null || - nowTime.isAfter(alertSilence.getPeriodStart().toLocalTime()); - boolean endMatch = alertSilence.getPeriodEnd() == null || - nowTime.isBefore(alertSilence.getPeriodEnd().toLocalTime()); + boolean startMatch = alertSilence.getPeriodStart() == null || nowTime.isAfter(alertSilence.getPeriodStart().toLocalTime()); + boolean endMatch = alertSilence.getPeriodEnd() == null || nowTime.isBefore(alertSilence.getPeriodEnd().toLocalTime()); if (startMatch && endMatch) { int times = Optional.ofNullable(alertSilence.getTimes()).orElse(0); alertSilence.setTimes(times + 1); diff --git a/alerter/src/main/java/org/apache/hertzbeat/alert/service/impl/AlertServiceImpl.java b/alerter/src/main/java/org/apache/hertzbeat/alert/service/impl/AlertServiceImpl.java index c2b106d9fe9..d744d8a9432 100644 --- a/alerter/src/main/java/org/apache/hertzbeat/alert/service/impl/AlertServiceImpl.java +++ b/alerter/src/main/java/org/apache/hertzbeat/alert/service/impl/AlertServiceImpl.java @@ -140,7 +140,7 @@ private Alert buildAlertData(AlertReport alertReport){ annotations.forEach((k, v) -> { finalSb.append(k).append(":").append(v).append("\n"); }); - }else { + } else { sb = new StringBuilder(alertReport.getContent()); } LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(alertReport.getAlertTime()), diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/CacheIdentifier.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/CacheIdentifier.java index 686dc8c0864..fd6c5495dc8 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/CacheIdentifier.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/CacheIdentifier.java @@ -41,11 +41,11 @@ public class CacheIdentifier { @Override public String toString() { - return "CacheIdentifier {" + - "ip='" + ip + '\'' + - ", port='" + port + '\'' + - ", username+password=>hash='" + Objects.hash(username, password) + '\'' + - ", customArg='" + customArg + '\'' + - '}'; + return "CacheIdentifier {" + + "ip='" + ip + '\'' + + ", port='" + port + '\'' + + ", username+password=>hash='" + Objects.hash(username, password) + '\'' + + ", customArg='" + customArg + '\'' + + '}'; } } diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/dns/DnsCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/dns/DnsCollectImpl.java index 26a4b14fb79..57f5ffde12f 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/dns/DnsCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/dns/DnsCollectImpl.java @@ -122,7 +122,7 @@ public void collect(CollectRep.MetricsData.Builder builder, long monitorId, Stri // add header columns Map headerInfo = dnsResolveResult.getHeaderInfo(); metrics.getAliasFields().forEach(field -> valueRowBuilder.addColumns(headerInfo.getOrDefault(field, CommonConstants.NULL_VALUE))); - }else { + } else { // add question/answer/authority/additional columns List currentMetricsResolveResultList = dnsResolveResult.getList(metrics.getName()); for (int index = 0; index < metrics.getAliasFields().size(); index++) { diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/HttpCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/HttpCollectImpl.java index 5538de0619c..db44abeab17 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/HttpCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/HttpCollectImpl.java @@ -290,8 +290,8 @@ private void parseResponseBySiteMap(String resp, List aliasFields, if (CollectorConstants.URL.equalsIgnoreCase(alias)) { valueRowBuilder.addColumns(siteUrl); } else if (CollectorConstants.STATUS_CODE.equalsIgnoreCase(alias)) { - valueRowBuilder.addColumns(statusCode == null ? - CommonConstants.NULL_VALUE : String.valueOf(statusCode)); + valueRowBuilder.addColumns(statusCode == null + ? CommonConstants.NULL_VALUE : String.valueOf(statusCode)); } else if (CollectorConstants.RESPONSE_TIME.equalsIgnoreCase(alias)) { valueRowBuilder.addColumns(String.valueOf(responseTime)); } else if (CollectorConstants.ERROR_MSG.equalsIgnoreCase(alias)) { @@ -452,8 +452,8 @@ public HttpContext createHttpContext(HttpProtocol httpProtocol) { if (StringUtils.hasText(auth.getDigestAuthUsername()) && StringUtils.hasText(auth.getDigestAuthPassword())) { CredentialsProvider provider = new BasicCredentialsProvider(); - UsernamePasswordCredentials credentials - = new UsernamePasswordCredentials(auth.getDigestAuthUsername(), auth.getDigestAuthPassword()); + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(auth.getDigestAuthUsername(), + auth.getDigestAuthPassword()); provider.setCredentials(AuthScope.ANY, credentials); AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(httpProtocol.getHost(), Integer.parseInt(httpProtocol.getPort())), new DigestScheme()); diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/promethus/exporter/ExporterParser.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/promethus/exporter/ExporterParser.java index a8d01e536e6..33ddab46e06 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/promethus/exporter/ExporterParser.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/http/promethus/exporter/ExporterParser.java @@ -145,9 +145,9 @@ private void parseMetric(StrBuffer buffer) { // todo 这里可能存在问题, 目前逻辑是HISTOGRAM和SUMMARY只创建一个metric // 相比源码有所改动: 源码通过属性存储解析结果; 这边通过参数传递 MetricFamily.Metric metric; - if (!metricList.isEmpty() && - (this.currentMetricFamily.getMetricType().equals(MetricType.HISTOGRAM) || - this.currentMetricFamily.getMetricType().equals(MetricType.SUMMARY))) { + if (!metricList.isEmpty() + && (this.currentMetricFamily.getMetricType().equals(MetricType.HISTOGRAM) + || this.currentMetricFamily.getMetricType().equals(MetricType.SUMMARY))) { metric = metricList.get(0); } else { metric = new MetricFamily.Metric(); diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/HttpsdImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/HttpsdImpl.java index ac90051eb45..6c7f102e10f 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/HttpsdImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/HttpsdImpl.java @@ -41,7 +41,7 @@ */ @Slf4j public class HttpsdImpl extends AbstractCollect { - private final static String SERVER = "server"; + private static final String SERVER = "server"; private final DiscoveryClientManagement discoveryClientManagement = new DiscoveryClientManagement(); @Override @@ -78,13 +78,13 @@ private void collectMetrics(CollectRep.MetricsData.Builder builder, Metrics metr metrics.getAliasFields().forEach(fieldName -> { if (StringUtils.equalsAnyIgnoreCase(CollectorConstants.RESPONSE_TIME, fieldName)) { valueRowBuilder.addColumns(String.valueOf(System.currentTimeMillis() - beginTime)); - }else { + } else { addColumnIfMatched(fieldName, serverInfo, valueRowBuilder); } }); builder.addValues(valueRowBuilder.build()); - }else { + } else { // Service instances monitor discoveryClient.getServices().forEach(serviceInstance -> { CollectRep.ValueRow.Builder valueRowBuilder = CollectRep.ValueRow.newBuilder(); diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/discovery/impl/NacosDiscoveryClient.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/discovery/impl/NacosDiscoveryClient.java index cb80da17985..3ad459fb8bd 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/discovery/impl/NacosDiscoveryClient.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/httpsd/discovery/impl/NacosDiscoveryClient.java @@ -53,7 +53,7 @@ public void initClient(ConnectConfig connectConfig) { try { localConnectConfig = connectConfig; namingService = NamingFactory.createNamingService(connectConfig.getHost() + ":" + connectConfig.getPort()); - }catch (NacosException exception) { + } catch (NacosException exception) { throw new RuntimeException("Failed to init namingService"); } } @@ -106,7 +106,7 @@ public void close() { try { namingService.shutDown(); - }catch (NacosException ignore) { + } catch (NacosException ignore) { } } } diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java index e3c6dc97eca..78c95e81032 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java @@ -102,7 +102,7 @@ public void collect(CollectRep.MetricsData.Builder builder, long monitorId, Stri } ClientSession clientSession = null; MongoClient mongoClient; - CacheIdentifier identifier= null; + CacheIdentifier identifier = null; try { identifier = getIdentifier(metrics.getMongodb()); mongoClient = getClient(metrics, identifier); diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/nebulagraph/NebulaGraphCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/nebulagraph/NebulaGraphCollectImpl.java index dfc7e18ec9c..135bb42ad6b 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/nebulagraph/NebulaGraphCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/nebulagraph/NebulaGraphCollectImpl.java @@ -53,19 +53,19 @@ */ @Slf4j public class NebulaGraphCollectImpl extends AbstractCollect { - private final static int SUCCESS_CODE = 200; + private static final int SUCCESS_CODE = 200; - private final static String[] TIME_RANGE = new String[]{"5", "60", "600", "3600"}; + private static final String[] TIME_RANGE = new String[]{"5", "60", "600", "3600"}; - private final static String REGEX = "\\.%s\\="; + private static final String REGEX = "\\.%s\\="; - private final static String STR_SPLIT = "\n"; + private static final String STR_SPLIT = "\n"; - private final static String STORAGE_SPLIT_KEY_VALUE = "="; + private static final String STORAGE_SPLIT_KEY_VALUE = "="; - private final static String GRAPH_API = "/stats"; + private static final String GRAPH_API = "/stats"; - private final static String STORAGE_API = "/rocksdb_stats"; + private static final String STORAGE_API = "/rocksdb_stats"; @Override @@ -79,7 +79,7 @@ public void collect(CollectRep.MetricsData.Builder builder, long monitorId, Stri NebulaGraphProtocol nebulaGraph = metrics.getNebulaGraph(); String timePeriod = nebulaGraph.getTimePeriod(); - if (!Objects.isNull(nebulaGraph.getTimePeriod())&&!Arrays.asList(TIME_RANGE).contains(timePeriod)) { + if (!Objects.isNull(nebulaGraph.getTimePeriod()) && !Arrays.asList(TIME_RANGE).contains(timePeriod)) { builder.setCode(CollectRep.Code.FAIL); builder.setMsg("The time range for metric statistics, currently supporting 5 seconds, 60 seconds, 600 seconds, and 3600 seconds."); return; diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/nginx/NginxCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/nginx/NginxCollectImpl.java index 9300984922c..2704c59df65 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/nginx/NginxCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/nginx/NginxCollectImpl.java @@ -60,19 +60,19 @@ @Slf4j public class NginxCollectImpl extends AbstractCollect { - private final static int SUCCESS_CODE = 200; - private final static String NGINX_STATUS_NAME = "nginx_status"; - private final static String REQ_STATUS_NAME = "req_status"; - private final static String AVAILABLE = "available"; - private final static String CONNECTIONS = "connections"; - private final static String ACTIVE = "active"; - private final static String GET = "get"; - private final static String FIELD_SPLIT = "_"; - private final static String REGEX_KEYS = "server\\s+(\\w+)\\s+(\\w+)\\s+(\\w+)"; - private final static String REGEX_VALUES = "(\\d+) (\\d+) (\\d+)"; - private final static String REGEX_SERVER = "(\\w+): (\\d+)"; - private final static String REGEX_SPLIT = "\\r?\\n"; - private final static String REGEX_LINE_SPLIT = "\\s+"; + private static final int SUCCESS_CODE = 200; + private static final String NGINX_STATUS_NAME = "nginx_status"; + private static final String REQ_STATUS_NAME = "req_status"; + private static final String AVAILABLE = "available"; + private static final String CONNECTIONS = "connections"; + private static final String ACTIVE = "active"; + private static final String GET = "get"; + private static final String FIELD_SPLIT = "_"; + private static final String REGEX_KEYS = "server\\s+(\\w+)\\s+(\\w+)\\s+(\\w+)"; + private static final String REGEX_VALUES = "(\\d+) (\\d+) (\\d+)"; + private static final String REGEX_SERVER = "(\\w+): (\\d+)"; + private static final String REGEX_SPLIT = "\\r?\\n"; + private static final String REGEX_LINE_SPLIT = "\\s+"; public NginxCollectImpl() { diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/pop3/Pop3CollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/pop3/Pop3CollectImpl.java index 43c67d95880..ed43fad3a89 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/pop3/Pop3CollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/pop3/Pop3CollectImpl.java @@ -42,8 +42,8 @@ @Slf4j public class Pop3CollectImpl extends AbstractCollect { - private final static String EMAIL_COUNT = "email_count"; - private final static String MAILBOX_SIZE = "mailbox_size"; + private static final String EMAIL_COUNT = "email_count"; + private static final String MAILBOX_SIZE = "mailbox_size"; public Pop3CollectImpl() { diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/prometheus/PrometheusAutoCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/prometheus/PrometheusAutoCollectImpl.java index 1631f27b590..90780459741 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/prometheus/PrometheusAutoCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/prometheus/PrometheusAutoCollectImpl.java @@ -223,8 +223,8 @@ public HttpContext createHttpContext(PrometheusProtocol protocol) { if (StringUtils.hasText(auth.getDigestAuthUsername()) && StringUtils.hasText(auth.getDigestAuthPassword())) { CredentialsProvider provider = new BasicCredentialsProvider(); - UsernamePasswordCredentials credentials - = new UsernamePasswordCredentials(auth.getDigestAuthUsername(), auth.getDigestAuthPassword()); + UsernamePasswordCredentials credentials = + new UsernamePasswordCredentials(auth.getDigestAuthUsername(), auth.getDigestAuthPassword()); provider.setCredentials(AuthScope.ANY, credentials); AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(protocol.getHost(), Integer.parseInt(protocol.getPort())), new DigestScheme()); diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/collect/snmp/SnmpCollectImpl.java b/collector/src/main/java/org/apache/hertzbeat/collector/collect/snmp/SnmpCollectImpl.java index 0c26c9d770a..c1661efd087 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/collect/snmp/SnmpCollectImpl.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/collect/snmp/SnmpCollectImpl.java @@ -75,10 +75,10 @@ public class SnmpCollectImpl extends AbstractCollect { private static final String OPERATION_WALK = "walk"; private static final String HEX_SPLIT = ":"; private static final String FORMAT_PATTERN = - "{0,choice,0#|1#1 day, |1<{0,number,integer} days, }" + - "{1,choice,0#|1#1 hour, |1<{1,number,integer} hours, }" + - "{2,choice,0#|1#1 minute, |1<{2,number,integer} minutes, }" + - "{3,choice,0#|1#1 second, |1<{3,number,integer} seconds }"; + "{0,choice,0#|1#1 day, |1<{0,number,integer} days, }" + + "{1,choice,0#|1#1 hour, |1<{1,number,integer} hours, }" + + "{2,choice,0#|1#1 minute, |1<{2,number,integer} minutes, }" + + "{3,choice,0#|1#1 second, |1<{3,number,integer} seconds }"; private final Map versionSnmpService = new ConcurrentHashMap<>(3); diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/MetricsCollect.java b/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/MetricsCollect.java index cffc97ce13f..6be9f859e03 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/MetricsCollect.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/MetricsCollect.java @@ -399,8 +399,8 @@ private void validateResponse(CollectRep.MetricsData metricsData) { } private void setNewThreadName(long monitorId, String app, long startTime, Metrics metrics) { - String builder = monitorId + "-" + app + "-" + metrics.getName() + - "-" + String.valueOf(startTime).substring(9); + String builder = monitorId + "-" + app + "-" + metrics.getName() + + "-" + String.valueOf(startTime).substring(9); Thread.currentThread().setName(builder); } diff --git a/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/HashedWheelTimer.java b/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/HashedWheelTimer.java index c9f60941804..58f9ef1e6b8 100644 --- a/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/HashedWheelTimer.java +++ b/collector/src/main/java/org/apache/hertzbeat/collector/dispatch/timer/HashedWheelTimer.java @@ -248,8 +248,8 @@ public HashedWheelTimer( this.maxPendingTimeouts = maxPendingTimeouts; - if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT && - WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { + if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT + && WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) { reportTooManyInstances(); } } @@ -331,9 +331,9 @@ public void start() { public Set stop() { if (Thread.currentThread() == workerThread) { throw new IllegalStateException( - HashedWheelTimer.class.getSimpleName() + - ".stop() cannot be called from " + - TimerTask.class.getSimpleName()); + HashedWheelTimer.class.getSimpleName() + + ".stop() cannot be called from " + + TimerTask.class.getSimpleName()); } if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) { @@ -411,9 +411,9 @@ public long pendingTimeouts() { } private static void reportTooManyInstances() { - logger.error("You are creating too many HashedWheelTimer instances. " + - "HashedWheelTimer is a shared resource that must be reused across the JVM," + - "so that only a few instances are created."); + logger.error("You are creating too many HashedWheelTimer instances. " + + "HashedWheelTimer is a shared resource that must be reused across the JVM," + + "so that only a few instances are created."); } private final class Worker implements Runnable { diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/Alert.java b/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/Alert.java index 90c31408268..e1087f49edf 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/Alert.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/Alert.java @@ -90,16 +90,16 @@ public class Alert { @Column(length = 4096) private String content; - @Schema(title = "Alarm status: " + - "0-normal alarm (to be processed) " + - "1-threshold triggered but not reached the number of alarms " + - "2-recovered alarm " + - "3-processed", - description = "Alarm status: " + - "0-normal alarm (to be processed) " + - "1-threshold triggered but not reached the number of alarms " + - "2-recovered alarm " + - "3-processed", + @Schema(title = "Alarm status: " + + "0-normal alarm (to be processed) " + + "1-threshold triggered but not reached the number of alarms " + + "2-recovered alarm " + + "3-processed", + description = "Alarm status: " + + "0-normal alarm (to be processed) " + + "1-threshold triggered but not reached the number of alarms " + + "2-recovered alarm " + + "3-processed", example = "1", accessMode = READ_WRITE) @Min(0) @Max(3) diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertConverge.java b/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertConverge.java index 8485f8ce814..0dbca60f9c7 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertConverge.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertConverge.java @@ -81,10 +81,10 @@ public class AlertConverge { example = "true", accessMode = READ_WRITE) private boolean matchAll = true; - @Schema(title = "Alarm Level " + - "0:High-Emergency-Critical Alarm " + - "1:Medium-Critical-Critical Alarm " + - "2:Low-Warning-Warning", + @Schema(title = "Alarm Level " + + "0:High-Emergency-Critical Alarm " + + "1:Medium-Critical-Critical Alarm " + + "2:Low-Warning-Warning", example = "[1]", accessMode = READ_WRITE) @Convert(converter = JsonByteListAttributeConverter.class) private List priorities; diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertSilence.java b/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertSilence.java index 1740872b1b7..3dbc9ae445d 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertSilence.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/alerter/AlertSilence.java @@ -107,8 +107,8 @@ public class AlertSilence { @Column(length = 2048) private List tags; - @Schema(title = "The day of the WEEK is valid in periodic silence, multiple," + - " all or empty is daily 7: Sunday 1: Monday 2: Tuesday 3: Wednesday 4: Thursday 5: Friday 6: Saturday", + @Schema(title = "The day of the WEEK is valid in periodic silence, multiple," + + " all or empty is daily 7: Sunday 1: Monday 2: Tuesday 3: Wednesday 4: Thursday 5: Friday 6: Saturday", example = "[0,1]", accessMode = READ_WRITE) @Convert(converter = JsonByteListAttributeConverter.class) private List days; diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/dto/AlertReport.java b/common/src/main/java/org/apache/hertzbeat/common/entity/dto/AlertReport.java index dee7b25c14c..9cb1b854c0b 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/dto/AlertReport.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/dto/AlertReport.java @@ -51,13 +51,13 @@ public class AlertReport { example = "1694589491000", accessMode = READ_WRITE) private long alertTime; - @Schema(title = "Alarm priority. " + - "0: high emergency alarm red " + - "1: medium critical serious alarm Orange " + - "2: low warning warning alarm yellow", - description = "Alarm priority. 0: high emergency alarm red " + - "1: medium critical serious alarm Orange " + - "2: low warning warning alarm yellow", + @Schema(title = "Alarm priority. " + + "0: high emergency alarm red " + + "1: medium critical serious alarm Orange " + + "2: low warning warning alarm yellow", + description = "Alarm priority. 0: high emergency alarm red " + + "1: medium critical serious alarm Orange " + + "2: low warning warning alarm yellow", example = "1", accessMode = READ_WRITE) private Integer priority; @@ -73,7 +73,7 @@ public class AlertReport { @Schema(title = " Alarm marking (monitorId:xxx,monitorName:xxx)", description = "Alarm labeling", - example ="{\"key1\":\"value1\"}" + example = "{\"key1\":\"value1\"}" , accessMode = READ_WRITE) private Map annotations; diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonLongListAttributeConverter.java b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonLongListAttributeConverter.java index ee25be0c083..f746adae499 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonLongListAttributeConverter.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/JsonLongListAttributeConverter.java @@ -41,7 +41,7 @@ public String convertToDatabaseColumn(List attribute) { @Override public List convertToEntityAttribute(String dbData) { if (StringUtils.isBlank(dbData)) { - return List.of(); + return List.of(); } TypeReference> typeReference = new TypeReference<>() { }; @@ -49,7 +49,11 @@ public List convertToEntityAttribute(String dbData) { if (longList == null && !dbData.isEmpty()) { if (StringUtils.isNumeric(dbData)) { return List.of(Long.parseLong(dbData)); - } else throw new NumberFormatException("String convert to Long error"); - } else return longList; + } else { + throw new NumberFormatException("String convert to Long error"); + } + } else { + return longList; + } } } diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeReceiver.java b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeReceiver.java index 614c4fd2fd2..a8e34a2051d 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeReceiver.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeReceiver.java @@ -67,13 +67,13 @@ public class NoticeReceiver { @NotNull private String name; - @Schema(title = "Notification information method: 0-SMS 1-Email 2-webhook 3-WeChat Official Account 4-Enterprise WeChat Robot " + - "5-DingTalk Robot 6-FeiShu Robot 7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise WeChat app message", - description = "Notification information method: " + - "0-SMS 1-Email 2-webhook 3-WeChat Official Account " + - "4-Enterprise WeChat Robot 5-DingTalk Robot 6-FeiShu Robot " + - "7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise " + - "WeChat app message", + @Schema(title = "Notification information method: 0-SMS 1-Email 2-webhook 3-WeChat Official Account 4-Enterprise WeChat Robot " + + "5-DingTalk Robot 6-FeiShu Robot 7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise WeChat app message", + description = "Notification information method: " + + "0-SMS 1-Email 2-webhook 3-WeChat Official Account " + + "4-Enterprise WeChat Robot 5-DingTalk Robot 6-FeiShu Robot " + + "7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise " + + "WeChat app message", accessMode = READ_WRITE) @Min(0) @NotNull diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeRule.java b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeRule.java index 03bf955a3b1..f0654712446 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeRule.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeRule.java @@ -105,8 +105,8 @@ public class NoticeRule { example = "false", accessMode = READ_WRITE) private boolean filterAll = true; - @Schema(title = "Filter the matching alarm level, empty is all alarm level " + - "0: high -emergency- Urgent alarm - red 1: Medium -critical- Serious alarm - orange 2: Low -warning- Warning alarm - yellow", + @Schema(title = "Filter the matching alarm level, empty is all alarm level " + + "0: high -emergency- Urgent alarm - red 1: Medium -critical- Serious alarm - orange 2: Low -warning- Warning alarm - yellow", example = "[1]", accessMode = READ_WRITE) @Convert(converter = JsonByteListAttributeConverter.class) private List priorities; diff --git a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeTemplate.java b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeTemplate.java index 23fd9ddaa8c..8f5a27559a4 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeTemplate.java +++ b/common/src/main/java/org/apache/hertzbeat/common/entity/manager/NoticeTemplate.java @@ -71,12 +71,12 @@ public class NoticeTemplate { @NotBlank private String name; - @Schema(title = "Notification information method: 0-SMS 1-Email 2-webhook 3-WeChat Official Account 4-Enterprise WeChat Robot " + - "5-DingTalk Robot 6-FeiShu Robot 7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise WeChat app message", - description = "Notification information method: " + - "0-SMS 1-Email 2-webhook 3-WeChat Official Account " + - "4-Enterprise WeChat Robot 5-DingTalk Robot 6-FeiShu Robot " + - "7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise WeChat app message", + @Schema(title = "Notification information method: 0-SMS 1-Email 2-webhook 3-WeChat Official Account 4-Enterprise WeChat Robot " + + "5-DingTalk Robot 6-FeiShu Robot 7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise WeChat app message", + description = "Notification information method: " + + "0-SMS 1-Email 2-webhook 3-WeChat Official Account " + + "4-Enterprise WeChat Robot 5-DingTalk Robot 6-FeiShu Robot " + + "7-Telegram Bot 8-SlackWebHook 9-Discord Bot 10-Enterprise WeChat app message", accessMode = READ_WRITE) @Min(0) @NotNull @@ -90,14 +90,14 @@ public class NoticeTemplate { @Schema(title = "Template content", description = "Template content", - example = "[${title}]\n" + - "${targetLabel} : ${target}\n" + - "<#if (monitorId??)>${monitorIdLabel} : ${monitorId} \n" + - "<#if (monitorName??)>${monitorNameLabel} : ${monitorName} \n" + - "<#if (monitorHost??)>${monitorHostLabel} : ${monitorHost} \n" + - "${priorityLabel} : ${priority}\n" + - "${triggerTimeLabel} : ${triggerTime}\n" + - "${contentLabel} : ${content}", accessMode = READ_WRITE) + example = "[${title}]\n" + + "${targetLabel} : ${target}\n" + + "<#if (monitorId??)>${monitorIdLabel} : ${monitorId} \n" + + "<#if (monitorName??)>${monitorNameLabel} : ${monitorName} \n" + + "<#if (monitorHost??)>${monitorHostLabel} : ${monitorHost} \n" + + "${priorityLabel} : ${priority}\n" + + "${triggerTimeLabel} : ${triggerTime}\n" + + "${contentLabel} : ${content}", accessMode = READ_WRITE) @Size(max = 60000) @Lob @NotBlank diff --git a/common/src/main/java/org/apache/hertzbeat/common/support/ResourceBundleUtf8Control.java b/common/src/main/java/org/apache/hertzbeat/common/support/ResourceBundleUtf8Control.java index eeb34effe13..13448e2868a 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/support/ResourceBundleUtf8Control.java +++ b/common/src/main/java/org/apache/hertzbeat/common/support/ResourceBundleUtf8Control.java @@ -49,8 +49,8 @@ public ResourceBundle newBundle(String baseName, Locale locale, String format, C if (JAVA_CLASS.equals(format)) { try { @SuppressWarnings("unchecked") - Class bundleClass - = (Class) loader.loadClass(bundleName); + Class bundleClass = + (Class) loader.loadClass(bundleName); // If the class isn't a ResourceBundle subclass, throw a // ClassCastException. diff --git a/common/src/main/java/org/apache/hertzbeat/common/util/prometheus/PrometheusUtil.java b/common/src/main/java/org/apache/hertzbeat/common/util/prometheus/PrometheusUtil.java index 11f9eca08fb..f7ff4150f81 100644 --- a/common/src/main/java/org/apache/hertzbeat/common/util/prometheus/PrometheusUtil.java +++ b/common/src/main/java/org/apache/hertzbeat/common/util/prometheus/PrometheusUtil.java @@ -230,7 +230,7 @@ private static int skipCommentLine(InputStream inputStream) throws IOException { } public static List parseMetrics(InputStream inputStream) throws IOException { - List metricList= new ArrayList<>(); + List metricList = new ArrayList<>(); int i = parseMetric(inputStream, metricList); while (i == '\n' || i == COMMENT_LINE) { if (i == COMMENT_LINE) { diff --git a/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/NoticeConfigServiceImpl.java b/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/NoticeConfigServiceImpl.java index 85fb1603d72..11ac076714e 100644 --- a/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/NoticeConfigServiceImpl.java +++ b/manager/src/main/java/org/apache/hertzbeat/manager/service/impl/NoticeConfigServiceImpl.java @@ -182,12 +182,12 @@ public List getReceiverFilterRule(Alert alert) { } // filter time LocalTime nowTime = nowDate.toLocalTime(); - boolean startMatch = rule.getPeriodStart() == null || - nowTime.isAfter(rule.getPeriodStart().toLocalTime()) || - (rule.getPeriodEnd() != null && rule.getPeriodStart().isAfter(rule.getPeriodEnd()) + boolean startMatch = rule.getPeriodStart() == null + || nowTime.isAfter(rule.getPeriodStart().toLocalTime()) + || (rule.getPeriodEnd() != null && rule.getPeriodStart().isAfter(rule.getPeriodEnd()) && nowTime.isBefore(rule.getPeriodStart().toLocalTime())); - boolean endMatch = rule.getPeriodEnd() == null || - nowTime.isBefore(rule.getPeriodEnd().toLocalTime()); + boolean endMatch = rule.getPeriodEnd() == null + || nowTime.isBefore(rule.getPeriodEnd().toLocalTime()); return startMatch && endMatch; }) .collect(Collectors.toList()); diff --git a/push/src/main/java/org/apache/hertzbeat/push/service/impl/PushServiceImpl.java b/push/src/main/java/org/apache/hertzbeat/push/service/impl/PushServiceImpl.java index f6db48c7c23..d267aef974f 100644 --- a/push/src/main/java/org/apache/hertzbeat/push/service/impl/PushServiceImpl.java +++ b/push/src/main/java/org/apache/hertzbeat/push/service/impl/PushServiceImpl.java @@ -67,9 +67,9 @@ public class PushServiceImpl implements PushService { new Timer().schedule(new TimerTask() { @Override public void run() { - try{ + try { deletePeriodically(); - }catch (Exception e) { + } catch (Exception e) { log.error("periodical deletion failed. {}", e.getMessage()); } } diff --git a/script/checkstyle/checkstyle.xml b/script/checkstyle/checkstyle.xml index e144b3debe4..91a4d9b97a2 100644 --- a/script/checkstyle/checkstyle.xml +++ b/script/checkstyle/checkstyle.xml @@ -324,5 +324,77 @@ value="Unused import: {0}."/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryGrepTimeDbDataStorage.java b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryGrepTimeDbDataStorage.java index 7e408c97b1b..eaea3595222 100644 --- a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryGrepTimeDbDataStorage.java +++ b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryGrepTimeDbDataStorage.java @@ -70,15 +70,15 @@ public class HistoryGrepTimeDbDataStorage extends AbstractHistoryDataStorage { * storage database */ private static final String STORAGE_DATABASE = "hertzbeat"; - private static final String QUERY_HISTORY_SQL - = "SELECT CAST (ts AS Int64) ts, instance, \"%s\" FROM %s WHERE ts >= %s and monitor_id = %s order by ts desc;"; - private static final String QUERY_HISTORY_WITH_INSTANCE_SQL - = "SELECT CAST (ts AS Int64) ts, instance, \"%s\" FROM %s WHERE ts >= %s and monitor_id = %s and instance = %s order by ts desc;"; - private static final String QUERY_INSTANCE_SQL - = "SELECT DISTINCT instance FROM %s WHERE ts >= now() - interval '1' WEEK"; - private static final String QUERY_HISTORY_INTERVAL_WITH_INSTANCE_SQL - = "SELECT first, avg ,max, min FROM (SELECT \"%s\" as first FROM %s WHERE monitor_id = %s and ts >= %s" + - " and ts < %s ORDER BY ts LIMIT 1) LEFT JOIN (SELECT avg(\"%s\") as avg, min(\"%s\") as min, max(\"%s\") as max FROM %s WHERE ts >= %s and ts < %s) ON 1=1"; + private static final String QUERY_HISTORY_SQL = + "SELECT CAST (ts AS Int64) ts, instance, \"%s\" FROM %s WHERE ts >= %s and monitor_id = %s order by ts desc;"; + private static final String QUERY_HISTORY_WITH_INSTANCE_SQL = + "SELECT CAST (ts AS Int64) ts, instance, \"%s\" FROM %s WHERE ts >= %s and monitor_id = %s and instance = %s order by ts desc;"; + private static final String QUERY_INSTANCE_SQL = + "SELECT DISTINCT instance FROM %s WHERE ts >= now() - interval '1' WEEK"; + private static final String QUERY_HISTORY_INTERVAL_WITH_INSTANCE_SQL = + "SELECT first, avg ,max, min FROM (SELECT \"%s\" as first FROM %s WHERE monitor_id = %s and ts >= %s" + + " and ts < %s ORDER BY ts LIMIT 1) LEFT JOIN (SELECT avg(\"%s\") as avg, min(\"%s\") as min, max(\"%s\") as max FROM %s WHERE ts >= %s and ts < %s) ON 1=1"; private static final String TABLE_NOT_EXIST = "not exist"; private static final String DATABASE_NOT_EXIST = "not exist"; private GreptimeDB greptimeDb; @@ -235,15 +235,15 @@ public Map> getHistoryMetricData(Long monitorId, String app, String label, String history) { Map> instanceValuesMap = new HashMap<>(8); if (!isServerAvailable()) { - log.error("\n\t---------------Greptime Init Failed---------------\n" + - "\t--------------Please Config Greptime--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------Greptime Init Failed---------------\n" + + "\t--------------Please Config Greptime--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return instanceValuesMap; } long expireTime = getExpireTimeFromToken(history); String table = app + "_" + metrics; - String selectSql = label == null ? - String.format(QUERY_HISTORY_SQL, metric, table, expireTime, monitorId) + String selectSql = label == null + ? String.format(QUERY_HISTORY_SQL, metric, table, expireTime, monitorId) : String.format(QUERY_HISTORY_WITH_INSTANCE_SQL, metric, table, expireTime, monitorId, label); log.debug("selectSql: {}", selectSql); QueryRequest request = QueryRequest.newBuilder() @@ -302,9 +302,9 @@ public Map> getHistoryIntervalMetricData(Long monitorId, Str String metric, String label, String history) { Map> instanceValuesMap = new HashMap<>(8); if (!isServerAvailable()) { - log.error("\n\t---------------Greptime Init Failed---------------\n" + - "\t--------------Please Config Greptime--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------Greptime Init Failed---------------\n" + + "\t--------------Please Config Greptime--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return instanceValuesMap; } String table = app + "_" + metrics; diff --git a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryIotDbDataStorage.java b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryIotDbDataStorage.java index bbafe19a95c..ab928e37b8e 100644 --- a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryIotDbDataStorage.java +++ b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryIotDbDataStorage.java @@ -76,10 +76,10 @@ public class HistoryIotDbDataStorage extends AbstractHistoryDataStorage { private static final String SHOW_STORAGE_GROUP = "show storage group"; - private static final String QUERY_HISTORY_SQL - = "SELECT %s FROM %s WHERE Time >= now() - %s order by Time desc"; - private static final String QUERY_HISTORY_INTERVAL_WITH_INSTANCE_SQL - = "SELECT FIRST_VALUE(%s), AVG(%s), MIN_VALUE(%s), MAX_VALUE(%s) FROM %s GROUP BY ([now() - %s, now()), 4h)"; + private static final String QUERY_HISTORY_SQL = + "SELECT %s FROM %s WHERE Time >= now() - %s order by Time desc"; + private static final String QUERY_HISTORY_INTERVAL_WITH_INSTANCE_SQL = + "SELECT FIRST_VALUE(%s), AVG(%s), MIN_VALUE(%s), MAX_VALUE(%s) FROM %s GROUP BY ([now() - %s, now()), 4h)"; private SessionPool sessionPool; @@ -256,9 +256,9 @@ public Map> getHistoryMetricData(Long monitorId, String app, String label, String history) { Map> instanceValuesMap = new HashMap<>(8); if (!isServerAvailable()) { - log.error("\n\t---------------IotDb Init Failed---------------\n" + - "\t--------------Please Config IotDb--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------IotDb Init Failed---------------\n" + + "\t--------------Please Config IotDb--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return instanceValuesMap; } String deviceId = getDeviceId(app, metrics, monitorId, label, true); @@ -317,9 +317,9 @@ public Map> getHistoryIntervalMetricData(Long monitorId, Str String metric, String label, String history) { Map> instanceValuesMap = new HashMap<>(8); if (!isServerAvailable()) { - log.error("\n\t---------------IotDb Init Failed---------------\n" + - "\t--------------Please Config IotDb--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------IotDb Init Failed---------------\n" + + "\t--------------Please Config IotDb--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return instanceValuesMap; } String deviceId = getDeviceId(app, metrics, monitorId, label, true); @@ -420,10 +420,10 @@ private List queryAllDevices(String deviceId) { * 查询时可以通过 ${group}.${app}.${metrics}.${monitor}.* 的方式获取所有instance数据 */ private String getDeviceId(String app, String metrics, Long monitorId, String labels, boolean useQuote) { - String deviceId = STORAGE_GROUP + "." + - (useQuote ? addQuote(app) : app) + "." + - (useQuote ? addQuote(metrics) : metrics) + "." + - ((IotDbVersion.V_1_0.equals(version) || useQuote) ? addQuote(monitorId.toString()) : monitorId.toString()); + String deviceId = STORAGE_GROUP + "." + + (useQuote ? addQuote(app) : app) + "." + + (useQuote ? addQuote(metrics) : metrics) + "." + + ((IotDbVersion.V_1_0.equals(version) || useQuote) ? addQuote(monitorId.toString()) : monitorId.toString()); if (labels != null && !labels.isEmpty() && !labels.equals(CommonConstants.NULL_VALUE)) { deviceId += "." + addQuote(labels); } diff --git a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryJpaDatabaseDataStorage.java b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryJpaDatabaseDataStorage.java index 58b04229c57..efe9c7e4caf 100644 --- a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryJpaDatabaseDataStorage.java +++ b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryJpaDatabaseDataStorage.java @@ -81,8 +81,8 @@ public void expiredDataCleaner() { .build(); ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory); scheduledExecutor.scheduleAtFixedRate(() -> { - log.warn("[jpa-metrics-store]-start running expired data cleaner." + - "Please use time series db instead of jpa for better performance"); + log.warn("[jpa-metrics-store]-start running expired data cleaner." + + "Please use time series db instead of jpa for better performance"); String expireTimeStr = jpaProperties.expireTime(); long expireTime = 0; try { diff --git a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryTdEngineDataStorage.java b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryTdEngineDataStorage.java index 4b96694b261..490377da7c0 100644 --- a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryTdEngineDataStorage.java +++ b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryTdEngineDataStorage.java @@ -57,17 +57,16 @@ public class HistoryTdEngineDataStorage extends AbstractHistoryDataStorage { private static final String INSERT_TABLE_DATA_SQL = "INSERT INTO `%s` USING `%s` TAGS (%s) VALUES %s"; private static final String CREATE_SUPER_TABLE_SQL = "CREATE STABLE IF NOT EXISTS `%s` %s TAGS (monitor BIGINT)"; private static final String NO_SUPER_TABLE_ERROR = "Table does not exist"; - private static final String QUERY_HISTORY_WITH_INSTANCE_SQL - = "SELECT ts, instance, `%s` FROM `%s` WHERE instance = '%s' AND ts >= now - %s order by ts desc"; - private static final String QUERY_HISTORY_SQL - = "SELECT ts, instance, `%s` FROM `%s` WHERE ts >= now - %s order by ts desc"; - private static final String QUERY_HISTORY_INTERVAL_WITH_INSTANCE_SQL - = "SELECT first(ts), first(`%s`), avg(`%s`), min(`%s`), max(`%s`) FROM `%s` WHERE instance = '%s' AND ts >= now - %s interval(4h)"; - private static final String QUERY_INSTANCE_SQL - = "SELECT DISTINCT instance FROM `%s` WHERE ts >= now - 1w"; + private static final String QUERY_HISTORY_WITH_INSTANCE_SQL = + "SELECT ts, instance, `%s` FROM `%s` WHERE instance = '%s' AND ts >= now - %s order by ts desc"; + private static final String QUERY_HISTORY_SQL = + "SELECT ts, instance, `%s` FROM `%s` WHERE ts >= now - %s order by ts desc"; + private static final String QUERY_HISTORY_INTERVAL_WITH_INSTANCE_SQL = + "SELECT first(ts), first(`%s`), avg(`%s`), min(`%s`), max(`%s`) FROM `%s` WHERE instance = '%s' AND ts >= now - %s interval(4h)"; + private static final String QUERY_INSTANCE_SQL = + "SELECT DISTINCT instance FROM `%s` WHERE ts >= now - 1w"; - private static final String TABLE_NOT_EXIST - = "Table does not exist"; + private static final String TABLE_NOT_EXIST = "Table does not exist"; private HikariDataSource hikariDataSource; private final int tableStrColumnDefineMaxLength; @@ -103,10 +102,10 @@ private boolean initTdEngineDatasource(WarehouseProperties.StoreProperties.TdEng try { this.hikariDataSource = new HikariDataSource(config); } catch (Exception e) { - log.warn("\n\t------------------WARN WARN WARN------------------\n" + - "\t---------------Init TdEngine Failed---------------\n" + - "\t--------------Please Config Tdengine--------------\n" + - "\t---------Or Can Not Use Metric History Now---------\n"); + log.warn("\n\t------------------WARN WARN WARN------------------\n" + + "\t---------------Init TdEngine Failed---------------\n" + + "\t--------------Please Config Tdengine--------------\n" + + "\t---------Or Can Not Use Metric History Now---------\n"); return false; } return true; @@ -241,9 +240,9 @@ public Map> getHistoryMetricData(Long monitorId, String app, log.debug(selectSql); Map> instanceValuesMap = new HashMap<>(8); if (!serverAvailable) { - log.error("\n\t---------------TdEngine Init Failed---------------\n" + - "\t--------------Please Config Tdengine--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------TdEngine Init Failed---------------\n" + + "\t--------------Please Config Tdengine--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return instanceValuesMap; } try (Connection connection = hikariDataSource.getConnection(); @@ -280,9 +279,9 @@ public Map> getHistoryMetricData(Long monitorId, String app, public Map> getHistoryIntervalMetricData(Long monitorId, String app, String metrics, String metric, String label, String history) { if (!serverAvailable) { - log.error("\n\t---------------TdEngine Init Failed---------------\n" + - "\t--------------Please Config Tdengine--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------TdEngine Init Failed---------------\n" + + "\t--------------Please Config Tdengine--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return Collections.emptyMap(); } String table = app + "_" + metrics + "_" + monitorId; diff --git a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryVictoriaMetricsDataStorage.java b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryVictoriaMetricsDataStorage.java index e2279618bcc..4c27cf868f9 100644 --- a/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryVictoriaMetricsDataStorage.java +++ b/warehouse/src/main/java/org/apache/hertzbeat/warehouse/store/HistoryVictoriaMetricsDataStorage.java @@ -209,9 +209,9 @@ public Map> getHistoryMetricData(Long monitorId, String app, if (CommonConstants.PROMETHEUS.equals(app)) { labelName = metrics; } - String timeSeriesSelector = LABEL_KEY_NAME + "=\"" + labelName + "\"" + - "," + LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"" + - "," + MONITOR_METRIC_KEY + "=\"" + metric + "\""; + String timeSeriesSelector = LABEL_KEY_NAME + "=\"" + labelName + "\"" + + "," + LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"" + + "," + MONITOR_METRIC_KEY + "=\"" + metric + "\""; Map> instanceValuesMap = new HashMap<>(8); try { HttpHeaders headers = new HttpHeaders(); @@ -275,9 +275,9 @@ public Map> getHistoryMetricData(Long monitorId, String app, public Map> getHistoryIntervalMetricData(Long monitorId, String app, String metrics, String metric, String label, String history) { if (!serverAvailable) { - log.error("\n\t---------------VictoriaMetrics Init Failed---------------\n" + - "\t--------------Please Config VictoriaMetrics--------------\n" + - "\t----------Can Not Use Metric History Now----------\n"); + log.error("\n\t---------------VictoriaMetrics Init Failed---------------\n" + + "\t--------------Please Config VictoriaMetrics--------------\n" + + "\t----------Can Not Use Metric History Now----------\n"); return Collections.emptyMap(); } long endTime = ZonedDateTime.now().toEpochSecond(); @@ -300,9 +300,9 @@ public Map> getHistoryIntervalMetricData(Long monitorId, Str if (CommonConstants.PROMETHEUS.equals(app)) { labelName = metrics; } - String timeSeriesSelector = LABEL_KEY_NAME + "=\"" + labelName + "\"" + - "," + LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"" + - "," + MONITOR_METRIC_KEY + "=\"" + metric + "\""; + String timeSeriesSelector = LABEL_KEY_NAME + "=\"" + labelName + "\"" + + "," + LABEL_KEY_INSTANCE + "=\"" + monitorId + "\"" + + "," + MONITOR_METRIC_KEY + "=\"" + metric + "\""; Map> instanceValuesMap = new HashMap<>(8); try { HttpHeaders headers = new HttpHeaders();