Unverified Commit ed895809 authored by Licho's avatar Licho Committed by GitHub

feat: change to sqlite for flink metric (#3613)

parent 9b5c592e
...@@ -36,6 +36,10 @@ ...@@ -36,6 +36,10 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.mitre.dsmiley.httpproxy</groupId> <groupId>org.mitre.dsmiley.httpproxy</groupId>
<artifactId>smiley-http-proxy-servlet</artifactId> <artifactId>smiley-http-proxy-servlet</artifactId>
......
...@@ -19,13 +19,19 @@ ...@@ -19,13 +19,19 @@
package org.dinky.context; package org.dinky.context;
import org.dinky.data.constant.PaimonTableConstant; import static org.dinky.data.constant.MonitorTableConstant.JOB_ID;
import org.dinky.data.constant.MonitorTableConstant;
import org.dinky.data.enums.SseTopic; import org.dinky.data.enums.SseTopic;
import org.dinky.data.vo.MetricsVO; import org.dinky.data.vo.MetricsVO;
import org.dinky.utils.PaimonUtil; import org.dinky.utils.PaimonUtil;
import org.dinky.utils.SqliteUtil;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
...@@ -35,6 +41,8 @@ import java.util.concurrent.ThreadPoolExecutor; ...@@ -35,6 +41,8 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
...@@ -47,6 +55,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -47,6 +55,7 @@ import lombok.extern.slf4j.Slf4j;
*/ */
@Slf4j @Slf4j
public class MetricsContextHolder { public class MetricsContextHolder {
private static final ObjectMapper objectMapper = new ObjectMapper();
@Getter @Getter
protected static final MetricsContextHolder instance = new MetricsContextHolder(); protected static final MetricsContextHolder instance = new MetricsContextHolder();
...@@ -54,6 +63,13 @@ public class MetricsContextHolder { ...@@ -54,6 +63,13 @@ public class MetricsContextHolder {
private final List<MetricsVO> metricsVOS = new CopyOnWriteArrayList<>(); private final List<MetricsVO> metricsVOS = new CopyOnWriteArrayList<>();
private final AtomicLong lastDumpTime = new AtomicLong(System.currentTimeMillis()); private final AtomicLong lastDumpTime = new AtomicLong(System.currentTimeMillis());
static {
String sql = String.format(
"%s BIGINT, %s TEXT, %s TEXT, %s INTEGER",
JOB_ID, MonitorTableConstant.VALUE, MonitorTableConstant.HEART_TIME, MonitorTableConstant.DATE);
SqliteUtil.INSTANCE.createTable(MonitorTableConstant.DINKY_METRICS, sql);
}
// Create a ThreadFactory with custom naming // Create a ThreadFactory with custom naming
ThreadFactory namedThreadFactory = ThreadFactory namedThreadFactory =
new ThreadFactoryBuilder().setNameFormat("metrics-send-thread-%d").build(); new ThreadFactoryBuilder().setNameFormat("metrics-send-thread-%d").build();
...@@ -64,7 +80,7 @@ public class MetricsContextHolder { ...@@ -64,7 +80,7 @@ public class MetricsContextHolder {
10, // Maximum pool size, allows the pool to expand as needed 10, // Maximum pool size, allows the pool to expand as needed
60L, // Keep alive time for idle threads 60L, // Keep alive time for idle threads
TimeUnit.SECONDS, // Unit of keep alive time TimeUnit.SECONDS, // Unit of keep alive time
new LinkedBlockingQueue<Runnable>(10), // Use a larger queue to hold excess tasks new LinkedBlockingQueue<>(10), // Use a larger queue to hold excess tasks
namedThreadFactory); namedThreadFactory);
public void sendAsync(String key, MetricsVO o) { public void sendAsync(String key, MetricsVO o) {
...@@ -86,10 +102,57 @@ public class MetricsContextHolder { ...@@ -86,10 +102,57 @@ public class MetricsContextHolder {
metricsVOS.clear(); metricsVOS.clear();
lastDumpTime.set(current); lastDumpTime.set(current);
} }
PaimonUtil.write(PaimonTableConstant.DINKY_METRICS, snapshot, MetricsVO.class); PaimonUtil.write(MonitorTableConstant.DINKY_METRICS, snapshot, MetricsVO.class);
} }
String topic = StrFormatter.format("{}/{}", SseTopic.METRICS.getValue(), key); String topic = StrFormatter.format("{}/{}", SseTopic.METRICS.getValue(), key);
SseSessionContextHolder.sendTopic(topic, o); // Ensure only successfully added metrics are sent SseSessionContextHolder.sendTopic(topic, o); // Ensure only successfully added metrics are sent
}); });
} }
public void saveToSqlite(String key, MetricsVO o) {
Object content = o.getContent();
if (content == null
|| (content instanceof ConcurrentHashMap && ((ConcurrentHashMap<?, ?>) content).isEmpty())) {
return;
}
metricsVOS.add(o);
long current = System.currentTimeMillis();
long duration = current - lastDumpTime.get();
if (metricsVOS.size() >= 1000 || duration >= 15000) {
lastDumpTime.set(current);
List<List<String>> values = convertMetricsVOsToStringList(metricsVOS);
try {
final List<String> columns = Arrays.asList(
JOB_ID, MonitorTableConstant.VALUE, MonitorTableConstant.HEART_TIME, MonitorTableConstant.DATE);
SqliteUtil.INSTANCE.write(MonitorTableConstant.DINKY_METRICS, columns, values);
} catch (SQLException e) {
log.error("Failed to write metrics to SQLite", e);
return;
}
metricsVOS.clear();
}
String topic = StrFormatter.format("{}/{}", SseTopic.METRICS.getValue(), key);
SseSessionContextHolder.sendTopic(topic, o);
}
public List<List<String>> convertMetricsVOsToStringList(List<MetricsVO> metricsVOS) {
List<List<String>> result = new ArrayList<>();
for (MetricsVO metricsVO : metricsVOS) {
Map<String, Object> content = (Map<String, Object>) metricsVO.getContent();
try {
List<String> row = new ArrayList<>();
row.add(metricsVO.getModel());
row.add(objectMapper.writeValueAsString(content));
row.add(metricsVO.getHeartTime().toString());
row.add(metricsVO.getDate());
result.add(row);
} catch (JsonProcessingException e) {
log.error("Failed to serialize content of MetricsVO: {}", metricsVO, e);
}
}
return result;
}
} }
...@@ -105,7 +105,7 @@ public class FlinkJobTask implements DaemonTask { ...@@ -105,7 +105,7 @@ public class FlinkJobTask implements DaemonTask {
if (Asserts.isAllNotNull(jobInfoDetail.getClusterInstance())) { if (Asserts.isAllNotNull(jobInfoDetail.getClusterInstance())) {
JobAlertHandler.getInstance().check(jobInfoDetail); JobAlertHandler.getInstance().check(jobInfoDetail);
if (SystemConfiguration.getInstances().getMetricsSysEnable().getValue()) { if (SystemConfiguration.getInstances().getMetricsSysEnable().getValue()) {
JobMetricsHandler.refeshAndWriteFlinkMetrics(jobInfoDetail, verticesAndMetricsMap); JobMetricsHandler.refreshAndWriteFlinkMetrics(jobInfoDetail, verticesAndMetricsMap);
} }
} }
return isDone; return isDone;
......
...@@ -54,7 +54,7 @@ public class JobMetricsHandler { ...@@ -54,7 +54,7 @@ public class JobMetricsHandler {
* Send to MetricsContextHolder asynchronously at the end of the method. </br> * Send to MetricsContextHolder asynchronously at the end of the method. </br>
* Thus, the operation of writing the Flink indicator is completed. </br> * Thus, the operation of writing the Flink indicator is completed. </br>
*/ */
public static void refeshAndWriteFlinkMetrics( public static void refreshAndWriteFlinkMetrics(
JobInfoDetail jobInfoDetail, Map<String, Map<String, String>> customMetricsList) { JobInfoDetail jobInfoDetail, Map<String, Map<String, String>> customMetricsList) {
String[] jobManagerUrls = String[] jobManagerUrls =
jobInfoDetail.getClusterInstance().getJobManagerHost().split(","); jobInfoDetail.getClusterInstance().getJobManagerHost().split(",");
...@@ -73,7 +73,7 @@ public class JobMetricsHandler { ...@@ -73,7 +73,7 @@ public class JobMetricsHandler {
metricsVO.setHeartTime(LocalDateTime.now()); metricsVO.setHeartTime(LocalDateTime.now());
metricsVO.setModel(jobId); metricsVO.setModel(jobId);
metricsVO.setDate(TimeUtil.nowStr("yyyy-MM-dd")); metricsVO.setDate(TimeUtil.nowStr("yyyy-MM-dd"));
MetricsContextHolder.getInstance().sendAsync(metricsVO.getModel(), metricsVO); MetricsContextHolder.getInstance().saveToSqlite(metricsVO.getModel(), metricsVO);
} catch (Exception e) { } catch (Exception e) {
log.error("Get and save Flink metrics error", e); log.error("Get and save Flink metrics error", e);
} }
......
...@@ -19,9 +19,11 @@ ...@@ -19,9 +19,11 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import static org.dinky.data.constant.MonitorTableConstant.HEART_TIME;
import org.dinky.context.SseSessionContextHolder; import org.dinky.context.SseSessionContextHolder;
import org.dinky.data.MetricsLayoutVo; import org.dinky.data.MetricsLayoutVo;
import org.dinky.data.constant.PaimonTableConstant; import org.dinky.data.constant.MonitorTableConstant;
import org.dinky.data.dto.MetricsLayoutDTO; import org.dinky.data.dto.MetricsLayoutDTO;
import org.dinky.data.exception.DinkyException; import org.dinky.data.exception.DinkyException;
import org.dinky.data.metrics.Jvm; import org.dinky.data.metrics.Jvm;
...@@ -32,13 +34,15 @@ import org.dinky.data.vo.MetricsVO; ...@@ -32,13 +34,15 @@ import org.dinky.data.vo.MetricsVO;
import org.dinky.mapper.MetricsMapper; import org.dinky.mapper.MetricsMapper;
import org.dinky.service.JobInstanceService; import org.dinky.service.JobInstanceService;
import org.dinky.service.MonitorService; import org.dinky.service.MonitorService;
import org.dinky.shaded.paimon.data.BinaryString; import org.dinky.utils.SqliteUtil;
import org.dinky.shaded.paimon.data.Timestamp;
import org.dinky.shaded.paimon.predicate.Predicate;
import org.dinky.shaded.paimon.predicate.PredicateBuilder;
import org.dinky.utils.JsonUtils;
import org.dinky.utils.PaimonUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
...@@ -48,7 +52,6 @@ import java.util.List; ...@@ -48,7 +52,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -83,30 +86,49 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -83,30 +86,49 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
throw new DinkyException("Please provide at least one monitoring ID"); throw new DinkyException("Please provide at least one monitoring ID");
} }
endTime = Opt.ofNullable(endTime).orElse(DateUtil.date()); endTime = Opt.ofNullable(endTime).orElse(DateUtil.date());
Timestamp startTS = Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(startTime));
Timestamp endTS = Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(endTime));
if (endTime.compareTo(startTime) < 1) { if (endTime.compareTo(startTime) < 1) {
throw new DinkyException("The end date must be greater than the start date!"); throw new DinkyException("The end date must be greater than the start date!");
} }
Function<PredicateBuilder, List<Predicate>> filter = p -> { String condition = getUtcCondition(startTime, endTime);
int heartTime = p.indexOf("heart_time"); List<MetricsVO> metricsVOList = new ArrayList<>();
Predicate greaterOrEqual = p.greaterOrEqual(heartTime, startTS); try (SqliteUtil.PreparedResultSet ps =
Predicate lessOrEqual = p.lessOrEqual(heartTime, endTS); SqliteUtil.INSTANCE.read(MonitorTableConstant.DINKY_METRICS, condition)) {
Predicate local = p.in( ResultSet read = ps.getRs();
p.indexOf("model"), while (read.next()) {
models.stream().map(BinaryString::fromString).collect(Collectors.toList())); MetricsVO metricsVO = new MetricsVO();
return CollUtil.newArrayList(PredicateBuilder.and(local, greaterOrEqual, lessOrEqual)); metricsVO.setModel(read.getString(MonitorTableConstant.JOB_ID));
}; metricsVO.setContent(read.getString(MonitorTableConstant.VALUE));
List<MetricsVO> metricsVOList = metricsVO.setHeartTime(convertToLocalDateTime(read.getString(HEART_TIME)));
PaimonUtil.batchReadTable(PaimonTableConstant.DINKY_METRICS, MetricsVO.class, filter); metricsVO.setDate(read.getString(MonitorTableConstant.DATE));
return metricsVOList.stream() metricsVOList.add(metricsVO);
// todo 这里再次过滤,是因为paimon查询的bug问题导致 }
.filter(x -> x.getHeartTime().isAfter(startTS.toLocalDateTime()))
.filter(x -> x.getHeartTime().isBefore(endTS.toLocalDateTime())) } catch (SQLException e) {
.peek(vo -> vo.setContent(JsonUtils.parseObject(vo.getContent().toString()))) throw new DinkyException("Failed to get data from the database");
.collect(Collectors.toList()); } catch (Exception e) {
throw new RuntimeException(e);
}
return metricsVOList;
}
public static LocalDateTime convertToLocalDateTime(String dateTimeString) {
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
return LocalDateTime.parse(dateTimeString, formatter1);
} catch (DateTimeParseException e) {
return LocalDateTime.parse(dateTimeString, formatter2);
}
}
public static String getUtcCondition(Date startTime, Date endTime) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime startLdt = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
LocalDateTime endLdt = LocalDateTime.ofInstant(endTime.toInstant(), ZoneId.systemDefault());
return MessageFormat.format(
"''{0}'' <= {2} AND {2} <= ''{1}''", startLdt.format(formatter), endLdt.format(formatter), HEART_TIME);
} }
@Override @Override
...@@ -232,7 +254,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -232,7 +254,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
for (Tuple tuple : tupleList) { for (Tuple tuple : tupleList) {
String metricsName = tuple.get(0); String metricsName = tuple.get(0);
String d = jsonObject.get(metricsName).asText(); String d = jsonObject.get(metricsName).asText();
Dict dict = Dict.create().set("time", x.getHeartTime()).set("value", d); Dict dict = Dict.create().set("time", x.getHeartTime()).set(MonitorTableConstant.VALUE, d);
Integer id = tuple.get(1); Integer id = tuple.get(1);
resultData.computeIfAbsent(id, k -> new ArrayList<>()).add(dict); resultData.computeIfAbsent(id, k -> new ArrayList<>()).add(dict);
} }
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
package org.dinky.utils; package org.dinky.utils;
import static org.dinky.data.constant.PaimonTableConstant.DINKY_DB; import static org.dinky.data.constant.MonitorTableConstant.DINKY_DB;
import org.dinky.data.annotations.paimon.Option; import org.dinky.data.annotations.paimon.Option;
import org.dinky.data.annotations.paimon.Options; import org.dinky.data.annotations.paimon.Options;
...@@ -81,7 +81,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -81,7 +81,7 @@ import lombok.extern.slf4j.Slf4j;
@Data @Data
public class PaimonUtil { public class PaimonUtil {
private static PaimonUtil instance; private static PaimonUtil instance = new PaimonUtil();
private final Cache<Class<?>, Schema> schemaCache; private final Cache<Class<?>, Schema> schemaCache;
private final CatalogContext context; private final CatalogContext context;
...@@ -98,24 +98,6 @@ public class PaimonUtil { ...@@ -98,24 +98,6 @@ public class PaimonUtil {
} }
} }
public static synchronized PaimonUtil getInstance() {
if (instance == null) {
instance = new PaimonUtil();
}
return instance;
}
public static void dropTable(String table) {
Identifier identifier = Identifier.create(DINKY_DB, table);
if (getInstance().getCatalog().tableExists(identifier)) {
try {
getInstance().getCatalog().dropTable(identifier, true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static <T> void write(String table, List<T> dataList, Class<?> clazz) { public static <T> void write(String table, List<T> dataList, Class<?> clazz) {
if (CollUtil.isEmpty(dataList)) { if (CollUtil.isEmpty(dataList)) {
return; return;
...@@ -171,10 +153,6 @@ public class PaimonUtil { ...@@ -171,10 +153,6 @@ public class PaimonUtil {
} }
} }
public static <T> List<T> batchReadTable(String table, Class<T> clazz) {
return batchReadTable(table, clazz, null);
}
public static <T> List<T> batchReadTable( public static <T> List<T> batchReadTable(
String table, Class<T> clazz, Function<PredicateBuilder, List<Predicate>> filter) { String table, Class<T> clazz, Function<PredicateBuilder, List<Predicate>> filter) {
Identifier identifier = getIdentifier(table); Identifier identifier = getIdentifier(table);
...@@ -185,10 +163,10 @@ public class PaimonUtil { ...@@ -185,10 +163,10 @@ public class PaimonUtil {
ReadBuilder readBuilder; ReadBuilder readBuilder;
try { try {
if (!getInstance().getCatalog().tableExists(identifier)) { if (!instance.getCatalog().tableExists(identifier)) {
return dataList; return dataList;
} }
readBuilder = getInstance().getCatalog().getTable(identifier).newReadBuilder(); readBuilder = instance.getCatalog().getTable(identifier).newReadBuilder();
if (filter != null) { if (filter != null) {
List<Predicate> predicates = filter.apply(builder); List<Predicate> predicates = filter.apply(builder);
readBuilder.withFilter(predicates); readBuilder.withFilter(predicates);
...@@ -234,18 +212,18 @@ public class PaimonUtil { ...@@ -234,18 +212,18 @@ public class PaimonUtil {
public static Table createOrGetTable(String tableName, Class<?> clazz) { public static Table createOrGetTable(String tableName, Class<?> clazz) {
try { try {
Identifier identifier = Identifier.create(DINKY_DB, tableName); Identifier identifier = Identifier.create(DINKY_DB, tableName);
if (getInstance().getCatalog().tableExists(identifier)) { if (instance.getCatalog().tableExists(identifier)) {
return getInstance().getCatalog().getTable(identifier); return instance.getCatalog().getTable(identifier);
} }
getInstance().getCatalog().createTable(identifier, getSchemaByClass(clazz), false); instance.getCatalog().createTable(identifier, getSchemaByClass(clazz), false);
return getInstance().getCatalog().getTable(identifier); return instance.getCatalog().getTable(identifier);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static Schema getSchemaByClass(Class<?> clazz) { public static Schema getSchemaByClass(Class<?> clazz) {
return getInstance().getSchemaCache().get(clazz, () -> { return instance.getSchemaCache().get(clazz, () -> {
List<String> primaryKeys = new ArrayList<>(); List<String> primaryKeys = new ArrayList<>();
List<String> partitionKeys = new ArrayList<>(); List<String> partitionKeys = new ArrayList<>();
Schema.Builder builder = Schema.newBuilder(); Schema.Builder builder = Schema.newBuilder();
......
/*
*
* 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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public enum SqliteUtil {
INSTANCE;
private Connection connection;
static {
try {
SqliteUtil.INSTANCE.connect("dinky.db");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void connect(String dbPath) throws SQLException {
connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
}
public void createTable(String tableName, String columns) {
String sql = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + columns + ");";
try (Statement stmt = connection.createStatement()) {
stmt.execute(sql);
} catch (SQLException e) {
log.error("Failed to create table: " + e.getMessage());
}
}
public void write(String tableName, String columns, String values) throws SQLException {
String sql = String.format("INSERT INTO %s (%s) VALUES (%s);", tableName, columns, values);
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
pstmt.executeUpdate();
}
}
public void write(String tableName, List<String> columns, List<List<String>> values) throws SQLException {
String sql = createInsertSql(tableName, columns);
try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
connection.setAutoCommit(false);
for (List<String> value : values) {
for (int i = 0; i < value.size(); i++) {
pstmt.setString(i + 1, value.get(i));
}
pstmt.addBatch();
}
pstmt.executeBatch();
connection.commit();
} catch (SQLException e) {
log.error("Failed to write to SQLite: " + e.getMessage());
}
}
private static @NotNull String createInsertSql(String tableName, List<String> columns) {
StringBuilder columnNames = new StringBuilder();
StringBuilder placeholders = new StringBuilder();
for (int i = 0; i < columns.size(); i++) {
columnNames.append(columns.get(i));
placeholders.append("?");
if (i < columns.size() - 1) {
columnNames.append(", ");
placeholders.append(", ");
}
}
return String.format("INSERT INTO %s (%s) VALUES (%s);", tableName, columnNames, placeholders);
}
public PreparedResultSet read(String tableName, String condition) throws SQLException {
String sql = String.format("SELECT * FROM %s where %s;", tableName, condition);
PreparedStatement pstmt = connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
return new PreparedResultSet(pstmt, rs);
}
public void close() throws SQLException {
if (connection != null) {
connection.close();
}
}
public static class PreparedResultSet implements AutoCloseable {
private final PreparedStatement pstmt;
private final ResultSet rs;
public PreparedResultSet(PreparedStatement pstmt, ResultSet rs) {
this.pstmt = pstmt;
this.rs = rs;
}
public PreparedStatement getPstmt() {
return pstmt;
}
public ResultSet getRs() {
return rs;
}
@Override
public void close() throws Exception {
pstmt.close();
}
}
}
...@@ -19,8 +19,11 @@ ...@@ -19,8 +19,11 @@
package org.dinky.data.constant; package org.dinky.data.constant;
public final class PaimonTableConstant { public final class MonitorTableConstant {
public static final String DINKY_DB = "dinky_db"; public static final String DINKY_DB = "dinky_db";
public static final String DINKY_CACHE = "dinky_cache";
public static final String DINKY_METRICS = "dinky_metrics"; public static final String DINKY_METRICS = "dinky_metrics";
public static final String HEART_TIME = "heart_time";
public static final String JOB_ID = "job_id";
public static final String VALUE = "value";
public static final String DATE = "date";
} }
...@@ -121,12 +121,18 @@ ...@@ -121,12 +121,18 @@
<spotless.version>2.27.1</spotless.version> <spotless.version>2.27.1</spotless.version>
<spring-boot-dependencies.version>2.7.18</spring-boot-dependencies.version> <spring-boot-dependencies.version>2.7.18</spring-boot-dependencies.version>
<spring.ldap.version>3.1.0</spring.ldap.version> <spring.ldap.version>3.1.0</spring.ldap.version>
<sqlite-jdbc.version>3.46.0.0</sqlite-jdbc.version>
<target.java.version>8</target.java.version> <target.java.version>8</target.java.version>
<testcontainers.version>1.16.2</testcontainers.version> <testcontainers.version>1.16.2</testcontainers.version>
</properties> </properties>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite-jdbc.version}</version>
</dependency>
<dependency> <dependency>
<groupId>io.fabric8</groupId> <groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId> <artifactId>kubernetes-client</artifactId>
......
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