Unverified Commit b5b25763 authored by gaoyan's avatar gaoyan Committed by GitHub

[Refactor][Admin]Refactor Add Global Sse (#2417)

* add global Sse control * delete BaseSse * add comment * merge dev * formate code * foramte comment * Optimize SSE logic
parent cd7a1743
/*
*
* 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 java.util.ArrayList;
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;
@Slf4j
public abstract class BaseSseContext<K, V> {
/**
* 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.
*/
protected LoadingCache<K, List<SseEmitter>> sseList = CacheBuilder.newBuilder()
.expireAfterAccess(60, TimeUnit.SECONDS)
.removalListener(this::onRemove)
.build(CacheLoader.from(key -> new ArrayList<>()));
/**
* Called during an asynchronous send procedure
*/
public abstract void append(K key, V o);
/**
* send data asynchronously.
*/
public void sendAsync(K key, V o) {
CompletableFuture.runAsync(() -> {
append(key, o);
send(key, o);
});
}
/**
* send data.
*/
protected void send(K key, V o) {
List<SseEmitter> sseEmitters = sseList.getIfPresent(key);
if (sseEmitters != null) {
sseEmitters.forEach(sseEmitter -> {
try {
sseEmitter.send(o);
} catch (Exception e) {
log.warn("send metrics error:{}", e.getMessage());
closeSse(sseEmitter);
sseEmitters.remove(sseEmitter);
}
});
}
}
/**
* remove the SseEmitter object from the cache
* When the connection times out or actively exits.
*
* @param removalNotification RemovalNotification object
*/
protected void onRemove(RemovalNotification<K, List<SseEmitter>> removalNotification) {
assert removalNotification.getValue() != null;
removalNotification.getValue().forEach(this::closeSse);
}
/**
* close the SseEmitter object.
*
* @param sseEmitter SseEmitter object
*/
protected void closeSse(SseEmitter sseEmitter) {
try {
sseEmitter.complete();
} catch (Exception e) {
log.warn("complete sseEmitter failed:{}", e.getMessage());
}
}
}
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.context; package org.dinky.context;
import org.dinky.aop.ProcessAspect; import org.dinky.aop.ProcessAspect;
import org.dinky.data.enums.SseTopic;
import org.dinky.data.exception.BusException; import org.dinky.data.exception.BusException;
import org.dinky.process.enums.ProcessStatus; import org.dinky.process.enums.ProcessStatus;
import org.dinky.process.enums.ProcessStepType; import org.dinky.process.enums.ProcessStepType;
...@@ -31,27 +32,25 @@ import org.dinky.utils.LogUtil; ...@@ -31,27 +32,25 @@ import org.dinky.utils.LogUtil;
import org.apache.http.util.TextUtils; import org.apache.http.util.TextUtils;
import java.nio.charset.Charset;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.MDC; import org.slf4j.MDC;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONObject;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class ConsoleContextHolder extends BaseSseContext<String, ProcessEntity> { public class ConsoleContextHolder {
protected static final ConsoleContextHolder instance = new ConsoleContextHolder(); protected static final ConsoleContextHolder instance = new ConsoleContextHolder();
/** /**
...@@ -72,37 +71,6 @@ public class ConsoleContextHolder extends BaseSseContext<String, ProcessEntity> ...@@ -72,37 +71,6 @@ public class ConsoleContextHolder extends BaseSseContext<String, ProcessEntity>
return new ArrayList<>(logPross.values()); return new ArrayList<>(logPross.values());
} }
/**
* Add the SseEmitter object to the context.
*
* @param processName process name, which is used as an indication for the keyword list
* @param sseEmitter SseEmitter object
*/
public void addSse(String processName, SseEmitter sseEmitter) {
List<SseEmitter> emitters = sseList.getIfPresent(processName);
if (emitters == null) {
emitters = new ArrayList<>();
sseList.put(processName, emitters);
}
emitters.add(sseEmitter);
if (logPross.containsKey(processName)) {
sendAsync(processName, logPross.get(processName));
} else {
String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), processName);
try {
String string = FileUtil.readString(filePath, Charset.defaultCharset());
ProcessEntity entity = JSONObject.parseObject(string, ProcessEntity.class);
sendAsync(processName, entity);
} catch (IORuntimeException e) {
log.warn("{} have no cache files", processName);
}
}
}
@Override
public void append(String key, ProcessEntity o) {}
/** /**
* Add log messages to specific processes and process steps. * Add log messages to specific processes and process steps.
* *
...@@ -118,7 +86,10 @@ public class ConsoleContextHolder extends BaseSseContext<String, ProcessEntity> ...@@ -118,7 +86,10 @@ public class ConsoleContextHolder extends BaseSseContext<String, ProcessEntity>
logPross.get(processName).appendLog(log); logPross.get(processName).appendLog(log);
ProcessStep stepNode = getStepNode(processStep.getValue(), getStepsMap(processName)); ProcessStep stepNode = getStepNode(processStep.getValue(), getStepsMap(processName));
stepNode.appendLog(log); stepNode.appendLog(log);
sendAsync(processName, logPross.get(processName)); String topic = StrFormatter.format("{}/{}", SseTopic.PROCESS_CONSOLE.getValue(), processName);
CompletableFuture.runAsync(() -> {
SseSessionContextHolder.sendTopic(topic, logPross.get(processName));
});
} }
/** /**
......
...@@ -19,17 +19,16 @@ ...@@ -19,17 +19,16 @@
package org.dinky.context; package org.dinky.context;
import org.dinky.data.enums.SseTopic;
import org.dinky.data.vo.MetricsVO; import org.dinky.data.vo.MetricsVO;
import org.dinky.utils.PaimonUtil; import org.dinky.utils.PaimonUtil;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import cn.hutool.core.text.StrFormatter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/** /**
...@@ -37,7 +36,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -37,7 +36,7 @@ import lombok.extern.slf4j.Slf4j;
* including operations such as storing and sending metric data. * including operations such as storing and sending metric data.
*/ */
@Slf4j @Slf4j
public class MetricsContextHolder extends BaseSseContext<String, MetricsVO> { public class MetricsContextHolder {
protected static final MetricsContextHolder instance = new MetricsContextHolder(); protected static final MetricsContextHolder instance = new MetricsContextHolder();
...@@ -53,8 +52,8 @@ public class MetricsContextHolder extends BaseSseContext<String, MetricsVO> { ...@@ -53,8 +52,8 @@ public class MetricsContextHolder extends BaseSseContext<String, MetricsVO> {
private final Long lastDumpTime = System.currentTimeMillis(); private final Long lastDumpTime = System.currentTimeMillis();
@Override public void sendAsync(String key, MetricsVO o) {
public void append(String key, MetricsVO o) { CompletableFuture.runAsync(() -> {
metricsVOS.add(o); metricsVOS.add(o);
long duration = System.currentTimeMillis() - lastDumpTime; long duration = System.currentTimeMillis() - lastDumpTime;
synchronized (metricsVOS) { synchronized (metricsVOS) {
...@@ -63,49 +62,8 @@ public class MetricsContextHolder extends BaseSseContext<String, MetricsVO> { ...@@ -63,49 +62,8 @@ public class MetricsContextHolder extends BaseSseContext<String, MetricsVO> {
metricsVOS.clear(); metricsVOS.clear();
} }
} }
} String topic = StrFormatter.format("{}/{}", SseTopic.METRICS.getValue(), key);
SseSessionContextHolder.sendTopic(topic, o);
/**
* 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 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 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);
}
}
});
}
}); });
} }
} }
/*
*
* 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.exception.BusException;
import org.dinky.data.vo.SseDataVo;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SseSessionContextHolder {
private static final Map<String, TopicSubscriber> sessionMap = new ConcurrentHashMap<>();
/**
* Subscribes a session to the topics.
* A session can subscribe to multiple topics
*
* @param sessionId The ID of the session.
* @param topics The list of topics to subscribe to.
* @return The updated set of topics for the session.
* @throws BusException If the session does not exist.
*/
public static Set<String> subscribeTopic(String sessionId, List<String> topics) {
if (exists(sessionId)) {
return sessionMap.get(sessionId).updateTopics(topics);
} else {
throw new BusException("Session does not exist");
}
}
/**
* Connects a session with the given session key.
*
* @param sessionKey The session key of the new session.
* @return The SseEmitter for the session.
*/
public static SseEmitter connectSession(String sessionKey) {
log.info("New session wants to connect: {}", sessionKey);
if (exists(sessionKey)) {
log.warn("Session key already exists: {}", sessionKey);
closeSse(sessionKey);
}
SseEmitter sseEmitter = new SseEmitter(60 * 1000L);
sseEmitter.onError(err -> onError(sessionKey, err));
sseEmitter.onTimeout(() -> onTimeout(sessionKey));
sseEmitter.onCompletion(() -> onCompletion(sessionKey));
try {
// Set the client reconnection interval, 0 to reconnect immediately
sseEmitter.send(SseEmitter.event().reconnectTime(0));
} catch (IOException e) {
throw new RuntimeException(e);
}
sessionMap.put(sessionKey, TopicSubscriber.of(sseEmitter));
return sseEmitter;
}
/**
* Checks if a session with the given session key exists.
*
* @param sessionKey The session key to check.
* @return true if the session exists, false otherwise.
*/
public static boolean exists(String sessionKey) {
return sessionMap.get(sessionKey) != null;
}
/**
* Handles the timeout event for a session.
*
* @param sessionKey The session key of the timed-out session.
*/
public static void onTimeout(String sessionKey) {
log.info("Type: SseSession Timeout, Session ID: {}", sessionKey);
closeSse(sessionKey);
}
/**
* Closes the SseEmitter for a session.
*
* @param sessionKey The session key of the session to close.
*/
public static void closeSse(String sessionKey) {
if (exists(sessionKey)) {
try {
sessionMap.get(sessionKey).getEmitter().complete();
} catch (Exception e) {
log.warn("Failed to complete sseEmitter, Session Key: {}, Error: {}", sessionKey, e.getMessage());
} finally {
sessionMap.remove(sessionKey);
}
}
}
/**
* Handles the error event for a session.
*
* @param sessionKey The session key of the session with the error.
* @param throwable The throwable representing the error.
*/
public static void onError(String sessionKey, Throwable throwable) {
log.error("Type: SseSession [{}] Error, Message: {}", sessionKey, throwable.getMessage());
if (exists(sessionKey)) {
try {
sessionMap.get(sessionKey).getEmitter().completeWithError(throwable);
} catch (Exception e) {
log.error("Failed to complete Sse With Error: {}", e.getMessage());
}
}
sessionMap.remove(sessionKey);
}
/**
* Handles the completion event for a session.
*
* @param sessionKey The session key of the completed session.
*/
public static void onCompletion(String sessionKey) {
log.info("Type: SseSession Completion, Session ID: {}", sessionKey);
closeSse(sessionKey);
}
/**
* Sends the specified content to all subscribers of the given topic.
*
* @param topic The topic to send the content to.
* @param content The content to send.
*/
public static void sendTopic(String topic, Object content) {
sessionMap.forEach((sessionKey, topicSubscriber) -> {
if (topicSubscriber.getTopics().contains(topic)) {
try {
SseDataVo data = new SseDataVo(sessionKey, topic, content);
sendSse(sessionKey, data);
} catch (Exception e) {
log.error("Error sending sse data", e);
onError(sessionKey, e);
}
}
});
}
/**
* Sends the specified SSE data to the session with the given session key.
*
* @param sessionKey The session key of the recipient session.
* @param content The SSE data to send.
* @throws IOException If an I/O error occurs while sending the data.
*/
public static void sendSse(String sessionKey, SseDataVo content) throws IOException {
if (exists(sessionKey)) {
sessionMap.get(sessionKey).getEmitter().send(content);
} else {
log.warn("SseEmitter not found for session key: {}", sessionKey);
}
}
/**
* Represents a topic subscriber with the subscribed topics and the associated SseEmitter.
*/
@Data
public static class TopicSubscriber {
private Set<String> topics;
private final SseEmitter emitter;
/**
* Creates a new TopicSubscriber with the specified SseEmitter.
*
* @param topics The initial set of topics.
* @param emitter The SseEmitter associated with the subscriber.
*/
public TopicSubscriber(Set<String> topics, SseEmitter emitter) {
this.topics = topics;
this.emitter = emitter;
}
/**
* Creates a new TopicSubscriber with the specified SseEmitter and an empty set of topics.
*
* @param emitter The SseEmitter associated with the subscriber.
* @return The created TopicSubscriber.
*/
public static TopicSubscriber of(SseEmitter emitter) {
return new TopicSubscriber(new HashSet<>(), emitter);
}
/**
* Updates the topics for the subscriber.
*
* @param topics The new list of topics.
* @return The updated set of topics.
*/
public Set<String> updateTopics(List<String> topics) {
this.topics = new HashSet<>(topics);
return this.topics;
}
}
}
...@@ -30,15 +30,11 @@ import org.dinky.data.result.Result; ...@@ -30,15 +30,11 @@ 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.JobInstanceService;
import org.dinky.service.MonitorService; import org.dinky.service.MonitorService;
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.stream.Collectors; import java.util.stream.Collectors;
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;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
...@@ -46,7 +42,6 @@ import org.springframework.web.bind.annotation.RequestBody; ...@@ -46,7 +42,6 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; 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 com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
...@@ -107,19 +102,6 @@ public class MonitorController { ...@@ -107,19 +102,6 @@ public class MonitorController {
jids)); jids));
} }
@GetMapping(value = "/getLastUpdateData", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Get Last Update Data")
@ApiImplicitParams({
@ApiImplicitParam(name = "lastTime", value = "Last Time", required = false, dataType = "Long"),
@ApiImplicitParam(name = "keys", value = "jobids", required = true, dataType = "String")
})
public SseEmitter getLastUpdateData(Long lastTime, String keys) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
lastTime = Opt.ofNullable(lastTime).orElse(TimeUtil.nowTimestamp());
return monitorService.sendLatestData(
emitter, TimeUtil.toLocalDateTime(lastTime), CollUtil.newArrayList(keys.split(",")));
}
@PutMapping("/saveFlinkMetrics/{layout}") @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)
......
...@@ -20,15 +20,17 @@ ...@@ -20,15 +20,17 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.vo.PrintTableVo;
import org.dinky.service.PrintTableService; import org.dinky.service.PrintTableService;
import org.dinky.utils.JsonUtils;
import org.springframework.http.MediaType; import java.util.List;
import org.springframework.web.bind.annotation.GetMapping; import java.util.Map;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
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 io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
...@@ -38,23 +40,22 @@ import lombok.AllArgsConstructor; ...@@ -38,23 +40,22 @@ import lombok.AllArgsConstructor;
@RestController @RestController
@Api(tags = "Print Table Controller") @Api(tags = "Print Table Controller")
@AllArgsConstructor @AllArgsConstructor
@RequestMapping("/api") @RequestMapping("/api/printTable")
public class PrintTableController { public class PrintTableController {
private final PrintTableService printTableService; private final PrintTableService printTableService;
@GetMapping(value = "/subscribe/print", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @PostMapping("/getPrintTables")
@ApiOperation("Subscribe p table") @ApiOperation("Get Print Tables")
@ApiImplicitParam(name = "table", value = "table name", required = true, dataType = "String", paramType = "query") @SuppressWarnings("unchecked")
public SseEmitter subscribe(@RequestParam String table) { @ApiImplicitParam(name = "statement", value = "Statement", dataType = "String", paramType = "body", required = true)
return printTableService.registerListenEntry(table); public Result<List<PrintTableVo>> getPrintTables(@RequestBody String statement) {
try {
Map<String, String> data = JsonUtils.toMap(statement);
String ss = data.get("statement");
return Result.succeed(printTableService.getPrintTables(ss));
} catch (Exception e) {
return Result.failed(e.getMessage());
} }
@PutMapping("/unSubscribe/print")
@ApiOperation("UnSubscribe print table")
@ApiImplicitParam(name = "table", value = "table name", required = true, dataType = "String", paramType = "query")
public Result<Void> unsubscribe(@RequestParam String table) {
printTableService.unRegisterListenEntry(table);
return Result.succeed();
} }
} }
...@@ -22,20 +22,14 @@ package org.dinky.controller; ...@@ -22,20 +22,14 @@ package org.dinky.controller;
import org.dinky.context.ConsoleContextHolder; import org.dinky.context.ConsoleContextHolder;
import org.dinky.data.result.ProTableResult; import org.dinky.data.result.ProTableResult;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.sse.SseEmitterUTF8;
import java.util.concurrent.TimeUnit;
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.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; 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 io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
...@@ -50,18 +44,6 @@ import lombok.RequiredArgsConstructor; ...@@ -50,18 +44,6 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor @RequiredArgsConstructor
public class ProcessController { public class ProcessController {
@GetMapping(value = "/getLastUpdateData", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Get Last Update Data")
@ApiImplicitParams({
@ApiImplicitParam(name = "lastTime", value = "Last Time", required = false, dataType = "Long"),
@ApiImplicitParam(name = "keys", value = "jobids", required = true, dataType = "String")
})
public SseEmitter getLastUpdateData(String keys) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
ConsoleContextHolder.getInstances().addSse(keys, emitter);
return emitter;
}
/** /**
* List all process * List all process
* *
......
...@@ -19,19 +19,21 @@ ...@@ -19,19 +19,21 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.service.MonitorService; import org.dinky.context.SseSessionContextHolder;
import org.dinky.sse.SseEmitterUTF8; import org.dinky.data.dto.SseSubscribeDTO;
import org.dinky.utils.TimeUtil; import org.dinky.data.enums.Status;
import org.dinky.data.result.Result;
import java.util.concurrent.TimeUnit; import java.util.Set;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; 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.lang.Opt;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
...@@ -42,22 +44,19 @@ import lombok.RequiredArgsConstructor; ...@@ -42,22 +44,19 @@ import lombok.RequiredArgsConstructor;
@RequestMapping("/api/sse") @RequestMapping("/api/sse")
@RequiredArgsConstructor @RequiredArgsConstructor
public class SseController { public class SseController {
private final MonitorService monitorService;
@PostMapping(value = "/subscribeTopic")
@GetMapping(value = "/getLastUpdateData", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @ApiOperation("subscribeTopic")
@ApiOperation("Get Last Update Data") @ApiImplicitParam(name = "topics", value = "topics", required = true, dataType = "List")
@ApiImplicitParam(name = "lastTime", value = "last time", required = false, dataType = "Long", paramType = "query") public Result<Set<String>> subscribeTopic(@RequestBody SseSubscribeDTO subscribeDTO) {
public SseEmitter getLastUpdateData(Long lastTime) { Set<String> b = SseSessionContextHolder.subscribeTopic(subscribeDTO.getSessionKey(), subscribeDTO.getTopics());
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30)); return Result.succeed(b, Status.SUCCESS);
lastTime = Opt.ofNullable(lastTime).orElse(TimeUtil.nowTimestamp());
return monitorService.sendLatestData(emitter, TimeUtil.toLocalDateTime(lastTime), null);
} }
@GetMapping(value = "/getJvmInfo", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ApiOperation("Get JVM Info") @ApiOperation("Connect Sse")
@ApiImplicitParam(name = "lastTime", value = "last time", required = false, dataType = "Long", paramType = "query") @ApiImplicitParam(name = "sessionKey", value = "Session unique key", required = true, dataType = "String")
public SseEmitter getJvmInfo(Long lastTime) { public SseEmitter getJvmInfo(String sessionKey) {
SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30)); return SseSessionContextHolder.connectSession(sessionKey);
return monitorService.sendJvmInfo(emitter);
} }
} }
...@@ -37,10 +37,8 @@ import org.dinky.process.annotations.ExecuteProcess; ...@@ -37,10 +37,8 @@ import org.dinky.process.annotations.ExecuteProcess;
import org.dinky.process.annotations.ProcessId; import org.dinky.process.annotations.ProcessId;
import org.dinky.process.enums.ProcessType; import org.dinky.process.enums.ProcessType;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import org.dinky.utils.JsonUtils;
import java.util.List; import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
...@@ -174,20 +172,6 @@ public class TaskController { ...@@ -174,20 +172,6 @@ public class TaskController {
return Result.succeed(taskService.getTaskInfoById(id)); return Result.succeed(taskService.getTaskInfoById(id));
} }
@PostMapping("/getPrintTables")
@ApiOperation("Get Print Tables")
@SuppressWarnings("unchecked")
@ApiImplicitParam(name = "statement", value = "Statement", dataType = "String", paramType = "body", required = true)
public Result<List<String>> getPrintTables(@RequestBody String statement) {
try {
Map<String, String> data = JsonUtils.toMap(statement);
String ss = data.get("statement");
return Result.succeed(taskService.getPrintTables(ss));
} catch (Exception e) {
return Result.failed(e.getMessage());
}
}
@GetMapping(value = "/listFlinkSQLEnv") @GetMapping(value = "/listFlinkSQLEnv")
@ApiOperation("Get All FlinkSQLEnv") @ApiOperation("Get All FlinkSQLEnv")
public Result<List<Task>> listFlinkSQLEnv() { public Result<List<Task>> listFlinkSQLEnv() {
......
/*
*
* 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.dto;
import java.util.List;
import lombok.Data;
@Data
public class SseSubscribeDTO {
private String sessionKey;
private List<String> topics;
}
/*
*
* 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.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class PrintTableVo {
private final String tableName;
private final String fullTableName;
}
/*
*
* 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.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@AllArgsConstructor
@Builder
public class SseDataVo {
private String sessionKey;
private String topic;
private Object data;
}
...@@ -23,7 +23,6 @@ import org.dinky.data.dto.MetricsLayoutDTO; ...@@ -23,7 +23,6 @@ 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;
...@@ -44,16 +43,6 @@ public interface MonitorService extends IService<Metrics> { ...@@ -44,16 +43,6 @@ 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);
/**
* Send the latest data to the specified SSE emitter.
*
* @param sseEmitter The SSE emitter to send the latest data to.
* @param lastDate The last date to include in the data.
* @param keys A list of keys to filter the data by.
* @return {@link SseEmitter}
*/
SseEmitter sendLatestData(SseEmitter sseEmitter, LocalDateTime lastDate, List<String> keys);
/** /**
* Send the JVM information to the specified SSE emitter. * Send the JVM information to the specified SSE emitter.
* *
......
...@@ -19,20 +19,17 @@ ...@@ -19,20 +19,17 @@
package org.dinky.service; package org.dinky.service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.dinky.data.vo.PrintTableVo;
import java.util.List;
public interface PrintTableService { public interface PrintTableService {
/**
* Register a listen entry for a specified table.
*
* @param table The name of the table to register the listen entry for.
*/
SseEmitter registerListenEntry(String table);
/** /**
* Unregister a listen entry for a specified table. * Get the print tables for the given SQL statement.
* *
* @param table The name of the table to unregister the listen entry for. * @param statement The SQL statement to get the print tables for.
* @return A list of strings representing the print tables.
*/ */
void unRegisterListenEntry(String table); List<PrintTableVo> getPrintTables(String statement);
} }
...@@ -260,12 +260,4 @@ public interface TaskService extends ISuperService<Task> { ...@@ -260,12 +260,4 @@ public interface TaskService extends ISuperService<Task> {
* @return A {@link JobModelOverview} object representing the job model overview. * @return A {@link JobModelOverview} object representing the job model overview.
*/ */
JobModelOverview getJobStreamingOrBatchModelOverview(); JobModelOverview getJobStreamingOrBatchModelOverview();
/**
* Get the print tables for the given SQL statement.
*
* @param statement The SQL statement to get the print tables for.
* @return A list of strings representing the print tables.
*/
List<String> getPrintTables(String statement);
} }
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.context.MetricsContextHolder;
import org.dinky.data.dto.MetricsLayoutDTO; import org.dinky.data.dto.MetricsLayoutDTO;
import org.dinky.data.metrics.Jvm; import org.dinky.data.metrics.Jvm;
import org.dinky.data.model.Metrics; import org.dinky.data.model.Metrics;
...@@ -34,7 +33,6 @@ import org.apache.paimon.data.Timestamp; ...@@ -34,7 +33,6 @@ 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;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
...@@ -91,12 +89,6 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl ...@@ -91,12 +89,6 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public SseEmitter sendLatestData(SseEmitter sseEmitter, LocalDateTime lastDate, List<String> keys) {
MetricsContextHolder.getInstances().addSse(keys, sseEmitter, lastDate);
return sseEmitter;
}
@Override @Override
public SseEmitter sendJvmInfo(SseEmitter sseEmitter) { public SseEmitter sendJvmInfo(SseEmitter sseEmitter) {
scheduleRefreshMonitorDataExecutor.execute(() -> { scheduleRefreshMonitorDataExecutor.execute(() -> {
......
...@@ -19,17 +19,20 @@ ...@@ -19,17 +19,20 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.context.SseSessionContextHolder;
import org.dinky.data.enums.SseTopic;
import org.dinky.data.vo.PrintTableVo;
import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.parser.SqlType;
import org.dinky.service.PrintTableService; import org.dinky.service.PrintTableService;
import org.dinky.trans.Operations;
import org.dinky.utils.SqlUtil;
import java.net.DatagramPacket; import java.net.DatagramPacket;
import java.net.DatagramSocket; import java.net.DatagramSocket;
import java.net.SocketException; import java.net.SocketException;
import java.text.MessageFormat; import java.util.Arrays;
import java.util.HashSet; import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.function.Consumer; import java.util.function.Consumer;
...@@ -38,16 +41,14 @@ import java.util.regex.Pattern; ...@@ -38,16 +41,14 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.text.StrFormatter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
@Service @Service
public class PrintTableServiceImpl implements PrintTableService { public class PrintTableServiceImpl implements PrintTableService {
private final Map<String, Set<Target>> registerTableMap = new ConcurrentHashMap<>();
private static final Pattern FULL_TABLE_NAME_PATTERN = Pattern.compile("^`(\\w+)`\\.`(\\w+)`\\.`(\\w+)`$"); private static final Pattern FULL_TABLE_NAME_PATTERN = Pattern.compile("^`(\\w+)`\\.`(\\w+)`\\.`(\\w+)`$");
public PrintTableServiceImpl() { public PrintTableServiceImpl() {
...@@ -55,69 +56,29 @@ public class PrintTableServiceImpl implements PrintTableService { ...@@ -55,69 +56,29 @@ public class PrintTableServiceImpl implements PrintTableService {
printer.start(); printer.start();
} }
@Override
public List<PrintTableVo> getPrintTables(String statement) {
// TODO: 2023/4/7 this function not support variable sql, because, JobManager and executor
// couple function
// and status and task execute.
final String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement));
return Arrays.stream(statements)
.filter(t -> SqlType.PRINT.equals(Operations.getOperationType(t)))
.flatMap(t -> Arrays.stream(PrintStatementExplainer.splitTableNames(t)))
.map(t -> new PrintTableVo(t, getFullTableName(t)))
.collect(Collectors.toList());
}
public void send(String message) { public void send(String message) {
try { try {
String[] data = message.split("\n", 2); String[] data = message.split("\n", 2);
final Set<Target> targets = registerTableMap.get(data[0]); String topic = StrFormatter.format("{}/{}", SseTopic.PRINT_TABLE.getValue(), data[0]);
if (targets != null) { SseSessionContextHolder.sendTopic(topic, data[1]);
targets.forEach(d -> d.send(data[1], "data"));
}
} catch (Exception e) { } catch (Exception e) {
log.error("send message failed: {}", e.getMessage()); log.error("send message failed: {}", e.getMessage());
} }
} }
@Override
public SseEmitter registerListenEntry(String table) {
String fullName = getFullTableName(table);
String destination = getDestinationByFullName(fullName);
Set<Target> targets = registerTableMap.get(fullName);
SseEmitter emitter = getSseEmitter(targets, fullName);
Set<Target> newTargets = new HashSet<>();
newTargets.add(Target.of(emitter, destination));
if (targets != null) {
newTargets.addAll(targets);
}
registerTableMap.put(fullName, newTargets);
return emitter;
}
private SseEmitter getSseEmitter(Set<Target> targets, String fullName) {
SseEmitter emitter = new SseEmitter();
emitter.onCompletion(() -> {
log.info(MessageFormat.format("SseEmitter {0} complete", emitter));
Set<Target> remains = targets.stream()
.filter(t -> !t.getEmitter().equals(emitter))
.collect(Collectors.toSet());
registerTableMap.put(fullName, remains);
});
emitter.onError(e -> {
log.error("SseEmitter error: {}", e.getMessage());
emitter.complete();
});
emitter.onTimeout(() -> {
log.debug("SseEmitter timeout: {}", emitter.getTimeout());
emitter.complete();
});
return emitter;
}
@Override
public void unRegisterListenEntry(String table) {
String fullName = getFullTableName(table);
String destination = getDestination(fullName);
Set<Target> destinations = registerTableMap.get(fullName);
if (destinations != null) {
destinations.stream().filter(d -> d.destination.equals(destination)).forEach(Target::complete);
destinations.removeIf(d -> d.destination.equals(destination));
}
}
public static String getFullTableName(String table) { public static String getFullTableName(String table) {
if (table == null) { if (table == null) {
throw new NullPointerException("table name empty"); throw new NullPointerException("table name empty");
...@@ -133,64 +94,6 @@ public class PrintTableServiceImpl implements PrintTableService { ...@@ -133,64 +94,6 @@ public class PrintTableServiceImpl implements PrintTableService {
return result; return result;
} }
public static String getDestination(String table) {
String fn = getFullTableName(table);
return String.format("/topic/table/%s", fn);
}
public static String getDestinationByFullName(String tableFullName) {
return String.format("/topic/table/%s", tableFullName);
}
public static final class Target {
private final String destination;
public final SseEmitter emitter;
public Target(String destination, SseEmitter emitter) {
this.destination = destination;
this.emitter = emitter;
}
public static Target of(SseEmitter emitter, String destination) {
return new Target(destination, emitter);
}
public void send(String message, String type) {
try {
SseEmitter.SseEventBuilder builder =
SseEmitter.event().data(message).name("pt_" + type);
emitter.send(builder);
} catch (Exception e) {
log.debug("SseEmitter {}, send message failed: {}", emitter, e.getMessage());
}
}
public String getDestination() {
return destination;
}
public SseEmitter getEmitter() {
return emitter;
}
public void complete() {
emitter.complete();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Target target = (Target) o;
return Objects.equals(destination, target.destination) && Objects.equals(emitter, target.emitter);
}
@Override
public int hashCode() {
return Objects.hash(destination, emitter);
}
}
public static class PrintTableListener { public static class PrintTableListener {
private final Consumer<String> consumer; private final Consumer<String> consumer;
......
...@@ -50,7 +50,6 @@ import org.dinky.data.model.TaskVersion; ...@@ -50,7 +50,6 @@ import org.dinky.data.model.TaskVersion;
import org.dinky.data.model.UDFTemplate; import org.dinky.data.model.UDFTemplate;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.result.SqlExplainResult; import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.function.compiler.CustomStringJavaCompiler; import org.dinky.function.compiler.CustomStringJavaCompiler;
import org.dinky.function.pool.UdfCodePool; import org.dinky.function.pool.UdfCodePool;
import org.dinky.function.util.UDFUtil; import org.dinky.function.util.UDFUtil;
...@@ -66,7 +65,6 @@ import org.dinky.job.JobManager; ...@@ -66,7 +65,6 @@ import org.dinky.job.JobManager;
import org.dinky.job.JobResult; import org.dinky.job.JobResult;
import org.dinky.mapper.TaskMapper; import org.dinky.mapper.TaskMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl; import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.parser.SqlType;
import org.dinky.process.annotations.ProcessStep; import org.dinky.process.annotations.ProcessStep;
import org.dinky.process.enums.ProcessStepType; import org.dinky.process.enums.ProcessStepType;
import org.dinky.service.AlertGroupService; import org.dinky.service.AlertGroupService;
...@@ -83,11 +81,9 @@ import org.dinky.service.TaskVersionService; ...@@ -83,11 +81,9 @@ import org.dinky.service.TaskVersionService;
import org.dinky.service.UDFTemplateService; import org.dinky.service.UDFTemplateService;
import org.dinky.service.UserService; import org.dinky.service.UserService;
import org.dinky.service.task.BaseTask; import org.dinky.service.task.BaseTask;
import org.dinky.trans.Operations;
import org.dinky.utils.FragmentVariableUtils; import org.dinky.utils.FragmentVariableUtils;
import org.dinky.utils.JsonUtils; import org.dinky.utils.JsonUtils;
import org.dinky.utils.RunTimeUtil; import org.dinky.utils.RunTimeUtil;
import org.dinky.utils.SqlUtil;
import org.dinky.utils.UDFUtils; import org.dinky.utils.UDFUtils;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
...@@ -98,7 +94,6 @@ import java.io.InputStreamReader; ...@@ -98,7 +94,6 @@ import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
...@@ -793,16 +788,4 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -793,16 +788,4 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
return treeNodes; return treeNodes;
} }
@Override
public List<String> getPrintTables(String statement) {
// TODO: 2023/4/7 this function not support variable sql, because, JobManager and executor
// couple function
// and status and task execute.
final String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement));
return Arrays.stream(statements)
.filter(t -> SqlType.PRINT.equals(Operations.getOperationType(t)))
.flatMap(t -> Arrays.stream(PrintStatementExplainer.splitTableNames(t)))
.collect(Collectors.toList());
}
} }
/*
*
* 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.service.sse;
public interface SseService {}
/*
*
* 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.service.sse.impl;
import org.dinky.service.sse.SseService;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Service
@RequiredArgsConstructor
@Slf4j
public class SseServiceImpl implements SseService {}
...@@ -21,17 +21,4 @@ package org.dinky.service.impl; ...@@ -21,17 +21,4 @@ package org.dinky.service.impl;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test; class PrintTableServiceImplTest {}
class PrintTableServiceImplTest {
@Test
void getDestination() {
String tableName = "`default_catalog`.`default_database`.`Orders`";
String result = PrintTableServiceImpl.getDestination(tableName);
assertEquals("/topic/table/`default_catalog`.`default_database`.`print_Orders`", result);
result = PrintTableServiceImpl.getDestination("Orders");
assertEquals("/topic/table/`default_catalog`.`default_database`.`print_Orders`", result);
}
}
/*
*
* 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 SseTopic {
METRICS("/TOPIC/METRICS"),
PROCESS_CONSOLE("/TOPIC/PROCESS_CONSOLE"),
PRINT_TABLE("/TOPIC/PRINT_TABLE"),
UNKNOWN("UNKNOWN");
private final String value;
SseTopic(String value) {
this.value = value;
}
public String getValue() {
return 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.
*
*/
import {useEffect, useRef, useState} from 'react'
import {postAll} from "@/services/api";
export type SseData = {
topic: string,
data: any
}
export type SubscriberData = {
topic: string[],
call: (data: SseData) => void
}
export default () => {
const uuidRef = useRef<string>(crypto.randomUUID());
const subscriberRef = useRef<SubscriberData[]>([]);
const [eventSource, setEventSource] = useState<EventSource>();
const subscribe = async () => {
const topics: string[] = []
subscriberRef.current.forEach(sub => topics.push(...sub.topic))
const para = {sessionKey: uuidRef.current, topics: topics}
await postAll('api/sse/subscribeTopic', para)
}
const reconnectSse = () => {
const sseUrl = '/api/sse/connect?sessionKey=' + uuidRef.current;
eventSource?.close();
setEventSource(new EventSource(sseUrl))
}
useEffect(() => {
reconnectSse();
}, []);
useEffect(() => {
if (eventSource) {
eventSource.onopen = () => subscribe();
eventSource.onmessage = (e) => {
const data: SseData = JSON.parse(e.data);
subscriberRef.current
.filter(sub => sub.topic.includes(data.topic))
.forEach(sub => sub.call(data));
}
}
}, [eventSource]);
const subscribeTopic = (topic: string[], onMessage: (data: SseData) => void) => {
const sub:SubscriberData = {topic: topic, call: onMessage}
subscriberRef.current = [...subscriberRef.current,sub];
subscribe()
return () => {
//组件卸载回调方法,取消订阅此topic
subscriberRef.current = subscriberRef.current.filter(item => item !== sub);
subscribe()
}
}
return {
subscribeTopic,
reconnectSse
}
}
import { getCurrentData } from '@/pages/DataStudio/function'; import { getCurrentData } from '@/pages/DataStudio/function';
import { StateType } from '@/pages/DataStudio/model'; import { StateType } from '@/pages/DataStudio/model';
import { getData, getSseData, postAll } from '@/services/api'; import { getData, postAll } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
import { l } from '@/utils/intl'; import { l } from '@/utils/intl';
import { connect } from '@@/exports'; import {connect, useModel} from '@@/exports';
import { Modal, Select, Tabs } from 'antd'; import { Modal, Select, Tabs } from 'antd';
import TextArea from 'antd/es/input/TextArea'; import TextArea from 'antd/es/input/TextArea';
import { Tab } from 'rc-tabs/lib/interface.d'; import { Tab } from 'rc-tabs/lib/interface.d';
import * as React from 'react'; import * as React from 'react';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import {SSE_TOPIC} from "@/pages/DevOps/constants";
import {SseData} from "@/models/Sse";
export async function getPrintTables(statement: string) { export async function getPrintTables(statement: string) {
return postAll('api/task/getPrintTables', { statement }); return postAll('api/printTable/getPrintTables', { statement });
} }
/*--- Clear Console ---*/ /*--- Clear Console ---*/
export function clearConsole() { export function clearConsole() {
return getData('api/process/clearConsole', {}); return getData('api/process/clearConsole', {});
} }
export type PrintTable = {
tableName:string,
fullTableName:string
}
const DataPage = (props: any) => { const DataPage = (props: any) => {
const { style, title } = props; const { style, title } = props;
const [consoleInfo, setConsoleInfo] = useState<string>(''); const [consoleInfo, setConsoleInfo] = useState<string>('');
const [eventSource, setEventSource] = useState<EventSource>(); const {subscribeTopic} = useModel('Sse',(model:any)=>({subscribeTopic:model.subscribeTopic}))
const [tableName, setTableName] = useState<string>(''); const [tableName, setTableName] = useState<string>('');
const onSearchName = (value: string) => {
if (!value) return;
eventSource?.close();
const eventSourceNew = getSseData(API_CONSTANTS.FLINK_TABLE_DATA + '?table=' + value);
eventSourceNew.onerror = (event: any) => {
console.log('EventSource failed:', event);
};
eventSourceNew.addEventListener('pt_data', (event: any) => {
setConsoleInfo((preConsoleInfo) => preConsoleInfo + '\n' + event.data);
});
setEventSource(eventSourceNew);
setTableName(value);
};
useEffect(() => { useEffect(() => {
onSearchName(title); if (title){
return eventSource?.close(); setTableName(title.tableName);
const topic = `${SSE_TOPIC.PRINT_TABLE}/${title.fullTableName}`
return subscribeTopic([topic],(data:SseData)=>{
setConsoleInfo((preConsoleInfo) => preConsoleInfo + '\n' + data.data);
});
}
}, []); }, []);
return <TextArea value={consoleInfo} style={{ width: style.width, height: style.height }} />; return <TextArea value={consoleInfo} style={{ width: style.width, height: style.height }} />;
...@@ -53,11 +47,11 @@ const TableData = (props: any) => { ...@@ -53,11 +47,11 @@ const TableData = (props: any) => {
const { statement, height } = props; const { statement, height } = props;
const [panes, setPanes] = useState<Tab[]>([]); const [panes, setPanes] = useState<Tab[]>([]);
function onOk(title: string) { function onOk(title: PrintTable) {
const activeKey = `${panes.length + 1}`; const activeKey = `${panes.length + 1}`;
const newPanes = [...panes]; const newPanes = [...panes];
newPanes.push({ newPanes.push({
label: title, label: title.tableName,
children: <DataPage title={title} style={{ width: '100%', height: height - 63 }} />, children: <DataPage title={title} style={{ width: '100%', height: height - 63 }} />,
key: activeKey key: activeKey
}); });
...@@ -67,21 +61,23 @@ const TableData = (props: any) => { ...@@ -67,21 +61,23 @@ const TableData = (props: any) => {
const addTab = async () => { const addTab = async () => {
if (!statement) return; if (!statement) return;
const result = await getPrintTables(statement); const result = await getPrintTables(statement);
const tables: [string] = result.datas; const tables: PrintTable[] = result.datas;
let title: string; let selectTable:PrintTable;
Modal.confirm({ Modal.confirm({
title: l('pages.datastudio.print.table.inputTableName'), title: l('pages.datastudio.print.table.inputTableName'),
content: ( content: (
<Select <Select
defaultValue='' defaultValue=''
style={{ width: '90%' }} style={{ width: '90%' }}
onChange={(e) => (title = e)} onChange={(e,t:any) => {
options={tables.map((table) => ({ value: table }))} selectTable = {tableName:t.label,fullTableName:t.value}
}}
options={tables.map((table) => ({ label:table.tableName, value: table.fullTableName }))}
/> />
), ),
onOk() { onOk() {
onOk(title); onOk(selectTable);
} }
}); });
}; };
......
...@@ -18,32 +18,27 @@ ...@@ -18,32 +18,27 @@
*/ */
import FlinkChart from '@/components/FlinkChart'; import FlinkChart from '@/components/FlinkChart';
import { JobMetricsItem } from '@/pages/DevOps/JobDetail/data'; 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 { MetricsDataType } from '@/pages/Metrics/Server/data'; import {MetricsDataType} from '@/pages/Metrics/Server/data';
import { getSseData } from '@/services/api'; import {connect} from '@@/exports';
import { API_CONSTANTS } from '@/services/endpoints'; import {Row, Spin} from 'antd';
import { connect } from '@@/exports'; import {useEffect, useState} from 'react';
import { Row, Spin } from 'antd'; import {useModel} from "umi";
import { useEffect, useState } from 'react'; import {SSE_TOPIC} from "@/pages/DevOps/constants";
import {SseData} from "@/models/Sse";
const JobChart = (props: any) => { const JobChart = (props: any) => {
const { jobDetail, metricsTarget, timeRange } = props; const {jobDetail, metricsTarget, timeRange} = props;
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 = `${API_CONSTANTS.MONITOR_GET_LAST_DATA}?lastTime=${new Date().getTime()}&keys=${ const {subscribeTopic} = useModel('Sse',(model:any)=>({subscribeTopic:model.subscribeTopic}))
jobDetail.instance.jid
}`;
const dataProcess = (chData: Record<string, ChartData[]>, data: MetricsDataType) => { const dataProcess = (chData: Record<string, ChartData[]>, data: MetricsDataType) => {
if (data.model == 'local') {
return;
}
const verticesMap = data.content as Record<string, Record<string, string>>; const verticesMap = data.content as Record<string, Record<string, string>>;
Object.keys(verticesMap).forEach((verticeId) => Object.keys(verticesMap).forEach((verticeId) =>
Object.keys(verticesMap[verticeId]).forEach((mertics) => { Object.keys(verticesMap[verticeId]).forEach((mertics) => {
...@@ -68,28 +63,18 @@ const JobChart = (props: any) => { ...@@ -68,28 +63,18 @@ const JobChart = (props: any) => {
endTime: timeRange.endTime, endTime: timeRange.endTime,
taskIds: jobDetail.instance.taskId taskIds: jobDetail.instance.taskId
}).then((result) => { }).then((result) => {
setLoading(false);
const chData = {}; const chData = {};
(result as MetricsDataType[]).forEach((d) => dataProcess(chData, d)); (result as MetricsDataType[]).forEach((d) => dataProcess(chData, d));
if (!timeRange.isReal) { setLoading(false);
eventSource?.close();
setEventSource(undefined);
} else {
if (!eventSource) {
setEventSource(getSseData(sseUrl));
}
}
}); });
}, [timeRange]);
useEffect(() => { if (timeRange.isReal){
if (eventSource && timeRange.isReal) { const topic = `${SSE_TOPIC.METRICS}/${jobDetail.instance.jid}`
eventSource.onmessage = (e) => { return subscribeTopic([topic],(data:SseData)=>{
let result = JSON.parse(e.data); dataProcess(chartDatas, data.data);
dataProcess(chartDatas, result); });
};
} }
}, [eventSource]); }, [timeRange]);
const renderMetricsCardList = ( const renderMetricsCardList = (
metricsList: Record<string, JobMetricsItem[]>, metricsList: Record<string, JobMetricsItem[]>,
...@@ -119,7 +104,7 @@ const JobChart = (props: any) => { ...@@ -119,7 +104,7 @@ const JobChart = (props: any) => {
); );
}; };
export default connect(({ Devops }: { Devops: DevopsType }) => ({ export default connect(({Devops}: { Devops: DevopsType }) => ({
jobDetail: Devops.jobInfoDetail, jobDetail: Devops.jobInfoDetail,
metricsTarget: Devops.metrics.jobMetricsTarget, metricsTarget: Devops.metrics.jobMetricsTarget,
layoutName: Devops.metrics.layoutName layoutName: Devops.metrics.layoutName
......
...@@ -26,7 +26,7 @@ import { Transfer } from 'antd'; ...@@ -26,7 +26,7 @@ import { Transfer } from 'antd';
const MetricsConfigTab = (props: any) => { const MetricsConfigTab = (props: any) => {
const { vertice, onValueChange, jobDetail, metricsTarget } = props; const { vertice, onValueChange, jobDetail, metricsTarget } = props;
const jobManagerUrl = jobDetail.cluster?.jobManagerHost; const jobManagerUrl = jobDetail.clusterInstance?.jobManagerHost;
const jobId = jobDetail.jobDataDto.job?.jid; const jobId = jobDetail.jobDataDto.job?.jid;
const { data } = useRequest({ const { data } = useRequest({
......
...@@ -40,3 +40,9 @@ export enum BackPressureStatus { ...@@ -40,3 +40,9 @@ export enum BackPressureStatus {
OK = 'ok', OK = 'ok',
HIGH = 'high' HIGH = 'high'
} }
export const SSE_TOPIC = {
METRICS: '/TOPIC/METRICS',
PROCESS_CONSOLE: '/TOPIC/PROCESS_CONSOLE',
PRINT_TABLE: '/TOPIC/PRINT_TABLE',
}
...@@ -19,19 +19,22 @@ ...@@ -19,19 +19,22 @@
import FlinkChart from '@/components/FlinkChart'; import FlinkChart from '@/components/FlinkChart';
import Job from '@/pages/Metrics/Job'; import Job from '@/pages/Metrics/Job';
import { ChartData, MetricsLayout } from '@/pages/Metrics/Job/data'; import {ChartData, MetricsLayout} from '@/pages/Metrics/Job/data';
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';
import GlobalFilter from '@/pages/Metrics/Server/GlobalFilter'; import GlobalFilter from '@/pages/Metrics/Server/GlobalFilter';
import { getMetricsLayout } from '@/pages/Metrics/service'; import {getMetricsLayout} from '@/pages/Metrics/service';
import { getSseData } from '@/services/api'; import {getSseData} from '@/services/api';
import { queryDataByParams } from '@/services/BusinessCrud'; import {queryDataByParams} from '@/services/BusinessCrud';
import { API_CONSTANTS } from '@/services/endpoints'; import {API_CONSTANTS} from '@/services/endpoints';
import { PageContainer, ProCard } from '@ant-design/pro-components'; 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 {useModel} from "@@/exports";
import {SSE_TOPIC} from "@/pages/DevOps/constants";
import {SseData} from "@/models/Sse";
const commonChartConfig: G2plotConfig = { const commonChartConfig: G2plotConfig = {
data: [], data: [],
...@@ -44,7 +47,6 @@ export default () => { ...@@ -44,7 +47,6 @@ export default () => {
const [jvmData] = useState<JVMMetric[]>([]); const [jvmData] = useState<JVMMetric[]>([]);
const [flinkMetricsData] = useState<FlinkMetricsData[]>([]); const [flinkMetricsData] = useState<FlinkMetricsData[]>([]);
const [chartDataList, setChartDataList] = useState<Record<string, ChartData[]>>({}); const [chartDataList, setChartDataList] = useState<Record<string, ChartData[]>>({});
const [eventSource, setEventSource] = useState<EventSource>();
const [endTime, setEndTime] = useState(new Date()); const [endTime, setEndTime] = useState(new Date());
const [dateRange, setDateRange] = useState<string>('60s'); const [dateRange, setDateRange] = useState<string>('60s');
const [custom, setCustom] = useState<boolean>(false); const [custom, setCustom] = useState<boolean>(false);
...@@ -53,6 +55,8 @@ export default () => { ...@@ -53,6 +55,8 @@ export default () => {
const [showDinkyServer, setShowDinkySever] = useState<boolean>(true); const [showDinkyServer, setShowDinkySever] = useState<boolean>(true);
const [loading, setLoading] = useState<boolean>(true); const [loading, setLoading] = useState<boolean>(true);
const {subscribeTopic} = useModel('Sse',(model:any)=>({subscribeTopic:model.subscribeTopic}))
/** /**
* Data processing * Data processing
* @param data * @param data
...@@ -92,30 +96,22 @@ export default () => { ...@@ -92,30 +96,22 @@ export default () => {
getInitData(); getInitData();
return () => { return () => clearInterval(timer);
clearInterval(timer);
eventSource?.close();
};
}, [startTime]); }, [startTime]);
useEffect(() => {
setEventSource(
getSseData(`${API_CONSTANTS.MONITOR_GET_LAST_DATA}?lastTime=${endTime.getTime()}&keys=local`)
);
}, [endTime]);
useEffect(() => { useEffect(() => {
setLayout(); setLayout();
}, []); }, []);
useEffect(() => { useEffect(() => {
!custom && if (!custom){
eventSource && const topic = `${SSE_TOPIC.METRICS}/local`
(eventSource.onmessage = (e) => { return subscribeTopic([topic],(data:SseData)=>{
let result = JSON.parse(e.data); dataProcess(data.data);
dataProcess(result);
}); });
}, [eventSource, custom]); }
}, [custom]);
const setLayout = async () => { const setLayout = async () => {
setLayoutData((await getMetricsLayout()).datas); setLayoutData((await getMetricsLayout()).datas);
}; };
...@@ -126,7 +122,7 @@ export default () => { ...@@ -126,7 +122,7 @@ export default () => {
}).then((res) => { }).then((res) => {
jvmData.length = 0; jvmData.length = 0;
flinkMetricsData.length = 0; flinkMetricsData.length = 0;
(res as MetricsDataType[]).forEach((d) => dataProcess(d)); (res as MetricsDataType[])?.forEach((d) => dataProcess(d));
}); });
queryDataByParams(API_CONSTANTS.SYSTEM_GET_ALL_CONFIG).then((res) => { queryDataByParams(API_CONSTANTS.SYSTEM_GET_ALL_CONFIG).then((res) => {
for (const config of res.metrics) { for (const config of res.metrics) {
...@@ -177,7 +173,10 @@ export default () => { ...@@ -177,7 +173,10 @@ export default () => {
}; };
return ( return (
<PageContainer title={false} loading={loading}> <PageContainer
title={false}
// loading={loading}
>
<ProCard size={'small'} colSpan={'100%'} bordered> <ProCard size={'small'} colSpan={'100%'} bordered>
<GlobalFilter <GlobalFilter
custom={custom} custom={custom}
...@@ -190,7 +189,7 @@ export default () => { ...@@ -190,7 +189,7 @@ export default () => {
</ProCard> </ProCard>
{showDinkyServer && ( {showDinkyServer && (
<ProCard collapsible title={'Dinky Server'} ghost hoverable bordered headerBordered> <ProCard collapsible title={'Dinky Server'} ghost hoverable bordered headerBordered>
<Server chartConfig={commonChartConfig} data={jvmData} /> <Server chartConfig={commonChartConfig} data={jvmData}/>
</ProCard> </ProCard>
)} )}
{layoutData != undefined && {layoutData != undefined &&
...@@ -226,7 +225,7 @@ export default () => { ...@@ -226,7 +225,7 @@ export default () => {
</ProCard> </ProCard>
); );
})} })}
<Job /> <Job/>
</PageContainer> </PageContainer>
); );
}; };
...@@ -42,6 +42,8 @@ const Login: React.FC = () => { ...@@ -42,6 +42,8 @@ const Login: React.FC = () => {
const [localStorageOfToken, setLocalStorageOfToken] = useLocalStorage('token', ''); const [localStorageOfToken, setLocalStorageOfToken] = useLocalStorage('token', '');
const {reconnectSse} = useModel('Sse',(model:any)=>({reconnectSse:model.reconnectSse}))
const containerClassName = useEmotionCss(() => { const containerClassName = useEmotionCss(() => {
return { return {
display: 'flex', display: 'flex',
...@@ -93,9 +95,11 @@ const Login: React.FC = () => { ...@@ -93,9 +95,11 @@ const Login: React.FC = () => {
* After the selection is complete, refresh all user information * After the selection is complete, refresh all user information
*/ */
await fetchUserInfo(); await fetchUserInfo();
/** /**
* Redirect to home page * Redirect to home page && reconnect Global Sse
*/ */
reconnectSse()
gotoRedirectUrl(); gotoRedirectUrl();
} else { } else {
ErrorMessage(l('login.chooseTenantFailed')); ErrorMessage(l('login.chooseTenantFailed'));
......
...@@ -194,7 +194,7 @@ declare namespace Jobs { ...@@ -194,7 +194,7 @@ declare namespace Jobs {
export type JobInfoDetail = { export type JobInfoDetail = {
id: number; id: number;
instance: JobInstance; instance: JobInstance;
cluster: any; clusterInstance: any;
clusterConfiguration: any; clusterConfiguration: any;
history: History; history: History;
jobDataDto: JobDataDtoItem; jobDataDto: JobDataDtoItem;
......
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