Unverified Commit 09ea7775 authored by gaoyan's avatar gaoyan Committed by GitHub

Add Devops Metrics Page (#2265)

* add monitor in devops * add job metrics * merge dev * add metrics on devops * add metrics on devops * add metrics filter on devops * add metrics loading on devops * fix bug * fix code style * replace List.of to ColUtil * fix ui bug * Add apache license * fix metrics center * dynamic chart time render * dynamic chart time render * formate code style * add apache licence
parent 18bbb39b
...@@ -52,7 +52,7 @@ public class MetricConfig { ...@@ -52,7 +52,7 @@ public class MetricConfig {
/** 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() throws Exception {
PaimonUtil.writeMetrics(new ArrayList<>(METRICS_QUEUE)); PaimonUtil.writeMetrics(new ArrayList<>(METRICS_QUEUE));
METRICS_QUEUE.clear(); METRICS_QUEUE.clear();
} }
......
...@@ -34,7 +34,9 @@ import org.dinky.service.MonitorService; ...@@ -34,7 +34,9 @@ import org.dinky.service.MonitorService;
import org.dinky.utils.HttpUtils; import org.dinky.utils.HttpUtils;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
...@@ -84,11 +86,13 @@ public class FlinkMetricsIndicator extends BaseSchedule { ...@@ -84,11 +86,13 @@ public class FlinkMetricsIndicator extends BaseSchedule {
.map((f) -> CompletableFuture.runAsync(() -> addFlinkMetrics(f, now))) .map((f) -> CompletableFuture.runAsync(() -> addFlinkMetrics(f, now)))
.toArray(CompletableFuture[]::new); .toArray(CompletableFuture[]::new);
AsyncUtil.waitAll(array); AsyncUtil.waitAll(array);
for (FlinkMetrics flinkMetrics : FLINK_METRICS_DATA_MAP.get(now)) {
MetricsVO metricsVO = new MetricsVO(); MetricsVO metricsVO = new MetricsVO();
metricsVO.setModel("flink"); metricsVO.setModel(flinkMetrics.getJobId());
metricsVO.setHeartTime(now); metricsVO.setHeartTime(now);
metricsVO.setContent(JSONUtil.toJsonStr(FLINK_METRICS_DATA_MAP.get(now))); metricsVO.setContent(flinkMetrics);
MetricConfig.getMetricsQueue().add(metricsVO); MetricConfig.getMetricsQueue().add(metricsVO);
}
FLINK_METRICS_DATA_MAP.remove(now); FLINK_METRICS_DATA_MAP.remove(now);
} }
...@@ -118,15 +122,27 @@ public class FlinkMetricsIndicator extends BaseSchedule { ...@@ -118,15 +122,27 @@ public class FlinkMetricsIndicator extends BaseSchedule {
List<History> historyList = historyService.listByIds( List<History> historyList = historyService.listByIds(
jobInstances.stream().map(JobInstance::getHistoryId).collect(Collectors.toList())); jobInstances.stream().map(JobInstance::getHistoryId).collect(Collectors.toList()));
List<Metrics> metricsList = monitorService.list(); List<Metrics> metricsList = monitorService.list();
Set<Integer> taskIdSet = metricsList.stream().map(Metrics::getTaskId).collect(Collectors.toSet()); // 使用流将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) { for (JobInstance jobInstance : jobInstances) {
Integer taskId = jobInstance.getTaskId(); Integer taskId = jobInstance.getTaskId();
if (!taskIdSet.contains(taskId)) { if (!taskMap.containsKey(taskId)) {
continue; continue;
} }
FlinkMetrics flinkMetrics = new FlinkMetrics(); FlinkMetrics flinkMetrics = new FlinkMetrics();
flinkMetrics.setTaskId(taskId); flinkMetrics.setTaskId(taskId);
flinkMetrics.setJobId(jobInstance.getJid()); flinkMetrics.setJobId(jobInstance.getJid());
flinkMetrics.setLayoutNames(taskMap.get(taskId));
TASK_FLINK_METRICS_MAP.put(taskId, flinkMetrics); TASK_FLINK_METRICS_MAP.put(taskId, flinkMetrics);
metricsList.stream().filter(x -> x.getTaskId().equals(taskId)).forEach(m -> { metricsList.stream().filter(x -> x.getTaskId().equals(taskId)).forEach(m -> {
Map<String, Map<String, String>> verticesAndMetricsMap = flinkMetrics.getVerticesAndMetricsMap(); Map<String, Map<String, String>> verticesAndMetricsMap = flinkMetrics.getVerticesAndMetricsMap();
...@@ -196,8 +212,9 @@ public class FlinkMetricsIndicator extends BaseSchedule { ...@@ -196,8 +212,9 @@ public class FlinkMetricsIndicator extends BaseSchedule {
@Setter @Setter
@Getter @Getter
static class FlinkMetrics { public static class FlinkMetrics {
private String jobId; private String jobId;
private Set<String> layoutNames;
private Integer taskId; private Integer taskId;
private List<String> urls = new CopyOnWriteArrayList<>(); private List<String> urls = new CopyOnWriteArrayList<>();
/** jobId -> metricsId -> metricsValue */ /** jobId -> metricsId -> metricsValue */
......
...@@ -22,6 +22,7 @@ package org.dinky.configure.schedule.metrics; ...@@ -22,6 +22,7 @@ package org.dinky.configure.schedule.metrics;
import org.dinky.configure.MetricConfig; import org.dinky.configure.MetricConfig;
import org.dinky.configure.schedule.BaseSchedule; import org.dinky.configure.schedule.BaseSchedule;
import org.dinky.data.annotation.GaugeM; import org.dinky.data.annotation.GaugeM;
import org.dinky.data.enums.MetricsType;
import org.dinky.data.metrics.BaseMetrics; import org.dinky.data.metrics.BaseMetrics;
import org.dinky.data.metrics.Cpu; import org.dinky.data.metrics.Cpu;
import org.dinky.data.metrics.Jvm; import org.dinky.data.metrics.Jvm;
...@@ -42,7 +43,6 @@ import org.springframework.stereotype.Component; ...@@ -42,7 +43,6 @@ import org.springframework.stereotype.Component;
import cn.hutool.core.annotation.AnnotationUtil; import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
...@@ -90,9 +90,9 @@ public class GatherSysIndicator extends BaseSchedule { ...@@ -90,9 +90,9 @@ public class GatherSysIndicator extends BaseSchedule {
metricsTotal.setMem(Mem.of()); metricsTotal.setMem(Mem.of());
MetricsVO metrics = new MetricsVO(); MetricsVO metrics = new MetricsVO();
metrics.setContent(JSONUtil.toJsonStr(metricsTotal)); metrics.setContent(metricsTotal);
metrics.setHeartTime(now); metrics.setHeartTime(now);
metrics.setModel("local"); metrics.setModel(MetricsType.LOCAL.getType());
MetricConfig.getMetricsQueue().add(metrics); MetricConfig.getMetricsQueue().add(metrics);
log.debug("Collecting jvm information ends."); log.debug("Collecting jvm information ends.");
......
...@@ -154,4 +154,21 @@ public class JobInstanceController { ...@@ -154,4 +154,21 @@ public class JobInstanceController {
public Result<String> getTaskManagerLog(@RequestParam String address, @RequestParam String containerId) { public Result<String> getTaskManagerLog(@RequestParam String address, @RequestParam String containerId) {
return Result.succeed(FlinkAPI.build(address).getTaskManagerLog(containerId), ""); return Result.succeed(FlinkAPI.build(address).getTaskManagerLog(containerId), "");
} }
@GetMapping("/getJobMetricsItems")
@ApiOperation(" getJobMetricsItems List")
public Result<JsonNode> getJobMetricsItems(
@RequestParam String address, @RequestParam String jobId, @RequestParam String verticeId) {
return Result.succeed(FlinkAPI.build(address).getJobMetricesItems(jobId, verticeId));
}
@GetMapping("/getJobMetricsData")
@ApiOperation(" getJobMetrics Data")
public Result<JsonNode> getJobMetricsItems(
@RequestParam String address,
@RequestParam String jobId,
@RequestParam String verticeId,
@RequestParam String metrics) {
return Result.succeed(FlinkAPI.build(address).getJobMetricesData(jobId, verticeId, metrics));
}
} }
...@@ -19,21 +19,29 @@ ...@@ -19,21 +19,29 @@
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;
import org.dinky.data.enums.MetricsType;
import org.dinky.data.model.JobInstance;
import org.dinky.data.model.Metrics; import org.dinky.data.model.Metrics;
import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.vo.MetricsVO; import org.dinky.data.vo.MetricsVO;
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 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 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.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -41,6 +49,10 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -41,6 +49,10 @@ import org.springframework.web.bind.annotation.RequestParam;
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 com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil; 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;
...@@ -54,30 +66,57 @@ import lombok.extern.slf4j.Slf4j; ...@@ -54,30 +66,57 @@ import lombok.extern.slf4j.Slf4j;
@RequestMapping("/api/monitor") @RequestMapping("/api/monitor")
@RequiredArgsConstructor @RequiredArgsConstructor
public class MonitorController { public class MonitorController {
private final MonitorService monitorService; private final MonitorService monitorService;
private final JobInstanceService jobInstanceService;
@Autowired
private FlinkMetricsIndicator flinkMetricsIndicator;
@GetMapping("/getSysData") @GetMapping("/getSysData")
@ApiOperation("Get System Data") @ApiOperation("Get System Data")
public Result<List<MetricsVO>> getData(@RequestParam Long startTime, Long endTime) { public Result<List<MetricsVO>> getData(@RequestParam Long startTime, Long endTime) {
List<MetricsVO> data = monitorService.getData(
DateUtil.date(startTime),
DateUtil.date(Opt.ofNullable(endTime).orElse(DateUtil.date().getTime())),
CollUtil.newArrayList(MetricsType.LOCAL.getType()));
return Result.succeed(data);
}
@GetMapping("/getFlinkData")
@ApiOperation("Get Flink Data")
public Result<List<MetricsVO>> getFlinkData(@RequestParam Long startTime, Long endTime, String taskIds) {
JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
ObjectNode para = nodeFactory.objectNode();
para.put("isHistory", false);
para.put("taskId", taskIds);
ProTableResult<JobInstance> jobInstanceProTableResult = jobInstanceService.listJobInstances(para);
List<String> jids = jobInstanceProTableResult.getData().stream()
.map(JobInstance::getJid)
.collect(Collectors.toList());
return Result.succeed(monitorService.getData( return Result.succeed(monitorService.getData(
DateUtil.date(startTime), DateUtil.date(startTime),
DateUtil.date(Opt.ofNullable(endTime).orElse(DateUtil.date().getTime())))); DateUtil.date(Opt.ofNullable(endTime).orElse(DateUtil.date().getTime())),
jids));
} }
@GetMapping(value = "/getLastUpdateData", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @GetMapping(value = "/getLastUpdateData", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Get Last Update Data") @ApiOperation("Get Last Update Data")
public SseEmitter getLastUpdateData(Long lastTime) { public SseEmitter getLastUpdateData(Long lastTime, String layoutName) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30)); SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
return monitorService.sendLatestData( return monitorService.sendLatestData(
emitter, emitter,
DateUtil.date(Opt.ofNullable(lastTime).orElse(DateUtil.date().getTime()))); DateUtil.date(Opt.ofNullable(lastTime).orElse(DateUtil.date().getTime())),
layoutName);
} }
@PutMapping("/saveFlinkMetrics") @PutMapping("/saveFlinkMetrics/{layout}")
@ApiOperation("Save Flink Metrics") @ApiOperation("Save Flink Metrics")
@Log(title = "Save Flink Metrics", businessType = BusinessType.INSERT) @Log(title = "Save Flink Metrics", businessType = BusinessType.INSERT)
public Result<Void> saveFlinkMetricLayout(@RequestBody List<MetricsLayoutDTO> metricsList) { public Result<Void> saveFlinkMetricLayout(
monitorService.saveFlinkMetricLayout(metricsList); @PathVariable(value = "layout") String layoutName, @RequestBody List<MetricsLayoutDTO> metricsList) {
monitorService.saveFlinkMetricLayout(layoutName, metricsList);
flinkMetricsIndicator.getAndCheckFlinkUrlAvailable();
return Result.succeed(); return Result.succeed();
} }
...@@ -86,4 +125,10 @@ public class MonitorController { ...@@ -86,4 +125,10 @@ public class MonitorController {
public Result<Map<String, List<Metrics>>> getMetricsLayout() { public Result<Map<String, List<Metrics>>> getMetricsLayout() {
return Result.succeed(monitorService.getMetricsLayout()); return Result.succeed(monitorService.getMetricsLayout());
} }
@GetMapping("/getMetricsLayoutByName")
@ApiOperation("Get Metrics Layout by task to Display")
public Result<List<Metrics>> getMetricsLayoutByName(@RequestParam String layoutName) {
return Result.succeed(monitorService.getMetricsLayoutByName(layoutName));
}
} }
...@@ -49,7 +49,8 @@ public class SseController { ...@@ -49,7 +49,8 @@ public class SseController {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30)); SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
return monitorService.sendLatestData( return monitorService.sendLatestData(
emitter, emitter,
DateUtil.date(Opt.ofNullable(lastTime).orElse(DateUtil.date().getTime()))); 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)
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.data.enums;
public enum MetricsType {
LOCAL("local"),
FLINK("flink");
private final String type;
public String getType() {
return this.type;
}
MetricsType(String type) {
this.type = type;
}
}
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.data.vo; package org.dinky.data.vo;
import org.dinky.configure.schedule.metrics.FlinkMetricsIndicator;
import org.dinky.data.metrics.MetricsTotal; import org.dinky.data.metrics.MetricsTotal;
import java.time.LocalDateTime; import java.time.LocalDateTime;
...@@ -29,8 +30,16 @@ import lombok.Setter; ...@@ -29,8 +30,16 @@ import lombok.Setter;
@Getter @Getter
@Setter @Setter
public class MetricsVO { public class MetricsVO {
private String content; private Object content;
private MetricsTotal metricsTotal; private MetricsTotal metricsTotal;
private String model; private String model;
private LocalDateTime heartTime; private LocalDateTime heartTime;
public FlinkMetricsIndicator.FlinkMetrics flinkContent() {
if (content instanceof FlinkMetricsIndicator.FlinkMetrics) {
return (FlinkMetricsIndicator.FlinkMetrics) content;
} else {
return new FlinkMetricsIndicator.FlinkMetrics();
}
}
} }
...@@ -27,18 +27,22 @@ import java.util.Date; ...@@ -27,18 +27,22 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.baomidou.mybatisplus.extension.service.IService; 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<MetricsVO> getData(Date startTime, Date endTime, List<String> jobIds);
SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate); SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate, String layoutName);
SseEmitter sendJvmInfo(SseEmitter sseEmitter); SseEmitter sendJvmInfo(SseEmitter sseEmitter);
void saveFlinkMetricLayout(List<MetricsLayoutDTO> metricsList); @Transactional(rollbackFor = Exception.class)
void saveFlinkMetricLayout(String layout, List<MetricsLayoutDTO> metricsList);
Map<String, List<Metrics>> getMetricsLayout(); Map<String, List<Metrics>> getMetricsLayout();
List<Metrics> getMetricsLayoutByName(String layoutName);
} }
...@@ -21,6 +21,7 @@ package org.dinky.service.impl; ...@@ -21,6 +21,7 @@ package org.dinky.service.impl;
import org.dinky.configure.MetricConfig; import org.dinky.configure.MetricConfig;
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;
...@@ -29,6 +30,8 @@ import org.dinky.process.exception.DinkyException; ...@@ -29,6 +30,8 @@ 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.Timestamp; import org.apache.paimon.data.Timestamp;
import org.apache.paimon.predicate.Predicate; import org.apache.paimon.predicate.Predicate;
import org.apache.paimon.predicate.PredicateBuilder; import org.apache.paimon.predicate.PredicateBuilder;
...@@ -49,6 +52,7 @@ import org.springframework.stereotype.Service; ...@@ -49,6 +52,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
...@@ -56,6 +60,7 @@ import cn.hutool.core.collection.CollUtil; ...@@ -56,6 +60,7 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
...@@ -65,7 +70,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -65,7 +70,7 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
private final Executor scheduleRefreshMonitorDataExecutor; private final Executor scheduleRefreshMonitorDataExecutor;
@Override @Override
public List<MetricsVO> getData(Date startTime, Date endTime) { public List<MetricsVO> getData(Date startTime, Date endTime, List<String> jobIds) {
endTime = Opt.ofNullable(endTime).orElse(DateUtil.date()); endTime = Opt.ofNullable(endTime).orElse(DateUtil.date());
Timestamp startTS = Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(startTime)); Timestamp startTS = Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(startTime));
Timestamp endTS = Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(endTime)); Timestamp endTS = Timestamp.fromLocalDateTime(DateUtil.toLocalDateTime(endTime));
...@@ -73,10 +78,12 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -73,10 +78,12 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
if (endTime.compareTo(startTime) < 1) { if (endTime.compareTo(startTime) < 1) {
throw new DinkyException("The end date must be greater than the start date!"); throw new DinkyException("The end date must be greater than the start date!");
} }
Function<PredicateBuilder, List<Predicate>> filter = p -> { Function<PredicateBuilder, List<Predicate>> filter = p -> {
Predicate greaterOrEqual = p.greaterOrEqual(0, startTS); Predicate greaterOrEqual = p.greaterOrEqual(0, startTS);
Predicate lessOrEqual = p.lessOrEqual(0, endTS); Predicate lessOrEqual = p.lessOrEqual(0, endTS);
Predicate local = p.equal(2, "local"); Predicate local =
p.in(1, jobIds.stream().map(BinaryString::fromString).collect(Collectors.toList()));
return CollUtil.newArrayList(local, greaterOrEqual, lessOrEqual); return CollUtil.newArrayList(local, greaterOrEqual, lessOrEqual);
}; };
List<MetricsVO> metricsVOList = List<MetricsVO> metricsVOList =
...@@ -84,11 +91,12 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -84,11 +91,12 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
return metricsVOList.stream() return metricsVOList.stream()
.filter(x -> x.getHeartTime().isAfter(startTS.toLocalDateTime())) .filter(x -> x.getHeartTime().isAfter(startTS.toLocalDateTime()))
.filter(x -> x.getHeartTime().isBefore(endTS.toLocalDateTime())) .filter(x -> x.getHeartTime().isBefore(endTS.toLocalDateTime()))
.peek(vo -> vo.setContent(new JSONObject(vo.getContent().toString())))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override @Override
public SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate) { public SseEmitter sendLatestData(SseEmitter sseEmitter, Date lastDate, String layoutName) {
Queue<MetricsVO> metricsQueue = MetricConfig.getMetricsQueue(); Queue<MetricsVO> metricsQueue = MetricConfig.getMetricsQueue();
scheduleRefreshMonitorDataExecutor.execute(() -> { scheduleRefreshMonitorDataExecutor.execute(() -> {
try { try {
...@@ -99,6 +107,12 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -99,6 +107,12 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
} }
for (MetricsVO metrics : metricsQueue) { for (MetricsVO metrics : metricsQueue) {
if (metrics.getHeartTime().isAfter(maxDate)) { 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); sseEmitter.send(metrics);
maxDate = metrics.getHeartTime(); maxDate = metrics.getHeartTime();
} }
...@@ -135,7 +149,10 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -135,7 +149,10 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void saveFlinkMetricLayout(List<MetricsLayoutDTO> metricsList) { public void saveFlinkMetricLayout(String layout, List<MetricsLayoutDTO> metricsList) {
QueryWrapper<Metrics> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(Metrics::getLayoutName, layout);
remove(wrapper);
if (CollUtil.isEmpty(metricsList)) { if (CollUtil.isEmpty(metricsList)) {
return; return;
} }
...@@ -153,4 +170,11 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -153,4 +170,11 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
}); });
return result; return result;
} }
@Override
public List<Metrics> getMetricsLayoutByName(String layoutName) {
QueryWrapper<Metrics> wrapper = new QueryWrapper<>();
wrapper.lambda().eq(Metrics::getLayoutName, layoutName);
return this.baseMapper.selectList(wrapper);
}
} }
...@@ -61,6 +61,7 @@ import cn.hutool.core.date.TimeInterval; ...@@ -61,6 +61,7 @@ import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil; import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
...@@ -113,9 +114,9 @@ public class PaimonUtil { ...@@ -113,9 +114,9 @@ public class PaimonUtil {
BinaryRow row = new BinaryRow(30); BinaryRow row = new BinaryRow(30);
BinaryRowWriter writer = new BinaryRowWriter(row); BinaryRowWriter writer = new BinaryRowWriter(row);
writer.writeTimestamp(0, Timestamp.fromLocalDateTime(now), 0); writer.writeTimestamp(0, Timestamp.fromLocalDateTime(now), 3);
writer.writeString(1, BinaryString.fromString(metrics.getModel())); writer.writeString(1, BinaryString.fromString(metrics.getModel()));
writer.writeString(2, BinaryString.fromString(metrics.getContent())); writer.writeString(2, BinaryString.fromString(JSONUtil.toJsonStr(metrics.getContent())));
writer.writeString(3, BinaryString.fromString(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))); writer.writeString(3, BinaryString.fromString(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))));
write.write(row); write.write(row);
} }
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
and dh.type = #{param.type} and dh.type = #{param.type}
</if> </if>
<if test='param.taskId!=null and param.taskId!=""'> <if test='param.taskId!=null and param.taskId!=""'>
and a.task_id = #{param.taskId} and a.task_id in (${param.taskId})
</if> </if>
<if test='param.step!=null and param.step!=""'> <if test='param.step!=null and param.step!=""'>
and a.step = #{param.step} and a.step = #{param.step}
......
...@@ -39,6 +39,7 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -39,6 +39,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method; import cn.hutool.http.Method;
...@@ -380,4 +381,17 @@ public class FlinkAPI { ...@@ -380,4 +381,17 @@ public class FlinkAPI {
public JsonNode getTaskManagerThreadDump(String containerId) { public JsonNode getTaskManagerThreadDump(String containerId) {
return get(FlinkRestAPIConstant.TASK_MANAGER + containerId + FlinkRestAPIConstant.THREAD_DUMP); return get(FlinkRestAPIConstant.TASK_MANAGER + containerId + FlinkRestAPIConstant.THREAD_DUMP);
} }
public JsonNode getJobMetricesItems(String jobId, String verticeId) {
return get(FlinkRestAPIConstant.JOBS
+ jobId
+ FlinkRestAPIConstant.VERTICES
+ verticeId
+ FlinkRestAPIConstant.METRICS);
}
public JsonNode getJobMetricesData(String jobId, String verticeId, String metrics) {
return get(FlinkRestAPIConstant.JOBS + jobId + FlinkRestAPIConstant.VERTICES + verticeId
+ FlinkRestAPIConstant.METRICS + "?get=" + URLEncodeUtil.encode(metrics));
}
} }
...@@ -33,6 +33,7 @@ public final class FlinkRestAPIConstant { ...@@ -33,6 +33,7 @@ public final class FlinkRestAPIConstant {
public static final String CONFIG = "/config"; public static final String CONFIG = "/config";
public static final String JOBS = "jobs/"; public static final String JOBS = "jobs/";
public static final String VERTICES = "/vertices/";
public static final String JOBSLIST = "jobs/overview"; public static final String JOBSLIST = "jobs/overview";
......
/*
*
* 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 { ChartData } from '@/pages/Metrics/Job/data';
import { differenceDays } from '@/utils/function';
import { Line } from '@ant-design/charts';
import { ExpandOutlined } from '@ant-design/icons';
import { ProCard, StatisticCard } from '@ant-design/pro-components';
import { Col, Modal, Radio } from 'antd';
import Paragraph from 'antd/es/typography/Paragraph';
import { useState } from 'react';
type extraRenderType = 'size' | 'agrandir';
type FlinkChartProps = {
title: string;
data?: ChartData[];
chartType?: string;
chartSize?: string;
extraType?: extraRenderType;
onChangeJobState?: (chartSize: string, chartType: string) => void;
chartOptions?: any;
};
const FlinkChart = (props: FlinkChartProps) => {
const {
data = [],
title,
chartType = 'Chart',
chartSize = '25%',
extraType = 'agrandir',
chartOptions = {},
onChangeJobState = () => {}
} = props;
const [chartProps, setChartProps] = useState({
chartType: chartType,
chartSize: chartSize,
titleWidth: '100%',
extraType: extraType
});
const getLineTimeMask = (charData: ChartData[]) => {
if (!charData || charData.length <= 1) {
return 'HH:mm:ss';
}
const t1 = charData[charData.length - 1].time;
const t2 = charData[0].time;
const duration = Math.abs(differenceDays(t1, t2));
console.log(duration);
if (duration <= 0) {
return 'HH:mm:ss';
} else if (duration >= 1 && duration < 7) {
return 'MM-DD HH:mm';
} else {
return 'MM-DD';
}
};
const config = {
animation: false,
data: data,
xField: 'time',
yField: 'value',
xAxis: {
type: 'time',
mask: getLineTimeMask(data),
tickCount: 40
},
...chartOptions
};
const [isModalOpen, setIsModalOpen] = useState(false);
/**
* render chart type radio
*/
const renderChartNumericRadio = () => [
<Radio.Group
key={'chartRadioKey'}
size='small'
buttonStyle='solid'
value={chartProps.chartType}
onChange={(e) => {
setChartProps((prevState) => ({ ...prevState, chartType: e.target.value }));
onChangeJobState(chartProps.chartSize, e.target.value);
}}
style={{ textAlign: 'left', paddingLeft: '5%' }}
>
<Radio.Button value='Chart'>Chart</Radio.Button>
<Radio.Button value='Numeric'>Numeric</Radio.Button>
</Radio.Group>
];
const renderMetricsChartTitle = (metricsId: string, titleWidth: string | number) => {
return (
<Paragraph style={{ width: titleWidth }} code ellipsis={{ tooltip: true }}>
{metricsId}
</Paragraph>
);
};
/**
* render chart size radio
* @returns {JSX.Element}
*/
const renderChartExtra = () => {
if (chartProps.extraType == 'size') {
return (
<Radio.Group
className={'radio-group-chart'}
size='small'
buttonStyle='solid'
value={chartProps.chartSize}
onChange={(e) => {
setChartProps((prevState) => ({
...prevState,
titleWidth: e.target.value == '25%' ? '50%' : '100%',
chartSize: e.target.value
}));
onChangeJobState(e.target.value, chartProps.chartType);
}}
style={{ paddingRight: '5%', paddingTop: '2%' }}
>
<Radio.Button value={'50%'}>Big</Radio.Button>
<Radio.Button value={'25%'}>Small</Radio.Button>
</Radio.Group>
);
} else {
return <ExpandOutlined onClick={() => setIsModalOpen(true)} />;
}
};
return (
<Col span={chartProps.chartSize == '25%' ? 6 : 12}>
<ProCard
bodyStyle={{ textAlign: 'center' }}
colSpan={chartProps.chartSize}
bordered
title={renderMetricsChartTitle(title, chartProps.titleWidth)}
extra={renderChartExtra()}
actions={renderChartNumericRadio()}
style={{ height: 240 }}
>
{chartProps.chartType == 'Chart' ? (
<Line {...config} />
) : (
<StatisticCard.Group
style={{
minHeight: '100%',
minWidth: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<StatisticCard statistic={{ value: data ? data[data.length - 1]?.value : 0 }} />
</StatisticCard.Group>
)}
</ProCard>
<Modal
title={title}
open={isModalOpen}
onCancel={() => setIsModalOpen(false)}
footer={null}
width={'100%'}
>
<Line {...config} forceFit={false} height={700} />
</Modal>
</Col>
);
};
export default FlinkChart;
...@@ -159,6 +159,10 @@ export default { ...@@ -159,6 +159,10 @@ export default {
'devops.jobinfo.ck.recovery.failed': 'Recovery job failed', 'devops.jobinfo.ck.recovery.failed': 'Recovery job failed',
'devops.jobinfo.ck.recovery.recoveryTo': 'Recovery Here', 'devops.jobinfo.ck.recovery.recoveryTo': 'Recovery Here',
'devops.jobinfo.metrics.configMetrics': 'Metrics Config',
'devops.jobinfo.metrics.metricsItems': 'Metrics Items',
'devops.jobinfo.metrics.selected': 'Selected',
'devops.baseinfo.taskid': 'Task Id', 'devops.baseinfo.taskid': 'Task Id',
'devops.baseinfo.name': 'Job Name', 'devops.baseinfo.name': 'Job Name',
'devops.baseinfo.status': 'Status', 'devops.baseinfo.status': 'Status',
...@@ -923,9 +927,12 @@ export default { ...@@ -923,9 +927,12 @@ export default {
'metrics.filter.60seconds': '60 Seconds', 'metrics.filter.60seconds': '60 Seconds',
'metrics.filter.5minutes': '5 Minutes', 'metrics.filter.5minutes': '5 Minutes',
'metrics.filter.10minutes': '10 Minutes', 'metrics.filter.10minutes': '10 Minutes',
'metrics.filter.real': 'Real Time',
'metrics.filter.1hour': '1 Hours', 'metrics.filter.1hour': '1 Hours',
'metrics.filter.2hours': '2 Hours', 'metrics.filter.2hours': '2 Hours',
'metrics.filter.5hours': '5 Hours', 'metrics.filter.5hours': '5 Hours',
'metrics.filter.1day': 'one day',
'metrics.filter.1week': 'one week',
'metrics.filter.custom': 'Custom', 'metrics.filter.custom': 'Custom',
'metrics.filter.custom.range': 'DateTime Range', 'metrics.filter.custom.range': 'DateTime Range',
......
...@@ -155,6 +155,10 @@ export default { ...@@ -155,6 +155,10 @@ export default {
'devops.jobinfo.ck.recovery.failed': '恢复作业失败', 'devops.jobinfo.ck.recovery.failed': '恢复作业失败',
'devops.jobinfo.ck.recovery.recoveryTo': '此处恢复', 'devops.jobinfo.ck.recovery.recoveryTo': '此处恢复',
'devops.jobinfo.metrics.configMetrics': '任务监控配置',
'devops.jobinfo.metrics.metricsItems': '监控项列表',
'devops.jobinfo.metrics.selected': '已选择',
'devops.baseinfo.taskid': '任务ID', 'devops.baseinfo.taskid': '任务ID',
'devops.baseinfo.name': '任务名称', 'devops.baseinfo.name': '任务名称',
'devops.baseinfo.status': '状态', 'devops.baseinfo.status': '状态',
...@@ -895,9 +899,12 @@ export default { ...@@ -895,9 +899,12 @@ export default {
'metrics.filter.60seconds': '60秒', 'metrics.filter.60seconds': '60秒',
'metrics.filter.5minutes': '5分钟', 'metrics.filter.5minutes': '5分钟',
'metrics.filter.10minutes': '10分钟', 'metrics.filter.10minutes': '10分钟',
'metrics.filter.real': '实时',
'metrics.filter.1hour': '1小时', 'metrics.filter.1hour': '1小时',
'metrics.filter.2hours': '2小时', 'metrics.filter.2hours': '2小时',
'metrics.filter.5hours': '5小时', 'metrics.filter.5hours': '5小时',
'metrics.filter.1day': '近一天',
'metrics.filter.1week': '近一周',
'metrics.filter.custom': '自定义', 'metrics.filter.custom': '自定义',
'metrics.filter.custom.range': '日期时间范围', 'metrics.filter.custom.range': '日期时间范围',
// flink job // flink job
......
/*
*
* 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 FlinkChart from '@/components/FlinkChart';
import { JobMetricsItem } from '@/pages/DevOps/JobDetail/data';
import { getMetricsData } from '@/pages/DevOps/JobDetail/JobMetrics/service';
import { DevopsType } from '@/pages/DevOps/JobDetail/model';
import { ChartData } from '@/pages/Metrics/Job/data';
import { FlinkMetricsData, MetricsDataType } from '@/pages/Metrics/Server/data';
import { getSseData } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
import { connect } from '@@/exports';
import { Row, Spin } from 'antd';
import { useEffect, useState } from 'react';
const JobChart = (props: any) => {
const { jobDetail, metricsTarget, layoutName, timeRange } = props;
const [eventSource, setEventSource] = useState<EventSource>();
const [chartDatas, setChartDatas] = useState<Record<string, ChartData[]>>({});
const [loading, setLoading] = useState<boolean>(false);
const sseUrl = `${
API_CONSTANTS.MONITOR_GET_LAST_DATA
}?lastTime=${new Date().getTime()}&layoutName=${layoutName}`;
const dataProcess = (chData: Record<string, ChartData[]>, data: MetricsDataType) => {
if (data.model == 'local') {
return;
}
const fd = data.content as FlinkMetricsData;
const verticesMap = fd.verticesAndMetricsMap;
Object.keys(verticesMap).forEach((verticeId) =>
Object.keys(verticesMap[verticeId]).forEach((mertics) => {
const key = `${verticeId}-${mertics}`;
const value = {
time: data.heartTime,
value: verticesMap[verticeId][mertics]
};
if (!(key in chData)) {
chData[key] = [];
}
chData[key].push(value);
})
);
setChartDatas(chData);
};
useEffect(() => {
setLoading(true);
getMetricsData({
startTime: timeRange.startTime,
endTime: timeRange.endTime,
taskIds: jobDetail.instance.taskId
}).then((result) => {
setLoading(false);
const chData = {};
(result as MetricsDataType[]).forEach((d) => dataProcess(chData, d));
if (!timeRange.isReal) {
eventSource?.close();
setEventSource(undefined);
} else {
if (!eventSource) {
setEventSource(getSseData(sseUrl));
}
}
});
}, [timeRange]);
useEffect(() => {
if (eventSource && timeRange.isReal) {
eventSource.onmessage = (e) => {
let result = JSON.parse(e.data);
dataProcess(chartDatas, result);
};
}
}, [eventSource]);
const renderMetricsCardList = (
metricsList: Record<string, JobMetricsItem[]>,
chartData: Record<string, ChartData[]>
) => {
let datas: JobMetricsItem[] = [];
for (let [key, value] of Object.entries(metricsList)) {
datas = [...datas, ...value];
}
return datas?.map((metricsItem) => {
const key = `${metricsItem.vertices}-${metricsItem.metrics}`;
return (
<FlinkChart
key={key}
chartSize={metricsItem.showSize}
chartType={metricsItem.showType}
title={metricsItem.metrics}
data={chartData[key] ?? []}
/>
);
});
};
return (
<Spin spinning={loading}>
<Row gutter={[8, 16]}>{renderMetricsCardList(metricsTarget ?? {}, chartDatas)}</Row>
</Spin>
);
};
export default connect(({ Devops }: { Devops: DevopsType }) => ({
jobDetail: Devops.jobInfoDetail,
metricsTarget: Devops.metrics.jobMetricsTarget,
layoutName: Devops.metrics.layoutName
}))(JobChart);
/*
*
* 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 { JobMetricsItem } from '@/pages/DevOps/JobDetail/data';
import MonitorConfigTab from '@/pages/DevOps/JobDetail/JobMetrics/MetricsFilter/MetricsConfigTab';
import { putMetricsLayout } from '@/pages/DevOps/JobDetail/JobMetrics/service';
import { DevopsType } from '@/pages/DevOps/JobDetail/model';
import { l } from '@/utils/intl';
import { ModalForm } from '@ant-design/pro-components';
import { Button, Tabs } from 'antd';
import { connect } from 'umi';
const MetricsConfigForm = (props: any) => {
const { dispatch, jobDetail, metricsTarget, layoutName } = props;
const saveJobMetrics = async () => {
let params: JobMetricsItem[] = [];
for (let value of Object.values(metricsTarget)) {
// @ts-ignore
params.push(...value);
}
await putMetricsLayout(layoutName, params);
dispatch({
type: 'Devops/queryMetricsTarget',
payload: { layoutName: layoutName }
});
return true;
};
const onValueChange = (vertice: any, keys: string[]) => {
const data = keys.map((key) => ({
taskId: jobDetail.history.taskId,
vertices: vertice.id,
metrics: key,
title: vertice.name,
layoutName: layoutName,
showType: 'Chart',
showSize: '25%'
}));
dispatch({
type: 'Devops/updateMetricsTarget',
payload: { verticeId: vertice.id, data: data }
});
};
const itemTabs = jobDetail?.jobHistory?.job?.vertices?.map((item: any) => {
return {
key: item.id,
label: item.name,
children: <MonitorConfigTab vertice={item} onValueChange={onValueChange} />
};
});
return (
<ModalForm
width={1000}
layout={'horizontal'}
title={l('devops.jobinfo.metrics.configMetrics')}
trigger={<Button type='primary'>{l('devops.jobinfo.metrics.configMetrics')}</Button>}
onFinish={async () => await saveJobMetrics()}
>
<Tabs items={itemTabs} />
</ModalForm>
);
};
export default connect(({ Devops }: { Devops: DevopsType }) => ({
jobDetail: Devops.jobInfoDetail,
metricsTarget: Devops.metrics.jobMetricsTarget,
layoutName: Devops.metrics.layoutName
}))(MetricsConfigForm);
/*
*
* 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 { JobMetricsItem } from '@/pages/DevOps/JobDetail/data';
import { DevopsType } from '@/pages/DevOps/JobDetail/model';
import { API_CONSTANTS } from '@/services/endpoints';
import { l } from '@/utils/intl';
import { connect, useRequest } from '@@/exports';
import { Transfer } from 'antd';
const MetricsConfigTab = (props: any) => {
const { vertice, onValueChange, jobDetail, metricsTarget } = props;
const jobManagerUrl = jobDetail.cluster?.jobManagerHost;
const jobId = jobDetail.jobHistory.job?.jid;
const { data } = useRequest({
url: API_CONSTANTS.GET_JOB_MERTICE_ITEMS,
params: { address: jobManagerUrl, jobId: jobId, verticeId: vertice.id }
});
const targetKeys = (data: []) => data.map((i: JobMetricsItem) => i.metrics);
return (
<>
<Transfer
showSearch={true}
dataSource={data ?? []}
titles={[l('devops.jobinfo.metrics.metricsItems'), l('devops.jobinfo.metrics.selected')]}
targetKeys={targetKeys(metricsTarget[vertice.id] ?? [])}
onChange={(tgk) => onValueChange(vertice, tgk)}
rowKey={(item) => item.id}
render={(item) => item.id}
listStyle={{ width: '42vh', height: '50vh' }}
oneWay
/>
</>
);
};
export default connect(({ Devops }: { Devops: DevopsType }) => ({
jobDetail: Devops.jobInfoDetail,
metricsTarget: Devops.metrics.jobMetricsTarget,
layoutName: Devops.metrics.layoutName
}))(MetricsConfigTab);
/*
*
* 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 { MetricsTimeFilter } from '@/pages/DevOps/JobDetail/data';
import MonitorConfigForm from '@/pages/DevOps/JobDetail/JobMetrics/MetricsFilter/MetricsConfigForm';
import { getSubMinTime } from '@/pages/Metrics/Server/function';
import { l } from '@/utils/intl';
import { DatePicker, Radio, Space } from 'antd';
const { RangePicker } = DatePicker;
type TimeSelectProps = {
onTimeSelect: (filter: MetricsTimeFilter) => void;
};
const MetricsFilter = (props: TimeSelectProps) => {
const { onTimeSelect } = props;
const onTimeSelectChange = (isReal: boolean, startTime: number, endTime?: number) =>
onTimeSelect({
startTime: startTime,
endTime: endTime,
isReal: isReal
});
const onTimeRadioChange = (e: any) => {
const dateKey = e.target.value;
let filter: MetricsTimeFilter = {
startTime: new Date().getTime(),
endTime: new Date().getTime(),
isReal: false
};
switch (dateKey) {
case 'real':
return onTimeSelectChange(true, getSubMinTime(new Date(), 1).getTime());
case '1h':
return onTimeSelectChange(false, getSubMinTime(new Date(), 60).getTime());
case '24h':
return onTimeSelectChange(false, getSubMinTime(new Date(), 1440).getTime());
case '7d':
return onTimeSelectChange(false, getSubMinTime(new Date(), 10080).getTime());
}
onTimeSelect(filter);
};
return (
<Space style={{ marginBottom: 20 }}>
<Radio.Group defaultValue={'real'} onChange={(v) => onTimeRadioChange(v)}>
<Radio.Button value='real'>{l('metrics.filter.real')}</Radio.Button>
<Radio.Button value='1h'>{l('metrics.filter.1hour')}</Radio.Button>
<Radio.Button value='24h'>{l('metrics.filter.1day')}</Radio.Button>
<Radio.Button value='7d'>{l('metrics.filter.1week')}</Radio.Button>
</Radio.Group>
<RangePicker
showTime
onChange={(_, time) =>
onTimeSelectChange(false, new Date(time[0]).getTime(), new Date(time[1]).getTime())
}
/>
<MonitorConfigForm />
</Space>
);
};
export default MetricsFilter;
/*
*
* 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 { MetricsTimeFilter } from '@/pages/DevOps/JobDetail/data';
import MetricsFilter from '@/pages/DevOps/JobDetail/JobMetrics/MetricsFilter/MetricsFilter';
import { DevopsType } from '@/pages/DevOps/JobDetail/model';
import { useEffect, useState } from 'react';
import { connect } from 'umi';
import JobChart from './JobChart/JobChart';
const JobMetrics = (props: any) => {
const { layoutName, dispatch } = props;
const [timeRange, setTimeRange] = useState<MetricsTimeFilter>({
startTime: new Date().getTime() - 60000,
endTime: new Date().getTime(),
isReal: true
});
useEffect(() => {
dispatch({
type: 'Devops/queryMetricsTarget',
payload: { layoutName: layoutName }
});
}, []);
const onTimeSelectChange = (filter: MetricsTimeFilter) => {
setTimeRange(filter);
};
return (
<>
<MetricsFilter onTimeSelect={onTimeSelectChange} />
<JobChart timeRange={timeRange} />
</>
);
};
export default connect(({ Devops }: { Devops: DevopsType }) => ({
jobDetail: Devops.jobInfoDetail,
layoutName: Devops.metrics.layoutName
}))(JobMetrics);
/*
*
* 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 { JobMetricsItem } from '@/pages/DevOps/JobDetail/data';
import { getData, putDataAsArray } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
export async function getMetricsLayout(params: {}) {
return (await getData(API_CONSTANTS.METRICS_LAYOUT_GET_BY_NAME, params)).datas;
}
export async function getMetricsData(params: {}) {
return (await getData(API_CONSTANTS.MONITOR_GET_FLINK_DATA, params)).datas;
}
export async function putMetricsLayout(layoutName: string, params: JobMetricsItem[]) {
return (await putDataAsArray(API_CONSTANTS.SAVE_FLINK_METRICS + layoutName, params)).datas;
}
/*
*
* 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 { Jobs } from '@/types/DevOps/data'; import { Jobs } from '@/types/DevOps/data';
type JobProps = { export type JobProps = {
jobDetail: Jobs.JobInfoDetail; jobDetail: Jobs.JobInfoDetail;
}; };
export type JobMetricsItem = {
id: number;
taskId: number;
vertices: string;
metrics: string;
position: string;
showType: string;
showSize: string;
title: string;
createTime: string;
updateTime: string;
};
export type MetricsTimeFilter = {
startTime: number;
endTime?: number;
isReal: boolean;
};
/*
*
* 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 { TagJobLifeCycle } from '@/pages/DevOps/function'; import { TagJobLifeCycle } from '@/pages/DevOps/function';
import CheckPoints from '@/pages/DevOps/JobDetail/CheckPointsTab'; import CheckPoints from '@/pages/DevOps/JobDetail/CheckPointsTab';
import JobLogsTab from '@/pages/DevOps/JobDetail/JobLogs/JobLogsTab'; import JobLogsTab from '@/pages/DevOps/JobDetail/JobLogs/JobLogsTab';
import JobMetrics from '@/pages/DevOps/JobDetail/JobMetrics';
import JobOperator from '@/pages/DevOps/JobDetail/JobOperator/JobOperator'; import JobOperator from '@/pages/DevOps/JobDetail/JobOperator/JobOperator';
import JobConfigTab from '@/pages/DevOps/JobDetail/JobOverview/JobOverview'; import JobConfigTab from '@/pages/DevOps/JobDetail/JobOverview/JobOverview';
import JobVersionTab from '@/pages/DevOps/JobDetail/JobVersion/JobVersionTab'; import JobVersionTab from '@/pages/DevOps/JobDetail/JobVersion/JobVersionTab';
import { DevopsType } from '@/pages/DevOps/JobDetail/model';
import JobOperatorGraph from '@/pages/Home/JobOverView/JobOperatorGraph'; import JobOperatorGraph from '@/pages/Home/JobOverView/JobOperatorGraph';
import { API_CONSTANTS } from '@/services/endpoints'; import { API_CONSTANTS } from '@/services/endpoints';
import { Jobs } from '@/types/DevOps/data'; import { Jobs } from '@/types/DevOps/data';
...@@ -12,9 +33,8 @@ import { ClusterOutlined, FireOutlined, RocketOutlined } from '@ant-design/icons ...@@ -12,9 +33,8 @@ import { ClusterOutlined, FireOutlined, RocketOutlined } from '@ant-design/icons
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max'; import { useRequest } from '@umijs/max';
import { Tag } from 'antd'; import { Tag } from 'antd';
import type { FC } from 'react';
import { useState } from 'react'; import { useState } from 'react';
import { useLocation } from 'umi'; import { connect, useLocation } from 'umi';
/** /**
* Enum defining different operators for the JobDetail component. * Enum defining different operators for the JobDetail component.
...@@ -25,7 +45,7 @@ const OperatorEnum = { ...@@ -25,7 +45,7 @@ const OperatorEnum = {
JOB_VERSION: 'job_version', JOB_VERSION: 'job_version',
JOB_CHECKPOINTS: 'job_checkpoints', JOB_CHECKPOINTS: 'job_checkpoints',
JOB_ALERT: 'job_alert', JOB_ALERT: 'job_alert',
JOB_MONITOR: 'job_monitor', JOB_METRICS: 'job_monitor',
JOB_LINEAGE: 'job_lineage', JOB_LINEAGE: 'job_lineage',
JOB_GRAPH: 'job_graph' JOB_GRAPH: 'job_graph'
}; };
...@@ -36,41 +56,43 @@ const OperatorEnum = { ...@@ -36,41 +56,43 @@ const OperatorEnum = {
* @param {any} props - The component props. * @param {any} props - The component props.
* @returns {JSX.Element} - The rendered JobDetail component. * @returns {JSX.Element} - The rendered JobDetail component.
*/ */
const JobDetail: FC = (props: any) => { const JobDetail = (props: any) => {
// Get the URL parameters const { dispatch, jobInfoDetail } = props;
const params = useLocation(); const params = useLocation();
const id = params.search.split('=')[1]; const id = params.search.split('=')[1];
// Set the initial tab key state
const [tabKey, setTabKey] = useState<string>(OperatorEnum.JOB_BASE_INFO); const [tabKey, setTabKey] = useState<string>(OperatorEnum.JOB_BASE_INFO);
// Fetch the job detail data
const { data } = useRequest(
{
url: API_CONSTANTS.GET_JOB_DETAIL,
params: { id: id }
},
{
cacheKey: 'data-detail',
pollingInterval: 1000
}
);
// Extract the job info detail from the fetched data
const jobInfoDetail: Jobs.JobInfoDetail = data;
// Define the components for each job operator // Define the components for each job operator
const JobOperatorItems = { const JobOperatorItems = {
[OperatorEnum.JOB_BASE_INFO]: <JobConfigTab jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_BASE_INFO]: <JobConfigTab jobDetail={jobInfoDetail} />,
[OperatorEnum.JOB_LOGS]: <JobLogsTab jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_LOGS]: <JobLogsTab jobDetail={jobInfoDetail} />,
[OperatorEnum.JOB_VERSION]: <JobVersionTab jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_VERSION]: <JobVersionTab jobDetail={jobInfoDetail} />,
[OperatorEnum.JOB_CHECKPOINTS]: <CheckPoints jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_CHECKPOINTS]: <CheckPoints jobDetail={jobInfoDetail} />,
[OperatorEnum.JOB_MONITOR]: <CheckPoints jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_METRICS]: <JobMetrics />,
[OperatorEnum.JOB_LINEAGE]: <CheckPoints jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_LINEAGE]: <CheckPoints jobDetail={jobInfoDetail} />,
[OperatorEnum.JOB_ALERT]: <CheckPoints jobDetail={jobInfoDetail} />, [OperatorEnum.JOB_ALERT]: <CheckPoints jobDetail={jobInfoDetail} />,
[OperatorEnum.JOB_GRAPH]: <JobOperatorGraph jobDetail={jobInfoDetail} /> [OperatorEnum.JOB_GRAPH]: <JobOperatorGraph jobDetail={jobInfoDetail} />
}; };
useRequest(
{
url: API_CONSTANTS.GET_JOB_DETAIL,
params: { id: id }
},
{
cacheKey: 'data-detail',
pollingInterval: 3000,
onSuccess: (data: Jobs.JobInfoDetail, params) => {
dispatch({
type: 'Devops/setJobInfoDetail',
jobDetail: data
});
}
}
);
// Define the tabs config for job operators // Define the tabs config for job operators
const JobOperatorTabs = [ const JobOperatorTabs = [
{ {
...@@ -88,7 +110,7 @@ const JobDetail: FC = (props: any) => { ...@@ -88,7 +110,7 @@ const JobDetail: FC = (props: any) => {
}, },
{ {
tab: l('devops.jobinfo.config.JobMonitor'), tab: l('devops.jobinfo.config.JobMonitor'),
key: OperatorEnum.JOB_MONITOR key: OperatorEnum.JOB_METRICS
}, },
{ {
tab: l('devops.jobinfo.config.JobLineage'), tab: l('devops.jobinfo.config.JobLineage'),
...@@ -128,4 +150,6 @@ const JobDetail: FC = (props: any) => { ...@@ -128,4 +150,6 @@ const JobDetail: FC = (props: any) => {
); );
}; };
export default JobDetail; export default connect(({ Devops }: { Devops: DevopsType }) => ({
jobInfoDetail: Devops.jobInfoDetail
}))(JobDetail);
/*
*
* 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 { JobMetricsItem } from '@/pages/DevOps/JobDetail/data';
import { getMetricsLayout } from '@/pages/DevOps/JobDetail/JobMetrics/service';
import { Effect, Reducer } from '@@/plugin-dva/types';
export type MetricsType = {
jobMetricsTarget: Record<string, JobMetricsItem[]>;
layoutName: string;
};
export type DevopsType = {
jobInfoDetail: any;
metrics: MetricsType;
};
export type DevopsModelType = {
namespace: string;
state: DevopsType;
effects: {
queryMetricsTarget: Effect;
};
reducers: {
updateMetricsTarget: Reducer;
setMetricsTarget: Reducer;
setJobInfoDetail: Reducer;
};
};
const Devops: DevopsModelType = {
namespace: 'Devops',
state: {
jobInfoDetail: {},
metrics: {
jobMetricsTarget: {},
layoutName: ''
}
},
effects: {
*queryMetricsTarget({ payload }, { call, put }) {
const data: JobMetricsItem[] = yield call(getMetricsLayout, payload);
yield put({ type: 'setMetricsTarget', payload: data });
}
},
reducers: {
updateMetricsTarget(state, { payload }) {
state.metrics.jobMetricsTarget[payload.verticeId] = payload.data;
return {
...state
};
},
setMetricsTarget(state, { payload }) {
const data: JobMetricsItem[] = payload;
const jobMetricsTarget: any = {};
data.forEach((metrics) => {
if (!(metrics.vertices in jobMetricsTarget)) {
jobMetricsTarget[metrics.vertices] = [];
}
jobMetricsTarget[metrics.vertices].push(metrics);
});
state.metrics.jobMetricsTarget = jobMetricsTarget;
return {
...state
};
},
setJobInfoDetail(state, { jobDetail }) {
return {
...state,
jobInfoDetail: jobDetail,
metrics: {
...state.metrics,
layoutName: `${jobDetail.instance.name}-${jobDetail.instance.taskId}`
}
};
}
}
};
export default Devops;
import { ChartData } from '@/pages/Metrics/Job/data';
import { renderMetricsChartTitle } from '@/pages/Metrics/Job/function';
import { Line } from '@ant-design/charts';
import { ProCard, StatisticCard } from '@ant-design/pro-components';
import { Col, Radio } from 'antd';
import React, { useEffect, useState } from 'react';
type FlinkChartProps = {
title: string;
data: ChartData[];
chartType: string;
chartSize: string;
onChangeJobState: (chartSize: string, chartType: string) => void;
};
const FlinkChart: React.FC<FlinkChartProps> = (props) => {
const { data, title, chartType, chartSize, onChangeJobState } = props;
const [chartProps, setChartProps] = useState({
chartType: chartType,
chartSize: chartSize,
titleWidth: '50%'
});
const [counter, setCounter] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCounter((prevCounter) => prevCounter + 1);
}, 1000); // 每隔1000毫秒(1秒)更新一次
return () => {
clearInterval(timer);
};
}, []);
const config = {
animation: false,
data: data,
xField: 'time',
yField: 'value',
xAxis: {
type: 'time',
mask: 'HH:mm:ss'
}
};
/**
* render chart size radio
* @returns {JSX.Element}
*/
const renderSizeChangeGroup = () => {
return (
<>
<Radio.Group
className={'radio-group-chart'}
size='small'
buttonStyle='solid'
value={chartProps.chartSize}
onChange={(e) => {
setChartProps((prevState) => ({
...prevState,
titleWidth: e.target.value == '25%' ? '50%' : '100%',
chartSize: e.target.value
}));
onChangeJobState(e.target.value, chartProps.chartType);
}}
style={{ paddingRight: '5%', paddingTop: '2%' }}
>
<Radio.Button value={'50%'}>Big</Radio.Button>
<Radio.Button value={'25%'}>Small</Radio.Button>
</Radio.Group>
</>
);
};
/**
* render chart type radio
* @returns {[JSX.Element]}
*/
const renderChartNumericRadio = () => [
<>
<Radio.Group
size='small'
buttonStyle='solid'
value={chartProps.chartType}
onChange={(e) => {
setChartProps((prevState) => ({
...prevState,
chartType: e.target.value
}));
onChangeJobState(chartProps.chartSize, e.target.value);
}}
style={{ textAlign: 'left', paddingLeft: '5%' }}
>
<Radio.Button value='Chart'>Chart</Radio.Button>
<Radio.Button value='Numeric'>Numeric</Radio.Button>
</Radio.Group>
</>
];
/**
* render
*/
return data === undefined ? (
<></>
) : (
<>
<Col span={chartProps.chartSize == '25%' ? 6 : 12}>
<ProCard
bodyStyle={{ textAlign: 'center' }}
colSpan={chartProps.chartSize}
bordered
title={renderMetricsChartTitle(title, chartProps.titleWidth)}
extra={renderSizeChangeGroup()}
actions={renderChartNumericRadio()}
style={{ height: 240 }}
>
{chartProps.chartType == 'Chart' ? (
<Line {...config} />
) : (
<StatisticCard.Group
style={{
minHeight: '100%',
minWidth: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<StatisticCard
statistic={{
value: data != undefined ? data[data.length - 1].value : 0
}}
/>
</StatisticCard.Group>
)}
</ProCard>
<ProCard />
</Col>
</>
);
};
FlinkChart.defaultProps = {
chartSize: '25%',
chartType: 'Chart'
};
export default FlinkChart;
...@@ -30,7 +30,7 @@ import { l } from '@/utils/intl'; ...@@ -30,7 +30,7 @@ import { l } from '@/utils/intl';
import { ProCard, ProFormSelect } from '@ant-design/pro-components'; import { ProCard, ProFormSelect } from '@ant-design/pro-components';
import { Button, Input, Row } from 'antd'; import { Button, Input, Row } from 'antd';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import FlinkChart from './FlinkChart'; import FlinkChart from '../../../components/FlinkChart';
const getJobMetrics = async (job: JobMetrics) => { const getJobMetrics = async (job: JobMetrics) => {
const url = const url =
...@@ -212,6 +212,7 @@ const Job = () => { ...@@ -212,6 +212,7 @@ const Job = () => {
}} }}
data={chartData[j.taskId + j.subTaskId + j.metrics]} data={chartData[j.taskId + j.subTaskId + j.metrics]}
title={j.metrics} title={j.metrics}
extraType={'size'}
/> />
); );
})} })}
......
...@@ -23,7 +23,7 @@ export type MetricsDataType = { ...@@ -23,7 +23,7 @@ export type MetricsDataType = {
// cpu: CPUType, // cpu: CPUType,
// mem: MemoryType, // mem: MemoryType,
// }, // },
content: string; content: any;
metricsTotal: number; metricsTotal: number;
model: string; model: string;
heartTime: Date; heartTime: Date;
......
...@@ -17,8 +17,9 @@ ...@@ -17,8 +17,9 @@
* *
*/ */
import FlinkChart from '@/components/FlinkChart';
import Job from '@/pages/Metrics/Job';
import { ChartData, MetricsLayout } from '@/pages/Metrics/Job/data'; import { ChartData, MetricsLayout } from '@/pages/Metrics/Job/data';
import FlinkChart from '@/pages/Metrics/Job/FlinkChart';
import Server from '@/pages/Metrics/Server'; import Server from '@/pages/Metrics/Server';
import { FlinkMetricsData, JVMMetric, MetricsDataType } from '@/pages/Metrics/Server/data'; import { FlinkMetricsData, JVMMetric, MetricsDataType } from '@/pages/Metrics/Server/data';
import { getSubMinTime } from '@/pages/Metrics/Server/function'; import { getSubMinTime } from '@/pages/Metrics/Server/function';
...@@ -31,7 +32,6 @@ import { PageContainer, ProCard } from '@ant-design/pro-components'; ...@@ -31,7 +32,6 @@ import { PageContainer, ProCard } from '@ant-design/pro-components';
import { AreaOptions as G2plotConfig } from '@antv/g2plot/lib/plots/area/types'; import { AreaOptions as G2plotConfig } from '@antv/g2plot/lib/plots/area/types';
import { Row } from 'antd'; import { Row } from 'antd';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import Job from './Job';
const commonChartConfig: G2plotConfig = { const commonChartConfig: G2plotConfig = {
data: [], data: [],
...@@ -218,6 +218,7 @@ export default () => { ...@@ -218,6 +218,7 @@ export default () => {
}} }}
data={chartDataList[j.taskId + j.vertices + j.metrics]} data={chartDataList[j.taskId + j.vertices + j.metrics]}
title={j.metrics} title={j.metrics}
extraType={'size'}
/> />
); );
})} })}
...@@ -225,7 +226,6 @@ export default () => { ...@@ -225,7 +226,6 @@ export default () => {
</ProCard> </ProCard>
); );
})} })}
<Job /> <Job />
</PageContainer> </PageContainer>
); );
......
...@@ -206,6 +206,7 @@ export enum API_CONSTANTS { ...@@ -206,6 +206,7 @@ export enum API_CONSTANTS {
GET_JOBMANAGER_THREAD_DUMP = 'api/jobInstance/getJobManagerThreadDump', GET_JOBMANAGER_THREAD_DUMP = 'api/jobInstance/getJobManagerThreadDump',
GET_TASKMANAGER_LIST = 'api/jobInstance/getTaskManagerList', GET_TASKMANAGER_LIST = 'api/jobInstance/getTaskManagerList',
GET_TASKMANAGER_LOG = 'api/jobInstance/getTaskManagerLog', GET_TASKMANAGER_LOG = 'api/jobInstance/getTaskManagerLog',
GET_JOB_MERTICE_ITEMS = 'api/jobInstance/getJobMetricsItems',
CANCEL_JOB = '/api/studio/cancel', CANCEL_JOB = '/api/studio/cancel',
OFFLINE_TASK = '/api/task/offLineTask', OFFLINE_TASK = '/api/task/offLineTask',
RESTART_TASK = '/api/task/restartTask', RESTART_TASK = '/api/task/restartTask',
...@@ -228,10 +229,11 @@ export enum API_CONSTANTS { ...@@ -228,10 +229,11 @@ export enum API_CONSTANTS {
// monitor // monitor
MONITOR_GET_SYSTEM_DATA = '/api/monitor/getSysData', MONITOR_GET_SYSTEM_DATA = '/api/monitor/getSysData',
MONITOR_GET_FLINK_DATA = '/api/monitor/getFlinkData',
MONITOR_GET_LAST_DATA = '/api/monitor/getLastUpdateData', MONITOR_GET_LAST_DATA = '/api/monitor/getLastUpdateData',
METRICS_LAYOUT_GET_BY_NAME = '/api/monitor/getMetricsLayoutByName',
JOB_METRICS = '/api/monitor/jobMetrics', JOB_METRICS = '/api/monitor/jobMetrics',
SAVE_FLINK_METRICS = '/api/monitor/saveFlinkMetrics/',
SAVE_FLINK_METRICS = '/api/monitor/saveFlinkMetrics',
GET_METRICS_LAYOUT = '/api/monitor/getMetricsLayout', GET_METRICS_LAYOUT = '/api/monitor/getMetricsLayout',
// flink // flink
......
/*
*
* 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 { BaseBeanColumns } from '@/types/Public/data'; import { BaseBeanColumns } from '@/types/Public/data';
/** /**
...@@ -52,9 +71,35 @@ declare namespace Jobs { ...@@ -52,9 +71,35 @@ declare namespace Jobs {
clusterName: string; clusterName: string;
}; };
export type JobVertices = {
id: string;
name: string;
maxParallelism: number;
parallelism: number;
status: string;
duration: number;
tasks: any;
metrics: any;
};
export type Job = {
jid: string;
name: string;
isStoppable: false;
state: string;
'start-time': number;
'end-time': number;
duration: number;
maxParallelism: number;
now: number;
timestamps: any;
vertices: JobVertices[];
'status-counts': {};
plan: {};
};
export type JobHistoryItem = { export type JobHistoryItem = {
id: number; id: number;
job: any; job: Job;
exceptions: any; exceptions: any;
checkpoints: any; checkpoints: any;
checkpointsConfig: any; checkpointsConfig: any;
......
...@@ -408,6 +408,27 @@ export function parseMilliSecondStr(second_time: number) { ...@@ -408,6 +408,27 @@ export function parseMilliSecondStr(second_time: number) {
return parseSecondStr(second_time / 1000); return parseSecondStr(second_time / 1000);
} }
/**
* Calculate how many days the dates differ
* @returns {any}
*/
export function differenceDays(startDateString: any, endDateString: any): number {
const startDate = new Date(startDateString);
const endDate = new Date(endDateString);
// 将日期对象的时间部分设为0,只保留日期
startDate.setHours(0, 0, 0, 0);
endDate.setHours(0, 0, 0, 0);
// 计算两个日期的时间差(毫秒)
const timeDifference = endDate.getTime() - startDate.getTime();
// 将毫秒转换为天数
const daysDifference = timeDifference / (1000 * 60 * 60 * 24);
return Math.floor(daysDifference);
}
/** /**
* build tree data * build tree data
* @param data * @param data
......
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