Unverified Commit 9f0d4a9d authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature] [monitor] add monitor & jmx (#2056)

* add monitor & jmx * add monitor & jmx * remove metrics model * add note * add note
parent ae619b9c
...@@ -221,11 +221,6 @@ ...@@ -221,11 +221,6 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId> <artifactId>spring-boot-starter-aop</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.prometheus.jmx</groupId>
<artifactId>jmx_prometheus_javaagent</artifactId>
<version>0.16.1</version>
</dependency>
<dependency> <dependency>
<groupId>com.github.jsqlparser</groupId> <groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId> <artifactId>jsqlparser</artifactId>
...@@ -302,12 +297,44 @@ ...@@ -302,12 +297,44 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId> <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
<dependency>
<groupId>io.prometheus.jmx</groupId>
<artifactId>jmx_prometheus_javaagent</artifactId>
<version>0.16.1</version>
<exclusions>
<exclusion>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> </dependency>
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.paimon</groupId>
<artifactId>paimon-bundle</artifactId>
<version>0.4.0-incubating</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.configure;
import org.dinky.data.annotation.GaugeM;
import org.dinky.data.metrics.BaseMetrics;
import org.dinky.data.metrics.Cpu;
import org.dinky.data.metrics.Jvm;
import org.dinky.data.metrics.Mem;
import org.dinky.data.metrics.MetricsTotal;
import org.dinky.data.vo.MetricsVO;
import org.dinky.utils.PaimonUtil;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Configuration
@RequiredArgsConstructor
@Getter
@Setter
@EnableScheduling
public class MetricConfig {
private final MeterRegistry registry;
private ThreadPoolExecutor writePool =
new ThreadPoolExecutor(5, 10, 1, TimeUnit.DAYS, new SynchronousQueue<>());
private static final Queue<MetricsVO> metricsQueue = new ConcurrentLinkedQueue<>();
public static final int SCHEDULED_RATE = 1000;
/** Update status per second */
@Scheduled(fixedRate = SCHEDULED_RATE)
public void scheduled() {
updateState();
}
/** Entering the lake every 10 states */
@Scheduled(fixedRate = 10000)
@PreDestroy
public void writeScheduled() {
PaimonUtil.writeMetrics(new ArrayList<>(metricsQueue));
metricsQueue.clear();
// PaimonUtil.batchReadTable(PaimonUtil.METRICS_IDENTIFIER,Metrics.class,p->
// Collections.singletonList(p.greaterThan(0,
// Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(DateUtil.date(1686300257085L))))));
PaimonUtil.batchReadTable(PaimonUtil.METRICS_IDENTIFIER, MetricsVO.class);
}
@PostConstruct
public void init() {
MetricsTotal metricsTotal = MetricsTotal.instance;
registerMetrics(metricsTotal.getJvm());
registerMetrics(metricsTotal.getCpu());
registerMetrics(metricsTotal.getMem());
}
public void updateState() {
MetricsTotal metricsTotal = MetricsTotal.instance;
LocalDateTime now = LocalDateTime.now();
metricsTotal.setJvm(Jvm.of());
metricsTotal.setCpu(Cpu.of());
metricsTotal.setMem(Mem.of());
MetricsVO metrics = new MetricsVO();
metrics.setContent(JSONUtil.toJsonStr(metricsTotal));
metrics.setHeartTime(now);
metrics.setModel("local");
metricsQueue.add(metrics);
// writePool.execute(metrics::insert);
}
public void registerMetrics(BaseMetrics baseMetrics) {
Field[] baseFields = ReflectUtil.getFields(this.getClass());
Field baseField =
Arrays.stream(baseFields)
.filter(field -> field.getType().equals(baseMetrics.getClass()))
.findFirst()
.orElse(null);
if (baseField == null) {
return;
}
Field[] fields = ReflectUtil.getFields(baseMetrics.getClass());
for (Field field : fields) {
GaugeM gaugeM = AnnotationUtil.getAnnotation(field, GaugeM.class);
Opt.ofNullable(gaugeM)
.ifPresent(
g ->
Gauge.builder(
gaugeM.name(),
() ->
(Number)
ReflectUtil.getFieldValue(
ReflectUtil
.getFieldValue(
this,
baseField),
field))
.baseUnit(g.baseUnit())
.tags(g.tags())
.description(gaugeM.description())
.register(registry));
}
}
public static Queue<MetricsVO> getMetricsQueue() {
return metricsQueue;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.configure;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import cn.hutool.core.thread.BlockPolicy;
@Configuration
public class ThreadPoolConfig {
/**
* Use sse to return to monitor the latest data(使用sse返回监控最新数据)
*
* @return
*/
@Bean
public Executor scheduleRefreshMonitorDataExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
// 核心线程数
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
// 最大线程数
threadPoolTaskExecutor.setMaxPoolSize(200);
// 配置队列大小
threadPoolTaskExecutor.setQueueCapacity(1000);
// 配置线程池前缀
threadPoolTaskExecutor.setThreadNamePrefix("SCH-refresh-mt-");
// 阻塞策略
threadPoolTaskExecutor.setRejectedExecutionHandler(new BlockPolicy());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.controller;
import org.dinky.data.result.Result;
import org.dinky.data.vo.MetricsVO;
import org.dinky.service.MonitorService;
import org.dinky.sse.SseEmitterUTF8;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/api/monitor")
@RequiredArgsConstructor
public class MonitorController {
private final MonitorService monitorService;
@GetMapping("/getSysData")
public Result<List<MetricsVO>> getData(@RequestParam Long startTime, Long endTime) {
return Result.succeed(
monitorService.getData(
DateUtil.date(startTime),
DateUtil.date(Opt.ofNullable(endTime).orElse(DateUtil.date().getTime()))));
}
@GetMapping(value = "/getLastUpdateData", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@CrossOrigin("*")
public SseEmitter getLastUpdateData(Long lastTime) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
return monitorService.sendLatestData(
emitter, DateUtil.date(Opt.ofNullable(lastTime).orElse(DateUtil.date().getTime())));
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface GaugeM {
String name();
String baseUnit() default "bytes";
String[] tags() default {};
String description() default "";
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.metrics;
import java.io.Serializable;
public class BaseMetrics implements Serializable {}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.metrics;
import org.dinky.data.annotation.GaugeM;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.With;
@Getter
@Setter
@With
@AllArgsConstructor
@NoArgsConstructor
public class Cpu extends BaseMetrics {
/** 核心数 */
private Integer cpuNum;
/** CPU总的使用率 */
@GaugeM(name = "cpu.total", description = "Total CPU usage")
private Double total;
/** CPU系统使用率 */
@GaugeM(name = "cpu.sys", description = "CPU system usage")
private Double sys;
/** CPU用户使用率 */
@GaugeM(name = "cpu.used", description = "CPU user usage")
private Double used;
/** CPU当前等待率 */
@GaugeM(name = "cpu.wait", description = "CPU current wait rate")
private Double wait;
/** CPU当前空闲率 */
@GaugeM(name = "cpu.free", description = "CPU current idle rate")
private Double free;
public static Cpu of() {
CpuInfo cpuInfo = OshiUtil.getCpuInfo();
return BeanUtil.toBean(cpuInfo, Cpu.class);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.metrics;
import org.dinky.data.annotation.GaugeM;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import cn.hutool.system.JvmInfo;
import cn.hutool.system.SystemUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.With;
@Setter
@Getter
@With
@AllArgsConstructor
@NoArgsConstructor
public class Jvm extends BaseMetrics {
/** 当前JVM占用的内存总数(b) */
@GaugeM(
name = "jvm.total",
description = "The total amount of memory currently occupied by the JVM (b)")
private long total;
/** JVM最大可用内存总数(b) */
@GaugeM(name = "jvm.max", description = "The total amount of JVM maximum available memory (b)")
private long max;
/** JVM空闲内存(b) */
@GaugeM(name = "jvm.free", description = "JVM free memory (b)")
private long free;
/** 当前程序cpu使用率 */
@GaugeM(name = "jvm.cpuUsed", baseUnit = "%", description = "Current program cpu usage")
private Double cpuUsed;
/** 非堆内存最大值 */
@GaugeM(name = "jvm.nonHeapMax", description = "Maximum non-heap memory")
private Long nonHeapMax;
/** 非堆内存使用值 */
@GaugeM(name = "jvm.nonHeapUsed", description = "Non-heap memory usage value")
private Long nonHeapUsed;
/** 堆内存最大值 */
@GaugeM(name = "jvm.heapMax", description = "Maximum heap memory")
private Long heapMax;
/** 堆内存使用值 */
@GaugeM(name = "jvm.heapUsed", description = "=heap memory usage value")
private Long heapUsed;
@GaugeM(name = "jvm.threadPeakCount", baseUnit = "units", description = "=thread peak count")
private Integer threadPeakCount;
@GaugeM(name = "jvm.threadCount", baseUnit = "units", description = "=thread count")
private Integer threadCount;
/** JDK版本 */
private String version;
/** JDK路径 */
private String home;
public static Jvm of() {
MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
MemoryUsage nonHeapMemoryUsage =
ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
JvmInfo jvmInfo = SystemUtil.getJvmInfo();
return new Jvm()
.withVersion(jvmInfo.getVersion())
.withFree(SystemUtil.getFreeMemory())
.withHome(SystemUtil.getJavaRuntimeInfo().getHomeDir())
.withTotal(SystemUtil.getTotalMemory())
.withMax(SystemUtil.getMaxMemory())
.withCpuUsed(SystemUtil.getOperatingSystemMXBean().getSystemLoadAverage() * 1000)
.withHeapMax(heapMemoryUsage.getMax())
.withHeapUsed(heapMemoryUsage.getUsed())
.withNonHeapMax(
nonHeapMemoryUsage.getMax() < 0
? nonHeapMemoryUsage.getUsed()
: nonHeapMemoryUsage.getMax())
.withNonHeapUsed(nonHeapMemoryUsage.getUsed())
.withThreadPeakCount(threadMXBean.getPeakThreadCount())
.withThreadCount(threadMXBean.getThreadCount());
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.metrics;
import org.dinky.data.annotation.GaugeM;
import cn.hutool.system.oshi.OshiUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.With;
import oshi.hardware.GlobalMemory;
@Getter
@Setter
@With
@AllArgsConstructor
@NoArgsConstructor
public class Mem extends BaseMetrics {
/** 内存总量 */
@GaugeM(name = "mem.total", description = "total memory")
private double total;
/** 已用内存 */
@GaugeM(name = "mem.used", description = "used memory")
private double used;
/** 剩余内存 */
@GaugeM(name = "mem.free", description = "remaining memory")
private double free;
public static Mem of() {
GlobalMemory memory = OshiUtil.getMemory();
long available = memory.getAvailable();
long total1 = memory.getTotal();
return new Mem().withTotal(total1).withFree(available).withUsed(total1 - available);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.metrics;
import cn.hutool.core.lang.Singleton;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MetricsTotal {
public static volatile MetricsTotal instance = Singleton.get(MetricsTotal.class);
private Jvm jvm = Jvm.of();
private Cpu cpu = Cpu.of();
private Mem mem = Mem.of();
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.vo;
import org.dinky.data.metrics.MetricsTotal;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MetricsVO {
private String content;
private MetricsTotal metricsTotal;
private String model;
private LocalDateTime heartTime;
}
...@@ -49,6 +49,7 @@ public class EnvInit implements ApplicationRunner { ...@@ -49,6 +49,7 @@ public class EnvInit implements ApplicationRunner {
+ "External: \thttp://{}:{}\n\t" + "External: \thttp://{}:{}\n\t"
+ "Doc: \thttp://{}:{}/doc.html\n" + "Doc: \thttp://{}:{}/doc.html\n"
+ "Druid Monitor: \thttp://{}:{}/druid/index.html\n" + "Druid Monitor: \thttp://{}:{}/druid/index.html\n"
+ "Actuator: \thttp://{}:{}/actuator\n"
+ "----------------------------------------------------------", + "----------------------------------------------------------",
port, port,
ipAddress, ipAddress,
...@@ -56,6 +57,8 @@ public class EnvInit implements ApplicationRunner { ...@@ -56,6 +57,8 @@ public class EnvInit implements ApplicationRunner {
ipAddress, ipAddress,
port, port,
ipAddress, ipAddress,
port,
ipAddress,
port); port);
} }
} }
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service;
import org.dinky.data.vo.MetricsVO;
import java.util.Date;
import java.util.List;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
public interface MonitorService {
List<MetricsVO> getData(Date startTime, Date endTime);
SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service.impl;
import org.dinky.configure.MetricConfig;
import org.dinky.data.vo.MetricsVO;
import org.dinky.process.exception.DinkyException;
import org.dinky.service.MonitorService;
import org.dinky.utils.PaimonUtil;
import org.apache.paimon.data.Timestamp;
import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.function.Function;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.ThreadUtil;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class MonitorServiceImpl implements MonitorService {
private final Executor scheduleRefreshMonitorDataExecutor;
@Override
public List<MetricsVO> getData(Date startTime, Date endTime) {
endTime = Opt.ofNullable(endTime).orElse(DateUtil.date());
if (endTime.compareTo(startTime) < 1) {
throw new DinkyException("The end date must be greater than the start date!");
}
Function<PredicateBuilder, List<Predicate>> filter =
p -> {
Timestamp timestamp =
Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(startTime));
Predicate greaterThan = p.greaterThan(0, timestamp);
Predicate local = p.equal(2, "local");
return CollUtil.newArrayList(local, greaterThan);
};
return PaimonUtil.batchReadTable(PaimonUtil.METRICS_IDENTIFIER, MetricsVO.class, filter);
}
@Override
public SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate) {
Queue<MetricsVO> metricsQueue = MetricConfig.getMetricsQueue();
scheduleRefreshMonitorDataExecutor.execute(
() -> {
try {
for (MetricsVO metrics : metricsQueue) {
if (metrics.getHeartTime()
.isAfter(DateUtil.toLocalDateTime(lastDate))) {
sseEmitter.send(metrics);
}
}
while (true) {
if (CollUtil.isEmpty(metricsQueue)) {
continue;
}
for (MetricsVO metrics : metricsQueue) {
sseEmitter.send(metrics);
}
ThreadUtil.sleep(MetricConfig.SCHEDULED_RATE - 200);
}
} catch (IOException e) {
sseEmitter.complete();
} catch (Exception e) {
e.printStackTrace();
sseEmitter.complete();
}
});
return sseEmitter;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.utils;
import org.dinky.data.vo.MetricsVO;
import org.dinky.function.constant.PathConstant;
import org.apache.paimon.catalog.Catalog;
import org.apache.paimon.catalog.CatalogContext;
import org.apache.paimon.catalog.CatalogFactory;
import org.apache.paimon.catalog.Identifier;
import org.apache.paimon.data.BinaryRow;
import org.apache.paimon.data.BinaryRowWriter;
import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.InternalRow;
import org.apache.paimon.data.Timestamp;
import org.apache.paimon.fs.Path;
import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder;
import org.apache.paimon.reader.RecordReader;
import org.apache.paimon.schema.Schema;
import org.apache.paimon.table.Table;
import org.apache.paimon.table.sink.BatchTableCommit;
import org.apache.paimon.table.sink.BatchTableWrite;
import org.apache.paimon.table.sink.BatchWriteBuilder;
import org.apache.paimon.table.sink.CommitMessage;
import org.apache.paimon.table.source.ReadBuilder;
import org.apache.paimon.table.source.Split;
import org.apache.paimon.table.source.TableRead;
import org.apache.paimon.types.DataTypes;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PaimonUtil {
private static final String DINKY_DB = "dinky_db";
private static final Map<Identifier, Schema> SCHEMA_MAP = new HashMap<>();
private static final CatalogContext CONTEXT =
CatalogContext.create(new Path("file://" + PathConstant.TMP_PATH + "paimon"));
private static final Catalog CATALOG = CatalogFactory.createCatalog(CONTEXT);
public static final Identifier METRICS_IDENTIFIER =
Identifier.create(DINKY_DB, "dinky_metrics");
static {
try {
CATALOG.createDatabase(DINKY_DB, true);
} catch (Catalog.DatabaseAlreadyExistException e) {
throw new RuntimeException(e);
}
Map<String, String> options = new HashMap<>();
options.put("partition.expiration-time", "7d");
options.put("partition.expiration-check-interval", "1d");
options.put("partition.timestamp-formatter", "yyyy-MM-dd");
options.put("partition.timestamp-pattern", "$date");
options.put("file.format", "parquet");
options.put("snapshot.time-retained", "10 s");
Schema.Builder schemaBuilder = Schema.newBuilder();
schemaBuilder.primaryKey("heart_time", "model", "date");
schemaBuilder.partitionKeys("model", "date");
schemaBuilder.column("heart_time", DataTypes.TIMESTAMP_MILLIS());
schemaBuilder.column("model", DataTypes.STRING());
schemaBuilder.column("content", DataTypes.STRING());
schemaBuilder.column("date", DataTypes.STRING());
schemaBuilder.options(options);
Schema schema = schemaBuilder.build();
SCHEMA_MAP.put(METRICS_IDENTIFIER, schema);
}
public static synchronized void writeMetrics(List<MetricsVO> metricsList) {
if (CollUtil.isEmpty(metricsList)) {
return;
}
Table metricsTable = createOrGetMetricsTable();
BatchWriteBuilder writeBuilder = metricsTable.newBatchWriteBuilder();
// 2. Write records in distributed tasks
try (BatchTableWrite write = writeBuilder.newWrite()) {
for (MetricsVO metrics : metricsList) {
LocalDateTime now = metrics.getHeartTime();
BinaryRow row = new BinaryRow(30);
BinaryRowWriter writer = new BinaryRowWriter(row);
writer.writeTimestamp(0, Timestamp.fromLocalDateTime(now), 3);
writer.writeString(1, BinaryString.fromString(metrics.getModel()));
writer.writeString(2, BinaryString.fromString(metrics.getContent()));
writer.writeString(
3,
BinaryString.fromString(
now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))));
write.write(row);
}
List<CommitMessage> messages = write.prepareCommit();
// 3. Collect all CommitMessages to a global node and commit
try (BatchTableCommit commit = writeBuilder.newCommit()) {
commit.commit(messages);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> batchReadTable(Identifier identifier, Class<T> clazz) {
return batchReadTable(identifier, clazz, null);
}
public static <T> List<T> batchReadTable(
Identifier identifier,
Class<T> clazz,
Function<PredicateBuilder, List<Predicate>> filter) {
TimeInterval timer = DateUtil.timer();
List<T> dataList = new ArrayList<>();
PredicateBuilder builder = new PredicateBuilder(SCHEMA_MAP.get(identifier).rowType());
ReadBuilder readBuilder;
try {
if (!CATALOG.tableExists(identifier)) {
return dataList;
}
readBuilder = CATALOG.getTable(identifier).newReadBuilder();
if (filter != null) {
List<Predicate> predicates = filter.apply(builder);
readBuilder.withFilter(predicates);
}
} catch (Catalog.TableNotExistException e) {
throw new RuntimeException(e);
}
// 2. Plan splits in 'Coordinator' (or named 'Driver')
List<Split> splits = readBuilder.newScan().plan().splits();
// 3. Distribute these splits to different tasks
// 4. Read a split in task
TableRead read = readBuilder.newRead();
try (RecordReader<InternalRow> reader = read.createReader(splits)) {
Schema schema = SCHEMA_MAP.get(METRICS_IDENTIFIER);
reader.forEachRemaining(
x -> {
T t = ReflectUtil.newInstance(clazz);
schema.fields()
.forEach(
f -> {
Object value =
InternalRow.createFieldGetter(f.type(), f.id())
.getFieldOrNull(x);
String fieldName = StrUtil.toCamelCase(f.name());
try {
ReflectUtil.setFieldValue(t, fieldName, value);
} catch (Exception ignored) {
}
});
dataList.add(t);
});
} catch (IOException e) {
throw new RuntimeException(e);
}
log.debug(
"paimon read; table: {} ,size: {} ,timer: {}ms",
identifier.getFullName(),
dataList.size(),
timer.intervalMs());
return dataList;
}
public static Table createOrGetMetricsTable() {
try {
if (CATALOG.tableExists(METRICS_IDENTIFIER)) {
return CATALOG.getTable(METRICS_IDENTIFIER);
}
CATALOG.createTable(METRICS_IDENTIFIER, SCHEMA_MAP.get(METRICS_IDENTIFIER), false);
return CATALOG.getTable(METRICS_IDENTIFIER);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
management:
endpoints:
web:
exposure:
include: "*"
enabled-by-default: true
jmx:
exposure:
include: "*"
health:
redis:
enabled: false
ldap:
enabled: false
endpoint:
health:
show-details: always
metrics:
tags:
application: ${spring.application.name}
\ No newline at end of file
...@@ -15,7 +15,7 @@ spring: ...@@ -15,7 +15,7 @@ spring:
# If you use pgsql database, please configure pgsql database connection information in application-pgsql.yml # If you use pgsql database, please configure pgsql database connection information in application-pgsql.yml
# If you use the h2 database, please configure the h2 database connection information in application-h2.yml, # If you use the h2 database, please configure the h2 database connection information in application-h2.yml,
# note: the h2 database is only for experience use, and the related data that has been created cannot be migrated, please use it with caution # note: the h2 database is only for experience use, and the related data that has been created cannot be migrated, please use it with caution
active: h2 #[h2,mysql,pgsql] active: h2,jmx #[h2,mysql,pgsql]
# mvc config # mvc config
mvc: mvc:
...@@ -164,11 +164,5 @@ knife4j: ...@@ -164,11 +164,5 @@ knife4j:
# - org.dinky.controller # - org.dinky.controller
Dinky: Dinky:
version: @project.version@ version: @project.version@
management:
health:
redis:
enabled: false
sms: sms:
is-print: false is-print: false
\ No newline at end of file
...@@ -92,6 +92,7 @@ ...@@ -92,6 +92,7 @@
<mybatis-plus-boot-starter.version>3.5.3.1</mybatis-plus-boot-starter.version> <mybatis-plus-boot-starter.version>3.5.3.1</mybatis-plus-boot-starter.version>
<mysql-connector-java.version>8.0.28</mysql-connector-java.version> <mysql-connector-java.version>8.0.28</mysql-connector-java.version>
<ojdbc8.version>12.2.0.1</ojdbc8.version> <ojdbc8.version>12.2.0.1</ojdbc8.version>
<oshi.version>6.4.2</oshi.version>
<poi.version>5.2.3</poi.version> <poi.version>5.2.3</poi.version>
<postgresql.version>42.5.1</postgresql.version> <postgresql.version>42.5.1</postgresql.version>
<powermock.version>2.0.9</powermock.version> <powermock.version>2.0.9</powermock.version>
...@@ -115,6 +116,11 @@ ...@@ -115,6 +116,11 @@
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>${oshi.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-dependencies</artifactId> <artifactId>knife4j-dependencies</artifactId>
...@@ -799,6 +805,12 @@ ...@@ -799,6 +805,12 @@
<connection>git@github.com:DataLinkDC/dinky.git</connection> <connection>git@github.com:DataLinkDC/dinky.git</connection>
<url>https://github.com/DataLinkDC/dinky</url> <url>https://github.com/DataLinkDC/dinky</url>
</scm> </scm>
<repositories>
<repository>
<id>apache-snapshots</id>
<url>https://maven.aliyun.com/repository/apache-snapshots</url>
</repository>
</repositories>
<profiles> <profiles>
<profile> <profile>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment