Unverified Commit 273b76eb authored by Licho's avatar Licho Committed by GitHub

feat: watch every table data for debug (#1746)

* feat: add flink-connector-udp * feat: add PrintNetSink * feat: rename PrintNetSink * fix: rename Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * feat: cloud receive. * feat: could receive result * feat: auto get ip * fix: printnet pom.xml Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * fix: flink-all printnet default flink version * Spotless Apply * fix: other flink version Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * fix: 2.12 Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * fix: flink 2.12 Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * Spotless Apply * fix: 1.12 Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * fix: 12 13 14 Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * chore Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * feat: Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * Spotless Apply * feat: add listen udp port and receive data. * Spotless Apply * fix: remove 1.12 Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * refactor: move printnet to executor module * Spotless Apply * chore: remove flink.version Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * chore: constant port Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * feat: add support websocket STOMP protocol * feat: adjust websocket buffer size and others * feat: register watch table entry point * Spotless Apply * feat: @PutMapping * Spotless Apply * feat: modify watch controller url * refactor: watch controller and table full name replace with print_ * Spotless Apply * feat: add watch table data front code * feat: create destination * fix: add file * feat: create destination * fix: add display table data * Spotless Apply * refactor: modify for review --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com> Co-authored-by: 's avatarLicho <licho.sun@gmail.com>
parent bc889bfe
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.yaml</groupId> <groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId> <artifactId>snakeyaml</artifactId>
...@@ -47,6 +48,10 @@ ...@@ -47,6 +48,10 @@
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId> <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId> <artifactId>spring-boot-configuration-processor</artifactId>
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.configure;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/stomp").setAllowedOrigins("*");
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
registry.setCacheLimit(1024 * 1024);
}
}
/*
*
* 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.controller;
import org.dinky.common.result.Result;
import org.dinky.service.WatchTableService;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lombok.AllArgsConstructor;
@RestController
@AllArgsConstructor
@RequestMapping("api")
public class WatchTableController {
private final WatchTableService watchTableService;
@PutMapping("/subscribe/watch")
public Result subscribe(@RequestParam Integer id, @RequestParam String table) {
String destination = watchTableService.registerListenEntry(id, table);
return Result.succeed(destination);
}
@PutMapping("/unSubscribe/watch")
public Result unsubscribe(@RequestParam Integer id, @RequestParam String table) {
watchTableService.unRegisterListenEntry(id, table);
return Result.succeed();
}
}
/*
*
* 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;
public interface WatchTableService {
String registerListenEntry(Integer userId, String table);
void unRegisterListenEntry(Integer userId, String table);
}
...@@ -1403,7 +1403,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1403,7 +1403,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public void handleJobDone(JobInstance jobInstance) { public void handleJobDone(JobInstance jobInstance) {
if (Asserts.isNull(jobInstance.getTaskId())) { if (Asserts.isNull(jobInstance.getTaskId()) || Asserts.isNull(jobInstance.getType())) {
return; return;
} }
......
/*
*
* 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.impl;
import org.dinky.service.WatchTableService;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class WatchTableServiceImpl implements WatchTableService {
private final SimpMessagingTemplate messagingTemplate;
private final Map<String, Set<String>> registerTableMap = new ConcurrentHashMap<>();
private static final Pattern FULL_TABLE_NAME_PATTERN =
Pattern.compile("^`([^\\.]+)`\\.`([^\\.]+)`\\.`([^\\.]+)`$");
public WatchTableServiceImpl(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
WatchTableListener watcher = new WatchTableListener(this::send);
watcher.start();
}
public void send(String message) {
try {
String[] data = message.split("\n", 2);
final Set<String> destinations = registerTableMap.get(data[0]);
if (destinations != null) {
destinations.forEach(d -> this.messagingTemplate.convertAndSend(d, data[1]));
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
@Override
public String registerListenEntry(Integer userId, String table) {
String fullName = getFullTableName(table);
String destination = getDestinationByFullName(userId, fullName);
Set<String> destinations = registerTableMap.get(fullName);
if (destinations == null) {
registerTableMap.put(fullName, new HashSet<>(Arrays.asList(destination)));
} else {
destinations.add(destination);
}
return destination;
}
@Override
public void unRegisterListenEntry(Integer userId, String table) {
String fullName = getFullTableName(table);
String destination = getDestination(userId, fullName);
Set<String> destinations = registerTableMap.get(fullName);
if (destinations != null) {
destinations.remove(destination);
}
}
public static String getFullTableName(String table) {
if (table == null) {
throw new NullPointerException("table name empty");
}
Matcher matcher = FULL_TABLE_NAME_PATTERN.matcher(table);
String result = "";
if (matcher.matches()) {
result = matcher.replaceAll("`$1`.`$2`.`print_$3`");
} else {
result = String.format("`default_catalog`.`default_database`.`print_%s`", table);
}
return result;
}
public static String getDestination(Integer userId, String table) {
String fn = getFullTableName(table);
return String.format("/topic/table/%s/%s", userId, fn);
}
public static String getDestinationByFullName(Integer userId, String tableFullName) {
return String.format("/topic/table/%s/%s", userId, tableFullName);
}
public static class WatchTableListener extends Thread {
private final Consumer<String> consumer;
public static final int PORT = 7125;
private DatagramSocket socket;
private boolean running;
private byte[] buf = new byte[4096];
public WatchTableListener(Consumer<String> consumer) {
this.consumer = consumer;
try {
this.socket = new DatagramSocket(PORT);
} catch (SocketException e) {
log.error(e.getMessage());
}
}
public void run() {
running = true;
while (running) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
consumer.accept(received);
} catch (Exception e) {
log.error(e.getMessage());
}
}
socket.close();
}
public void stopThread() {
running = false;
}
}
}
/*
*
* 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.impl;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class WatchTableServiceImplTest {
@Test
void getDestination() {
String tableName = "`default_catalog`.`default_database`.`Orders`";
String result = WatchTableServiceImpl.getDestination(123, tableName);
assertEquals(
"/topic/table/123/`default_catalog`.`default_database`.`print_Orders`", result);
result = WatchTableServiceImpl.getDestination(123, "Orders");
assertEquals(
"/topic/table/123/`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.connector.printnet.sink;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.connector.format.EncodingFormat;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.connector.sink.SinkFunctionProvider;
import org.apache.flink.table.connector.sink.abilities.SupportsPartitioning;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.DataType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class PrintNetDynamicTableSink implements DynamicTableSink, SupportsPartitioning {
private final String hostname;
private final int port;
private final EncodingFormat<SerializationSchema<RowData>> encodingFormat;
private final DataType type;
private final int parallelism;
private final List<String> partitionKeys;
private String printIdentifier;
private ObjectIdentifier objectIdentifier;
private Map<String, String> staticPartitions = new LinkedHashMap<>();
public PrintNetDynamicTableSink(
DataType type,
List<String> partitionKeys,
EncodingFormat<SerializationSchema<RowData>> serializingFormat,
String hostname,
int port,
int parallelism,
String printIdentifier,
ObjectIdentifier objectIdentifier) {
this.hostname = hostname;
this.port = port;
this.encodingFormat = serializingFormat;
this.type = type;
this.parallelism = parallelism;
this.partitionKeys = partitionKeys;
this.printIdentifier = printIdentifier;
this.objectIdentifier = objectIdentifier;
}
@Override
public ChangelogMode getChangelogMode(ChangelogMode requestedMode) {
return requestedMode;
}
@Override
public SinkRuntimeProvider getSinkRuntimeProvider(Context context) {
final SerializationSchema<RowData> serializer =
encodingFormat != null ? encodingFormat.createRuntimeEncoder(context, type) : null;
DataStructureConverter converter = context.createDataStructureConverter(type);
if (printIdentifier == null) {
printIdentifier = objectIdentifier.asSerializableString();
}
staticPartitions.forEach(
(key, value) -> {
printIdentifier = null != printIdentifier ? printIdentifier + ":" : "";
printIdentifier += key + "=" + value;
});
return SinkFunctionProvider.of(
new PrintNetSinkFunction(hostname, port, serializer, converter, printIdentifier),
parallelism);
}
@Override
public DynamicTableSink copy() {
return new PrintNetDynamicTableSink(
type,
partitionKeys,
encodingFormat,
hostname,
port,
parallelism,
printIdentifier,
objectIdentifier);
}
@Override
public String asSummaryString() {
return "Print Net Sink";
}
@Override
public void applyStaticPartition(Map<String, String> partition) {
// make it a LinkedHashMap to maintain partition column order
staticPartitions = new LinkedHashMap<>();
for (String partitionCol : partitionKeys) {
if (partition.containsKey(partitionCol)) {
staticPartitions.put(partitionCol, partition.get(partitionCol));
}
}
}
}
/*
*
* 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.connector.printnet.sink;
import static org.apache.flink.configuration.ConfigOptions.key;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.connector.format.EncodingFormat;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.factories.DynamicTableSinkFactory;
import org.apache.flink.table.factories.FactoryUtil;
import org.apache.flink.table.factories.SerializationFormatFactory;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class PrintNetDynamicTableSinkFactory implements DynamicTableSinkFactory {
public static final String IDENTIFIER = "printnet";
public static final ConfigOption<String> HOSTNAME =
ConfigOptions.key("hostName").stringType().defaultValue("127.0.0.1");
public static final ConfigOption<Integer> PORT =
ConfigOptions.key("port").intType().noDefaultValue();
public static final ConfigOption<String> PRINT_IDENTIFIER =
key("print-identifier")
.stringType()
.noDefaultValue()
.withDescription(
"Message that identify print and is prefixed to the output of the value.");
@Override
public DynamicTableSink createDynamicTableSink(Context context) {
final FactoryUtil.TableFactoryHelper helper =
FactoryUtil.createTableFactoryHelper(this, context);
ObjectIdentifier objectIdentifier = context.getObjectIdentifier();
final ReadableConfig options = helper.getOptions();
FactoryUtil.validateFactoryOptions(this, options);
EncodingFormat<SerializationSchema<RowData>> serializingFormat = null;
try {
// TODO: 2023/3/17 maybe not right
serializingFormat =
helper.discoverEncodingFormat(
SerializationFormatFactory.class, FactoryUtil.FORMAT);
} catch (Exception ignored) {
}
return new PrintNetDynamicTableSink(
context.getCatalogTable().getResolvedSchema().toPhysicalRowDataType(),
context.getCatalogTable().getPartitionKeys(),
serializingFormat,
options.get(HOSTNAME),
options.get(PORT),
options.get(FactoryUtil.SINK_PARALLELISM),
options.get(PRINT_IDENTIFIER),
objectIdentifier);
}
@Override
public String factoryIdentifier() {
return IDENTIFIER;
}
@Override
public Set<ConfigOption<?>> requiredOptions() {
return new HashSet<>(Arrays.asList(HOSTNAME, PORT));
}
@Override
public Set<ConfigOption<?>> optionalOptions() {
return new HashSet<>(
Arrays.asList(PRINT_IDENTIFIER, FactoryUtil.SINK_PARALLELISM, FactoryUtil.FORMAT));
}
}
/*
*
* 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.connector.printnet.sink;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.operators.StreamingRuntimeContext;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.data.RowData;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class PrintNetSinkFunction extends RichSinkFunction<RowData> {
private final String hostname;
private final int port;
private final SerializationSchema<RowData> serializer;
private DynamicTableSink.DataStructureConverter converter;
private String printIdentifier;
private byte[] printHeader;
private volatile boolean running = true;
private DatagramSocket socket;
private final InetAddress target;
public PrintNetSinkFunction(
String hostname,
int port,
SerializationSchema<RowData> serializer,
DynamicTableSink.DataStructureConverter converter,
String printIdentifier) {
this.hostname = hostname;
this.port = port;
this.serializer = serializer;
this.converter = converter;
this.printIdentifier = printIdentifier;
printHeader = (printIdentifier + "\n").getBytes();
try {
this.target = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
if (serializer != null) {
serializer.open(null);
}
StreamingRuntimeContext context = (StreamingRuntimeContext) getRuntimeContext();
socket = new DatagramSocket();
}
@Override
public void invoke(RowData value, Context context) throws IOException {
try {
byte[] buf =
serializer != null
? serializer.serialize(value)
: converter.toExternal(value).toString().getBytes();
byte[] target = new byte[printHeader.length + buf.length];
System.arraycopy(printHeader, 0, target, 0, printHeader.length);
System.arraycopy(buf, 0, target, printHeader.length, buf.length);
DatagramPacket packet = new DatagramPacket(target, target.length, this.target, port);
socket.send(packet);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
...@@ -85,7 +85,7 @@ public class Operations { ...@@ -85,7 +85,7 @@ public class Operations {
String sql = statement.replace("\n", " ").replaceAll("\\s+", " ").trim().toUpperCase(); String sql = statement.replace("\n", " ").replaceAll("\\s+", " ").trim().toUpperCase();
return Arrays.stream(ALL_OPERATIONS) return Arrays.stream(ALL_OPERATIONS)
.filter(p -> sql.startsWith(p.getHandle())) .filter(p -> p.getHandle() != null && sql.startsWith(p.getHandle()))
.findFirst() .findFirst()
.map(p -> p.create(statement)) .map(p -> p.create(statement))
.orElse(null); .orElse(null);
......
/*
*
* 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.trans.ddl;
import org.dinky.executor.Executor;
import org.dinky.trans.AbstractOperation;
import org.dinky.trans.Operation;
import org.apache.flink.table.api.TableResult;
public class PrintTableOperation extends AbstractOperation implements Operation {
@Override
public String getHandle() {
return "Print";
}
@Override
public Operation create(String statement) {
return null;
}
@Override
public TableResult build(Executor executor) {
return null;
}
}
/*
*
* 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.trans.ddl;
import org.dinky.executor.Executor;
import org.dinky.trans.AbstractOperation;
import org.dinky.trans.Operation;
import org.apache.flink.table.api.TableResult;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WatchTableOperation extends AbstractOperation implements Operation {
private static final String KEY_WORD = "WATCH";
public static final String PATTERN_STR = "WATCH (.+)";
public static final Pattern PATTERN = Pattern.compile(PATTERN_STR, Pattern.CASE_INSENSITIVE);
public static final String CREATE_SQL_TEMPLATE =
"CREATE TABLE print_{0} WITH (''connector'' = ''printnet'', "
+ "''port''=''{2,number,#}'', ''hostName'' = ''{1}'', ''sink.parallelism''=''{3}'')\n"
+ "LIKE {0};";
public static final String INSERT_SQL_TEMPLATE = "insert into print_{0} select * from {0};";
public static final int PORT = 7125;
public WatchTableOperation() {}
public WatchTableOperation(String statement) {
super(statement);
}
@Override
public String getHandle() {
return KEY_WORD;
}
@Override
public Operation create(String statement) {
return new WatchTableOperation(statement);
}
@Override
public TableResult build(Executor executor) {
Matcher matcher = PATTERN.matcher(statement);
matcher.find();
String tableName = matcher.group(1);
Optional<InetAddress> address = getSystemLocalIp();
String ip = address.isPresent() ? address.get().getHostAddress() : "127.0.0.1";
String printCreateSql = MessageFormat.format(CREATE_SQL_TEMPLATE, tableName, ip, PORT, 1);
executor.getCustomTableEnvironment().executeSql(printCreateSql);
String printInsertSql = MessageFormat.format(INSERT_SQL_TEMPLATE, tableName);
return executor.getCustomTableEnvironment().executeSql(printInsertSql);
}
private Optional<InetAddress> getSystemLocalIp() {
try {
InetAddress ip = InetAddress.getLocalHost();
return Optional.of(ip);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
}
org.dinky.connector.printnet.sink.PrintNetDynamicTableSinkFactory
...@@ -88,7 +88,9 @@ ...@@ -88,7 +88,9 @@
"react-highlight-words": "^0.17.0", "react-highlight-words": "^0.17.0",
"react-lineage-dag": "^1.0.0", "react-lineage-dag": "^1.0.0",
"react-monaco-editor": "^0.43.0", "react-monaco-editor": "^0.43.0",
"sockjs-client": "^1.6.1",
"sql-formatter": "^4.0.2", "sql-formatter": "^4.0.2",
"stompjs": "^2.3.3",
"umi": "^3.5.0", "umi": "^3.5.0",
"umi-serve": "^1.9.10" "umi-serve": "^1.9.10"
}, },
...@@ -100,8 +102,11 @@ ...@@ -100,8 +102,11 @@
"@types/jest": "^26.0.0", "@types/jest": "^26.0.0",
"@types/lodash": "^4.14.144", "@types/lodash": "^4.14.144",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/react-custom-scrollbars": "^4.0.10",
"@types/react-dom": "^17.0.0", "@types/react-dom": "^17.0.0",
"@types/react-helmet": "^6.1.0", "@types/react-helmet": "^6.1.0",
"@types/sockjs-client": "^1.5.1",
"@types/stompjs": "^2.3.5",
"@umijs/fabric": "^2.5.2", "@umijs/fabric": "^2.5.2",
"@umijs/plugin-blocks": "^2.0.5", "@umijs/plugin-blocks": "^2.0.5",
"@umijs/plugin-esbuild": "^1.0.1", "@umijs/plugin-esbuild": "^1.0.1",
......
...@@ -136,7 +136,7 @@ export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => ...@@ -136,7 +136,7 @@ export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) =>
enableDarkTheme enableDarkTheme
settings={initialState?.settings} settings={initialState?.settings}
onSettingChange={(settings) => { onSettingChange={(settings) => {
setInitialState((preInitialState) => ({ setInitialState((preInitialState: any) => ({
...preInitialState, ...preInitialState,
settings, settings,
})); }));
......
/*
*
* 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 { Input, Space } from "antd";
const { Search } = Input;
import { StateType } from "@/pages/DataStudio/model";
import { registerWatchTable, unRegisterWatchTable } from "@/pages/DataStudio/service";
import { connect } from "umi";
import { useEffect, useState, useRef } from "react";
import stompClient from "@/utils/stompClient"
import { Scrollbars } from 'react-custom-scrollbars';
import CodeShow from "@/components/Common/CodeShow";
const StudioData = (props: any) => {
const { height, isActive } = props;
const [consoleInfo, setConsoleInfo] = useState<string>("");
const [tableName, setTableName] = useState<string>("");
const preTableNameRef = useRef(tableName)
const preTableName = preTableNameRef.current
let consoleHeight = (height - 37.6);
const id = Number(localStorage.getItem('dlink-tenantId'));
const onSearchName = (value: string) => {
unRegisterWatchTable({ id, table: preTableName }).then(res => {
setConsoleInfo("")
stompClient.unsubscribe();
registerWatchTable({ id, table: value }).then(res => {
stompClient.subObj = stompClient.mqClient.subscribe(res.msg, (res) => {
setConsoleInfo(consoleInfo + res.body)
})
})
})
setTableName(value)
};
useEffect(() => {
stompClient.con();
}, [isActive])
return (<div style={{ width: '100%' }}>
<Space direction="horizontal" style={{ margin: 10 }}>
<Search placeholder="请输入表名" onSearch={onSearchName} style={{ width: 200 }} />
</Space>
<Scrollbars style={{ height: consoleHeight }}>
{/* <CodeShow code={consoleInfo} language='Markdown' height={height} theme="vs" /> */}
<CodeShow code={JSON.stringify((consoleInfo ? consoleInfo : ""), null, "\t")} language='json'
height={height} theme="vs-dark" />
</Scrollbars>
</div>)
};
export default connect(({ Studio }: { Studio: StateType }) => ({
current: Studio.current,
}))(StudioData);
...@@ -18,34 +18,35 @@ ...@@ -18,34 +18,35 @@
*/ */
import {Empty, Tabs} from "antd"; import { Empty, Tabs } from "antd";
import { import {
ApartmentOutlined, ApartmentOutlined,
BarChartOutlined, BarChartOutlined,
CalendarOutlined, CalendarOutlined,
CodeOutlined, CodeOutlined,
DesktopOutlined, DesktopOutlined, PrinterOutlined,
TableOutlined TableOutlined
} from "@ant-design/icons"; } from "@ant-design/icons";
import {StateType} from "@/pages/DataStudio/model"; import { StateType } from "@/pages/DataStudio/model";
import {connect} from "umi"; import { connect } from "umi";
import StudioMsg from "./StudioMsg"; import StudioMsg from "./StudioMsg";
import StudioTable from "./StudioTable"; import StudioTable from "./StudioTable";
import StudioHistory from "./StudioHistory"; import StudioHistory from "./StudioHistory";
import StudioData from "./StudioData"
import StudioCA from "./StudioCA"; import StudioCA from "./StudioCA";
import StudioProcess from "./StudioProcess"; import StudioProcess from "./StudioProcess";
import {Scrollbars} from 'react-custom-scrollbars'; import { Scrollbars } from 'react-custom-scrollbars';
import Chart from "@/components/Chart"; import Chart from "@/components/Chart";
import {useState} from "react"; import React, { useState } from "react";
import {l} from "@/utils/intl"; import { l } from "@/utils/intl";
const {TabPane} = Tabs; const { TabPane } = Tabs;
const StudioConsole = (props: any) => { const StudioConsole = (props: any) => {
const {height, current} = props; const { height, current } = props;
let consoleHeight = (height - 37.6); let consoleHeight = (height - 37.6);
const [activeKey, setActiveKey] = useState<string>("StudioMsg"); const [activeKey, setActiveKey] = useState<string>("StudioMsg");
...@@ -60,99 +61,97 @@ const StudioConsole = (props: any) => { ...@@ -60,99 +61,97 @@ const StudioConsole = (props: any) => {
<TabPane <TabPane
tab={ tab={
<span> <span>
<CodeOutlined/> <CodeOutlined />
{l('pages.datastudio.label.info')} {l('pages.datastudio.label.info')}
</span> </span>
} }
key="StudioMsg" key="StudioMsg"
> >
<Scrollbars style={{height: consoleHeight}}> <Scrollbars style={{ height: consoleHeight }}>
<StudioMsg height={consoleHeight} isActive={activeKey === "StudioMsg"}/> <StudioMsg height={consoleHeight} isActive={activeKey === "StudioMsg"} />
</Scrollbars> </Scrollbars>
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<TableOutlined/> <TableOutlined />
{l('pages.datastudio.label.result')} {l('pages.datastudio.label.result')}
</span> </span>
} }
key="StudioTable" key="StudioTable"
> >
<Scrollbars style={{height: consoleHeight}}> <Scrollbars style={{ height: consoleHeight }}>
{current ? <StudioTable/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>} {current ? <StudioTable /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
</Scrollbars> </Scrollbars>
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<BarChartOutlined/> <BarChartOutlined />
BI BI
</span> </span>
} }
key="StudioChart" key="StudioChart"
> >
<Scrollbars style={{height: consoleHeight}}> <Scrollbars style={{ height: consoleHeight }}>
{current ? <Chart height={consoleHeight}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>} {current ? <Chart height={consoleHeight} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
</Scrollbars> </Scrollbars>
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<ApartmentOutlined/> <ApartmentOutlined />
{l('pages.datastudio.label.lineage')} {l('pages.datastudio.label.lineage')}
</span> </span>
} }
key="StudioConsanguinity" key="StudioConsanguinity"
> >
<Scrollbars style={{height: consoleHeight}}> <Scrollbars style={{ height: consoleHeight }}>
{current ? <StudioCA/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>} {current ? <StudioCA /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
</Scrollbars> </Scrollbars>
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<DesktopOutlined/> <DesktopOutlined />
{l('pages.datastudio.label.process')} {l('pages.datastudio.label.process')}
</span> </span>
} }
key="StudioProcess" key="StudioProcess"
> >
<Scrollbars style={{height: consoleHeight}}> <Scrollbars style={{ height: consoleHeight }}>
<StudioProcess/> <StudioProcess />
</Scrollbars> </Scrollbars>
</TabPane> </TabPane>
<TabPane <TabPane
tab={ tab={
<span> <span>
<CalendarOutlined/> <CalendarOutlined />
{l('pages.datastudio.label.history')} {l('pages.datastudio.label.history')}
</span> </span>
} }
key="StudioHistory" key="StudioHistory"
> >
<Scrollbars style={{height: consoleHeight}}> <Scrollbars style={{ height: consoleHeight }}>
<StudioHistory/> <StudioHistory />
</Scrollbars> </Scrollbars>
</TabPane> </TabPane>
{/*<TabPane*/} <TabPane
{/* tab={*/} tab={
{/* <span>*/} <span>
{/* <FunctionOutlined/>*/} <PrinterOutlined />
{/* {l('pages.datastudio.label.function')}*/} {l('pages.datastudio.label.data')}
{/* </span>*/} </span>
{/* }*/} }
{/* key="StudioFX"*/} key="StudioData"
{/*>*/} >
{/* <Scrollbars style={{height: consoleHeight}}>*/} <StudioData height={consoleHeight} isActive={activeKey === "StudioData"} />
{/* <StudioFX/>*/} </TabPane>
{/* </Scrollbars>*/}
{/*</TabPane>*/}
</Tabs> </Tabs>
); );
}; };
export default connect(({Studio}: { Studio: StateType }) => ({ export default connect(({ Studio }: { Studio: StateType }) => ({
sql: Studio.sql, sql: Studio.sql,
current: Studio.current, current: Studio.current,
}))(StudioConsole); }))(StudioConsole);
...@@ -64,6 +64,11 @@ export type StudioParam = { ...@@ -64,6 +64,11 @@ export type StudioParam = {
savePointPath?: string, savePointPath?: string,
} }
export type WatchParam = {
id: number,
table: string
}
export type StudioMetaStoreParam = { export type StudioMetaStoreParam = {
statement?: string, statement?: string,
fragment?: boolean, fragment?: boolean,
......
...@@ -35,7 +35,6 @@ const {TabPane} = Tabs; ...@@ -35,7 +35,6 @@ const {TabPane} = Tabs;
const EditorTabs = (props: any) => { const EditorTabs = (props: any) => {
const {tabs, current, toolHeight, width, height} = props; const {tabs, current, toolHeight, width, height} = props;
const onChange = (activeKey: any) => { const onChange = (activeKey: any) => {
props.saveToolHeight(toolHeight); props.saveToolHeight(toolHeight);
props.changeActiveKey(activeKey); props.changeActiveKey(activeKey);
...@@ -46,9 +45,6 @@ const EditorTabs = (props: any) => { ...@@ -46,9 +45,6 @@ const EditorTabs = (props: any) => {
add(); add();
} else if (action === 'remove') { } else if (action === 'remove') {
props.saveToolHeight(toolHeight - 0.0001); props.saveToolHeight(toolHeight - 0.0001);
// if (current.isModified) {
// saveTask(current, dispatch);
// }
remove(targetKey); remove(targetKey);
} }
}; };
......
...@@ -369,6 +369,7 @@ export default { ...@@ -369,6 +369,7 @@ export default {
'pages.datastudio.label.structure': 'Structure', 'pages.datastudio.label.structure': 'Structure',
'pages.datastudio.label.cluster': 'Cluster', 'pages.datastudio.label.cluster': 'Cluster',
'pages.datastudio.label.datasource': 'Data Source', 'pages.datastudio.label.datasource': 'Data Source',
'pages.datastudio.label.data': 'Table Data',
'pages.datastudio.label.meta': 'Meta Data', 'pages.datastudio.label.meta': 'Meta Data',
'pages.datastudio.label.globalvariable': 'Global Variable', 'pages.datastudio.label.globalvariable': 'Global Variable',
'pages.datastudio.label.guidepage': 'Guide Page', 'pages.datastudio.label.guidepage': 'Guide Page',
......
...@@ -369,6 +369,7 @@ export default { ...@@ -369,6 +369,7 @@ export default {
'pages.datastudio.label.structure': '结构', 'pages.datastudio.label.structure': '结构',
'pages.datastudio.label.cluster': '集群', 'pages.datastudio.label.cluster': '集群',
'pages.datastudio.label.datasource': '数据源', 'pages.datastudio.label.datasource': '数据源',
'pages.datastudio.label.data': '表数据',
'pages.datastudio.label.meta': '元数据', 'pages.datastudio.label.meta': '元数据',
'pages.datastudio.label.globalvariable': '全局变量', 'pages.datastudio.label.globalvariable': '全局变量',
'pages.datastudio.label.guidepage': '引导页', 'pages.datastudio.label.guidepage': '引导页',
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
*/ */
import {CAParam, StudioMetaStoreParam, StudioParam} from "@/components/Studio/StudioEdit/data"; import {CAParam, StudioMetaStoreParam, StudioParam, WatchParam} from "@/components/Studio/StudioEdit/data";
import {request2} from "@/components/Common/crud"; import {request2} from "@/components/Common/crud";
import {request} from "umi"; import {request} from "umi";
...@@ -76,6 +76,24 @@ export async function getJobData(jobId: string) { ...@@ -76,6 +76,24 @@ export async function getJobData(jobId: string) {
}); });
} }
export async function registerWatchTable(params?: WatchParam) {
return request2<API.Result>('/api/subscribe/watch', {
method : 'PUT',
params : {
...params,
}
})
}
export async function unRegisterWatchTable(params?: WatchParam) {
return request2<API.Result>('/api/unSubscribe/watch', {
method : 'PUT',
params : {
...params,
}
})
}
export async function getCatalogueTreeData(params?: StudioParam) { export async function getCatalogueTreeData(params?: StudioParam) {
return request2<API.Result>('/api/catalogue/getCatalogueTreeData', { return request2<API.Result>('/api/catalogue/getCatalogueTreeData', {
method: 'POST', method: 'POST',
......
import { reject } from "lodash";
import Stomp, { Subscription } from "stompjs";
interface SocketRes {
body: string,
ack?: () => {},
command?: string,
headers?: object,
nack?: () => {},
}
export let stompClient: Stomp.Client;
let connetStatus = false;
class MyStompClient {
mqClient: Stomp.Client;
connetStatus: boolean;
subObj: Subscription;
constructor() {
const baseUrl = "ws://127.0.0.1:8888/stomp";
let socket = new WebSocket(baseUrl);
this.mqClient = Stomp.over(socket);
this.connetStatus = false;
this.subObj = { id: "", unsubscribe: () => { } };
this.con();
}
con() {
this.mqClient.connect(
{},
() => {
this.connetStatus = true;
console.log("connectsuccess>>>>>>>>>>>>>>>>>>>");
},
(err: any) => {
console.log("error");
console.log(err);
}
);
}
close() {
if (this.mqClient) {
this.mqClient.disconnect(() => {
console.log("============connect release============");
this.connetStatus = false;
});
}
}
subscribe(topicurl: string) {
return new Promise<string>((resolve, reject) => {
this.subObj = this.mqClient.subscribe(topicurl, (res: SocketRes) => {
resolve(res.body)
})
}).catch(err => {
console.log(err);
reject(err)
})
}
unsubscribe() {
this.subObj.unsubscribe()
this.subObj = { id: "", unsubscribe: () => { } };
}
}
export default new MyStompClient()
...@@ -888,7 +888,6 @@ ...@@ -888,7 +888,6 @@
<properties> <properties>
<!-- modify flink version --> <!-- modify flink version -->
<dinky.flink.version>1.16</dinky.flink.version> <dinky.flink.version>1.16</dinky.flink.version>
<flink.version>1.16.0</flink.version>
</properties> </properties>
</profile> </profile>
......
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