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

[Feature]support sql cli (#3605)

parent d15b8660
......@@ -19,26 +19,29 @@
package org.dinky.configure;
import org.springframework.context.annotation.Bean;
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;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/stomp").setAllowedOrigins("*");
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
registry.setCacheLimit(1024 * 1024);
}
// @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.context;
import org.dinky.gateway.SqlCliMode;
import org.dinky.gateway.SqlClientOptions;
import org.dinky.gateway.sqlgateway.cli.SqlClientAdapter;
import org.dinky.utils.CloseUtil;
import org.dinky.utils.JsonUtils;
import org.dinky.utils.LogUtil;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.ExecutorService;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
@ServerEndpoint("/ws/sql-gateway/")
public class SqlGatewayWsContext {
private Session session;
private SqlClientAdapter client;
private PipedInputStream in2web;
private long lastHeartTime = System.currentTimeMillis();
private boolean isRunning = true;
/**
* 最大化减少线程占用,默认线程为0,无最大限制,不保持线程,任务直接提交给线程
* */
private static final ExecutorService executor = ThreadUtil.newExecutor();
private void startClient(SqlClientOptions options) {
try {
PipedInputStream in2client = new PipedInputStream();
in2web = new PipedInputStream();
PipedOutputStream clientWrite2web = new PipedOutputStream(in2web);
clientWrite2web.write("Dinky Sql Client\n".getBytes());
client = new SqlClientAdapter(in2client, clientWrite2web, options);
executor.execute(() -> {
try {
log.info("Sql Client Start : " + options.getConnectAddress());
client.startClient();
} catch (Exception e) {
sendError(e);
}
});
executor.execute(() -> {
try {
int data;
byte[] bytes = new byte[1024];
while ((data = in2web.read(bytes)) != -1) {
session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytes, 0, data));
}
log.info("Sql Client Read Terminal Thread Closed :" + options.getConnectAddress());
} catch (IOException e) {
log.error("sql client receive error", e);
}
});
} catch (Exception e) {
sendError(e);
}
log.info("Sql Client Start Success : " + options.getConnectAddress());
}
private void sendError(Throwable err) {
try {
log.error("send error to client", err);
ByteBuffer byteBuffer = ByteBuffer.wrap(LogUtil.getError(err).getBytes());
session.getBasicRemote().sendBinary(byteBuffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
String cols = getParameter("cols", true);
String rows = getParameter("rows", true);
SqlClientOptions.TerminalSize size =
new SqlClientOptions.TerminalSize(Integer.parseInt(cols), Integer.parseInt(rows));
SqlClientOptions options = SqlClientOptions.builder()
.mode(SqlCliMode.fromString(getParameter("mode", true)))
.sessionId(getParameter("sessionId"))
.connectAddress(getParameter("connectAddress", true))
.initSql(getParameter("initSql"))
.historyFilePath("./tmp/flink-sql-history/history")
.terminalSize(size)
.build();
startClient(options);
executor.execute(() -> {
while (isRunning) {
try {
Thread.sleep(1000);
if (System.currentTimeMillis() - lastHeartTime > 1000 * 60) {
onClose();
}
} catch (Exception e) {
log.error("SQl Client Heart Thread Error: ", e);
}
}
log.info("Sql Client Heart Thread Closed :");
});
}
@OnClose
public void onClose() {
isRunning = false;
CloseUtil.closeNoErrorPrint(client, in2web, session);
}
@OnMessage
public void onMessage(String messages) {
SqlClientAdapter.WsEvent wsEvent = JsonUtils.parseObject(messages, SqlClientAdapter.WsEvent.class);
if (wsEvent == null) {
throw new RuntimeException("parse wsEvent error");
} else {
SqlClientAdapter.WsEvent.EventType eventType =
SqlClientAdapter.WsEvent.EventType.getEventType(wsEvent.getType());
if (eventType == SqlClientAdapter.WsEvent.EventType.TERM_HEART_EVENT) {
lastHeartTime = System.currentTimeMillis();
} else {
try {
client.onMessage(wsEvent, eventType);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
private String getParameter(String key) {
return getParameter(key, false);
}
private String getParameter(String key, boolean required) {
List<String> list = session.getRequestParameterMap().get(key);
if (list == null || list.size() == 0) {
if (required) {
throw new RuntimeException("parameter " + key + " is required");
} else {
return "";
}
}
return list.get(0);
}
}
/*
*
* 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.gateway;
import org.apache.flink.configuration.Configuration;
import java.io.Closeable;
import java.io.IOException;
import java.util.function.Supplier;
import org.jline.terminal.Terminal;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkSqlClient implements Closeable, ISqlClient {
public static final String CLI_NAME = "Dinky Flink SQL WEB CLI";
private final Supplier<Terminal> terminalFactory;
public FlinkSqlClient(SqlClientOptions sqlClientOptions, Supplier<Terminal> terminalFactory) {
this.terminalFactory = terminalFactory;
}
public void startCli(Configuration configuration) {
terminalFactory.get().writer().printf("Flink 1.14 ~ 1.16 Not Support yet! \n Flink 1.14 ~ 1.16 暂不支持!敬请期待 \n");
try {
terminalFactory.get().close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void close() {}
}
/*
*
* 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.gateway;
import org.apache.flink.configuration.Configuration;
import java.io.Closeable;
import java.io.IOException;
import java.util.function.Supplier;
import org.jline.terminal.Terminal;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkSqlClient implements Closeable, ISqlClient {
public static final String CLI_NAME = "Dinky Flink SQL WEB CLI";
private final Supplier<Terminal> terminalFactory;
public FlinkSqlClient(SqlClientOptions sqlClientOptions, Supplier<Terminal> terminalFactory) {
this.terminalFactory = terminalFactory;
}
public void startCli(Configuration configuration) {
terminalFactory.get().writer().printf("Flink 1.14 ~ 1.16 Not Support yet! \n Flink 1.14 ~ 1.16 暂不支持!敬请期待 \n");
try {
terminalFactory.get().close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void close() {}
}
/*
*
* 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.gateway;
import org.apache.flink.configuration.Configuration;
import java.io.Closeable;
import java.io.IOException;
import java.util.function.Supplier;
import org.jline.terminal.Terminal;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkSqlClient implements Closeable, ISqlClient {
public static final String CLI_NAME = "Dinky Flink SQL WEB CLI";
private final Supplier<Terminal> terminalFactory;
public FlinkSqlClient(SqlClientOptions sqlClientOptions, Supplier<Terminal> terminalFactory) {
this.terminalFactory = terminalFactory;
}
public void startCli(Configuration configuration) {
terminalFactory.get().writer().printf("Flink 1.14 ~ 1.16 Not Support yet! \n Flink 1.14 ~ 1.16 暂不支持!敬请期待 \n");
try {
terminalFactory.get().close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void close() {}
}
/*
*
* 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.gateway;
import org.dinky.utils.CloseUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.core.plugin.PluginUtils;
import org.apache.flink.table.client.SqlClientException;
import org.apache.flink.table.client.cli.CliClient;
import org.apache.flink.table.client.gateway.Executor;
import org.apache.flink.table.client.gateway.SingleSessionManager;
import org.apache.flink.table.gateway.SqlGateway;
import org.apache.flink.table.gateway.api.endpoint.SqlGatewayEndpointFactoryUtils;
import org.apache.flink.table.gateway.rest.SqlGatewayRestEndpointFactory;
import org.apache.flink.table.gateway.rest.util.SqlGatewayRestOptions;
import org.apache.flink.table.gateway.service.context.DefaultContext;
import org.apache.flink.util.NetUtils;
import java.io.Closeable;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.function.Supplier;
import org.jline.terminal.Terminal;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkSqlClient implements Closeable, ISqlClient {
public static final String CLI_NAME = "Dinky Flink SQL WEB CLI";
private final Supplier<Terminal> terminalFactory;
private final SqlClientOptions sqlClientOptions;
private Executor executor;
private EmbeddedGateway embeddedGateway;
public FlinkSqlClient(SqlClientOptions sqlClientOptions, Supplier<Terminal> terminalFactory) {
this.sqlClientOptions = sqlClientOptions;
this.terminalFactory = terminalFactory;
}
public void startCli(Configuration configuration) {
InetSocketAddress inetSocketAddress;
DefaultContext context = createDefaultContext(configuration);
if (sqlClientOptions.getMode() == SqlCliMode.MODE_EMBEDDED) {
embeddedGateway = EmbeddedGateway.create(context);
inetSocketAddress =
InetSocketAddress.createUnresolved(embeddedGateway.getAddress(), embeddedGateway.getPort());
} else if (sqlClientOptions.getMode() == SqlCliMode.MODE_GATEWAY) {
inetSocketAddress = sqlClientOptions
.buildConnectAddress()
.orElseThrow(() -> new SqlClientException("Gateway address is not set."));
} else {
throw new SqlClientException("Unsupported mode: " + sqlClientOptions.getMode());
}
executor = Executor.create(context, inetSocketAddress, sqlClientOptions.getSessionId());
Path historyFilePath = Paths.get(sqlClientOptions.getHistoryFilePath());
try (CliClient cli = new CliClient(terminalFactory, executor, historyFilePath)) {
if (sqlClientOptions.getInitSql() != null) {
boolean success = cli.executeInitialization(sqlClientOptions.getInitSql());
}
cli.executeInInteractiveMode();
} finally {
close();
}
log.info("Sql Client exit : " + sqlClientOptions.getConnectAddress());
}
private DefaultContext createDefaultContext(Configuration configuration) {
FileSystem.initialize(configuration, PluginUtils.createPluginManagerFromRootFolder(configuration));
return new DefaultContext(configuration, new ArrayList<>());
}
public void close() {
CloseUtil.closeNoErrorPrint(executor, embeddedGateway);
}
// --------------------------------------------------------------------------------------------
private static class EmbeddedGateway implements Closeable {
private static final String ADDRESS = "localhost";
private final NetUtils.Port port;
private final SqlGateway sqlGateway;
public static EmbeddedGateway create(DefaultContext defaultContext) {
NetUtils.Port port = NetUtils.getAvailablePort();
Configuration defaultConfig = defaultContext.getFlinkConfig();
Configuration restConfig = new Configuration();
// always use localhost
restConfig.set(SqlGatewayRestOptions.ADDRESS, ADDRESS);
restConfig.set(SqlGatewayRestOptions.PORT, port.getPort());
defaultConfig.addAll(
restConfig,
SqlGatewayEndpointFactoryUtils.getSqlGatewayOptionPrefix(SqlGatewayRestEndpointFactory.IDENTIFIER));
SqlGateway sqlGateway = new SqlGateway(defaultConfig, new SingleSessionManager(defaultContext));
try {
sqlGateway.start();
log.info("Start embedded gateway on port {}", port.getPort());
} catch (Throwable t) {
closePort(port);
throw new SqlClientException("Failed to start the embedded sql-gateway.", t);
}
return new EmbeddedGateway(sqlGateway, port);
}
private EmbeddedGateway(SqlGateway sqlGateway, NetUtils.Port port) {
this.sqlGateway = sqlGateway;
this.port = port;
}
String getAddress() {
return ADDRESS;
}
int getPort() {
return port.getPort();
}
@Override
public void close() {
sqlGateway.stop();
closePort(port);
}
private static void closePort(NetUtils.Port port) {
try {
port.close();
} catch (Exception e) {
// ignore
}
}
}
}
/*
*
* 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.gateway;
import org.dinky.utils.CloseUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.core.plugin.PluginUtils;
import org.apache.flink.table.client.SqlClientException;
import org.apache.flink.table.client.cli.CliClient;
import org.apache.flink.table.client.gateway.Executor;
import org.apache.flink.table.client.gateway.SingleSessionManager;
import org.apache.flink.table.gateway.SqlGateway;
import org.apache.flink.table.gateway.api.endpoint.SqlGatewayEndpointFactoryUtils;
import org.apache.flink.table.gateway.rest.SqlGatewayRestEndpointFactory;
import org.apache.flink.table.gateway.rest.util.SqlGatewayRestOptions;
import org.apache.flink.table.gateway.service.context.DefaultContext;
import org.apache.flink.util.NetUtils;
import java.io.Closeable;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.function.Supplier;
import org.jline.terminal.Terminal;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkSqlClient implements Closeable, ISqlClient {
public static final String CLI_NAME = "Dinky Flink SQL WEB CLI";
private final Supplier<Terminal> terminalFactory;
private final SqlClientOptions sqlClientOptions;
private Executor executor;
private EmbeddedGateway embeddedGateway;
public FlinkSqlClient(SqlClientOptions sqlClientOptions, Supplier<Terminal> terminalFactory) {
this.sqlClientOptions = sqlClientOptions;
this.terminalFactory = terminalFactory;
}
public void startCli(Configuration configuration) {
InetSocketAddress inetSocketAddress;
DefaultContext context = createDefaultContext(configuration);
if (sqlClientOptions.getMode() == SqlCliMode.MODE_EMBEDDED) {
embeddedGateway = EmbeddedGateway.create(context);
inetSocketAddress =
InetSocketAddress.createUnresolved(embeddedGateway.getAddress(), embeddedGateway.getPort());
} else if (sqlClientOptions.getMode() == SqlCliMode.MODE_GATEWAY) {
inetSocketAddress = sqlClientOptions
.buildConnectAddress()
.orElseThrow(() -> new SqlClientException("Gateway address is not set."));
} else {
throw new SqlClientException("Unsupported mode: " + sqlClientOptions.getMode());
}
executor = Executor.create(context, inetSocketAddress, sqlClientOptions.getSessionId());
Path historyFilePath = Paths.get(sqlClientOptions.getHistoryFilePath());
try (CliClient cli = new CliClient(terminalFactory, executor, historyFilePath)) {
if (sqlClientOptions.getInitSql() != null) {
boolean success = cli.executeInitialization(sqlClientOptions.getInitSql());
}
cli.executeInInteractiveMode();
} finally {
close();
}
log.info("Sql Client exit : " + sqlClientOptions.getConnectAddress());
}
private DefaultContext createDefaultContext(Configuration configuration) {
FileSystem.initialize(configuration, PluginUtils.createPluginManagerFromRootFolder(configuration));
return new DefaultContext(configuration, new ArrayList<>());
}
public void close() {
CloseUtil.closeNoErrorPrint(executor, embeddedGateway);
}
// --------------------------------------------------------------------------------------------
private static class EmbeddedGateway implements Closeable {
private static final String ADDRESS = "localhost";
private final NetUtils.Port port;
private final SqlGateway sqlGateway;
public static EmbeddedGateway create(DefaultContext defaultContext) {
NetUtils.Port port = NetUtils.getAvailablePort();
Configuration defaultConfig = defaultContext.getFlinkConfig();
Configuration restConfig = new Configuration();
// always use localhost
restConfig.set(SqlGatewayRestOptions.ADDRESS, ADDRESS);
restConfig.set(SqlGatewayRestOptions.PORT, port.getPort());
defaultConfig.addAll(
restConfig,
SqlGatewayEndpointFactoryUtils.getSqlGatewayOptionPrefix(SqlGatewayRestEndpointFactory.IDENTIFIER));
SqlGateway sqlGateway = new SqlGateway(defaultConfig, new SingleSessionManager(defaultContext));
try {
sqlGateway.start();
log.info("Start embedded gateway on port {}", port.getPort());
} catch (Throwable t) {
closePort(port);
throw new SqlClientException("Failed to start the embedded sql-gateway.", t);
}
return new EmbeddedGateway(sqlGateway, port);
}
private EmbeddedGateway(SqlGateway sqlGateway, NetUtils.Port port) {
this.sqlGateway = sqlGateway;
this.port = port;
}
String getAddress() {
return ADDRESS;
}
int getPort() {
return port.getPort();
}
@Override
public void close() {
sqlGateway.stop();
closePort(port);
}
private static void closePort(NetUtils.Port port) {
try {
port.close();
} catch (Exception e) {
// ignore
}
}
}
}
/*
*
* 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.gateway;
import org.dinky.utils.CloseUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.core.plugin.PluginUtils;
import org.apache.flink.table.client.SqlClientException;
import org.apache.flink.table.client.cli.CliClient;
import org.apache.flink.table.client.gateway.Executor;
import org.apache.flink.table.client.gateway.SingleSessionManager;
import org.apache.flink.table.gateway.SqlGateway;
import org.apache.flink.table.gateway.api.endpoint.SqlGatewayEndpointFactoryUtils;
import org.apache.flink.table.gateway.rest.SqlGatewayRestEndpointFactory;
import org.apache.flink.table.gateway.rest.util.SqlGatewayRestOptions;
import org.apache.flink.table.gateway.service.context.DefaultContext;
import org.apache.flink.util.NetUtils;
import java.io.Closeable;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.function.Supplier;
import org.jline.terminal.Terminal;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkSqlClient implements Closeable, ISqlClient {
public static final String CLI_NAME = "Dinky Flink SQL WEB CLI";
private final Supplier<Terminal> terminalFactory;
private final SqlClientOptions sqlClientOptions;
private Executor executor;
private EmbeddedGateway embeddedGateway;
public FlinkSqlClient(SqlClientOptions sqlClientOptions, Supplier<Terminal> terminalFactory) {
this.sqlClientOptions = sqlClientOptions;
this.terminalFactory = terminalFactory;
}
public void startCli(Configuration configuration) {
InetSocketAddress inetSocketAddress;
DefaultContext context = createDefaultContext(configuration);
if (sqlClientOptions.getMode() == SqlCliMode.MODE_EMBEDDED) {
embeddedGateway = EmbeddedGateway.create(context);
inetSocketAddress =
InetSocketAddress.createUnresolved(embeddedGateway.getAddress(), embeddedGateway.getPort());
} else if (sqlClientOptions.getMode() == SqlCliMode.MODE_GATEWAY) {
inetSocketAddress = sqlClientOptions
.buildConnectAddress()
.orElseThrow(() -> new SqlClientException("Gateway address is not set."));
} else {
throw new SqlClientException("Unsupported mode: " + sqlClientOptions.getMode());
}
executor = Executor.create(context, inetSocketAddress, sqlClientOptions.getSessionId());
Path historyFilePath = Paths.get(sqlClientOptions.getHistoryFilePath());
try (CliClient cli = new CliClient(terminalFactory, executor, historyFilePath)) {
if (sqlClientOptions.getInitSql() != null) {
boolean success = cli.executeInitialization(sqlClientOptions.getInitSql());
}
cli.executeInInteractiveMode();
} finally {
close();
}
log.info("Sql Client exit : " + sqlClientOptions.getConnectAddress());
}
private DefaultContext createDefaultContext(Configuration configuration) {
FileSystem.initialize(configuration, PluginUtils.createPluginManagerFromRootFolder(configuration));
return new DefaultContext(configuration, new ArrayList<>());
}
public void close() {
CloseUtil.closeNoErrorPrint(executor, embeddedGateway);
}
// --------------------------------------------------------------------------------------------
private static class EmbeddedGateway implements Closeable {
private static final String ADDRESS = "localhost";
private final NetUtils.Port port;
private final SqlGateway sqlGateway;
public static EmbeddedGateway create(DefaultContext defaultContext) {
NetUtils.Port port = NetUtils.getAvailablePort();
Configuration defaultConfig = defaultContext.getFlinkConfig();
Configuration restConfig = new Configuration();
// always use localhost
restConfig.set(SqlGatewayRestOptions.ADDRESS, ADDRESS);
restConfig.set(SqlGatewayRestOptions.PORT, port.getPort());
defaultConfig.addAll(
restConfig,
SqlGatewayEndpointFactoryUtils.getSqlGatewayOptionPrefix(SqlGatewayRestEndpointFactory.IDENTIFIER));
SqlGateway sqlGateway = new SqlGateway(defaultConfig, new SingleSessionManager(defaultContext));
try {
sqlGateway.start();
log.info("Start embedded gateway on port {}", port.getPort());
} catch (Throwable t) {
closePort(port);
throw new SqlClientException("Failed to start the embedded sql-gateway.", t);
}
return new EmbeddedGateway(sqlGateway, port);
}
private EmbeddedGateway(SqlGateway sqlGateway, NetUtils.Port port) {
this.sqlGateway = sqlGateway;
this.port = port;
}
String getAddress() {
return ADDRESS;
}
int getPort() {
return port.getPort();
}
@Override
public void close() {
sqlGateway.stop();
closePort(port);
}
private static void closePort(NetUtils.Port port) {
try {
port.close();
} catch (Exception e) {
// ignore
}
}
}
}
/*
*
* 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.gateway;
import org.apache.flink.configuration.Configuration;
import java.io.Closeable;
public interface ISqlClient extends Closeable {
void startCli(Configuration configuration);
}
/*
*
* 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.gateway;
import cn.hutool.core.lang.Assert;
public enum SqlCliMode {
MODE_EMBEDDED,
MODE_GATEWAY;
public static SqlCliMode fromString(String mode) {
Assert.notNull(mode, "sql client mode is null,please check parameters");
if (mode.equals("MODE_EMBEDDED")) {
return MODE_EMBEDDED;
} else if (mode.equals("MODE_GATEWAY")) {
return MODE_GATEWAY;
} else {
throw new IllegalArgumentException("Unsupported mode: " + mode);
}
}
}
/*
*
* 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.gateway;
import java.net.InetSocketAddress;
import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class SqlClientOptions {
private SqlCliMode mode;
private String sessionId;
private String connectAddress;
private String initSql;
private String historyFilePath;
private TerminalSize terminalSize;
public Optional<InetSocketAddress> buildConnectAddress() {
if (connectAddress == null) {
return Optional.empty();
}
String[] hosts = connectAddress.split(",");
if (hosts.length > 0) {
String[] hostPort = hosts[0].split(":");
if (hostPort.length == 2) {
return Optional.of(new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1])));
}
}
throw new IllegalArgumentException("Invalid connect address: " + connectAddress);
}
@Data
@AllArgsConstructor
public static class TerminalSize {
private int columns;
private int rows;
}
}
/*
*
* 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.utils;
import java.io.Closeable;
import java.io.IOException;
public class CloseUtil {
public static void closeNoErrorPrint(Closeable... closeables) {
if (closeables != null) {
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
}
......@@ -202,6 +202,10 @@
<artifactId>flink-s3-fs-presto</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-client_2.12</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
</project>
......@@ -201,7 +201,11 @@
<artifactId>flink-s3-fs-presto</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-client</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
</project>
......@@ -155,6 +155,11 @@
<artifactId>flink-s3-fs-presto</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-client</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
<repositories>
......
......@@ -155,6 +155,15 @@
<artifactId>flink-s3-fs-presto</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-gateway</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-client</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
</project>
......@@ -153,6 +153,15 @@
<artifactId>flink-s3-fs-presto</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-gateway</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-client</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
</project>
......@@ -153,6 +153,15 @@
<artifactId>flink-s3-fs-presto</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-gateway</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-sql-client</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
</project>
/*
*
* 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.gateway.sqlgateway.cli;
import org.dinky.gateway.FlinkSqlClient;
import org.dinky.gateway.ISqlClient;
import org.dinky.gateway.SqlClientOptions;
import org.dinky.utils.CloseUtil;
import org.dinky.utils.JsonUtils;
import org.apache.flink.client.deployment.executors.RemoteExecutor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.configuration.RestOptions;
import org.apache.http.util.TextUtils;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.InetSocketAddress;
import java.util.Objects;
import org.jline.terminal.Size;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SqlClientAdapter implements Closeable {
private final Terminal terminal;
private final PipedOutputStream webWrite2client;
private final PipedInputStream in2client;
private final OutputStream clientWrite2web;
private final SqlClientOptions options;
private final ISqlClient flinkSqlClient;
public SqlClientAdapter(PipedInputStream in2client, OutputStream clientWrite2web, SqlClientOptions options)
throws IOException {
this.options = options;
this.in2client = in2client;
this.clientWrite2web = clientWrite2web;
webWrite2client = new PipedOutputStream(in2client);
flinkSqlClient = new FlinkSqlClient(options, this::getDefaultTerminal);
SqlClientOptions.TerminalSize terminalSize = options.getTerminalSize();
terminal = TerminalBuilder.builder()
.name(FlinkSqlClient.CLI_NAME)
.streams(in2client, clientWrite2web)
.size(new Size(terminalSize.getColumns(), terminalSize.getRows()))
.build();
}
public void startClient() {
options.setSessionId(checkSessionId(options.getSessionId()));
Configuration configuration = GlobalConfiguration.loadConfiguration();
InetSocketAddress clusterAddress = options.buildConnectAddress()
.orElseThrow(() -> new IllegalArgumentException("Flink Cluster address is not set."));
configuration.set(RestOptions.BIND_ADDRESS, clusterAddress.getHostName());
configuration.set(RestOptions.BIND_PORT, clusterAddress.getPort() + "");
configuration.set(DeploymentOptions.TARGET, RemoteExecutor.NAME);
// 当客户端程序终止时,作业执行也会终止。
configuration.set(DeploymentOptions.ATTACHED, true);
// 如果作业是在attached模式下提交的,在CLI突然终止时执行群集关闭,例如响应用户中断,例如键入Ctrl+C
// dinky的CLI只作为调试用,不鼓励CLI提交任务,所以开启此选项
configuration.set(DeploymentOptions.SHUTDOWN_IF_ATTACHED, true);
flinkSqlClient.startCli(configuration);
}
public void onMessage(WsEvent wsEvent, WsEvent.EventType eventType) throws IOException {
switch (Objects.requireNonNull(eventType)) {
case TERM_KEY_EVENT:
String msg = wsEvent.getData();
webWrite2client.write(msg.getBytes());
webWrite2client.flush();
break;
case TERM_RESIZE:
Size size = JsonUtils.parseObject(wsEvent.getData(), Size.class);
terminal.setSize(size);
break;
case TERM_CLOSE_EVENT:
// TODO: 目前没有好办法可以全程优雅的关闭,只能触发exception强制关闭
terminal.close();
// String exitMsg = Command.QUIT.name() + ";\n";
// webWrite2client.write("\u0003\r".getBytes());
// webWrite2client.write(exitMsg.getBytes());
break;
default:
throw new RuntimeException("unknown message type:" + wsEvent.type);
}
}
private String checkSessionId(String sessionId) {
if (TextUtils.isEmpty(sessionId)) {
return "default";
}
if (!sessionId.matches("[a-zA-Z0-9_\\-.]+")) {
throw new IllegalArgumentException("Session identifier must only consists of 'a-zA-Z0-9_-.'.");
}
return sessionId;
}
private Terminal getDefaultTerminal() {
return terminal;
}
@Override
public void close() throws IOException {
CloseUtil.closeNoErrorPrint(flinkSqlClient, webWrite2client, in2client, clientWrite2web);
}
@Data
public static class WsEvent {
public enum EventType {
TERM_KEY_EVENT,
TERM_HEART_EVENT,
TERM_CLOSE_EVENT,
TERM_RESIZE;
public static EventType getEventType(String type) {
switch (type) {
case "TERM_KEY_EVENT":
return TERM_KEY_EVENT;
case "TERM_HEART_EVENT":
return TERM_HEART_EVENT;
case "TERM_RESIZE":
return TERM_RESIZE;
case "TERM_CLOSE_EVENT":
return TERM_CLOSE_EVENT;
default:
throw new RuntimeException("unknown event type:" + type);
}
}
}
private String type;
private String data;
private String sessionId;
}
}
......@@ -81,7 +81,10 @@
"echarts": "^5.5.0",
"echarts-for-react": "^3.0.2",
"react-grid-layout": "^1.4.4",
"@babel/runtime": "^7.24.7"
"@babel/runtime": "^7.24.7",
"websocket": "^1.0.35",
"@xterm/xterm": "^5.5.0",
"@xterm/addon-fit": "^0.10.0"
},
"devDependencies": {
"@ant-design/pro-cli": "^3.2.1",
......
......@@ -85,6 +85,19 @@ export default {
*
* */
'datastudio.middle.terminal.mode': 'Connect Mode',
'datastudio.middle.terminal.websocket': 'dinky backend',
'datastudio.middle.terminal.websocket.tip':
'In general, no modifications are required. If you have custom Nginx configurations, please edit this address.',
'datastudio.middle.terminal.cluster': 'Flink Cluster',
'datastudio.middle.terminal.cluster.tip':
'It is necessary to pre-register the corresponding cluster in the registry. Only manually registered clusters will be displayed.',
'datastudio.middle.terminal.fontSize': 'Font Size',
'datastudio.middle.terminal.backspaceAsCtrlH': 'Backspace As CtrlH',
'datastudio.middle.terminal.backspaceAsCtrlH.tip':
'If issues with display arise following a rollback deletion, modify this ',
'datastudio.middle.terminal.connect': 'Connect',
'datastudio.middle.qg': 'Quick Guide',
'datastudio.middle.qg.alertGroup': 'Register Alert Group',
'datastudio.middle.qg.alertInstance': 'Register Alert Instance',
......
......@@ -80,6 +80,17 @@ export default {
* */
'datastudio.middle.qg': '快捷引导',
'datastudio.middle.terminal.mode': '连接方式',
'datastudio.middle.terminal.websocket': 'dinky后端',
'datastudio.middle.terminal.websocket.tip':
'一般情况下无需改动,如果您有自定义nginx配置,请修改此地址',
'datastudio.middle.terminal.cluster': 'Flink 集群',
'datastudio.middle.terminal.cluster.tip': '需要提前在注册中心添加对应集群,仅展示手动注册集群',
'datastudio.middle.terminal.fontSize': '字体大小',
'datastudio.middle.terminal.backspaceAsCtrlH': '回退字符转换',
'datastudio.middle.terminal.backspaceAsCtrlH.tip': '如果回退删除显示异常,修改此选项',
'datastudio.middle.terminal.connect': '连接',
'datastudio.middle.qg.alertGroup': '注册告警组',
'datastudio.middle.qg.alertInstance': '注册告警实例',
'datastudio.middle.qg.clusterConfiguration': '注册集群配置',
......
......@@ -77,11 +77,7 @@ const Lineage: React.FC<connect> = (props) => {
{lineageData && (lineageData.tables.length !== 0 || lineageData.relations.length !== 0) ? (
<LineageGraph lineageData={lineageData} refreshCallBack={queryLineageData} />
) : (
<Result
style={{ height: 'inherit' }}
status='warning'
title={l('lineage.getError')}
/>
<Result style={{ height: 'inherit' }} status='warning' title={l('lineage.getError')} />
)}
</Card>
);
......
......@@ -30,6 +30,7 @@ import {
STUDIO_MODEL,
STUDIO_MODEL_ASYNC,
TabsItemType,
TabsPageType,
TreeVo
} from '@/pages/DataStudio/model';
import { SysConfigStateType } from '@/pages/SettingCenter/GlobalSetting/model';
......@@ -38,13 +39,15 @@ import { connect } from '@@/exports';
import { SortAscendingOutlined } from '@ant-design/icons';
import { Key } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import type { MenuProps } from 'antd';
import { Divider, MenuProps } from 'antd';
import { Button, Dropdown, Empty, Space, Tree } from 'antd';
import type { ButtonType } from 'antd/es/button/buttonHelpers';
import Search from 'antd/es/input/Search';
import { ItemType } from 'rc-menu/es/interface';
import React, { useEffect, useState } from 'react';
import { BtnRoute, useTasksDispatch } from '../../BtnContext';
import { CodeTwoTone } from '@ant-design/icons';
import { DIALECT } from '@/services/constants';
const { DirectoryTree } = Tree;
......@@ -185,7 +188,18 @@ const JobTree: React.FC<TreeProps & connect> = (props) => {
payload: getLeafKeyList(projectData)
});
};
const openTerminal = () => {
dispatch({
type: STUDIO_MODEL.addTab,
payload: {
icon: DIALECT.TERMINAL,
// id: selectDatabaseId + schemaName + tableName,
breadcrumbLabel: 'SQL CLI Terminal',
label: 'SQL CLI Terminal',
type: TabsPageType.terminal
}
});
};
const currentTabName = LeftMenuKey.PROJECT_KEY;
const btnEvent = [...BtnRoute[currentTabName]];
const positionKey = (panes: TabsItemType[], activeKey: string) => {
......@@ -271,6 +285,11 @@ const JobTree: React.FC<TreeProps & connect> = (props) => {
</Dropdown>
</Space>
<div style={{ padding: '3px', background: '#F5F5F5' }} onClick={() => openTerminal()}>
<CodeTwoTone /> <a>SQL Cli Terminal</a>
</div>
<Divider style={{ margin: 3 }} />
{data.length ? (
<DirectoryTree
style={{ ...style, height: height - 40 - 16, overflowY: 'auto' }}
......
/*
*
* 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.
*
*/
export type TermProps = {
mode: string;
wsUrl: string;
fontSize: number;
backspaceAsCtrlH: boolean;
initSql?: string;
sessionId?: string;
connectAddress: string;
};
export const setTermConfig = (config: TermProps) => {
localStorage.setItem('terminal-config', JSON.stringify(config));
};
export const getTermConfig = () => {
const initializeConfig = () => {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return {
mode: 'MODE_EMBEDDED',
wsUrl: `${protocol}//${window.location.host}/ws/sql-gateway`,
fontSize: 14,
backspaceAsCtrlH: true
};
};
const configKey = 'terminal-config';
const storedConfig = localStorage.getItem(configKey);
if (storedConfig) {
try {
return JSON.parse(storedConfig);
} catch (error) {
console.error('Failed to parse stored config:', error);
return initializeConfig();
}
} else {
return initializeConfig();
}
};
export const HEART_TIMEOUT = 30 * 1000;
export const HEART_TNERVAL = 30 * 1000;
export const enum TerminalEvent {
TERM_KEY_EVENT = 'TERM_KEY_EVENT',
TERM_HEART_EVENT = 'TERM_HEART_EVENT',
TERM_CLOSE_EVENT = 'TERM_CLOSE_EVENT',
TERM_RESIZE = 'TERM_RESIZE'
}
export const enum KeyCode {
Backspace = 8,
Tab = 9,
Enter = 13,
Shift = 16,
Ctrl = 17,
Alt = 18,
PauseBreak = 19,
CapsLock = 20,
Escape = 27,
Space = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
LeftArrow = 37,
UpArrow = 38,
RightArrow = 39,
DownArrow = 40,
Insert = 45,
Delete = 46,
Key0 = 48,
Key1 = 49,
Key2 = 50,
Key3 = 51,
Key4 = 52,
Key5 = 53,
Key6 = 54,
Key7 = 55,
Key8 = 56,
Key9 = 57,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftWindowKey = 91,
RightWindowKey = 92,
SelectKey = 93,
Numpad0 = 96,
Numpad1 = 97,
Numpad2 = 98,
Numpad3 = 99,
Numpad4 = 100,
Numpad5 = 101,
Numpad6 = 102,
Numpad7 = 103,
Numpad8 = 104,
Numpad9 = 105,
Multiply = 106,
Add = 107,
Subtract = 109,
DecimalPoint = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
NumLock = 144,
ScrollLock = 145,
SemiColon = 186,
EqualSign = 187,
Comma = 188,
Dash = 189,
Period = 190,
ForwardSlash = 191,
GraveAccent = 192,
OpenBracket = 219,
BackSlash = 220,
CloseBracket = 221,
SingleQuote = 222
}
export const enum AsciiCode {
Null = 0,
StartOfHeader = 1,
StartOfText = 2,
EndOfText = 3,
EndOfTransmission = 4,
Enquiry = 5,
Acknowledge = 6,
Bell = 7,
Backspace = 8,
HorizontalTab = 9,
LineFeed = 10,
VerticalTab = 11,
FormFeed = 12,
CarriageReturn = 13,
ShiftOut = 14,
ShiftIn = 15,
DataLinkEscape = 16,
DeviceControl1 = 17,
DeviceControl2 = 18,
DeviceControl3 = 19,
DeviceControl4 = 20,
NegativeAcknowledge = 21,
SynchronousIdle = 22,
EndOfTransmissionBlock = 23,
Cancel = 24,
EndOfMedium = 25,
Substitute = 26,
Escape = 27,
FileSeparator = 28,
GroupSeparator = 29,
RecordSeparator = 30,
UnitSeparator = 31,
Space = 32,
ExclamationMark = 33,
DoubleQuote = 34,
Hash = 35,
Dollar = 36,
Percent = 37,
Ampersand = 38,
SingleQuote = 39,
LeftParenthesis = 40,
RightParenthesis = 41,
Asterisk = 42,
Plus = 43,
Comma = 44,
Minus = 45,
Period = 46,
Slash = 47,
Zero = 48,
One = 49,
Two = 50,
Three = 51,
Four = 52,
Five = 53,
Six = 54,
Seven = 55,
Eight = 56,
Nine = 57,
Colon = 58,
Semicolon = 59,
LessThan = 60,
Equals = 61,
GreaterThan = 62,
QuestionMark = 63,
At = 64,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftSquareBracket = 91,
Backslash = 92,
RightSquareBracket = 93,
Caret = 94,
Underscore = 95,
Backtick = 96,
a = 97,
b = 98,
c = 99,
d = 100,
e = 101,
f = 102,
g = 103,
h = 104,
i = 105,
j = 106,
k = 107,
l = 108,
m = 109,
n = 110,
o = 111,
p = 112,
q = 113,
r = 114,
s = 115,
t = 116,
u = 117,
v = 118,
w = 119,
x = 120,
y = 121,
z = 122,
LeftCurlyBracket = 123,
Pipe = 124,
RightCurlyBracket = 125,
Tilde = 126,
Delete = 127
}
/*
*
* 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 React, { useEffect } from 'react';
import {
AsciiCode,
HEART_TIMEOUT,
HEART_TNERVAL,
KeyCode,
TerminalEvent
} from '@/pages/DataStudio/MiddleContainer/Terminal/TerminalConfig';
import { FitAddon } from '@xterm/addon-fit';
import { Terminal } from '@xterm/xterm';
import { TermProps } from '@/pages/DataStudio/MiddleContainer/Terminal/TerminalConfig';
import './xterm.css';
const TerminalContent: React.FC<TermProps> = (props) => {
const { mode, wsUrl, backspaceAsCtrlH, fontSize, initSql, sessionId, connectAddress } = props;
// const currentData = tabsItem.params.taskData;
let term: Terminal;
let ws: WebSocket;
let lastHeartTime: Date = new Date();
let heartInterval: NodeJS.Timeout;
const sendWs = (data: any, type: string) => {
ws.send(JSON.stringify({ type: type, data: data }));
};
const CheckWebSocket = (ws: WebSocket) => {
if (ws) {
return !(ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED);
}
return false;
};
const preprocessInput = (data: any) => {
if (backspaceAsCtrlH) {
if (data.charCodeAt(0) === AsciiCode.Delete) {
data = String.fromCharCode(KeyCode.Backspace);
}
}
if (data.charCodeAt(0) === AsciiCode.EndOfText) {
data = String.fromCharCode(AsciiCode.Substitute);
}
if (data === '\r') {
data = '\n';
}
return data;
};
const connectWs = (term: Terminal) => {
const termCols = term.cols;
const termRows = term.rows;
const params = `mode=${mode}&cols=${termCols}&rows=${termRows}&sessionId=${sessionId}&initSql=${initSql}&connectAddress=${connectAddress}`;
ws = new WebSocket(`${wsUrl}/?${params}`);
ws.binaryType = 'arraybuffer';
ws.onopen = function () {
if (heartInterval) {
clearInterval(heartInterval);
}
heartInterval = setInterval(() => {
if (!CheckWebSocket(ws)) {
clearInterval(heartInterval);
} else {
let currentDate = new Date();
if (lastHeartTime.getTime() - currentDate.getTime() > HEART_TIMEOUT) {
console.error('ws heart timeout');
}
sendWs('PING', TerminalEvent.TERM_HEART_EVENT);
}
}, HEART_TNERVAL);
};
ws.onclose = function (evt: CloseEvent) {
term.writeln('\nThe connection closed: ' + evt.code + ' ' + evt.reason);
};
ws.onerror = function (evt: Event) {
term.write('\nThe connection error:' + evt);
};
ws.onmessage = function (e: MessageEvent) {
if (typeof e.data === 'object') {
const data = new Uint8Array(e.data);
if (data.length == 1 && data[0] === KeyCode.Backspace) {
term.write('\b \b');
} else {
term.write(data);
}
} else {
//预留接口
term.write(e.data.replace('\r', '\n\n'));
}
};
};
const createTerminal = () => {
if (term) {
return term;
} else {
const terminal = new Terminal({
// rendererType: "canvas", //渲染类型
// cols: this.cols,// 设置之后会输入多行之后覆盖现象
// convertEol: true, //启用时,光标将设置为下一行的开头
scrollback: 10, //终端中的回滚量
fontSize: fontSize, //字体大小
// disableStdin: false, //是否应禁用输入。
// cursorStyle: "block", //光标样式
// cursorBlink: true, //光标闪烁
// tabStopWidth: 4,
theme: {
// foreground: "black", //字体
// background: "#000000", //背景色
// cursor: "help" //设置光标
}
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(document.getElementById('terminal-container') as HTMLElement);
fitAddon.fit();
terminal.focus();
window.addEventListener('resize', () => fitAddon.fit());
return terminal;
}
};
const initAll = () => {
if (!term) {
term = createTerminal();
}
term.onData((data) => {
if (!CheckWebSocket(ws)) {
console.error('ws not activated');
return;
}
// this.lastSendTime = new Date();
data = preprocessInput(data);
sendWs(data, TerminalEvent.TERM_KEY_EVENT);
});
term.onResize(({ cols, rows }) => {
if (!CheckWebSocket(ws)) {
return;
}
sendWs(JSON.stringify({ columns: cols, rows }), TerminalEvent.TERM_RESIZE);
});
connectWs(term);
};
useEffect(() => {
initAll();
return () => {
if (CheckWebSocket(ws)) {
sendWs('', TerminalEvent.TERM_CLOSE_EVENT);
//延迟关闭,给与后端注销时间
setTimeout(() => ws.close(), 2000);
}
clearInterval(heartInterval);
term?.dispose();
};
}, []);
return <div id='terminal-container' style={{ height: '80vh' }}></div>;
};
export default TerminalContent;
/*
*
* 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 { API_CONSTANTS } from '@/services/endpoints';
import React, { useState } from 'react';
import {
Button,
Col,
Divider,
Form,
Input,
InputNumber,
Radio,
Row,
Select,
Space,
Switch,
Tag,
Typography
} from 'antd';
import { EditTwoTone } from '@ant-design/icons';
import useHookRequest from '@/hooks/useHookRequest';
import { getData } from '@/services/api';
import { Cluster } from '@/types/RegCenter/data';
import { CLUSTER_TYPE_OPTIONS, ClusterType } from '@/pages/RegCenter/Cluster/constants';
import {
getTermConfig,
setTermConfig,
TermProps
} from '@/pages/DataStudio/MiddleContainer/Terminal/TerminalConfig';
import TerminalContent from '@/pages/DataStudio/MiddleContainer/Terminal/TerminalContent';
import { l } from '@/utils/intl';
const TerminalTab = () => {
// const [form] = Form.useForm();
const EMBBED_FILTER = [
ClusterType.STANDALONE,
ClusterType.YARN_SESSION,
ClusterType.KUBERNETES_SESSION
];
const GATEWAY_FILTER = [ClusterType.SQL_GATEWAY];
const [disableUrlEditable, setUrlEditable] = useState(true);
const [opentTerm, setOpentTerm] = useState(false);
const [connectCfg, setConnectCfg] = useState(getTermConfig());
const [currentMode, setCurrentMode] = useState(connectCfg.mode);
const dealClusterData = (data: Cluster.Instance[]) => {
const renderClusterItem = (item: Cluster.Instance) => {
return (
<Space split={<Divider type='vertical' />}>
<Tag color='cyan'>
{CLUSTER_TYPE_OPTIONS().find((record) => item.type === record.value)?.label}
</Tag>
<Typography.Text>{item.name}</Typography.Text>
<Typography.Text type={'secondary'} style={{ fontSize: 'small' }}>
{item.alias}
</Typography.Text>
<Typography.Link>{item.hosts}</Typography.Link>
</Space>
);
};
return data
.filter((item: Cluster.Instance) => {
if (currentMode === 'MODE_EMBEDDED') {
return EMBBED_FILTER.includes(item.type as ClusterType);
} else {
return GATEWAY_FILTER.includes(item.type as ClusterType);
}
})
.map((item: Cluster.Instance) => {
return {
label: renderClusterItem(item),
value: item.hosts
};
});
};
const clusterData = useHookRequest<any, any>(getData, {
refreshDeps: [currentMode],
defaultParams: [API_CONSTANTS.CLUSTER_INSTANCE_LIST, { isAutoCreate: false }],
onSuccess: (data: Cluster.Instance[]) => dealClusterData(data)
});
const envData = useHookRequest<any, any>(getData, {
defaultParams: [API_CONSTANTS.LIST_FLINK_SQL_ENV],
onSuccess: (data: any[]) =>
data.map((item: any) => ({ label: item.name, value: item.statement }))
});
const onFinish = (values: TermProps) => {
setTermConfig(values);
setConnectCfg(values);
setOpentTerm(true);
};
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 }
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 }
}
};
return (
<>
{opentTerm ? (
<TerminalContent {...connectCfg} />
) : (
<div style={{ padding: '40px' }}>
<Form
{...formItemLayout}
onFinish={onFinish}
initialValues={connectCfg}
style={{ maxWidth: 800 }}
requiredMark={'optional'}
>
<Form.Item label={l('datastudio.middle.terminal.mode')} name='mode' required>
<Radio.Group onChange={(e) => setCurrentMode(e.target.value)}>
<Radio.Button value='MODE_EMBEDDED'>Embedded</Radio.Button>
<Radio.Button value='MODE_GATEWAY' disabled>
SQL Gateway
</Radio.Button>
</Radio.Group>
</Form.Item>
<Form.Item label={l('datastudio.middle.terminal.websocket')} required>
<Row gutter={24}>
<Col span={21}>
<Form.Item
name='wsUrl'
noStyle
rules={[{ required: true, message: 'WS Addr is required!' }]}
>
<Input disabled={disableUrlEditable} />
</Form.Item>
<Typography.Text type='secondary' italic style={{ fontSize: 'small' }}>
{l('datastudio.middle.terminal.websocket.tip')}
</Typography.Text>
</Col>
<Col span={1}>
<EditTwoTone onClick={() => setUrlEditable(!disableUrlEditable)} />
</Col>
</Row>
</Form.Item>
<Form.Item label={l('datastudio.middle.terminal.cluster')} required>
<Form.Item
name='connectAddress'
noStyle
rules={[{ required: true, message: 'Cluster Addr is required!' }]}
>
<Select
placeholder=''
// onChange={onGenderChange}
allowClear
options={clusterData.data}
></Select>
</Form.Item>
<Typography.Text type='secondary' italic style={{ fontSize: 'small' }}>
{l('datastudio.middle.terminal.cluster.tip')}
</Typography.Text>
</Form.Item>
<Form.Item name='sessionId' label='sessionId'>
<Input />
</Form.Item>
<Form.Item name='initSql' label='Init Sql'>
<Select placeholder='Init SQL' options={envData.data} allowClear></Select>
</Form.Item>
<Form.Item
rules={[{ required: true, message: 'Font Size is required!' }]}
name='fontSize'
label={l('datastudio.middle.terminal.fontSize')}
>
<InputNumber min={1} max={100} />
</Form.Item>
<Form.Item required label={l('datastudio.middle.terminal.backspaceAsCtrlH')}>
<Form.Item name='backspaceAsCtrlH' noStyle required>
<Switch />
</Form.Item>
<Typography.Text type='secondary' italic style={{ fontSize: 'small' }}>
{l('datastudio.middle.terminal.backspaceAsCtrlH.tip')}
</Typography.Text>
</Form.Item>
<Form.Item wrapperCol={{ offset: 6, span: 16 }}>
<Button type='primary' htmlType='submit'>
{l('datastudio.middle.terminal.connect')}
</Button>
</Form.Item>
</Form>
</div>
)}
</>
);
};
export default TerminalTab;
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}
......@@ -45,6 +45,7 @@ import {
StarRocksIcons
} from '@/components/Icons/DBIcons';
import { DIALECT } from '@/services/constants';
import { CodeTwoTone } from '@ant-design/icons';
export const matchLanguage = (language = DIALECT.FLINK_SQL) => {
switch (language.toLowerCase()) {
......@@ -131,6 +132,8 @@ export const getTabIcon = (type: string, size?: number) => {
return <StarRocksIcons size={size} />;
case DIALECT.PRESTO:
return <PrestoIcons size={size} />;
case DIALECT.TERMINAL:
return <CodeTwoTone size={size} />;
default:
return <FileIcon />;
}
......
......@@ -22,17 +22,19 @@ import ContentScroll from '@/components/Scroll/ContentScroll';
import { useEditor } from '@/hooks/useEditor';
import useThemeValue from '@/hooks/useThemeValue';
import { STUDIO_TAG_RIGHT_CONTEXT_MENU } from '@/pages/DataStudio/constants';
import {
getCurrentTab,
isDataStudioTabsItemType,
isMetadataTabsItemType
} from '@/pages/DataStudio/function';
import { getCurrentTab } from '@/pages/DataStudio/function';
import { getRightSelectKeyFromNodeClickJobType } from '@/pages/DataStudio/LeftContainer/Project/function';
import { getTabIcon } from '@/pages/DataStudio/MiddleContainer/function';
import KeyBoard from '@/pages/DataStudio/MiddleContainer/KeyBoard';
import QuickGuide from '@/pages/DataStudio/MiddleContainer/QuickGuide';
import StudioEditor from '@/pages/DataStudio/MiddleContainer/StudioEditor';
import { StateType, STUDIO_MODEL, TabsItemType, TabsPageType } from '@/pages/DataStudio/model';
import {
MetadataTabsItemType,
StateType,
STUDIO_MODEL,
TabsItemType,
TabsPageType
} from '@/pages/DataStudio/model';
import { RightSide } from '@/pages/DataStudio/route';
import RightTagsRouter from '@/pages/RegCenter/DataSource/components/DataSourceDetail/RightTagsRouter';
import { ContextMenuPosition, InitContextMenuPosition } from '@/types/Public/state.d';
......@@ -42,6 +44,7 @@ import { ExclamationCircleFilled } from '@ant-design/icons';
import { ConfigProvider, Divider, Modal, Space, Tabs, Typography } from 'antd';
import { MenuInfo } from 'rc-menu/es/interface';
import React, { memo, useState } from 'react';
import TerminalTab from '@/pages/DataStudio/MiddleContainer/Terminal';
const { Text } = Typography;
const { confirm } = Modal;
......@@ -218,32 +221,33 @@ const MiddleContainer = (props: any) => {
*/
const tabItems = panes.map((item: TabsItemType) => {
const renderContent = () => {
if (isDataStudioTabsItemType(item)) {
if (parseInt(activeKey) < 0) {
return TabsPageType.None;
switch (item.type) {
case TabsPageType.terminal:
return <TerminalTab />;
case TabsPageType.metadata: {
const params = (item as MetadataTabsItemType).params;
return <RightTagsRouter tableInfo={params.tableInfo} queryParams={params.queryParams} />;
}
return (
<StudioEditor
tabsItem={item}
monacoInstance={item.monacoInstance}
height={
activeKey === item.key
? fullscreen
? document.body.clientHeight
: props.centerContentHeight - 48
: 0
}
/>
);
}
if (isMetadataTabsItemType(item)) {
const params = item.params;
return <RightTagsRouter tableInfo={params.tableInfo} queryParams={params.queryParams} />;
case TabsPageType.project:
if (parseInt(activeKey) < 0) {
return TabsPageType.None;
}
return (
<StudioEditor
tabsItem={item}
monacoInstance={item.monacoInstance}
height={
activeKey === item.key
? fullscreen
? document.body.clientHeight
: props.centerContentHeight - 48
: 0
}
/>
);
default:
return <>The type {item.type} is unknown</>;
}
return <></>;
};
return {
......
......@@ -163,6 +163,7 @@ export type DataStudioParams = {
export enum TabsPageType {
None = '',
metadata = 'metadata',
terminal = 'terminal',
project = 'project'
}
......
......@@ -27,6 +27,7 @@ export enum ClusterType {
KUBERNETES_APPLICATION = 'kubernetes-application',
KUBERNETES_OPERATOR = 'kubernetes-application-operator',
YARN_APPLICATION = 'yarn-application',
SQL_GATEWAY = 'sql-gateway',
LOCAL = 'local'
}
......
......@@ -223,7 +223,8 @@ export const DIALECT = {
HIVE: 'hive',
PHOENIX: 'phoenix',
STARROCKS: 'starrocks',
PRESTO: 'presto'
PRESTO: 'presto',
TERMINAL: 'terminal'
};
export const RUN_MODE = {
......
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