Unverified Commit ac56063c authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Optimize][sysconfig]Optimze sys settings (#2106)

* optimize_sys_settings & add metrics settings * optimize_sys_settings & add metrics settings
parent 2fc67eb1
...@@ -19,62 +19,21 @@ ...@@ -19,62 +19,21 @@
package org.dinky.configure; package org.dinky.configure;
import org.dinky.context.TenantContextHolder; import org.dinky.data.model.SystemConfiguration;
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.model.History;
import org.dinky.data.model.JobInstance;
import org.dinky.data.model.Metrics;
import org.dinky.data.vo.MetricsVO; import org.dinky.data.vo.MetricsVO;
import org.dinky.service.HistoryService;
import org.dinky.service.JobInstanceService;
import org.dinky.service.MonitorService;
import org.dinky.utils.HttpUtils;
import org.dinky.utils.PaimonUtil; import org.dinky.utils.PaimonUtil;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue; import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.AsyncUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
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.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Configuration @Configuration
...@@ -83,208 +42,22 @@ import lombok.extern.slf4j.Slf4j; ...@@ -83,208 +42,22 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class MetricConfig { public class MetricConfig {
private final MeterRegistry registry; private static final Queue<MetricsVO> METRICS_QUEUE = new ConcurrentLinkedQueue<>();
private final HistoryService historyService;
private final JobInstanceService jobInstanceService;
private final MonitorService monitorService;
private final Executor scheduleRefreshMonitorDataExecutor;
private static final Queue<MetricsVO> metricsQueue = new ConcurrentLinkedQueue<>();
/** task可用的url */
private static final Map<Integer, FlinkMetrics> TASK_FLINK_METRICS_MAP =
new ConcurrentHashMap<>();
private static final Map<LocalDateTime, List<FlinkMetrics>> FLINK_METRICS_DATA_MAP = public int flinkMetricsRequestTimeout =
new ConcurrentHashMap<>(); SystemConfiguration.getInstances().getFlinkMetricsGatherTimeout().getDefaultValue();
public static final int SCHEDULED_RATE = 1000;
public static final int REQUEST_FLINK_TIMEOUT = 100;
/** Update status per second */ /** Update status per second */
@Scheduled(fixedRate = SCHEDULED_RATE)
public void scheduled() {
updateState();
LocalDateTime now = LocalDateTime.now();
TimeInterval timer = DateUtil.timer();
FLINK_METRICS_DATA_MAP.put(now, new CopyOnWriteArrayList<>());
CompletableFuture<?>[] array =
TASK_FLINK_METRICS_MAP.values().stream()
.map((f) -> CompletableFuture.runAsync(() -> addFlinkMetrics(f, now)))
.toArray(CompletableFuture[]::new);
AsyncUtil.waitAll(array);
MetricsVO metricsVO = new MetricsVO();
metricsVO.setModel("flink");
metricsVO.setHeartTime(now);
metricsVO.setContent(JSONUtil.toJsonStr(FLINK_METRICS_DATA_MAP.get(now)));
metricsQueue.add(metricsVO);
FLINK_METRICS_DATA_MAP.remove(now);
}
/** Entering the lake every 10 states */ /** Entering the lake every 10 states */
@Scheduled(fixedRate = 10000) @Scheduled(fixedRate = 10000)
@PreDestroy @PreDestroy
public void writeScheduled() { public void writeScheduled() {
PaimonUtil.writeMetrics(new ArrayList<>(metricsQueue)); PaimonUtil.writeMetrics(new ArrayList<>(METRICS_QUEUE));
metricsQueue.clear(); METRICS_QUEUE.clear();
}
@PostConstruct
public void init() {
MetricsTotal metricsTotal = MetricsTotal.instance;
registerMetrics(metricsTotal.getJvm());
registerMetrics(metricsTotal.getCpu());
registerMetrics(metricsTotal.getMem());
getAndCheckFlinkUrlAvailable();
}
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 void getAndCheckFlinkUrlAvailable() {
TenantContextHolder.set(1);
List<JobInstance> jobInstances = jobInstanceService.listJobInstanceActive();
if (CollUtil.isEmpty(jobInstances)) {
return;
}
List<History> historyList =
historyService.listByIds(
jobInstances.stream()
.map(JobInstance::getHistoryId)
.collect(Collectors.toList()));
List<Metrics> metricsList = monitorService.list();
Set<Integer> taskIdSet =
metricsList.stream().map(Metrics::getTaskId).collect(Collectors.toSet());
for (JobInstance jobInstance : jobInstances) {
Integer taskId = jobInstance.getTaskId();
if (!taskIdSet.contains(taskId)) {
continue;
}
FlinkMetrics flinkMetrics = new FlinkMetrics();
flinkMetrics.setTaskId(taskId);
flinkMetrics.setJobId(jobInstance.getJid());
TASK_FLINK_METRICS_MAP.put(taskId, flinkMetrics);
metricsList.stream()
.filter(x -> x.getTaskId().equals(taskId))
.forEach(
m -> {
Map<String, Map<String, String>> verticesAndMetricsMap =
flinkMetrics.getVerticesAndMetricsMap();
verticesAndMetricsMap.putIfAbsent(
m.getVertices(), new ConcurrentHashMap<>());
verticesAndMetricsMap.get(m.getVertices()).put(m.getMetrics(), "");
});
for (History jobHistory : historyList) {
if (jobInstance.getHistoryId().equals(jobHistory.getId())) {
String hosts = jobHistory.getJobManagerAddress();
List<String> hostList = StrUtil.split(hosts, ",");
for (String host : hostList) {
HttpUtil.createGet(host + "/config")
.timeout(REQUEST_FLINK_TIMEOUT)
.then(
resp -> {
TASK_FLINK_METRICS_MAP.get(taskId).getUrls().add(host);
});
}
break;
}
}
}
}
public void addFlinkMetrics(FlinkMetrics flinkMetrics, LocalDateTime now) {
Integer taskId = flinkMetrics.getTaskId();
List<String> urlList = flinkMetrics.getUrls();
if (CollUtil.isEmpty(urlList)) {
// todo url都挂掉,需要做异常通知处理,和计数淘汰此flink metrics
log.error("");
return;
}
// http://10.8.16.125:8282/jobs/06ccde3ff6e53bafe729e0e50fca72fd/vertices/cbc357ccb763df2852fee8c4fc7d55f2/metrics?get=0.buffers.inputExclusiveBuffersUsage
flinkMetrics
.getVerticesAndMetricsMap()
.forEach(
(v, m) -> {
for (String metrics : m.keySet()) {
if (CollUtil.isEmpty(urlList)) {
return;
}
HttpUtils.asyncRequest(
flinkMetrics.getUrls(),
"/jobs/"
+ flinkMetrics.getJobId()
+ "/vertices/"
+ v
+ "/metrics?get="
+ metrics,
REQUEST_FLINK_TIMEOUT,
x -> {
JSONArray array = JSONUtil.parseArray(x.body());
String value = array.getJSONObject(0).getStr("value");
m.put(metrics, value);
});
}
});
FLINK_METRICS_DATA_MAP.get(now).add(flinkMetrics);
} }
public static Queue<MetricsVO> getMetricsQueue() { public static Queue<MetricsVO> getMetricsQueue() {
return metricsQueue; return METRICS_QUEUE;
}
@Setter
@Getter
static class FlinkMetrics {
private String jobId;
private Integer taskId;
private List<String> urls = new CopyOnWriteArrayList<>();
/** jobId -> metricsId -> metricsValue */
private Map<String, Map<String, String>> verticesAndMetricsMap = new HashMap<>();
} }
} }
/*
*
* 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.schedule;
import java.util.HashMap;
import java.util.concurrent.ScheduledFuture;
import javax.annotation.Resource;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
public abstract class BaseSchedule {
private static final HashMap<String, ScheduledFuture<?>> SCHEDULE_MAP = new HashMap<>();
@Resource private ThreadPoolTaskScheduler threadPoolTaskScheduler;
protected void addSchedule(String key, Runnable runnable, Trigger trigger) {
ScheduledFuture<?> schedule = threadPoolTaskScheduler.schedule(runnable, trigger);
getScheduleMap().put(key, schedule);
}
protected void removeSchedule(String key) {
ScheduledFuture<?> scheduledFuture = getScheduleMap().get(key);
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
}
public static HashMap<String, ScheduledFuture<?>> getScheduleMap() {
return SCHEDULE_MAP;
}
}
/*
*
* 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.schedule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class ScheduledConfig {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
threadPoolTaskScheduler.setThreadNamePrefix("scheduler-");
threadPoolTaskScheduler.setRemoveOnCancelPolicy(true);
return threadPoolTaskScheduler;
}
}
/*
*
* 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.schedule.metrics;
import org.dinky.configure.MetricConfig;
import org.dinky.configure.schedule.BaseSchedule;
import org.dinky.context.TenantContextHolder;
import org.dinky.data.model.Configuration;
import org.dinky.data.model.History;
import org.dinky.data.model.JobInstance;
import org.dinky.data.model.Metrics;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.vo.MetricsVO;
import org.dinky.service.HistoryService;
import org.dinky.service.JobInstanceService;
import org.dinky.service.MonitorService;
import org.dinky.utils.HttpUtils;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.AsyncUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Component
@RequiredArgsConstructor
@Slf4j
public class FlinkMetricsIndicator extends BaseSchedule {
private final HistoryService historyService;
private final JobInstanceService jobInstanceService;
private final MonitorService monitorService;
public AtomicReference<Integer> flinkMetricsRequestTimeout =
new AtomicReference<>(
SystemConfiguration.getInstances()
.getFlinkMetricsGatherTimeout()
.getDefaultValue());
/** task可用的url */
private static final Map<Integer, FlinkMetrics> TASK_FLINK_METRICS_MAP =
new ConcurrentHashMap<>();
private static final Map<LocalDateTime, List<FlinkMetrics>> FLINK_METRICS_DATA_MAP =
new ConcurrentHashMap<>();
public void writeFlinkMetrics() {
LocalDateTime now = LocalDateTime.now();
FLINK_METRICS_DATA_MAP.put(now, new CopyOnWriteArrayList<>());
CompletableFuture<?>[] array =
TASK_FLINK_METRICS_MAP.values().stream()
.map((f) -> CompletableFuture.runAsync(() -> addFlinkMetrics(f, now)))
.toArray(CompletableFuture[]::new);
AsyncUtil.waitAll(array);
MetricsVO metricsVO = new MetricsVO();
metricsVO.setModel("flink");
metricsVO.setHeartTime(now);
metricsVO.setContent(JSONUtil.toJsonStr(FLINK_METRICS_DATA_MAP.get(now)));
MetricConfig.getMetricsQueue().add(metricsVO);
FLINK_METRICS_DATA_MAP.remove(now);
}
@PostConstruct
public void init() {
getAndCheckFlinkUrlAvailable();
Configuration<Integer> flinkMetricsGatherTimeout =
SystemConfiguration.getInstances().getFlinkMetricsGatherTimeout();
flinkMetricsGatherTimeout.addChangeEvent(flinkMetricsRequestTimeout::set);
Configuration<Integer> flinkMetricsGatherTiming =
SystemConfiguration.getInstances().getFlinkMetricsGatherTiming();
final String key = flinkMetricsGatherTiming.getKey();
flinkMetricsGatherTiming.addChangeEvent(
time -> {
removeSchedule(key);
addSchedule(key, this::writeFlinkMetrics, new PeriodicTrigger(time));
});
}
public void getAndCheckFlinkUrlAvailable() {
TenantContextHolder.set(1);
List<JobInstance> jobInstances = jobInstanceService.listJobInstanceActive();
if (CollUtil.isEmpty(jobInstances)) {
return;
}
List<History> historyList =
historyService.listByIds(
jobInstances.stream()
.map(JobInstance::getHistoryId)
.collect(Collectors.toList()));
List<Metrics> metricsList = monitorService.list();
Set<Integer> taskIdSet =
metricsList.stream().map(Metrics::getTaskId).collect(Collectors.toSet());
for (JobInstance jobInstance : jobInstances) {
Integer taskId = jobInstance.getTaskId();
if (!taskIdSet.contains(taskId)) {
continue;
}
FlinkMetrics flinkMetrics = new FlinkMetrics();
flinkMetrics.setTaskId(taskId);
flinkMetrics.setJobId(jobInstance.getJid());
TASK_FLINK_METRICS_MAP.put(taskId, flinkMetrics);
metricsList.stream()
.filter(x -> x.getTaskId().equals(taskId))
.forEach(
m -> {
Map<String, Map<String, String>> verticesAndMetricsMap =
flinkMetrics.getVerticesAndMetricsMap();
verticesAndMetricsMap.putIfAbsent(
m.getVertices(), new ConcurrentHashMap<>());
verticesAndMetricsMap.get(m.getVertices()).put(m.getMetrics(), "");
});
for (History jobHistory : historyList) {
if (jobInstance.getHistoryId().equals(jobHistory.getId())) {
String hosts = jobHistory.getJobManagerAddress();
List<String> hostList = StrUtil.split(hosts, ",");
for (String host : hostList) {
try {
HttpUtil.createGet(host + "/config")
.timeout(flinkMetricsRequestTimeout.get())
.then(
resp ->
TASK_FLINK_METRICS_MAP
.get(taskId)
.getUrls()
.add(host));
} catch (Exception e) {
log.warn("host read Timeout:{}", host);
}
}
break;
}
}
}
}
public void addFlinkMetrics(FlinkMetrics flinkMetrics, LocalDateTime now) {
List<String> urlList = flinkMetrics.getUrls();
if (CollUtil.isEmpty(urlList)) {
// todo url都挂掉,需要做异常通知处理,和计数淘汰此flink metrics
log.error("");
return;
}
// http://10.8.16.125:8282/jobs/06ccde3ff6e53bafe729e0e50fca72fd/vertices/cbc357ccb763df2852fee8c4fc7d55f2/metrics?get=0.buffers.inputExclusiveBuffersUsage
flinkMetrics
.getVerticesAndMetricsMap()
.forEach(
(v, m) -> {
for (String metrics : m.keySet()) {
if (CollUtil.isEmpty(urlList)) {
return;
}
HttpUtils.asyncRequest(
flinkMetrics.getUrls(),
"/jobs/"
+ flinkMetrics.getJobId()
+ "/vertices/"
+ v
+ "/metrics?get="
+ metrics,
flinkMetricsRequestTimeout.get(),
x -> {
JSONArray array = JSONUtil.parseArray(x.body());
String value = array.getJSONObject(0).getStr("value");
m.put(metrics, value);
});
}
});
FLINK_METRICS_DATA_MAP.get(now).add(flinkMetrics);
}
@Setter
@Getter
static class FlinkMetrics {
private String jobId;
private Integer taskId;
private List<String> urls = new CopyOnWriteArrayList<>();
/** jobId -> metricsId -> metricsValue */
private Map<String, Map<String, String>> verticesAndMetricsMap = new HashMap<>();
}
}
/*
*
* 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.schedule.metrics;
import org.dinky.configure.MetricConfig;
import org.dinky.configure.schedule.BaseSchedule;
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.model.SystemConfiguration;
import org.dinky.data.vo.MetricsVO;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
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.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Component
@RequiredArgsConstructor
@Slf4j
public class GatherSysIndicator extends BaseSchedule {
private final MeterRegistry registry;
@PostConstruct
public void init() {
MetricsTotal metricsTotal = MetricsTotal.instance;
registerMetrics(metricsTotal.getJvm());
registerMetrics(metricsTotal.getCpu());
registerMetrics(metricsTotal.getMem());
org.dinky.data.model.Configuration<Boolean> metricsSysEnable =
SystemConfiguration.getInstances().getMetricsSysEnable();
String key = metricsSysEnable.getKey();
metricsSysEnable.addChangeEvent(
x -> {
if (x) {
addSchedule(
key,
this::updateState,
new PeriodicTrigger(
SystemConfiguration.getInstances()
.getMetricsSysGatherTiming()
.getValue()));
} else {
removeSchedule(key);
log.info("Information collection for jvm is turned off(已关闭对jvm的信息收集)");
}
});
}
public void updateState() {
log.debug("Collecting jvm related information.");
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");
MetricConfig.getMetricsQueue().add(metrics);
log.debug("Collecting jvm information ends.");
}
private 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));
}
}
}
...@@ -54,6 +54,7 @@ import org.springframework.stereotype.Component; ...@@ -54,6 +54,7 @@ import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.extension.activerecord.Model;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
...@@ -104,16 +105,21 @@ public class SystemInit implements ApplicationRunner { ...@@ -104,16 +105,21 @@ public class SystemInit implements ApplicationRunner {
/** init DolphinScheduler */ /** init DolphinScheduler */
private void initDolphinScheduler() { private void initDolphinScheduler() {
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances(); SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
systemConfiguration.setInitMethod( systemConfiguration
c -> { .getAllConfiguration()
if (c == systemConfiguration.getDolphinschedulerEnable()) { .get("dolphinscheduler")
if (systemConfiguration.getDolphinschedulerEnable().getValue()) { .forEach(
if (StrUtil.hasBlank( c ->
systemConfiguration.getDolphinschedulerUrl().getValue(), c.addParameterCheck(
systemConfiguration.getDolphinschedulerProjectName().getValue(), v -> {
systemConfiguration.getDolphinschedulerToken().getValue())) { if (systemConfiguration
.getDolphinschedulerEnable()
.getValue()) {
if (StrUtil.isEmpty(Convert.toStr(v))) {
sysConfigService.updateSysConfigByKv( sysConfigService.updateSysConfigByKv(
systemConfiguration.getDolphinschedulerEnable().getKey(), systemConfiguration
.getDolphinschedulerEnable()
.getKey(),
"false"); "false");
throw new DinkyException( throw new DinkyException(
"Before starting DolphinScheduler docking, please fill in the relevant configuration"); "Before starting DolphinScheduler docking, please fill in the relevant configuration");
...@@ -121,15 +127,15 @@ public class SystemInit implements ApplicationRunner { ...@@ -121,15 +127,15 @@ public class SystemInit implements ApplicationRunner {
try { try {
project = projectClient.getDinkyProject(); project = projectClient.getDinkyProject();
if (Asserts.isNull(project)) { if (Asserts.isNull(project)) {
project = projectClient.createDinkyProject(); project =
projectClient.createDinkyProject();
} }
} catch (Exception e) { } catch (Exception e) {
log.error("Error in DolphinScheduler: ", e); log.error("Error in DolphinScheduler: ", e);
throw new DinkyException(e); throw new DinkyException(e);
} }
} }
} }));
});
} }
/** /**
......
...@@ -104,7 +104,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> ...@@ -104,7 +104,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics>
maxDate = metrics.getHeartTime(); maxDate = metrics.getHeartTime();
} }
} }
ThreadUtil.sleep(MetricConfig.SCHEDULED_RATE - 200); ThreadUtil.sleep(800);
} }
} catch (IOException e) { } catch (IOException e) {
sseEmitter.complete(); sseEmitter.complete();
......
...@@ -24,7 +24,6 @@ import org.dinky.data.model.SysConfig; ...@@ -24,7 +24,6 @@ import org.dinky.data.model.SysConfig;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.mapper.SysConfigMapper; import org.dinky.mapper.SysConfigMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl; import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.process.exception.DinkyException;
import org.dinky.service.SysConfigService; import org.dinky.service.SysConfigService;
import java.util.HashMap; import java.util.HashMap;
...@@ -39,8 +38,6 @@ import com.baomidou.mybatisplus.extension.activerecord.Model; ...@@ -39,8 +38,6 @@ import com.baomidou.mybatisplus.extension.activerecord.Model;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
/** /**
* SysConfigServiceImpl * SysConfigServiceImpl
...@@ -79,7 +76,7 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC ...@@ -79,7 +76,7 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC
.forEach(Model::insertOrUpdate); .forEach(Model::insertOrUpdate);
Map<String, String> configMap = Map<String, String> configMap =
CollUtil.toMap(list(), new HashMap<>(), SysConfig::getName, SysConfig::getValue); CollUtil.toMap(list(), new HashMap<>(), SysConfig::getName, SysConfig::getValue);
systemConfiguration.setConfiguration(configMap); systemConfiguration.initSetConfiguration(configMap);
} }
@Override @Override
...@@ -88,17 +85,7 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC ...@@ -88,17 +85,7 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC
config.setValue(value); config.setValue(value);
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances(); SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
if (key.equals(systemConfiguration.getDolphinschedulerEnable().getKey()) systemConfiguration.setConfiguration(key, value);
&& Convert.toBool(value)) {
if (StrUtil.hasBlank(
systemConfiguration.getDolphinschedulerUrl().getValue(),
systemConfiguration.getDolphinschedulerProjectName().getValue(),
systemConfiguration.getDolphinschedulerToken().getValue())) {
throw new DinkyException(
"Before starting DolphinScheduler docking, please fill in the relevant configuration");
}
}
systemConfiguration.setConfiguration(MapUtil.of(key, value));
config.updateById(); config.updateById();
} }
} }
...@@ -21,7 +21,9 @@ package org.dinky.data.model; ...@@ -21,7 +21,9 @@ package org.dinky.data.model;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
...@@ -42,6 +44,10 @@ public class Configuration<T> implements Serializable { ...@@ -42,6 +44,10 @@ public class Configuration<T> implements Serializable {
private String note; private String note;
private final T defaultValue; private final T defaultValue;
@JsonIgnore private final transient List<Consumer<T>> changeEventConsumer = new LinkedList<>();
@JsonIgnore
private final transient List<Consumer<T>> parameterCheckConsumer = new LinkedList<>();
private T value; private T value;
private static final List<Class<?>> NUMBER_LIST = private static final List<Class<?>> NUMBER_LIST =
...@@ -137,4 +143,32 @@ public class Configuration<T> implements Serializable { ...@@ -137,4 +143,32 @@ public class Configuration<T> implements Serializable {
return tConfiguration; return tConfiguration;
} }
} }
public void addChangeEvent(Consumer<T> consumer) {
getChangeEventConsumer().add(consumer);
}
public void addParameterCheck(Consumer<T> consumer) {
getParameterCheckConsumer().add(consumer);
}
public void runParameterCheck() {
getParameterCheckConsumer()
.forEach(
x -> {
x.accept(getValue());
});
}
public void runChangeEvent() {
getChangeEventConsumer()
.forEach(
x -> {
try {
x.accept(getValue());
} catch (Exception e) {
e.printStackTrace();
}
});
}
} }
...@@ -27,6 +27,7 @@ import java.util.TreeMap; ...@@ -27,6 +27,7 @@ import java.util.TreeMap;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.DesensitizedUtil; import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
...@@ -47,7 +48,7 @@ public class SystemConfiguration { ...@@ -47,7 +48,7 @@ public class SystemConfiguration {
return systemConfiguration; return systemConfiguration;
} }
private Consumer<Configuration<?>> initMethod = null; private final Consumer<Configuration<?>> initMethod = null;
public static Configuration.OptionBuilder key(String key) { public static Configuration.OptionBuilder key(String key) {
return new Configuration.OptionBuilder(key); return new Configuration.OptionBuilder(key);
...@@ -60,76 +61,76 @@ public class SystemConfiguration { ...@@ -60,76 +61,76 @@ public class SystemConfiguration {
f -> f.getType() == Configuration.class)) f -> f.getType() == Configuration.class))
.map(f -> (Configuration<?>) ReflectUtil.getFieldValue(systemConfiguration, f)) .map(f -> (Configuration<?>) ReflectUtil.getFieldValue(systemConfiguration, f))
.collect(Collectors.toList()); .collect(Collectors.toList());
private Configuration<Boolean> useRestAPI = private final Configuration<Boolean> useRestAPI =
key("flink.settings.useRestAPI") key("flink.settings.useRestAPI")
.booleanType() .booleanType()
.defaultValue(true) .defaultValue(true)
.note("在运维 Flink 任务时是否使用 RestAPI"); .note("在运维 Flink 任务时是否使用 RestAPI");
private Configuration<String> sqlSeparator = private final Configuration<String> sqlSeparator =
key("flink.settings.sqlSeparator") key("flink.settings.sqlSeparator")
.stringType() .stringType()
.defaultValue(";\\n") .defaultValue(";\\n")
.note("FlinkSQL语句分割符"); .note("FlinkSQL语句分割符");
private Configuration<Integer> jobIdWait = private final Configuration<Integer> jobIdWait =
key("flink.settings.jobIdWait") key("flink.settings.jobIdWait")
.intType() .intType()
.defaultValue(30) .defaultValue(30)
.note("提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)"); .note("提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)");
private Configuration<String> mavenSettings = private final Configuration<String> mavenSettings =
key("maven.settings.settingsFilePath") key("maven.settings.settingsFilePath")
.stringType() .stringType()
.defaultValue("") .defaultValue("")
.note("Maven Settings 文件路径"); .note("Maven Settings 文件路径");
private Configuration<String> mavenRepository = private final Configuration<String> mavenRepository =
key("maven.settings.repository") key("maven.settings.repository")
.stringType() .stringType()
.defaultValue("https://maven.aliyun.com/nexus/content/repositories/central") .defaultValue("https://maven.aliyun.com/nexus/content/repositories/central")
.note("Maven private server address"); .note("Maven private server address");
private Configuration<String> mavenRepositoryUser = private final Configuration<String> mavenRepositoryUser =
key("maven.settings.repositoryUser") key("maven.settings.repositoryUser")
.stringType() .stringType()
.defaultValue("") .defaultValue("")
.note("Maven private server authentication username"); .note("Maven private server authentication username");
private Configuration<String> mavenRepositoryPassword = private final Configuration<String> mavenRepositoryPassword =
key("maven.settings.repositoryPassword") key("maven.settings.repositoryPassword")
.stringType() .stringType()
.defaultValue("") .defaultValue("")
.desensitizedHandler(DesensitizedUtil::password) .desensitizedHandler(DesensitizedUtil::password)
.note("Maven Central Repository Auth Password"); .note("Maven Central Repository Auth Password");
private Configuration<String> pythonHome = private final Configuration<String> pythonHome =
key("env.settings.pythonHome").stringType().defaultValue("python3").note("PYTHON HOME"); key("env.settings.pythonHome").stringType().defaultValue("python3").note("PYTHON HOME");
private Configuration<String> dinkyAddr = private final Configuration<String> dinkyAddr =
key("env.settings.dinkyAddr") key("env.settings.dinkyAddr")
.stringType() .stringType()
.defaultValue(System.getProperty("dinkyAddr")) .defaultValue(System.getProperty("dinkyAddr"))
.note( .note(
"the address must be the same as the address configured in the Dinky Application background url"); "the address must be the same as the address configured in the Dinky Application background url");
private Configuration<Boolean> dolphinschedulerEnable = private final Configuration<Boolean> dolphinschedulerEnable =
key("dolphinscheduler.settings.enable") key("dolphinscheduler.settings.enable")
.booleanType() .booleanType()
.defaultValue(false) .defaultValue(false)
.note("Dolphinscheduler ON-OFF"); .note("Dolphinscheduler ON-OFF");
private Configuration<String> dolphinschedulerUrl = private final Configuration<String> dolphinschedulerUrl =
key("dolphinscheduler.settings.url") key("dolphinscheduler.settings.url")
.stringType() .stringType()
.defaultValue("") .defaultValue("")
.note( .note(
"The address must be the same as the address configured in the DolphinScheduler background , eg: http://127.0.0.1:12345/dolphinscheduler"); "The address must be the same as the address configured in the DolphinScheduler background , eg: http://127.0.0.1:12345/dolphinscheduler");
private Configuration<String> dolphinschedulerToken = private final Configuration<String> dolphinschedulerToken =
key("dolphinscheduler.settings.token") key("dolphinscheduler.settings.token")
.stringType() .stringType()
.defaultValue("") .defaultValue("")
.note( .note(
"DolphinScheduler's Token , Please create a token in DolphinScheduler's Security Center -> Token Management, and modify the following configuration"); "DolphinScheduler's Token , Please create a token in DolphinScheduler's Security Center -> Token Management, and modify the following configuration");
private Configuration<String> dolphinschedulerProjectName = private final Configuration<String> dolphinschedulerProjectName =
key("dolphinscheduler.settings.projectName") key("dolphinscheduler.settings.projectName")
.stringType() .stringType()
.defaultValue("Dinky") .defaultValue("Dinky")
...@@ -187,6 +188,29 @@ public class SystemConfiguration { ...@@ -187,6 +188,29 @@ public class SystemConfiguration {
private final Configuration<Boolean> ldapEnable = private final Configuration<Boolean> ldapEnable =
key("ldap.settings.enable").booleanType().defaultValue(false).note("LDAP ON-OFF"); key("ldap.settings.enable").booleanType().defaultValue(false).note("LDAP ON-OFF");
private final Configuration<Boolean> metricsSysEnable =
key("metrics.settings.sys.enable")
.booleanType()
.defaultValue(false)
.note("Is the collection system indicator enabled");
private final Configuration<Integer> metricsSysGatherTiming =
key("metrics.settings.sys.gatherTiming")
.intType()
.defaultValue(3000)
.note("System METRICS gather Timing (unit: ms)");
private final Configuration<Integer> flinkMetricsGatherTiming =
key("metrics.settings.flink.gatherTiming")
.intType()
.defaultValue(3000)
.note("FLINK METRICS gather Timing (unit: ms)");
private final Configuration<Integer> flinkMetricsGatherTimeout =
key("metrics.settings.flink.gatherTimeout")
.intType()
.defaultValue(1000)
.note("FLINK METRICS gather timeout (unit: ms)");
/** Initialize after spring bean startup */ /** Initialize after spring bean startup */
public void initAfterBeanStarted() { public void initAfterBeanStarted() {
if (StrUtil.isBlank(dinkyAddr.getDefaultValue())) { if (StrUtil.isBlank(dinkyAddr.getDefaultValue())) {
...@@ -194,23 +218,41 @@ public class SystemConfiguration { ...@@ -194,23 +218,41 @@ public class SystemConfiguration {
} }
} }
public void setConfiguration(Map<String, String> configMap) { public void setConfiguration(String key, String value) {
CONFIGURATION_LIST.stream()
.filter(x -> x.getKey().equals(key))
.forEach(
item -> {
if (value == null) {
item.setValue(item.getDefaultValue());
item.runParameterCheck();
item.runChangeEvent();
return;
}
if (!StrUtil.equals(Convert.toStr(item.getValue()), value)) {
item.setValue(value);
item.runParameterCheck();
item.runChangeEvent();
}
});
}
public void initSetConfiguration(Map<String, String> configMap) {
CONFIGURATION_LIST.forEach( CONFIGURATION_LIST.forEach(
item -> { item -> {
if (!configMap.containsKey(item.getKey())) { if (!configMap.containsKey(item.getKey())) {
return; return;
} }
final String value = configMap.get(item.getKey()); final String value = configMap.get(item.getKey());
if (StrUtil.isBlank(value)) { if (value == null) {
item.setValue(item.getDefaultValue()); item.setValue(item.getDefaultValue());
return; return;
} }
item.setValue(value); item.setValue(value);
}); });
// initRun CONFIGURATION_LIST.stream()
for (Configuration<?> configuration : CONFIGURATION_LIST) { .peek(Configuration::runParameterCheck)
Opt.ofNullable(this.initMethod).ifPresent(x -> x.accept(configuration)); .forEach(Configuration::runChangeEvent);
}
} }
public Map<String, List<Configuration<?>>> getAllConfiguration() { public Map<String, List<Configuration<?>>> getAllConfiguration() {
...@@ -228,10 +270,6 @@ public class SystemConfiguration { ...@@ -228,10 +270,6 @@ public class SystemConfiguration {
return data; return data;
} }
public void setInitMethod(Consumer<Configuration<?>> initMethod) {
this.initMethod = initMethod;
}
public boolean isUseRestAPI() { public boolean isUseRestAPI() {
return useRestAPI.getValue(); return useRestAPI.getValue();
} }
......
...@@ -519,11 +519,13 @@ export default { ...@@ -519,11 +519,13 @@ export default {
'sys.setting.maven': 'Maven Configuration', 'sys.setting.maven': 'Maven Configuration',
'sys.setting.ds': 'DolphinScheduler Configuration', 'sys.setting.ds': 'DolphinScheduler Configuration',
'sys.setting.ldap': 'LDAP Configuration', 'sys.setting.ldap': 'LDAP Configuration',
'sys.setting.metrics': 'Metrics Configuration',
'sys.setting.dinky.tooltip': 'Mainly modify system variables to ensure stable operation of basic functions', 'sys.setting.dinky.tooltip': 'Mainly modify system variables to ensure stable operation of basic functions',
'sys.setting.flink.tooltip': 'Dinky docking Flink main parameters', 'sys.setting.flink.tooltip': 'Dinky docking Flink main parameters',
'sys.setting.maven.tooltip': 'The main parameters of Maven compilation', 'sys.setting.maven.tooltip': 'The main parameters of Maven compilation',
'sys.setting.ds.tooltip': 'DolphinScheduler plug-in settings that allow you to push dinky tasks to the DolphinScheduler workflow', 'sys.setting.ds.tooltip': 'DolphinScheduler plug-in settings that allow you to push dinky tasks to the DolphinScheduler workflow',
'sys.setting.ldap.tooltip': 'Unified authentication service LDAP docking configuration', 'sys.setting.ldap.tooltip': 'Unified authentication service LDAP docking configuration',
'sys.setting.metrics.tooltip': 'Monitor monitoring page settings, adjust Metrics detection',
'sys.setting.modify': 'Modify Settings {key}', 'sys.setting.modify': 'Modify Settings {key}',
'sys.env.settings.pythonHome': 'Python Env variables', 'sys.env.settings.pythonHome': 'Python Env variables',
'sys.env.settings.pythonHome.note': 'Python Env variables', 'sys.env.settings.pythonHome.note': 'Python Env variables',
...@@ -586,6 +588,16 @@ export default { ...@@ -586,6 +588,16 @@ export default {
'sys.ldap.settings.loadUser': 'Load User', 'sys.ldap.settings.loadUser': 'Load User',
'sys.ldap.settings.loadable': 'Whether it can be imported', 'sys.ldap.settings.loadable': 'Whether it can be imported',
// Metrics
'sys.metrics.settings.sys.enable':'Dinky JVM Monitor switch',
'sys.metrics.settings.sys.enable.note':'This switch is related to Dinky JVM Monitor, which determines the display of Dinky Server in the monitoring page and the collection of JVM Metrics',
'sys.metrics.settings.sys.gatherTiming':'Dinky JVM Metrics collection time granularity',
'sys.metrics.settings.sys.gatherTiming.note':'Dinky JVM Metrics collection time granularity, timed task interval trigger',
'sys.metrics.settings.flink.gatherTiming':'Flink Metrics collection time granularity',
'sys.metrics.settings.flink.gatherTiming.note':'Flink Metrics collection time granularity, scheduled task interval trigger',
'sys.metrics.settings.flink.gatherTimeout':'Flink Metrics collection time granularity, scheduled task interval trigger',
'sys.metrics.settings.flink.gatherTimeout.note':'Flink Metrics collection timeout period, scheduled task interval trigger (this configuration item should be smaller than Flink Metrics collection time granularity)',
// process // process
'sys.process.id': 'Process ID', 'sys.process.id': 'Process ID',
'sys.process.name': 'Process Name', 'sys.process.name': 'Process Name',
......
...@@ -519,13 +519,15 @@ export default { ...@@ -519,13 +519,15 @@ export default {
'sys.setting.dinky': 'Dinky 环境配置', 'sys.setting.dinky': 'Dinky 环境配置',
'sys.setting.flink': 'Flink 配置', 'sys.setting.flink': 'Flink 配置',
'sys.setting.maven': 'Maven 配置', 'sys.setting.maven': 'Maven 配置',
'sys.setting.ds': 'DolphinSchuder 配置', 'sys.setting.ds': 'DolphinScheduler 配置',
'sys.setting.ldap': 'LDAP配置', 'sys.setting.ldap': 'LDAP 配置',
'sys.setting.metrics': 'Metrics 配置',
'sys.setting.dinky.tooltip': '主要以修改系统变量为主,保证基础功能稳定运行', 'sys.setting.dinky.tooltip': '主要以修改系统变量为主,保证基础功能稳定运行',
'sys.setting.flink.tooltip': 'Dinky对接 Flink 主要参数', 'sys.setting.flink.tooltip': 'Dinky对接 Flink 主要参数',
'sys.setting.maven.tooltip': 'Maven 编译的主要参数', 'sys.setting.maven.tooltip': 'Maven 编译的主要参数',
'sys.setting.ds.tooltip': '海豚调度插件设置,可以让您把dinky任务丝滑推到海豚调度器工作流上', 'sys.setting.ds.tooltip': '海豚调度插件设置,可以让您把dinky任务丝滑推到海豚调度器工作流上',
'sys.setting.ldap.tooltip': 'LDAP统一认证配置', 'sys.setting.ldap.tooltip': 'LDAP统一认证配置',
'sys.setting.metrics.tooltip': 'Monitor 监控页面设置,调整Metrics探测',
'sys.setting.modify': '修改配置 {key}', 'sys.setting.modify': '修改配置 {key}',
'sys.setting.tag.extend': '扩展配置', 'sys.setting.tag.extend': '扩展配置',
'sys.setting.tag.core': '核心配置', 'sys.setting.tag.core': '核心配置',
...@@ -590,6 +592,15 @@ export default { ...@@ -590,6 +592,15 @@ export default {
'sys.ldap.settings.loadUser': '导入用户', 'sys.ldap.settings.loadUser': '导入用户',
'sys.ldap.settings.loadable': '是否可以导入', 'sys.ldap.settings.loadable': '是否可以导入',
// Metrics
'sys.metrics.settings.sys.enable':'Dinky JVM Monitor 开关',
'sys.metrics.settings.sys.enable.note':'此开关会关系到Dinky JVM Monitor,决定监控页面中的Dinky Server显示,以及JVM Metrics采集',
'sys.metrics.settings.sys.gatherTiming':'Dinky JVM Metrics 采集时间粒度',
'sys.metrics.settings.sys.gatherTiming.note':'Dinky JVM Metrics 采集时间粒度,定时任务间隔触发',
'sys.metrics.settings.flink.gatherTiming':'Flink Metrics 采集时间粒度',
'sys.metrics.settings.flink.gatherTiming.note':'Flink Metrics 采集时间粒度,定时任务间隔触发',
'sys.metrics.settings.flink.gatherTimeout':'Flink Metrics 采集时间粒度,定时任务间隔触发',
'sys.metrics.settings.flink.gatherTimeout.note':'Flink Metrics 采集超时时长,定时任务间隔触发(此配置项应小于Flink Metrics 采集时间粒度)',
// process // process
'sys.process.id': '进程ID', 'sys.process.id': '进程ID',
......
...@@ -51,11 +51,8 @@ export default () => { ...@@ -51,11 +51,8 @@ export default () => {
const [custom, setCustom] = useState<boolean>(false); const [custom, setCustom] = useState<boolean>(false);
const [currentTime, setCurrentTime] = useState(new Date()); const [currentTime, setCurrentTime] = useState(new Date());
const [startTime, setStartTime] = useState(getSubMinTime(currentTime, 1)); const [startTime, setStartTime] = useState(getSubMinTime(currentTime, 1));
const [dataRecord, setDataRecord] = useState<JvmDataRecord>({ const [showDinkyServer, setShowDinkySever] = useState<boolean>(true)
heapLastValue: 0, cpuLastValue: 0, heapMax: 0 const [loading, setLoading] = useState<boolean>(true)
, threadCount: 0, threadPeakCount: 0
, nonHeapMax: 0, nonHeapLastValue: 0
});
/** /**
* Data processing * Data processing
...@@ -121,12 +118,20 @@ export default () => { ...@@ -121,12 +118,20 @@ export default () => {
queryDataByParams(API_CONSTANTS.MONITOR_GET_SYSTEM_DATA, { queryDataByParams(API_CONSTANTS.MONITOR_GET_SYSTEM_DATA, {
startTime: startTime.getTime(), startTime: startTime.getTime(),
endTime: endTime.getTime() endTime: endTime.getTime()
}) }).then(res => {
.then(res => {
jvmData.length = 0; jvmData.length = 0;
flinkMetricsData.length = 0; flinkMetricsData.length = 0;
(res as MetricsDataType[]).forEach(d => dataProcess(d)) (res as MetricsDataType[]).forEach(d => dataProcess(d))
}) })
queryDataByParams(API_CONSTANTS.SYSTEM_GET_ALL_CONFIG).then(res => {
for (const config of res.metrics) {
if (config.key === "metrics.settings.sys.enable") {
setShowDinkySever(config.value)
setLoading(false)
break
}
}
})
} }
const handleRangeChange = (dates: any) => { const handleRangeChange = (dates: any) => {
setDateRange('custom') setDateRange('custom')
...@@ -167,14 +172,14 @@ export default () => { ...@@ -167,14 +172,14 @@ export default () => {
} }
return <PageContainer title={false}> return <PageContainer title={false} loading={loading}>
<ProCard size={'small'} colSpan={'100%'} bordered> <ProCard size={'small'} colSpan={'100%'} bordered>
<GlobalFilter custom={custom} dateRange={dateRange} endTime={endTime} startTime={startTime} <GlobalFilter custom={custom} dateRange={dateRange} endTime={endTime} startTime={startTime}
handleDateRadioChange={handleDateRadioChange} handleRangeChange={handleRangeChange}/> handleDateRadioChange={handleDateRadioChange} handleRangeChange={handleRangeChange}/>
</ProCard> </ProCard>
<ProCard collapsible title={'Dinky Server'} ghost hoverable bordered headerBordered> {showDinkyServer && <ProCard collapsible title={'Dinky Server'} ghost hoverable bordered headerBordered>
<Server chartConfig={commonChartConfig} data={jvmData}/> <Server chartConfig={commonChartConfig} data={jvmData}/>
</ProCard> </ProCard>}
{(layoutData != undefined) && Object.keys(layoutData).map(name => { {(layoutData != undefined) && Object.keys(layoutData).map(name => {
return <ProCard collapsible title={name} ghost hoverable bordered headerBordered gutter={[0, 8]}> return <ProCard collapsible title={name} ghost hoverable bordered headerBordered gutter={[0, 8]}>
<Row gutter={[8, 16]}> <Row gutter={[8, 16]}>
......
...@@ -32,12 +32,10 @@ export const DSConfig = ({data, onSave}: DSConfigProps) => { ...@@ -32,12 +32,10 @@ export const DSConfig = ({data, onSave}: DSConfigProps) => {
const [loading, setLoading] = React.useState(false); const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => { const onSaveHandler = async (data: BaseConfigProperties) => {
setLoading(true); setLoading(true);
onSave(data); await onSave(data);
setTimeout(() => {
setLoading(false); setLoading(false);
}, 1000);
}; };
return <> return <>
<ProCard <ProCard
......
...@@ -31,12 +31,10 @@ interface EnvConfigProps { ...@@ -31,12 +31,10 @@ interface EnvConfigProps {
export const EnvConfig = ({data, onSave}: EnvConfigProps) => { export const EnvConfig = ({data, onSave}: EnvConfigProps) => {
const [loading, setLoading] = React.useState(false); const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => { const onSaveHandler =async (data: BaseConfigProperties) => {
setLoading(true); setLoading(true);
onSave(data); await onSave(data);
setTimeout(() => {
setLoading(false); setLoading(false);
}, 1000);
}; };
return <> return <>
......
...@@ -32,12 +32,10 @@ export const FlinkConfig = ({data, onSave}: FlinkConfigProps) => { ...@@ -32,12 +32,10 @@ export const FlinkConfig = ({data, onSave}: FlinkConfigProps) => {
const [loading, setLoading] = React.useState(false); const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => { const onSaveHandler = async (data: BaseConfigProperties) => {
setLoading(true); setLoading(true);
onSave(data); await onSave(data);
setTimeout(() => {
setLoading(false); setLoading(false);
}, 1000);
}; };
return <> return <>
......
...@@ -32,12 +32,10 @@ export const MavenConfig = ({data, onSave}: MavenConfigProps) => { ...@@ -32,12 +32,10 @@ export const MavenConfig = ({data, onSave}: MavenConfigProps) => {
const [loading, setLoading] = React.useState(false); const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => { const onSaveHandler =async (data: BaseConfigProperties) => {
setLoading(true); setLoading(true);
onSave(data); await onSave(data);
setTimeout(() => {
setLoading(false); setLoading(false);
}, 1000);
}; };
......
/*
* 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.
*/
import {BaseConfigProperties} from '@/types/SettingCenter/data';
import {ProCard} from '@ant-design/pro-components';
import GeneralConfig from '@/pages/SettingCenter/GlobalSetting/SettingOverView/GeneralConfig';
import {l} from '@/utils/intl';
import {Tag} from 'antd';
import React from 'react';
interface MetricsConfigProps {
data: BaseConfigProperties[];
onSave: (data: BaseConfigProperties) => void;
}
export const MetricsConfig = ({data, onSave}: MetricsConfigProps) => {
const [loading, setLoading] = React.useState(false);
const onSaveHandler =async (data: BaseConfigProperties) => {
setLoading(true);
await onSave(data);
setLoading(false);
};
return <>
<ProCard
title={l('sys.setting.metrics')}
tooltip={l('sys.setting.metrics.tooltip')}
size="small"
headerBordered ghost collapsible
defaultCollapsed={false}
>
<GeneralConfig
loading={loading}
onSave={onSaveHandler}
tag={<><Tag color={'default'}>{l('sys.setting.tag.integration')}</Tag></>}
data={data}
/>
</ProCard>
</>;
};
...@@ -26,10 +26,18 @@ import {DSConfig} from '@/pages/SettingCenter/GlobalSetting/SettingOverView/DSCo ...@@ -26,10 +26,18 @@ import {DSConfig} from '@/pages/SettingCenter/GlobalSetting/SettingOverView/DSCo
import {LdapConfig} from "@/pages/SettingCenter/GlobalSetting/SettingOverView/LdapConfig"; import {LdapConfig} from "@/pages/SettingCenter/GlobalSetting/SettingOverView/LdapConfig";
import {l} from '@/utils/intl'; import {l} from '@/utils/intl';
import FadeIn from "@/components/Animation/FadeIn"; import FadeIn from "@/components/Animation/FadeIn";
import {MetricsConfig} from "@/pages/SettingCenter/GlobalSetting/SettingOverView/MetricsConfig";
const SettingOverView = () => { const SettingOverView = () => {
const [data, setData] = React.useState<Settings>({dolphinscheduler: [], env: [], flink: [], maven: [] , ldap: []}); const [data, setData] = React.useState<Settings>({
dolphinscheduler: [],
env: [],
flink: [],
maven: [],
ldap: [],
metrics: []
});
const fetchData = async () => { const fetchData = async () => {
...@@ -42,9 +50,20 @@ const SettingOverView = () => { ...@@ -42,9 +50,20 @@ const SettingOverView = () => {
fetchData(); fetchData();
}, []); }, []);
const handleSaveSubmit = async (data: BaseConfigProperties) => { const handleSaveSubmit = async (dataConfig: BaseConfigProperties) => {
const {code} = await handleOption(API_CONSTANTS.SYSTEM_MODIFY_CONFIG, l('sys.setting.modify', '', {key: l(`sys.${data.key}`)}), data); const {code} = await handleOption(API_CONSTANTS.SYSTEM_MODIFY_CONFIG, l('sys.setting.modify', '', {key: l(`sys.${dataConfig.key}`)}), dataConfig);
if (code === RESPONSE_CODE.SUCCESS) await fetchData();
if (code === RESPONSE_CODE.ERROR) {
await fetchData()
} else {
// @ts-ignore
for (const d of data[dataConfig.key.split('.')[0]]) {
if (d.key == dataConfig.key) {
d.value = dataConfig.value
break
}
}
}
}; };
const renderData = () => { const renderData = () => {
...@@ -54,13 +73,16 @@ const SettingOverView = () => { ...@@ -54,13 +73,16 @@ const SettingOverView = () => {
flink: flinkConfig, flink: flinkConfig,
maven: mavenConfig, maven: mavenConfig,
dolphinscheduler: dsConfig, dolphinscheduler: dsConfig,
ldap: ldapConfig} = data; ldap: ldapConfig,
return <div style={{paddingBottom:"20px"}}> metrics: metricsConfig
} = data;
return <div style={{paddingBottom: "20px"}}>
<EnvConfig onSave={handleSaveSubmit} data={dinkyEnv}/> <EnvConfig onSave={handleSaveSubmit} data={dinkyEnv}/>
<FlinkConfig onSave={handleSaveSubmit} data={flinkConfig}/> <FlinkConfig onSave={handleSaveSubmit} data={flinkConfig}/>
<MavenConfig onSave={handleSaveSubmit} data={mavenConfig}/> <MavenConfig onSave={handleSaveSubmit} data={mavenConfig}/>
<DSConfig onSave={handleSaveSubmit} data={dsConfig}/> <DSConfig onSave={handleSaveSubmit} data={dsConfig}/>
<LdapConfig onSave={handleSaveSubmit} data={ldapConfig}/> <LdapConfig onSave={handleSaveSubmit} data={ldapConfig}/>
<MetricsConfig onSave={handleSaveSubmit} data={metricsConfig}/>
</div>; </div>;
} }
}; };
......
...@@ -149,10 +149,10 @@ export const handleOption = async (url: string, title: string, param: any) => { ...@@ -149,10 +149,10 @@ export const handleOption = async (url: string, title: string, param: any) => {
try { try {
const result = await postAll(url, param); const result = await postAll(url, param);
if (result.code === RESPONSE_CODE.SUCCESS) { if (result.code === RESPONSE_CODE.SUCCESS) {
await SuccessMessage(result.msg); SuccessMessage(result.msg);
return result; return result;
} else { } else {
await WarningMessage(result.msg); WarningMessage(result.msg);
return false; return false;
} }
} catch (error) { } catch (error) {
......
...@@ -49,6 +49,7 @@ export type Settings = { ...@@ -49,6 +49,7 @@ export type Settings = {
flink: BaseConfigProperties[]; flink: BaseConfigProperties[];
maven: BaseConfigProperties[]; maven: BaseConfigProperties[];
ldap: BaseConfigProperties[]; ldap: BaseConfigProperties[];
metrics: BaseConfigProperties[];
} }
export type BaseConfigProperties = { export type BaseConfigProperties = {
key: string; key: string;
......
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