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
/*
*
* 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;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
......@@ -104,16 +105,21 @@ public class SystemInit implements ApplicationRunner {
/** init DolphinScheduler */
private void initDolphinScheduler() {
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
systemConfiguration.setInitMethod(
c -> {
if (c == systemConfiguration.getDolphinschedulerEnable()) {
if (systemConfiguration.getDolphinschedulerEnable().getValue()) {
if (StrUtil.hasBlank(
systemConfiguration.getDolphinschedulerUrl().getValue(),
systemConfiguration.getDolphinschedulerProjectName().getValue(),
systemConfiguration.getDolphinschedulerToken().getValue())) {
systemConfiguration
.getAllConfiguration()
.get("dolphinscheduler")
.forEach(
c ->
c.addParameterCheck(
v -> {
if (systemConfiguration
.getDolphinschedulerEnable()
.getValue()) {
if (StrUtil.isEmpty(Convert.toStr(v))) {
sysConfigService.updateSysConfigByKv(
systemConfiguration.getDolphinschedulerEnable().getKey(),
systemConfiguration
.getDolphinschedulerEnable()
.getKey(),
"false");
throw new DinkyException(
"Before starting DolphinScheduler docking, please fill in the relevant configuration");
......@@ -121,15 +127,15 @@ public class SystemInit implements ApplicationRunner {
try {
project = projectClient.getDinkyProject();
if (Asserts.isNull(project)) {
project = projectClient.createDinkyProject();
project =
projectClient.createDinkyProject();
}
} catch (Exception e) {
log.error("Error in DolphinScheduler: ", e);
throw new DinkyException(e);
}
}
}
});
}));
}
/**
......
......@@ -104,7 +104,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics>
maxDate = metrics.getHeartTime();
}
}
ThreadUtil.sleep(MetricConfig.SCHEDULED_RATE - 200);
ThreadUtil.sleep(800);
}
} catch (IOException e) {
sseEmitter.complete();
......
......@@ -24,7 +24,6 @@ import org.dinky.data.model.SysConfig;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.mapper.SysConfigMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.process.exception.DinkyException;
import org.dinky.service.SysConfigService;
import java.util.HashMap;
......@@ -39,8 +38,6 @@ import com.baomidou.mybatisplus.extension.activerecord.Model;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
/**
* SysConfigServiceImpl
......@@ -79,7 +76,7 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC
.forEach(Model::insertOrUpdate);
Map<String, String> configMap =
CollUtil.toMap(list(), new HashMap<>(), SysConfig::getName, SysConfig::getValue);
systemConfiguration.setConfiguration(configMap);
systemConfiguration.initSetConfiguration(configMap);
}
@Override
......@@ -88,17 +85,7 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC
config.setValue(value);
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
if (key.equals(systemConfiguration.getDolphinschedulerEnable().getKey())
&& 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));
systemConfiguration.setConfiguration(key, value);
config.updateById();
}
}
......@@ -21,7 +21,9 @@ package org.dinky.data.model;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonIgnore;
......@@ -42,6 +44,10 @@ public class Configuration<T> implements Serializable {
private String note;
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 static final List<Class<?>> NUMBER_LIST =
......@@ -137,4 +143,32 @@ public class Configuration<T> implements Serializable {
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;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ReflectUtil;
......@@ -47,7 +48,7 @@ public class SystemConfiguration {
return systemConfiguration;
}
private Consumer<Configuration<?>> initMethod = null;
private final Consumer<Configuration<?>> initMethod = null;
public static Configuration.OptionBuilder key(String key) {
return new Configuration.OptionBuilder(key);
......@@ -60,76 +61,76 @@ public class SystemConfiguration {
f -> f.getType() == Configuration.class))
.map(f -> (Configuration<?>) ReflectUtil.getFieldValue(systemConfiguration, f))
.collect(Collectors.toList());
private Configuration<Boolean> useRestAPI =
private final Configuration<Boolean> useRestAPI =
key("flink.settings.useRestAPI")
.booleanType()
.defaultValue(true)
.note("在运维 Flink 任务时是否使用 RestAPI");
private Configuration<String> sqlSeparator =
private final Configuration<String> sqlSeparator =
key("flink.settings.sqlSeparator")
.stringType()
.defaultValue(";\\n")
.note("FlinkSQL语句分割符");
private Configuration<Integer> jobIdWait =
private final Configuration<Integer> jobIdWait =
key("flink.settings.jobIdWait")
.intType()
.defaultValue(30)
.note("提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)");
private Configuration<String> mavenSettings =
private final Configuration<String> mavenSettings =
key("maven.settings.settingsFilePath")
.stringType()
.defaultValue("")
.note("Maven Settings 文件路径");
private Configuration<String> mavenRepository =
private final Configuration<String> mavenRepository =
key("maven.settings.repository")
.stringType()
.defaultValue("https://maven.aliyun.com/nexus/content/repositories/central")
.note("Maven private server address");
private Configuration<String> mavenRepositoryUser =
private final Configuration<String> mavenRepositoryUser =
key("maven.settings.repositoryUser")
.stringType()
.defaultValue("")
.note("Maven private server authentication username");
private Configuration<String> mavenRepositoryPassword =
private final Configuration<String> mavenRepositoryPassword =
key("maven.settings.repositoryPassword")
.stringType()
.defaultValue("")
.desensitizedHandler(DesensitizedUtil::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");
private Configuration<String> dinkyAddr =
private final Configuration<String> dinkyAddr =
key("env.settings.dinkyAddr")
.stringType()
.defaultValue(System.getProperty("dinkyAddr"))
.note(
"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")
.booleanType()
.defaultValue(false)
.note("Dolphinscheduler ON-OFF");
private Configuration<String> dolphinschedulerUrl =
private final Configuration<String> dolphinschedulerUrl =
key("dolphinscheduler.settings.url")
.stringType()
.defaultValue("")
.note(
"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")
.stringType()
.defaultValue("")
.note(
"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")
.stringType()
.defaultValue("Dinky")
......@@ -187,6 +188,29 @@ public class SystemConfiguration {
private final Configuration<Boolean> ldapEnable =
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 */
public void initAfterBeanStarted() {
if (StrUtil.isBlank(dinkyAddr.getDefaultValue())) {
......@@ -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(
item -> {
if (!configMap.containsKey(item.getKey())) {
return;
}
final String value = configMap.get(item.getKey());
if (StrUtil.isBlank(value)) {
if (value == null) {
item.setValue(item.getDefaultValue());
return;
}
item.setValue(value);
});
// initRun
for (Configuration<?> configuration : CONFIGURATION_LIST) {
Opt.ofNullable(this.initMethod).ifPresent(x -> x.accept(configuration));
}
CONFIGURATION_LIST.stream()
.peek(Configuration::runParameterCheck)
.forEach(Configuration::runChangeEvent);
}
public Map<String, List<Configuration<?>>> getAllConfiguration() {
......@@ -228,10 +270,6 @@ public class SystemConfiguration {
return data;
}
public void setInitMethod(Consumer<Configuration<?>> initMethod) {
this.initMethod = initMethod;
}
public boolean isUseRestAPI() {
return useRestAPI.getValue();
}
......
......@@ -519,11 +519,13 @@ export default {
'sys.setting.maven': 'Maven Configuration',
'sys.setting.ds': 'DolphinScheduler 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.flink.tooltip': 'Dinky docking Flink main parameters',
'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.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.env.settings.pythonHome': 'Python Env variables',
'sys.env.settings.pythonHome.note': 'Python Env variables',
......@@ -586,6 +588,16 @@ export default {
'sys.ldap.settings.loadUser': 'Load User',
'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
'sys.process.id': 'Process ID',
'sys.process.name': 'Process Name',
......
......@@ -519,13 +519,15 @@ export default {
'sys.setting.dinky': 'Dinky 环境配置',
'sys.setting.flink': 'Flink 配置',
'sys.setting.maven': 'Maven 配置',
'sys.setting.ds': 'DolphinSchuder 配置',
'sys.setting.ldap': 'LDAP配置',
'sys.setting.ds': 'DolphinScheduler 配置',
'sys.setting.ldap': 'LDAP 配置',
'sys.setting.metrics': 'Metrics 配置',
'sys.setting.dinky.tooltip': '主要以修改系统变量为主,保证基础功能稳定运行',
'sys.setting.flink.tooltip': 'Dinky对接 Flink 主要参数',
'sys.setting.maven.tooltip': 'Maven 编译的主要参数',
'sys.setting.ds.tooltip': '海豚调度插件设置,可以让您把dinky任务丝滑推到海豚调度器工作流上',
'sys.setting.ldap.tooltip': 'LDAP统一认证配置',
'sys.setting.metrics.tooltip': 'Monitor 监控页面设置,调整Metrics探测',
'sys.setting.modify': '修改配置 {key}',
'sys.setting.tag.extend': '扩展配置',
'sys.setting.tag.core': '核心配置',
......@@ -590,6 +592,15 @@ export default {
'sys.ldap.settings.loadUser': '导入用户',
'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
'sys.process.id': '进程ID',
......
......@@ -51,11 +51,8 @@ export default () => {
const [custom, setCustom] = useState<boolean>(false);
const [currentTime, setCurrentTime] = useState(new Date());
const [startTime, setStartTime] = useState(getSubMinTime(currentTime, 1));
const [dataRecord, setDataRecord] = useState<JvmDataRecord>({
heapLastValue: 0, cpuLastValue: 0, heapMax: 0
, threadCount: 0, threadPeakCount: 0
, nonHeapMax: 0, nonHeapLastValue: 0
});
const [showDinkyServer, setShowDinkySever] = useState<boolean>(true)
const [loading, setLoading] = useState<boolean>(true)
/**
* Data processing
......@@ -121,12 +118,20 @@ export default () => {
queryDataByParams(API_CONSTANTS.MONITOR_GET_SYSTEM_DATA, {
startTime: startTime.getTime(),
endTime: endTime.getTime()
})
.then(res => {
}).then(res => {
jvmData.length = 0;
flinkMetricsData.length = 0;
(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) => {
setDateRange('custom')
......@@ -167,14 +172,14 @@ export default () => {
}
return <PageContainer title={false}>
return <PageContainer title={false} loading={loading}>
<ProCard size={'small'} colSpan={'100%'} bordered>
<GlobalFilter custom={custom} dateRange={dateRange} endTime={endTime} startTime={startTime}
handleDateRadioChange={handleDateRadioChange} handleRangeChange={handleRangeChange}/>
</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}/>
</ProCard>
</ProCard>}
{(layoutData != undefined) && Object.keys(layoutData).map(name => {
return <ProCard collapsible title={name} ghost hoverable bordered headerBordered gutter={[0, 8]}>
<Row gutter={[8, 16]}>
......
......@@ -32,12 +32,10 @@ export const DSConfig = ({data, onSave}: DSConfigProps) => {
const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => {
const onSaveHandler = async (data: BaseConfigProperties) => {
setLoading(true);
onSave(data);
setTimeout(() => {
await onSave(data);
setLoading(false);
}, 1000);
};
return <>
<ProCard
......
......@@ -31,12 +31,10 @@ interface EnvConfigProps {
export const EnvConfig = ({data, onSave}: EnvConfigProps) => {
const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => {
const onSaveHandler =async (data: BaseConfigProperties) => {
setLoading(true);
onSave(data);
setTimeout(() => {
await onSave(data);
setLoading(false);
}, 1000);
};
return <>
......
......@@ -32,12 +32,10 @@ export const FlinkConfig = ({data, onSave}: FlinkConfigProps) => {
const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => {
const onSaveHandler = async (data: BaseConfigProperties) => {
setLoading(true);
onSave(data);
setTimeout(() => {
await onSave(data);
setLoading(false);
}, 1000);
};
return <>
......
......@@ -32,12 +32,10 @@ export const MavenConfig = ({data, onSave}: MavenConfigProps) => {
const [loading, setLoading] = React.useState(false);
const onSaveHandler = (data: BaseConfigProperties) => {
const onSaveHandler =async (data: BaseConfigProperties) => {
setLoading(true);
onSave(data);
setTimeout(() => {
await onSave(data);
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
import {LdapConfig} from "@/pages/SettingCenter/GlobalSetting/SettingOverView/LdapConfig";
import {l} from '@/utils/intl';
import FadeIn from "@/components/Animation/FadeIn";
import {MetricsConfig} from "@/pages/SettingCenter/GlobalSetting/SettingOverView/MetricsConfig";
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 () => {
......@@ -42,9 +50,20 @@ const SettingOverView = () => {
fetchData();
}, []);
const handleSaveSubmit = async (data: BaseConfigProperties) => {
const {code} = await handleOption(API_CONSTANTS.SYSTEM_MODIFY_CONFIG, l('sys.setting.modify', '', {key: l(`sys.${data.key}`)}), data);
if (code === RESPONSE_CODE.SUCCESS) await fetchData();
const handleSaveSubmit = async (dataConfig: BaseConfigProperties) => {
const {code} = await handleOption(API_CONSTANTS.SYSTEM_MODIFY_CONFIG, l('sys.setting.modify', '', {key: l(`sys.${dataConfig.key}`)}), dataConfig);
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 = () => {
......@@ -54,13 +73,16 @@ const SettingOverView = () => {
flink: flinkConfig,
maven: mavenConfig,
dolphinscheduler: dsConfig,
ldap: ldapConfig} = data;
return <div style={{paddingBottom:"20px"}}>
ldap: ldapConfig,
metrics: metricsConfig
} = data;
return <div style={{paddingBottom: "20px"}}>
<EnvConfig onSave={handleSaveSubmit} data={dinkyEnv}/>
<FlinkConfig onSave={handleSaveSubmit} data={flinkConfig}/>
<MavenConfig onSave={handleSaveSubmit} data={mavenConfig}/>
<DSConfig onSave={handleSaveSubmit} data={dsConfig}/>
<LdapConfig onSave={handleSaveSubmit} data={ldapConfig}/>
<MetricsConfig onSave={handleSaveSubmit} data={metricsConfig}/>
</div>;
}
};
......
......@@ -149,10 +149,10 @@ export const handleOption = async (url: string, title: string, param: any) => {
try {
const result = await postAll(url, param);
if (result.code === RESPONSE_CODE.SUCCESS) {
await SuccessMessage(result.msg);
SuccessMessage(result.msg);
return result;
} else {
await WarningMessage(result.msg);
WarningMessage(result.msg);
return false;
}
} catch (error) {
......
......@@ -49,6 +49,7 @@ export type Settings = {
flink: BaseConfigProperties[];
maven: BaseConfigProperties[];
ldap: BaseConfigProperties[];
metrics: BaseConfigProperties[];
}
export type BaseConfigProperties = {
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