Unverified Commit 7d966bf8 authored by gaoyan's avatar gaoyan Committed by GitHub

Refactor job metricss (#2331)

* refactor JobInstance refesh * fix job refesh npe * fix code style * Compatible with J Dk 8 * Modify the job refresh time to 5 秒之前 * fix alert npe * fix devops data * fix json parse error * refactor JobMetrics logic * remove recordStats * refactor JobMetrics * fix code style * fix code style * fix jdk8 * fix code style
parent c2dc2b09
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.configure;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.vo.MetricsVO;
import org.dinky.utils.PaimonUtil;
import java.util.ArrayList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Configuration
@RequiredArgsConstructor
@EnableScheduling
@Slf4j
public class MetricConfig {
private static final Queue<MetricsVO> METRICS_QUEUE = new ConcurrentLinkedQueue<>();
public int flinkMetricsRequestTimeout =
SystemConfiguration.getInstances().getFlinkMetricsGatherTimeout().getDefaultValue();
/** Update status per second */
/** Entering the lake every 10 states */
@Scheduled(fixedRate = 10000)
@PreDestroy
public void writeScheduled() throws Exception {
PaimonUtil.writeMetrics(new ArrayList<>(METRICS_QUEUE));
METRICS_QUEUE.clear();
}
public static Queue<MetricsVO> getMetricsQueue() {
return METRICS_QUEUE;
}
}
/*
*
* 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.Collections;
import java.util.HashMap;
import java.util.HashSet;
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.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
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);
for (FlinkMetrics flinkMetrics : FLINK_METRICS_DATA_MAP.get(now)) {
MetricsVO metricsVO = new MetricsVO();
metricsVO.setModel(flinkMetrics.getJobId());
metricsVO.setHeartTime(now);
metricsVO.setContent(flinkMetrics);
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();
// 使用流将List转换为Map,taskId为键,LayoutName为值,
// 如果一个任务被分配到多个layoutName,则存储到Set去重
Map<Integer, Set<String>> taskMap = metricsList.stream()
.collect(Collectors.toMap(
Metrics::getTaskId,
metrics -> new HashSet<>(Collections.singletonList(metrics.getLayoutName())),
(existingValue, newValue) -> {
existingValue.addAll(newValue);
return existingValue;
}));
for (JobInstance jobInstance : jobInstances) {
Integer taskId = jobInstance.getTaskId();
if (!taskMap.containsKey(taskId)) {
continue;
}
FlinkMetrics flinkMetrics = new FlinkMetrics();
flinkMetrics.setTaskId(taskId);
flinkMetrics.setJobId(jobInstance.getJid());
flinkMetrics.setLayoutNames(taskMap.get(taskId));
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,0.numRecordsInPerSecond
flinkMetrics.getVerticesAndMetricsMap().forEach((v, m) -> {
if (CollUtil.isEmpty(urlList)) {
return;
}
String metricsName = StrUtil.join(",", m.keySet());
HttpUtils.asyncRequest(
flinkMetrics.getUrls(),
"/jobs/"
+ flinkMetrics.getJobId()
+ "/vertices/"
+ v
+ "/metrics?get="
+ URLUtil.encode(metricsName),
flinkMetricsRequestTimeout.get(),
x -> {
JSONArray array = JSONUtil.parseArray(x.body());
if (CollUtil.isEmpty(array)) {
return;
}
array.forEach(y -> {
JSONObject jsonObject = JSONUtil.parseObj(y);
String id = jsonObject.getStr("id");
String value = jsonObject.getStr("value");
m.put(id, value);
});
});
});
FLINK_METRICS_DATA_MAP.get(now).add(flinkMetrics);
}
@Setter
@Getter
public static class FlinkMetrics {
private String jobId;
private Set<String> layoutNames;
private Integer taskId;
private List<String> urls = new CopyOnWriteArrayList<>();
/** jobId -> metricsId -> metricsValue */
private Map<String, Map<String, String>> verticesAndMetricsMap = new HashMap<>();
}
}
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
package org.dinky.configure.schedule.metrics; package org.dinky.configure.schedule.metrics;
import org.dinky.configure.MetricConfig;
import org.dinky.configure.schedule.BaseSchedule; import org.dinky.configure.schedule.BaseSchedule;
import org.dinky.context.MetricsContextHolder;
import org.dinky.data.annotation.GaugeM; import org.dinky.data.annotation.GaugeM;
import org.dinky.data.enums.MetricsType; import org.dinky.data.enums.MetricsType;
import org.dinky.data.metrics.BaseMetrics; import org.dinky.data.metrics.BaseMetrics;
...@@ -93,7 +93,7 @@ public class GatherSysIndicator extends BaseSchedule { ...@@ -93,7 +93,7 @@ public class GatherSysIndicator extends BaseSchedule {
metrics.setContent(metricsTotal); metrics.setContent(metricsTotal);
metrics.setHeartTime(now); metrics.setHeartTime(now);
metrics.setModel(MetricsType.LOCAL.getType()); metrics.setModel(MetricsType.LOCAL.getType());
MetricConfig.getMetricsQueue().add(metrics); MetricsContextHolder.sendAsync(metrics);
log.debug("Collecting jvm information ends."); log.debug("Collecting jvm information ends.");
} }
......
/*
*
* 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.context;
import org.dinky.data.vo.MetricsVO;
import org.dinky.utils.PaimonUtil;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalNotification;
import lombok.extern.slf4j.Slf4j;
/**
* The MetricsContextHolder class is used to manage the metric context,
* including operations such as storing and sending metric data.
*/
@Slf4j
public class MetricsContextHolder {
/**
* Temporary cache monitoring information, mainly to prevent excessive buffering of write IO,
* when metricsVOS data reaches 1000 or the time exceeds 5 seconds
*/
private static final List<MetricsVO> metricsVOS = Collections.synchronizedList(new ArrayList<>());
private static final Long lastDumpTime = System.currentTimeMillis();
/**
* Cache that stores SseEmitter objects for sending metric data,
* prevents OOM with LoadingCache, and is automatically removed when objects
* in the cache are not accessed or used for more than 60 seconds.
*/
private static final LoadingCache<Object, List<SseEmitter>> sseList = CacheBuilder.newBuilder()
.expireAfterAccess(60, TimeUnit.SECONDS)
.removalListener(MetricsContextHolder::onRemove)
.build(CacheLoader.from(key -> new ArrayList<>()));
/**
* The sendAsync method is used to send metric data asynchronously.
*
* @param metrics metric data object
*/
public static void sendAsync(MetricsVO metrics) {
CompletableFuture.runAsync(() -> {
dumpMetrics(metrics);
send(metrics);
});
}
/**
* The addSse method is used to add the SseEmitter object.
*
* @param keys keyword list for indicator data
* @param sseEmitter SseEmitter object
* @param lastTime initialization data intercepts the largest timestamp
*/
public static void addSse(List<String> keys, SseEmitter sseEmitter, LocalDateTime lastTime) {
keys.forEach(key -> {
List<SseEmitter> sseEmitters = sseList.getIfPresent(key);
if (sseEmitters == null) {
sseEmitters = new ArrayList<>();
sseList.put(key, sseEmitters);
}
sseEmitters.add(sseEmitter);
});
sendInitData(keys, sseEmitter, lastTime);
}
/**
* The sendInitData method is used to send initialized indicator data.
*
* @param keys keyword list for indicator data
* @param sseEmitter SseEmitter object
* @param lastTime's last timestamp
*/
private static void sendInitData(List<String> keys, SseEmitter sseEmitter, LocalDateTime lastTime) {
CompletableFuture.runAsync(() -> {
synchronized (metricsVOS) {
metricsVOS.forEach(metricsVO -> {
if (keys.contains(metricsVO.getModel())
&& metricsVO.getHeartTime().isAfter(lastTime)) {
try {
sseEmitter.send(metricsVO);
} catch (Exception e) {
log.warn("send metrics error:{}", e.getMessage());
closeSse(sseEmitter);
}
}
});
}
});
}
/**
* The dumpMetrics method is used to dump metric data to paimon.
*
* @param metrics metric data object
*/
private static void dumpMetrics(MetricsVO metrics) {
metricsVOS.add(metrics);
long duration = System.currentTimeMillis() - lastDumpTime;
synchronized (metricsVOS) {
if (metricsVOS.size() > 1000 || duration > 1000 * 5) {
PaimonUtil.writeMetrics(metricsVOS);
metricsVOS.clear();
}
}
}
/**
* The send method is used to send metric data.
*
* @param metrics metric data object
*/
private static void send(MetricsVO metrics) {
List<SseEmitter> sseEmitters = sseList.getIfPresent(metrics.getModel());
if (sseEmitters != null) {
sseEmitters.forEach(sseEmitter -> {
try {
sseEmitter.send(metrics);
} catch (Exception e) {
log.warn("send metrics error:{}", e.getMessage());
closeSse(sseEmitter);
sseEmitters.remove(sseEmitter);
}
});
}
}
/**
* The onRemove method is used to remove the SseEmitter object from the cache.
*
* @param removalNotification RemovalNotification object
*/
private static void onRemove(RemovalNotification<Object, List<SseEmitter>> removalNotification) {
assert removalNotification.getValue() != null;
removalNotification.getValue().forEach(MetricsContextHolder::closeSse);
}
/**
* The closeSse method is used to close the SseEmitter object.
*
* @param sseEmitter SseEmitter object
*/
private static void closeSse(SseEmitter sseEmitter) {
try {
sseEmitter.complete();
} catch (Exception e) {
log.warn("complete sseEmitter failed:{}", e.getMessage());
}
}
}
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.configure.schedule.metrics.FlinkMetricsIndicator;
import org.dinky.data.annotation.Log; import org.dinky.data.annotation.Log;
import org.dinky.data.dto.MetricsLayoutDTO; import org.dinky.data.dto.MetricsLayoutDTO;
import org.dinky.data.enums.BusinessType; import org.dinky.data.enums.BusinessType;
...@@ -32,13 +31,13 @@ import org.dinky.data.vo.MetricsVO; ...@@ -32,13 +31,13 @@ import org.dinky.data.vo.MetricsVO;
import org.dinky.service.JobInstanceService; import org.dinky.service.JobInstanceService;
import org.dinky.service.MonitorService; import org.dinky.service.MonitorService;
import org.dinky.sse.SseEmitterUTF8; import org.dinky.sse.SseEmitterUTF8;
import org.dinky.utils.TimeUtil;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
...@@ -72,9 +71,6 @@ public class MonitorController { ...@@ -72,9 +71,6 @@ public class MonitorController {
private final MonitorService monitorService; private final MonitorService monitorService;
private final JobInstanceService jobInstanceService; private final JobInstanceService jobInstanceService;
@Autowired
private FlinkMetricsIndicator flinkMetricsIndicator;
@GetMapping("/getSysData") @GetMapping("/getSysData")
@ApiOperation("Get System Data") @ApiOperation("Get System Data")
@ApiImplicitParams({ @ApiImplicitParams({
...@@ -115,14 +111,13 @@ public class MonitorController { ...@@ -115,14 +111,13 @@ public class MonitorController {
@ApiOperation("Get Last Update Data") @ApiOperation("Get Last Update Data")
@ApiImplicitParams({ @ApiImplicitParams({
@ApiImplicitParam(name = "lastTime", value = "Last Time", required = false, dataType = "Long"), @ApiImplicitParam(name = "lastTime", value = "Last Time", required = false, dataType = "Long"),
@ApiImplicitParam(name = "layoutName", value = "Layout Name", required = true, dataType = "String") @ApiImplicitParam(name = "keys", value = "jobids", required = true, dataType = "String")
}) })
public SseEmitter getLastUpdateData(Long lastTime, String layoutName) { public SseEmitter getLastUpdateData(Long lastTime, String keys) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30)); SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
lastTime = Opt.ofNullable(lastTime).orElse(TimeUtil.nowTimestamp());
return monitorService.sendLatestData( return monitorService.sendLatestData(
emitter, emitter, TimeUtil.toLocalDateTime(lastTime), CollUtil.newArrayList(keys.split(",")));
DateUtil.date(Opt.ofNullable(lastTime).orElse(DateUtil.date().getTime())),
layoutName);
} }
@PutMapping("/saveFlinkMetrics/{layout}") @PutMapping("/saveFlinkMetrics/{layout}")
...@@ -139,7 +134,8 @@ public class MonitorController { ...@@ -139,7 +134,8 @@ public class MonitorController {
public Result<Void> saveFlinkMetricLayout( public Result<Void> saveFlinkMetricLayout(
@PathVariable(value = "layout") String layoutName, @RequestBody List<MetricsLayoutDTO> metricsList) { @PathVariable(value = "layout") String layoutName, @RequestBody List<MetricsLayoutDTO> metricsList) {
monitorService.saveFlinkMetricLayout(layoutName, metricsList); monitorService.saveFlinkMetricLayout(layoutName, metricsList);
flinkMetricsIndicator.getAndCheckFlinkUrlAvailable(); jobInstanceService.refreshJobByTaskIds(
metricsList.stream().map(MetricsLayoutDTO::getTaskId).distinct().toArray(Integer[]::new));
return Result.succeed(); return Result.succeed();
} }
......
...@@ -21,6 +21,7 @@ package org.dinky.controller; ...@@ -21,6 +21,7 @@ package org.dinky.controller;
import org.dinky.service.MonitorService; import org.dinky.service.MonitorService;
import org.dinky.sse.SseEmitterUTF8; import org.dinky.sse.SseEmitterUTF8;
import org.dinky.utils.TimeUtil;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
...@@ -30,7 +31,6 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -30,7 +31,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
...@@ -49,10 +49,8 @@ public class SseController { ...@@ -49,10 +49,8 @@ public class SseController {
@ApiImplicitParam(name = "lastTime", value = "last time", required = false, dataType = "Long", paramType = "query") @ApiImplicitParam(name = "lastTime", value = "last time", required = false, dataType = "Long", paramType = "query")
public SseEmitter getLastUpdateData(Long lastTime) { public SseEmitter getLastUpdateData(Long lastTime) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30)); SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
return monitorService.sendLatestData( lastTime = Opt.ofNullable(lastTime).orElse(TimeUtil.nowTimestamp());
emitter, return monitorService.sendLatestData(emitter, TimeUtil.toLocalDateTime(lastTime), null);
DateUtil.date(Opt.ofNullable(lastTime).orElse(DateUtil.date().getTime())),
null);
} }
@GetMapping(value = "/getJvmInfo", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @GetMapping(value = "/getJvmInfo", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
......
...@@ -21,7 +21,8 @@ package org.dinky.data.model; ...@@ -21,7 +21,8 @@ package org.dinky.data.model;
import org.dinky.data.dto.JobDataDto; import org.dinky.data.dto.JobDataDto;
import java.util.Set; import java.util.HashMap;
import java.util.Map;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
...@@ -51,14 +52,14 @@ public class JobInfoDetail { ...@@ -51,14 +52,14 @@ public class JobInfoDetail {
@ApiModelProperty(value = "History", notes = "Details about the history") @ApiModelProperty(value = "History", notes = "Details about the history")
private History history; private History history;
@ApiModelProperty(value = "Job Manager Configuration", notes = "Details about the job manager configuration")
private JobManagerConfiguration jobManagerConfiguration;
@ApiModelProperty(value = "JobDataDto", notes = "Details about the job") @ApiModelProperty(value = "JobDataDto", notes = "Details about the job")
private JobDataDto jobDataDto; private JobDataDto jobDataDto;
@ApiModelProperty(value = "Task Manager Configurations", notes = "Set of task manager configurations") /**
private Set<TaskManagerConfiguration> taskManagerConfiguration; * jobId -> metricsId -> metricsValue
*/
@ApiModelProperty(value = "Metrics Map", notes = "Details about the metrics map")
private Map<String, Map<String, String>> customMetricsMap = new HashMap<>();
public JobInfoDetail(Integer id) { public JobInfoDetail(Integer id) {
this.id = id; this.id = id;
......
...@@ -90,4 +90,8 @@ public class Metrics extends Model<Metrics> { ...@@ -90,4 +90,8 @@ public class Metrics extends Model<Metrics> {
@TableField(exist = false) @TableField(exist = false)
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "Job ID", dataType = "String", notes = "ID of the associated job")
@TableField(exist = false)
private String jobId;
} }
...@@ -19,9 +19,6 @@ ...@@ -19,9 +19,6 @@
package org.dinky.data.vo; package org.dinky.data.vo;
import org.dinky.configure.schedule.metrics.FlinkMetricsIndicator;
import org.dinky.data.metrics.MetricsTotal;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
...@@ -32,19 +29,18 @@ import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; ...@@ -32,19 +29,18 @@ import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Getter; import lombok.AllArgsConstructor;
import lombok.Setter; import lombok.Data;
import lombok.NoArgsConstructor;
@Getter @Data
@Setter @AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "MetricsVO", description = "Metrics Value Object") @ApiModel(value = "MetricsVO", description = "Metrics Value Object")
public class MetricsVO { public class MetricsVO {
@ApiModelProperty(value = "Content of metrics", dataType = "Object", notes = "Content of the metrics data.") @ApiModelProperty(value = "Content of metrics", dataType = "Object", notes = "Content of the metrics data.")
private Object content; private Object content;
@ApiModelProperty(value = "Total metrics", dataType = "MetricsTotal", notes = "Total metrics data.")
private MetricsTotal metricsTotal;
@ApiModelProperty(value = "Model name", dataType = "String", notes = "Name of the model.") @ApiModelProperty(value = "Model name", dataType = "String", notes = "Name of the model.")
private String model; private String model;
...@@ -57,12 +53,4 @@ public class MetricsVO { ...@@ -57,12 +53,4 @@ public class MetricsVO {
notes = "Timestamp of the heartbeat data.", notes = "Timestamp of the heartbeat data.",
example = "2023-09-15 14:30:00") example = "2023-09-15 14:30:00")
private LocalDateTime heartTime; private LocalDateTime heartTime;
public FlinkMetricsIndicator.FlinkMetrics flinkContent() {
if (content instanceof FlinkMetricsIndicator.FlinkMetrics) {
return (FlinkMetricsIndicator.FlinkMetrics) content;
} else {
return new FlinkMetricsIndicator.FlinkMetrics();
}
}
} }
...@@ -26,6 +26,7 @@ import org.dinky.daemon.task.DaemonTask; ...@@ -26,6 +26,7 @@ import org.dinky.daemon.task.DaemonTask;
import org.dinky.daemon.task.DaemonTaskConfig; import org.dinky.daemon.task.DaemonTaskConfig;
import org.dinky.data.model.JobInfoDetail; import org.dinky.data.model.JobInfoDetail;
import org.dinky.job.handler.JobAlertHandler; import org.dinky.job.handler.JobAlertHandler;
import org.dinky.job.handler.JobMetricsHandler;
import org.dinky.job.handler.JobRefeshHandler; import org.dinky.job.handler.JobRefeshHandler;
import org.dinky.service.JobInstanceService; import org.dinky.service.JobInstanceService;
...@@ -71,13 +72,12 @@ public class FlinkJobTask implements DaemonTask { ...@@ -71,13 +72,12 @@ public class FlinkJobTask implements DaemonTask {
*/ */
@Override @Override
public boolean dealTask() { public boolean dealTask() {
// TODO: 目前只是完成作业刷新,告警与监控需要继续完善
volatilityBalance(); volatilityBalance();
TenantContextHolder.set(1); TenantContextHolder.set(1);
boolean isDone = JobRefeshHandler.refeshJob(jobInfoDetail, isNeedSave()); boolean isDone = JobRefeshHandler.refeshJob(jobInfoDetail, isNeedSave());
JobAlertHandler.getInstance().check(jobInfoDetail); JobAlertHandler.getInstance().check(jobInfoDetail);
JobMetricsHandler.writeFlinkMetrics(jobInfoDetail);
return isDone; return isDone;
} }
......
...@@ -200,7 +200,7 @@ public class Job2MysqlHandler implements JobHandler { ...@@ -200,7 +200,7 @@ public class Job2MysqlHandler implements JobHandler {
.build(); .build();
jobHistoryService.save(jobHistory); jobHistoryService.save(jobHistory);
DaemonFactory.addTask(DaemonTaskConfig.build(FlinkJobTask.TYPE, jobInstance.getId())); DaemonFactory.refeshOraddTask(DaemonTaskConfig.build(FlinkJobTask.TYPE, jobInstance.getId()));
return true; return true;
} }
......
/*
*
* 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.job.handler;
import org.dinky.context.MetricsContextHolder;
import org.dinky.data.constant.NetConstant;
import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.vo.MetricsVO;
import org.dinky.utils.HttpUtils;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.thread.AsyncUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
* The Job Metrics Handler class is used to process operations related to job metrics。
*/
public class JobMetricsHandler {
/**
* The writeFlinkMetrics method is used to write Flink metrics. </br>
* Use concurrent programming to get the data of each indicator through asynchronous requests. </br>
* Send to MetricsContextHolder asynchronously at the end of the method. </br>
* Thus, the operation of writing the Flink indicator is completed. </br>
*
*/
public static void writeFlinkMetrics(JobInfoDetail jobInfoDetail) {
Map<String, Map<String, String>> customMetricsList = jobInfoDetail.getCustomMetricsMap();
String[] jobManagerUrls = jobInfoDetail.getCluster().getJobManagerHost().split(",");
String jobId = jobInfoDetail.getInstance().getJid();
// Create a CompletableFuture array for concurrent acquisition of indicator data
CompletableFuture<?>[] array = customMetricsList.entrySet().stream()
.map((e) -> CompletableFuture.runAsync(
() -> fetchFlinkMetrics(e.getKey(), e.getValue(), jobManagerUrls, jobId)))
.toArray(CompletableFuture[]::new);
// Wait for all Completable Future executions to finish
AsyncUtil.waitAll(array);
MetricsVO metricsVO = new MetricsVO(customMetricsList, jobId, LocalDateTime.now());
MetricsContextHolder.sendAsync(metricsVO);
}
/**
* The fetchFlinkMetrics method is used to obtain Flink indicator data.
*
* @param v metric name
* @param m metric mapping table
* @param urlList List of URLs for JobManager
* @param jid job ID
*/
private static void fetchFlinkMetrics(String v, Map<String, String> m, String[] urlList, String jid) {
if (CollUtil.isEmpty(Arrays.asList(urlList))) {
return;
}
String metricsName = StrUtil.join(",", m.keySet());
String urlParam =
StrFormatter.format("/jobs/{}/vertices/{}/metrics?get={}", jid, v, URLUtil.encode(metricsName));
HttpUtils.asyncRequest(Arrays.asList(urlList), urlParam, NetConstant.READ_TIME_OUT, x -> {
JSONArray array = JSONUtil.parseArray(x.body());
array.forEach(y -> {
JSONObject jsonObject = JSONUtil.parseObj(y);
String id = jsonObject.getStr("id");
String value = jsonObject.getStr("value");
m.put(id, value);
});
});
}
}
...@@ -104,9 +104,9 @@ public class JobRefeshHandler { ...@@ -104,9 +104,9 @@ public class JobRefeshHandler {
jobInstance.setStatus(getJobStatus(jobInfoDetail).getValue()); jobInstance.setStatus(getJobStatus(jobInfoDetail).getValue());
jobInstance.setDuration( jobInstance.setDuration(
job.get(FlinkRestResultConstant.JOB_DURATION).asLong()); job.get(FlinkRestResultConstant.JOB_DURATION).asLong());
jobInstance.setCreateTime(TimeUtil.longToLocalDateTime(startTime)); jobInstance.setCreateTime(TimeUtil.toLocalDateTime(startTime));
// if the job is still running the end-time is -1 // if the job is still running the end-time is -1
jobInstance.setFinishTime(TimeUtil.longToLocalDateTime(endTime)); jobInstance.setFinishTime(TimeUtil.toLocalDateTime(endTime));
} }
jobInstance.setUpdateTime(LocalDateTime.now()); jobInstance.setUpdateTime(LocalDateTime.now());
......
...@@ -49,6 +49,8 @@ public interface JobInstanceService extends ISuperService<JobInstance> { ...@@ -49,6 +49,8 @@ public interface JobInstanceService extends ISuperService<JobInstance> {
JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId); JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId);
void refreshJobByTaskIds(Integer... taskIds);
LineageResult getLineage(Integer id); LineageResult getLineage(Integer id);
JobInstance getJobInstanceByTaskId(Integer id); JobInstance getJobInstanceByTaskId(Integer id);
......
...@@ -23,6 +23,7 @@ import org.dinky.data.dto.MetricsLayoutDTO; ...@@ -23,6 +23,7 @@ import org.dinky.data.dto.MetricsLayoutDTO;
import org.dinky.data.model.Metrics; import org.dinky.data.model.Metrics;
import org.dinky.data.vo.MetricsVO; import org.dinky.data.vo.MetricsVO;
import java.time.LocalDateTime;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -35,7 +36,7 @@ import com.baomidou.mybatisplus.extension.service.IService; ...@@ -35,7 +36,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
public interface MonitorService extends IService<Metrics> { public interface MonitorService extends IService<Metrics> {
List<MetricsVO> getData(Date startTime, Date endTime, List<String> jobIds); List<MetricsVO> getData(Date startTime, Date endTime, List<String> jobIds);
SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate, String layoutName); SseEmitter sendLatestData(SseEmitter sseEmitter, LocalDateTime lastDate, List<String> keys);
SseEmitter sendJvmInfo(SseEmitter sseEmitter); SseEmitter sendJvmInfo(SseEmitter sseEmitter);
...@@ -45,4 +46,6 @@ public interface MonitorService extends IService<Metrics> { ...@@ -45,4 +46,6 @@ public interface MonitorService extends IService<Metrics> {
Map<String, List<Metrics>> getMetricsLayout(); Map<String, List<Metrics>> getMetricsLayout();
List<Metrics> getMetricsLayoutByName(String layoutName); List<Metrics> getMetricsLayoutByName(String layoutName);
List<Metrics> getJobMetrics(Integer taskId);
} }
...@@ -46,10 +46,12 @@ import org.dinky.service.ClusterInstanceService; ...@@ -46,10 +46,12 @@ import org.dinky.service.ClusterInstanceService;
import org.dinky.service.HistoryService; import org.dinky.service.HistoryService;
import org.dinky.service.JobHistoryService; import org.dinky.service.JobHistoryService;
import org.dinky.service.JobInstanceService; import org.dinky.service.JobInstanceService;
import org.dinky.service.MonitorService;
import org.dinky.utils.JSONUtil; import org.dinky.utils.JSONUtil;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -74,6 +76,7 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper, ...@@ -74,6 +76,7 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper,
private final ClusterInstanceService clusterInstanceService; private final ClusterInstanceService clusterInstanceService;
private final ClusterConfigurationService clusterConfigurationService; private final ClusterConfigurationService clusterConfigurationService;
private final JobHistoryService jobHistoryService; private final JobHistoryService jobHistoryService;
private final MonitorService monitorService;
@Override @Override
public JobInstance getByIdWithoutTenant(Integer id) { public JobInstance getByIdWithoutTenant(Integer id) {
...@@ -166,6 +169,14 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper, ...@@ -166,6 +169,14 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper,
JobDataDto jobDataDto = jobHistoryService.getJobHistoryDto(jobInstance.getId()); JobDataDto jobDataDto = jobHistoryService.getJobHistoryDto(jobInstance.getId());
jobInfoDetail.setJobDataDto(jobDataDto); jobInfoDetail.setJobDataDto(jobDataDto);
// Get a list of metrics and deduplicate them based on vertices and metrics
Map<String, Map<String, String>> verticesAndMetricsMap = new ConcurrentHashMap<>();
monitorService.getJobMetrics(jobInstance.getTaskId()).forEach(m -> {
verticesAndMetricsMap.putIfAbsent(m.getVertices(), new ConcurrentHashMap<>());
verticesAndMetricsMap.get(m.getVertices()).put(m.getMetrics(), "");
});
jobInfoDetail.setCustomMetricsMap(verticesAndMetricsMap);
return jobInfoDetail; return jobInfoDetail;
} }
...@@ -173,10 +184,18 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper, ...@@ -173,10 +184,18 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper,
public JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId) { public JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId) {
JobInfoDetail jobInfoDetail = getJobInfoDetail(jobInstanceId); JobInfoDetail jobInfoDetail = getJobInfoDetail(jobInstanceId);
JobRefeshHandler.refeshJob(jobInfoDetail, true); JobRefeshHandler.refeshJob(jobInfoDetail, true);
DaemonFactory.addTask(DaemonTaskConfig.build(FlinkJobTask.TYPE, jobInstanceId)); DaemonFactory.refeshOraddTask(DaemonTaskConfig.build(FlinkJobTask.TYPE, jobInstanceId));
return jobInfoDetail; return jobInfoDetail;
} }
@Override
public void refreshJobByTaskIds(Integer... taskIds) {
for (Integer taskId : taskIds) {
JobInstance instance = getJobInstanceByTaskId(taskId);
refreshJobInfoDetail(instance.getId());
}
}
@Override @Override
public LineageResult getLineage(Integer id) { public LineageResult getLineage(Integer id) {
History history = getJobInfoDetail(id).getHistory(); History history = getJobInfoDetail(id).getHistory();
......
...@@ -19,9 +19,8 @@ ...@@ -19,9 +19,8 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.configure.MetricConfig; import org.dinky.context.MetricsContextHolder;
import org.dinky.data.dto.MetricsLayoutDTO; import org.dinky.data.dto.MetricsLayoutDTO;
import org.dinky.data.enums.MetricsType;
import org.dinky.data.metrics.Jvm; import org.dinky.data.metrics.Jvm;
import org.dinky.data.model.Metrics; import org.dinky.data.model.Metrics;
import org.dinky.data.vo.MetricsVO; import org.dinky.data.vo.MetricsVO;
...@@ -30,7 +29,6 @@ import org.dinky.process.exception.DinkyException; ...@@ -30,7 +29,6 @@ import org.dinky.process.exception.DinkyException;
import org.dinky.service.MonitorService; import org.dinky.service.MonitorService;
import org.dinky.utils.PaimonUtil; import org.dinky.utils.PaimonUtil;
import org.apache.http.util.TextUtils;
import org.apache.paimon.data.BinaryString; import org.apache.paimon.data.BinaryString;
import org.apache.paimon.data.Timestamp; import org.apache.paimon.data.Timestamp;
import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.Predicate;
...@@ -43,7 +41,6 @@ import java.util.Date; ...@@ -43,7 +41,6 @@ import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Queue;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -96,36 +93,8 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -96,36 +93,8 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
} }
@Override @Override
public SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate, String layoutName) { public SseEmitter sendLatestData(SseEmitter sseEmitter, LocalDateTime lastDate, List<String> keys) {
Queue<MetricsVO> metricsQueue = MetricConfig.getMetricsQueue(); MetricsContextHolder.addSse(keys, sseEmitter, lastDate);
scheduleRefreshMonitorDataExecutor.execute(() -> {
try {
LocalDateTime maxDate = DateUtil.toLocalDateTime(lastDate);
while (true) {
if (CollUtil.isEmpty(metricsQueue)) {
continue;
}
for (MetricsVO metrics : metricsQueue) {
if (metrics.getHeartTime().isAfter(maxDate)) {
// 过滤非layoutName指定的Flink监控数据,防止数据过多卡顿
if (!TextUtils.isEmpty(layoutName)
&& !metrics.getModel().equals(MetricsType.LOCAL.getType())
&& !metrics.flinkContent().getLayoutNames().contains(layoutName)) {
continue;
}
sseEmitter.send(metrics);
maxDate = metrics.getHeartTime();
}
}
ThreadUtil.sleep(800);
}
} catch (IOException e) {
sseEmitter.complete();
} catch (Exception e) {
e.printStackTrace();
sseEmitter.complete();
}
});
return sseEmitter; return sseEmitter;
} }
...@@ -177,4 +146,11 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -177,4 +146,11 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
wrapper.lambda().eq(Metrics::getLayoutName, layoutName); wrapper.lambda().eq(Metrics::getLayoutName, layoutName);
return this.baseMapper.selectList(wrapper); return this.baseMapper.selectList(wrapper);
} }
@Override
public List<Metrics> getJobMetrics(Integer taskId) {
QueryWrapper<Metrics> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(Metrics::getTaskId, taskId);
return this.baseMapper.selectList(wrapper);
}
} }
...@@ -37,7 +37,6 @@ public class CheckpointsRule { ...@@ -37,7 +37,6 @@ public class CheckpointsRule {
public CheckpointsRule() { public CheckpointsRule() {
checkpointsCache = CacheBuilder.newBuilder() checkpointsCache = CacheBuilder.newBuilder()
.expireAfterAccess(60, TimeUnit.SECONDS) .expireAfterAccess(60, TimeUnit.SECONDS)
.recordStats()
.build(CacheLoader.from(key -> null)); .build(CacheLoader.from(key -> null));
} }
......
...@@ -33,7 +33,6 @@ public class ExceptionRule { ...@@ -33,7 +33,6 @@ public class ExceptionRule {
public ExceptionRule() { public ExceptionRule() {
hisTime = CacheBuilder.newBuilder() hisTime = CacheBuilder.newBuilder()
.expireAfterAccess(60, TimeUnit.SECONDS) .expireAfterAccess(60, TimeUnit.SECONDS)
.recordStats()
.build(CacheLoader.from(key -> null)); .build(CacheLoader.from(key -> null));
} }
......
...@@ -39,6 +39,10 @@ public class TimeUtil { ...@@ -39,6 +39,10 @@ public class TimeUtil {
return nowStr("yyyy-MM-dd HH:mm:ss"); return nowStr("yyyy-MM-dd HH:mm:ss");
} }
public static Long nowTimestamp() {
return localDateTimeToLong(LocalDateTime.now());
}
/** /**
* Returns the current date and time as a formatted string based on the provided format. * Returns the current date and time as a formatted string based on the provided format.
* *
...@@ -134,7 +138,7 @@ public class TimeUtil { ...@@ -134,7 +138,7 @@ public class TimeUtil {
* *
* @return A LocalDateTime object representing the parsed date and time. * @return A LocalDateTime object representing the parsed date and time.
*/ */
public static LocalDateTime longToLocalDateTime(Long timestamp) { public static LocalDateTime toLocalDateTime(Long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp); Instant instant = Instant.ofEpochMilli(timestamp);
return instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
} }
......
...@@ -87,7 +87,7 @@ public class DaemonFactory { ...@@ -87,7 +87,7 @@ public class DaemonFactory {
* @param config * @param config
* add task * add task
* */ * */
public static void addTask(DaemonTaskConfig config) { public static void refeshOraddTask(DaemonTaskConfig config) {
DefaultThreadPool.getInstance().execute(DaemonTask.build(config)); DefaultThreadPool.getInstance().execute(DaemonTask.build(config));
} }
} }
...@@ -19,7 +19,8 @@ ...@@ -19,7 +19,8 @@
import { import {
buildProjectTree, buildProjectTree,
generateList, getLeafKeyList, generateList,
getLeafKeyList,
getParentKey getParentKey
} from '@/pages/DataStudio/LeftContainer/Project/function'; } from '@/pages/DataStudio/LeftContainer/Project/function';
import { StateType } from '@/pages/DataStudio/model'; import { StateType } from '@/pages/DataStudio/model';
......
import {getTabIcon} from '@/pages/DataStudio/MiddleContainer/function'; import { getTabIcon } from '@/pages/DataStudio/MiddleContainer/function';
import {Catalogue} from '@/types/Studio/data.d'; import { Catalogue } from '@/types/Studio/data.d';
import {searchTreeNode} from '@/utils/function'; import { searchTreeNode } from '@/utils/function';
export const generateList = (data: any, list: any[]) => { export const generateList = (data: any, list: any[]) => {
for (const element of data) { for (const element of data) {
const node = element; const node = element;
const {name, id, parentId, level} = node; const { name, id, parentId, level } = node;
list.push({name, id, key: id, title: name, parentId, level}); list.push({ name, id, key: id, title: name, parentId, level });
if (node.children) { if (node.children) {
generateList(node.children, list); generateList(node.children, list);
} }
...@@ -37,7 +37,7 @@ export const getLeafKeyList = (tree: any): any => { ...@@ -37,7 +37,7 @@ export const getLeafKeyList = (tree: any): any => {
continue; continue;
} }
if (node.children) { if (node.children) {
leafKeyList = leafKeyList.concat(getLeafKeyList(node.children)) leafKeyList = leafKeyList.concat(getLeafKeyList(node.children));
} }
} }
return leafKeyList; return leafKeyList;
...@@ -82,5 +82,4 @@ export const isUDF = (jobType: string) => { ...@@ -82,5 +82,4 @@ export const isUDF = (jobType: string) => {
return jobType === 'Scala' || jobType === 'Python' || jobType === 'Java'; return jobType === 'Scala' || jobType === 'Python' || jobType === 'Java';
}; };
export const buildUDFTree = (data: []) => { export const buildUDFTree = (data: []) => {};
};
...@@ -165,7 +165,17 @@ const DataStudio = (props: any) => { ...@@ -165,7 +165,17 @@ const DataStudio = (props: any) => {
const info = res as { [key: string]: any }; const info = res as { [key: string]: any };
const changed = Object.keys(params.taskData).some((key) => { const changed = Object.keys(params.taskData).some((key) => {
// ignore this property // ignore this property
if (['updateTime', 'createTime', 'jobInstanceId', 'useResult', 'maxRowNum', 'useChangeLog', 'useAutoCancel'].includes(key)) { if (
[
'updateTime',
'createTime',
'jobInstanceId',
'useResult',
'maxRowNum',
'useChangeLog',
'useAutoCancel'
].includes(key)
) {
return false; return false;
} }
......
...@@ -22,7 +22,7 @@ import { JobMetricsItem } from '@/pages/DevOps/JobDetail/data'; ...@@ -22,7 +22,7 @@ import { JobMetricsItem } from '@/pages/DevOps/JobDetail/data';
import { getMetricsData } from '@/pages/DevOps/JobDetail/JobMetrics/service'; import { getMetricsData } from '@/pages/DevOps/JobDetail/JobMetrics/service';
import { DevopsType } from '@/pages/DevOps/JobDetail/model'; import { DevopsType } from '@/pages/DevOps/JobDetail/model';
import { ChartData } from '@/pages/Metrics/Job/data'; import { ChartData } from '@/pages/Metrics/Job/data';
import { FlinkMetricsData, MetricsDataType } from '@/pages/Metrics/Server/data'; import { MetricsDataType } from '@/pages/Metrics/Server/data';
import { getSseData } from '@/services/api'; import { getSseData } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints'; import { API_CONSTANTS } from '@/services/endpoints';
import { connect } from '@@/exports'; import { connect } from '@@/exports';
...@@ -30,22 +30,21 @@ import { Row, Spin } from 'antd'; ...@@ -30,22 +30,21 @@ import { Row, Spin } from 'antd';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
const JobChart = (props: any) => { const JobChart = (props: any) => {
const { jobDetail, metricsTarget, layoutName, timeRange } = props; const { jobDetail, metricsTarget, timeRange } = props;
const [eventSource, setEventSource] = useState<EventSource>(); const [eventSource, setEventSource] = useState<EventSource>();
const [chartDatas, setChartDatas] = useState<Record<string, ChartData[]>>({}); const [chartDatas, setChartDatas] = useState<Record<string, ChartData[]>>({});
const [loading, setLoading] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false);
const sseUrl = `${ const sseUrl = `${API_CONSTANTS.MONITOR_GET_LAST_DATA}?lastTime=${new Date().getTime()}&keys=${
API_CONSTANTS.MONITOR_GET_LAST_DATA jobDetail.instance.jid
}?lastTime=${new Date().getTime()}&layoutName=${layoutName}`; }`;
const dataProcess = (chData: Record<string, ChartData[]>, data: MetricsDataType) => { const dataProcess = (chData: Record<string, ChartData[]>, data: MetricsDataType) => {
if (data.model == 'local') { if (data.model == 'local') {
return; return;
} }
const fd = data.content as FlinkMetricsData; const verticesMap = data.content as Record<string, Record<string, string>>;
const verticesMap = fd.verticesAndMetricsMap;
Object.keys(verticesMap).forEach((verticeId) => Object.keys(verticesMap).forEach((verticeId) =>
Object.keys(verticesMap[verticeId]).forEach((mertics) => { Object.keys(verticesMap[verticeId]).forEach((mertics) => {
const key = `${verticeId}-${mertics}`; const key = `${verticeId}-${mertics}`;
......
...@@ -34,12 +34,9 @@ export type JVMMetric = { ...@@ -34,12 +34,9 @@ export type JVMMetric = {
mem: MemoryType; mem: MemoryType;
time: Date; time: Date;
}; };
export type FlinkMetricsData = {
jobId: string; export type FlinkMetricsData = Record<string, Record<string, string>>;
taskId: number;
urls: string[];
verticesAndMetricsMap: Record<string, Record<string, string>>;
};
export type JvmDataRecord = { export type JvmDataRecord = {
cpuLastValue: number; cpuLastValue: number;
heapMax: number; heapMax: number;
......
...@@ -60,7 +60,7 @@ export default () => { ...@@ -60,7 +60,7 @@ export default () => {
const dataProcess = (data: MetricsDataType) => { const dataProcess = (data: MetricsDataType) => {
switch (data.model) { switch (data.model) {
case 'local': case 'local':
const d = JSON.parse(data.content) as JVMMetric; const d: JVMMetric = data.content;
d.time = data.heartTime; d.time = data.heartTime;
jvmData.push(d); jvmData.push(d);
break; break;
...@@ -100,7 +100,7 @@ export default () => { ...@@ -100,7 +100,7 @@ export default () => {
useEffect(() => { useEffect(() => {
setEventSource( setEventSource(
getSseData(API_CONSTANTS.MONITOR_GET_LAST_DATA + '?lastTime=' + endTime.getTime()) getSseData(`${API_CONSTANTS.MONITOR_GET_LAST_DATA}?lastTime=${endTime.getTime()}&keys=local`)
); );
}, [endTime]); }, [endTime]);
......
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