diff --git a/docs/errorcode/linkis-engineconn-plugin-core-errorcode.md b/docs/errorcode/linkis-engineconn-plugin-core-errorcode.md
index a929d062d2..0fc2521a76 100644
--- a/docs/errorcode/linkis-engineconn-plugin-core-errorcode.md
+++ b/docs/errorcode/linkis-engineconn-plugin-core-errorcode.md
@@ -3,7 +3,7 @@
| module name(模块名) | error code(错误码) | describe(描述) |enumeration name(枚举)| Exception Class(类名)|
| -------- | -------- | ----- |-----|-----|
|linkis-engineconn-plugin-core |10001|Failed to createEngineConnLaunchRequest(创建 EngineConnLaunchRequest失败)|FAILED_CREATE_ELR|EngineconnCoreErrorCodeSummary|
-|linkis-engineconn-plugin-core |10001|The engine plug-in material is abnormal, please check whether the material is uploaded successfully(引擎插件物料异常,请检查物料是否上传成功)|EN_PLUGIN_MATERIAL_SOURCE_EXCEPTION|EngineconnCoreErrorCodeSummary|
+|linkis-engineconn-plugin-core |10001|The engine plugin material is abnormal, please check whether the material is uploaded successfully(引擎插件物料异常,请检查物料是否上传成功)|EN_PLUGIN_MATERIAL_SOURCE_EXCEPTION|EngineconnCoreErrorCodeSummary|
|linkis-engineconn-plugin-core |10001|EngineTypeLabel are requested(需要参数 EngineTypeLabel)|ETL_REQUESTED|EngineconnCoreErrorCodeSummary|
|linkis-engineconn-plugin-core |20000|Cannot instance EngineConnExecution(无法实例化 EngineConnExecution)|CANNOT_INSTANCE_ECE|EngineconnCoreErrorCodeSummary|
|linkis-engineconn-plugin-core |20000|Cannot find default ExecutorFactory(找不到默认的 ExecutorFactory)|CANNOT_DEFAULT_EF|EngineconnCoreErrorCodeSummary|
diff --git a/docs/errorcode/python-errorcode.md b/docs/errorcode/python-errorcode.md
index 8a4f843484..cf63aaa3fe 100644
--- a/docs/errorcode/python-errorcode.md
+++ b/docs/errorcode/python-errorcode.md
@@ -1,7 +1,7 @@
## python errorcode
-| 模块名(服务名) | 错误码 | 描述 |enumeration name| Exception Class|
-| -------- | -------- | ----- |-----|-----|
-|python|41001| |PYTHON_EXECUTE_ERROR|LinkisPythonErrorCodeSummary|
-|python|60003|Pyspark process has stopped, query failed!(Pyspark 进程已停止,查询失败!)|PYSPARK_PROCESSS_STOPPED|LinkisPythonErrorCodeSummary|
-|python|400201|Invalid python session.(无效的 python 会话.)|INVALID_PYTHON_SESSION|LinkisPythonErrorCodeSummary|
+| 模块名(服务名) | 错误码 | 描述 |enumeration name| Exception Class|
+| -------- |--------| ----- |-----|-----|
+|python| 60002 | |PYTHON_EXECUTE_ERROR|LinkisPythonErrorCodeSummary|
+|python| 60003 |Pyspark process has stopped, query failed!(Pyspark 进程已停止,查询失败!)|PYSPARK_PROCESSS_STOPPED|LinkisPythonErrorCodeSummary|
+|python| 400201 |Invalid python session.(无效的 python 会话.)|INVALID_PYTHON_SESSION|LinkisPythonErrorCodeSummary|
diff --git a/docs/info-1.3.2.md b/docs/info-1.3.2.md
index 55e5aeecbc..0c690517fb 100644
--- a/docs/info-1.3.2.md
+++ b/docs/info-1.3.2.md
@@ -4,4 +4,5 @@
|------------------| ----- |----------------------------------------------------------------------|------| ------------------------------------------------------- |
| linkis-jobhistory | 新增 | wds.linkis.jobhistory.admin | hadoop |可以查看所有历史任务的用户 注意:wds.linkis.governance.station.admin 为管理用户(也具有可以查看所有历史任务的权限)|
| linkis | 新增 | wds.linkis.governance.station.admin.token | /具有管理员权限的特殊token|
+| linkis | 新增 | linkis.configuration.remove.application.cache | IDE |清除该应用的配置缓存|
| cg-entrance | 新增 | linkis.entrance.auto.clean.dirty.data.enable | true |entrance重启调用ps-jobhistory接口是否开启,ture为开启,取值范围:true或false|
diff --git a/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ByteTimeUtils.java b/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ByteTimeUtils.java
index d23f4a0867..0ecb3dc2a5 100644
--- a/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ByteTimeUtils.java
+++ b/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ByteTimeUtils.java
@@ -213,7 +213,6 @@ private static long parseByteString(String str, ByteUnit unit) {
} else {
throw new NumberFormatException("Failed to parse byte string: " + str);
}
- suffix = suffix.toLowerCase();
// Check for invalid suffixes
if (suffix != null && !byteSuffixes.containsKey(suffix)) {
throw new NumberFormatException("Invalid suffix: \"" + suffix + "\"");
@@ -297,6 +296,18 @@ public static long byteStringAsGb(String str) {
return parseByteString(str, ByteUnit.GiB);
}
+ /**
+ * Convert a passed byte string (e.g. -50b, -100k, or -250m) to gibibytes for internal use.
+ *
+ *
If no suffix is provided, the passed number is assumed to be in gibibytes.
+ */
+ public static long negativeByteStringAsGb(String str) {
+ if (str.startsWith("-")) {
+ return Math.negateExact(parseByteString(str.substring(1), ByteUnit.GiB));
+ }
+ return parseByteString(str, ByteUnit.GiB);
+ }
+
/**
* Returns a byte array with the buffer's contents, trying to avoid copying the data if possible.
*/
diff --git a/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ResultSetUtils.java b/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ResultSetUtils.java
new file mode 100644
index 0000000000..a367b38b80
--- /dev/null
+++ b/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/ResultSetUtils.java
@@ -0,0 +1,57 @@
+/*
+ * 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.apache.linkis.common.utils;
+
+import org.apache.linkis.common.io.FsPath;
+
+import java.io.File;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ResultSetUtils {
+
+ // Sort in ASC order by numx in the result set _numx.dolphin file name
+ public static Comparator getResultSetFileComparatorOrderByNameNum() {
+
+ Comparator comparator =
+ (o1, o2) -> {
+ // get the num of file name
+ String regx = "\\d+";
+
+ String[] res1 = o1.getPath().split(File.separator);
+ String fileName1 = res1[res1.length - 1];
+ Matcher matcher1 = Pattern.compile(regx).matcher(fileName1);
+ int num1 = matcher1.find() ? Integer.parseInt(matcher1.group()) : Integer.MAX_VALUE;
+
+ String[] res2 = o2.getPath().split(File.separator);
+ String fileName2 = res2[res2.length - 1];
+ Matcher matcher2 = Pattern.compile(regx).matcher(fileName2);
+ int num2 = matcher2.find() ? Integer.parseInt(matcher2.group()) : Integer.MAX_VALUE;
+
+ return num1 - num2;
+ };
+ return comparator;
+ }
+
+ public static void sortByNameNum(List fsPathList) {
+ Collections.sort(fsPathList, getResultSetFileComparatorOrderByNameNum());
+ }
+}
diff --git a/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/VariableOperationUtils.java b/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/VariableOperationUtils.java
index d71f8b40e6..615472474d 100644
--- a/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/VariableOperationUtils.java
+++ b/linkis-commons/linkis-common/src/main/java/org/apache/linkis/common/utils/VariableOperationUtils.java
@@ -28,7 +28,10 @@
import java.util.Iterator;
import java.util.Map;
+import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -49,6 +52,9 @@ public class VariableOperationUtils {
private static final String[] CYCLES =
new String[] {CYCLE_YEAR, CYCLE_MONTH, CYCLE_DAY, CYCLE_HOUR, CYCLE_MINUTE, CYCLE_SECOND};
+ private static final ObjectMapper mapper =
+ JsonMapper.builder().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build();
+
/**
* yyyy-MM-dd HH:mm:ss
*
@@ -78,30 +84,44 @@ public static ZonedDateTime toZonedDateTime(Date date) {
* @param str
* @return
*/
+ @Deprecated
public static String replaces(ZonedDateTime dateTime, String str)
throws VariableOperationFailedException {
- return replaces(dateTime, str, true);
+ try {
+ JsonNode rootNode = mapper.readTree(str);
+ if (rootNode.isArray() || rootNode.isObject()) {
+ replaceJson(dateTime, rootNode);
+ return rootNode.toString();
+ }
+ } catch (Exception e) {
+ return replace(dateTime, str);
+ }
+ return replace(dateTime, str);
}
/**
* json support variable operation
*
+ * @param codeType
* @param dateTime
* @param str
- * @param format
* @return
*/
- public static String replaces(ZonedDateTime dateTime, String str, boolean format)
+ public static String replaces(String codeType, ZonedDateTime dateTime, String str)
throws VariableOperationFailedException {
- try {
- JsonNode rootNode = JsonUtils.jackson().readTree(str);
- if (rootNode.isArray() || rootNode.isObject()) {
- replaceJson(dateTime, rootNode);
- return rootNode.toString();
+ String languageType = CodeAndRunTypeUtils.getLanguageTypeByCodeType(codeType, "");
+ if (languageType.equals(CodeAndRunTypeUtils.LANGUAGE_TYPE_JSON())) {
+ try {
+ JsonNode rootNode = mapper.readTree(str);
+ if (rootNode.isArray() || rootNode.isObject()) {
+ replaceJson(dateTime, rootNode);
+ return rootNode.toString();
+ }
+ } catch (Exception e) {
+ return replace(dateTime, str);
}
- } catch (Exception e) {
- return replace(dateTime, str);
}
+
return replace(dateTime, str);
}
@@ -197,7 +217,7 @@ private static void replaceJson(ZonedDateTime dateTime, JsonNode object)
} else if (temp.isObject()) {
replaceJson(dateTime, temp);
} else {
- arrayNode.insert(i, replace(dateTime, temp.toString()));
+ arrayNode.set(i, replace(dateTime, temp.toString()));
}
}
} else if (object.isObject()) {
diff --git a/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/conf/BDPConfiguration.scala b/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/conf/BDPConfiguration.scala
index 55535e5336..14febab63a 100644
--- a/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/conf/BDPConfiguration.scala
+++ b/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/conf/BDPConfiguration.scala
@@ -22,7 +22,7 @@ import org.apache.linkis.common.utils.{Logging, Utils}
import org.apache.commons.io.IOUtils
import org.apache.commons.lang3.StringUtils
-import java.io.{File, FileInputStream, InputStream, IOException}
+import java.io._
import java.util.Properties
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantReadWriteLock
@@ -140,15 +140,20 @@ private[conf] object BDPConfiguration extends Logging {
private def initConfig(config: Properties, filePath: String) {
var inputStream: InputStream = null
-
+ var reader: InputStreamReader = null
+ var buff: BufferedReader = null
Utils.tryFinally {
Utils.tryCatch {
inputStream = new FileInputStream(filePath)
- config.load(inputStream)
+ reader = new InputStreamReader(inputStream, "UTF-8")
+ buff = new BufferedReader(reader)
+ config.load(buff)
} { case e: IOException =>
logger.error("Can't load " + filePath, e)
}
} {
+ IOUtils.closeQuietly(buff)
+ IOUtils.closeQuietly(reader)
IOUtils.closeQuietly(inputStream)
}
}
diff --git a/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/utils/VariableUtils.scala b/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/utils/VariableUtils.scala
index 30bdeb4b14..6c5bd7cf3c 100644
--- a/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/utils/VariableUtils.scala
+++ b/linkis-commons/linkis-common/src/main/scala/org/apache/linkis/common/utils/VariableUtils.scala
@@ -143,9 +143,10 @@ object VariableUtils extends Logging {
}
initAllDateVars(run_date, nameAndType)
val codeOperation = parserVar(code, nameAndType)
- parserDate(codeOperation, run_date)
+ parserDate(codeType, codeOperation, run_date)
}
+ @deprecated
private def parserDate(code: String, run_date: CustomDateType): String = {
if (Configuration.VARIABLE_OPERATION) {
val zonedDateTime: ZonedDateTime = VariableOperationUtils.toZonedDateTime(run_date.getDate)
@@ -155,6 +156,15 @@ object VariableUtils extends Logging {
}
}
+ private def parserDate(codeType: String, code: String, run_date: CustomDateType): String = {
+ if (Configuration.VARIABLE_OPERATION) {
+ val zonedDateTime: ZonedDateTime = VariableOperationUtils.toZonedDateTime(run_date.getDate)
+ VariableOperationUtils.replaces(codeType, zonedDateTime, code)
+ } else {
+ code
+ }
+ }
+
private def initAllDateVars(
run_date: CustomDateType,
nameAndType: mutable.Map[String, variable.VariableType]
@@ -337,7 +347,7 @@ object VariableUtils extends Logging {
*
* @param code
* :code
- * @param codeType
+ * @param languageType
* :SQL,PYTHON
* @return
*/
@@ -346,27 +356,37 @@ object VariableUtils extends Logging {
var varString: String = null
var errString: String = null
+ var rightVarString: String = null
languageType match {
case CodeAndRunTypeUtils.LANGUAGE_TYPE_SQL =>
varString = """\s*--@set\s*.+\s*"""
+ rightVarString = """^\s*--@set\s*.+\s*"""
errString = """\s*--@.*"""
case CodeAndRunTypeUtils.LANGUAGE_TYPE_PYTHON | CodeAndRunTypeUtils.LANGUAGE_TYPE_SHELL =>
varString = """\s*#@set\s*.+\s*"""
+ rightVarString = """^\s*#@set\s*.+\s*"""
errString = """\s*#@"""
case CodeAndRunTypeUtils.LANGUAGE_TYPE_SCALA =>
varString = """\s*//@set\s*.+\s*"""
+ rightVarString = """^\s*//@set\s*.+\s*"""
errString = """\s*//@.+"""
case CodeAndRunTypeUtils.LANGUAGE_TYPE_JAVA =>
varString = """\s*!!@set\s*.+\s*"""
+ rightVarString = """^\s*!!@set\s*.+\s*"""
case _ =>
return nameAndValue
}
val customRegex = varString.r.unanchored
+ val customRightRegex = rightVarString.r.unanchored
val errRegex = errString.r.unanchored
code.split("\n").foreach { str =>
{
+
+ if (customRightRegex.unapplySeq(str).size < customRegex.unapplySeq(str).size) {
+ logger.warn(s"code:$str is wrong custom variable format!!!")
+ }
str match {
case customRegex() =>
val clearStr = if (str.endsWith(";")) str.substring(0, str.length - 1) else str
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-core/src/test/java/org/apache/linkis/cli/core/present/PresentModeImplTest.java b/linkis-commons/linkis-common/src/test/java/org/apache/linkis/common/conf/BDPConfigurationTest.java
similarity index 60%
rename from linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-core/src/test/java/org/apache/linkis/cli/core/present/PresentModeImplTest.java
rename to linkis-commons/linkis-common/src/test/java/org/apache/linkis/common/conf/BDPConfigurationTest.java
index 8f776bef81..5a025eb8b0 100644
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-core/src/test/java/org/apache/linkis/cli/core/present/PresentModeImplTest.java
+++ b/linkis-commons/linkis-common/src/test/java/org/apache/linkis/common/conf/BDPConfigurationTest.java
@@ -15,22 +15,27 @@
* limitations under the License.
*/
-package org.apache.linkis.cli.core.present;
+package org.apache.linkis.common.conf;
import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
-public class PresentModeImplTest {
+/** BDPConfiguration Tester */
+public class BDPConfigurationTest {
@Test
- @DisplayName("enumTest")
- public void enumTest() {
+ public void testGetOption() {
- String stdoutName = PresentModeImpl.STDOUT.getName();
- String textFileName = PresentModeImpl.TEXT_FILE.getName();
+ Assertions.assertEquals(
+ "properties支持中文",
+ BDPConfiguration.getOption(
+ CommonVars.apply("linkis.jobhistory.error.msg.tip", "properties支持中文"))
+ .get());
- Assertions.assertEquals("STDOUT", stdoutName);
- Assertions.assertEquals("TEXT_FILE", textFileName);
+ Assertions.assertEquals(
+ "properties支持中文(默认)",
+ BDPConfiguration.getOption(
+ CommonVars.apply("linkis.jobhistory.error.msg.tip1", "properties支持中文(默认)"))
+ .get());
}
}
diff --git a/linkis-commons/linkis-common/src/test/java/org/apache/linkis/common/utils/ByteTimeUtilsTest.java b/linkis-commons/linkis-common/src/test/java/org/apache/linkis/common/utils/ByteTimeUtilsTest.java
new file mode 100644
index 0000000000..f548d89d46
--- /dev/null
+++ b/linkis-commons/linkis-common/src/test/java/org/apache/linkis/common/utils/ByteTimeUtilsTest.java
@@ -0,0 +1,175 @@
+/*
+ * 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.apache.linkis.common.utils;
+
+import java.util.function.Function;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class ByteTimeUtilsTest {
+
+ private static final ImmutableMap> opFunction =
+ ImmutableMap.>builder()
+ .put("byteStringAsBytes", tar -> ByteTimeUtils.byteStringAsBytes(tar))
+ .put("byteStringAsKb", tar -> ByteTimeUtils.byteStringAsKb(tar))
+ .put("byteStringAsMb", tar -> ByteTimeUtils.byteStringAsMb(tar))
+ .put("byteStringAsGb", tar -> ByteTimeUtils.byteStringAsGb(tar))
+ .build();
+
+ private static final ImmutableMap convertToByte =
+ ImmutableMap.builder()
+ .put("1", 1l)
+ .put("1b", 1l)
+ .put("1B", 1l)
+ .put("1k", 1024l)
+ .put("1K", 1024l)
+ .put("1kb", 1024l)
+ .put("1Kb", 1024l)
+ .put("1kB", 1024l)
+ .put("1KB", 1024l)
+ .put("1m", 1024l * 1024l)
+ .put("1M", 1024l * 1024l)
+ .put("1mb", 1024l * 1024l)
+ .put("1Mb", 1024l * 1024l)
+ .put("1mB", 1024l * 1024l)
+ .put("1MB", 1024l * 1024l)
+ .put("1g", 1024l * 1024l * 1024l)
+ .put("1G", 1024l * 1024l * 1024l)
+ .put("1gb", 1024l * 1024l * 1024l)
+ .put("1gB", 1024l * 1024l * 1024l)
+ .put("1Gb", 1024l * 1024l * 1024l)
+ .put("1GB", 1024l * 1024l * 1024l)
+ .put("1t", 1024l * 1024l * 1024l * 1024l)
+ .put("1T", 1024l * 1024l * 1024l * 1024l)
+ .put("1tb", 1024l * 1024l * 1024l * 1024l)
+ .put("1Tb", 1024l * 1024l * 1024l * 1024l)
+ .put("1tB", 1024l * 1024l * 1024l * 1024l)
+ .put("1TB", 1024l * 1024l * 1024l * 1024l)
+ .put("1p", 1024l * 1024l * 1024l * 1024l * 1024l)
+ .put("1P", 1024l * 1024l * 1024l * 1024l * 1024l)
+ .put("1pb", 1024l * 1024l * 1024l * 1024l * 1024l)
+ .put("1Pb", 1024l * 1024l * 1024l * 1024l * 1024l)
+ .put("1pB", 1024l * 1024l * 1024l * 1024l * 1024l)
+ .put("1PB", 1024l * 1024l * 1024l * 1024l * 1024l)
+ .build();
+
+ private static final ImmutableMap convertToKB =
+ ImmutableMap.builder()
+ .put("1", 1l)
+ .put("1024b", 1l)
+ .put("1024B", 1l)
+ .put("1k", 1l)
+ .put("1K", 1l)
+ .put("1kb", 1l)
+ .put("1Kb", 1l)
+ .put("1kB", 1l)
+ .put("1KB", 1l)
+ .put("1m", 1024l)
+ .put("1M", 1024l)
+ .put("1mb", 1024l)
+ .put("1Mb", 1024l)
+ .put("1mB", 1024l)
+ .put("1MB", 1024l)
+ .put("1g", 1024l * 1024l)
+ .put("1G", 1024l * 1024l)
+ .put("1gb", 1024l * 1024l)
+ .put("1gB", 1024l * 1024l)
+ .put("1Gb", 1024l * 1024l)
+ .put("1GB", 1024l * 1024l)
+ .build();
+
+ private static final ImmutableMap convertToMB =
+ ImmutableMap.builder()
+ .put("1", 1l)
+ .put("1024k", 1l)
+ .put("1024K", 1l)
+ .put("1024kb", 1l)
+ .put("1024Kb", 1l)
+ .put("1024kB", 1l)
+ .put("1024KB", 1l)
+ .put("1m", 1l)
+ .put("1M", 1l)
+ .put("1mb", 1l)
+ .put("1Mb", 1l)
+ .put("1mB", 1l)
+ .put("1MB", 1l)
+ .put("1g", 1024l)
+ .put("1G", 1024l)
+ .put("1gb", 1024l)
+ .put("1gB", 1024l)
+ .put("1Gb", 1024l)
+ .put("1GB", 1024l)
+ .build();
+
+ private static final ImmutableMap convertToGB =
+ ImmutableMap.builder()
+ .put("1", 1l)
+ .put("1024m", 1l)
+ .put("1024M", 1l)
+ .put("1024mb", 1l)
+ .put("1024Mb", 1l)
+ .put("1024mB", 1l)
+ .put("1024MB", 1l)
+ .put("1g", 1l)
+ .put("1G", 1l)
+ .put("1gb", 1l)
+ .put("1gB", 1l)
+ .put("1Gb", 1l)
+ .put("1GB", 1l)
+ .put("1t", 1024l)
+ .put("1T", 1024l)
+ .put("1tb", 1024l)
+ .put("1Tb", 1024l)
+ .put("1tB", 1024l)
+ .put("1TB", 1024l)
+ .build();
+
+ @Test
+ void byteStringAsBytes() {
+ convertToByte.forEach(
+ (k, v) -> Assertions.assertEquals(opFunction.get("byteStringAsBytes").apply(k), v));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> opFunction.get("byteStringAsBytes").apply("1A"));
+ }
+
+ @Test
+ void byteStringAsKb() {
+ convertToKB.forEach(
+ (k, v) -> Assertions.assertEquals(opFunction.get("byteStringAsKb").apply(k), v));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> opFunction.get("byteStringAsKb").apply("1a"));
+ }
+
+ @Test
+ void byteStringAsMb() {
+ convertToMB.forEach(
+ (k, v) -> Assertions.assertEquals(opFunction.get("byteStringAsMb").apply(k), v));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> opFunction.get("byteStringAsMb").apply("1c"));
+ }
+
+ @Test
+ void byteStringAsGb() {
+ convertToGB.forEach(
+ (k, v) -> Assertions.assertEquals(opFunction.get("byteStringAsGb").apply(k), v));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> opFunction.get("byteStringAsGb").apply("1C"));
+ }
+}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-core/src/test/resources/conf/user.properties b/linkis-commons/linkis-common/src/test/resources/linkis.properties
similarity index 86%
rename from linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-core/src/test/resources/conf/user.properties
rename to linkis-commons/linkis-common/src/test/resources/linkis.properties
index faa650fc5c..230ad85a4e 100644
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-core/src/test/resources/conf/user.properties
+++ b/linkis-commons/linkis-common/src/test/resources/linkis.properties
@@ -12,8 +12,5 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-#
-user.props=xxxxxxxxxxxxx
-conf.prop.integer=9
-conf.prop.string=str
-wds.linkis.client.param.conf.spark.executor.memory=11111G
\ No newline at end of file
+
+linkis.jobhistory.error.msg.tip=properties支持中文
\ No newline at end of file
diff --git a/linkis-commons/linkis-common/src/test/scala/org/apache/linkis/common/utils/VariableUtilsTest.scala b/linkis-commons/linkis-common/src/test/scala/org/apache/linkis/common/utils/VariableUtilsTest.scala
index c0d4ad1d61..e7a105497c 100644
--- a/linkis-commons/linkis-common/src/test/scala/org/apache/linkis/common/utils/VariableUtilsTest.scala
+++ b/linkis-commons/linkis-common/src/test/scala/org/apache/linkis/common/utils/VariableUtilsTest.scala
@@ -22,6 +22,8 @@ import org.apache.linkis.common.variable.DateTypeUtils.{getCurHour, getToday}
import java.util
+import scala.collection.mutable
+
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
@@ -63,4 +65,19 @@ class VariableUtilsTest {
assertEquals(VariableUtils.replace(sql, "sql", varMap), resSql)
}
+ @Test
+ def testGetCustomVar: Unit = {
+ var scalaCode = "" +
+ "-------@set globalpara=60--------\n" +
+ "--@set globalpara2=66\n" +
+ "select ${globalpara} as globalpara,\n" +
+ "-- ${globalpara1} as globalpara1, \n" +
+ "${globalpara2} as globalpara2;\n"
+ var pythonCode = ""
+
+ val nameAndValue: mutable.Map[String, String] =
+ VariableUtils.getCustomVar(scalaCode, CodeAndRunTypeUtils.LANGUAGE_TYPE_SQL);
+ assertEquals(nameAndValue.size, 2)
+ }
+
}
diff --git a/linkis-commons/linkis-httpclient/src/main/scala/org/apache/linkis/httpclient/config/ClientConfigBuilder.scala b/linkis-commons/linkis-httpclient/src/main/scala/org/apache/linkis/httpclient/config/ClientConfigBuilder.scala
index c3e5afba30..b1fc579f3c 100644
--- a/linkis-commons/linkis-httpclient/src/main/scala/org/apache/linkis/httpclient/config/ClientConfigBuilder.scala
+++ b/linkis-commons/linkis-httpclient/src/main/scala/org/apache/linkis/httpclient/config/ClientConfigBuilder.scala
@@ -17,6 +17,7 @@
package org.apache.linkis.httpclient.config
+import org.apache.linkis.common.exception.LinkisRetryException
import org.apache.linkis.common.utils.{DefaultRetryHandler, RetryHandler}
import org.apache.linkis.httpclient.authentication.AuthenticationStrategy
import org.apache.linkis.httpclient.loadbalancer.LoadBalancerStrategy
@@ -38,7 +39,12 @@ class ClientConfigBuilder protected () {
protected var readTimeout: Long = _
protected var maxConnection: Int = _
protected var retryEnabled: Boolean = true
- protected var retryHandler: RetryHandler = new DefaultRetryHandler
+
+ protected var retryHandler: RetryHandler = {
+ val retryHandler = new DefaultRetryHandler
+ retryHandler.addRetryException(classOf[LinkisRetryException])
+ retryHandler
+ }
def addServerUrl(serverUrl: String): this.type = {
this.serverUrl = serverUrl
diff --git a/linkis-commons/linkis-module/pom.xml b/linkis-commons/linkis-module/pom.xml
index b70331e0d1..cbaf0295fd 100644
--- a/linkis-commons/linkis-module/pom.xml
+++ b/linkis-commons/linkis-module/pom.xml
@@ -294,6 +294,7 @@
org.springframework.security
spring-security-crypto
+ 5.7.5
diff --git a/linkis-commons/linkis-module/src/main/scala/org/apache/linkis/server/security/SecurityFilter.scala b/linkis-commons/linkis-module/src/main/scala/org/apache/linkis/server/security/SecurityFilter.scala
index 411bda4820..5cc796d23e 100644
--- a/linkis-commons/linkis-module/src/main/scala/org/apache/linkis/server/security/SecurityFilter.scala
+++ b/linkis-commons/linkis-module/src/main/scala/org/apache/linkis/server/security/SecurityFilter.scala
@@ -199,7 +199,11 @@ object SecurityFilter {
def getLoginUsername(req: HttpServletRequest): String = {
if (Configuration.IS_TEST_MODE.getValue) {
- ServerConfiguration.BDP_TEST_USER.getValue;
+ val testUser = ServerConfiguration.BDP_TEST_USER.getValue
+ if (StringUtils.isBlank(testUser)) {
+ throw new IllegalUserTicketException("Need to set test user when enable test module")
+ }
+ testUser
} else {
getLoginUser(req).getOrElse(
throw new IllegalUserTicketException(ILLEGAL_USER_TOKEN.getErrorDesc)
diff --git a/linkis-commons/linkis-protocol/src/main/java/org/apache/linkis/protocol/constants/TaskConstant.java b/linkis-commons/linkis-protocol/src/main/java/org/apache/linkis/protocol/constants/TaskConstant.java
index 42661f8283..6eb97c84d9 100644
--- a/linkis-commons/linkis-protocol/src/main/java/org/apache/linkis/protocol/constants/TaskConstant.java
+++ b/linkis-commons/linkis-protocol/src/main/java/org/apache/linkis/protocol/constants/TaskConstant.java
@@ -69,6 +69,7 @@ public interface TaskConstant {
String TICKET_ID = "ticketId";
String ENGINE_CONN_TASK_ID = "engineConnTaskId";
String ENGINE_CONN_SUBMIT_TIME = "engineConnSubmitTime";
+ String DEBUG_ENBALE = "debug.enable";
String PARAMS_DATA_SOURCE = "dataSources";
diff --git a/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/callback/LogCallbackProtocol.scala b/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/callback/LogCallbackProtocol.scala
index 91b0e01727..0109472a90 100644
--- a/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/callback/LogCallbackProtocol.scala
+++ b/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/callback/LogCallbackProtocol.scala
@@ -19,9 +19,6 @@ package org.apache.linkis.protocol.callback
import org.apache.linkis.protocol.message.RequestProtocol
-// TODO: log type
-case class LogCallbackProtocol(nodeId: String, logs: Array[String]) extends RequestProtocol
-
case class YarnAPPIdCallbackProtocol(nodeId: String, applicationId: String) extends RequestProtocol
case class YarnInfoCallbackProtocol(nodeId: String, uri: String) extends RequestProtocol
diff --git a/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/utils/TaskUtils.scala b/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/utils/TaskUtils.scala
index 3b94bbdc14..9b2be16ef7 100644
--- a/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/utils/TaskUtils.scala
+++ b/linkis-commons/linkis-protocol/src/main/scala/org/apache/linkis/protocol/utils/TaskUtils.scala
@@ -97,4 +97,15 @@ object TaskUtils {
def addLabelsMap(params: util.Map[String, AnyRef], labels: util.Map[String, AnyRef]): Unit =
addMap(params, labels, TaskConstant.LABELS)
+ def isWithDebugInfo(params: util.Map[String, AnyRef]): Boolean = {
+ val debug = getConfigurationMap(params, TaskConstant.PARAMS_CONFIGURATION_STARTUP).get(
+ TaskConstant.DEBUG_ENBALE
+ )
+ if (debug != null && "true".equals(debug.toString)) {
+ true
+ } else {
+ false
+ }
+ }
+
}
diff --git a/linkis-commons/linkis-rpc/pom.xml b/linkis-commons/linkis-rpc/pom.xml
index 3a51a0bfcd..e916107f50 100644
--- a/linkis-commons/linkis-rpc/pom.xml
+++ b/linkis-commons/linkis-rpc/pom.xml
@@ -56,15 +56,7 @@
com.fasterxml.jackson.core
- jackson-annotations
-
-
- com.fasterxml.jackson.core
- jackson-core
-
-
- com.fasterxml.jackson.core
- jackson-databind
+ *
com.google.code.findbugs
@@ -78,8 +70,17 @@
org.springframework.cloud
spring-cloud-commons
+
+ commons-fileupload
+ commons-fileupload
+
+
+ commons-fileupload
+ commons-fileupload
+ ${commons-fileupload.version}
+
org.springframework.cloud
spring-cloud-commons
diff --git a/linkis-commons/linkis-rpc/src/main/scala/org/apache/linkis/rpc/conf/RPCConfiguration.scala b/linkis-commons/linkis-rpc/src/main/scala/org/apache/linkis/rpc/conf/RPCConfiguration.scala
index 32f12da273..22e6ea9f6c 100644
--- a/linkis-commons/linkis-rpc/src/main/scala/org/apache/linkis/rpc/conf/RPCConfiguration.scala
+++ b/linkis-commons/linkis-rpc/src/main/scala/org/apache/linkis/rpc/conf/RPCConfiguration.scala
@@ -80,6 +80,13 @@ object RPCConfiguration {
CommonVars("wds.linkis.gateway.conf.linkismanager.list", "linkisManager,engineplugin").getValue
.split(",")
+ val LINKIS_DATASOURCE_SERVICE_NAME: CommonVars[String] =
+ CommonVars("linkis.gateway.conf.linkisdatasource.name", "linkis-ps-datasource")
+
+ val LINKIS_DATASOURCE_SERVICE_LIST: Array[String] =
+ CommonVars("linkis.gateway.conf.linkisdatasource.list", "datasource").getValue
+ .split(",")
+
val BDP_RPC_INSTANCE_ALIAS_SERVICE_REFRESH_INTERVAL: CommonVars[TimeType] =
CommonVars("wds.linkis.rpc.instancealias.refresh.interval", new TimeType("3s"))
diff --git a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/Consumer.scala b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/Consumer.scala
index 50dce2ca12..165a274362 100644
--- a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/Consumer.scala
+++ b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/Consumer.scala
@@ -41,7 +41,6 @@ abstract class Consumer(schedulerContext: SchedulerContext, executeService: Exec
def start(): Unit
def shutdown(): Unit = {
- logger.info(s"$toString is ready to stop!")
terminate = true
logger.info(s"$toString stopped!")
}
diff --git a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/GroupFactory.scala b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/GroupFactory.scala
index f3471b07dd..be1716f238 100644
--- a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/GroupFactory.scala
+++ b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/GroupFactory.scala
@@ -19,6 +19,11 @@ package org.apache.linkis.scheduler.queue
abstract class GroupFactory {
+ /**
+ * Create a Group and set the concurrency limit of the group
+ * @param event
+ * @return
+ */
def getOrCreateGroup(event: SchedulerEvent): Group
def getGroup(groupName: String): Group
diff --git a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/LoopArrayQueue.scala b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/LoopArrayQueue.scala
index b0bbfd3c2b..8bea7e52b1 100644
--- a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/LoopArrayQueue.scala
+++ b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/LoopArrayQueue.scala
@@ -40,7 +40,12 @@ class LoopArrayQueue(var group: Group) extends ConsumeQueue with Logging {
override def getWaitingEvents: Array[SchedulerEvent] = {
eventQueue synchronized {
- toIndexedSeq.filter(x => x.getState.equals(SchedulerEventState.Inited)).toArray
+ toIndexedSeq
+ .filter(x =>
+ x.getState.equals(SchedulerEventState.Inited) || x.getState
+ .equals(SchedulerEventState.Scheduled)
+ )
+ .toArray
}
}
diff --git a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala
index 2a40c2517b..d541d8a2eb 100644
--- a/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala
+++ b/linkis-commons/linkis-scheduler/src/main/scala/org/apache/linkis/scheduler/queue/fifoqueue/FIFOUserConsumer.scala
@@ -73,6 +73,8 @@ class FIFOUserConsumer(
override def getRunningEvents: Array[SchedulerEvent] =
getEvents(e => e.isRunning || e.isWaitForRetry)
+ protected def getSchedulerContext: SchedulerContext = schedulerContext
+
private def getEvents(op: SchedulerEvent => Boolean): Array[SchedulerEvent] = {
val result = ArrayBuffer[SchedulerEvent]()
runningJobs.filter(_ != null).filter(x => op(x)).foreach(result += _)
@@ -82,16 +84,28 @@ class FIFOUserConsumer(
override def run(): Unit = {
Thread.currentThread().setName(s"${toString}Thread")
logger.info(s"$toString thread started!")
- while (!terminate) {
- Utils.tryAndError(loop())
- Utils.tryAndError(Thread.sleep(10))
+ while (!terminate) Utils.tryAndError {
+ loop()
+ Thread.sleep(10)
}
logger.info(s"$toString thread stopped!")
}
protected def askExecutorGap(): Unit = {}
+ /**
+ * Task scheduling interception is used to judge the rules of task operation, and to judge other
+ * task rules based on Group. For example, Entrance makes Creator-level task judgment.
+ */
+ protected def runScheduleIntercept(): Boolean = {
+ true
+ }
+
protected def loop(): Unit = {
+ if (!runScheduleIntercept()) {
+ Utils.tryQuietly(Thread.sleep(1000))
+ return
+ }
var isRetryJob = false
def getWaitForRetryEvent: Option[SchedulerEvent] = {
val waitForRetryJobs = runningJobs.filter(job => job != null && job.isJobCanRetry)
@@ -110,7 +124,7 @@ class FIFOUserConsumer(
if (event.isEmpty) {
val completedNums = runningJobs.filter(job => job == null || job.isCompleted)
if (completedNums.length < 1) {
- Utils.tryQuietly(Thread.sleep(1000)) // TODO 还可以优化,通过实现JobListener进行优化
+ Utils.tryQuietly(Thread.sleep(1000))
return
}
while (event.isEmpty) {
@@ -119,7 +133,12 @@ class FIFOUserConsumer(
if (
takeEvent.exists(e =>
Utils.tryCatch(e.turnToScheduled()) { t =>
- takeEvent.get.asInstanceOf[Job].onFailure("Job状态翻转为Scheduled失败!", t)
+ takeEvent.get
+ .asInstanceOf[Job]
+ .onFailure(
+ "Failed to change the job status to Scheduled(Job状态翻转为Scheduled失败)",
+ t
+ )
false
}
)
@@ -174,7 +193,7 @@ class FIFOUserConsumer(
)
)
case error: Throwable =>
- job.onFailure("请求引擎失败,可能是由于后台进程错误!请联系管理员", error)
+ job.onFailure("Failed to request EngineConn", error)
if (job.isWaitForRetry) {
logger.warn(s"Ask executor for Job $job failed, wait for the next retry!", error)
if (!isRetryJob) putToRunningJobs(job)
@@ -190,6 +209,20 @@ class FIFOUserConsumer(
override def shutdown(): Unit = {
future.cancel(true)
+ val waitEvents = queue.getWaitingEvents
+ if (waitEvents.nonEmpty) {
+ waitEvents.foreach {
+ case job: Job =>
+ job.onFailure("Your job will be marked as canceled because the consumer be killed", null)
+ case _ =>
+ }
+ }
+
+ this.runningJobs.foreach { job =>
+ if (job != null && !job.isCompleted) {
+ job.onFailure("Your job will be marked as canceled because the consumer be killed", null)
+ }
+ }
super.shutdown()
}
diff --git a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/excel/XlsUtils.java b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/excel/XlsUtils.java
index f3b8f44865..68469cb520 100644
--- a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/excel/XlsUtils.java
+++ b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/excel/XlsUtils.java
@@ -61,6 +61,7 @@ public static String excelToCsv(
throws Exception {
String hdfsPath =
"/tmp/" + StorageUtils.getJvmUser() + "/" + System.currentTimeMillis() + ".csv";
+ LOG.info("The excel to csv with hdfs path:" + hdfsPath);
ExcelXlsReader xlsReader = new ExcelXlsReader();
RowToCsvDeal rowToCsvDeal = new RowToCsvDeal();
OutputStream out = null;
diff --git a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/exception/StorageErrorCode.java b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/exception/StorageErrorCode.java
index 3c82ceb523..a8123a1f92 100644
--- a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/exception/StorageErrorCode.java
+++ b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/exception/StorageErrorCode.java
@@ -20,7 +20,9 @@
public enum StorageErrorCode {
/** */
- FS_NOT_INIT(53001, "please init first(请先初始化)");
+ FS_NOT_INIT(53001, "please init first(请先初始化)"),
+ INCONSISTENT_DATA(53001, "Inconsistent row data read,read %s,need rowLen %s"),
+ FS_OOM(53002, "OOM occurred while reading the file");
StorageErrorCode(int errorCode, String message) {
this.code = errorCode;
diff --git a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/FileSystem.java b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/FileSystem.java
index c19213a9cc..4bb7cb33b4 100644
--- a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/FileSystem.java
+++ b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/FileSystem.java
@@ -24,8 +24,13 @@
import java.io.File;
import java.io.IOException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public abstract class FileSystem implements Fs {
+ private static final Logger LOG = LoggerFactory.getLogger(FileSystem.class);
+
protected String user;
private String defaultFilePerm = "rwxr-----"; // 740
private String defaultFolderPerm = "rwxr-x---"; // 750
@@ -94,6 +99,7 @@ protected FsPath getParentPath(String path) {
} else {
parentPath = path.substring(0, path.lastIndexOf("/"));
}
+ LOG.info("Get parent path:" + parentPath);
return new FsPath(parentPath);
}
diff --git a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/impl/LocalFileSystem.java b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/impl/LocalFileSystem.java
index ce2ee43b7e..2df547f10e 100644
--- a/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/impl/LocalFileSystem.java
+++ b/linkis-commons/linkis-storage/src/main/java/org/apache/linkis/storage/fs/impl/LocalFileSystem.java
@@ -75,12 +75,14 @@ public String listRoot() throws IOException {
@Override
public long getTotalSpace(FsPath dest) throws IOException {
String path = dest.getPath();
+ LOG.info("Get total space with path:" + path);
return new File(path).getTotalSpace();
}
@Override
public long getFreeSpace(FsPath dest) throws IOException {
String path = dest.getPath();
+ LOG.info("Get free space with path:" + path);
return new File(path).getFreeSpace();
}
@@ -117,6 +119,7 @@ public boolean setOwner(FsPath dest, String user, String group) throws IOExcepti
@Override
public boolean setOwner(FsPath dest, String user) throws IOException {
+ LOG.info("Set owner with path:" + dest.getPath() + "and user:" + user);
if (!StorageUtils.isIOProxy()) {
LOG.info("io not proxy, setOwner skip");
return true;
@@ -133,6 +136,7 @@ public boolean setOwner(FsPath dest, String user) throws IOException {
@Override
public boolean setGroup(FsPath dest, String group) throws IOException {
+ LOG.info("Set group with path:" + dest.getPath() + "and group:" + user);
if (!StorageUtils.isIOProxy()) {
LOG.info("io not proxy, setGroup skip");
return true;
@@ -155,6 +159,7 @@ public boolean mkdir(FsPath dest) throws IOException {
@Override
public boolean mkdirs(FsPath dest) throws IOException {
String path = dest.getPath();
+ LOG.info("Try to mkdirs with path:" + path);
File file = new File(path);
// Create parent directories one by one and set their permissions to rwxrwxrwx.
Stack dirsToMake = new Stack();
@@ -182,6 +187,7 @@ public boolean mkdirs(FsPath dest) throws IOException {
}
public boolean canMkdir(FsPath destParentDir) throws IOException {
+ LOG.info("Try to check if the directory can be created with path:" + destParentDir.getPath());
if (!StorageUtils.isIOProxy()) {
LOG.debug("io not proxy, not check owner, just check if have write permission ");
return this.canWrite(destParentDir);
@@ -203,6 +209,7 @@ public boolean canMkdir(FsPath destParentDir) throws IOException {
@Override
public boolean copy(String origin, String dest) throws IOException {
File file = new File(dest);
+ LOG.info("Try to copy file from:" + origin + " to dest:" + dest);
if (!isOwner(file.getParent())) {
throw new IOException("you have on permission to create file " + dest);
}
@@ -225,6 +232,7 @@ public boolean copy(String origin, String dest) throws IOException {
@Override
public boolean setPermission(FsPath dest, String permission) throws IOException {
+ LOG.info("Try to set permission dest with path:" + dest.getPath());
if (!StorageUtils.isIOProxy()) {
LOG.info("io not proxy, setPermission as parent.");
try {
@@ -251,6 +259,7 @@ public boolean setPermission(FsPath dest, String permission) throws IOException
public FsPathListWithError listPathWithError(FsPath path) throws IOException {
File file = new File(path.getPath());
File[] files = file.listFiles();
+ LOG.info("Try to list path:" + path.getPath() + " with error msg");
if (files != null) {
List rtn = new ArrayList();
String message = "";
@@ -294,6 +303,7 @@ public void init(Map properties) throws IOException {
String groupInfo;
try {
groupInfo = Utils.exec(new String[] {"id", user});
+ LOG.info("Get groupinfo:" + groupInfo + " with shell command: id " + user);
} catch (RuntimeException e) {
group = user;
return;
@@ -322,7 +332,7 @@ public FsPath get(String dest) throws IOException {
} else {
fsPath = new FsPath(dest);
}
-
+ LOG.info("Try to get FsPath with path:" + fsPath.getPath());
PosixFileAttributes attr = null;
try {
attr = Files.readAttributes(Paths.get(fsPath.getPath()), PosixFileAttributes.class);
@@ -365,7 +375,7 @@ public OutputStream write(FsPath dest, boolean overwrite) throws IOException {
@Override
public boolean create(String dest) throws IOException {
-
+ LOG.info("try to create file with path:" + dest);
File file = new File(dest);
if (!isOwner(file.getParent())) {
throw new IOException("you have on permission to create file " + dest);
@@ -391,6 +401,7 @@ public boolean create(String dest) throws IOException {
public List list(FsPath path) throws IOException {
File file = new File(path.getPath());
File[] files = file.listFiles();
+ LOG.info("Try to get file list with path:" + path.getPath());
if (files != null) {
List rtn = new ArrayList();
for (File f : files) {
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/conf/LinkisStorageConf.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/conf/LinkisStorageConf.scala
index bf03c78754..1d32d97fef 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/conf/LinkisStorageConf.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/conf/LinkisStorageConf.scala
@@ -60,4 +60,5 @@ object LinkisStorageConf {
fileTypeArr
}
+ val LINKIS_RESULT_ENABLE_NULL = CommonVars("linkis.resultset.enable.null.replace", true).getValue
}
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/csv/StorageCSVWriter.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/csv/StorageCSVWriter.scala
index f9b811b6a6..63dce31ca4 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/csv/StorageCSVWriter.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/csv/StorageCSVWriter.scala
@@ -36,6 +36,8 @@ class StorageCSVWriter(
with Logging {
private val delimiter = separator match {
+ // Compatible with possible missing escape characters
+ case "t" => '\t'
case separ if StringUtils.isNotEmpty(separ) => separ
case _ => '\t'
}
@@ -50,14 +52,21 @@ class StorageCSVWriter(
private def compact(row: Array[String]): String = {
val quotationMarks: String = "\""
+ val dealNewlineSymbolMarks: String = "\n"
+
def decorateValue(v: String): String = {
if (StringUtils.isBlank(v)) v
else {
+ var res = v
if (quoteRetouchEnable) {
- s"$quotationMarks${v.replaceAll(quotationMarks, "")}$quotationMarks"
- } else v
+ res = s"$quotationMarks${v.replaceAll(quotationMarks, "")}$quotationMarks"
+ }
+ res = res.replaceAll(dealNewlineSymbolMarks, " ")
+ logger.debug("decorateValue with input:" + v + " output:" + res)
+ res
}
}
+
if (logger.isDebugEnabled()) {
logger.debug("delimiter:" + delimiter.toString)
}
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/DataType.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/DataType.scala
index 55c82abd38..61d5fb7b3d 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/DataType.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/DataType.scala
@@ -18,15 +18,15 @@
package org.apache.linkis.storage.domain
import org.apache.linkis.common.utils.{Logging, Utils}
+import org.apache.linkis.storage.conf.LinkisStorageConf
import java.math.{BigDecimal => JavaBigDecimal}
import java.sql.{Date, Timestamp}
object DataType extends Logging {
- val NULL_VALUE = "NULL"
val LOWCASE_NULL_VALUE = "null"
- // TODO Change to fine-grained regular expressions(改为精细化正则表达式)
+
val DECIMAL_REGEX = "^decimal\\(\\d*\\,\\d*\\)".r.unanchored
val SHORT_REGEX = "^short.*".r.unanchored
@@ -70,39 +70,53 @@ object DataType extends Logging {
case _ => StringType
}
- def toValue(dataType: DataType, value: String): Any = Utils.tryCatch(dataType match {
- case NullType => null
- case StringType | CharType | VarcharType | StructType | ListType | ArrayType | MapType =>
- value
- case BooleanType => if (isNumberNull(value)) null else value.toBoolean
- case ShortIntType => if (isNumberNull(value)) null else value.toShort
- case IntType => if (isNumberNull(value)) null else value.toInt
- case LongType | BigIntType => if (isNumberNull(value)) null else value.toLong
- case FloatType => if (isNumberNull(value)) null else value.toFloat
- case DoubleType => if (isNumberNull(value)) null else value.toDouble
- case DecimalType => if (isNumberNull(value)) null else new JavaBigDecimal(value)
- case DateType => if (isNumberNull(value)) null else Date.valueOf(value)
- case TimestampType =>
- if (isNumberNull(value)) null else Timestamp.valueOf(value).toString.stripSuffix(".0")
- case BinaryType => if (isNull(value)) null else value.getBytes()
- case _ => value
- }) { t =>
- logger.debug(s"Failed to $value switch to dataType:", t)
- value
+ def toValue(dataType: DataType, value: String): Any = {
+ var newValue: String = value
+ if (isLinkisNull(value)) {
+ if (!LinkisStorageConf.LINKIS_RESULT_ENABLE_NULL) {
+ return null
+ } else {
+ newValue = Dolphin.NULL
+ }
+ }
+ Utils.tryCatch(dataType match {
+ case NullType => null
+ case StringType | CharType | VarcharType | StructType | ListType | ArrayType | MapType =>
+ newValue
+ case BooleanType => if (isNumberNull(newValue)) null else newValue.toBoolean
+ case ShortIntType => if (isNumberNull(newValue)) null else newValue.toShort
+ case IntType => if (isNumberNull(newValue)) null else newValue.toInt
+ case LongType | BigIntType => if (isNumberNull(newValue)) null else newValue.toLong
+ case FloatType => if (isNumberNull(newValue)) null else newValue.toFloat
+ case DoubleType => if (isNumberNull(newValue)) null else newValue.toDouble
+ case DecimalType => if (isNumberNull(newValue)) null else new JavaBigDecimal(newValue)
+ case DateType => if (isNumberNull(newValue)) null else Date.valueOf(newValue)
+ case TimestampType =>
+ if (isNumberNull(newValue)) null else Timestamp.valueOf(newValue).toString.stripSuffix(".0")
+ case BinaryType => if (isNull(newValue)) null else newValue.getBytes()
+ case _ => newValue
+ }) { t =>
+ logger.debug(s"Failed to $newValue switch to dataType:", t)
+ newValue
+ }
+ }
+
+ def isLinkisNull(value: String): Boolean = {
+ if (value == null || value == Dolphin.LINKIS_NULL) true else false
}
def isNull(value: String): Boolean =
- if (value == null || value == NULL_VALUE || value.trim == "") true else false
+ if (value == null || value == Dolphin.NULL || value.trim == "") true else false
def isNumberNull(value: String): Boolean =
- if (null == value || NULL_VALUE.equalsIgnoreCase(value) || value.trim == "") {
+ if (null == value || Dolphin.NULL.equalsIgnoreCase(value) || value.trim == "") {
true
} else {
false
}
def valueToString(value: Any): String = {
- if (null == value) return LOWCASE_NULL_VALUE
+ if (null == value) return null
value match {
case javaDecimal: JavaBigDecimal =>
javaDecimal.toPlainString
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/Dolphin.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/Dolphin.scala
index 378c2c2ecb..8e7e7d6131 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/Dolphin.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/domain/Dolphin.scala
@@ -39,7 +39,10 @@ object Dolphin extends Logging {
val COL_SPLIT_LEN = COL_SPLIT_BYTES.length
val NULL = "NULL"
- val NULL_BYTES = "NULL".getBytes("utf-8")
+ val NULL_BYTES = NULL.getBytes("utf-8")
+
+ val LINKIS_NULL = "LINKIS_NULL"
+ val LINKIS_NULL_BYTES = LINKIS_NULL.getBytes("utf-8")
val INT_LEN = 10
@@ -59,6 +62,14 @@ object Dolphin extends Logging {
def getString(bytes: Array[Byte], start: Int, len: Int): String =
new String(bytes, start, len, Dolphin.CHAR_SET)
+ def toStringValue(value: String): String = {
+ if (LINKIS_NULL.equals(value)) {
+ NULL
+ } else {
+ value
+ }
+ }
+
/**
* Read an integer value that converts the array to a byte of length 10 bytes
* 读取整数值,该值为将数组转换为10字节长度的byte
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/DefaultResultSetFactory.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/DefaultResultSetFactory.scala
index 38973ae1ab..d4836731db 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/DefaultResultSetFactory.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/DefaultResultSetFactory.scala
@@ -108,7 +108,7 @@ class DefaultResultSetFactory extends ResultSetFactory with Logging {
if (StringUtils.isEmpty(resultSetType)) {
throw new StorageWarnException(
THE_FILE_IS_EMPTY.getErrorCode,
- s"The file (${fsPath.getPath}) is empty(文件(${fsPath.getPath}) 为空)"
+ MessageFormat.format(THE_FILE_IS_EMPTY.getErrorDesc, fsPath.getPath)
)
}
Utils.tryQuietly(inputStream.close())
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/ResultSetReader.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/ResultSetReader.scala
index 663e379b5b..e61cf36b3d 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/ResultSetReader.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/ResultSetReader.scala
@@ -19,6 +19,7 @@ package org.apache.linkis.storage.resultset
import org.apache.linkis.common.io.{FsPath, MetaData, Record}
import org.apache.linkis.common.io.resultset.{ResultSet, ResultSetReader}
+import org.apache.linkis.common.utils.Logging
import org.apache.linkis.storage.FSFactory
import org.apache.linkis.storage.errorcode.LinkisStorageErrorCodeSummary.TABLE_ARE_NOT_SUPPORTED
import org.apache.linkis.storage.exception.StorageErrorException
@@ -26,7 +27,7 @@ import org.apache.linkis.storage.resultset.table.{TableMetaData, TableRecord, Ta
import java.io.InputStream
-object ResultSetReader {
+object ResultSetReader extends Logging {
def getResultSetReader[K <: MetaData, V <: Record](
resultSet: ResultSet[K, V],
@@ -83,6 +84,7 @@ object ResultSetReader {
)
}
val fs = FSFactory.getFs(resPath)
+ logger.info("Try to init Fs with path:" + resPath.getPath)
fs.init(null)
ResultSetReader.getResultSetReader(resultSet.asInstanceOf[TableResultSet], fs.read(resPath))
}
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSet.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSet.scala
index fc303fbb5c..7b3aca62d9 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSet.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSet.scala
@@ -34,6 +34,7 @@ abstract class StorageResultSet[K <: MetaData, V <: Record] extends ResultSet[K,
} else {
parentDir.toPath + "/" + fileName + Dolphin.DOLPHIN_FILE_SUFFIX
}
+ logger.info(s"Get result set path:${path}")
new FsPath(path)
}
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetReader.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetReader.scala
index 3f49faf3ed..80db410746 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetReader.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetReader.scala
@@ -21,7 +21,11 @@ import org.apache.linkis.common.io.{Fs, MetaData, Record}
import org.apache.linkis.common.io.resultset.{ResultSet, ResultSetReader}
import org.apache.linkis.common.utils.{Logging, Utils}
import org.apache.linkis.storage.domain.Dolphin
-import org.apache.linkis.storage.exception.StorageWarnException
+import org.apache.linkis.storage.exception.{
+ StorageErrorCode,
+ StorageErrorException,
+ StorageWarnException
+}
import org.apache.linkis.storage.utils.StorageUtils
import java.io.{ByteArrayInputStream, InputStream, IOException}
@@ -43,7 +47,6 @@ class StorageResultSetReader[K <: MetaData, V <: Record](
private var fs: Fs = _
private val READ_CACHE = 1024
- private val bytes = new Array[Byte](READ_CACHE)
def this(resultSet: ResultSet[K, V], value: String) = {
this(resultSet, new ByteArrayInputStream(value.getBytes(Dolphin.CHAR_SET)))
@@ -74,24 +77,27 @@ class StorageResultSetReader[K <: MetaData, V <: Record](
case t: Throwable => throw t
}
- val rowBuffer = ArrayBuffer[Byte]()
- var len = 0
-
- // Read the entire line, except for the data of the line length(读取整行,除了行长的数据)
- while (rowLen > 0 && len >= 0) {
- if (rowLen > READ_CACHE) {
- len = StorageUtils.readBytes(inputStream, bytes, READ_CACHE)
- } else {
- len = StorageUtils.readBytes(inputStream, bytes, rowLen)
- }
-
- if (len > 0) {
- rowLen -= len
- rowBuffer ++= bytes.slice(0, len)
- }
+ var bytes: Array[Byte] = null
+ try {
+ bytes = new Array[Byte](rowLen)
+ } catch {
+ case e: OutOfMemoryError =>
+ logger.error("Result set read oom, read size {} Byte", rowLen)
+ throw new StorageErrorException(
+ StorageErrorCode.FS_OOM.getCode,
+ StorageErrorCode.FS_OOM.getMessage,
+ e
+ )
+ }
+ val len = StorageUtils.readBytes(inputStream, bytes, rowLen)
+ if (len != rowLen) {
+ throw new StorageErrorException(
+ StorageErrorCode.INCONSISTENT_DATA.getCode,
+ String.format(StorageErrorCode.INCONSISTENT_DATA.getMessage, len.toString, rowLen.toString)
+ )
}
rowCount = rowCount + 1
- rowBuffer.toArray
+ bytes
}
@scala.throws[IOException]
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetWriter.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetWriter.scala
index 9c7947272c..17106dca67 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetWriter.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/StorageResultSetWriter.scala
@@ -86,6 +86,7 @@ class StorageResultSetWriter[K <: MetaData, V <: Record](
WRITER_LOCK_CREATE.synchronized {
if (!fileCreated) {
if (storePath != null && outputStream == null) {
+ logger.info(s"Try to create a new file:${storePath}, with proxy user:${proxyUser}")
fs = FSFactory.getFsByProxyUser(storePath, proxyUser)
fs.init(null)
FileSystemUtils.createNewFile(storePath, proxyUser, true)
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableRecord.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableRecord.scala
index d8e0560964..64d2b18b9c 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableRecord.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableRecord.scala
@@ -27,10 +27,4 @@ class TableRecord(val row: Array[Any]) extends ResultRecord {
new TableRecord(row)
}
- def tableRecordToString(nullValue: String = "NULL"): Array[String] = {
- row.map { col =>
- StorageUtils.colToString(col, nullValue)
- }
- }
-
}
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultDeserializer.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultDeserializer.scala
index 40c4e031f7..32ea4f5e22 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultDeserializer.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultDeserializer.scala
@@ -47,13 +47,13 @@ class TableResultDeserializer extends ResultDeserializer[TableMetaData, TableRec
val columns = new ArrayBuffer[Column]()
for (i <- 0 until (colArray.length, 3)) {
var len = colArray(i).toInt
- val colName = Dolphin.getString(bytes, index, len)
+ val colName = Dolphin.toStringValue(Dolphin.getString(bytes, index, len))
index += len
len = colArray(i + 1).toInt
- val colType = Dolphin.getString(bytes, index, len)
+ val colType = Dolphin.toStringValue(Dolphin.getString(bytes, index, len))
index += len
len = colArray(i + 2).toInt
- val colComment = Dolphin.getString(bytes, index, len)
+ val colComment = Dolphin.toStringValue(Dolphin.getString(bytes, index, len))
index += len
columns += Column(colName, colType, colComment)
}
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultSerializer.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultSerializer.scala
index 94b6cb4c03..5d1738a346 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultSerializer.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/resultset/table/TableResultSerializer.scala
@@ -19,6 +19,7 @@ package org.apache.linkis.storage.resultset.table
import org.apache.linkis.common.io.{MetaData, Record}
import org.apache.linkis.common.io.resultset.ResultSerializer
+import org.apache.linkis.storage.conf.LinkisStorageConf
import org.apache.linkis.storage.domain.Dolphin
import scala.collection.mutable.ArrayBuffer
@@ -45,14 +46,20 @@ class TableResultSerializer extends ResultSerializer {
* @param line
*/
def lineToBytes(line: Array[Any]): Array[Byte] = {
- // Data cache(数据缓存)
val dataBytes = ArrayBuffer[Array[Byte]]()
- // Column cache(列缓存)
val colIndex = ArrayBuffer[Array[Byte]]()
var colByteLen = 0
var length = 0
line.foreach { data =>
- val bytes = if (data == null) Dolphin.NULL_BYTES else Dolphin.getBytes(data)
+ val bytes = if (data == null) {
+ if (!LinkisStorageConf.LINKIS_RESULT_ENABLE_NULL) {
+ Dolphin.LINKIS_NULL_BYTES
+ } else {
+ Dolphin.NULL_BYTES
+ }
+ } else {
+ Dolphin.getBytes(data)
+ }
dataBytes += bytes
val colBytes = Dolphin.getBytes(bytes.length)
colIndex += colBytes += Dolphin.COL_SPLIT_BYTES
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/FileSource.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/FileSource.scala
index 7a9fa4f04c..b6830a13b4 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/FileSource.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/FileSource.scala
@@ -18,6 +18,7 @@
package org.apache.linkis.storage.source
import org.apache.linkis.common.io._
+import org.apache.linkis.common.utils.Logging
import org.apache.linkis.storage.conf.LinkisStorageConf
import org.apache.linkis.storage.errorcode.LinkisStorageErrorCodeSummary.UNSUPPORTED_OPEN_FILE_TYPE
import org.apache.linkis.storage.exception.StorageErrorException
@@ -55,7 +56,7 @@ trait FileSource extends Closeable {
def getFileSplits: Array[FileSplit]
}
-object FileSource {
+object FileSource extends Logging {
private val fileType = LinkisStorageConf.getFileTypeArr
private val suffixPredicate = (path: String, suffix: String) => path.endsWith(s".$suffix")
@@ -124,6 +125,7 @@ object FileSource {
}
private def createResultSetFileSplit(fsPath: FsPath, fs: Fs): FileSplit = {
+ logger.info(s"try create result set file split with path:${fsPath.getPath}")
val resultset = ResultSetFactory.getInstance.getResultSetByPath(fsPath, fs)
val resultsetReader = ResultSetReader.getResultSetReader(resultset, fs.read(fsPath))
new FileSplit(resultsetReader, resultset.resultSetType())
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/ResultsetFileSource.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/ResultsetFileSource.scala
index 7b387e9f19..adbb596aa2 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/ResultsetFileSource.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/source/ResultsetFileSource.scala
@@ -17,6 +17,7 @@
package org.apache.linkis.storage.source
+import org.apache.linkis.storage.domain.Dolphin
import org.apache.linkis.storage.resultset.table.TableRecord
import org.apache.linkis.storage.utils.StorageUtils
@@ -24,11 +25,27 @@ class ResultsetFileSource(fileSplits: Array[FileSplit]) extends AbstractFileSour
shuffle({
case t: TableRecord =>
- new TableRecord(t.row.map {
- case null | "NULL" => getParams.getOrDefault("nullValue", "NULL")
- case "" => getParams.getOrDefault("nullValue", "")
- case value: Double => StorageUtils.doubleToString(value)
- case r => r
+ new TableRecord(t.row.map { rvalue =>
+ {
+ rvalue match {
+ case null | "NULL" =>
+ val nullValue = getParams.getOrDefault("nullValue", "NULL")
+ if (nullValue.equals(Dolphin.LINKIS_NULL)) {
+ rvalue
+ } else {
+ nullValue
+ }
+ case "" =>
+ val nullValue = getParams.getOrDefault("nullValue", "")
+ if (nullValue.equals(Dolphin.LINKIS_NULL)) {
+ ""
+ } else {
+ nullValue
+ }
+ case value: Double => StorageUtils.doubleToString(value)
+ case _ => rvalue
+ }
+ }
})
case record => record
})
diff --git a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/utils/StorageUtils.scala b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/utils/StorageUtils.scala
index 90eb319fa0..7a5b134749 100644
--- a/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/utils/StorageUtils.scala
+++ b/linkis-commons/linkis-storage/src/main/scala/org/apache/linkis/storage/utils/StorageUtils.scala
@@ -46,7 +46,11 @@ object StorageUtils extends Logging {
nf.setMaximumFractionDigits(StorageConfiguration.DOUBLE_FRACTION_LEN.getValue)
def doubleToString(value: Double): String = {
- nf.format(value)
+ if (value.isNaN) {
+ "NaN"
+ } else {
+ nf.format(value)
+ }
}
def loadClass[T](classStr: String, op: T => String): Map[String, T] = {
@@ -211,17 +215,6 @@ object StorageUtils extends Logging {
readLen
}
- def colToString(col: Any, nullValue: String = "NULL"): String = {
- if (null == col) nullValue
- else {
- col match {
- case value: Double => doubleToString(value)
- case "NULL" | "" => nullValue
- case _ => col.toString
- }
- }
- }
-
def isIOProxy(): Boolean = {
StorageConfiguration.ENABLE_IO_PROXY.getValue
}
diff --git a/linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/domain/DataTypeTest.scala b/linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/domain/DataTypeTest.scala
index 3bfc35b17c..5537794840 100644
--- a/linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/domain/DataTypeTest.scala
+++ b/linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/domain/DataTypeTest.scala
@@ -25,7 +25,7 @@ class DataTypeTest {
@DisplayName("constTest")
def constTest(): Unit = {
- val nullvalue = DataType.NULL_VALUE
+ val nullvalue = Dolphin.NULL
val lowcasenullvalue = DataType.LOWCASE_NULL_VALUE
Assertions.assertEquals("NULL", nullvalue)
@@ -60,4 +60,12 @@ class DataTypeTest {
}
+ @Test
+ @DisplayName("toValueTest")
+ def toValueTest(): Unit = {
+ val dateType = DataType.toDataType("double")
+ val str = DataType.toValue(dateType, "NaN")
+ Assertions.assertNotNull(str)
+ }
+
}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-common/src/main/java/org/apache/linkis/cli/common/entity/job/JobData.java b/linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/utils/StorageUtilsTest.scala
similarity index 72%
rename from linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-common/src/main/java/org/apache/linkis/cli/common/entity/job/JobData.java
rename to linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/utils/StorageUtilsTest.scala
index 10d55e6541..6ae15782ee 100644
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-common/src/main/java/org/apache/linkis/cli/common/entity/job/JobData.java
+++ b/linkis-commons/linkis-storage/src/test/scala/org/apache/linkis/storage/utils/StorageUtilsTest.scala
@@ -15,20 +15,18 @@
* limitations under the License.
*/
-package org.apache.linkis.cli.common.entity.job;
+package org.apache.linkis.storage.utils
-public interface JobData {
- JobStatus getJobStatus();
+import org.junit.jupiter.api.{Assertions, DisplayName, Test}
- String getJobID();
+class StorageUtilsTest {
- String getUser();
+ @Test
+ @DisplayName("doubleToStringTest")
+ def doubleToStringTest(): Unit = {
+ val str = StorageUtils.doubleToString(Double.NaN)
+ Assertions.assertEquals("NaN", str)
- String getMessage();
+ }
- void setMessage(String message);
-
- Exception getException();
-
- void setException(Exception e);
}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/pom.xml b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/pom.xml
deleted file mode 100644
index 980141f9a3..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/pom.xml
+++ /dev/null
@@ -1,87 +0,0 @@
-
-
-
- 4.0.0
-
-
- org.apache.linkis
- linkis-cli
- ${revision}
-
- linkis-cli-application
- jar
-
-
-
- org.apache.linkis
- linkis-cli-common
- ${project.version}
-
-
- org.apache.linkis
- linkis-cli-core
- ${project.version}
-
-
- org.apache.linkis
- linkis-computation-client
- ${project.version}
-
-
- org.apache.linkis
- linkis-gateway-httpclient-support
- ${project.version}
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
- false
-
- false
- out
- false
- false
-
- /src/main/assembly/distribution.xml
-
-
-
-
- make-assembly
-
- single
-
- package
-
-
- /src/main/assembly/distribution.xml
-
-
-
-
-
-
-
-
-
-
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/LinkisClientApplication.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/LinkisClientApplication.java
deleted file mode 100644
index 0c6fc1ec73..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/LinkisClientApplication.java
+++ /dev/null
@@ -1,341 +0,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.apache.linkis.cli.application;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.data.FinishedData;
-import org.apache.linkis.cli.application.data.PreparedData;
-import org.apache.linkis.cli.application.data.ProcessedData;
-import org.apache.linkis.cli.application.interactor.command.LinkisCmdType;
-import org.apache.linkis.cli.application.interactor.command.template.UniversalCmdTemplate;
-import org.apache.linkis.cli.application.operator.ujes.LinkisOperatorBuilder;
-import org.apache.linkis.cli.application.suite.ExecutionSuite;
-import org.apache.linkis.cli.application.suite.ExecutionSuiteFactory;
-import org.apache.linkis.cli.application.utils.Utils;
-import org.apache.linkis.cli.common.entity.command.CmdTemplate;
-import org.apache.linkis.cli.common.entity.command.Params;
-import org.apache.linkis.cli.common.entity.execution.Execution;
-import org.apache.linkis.cli.common.entity.job.Job;
-import org.apache.linkis.cli.common.entity.properties.ClientProperties;
-import org.apache.linkis.cli.common.entity.result.ExecutionResult;
-import org.apache.linkis.cli.common.entity.result.ResultHandler;
-import org.apache.linkis.cli.common.entity.var.VarAccess;
-import org.apache.linkis.cli.common.exception.LinkisClientRuntimeException;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.common.exception.handler.ExceptionHandler;
-import org.apache.linkis.cli.core.constants.CommonConstants;
-import org.apache.linkis.cli.core.exception.CommandException;
-import org.apache.linkis.cli.core.exception.PropsException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.exception.handler.CommandExceptionHandler;
-import org.apache.linkis.cli.core.exception.handler.DefaultExceptionHandler;
-import org.apache.linkis.cli.core.interactor.command.CmdTemplateFactory;
-import org.apache.linkis.cli.core.interactor.command.fitter.SingleTplFitter;
-import org.apache.linkis.cli.core.interactor.command.parser.Parser;
-import org.apache.linkis.cli.core.interactor.command.parser.SingleCmdParser;
-import org.apache.linkis.cli.core.interactor.command.parser.result.ParseResult;
-import org.apache.linkis.cli.core.interactor.properties.PropertiesLoader;
-import org.apache.linkis.cli.core.interactor.properties.PropsFilesScanner;
-import org.apache.linkis.cli.core.interactor.properties.StdPropsLoader;
-import org.apache.linkis.cli.core.interactor.properties.reader.PropertiesReader;
-import org.apache.linkis.cli.core.interactor.properties.reader.PropsFileReader;
-import org.apache.linkis.cli.core.interactor.properties.reader.SysEnvReader;
-import org.apache.linkis.cli.core.interactor.properties.reader.SysPropsReader;
-import org.apache.linkis.cli.core.interactor.result.DefaultResultHandler;
-import org.apache.linkis.cli.core.interactor.result.ExecutionResultImpl;
-import org.apache.linkis.cli.core.interactor.result.ExecutionStatusEnum;
-import org.apache.linkis.cli.core.interactor.validate.ParsedTplValidator;
-import org.apache.linkis.cli.core.interactor.var.StdVarAccess;
-import org.apache.linkis.cli.core.interactor.var.SysVarAccess;
-import org.apache.linkis.cli.core.operator.JobOperatorBuilder;
-import org.apache.linkis.cli.core.operator.JobOperatorFactory;
-import org.apache.linkis.cli.core.present.PresentModeImpl;
-import org.apache.linkis.cli.core.present.display.DisplayOperFactory;
-import org.apache.linkis.cli.core.present.display.PlainTextFileWriter;
-import org.apache.linkis.cli.core.present.display.StdOutWriter;
-import org.apache.linkis.cli.core.utils.LogUtils;
-import org.apache.linkis.cli.core.utils.SchedulerUtils;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisClientApplication {
- private static Logger logger = LoggerFactory.getLogger(LinkisClientApplication.class);
-
- /**
- * generate Templates load env variables TODO: load version info
- *
- * @return PreparedData
- */
- private static PreparedData prepare() throws LinkisClientRuntimeException {
- /*
- generate template
- */
- CmdTemplate template = new UniversalCmdTemplate();
- CmdTemplateFactory.register(template);
- /*
- load env variables
- */
- Map propertiesMap = new HashMap<>();
- PropertiesLoader loader =
- new StdPropsLoader()
- .addPropertiesReader(new SysPropsReader())
- .addPropertiesReader(new SysEnvReader());
- for (ClientProperties properties : loader.loadProperties()) {
- propertiesMap.put(properties.getPropsId(), properties);
- }
-
- return new PreparedData(propertiesMap);
- }
-
- /**
- * parse user input load user config load default config check if all inputs are ok
- *
- * @param args user input arguments
- * @return ProcessedData
- */
- private static ProcessedData processInput(String[] args, PreparedData preparedData)
- throws Exception {
-
- if (preparedData == null) {
- return null;
- }
-
- /*
- user input
- */
- CmdTemplate template = CmdTemplateFactory.getTemplateCopy(LinkisCmdType.UNIVERSAL);
- Parser parser =
- new SingleCmdParser()
- .setMapper(null)
- .setTemplate(template)
- .setFitter(new SingleTplFitter());
-
- ParseResult result = parser.parse(args);
-
- ParsedTplValidator parsedTplValidator = new ParsedTplValidator();
- parsedTplValidator.doValidation(result.getParsedTemplate());
-
- Params params = result.getParams();
- logger.debug("==========params============\n" + Utils.GSON.toJson(params));
-
- /*
- VarAccess for sys_prop, sys_env
- */
- Map propertiesMap = preparedData.getPropertiesMap();
- VarAccess sysVarAccess =
- new SysVarAccess()
- .setSysProp(propertiesMap.get(CommonConstants.SYSTEM_PROPERTIES_IDENTIFIER))
- .setSysEnv(propertiesMap.get(CommonConstants.SYSTEM_ENV_IDENTIFIER));
- logger.debug("==========sys_var============\n" + Utils.GSON.toJson(sysVarAccess));
-
- LogUtils.getInformationLogger()
- .info(
- "LogFile path: "
- + sysVarAccess.getVar(String.class, AppKeys.LOG_PATH_KEY)
- + "/"
- + sysVarAccess.getVar(String.class, AppKeys.LOG_FILE_KEY));
- /*
- default config, -Dconf.root & -Dconf.file specifies config path
- */
- // scan config files given root path
- String configPath = sysVarAccess.getVar(String.class, AppKeys.CLIENT_CONFIG_ROOT_KEY);
- String defaultConfFileName =
- sysVarAccess.getVarOrDefault(
- String.class, AppKeys.DEFAULT_CONFIG_FILE_NAME_KEY, AppConstants.DEFAULT_CONFIG_NAME);
- if (StringUtils.isBlank(configPath)) {
- throw new PropsException(
- "PRP0007",
- ErrorLevel.ERROR,
- CommonErrMsg.PropsLoaderErr,
- "configuration root path specified by env variable: "
- + AppKeys.CLIENT_CONFIG_ROOT_KEY
- + " is empty.");
- }
-
- List readersList =
- new PropsFilesScanner().getPropsReaders(configPath); // +1 user config
- /*
- user defined config
- */
- String userConfPath = null;
- if (params.containsParam(AppKeys.LINKIS_CLIENT_USER_CONFIG)) {
- userConfPath =
- (String) params.getParamItemMap().get(AppKeys.LINKIS_CLIENT_USER_CONFIG).getValue();
- }
- if (StringUtils.isNotBlank(userConfPath)) {
- PropertiesReader reader =
- new PropsFileReader()
- .setPropsId(AppKeys.LINKIS_CLIENT_USER_CONFIG)
- .setPropsPath(userConfPath);
- readersList.add(reader);
- } else {
- LogUtils.getInformationLogger()
- .info("User does not provide usr-configuration file. Will use default config");
- }
- /*
- load properties
- */
- PropertiesLoader loader =
- new StdPropsLoader()
- .addPropertiesReaders(readersList.toArray(new PropertiesReader[readersList.size()]));
- ClientProperties[] loaderResult = loader.loadProperties();
- for (ClientProperties properties : loaderResult) {
- if (StringUtils.equals(properties.getPropsId(), AppKeys.LINKIS_CLIENT_USER_CONFIG)) {
- for (Map.Entry prop : properties.entrySet()) {
- if (StringUtils.startsWith(
- (String) prop.getKey(), AppKeys.LINKIS_CLIENT_NONCUSTOMIZABLE)) {
- throw new PropsException(
- "PRP0007",
- ErrorLevel.ERROR,
- CommonErrMsg.PropsLoaderErr,
- "User cannot specify non-customizable configuration: " + prop.getKey());
- }
- }
- }
- propertiesMap.put(properties.getPropsId(), properties);
- }
-
- /*
- VarAccess for cmd, config
- */
- VarAccess stdVarAccess =
- new StdVarAccess()
- .setCmdParams(params)
- .setUserConf(propertiesMap.get(AppKeys.LINKIS_CLIENT_USER_CONFIG))
- .setDefaultConf(propertiesMap.get(defaultConfFileName))
- .init();
- logger.info("==========std_var============\n" + Utils.GSON.toJson(stdVarAccess));
-
- /*
- Prepare operator for accessing linkis
- */
- JobOperatorBuilder builder =
- new LinkisOperatorBuilder().setStdVarAccess(stdVarAccess).setSysVarAccess(sysVarAccess);
-
- JobOperatorFactory.register(AppKeys.REUSABLE_UJES_CLIENT, builder);
- /*
- Prepare DisplayOperator
- */
- DisplayOperFactory.register(PresentModeImpl.STDOUT, new StdOutWriter());
- DisplayOperFactory.register(PresentModeImpl.TEXT_FILE, new PlainTextFileWriter());
-
- return new ProcessedData(
- AppConstants.DUMMY_CID, params.getCmdType(), stdVarAccess, sysVarAccess);
- }
-
- /**
- * submit job display result
- *
- * @return FinishedData
- */
- private static FinishedData exec(ProcessedData data) throws Exception {
- if (data == null) {
- return null;
- }
-
- ExecutionSuite suite =
- ExecutionSuiteFactory.getSuite(
- data.getCmdType(), data.getStdVarAccess(), data.getSysVarAccess());
-
- /*
- Get everything
- */
- Map jobs = suite.getJobs();
- ResultHandler[] resultHandlers = suite.getResultHandlers();
- Execution execution = suite.getExecution();
-
- /*
- execute
- */
- final Map jobsToKill = jobs;
- Thread hook = new Thread(() -> execution.terminate(jobsToKill));
- if (jobsToKill != null && jobsToKill.size() != 0) {
- Runtime.getRuntime().addShutdownHook(hook);
- }
- ExecutionResult result = execution.execute(jobs);
-
- Runtime.getRuntime().removeShutdownHook(hook);
-
- return new FinishedData(result, resultHandlers);
- }
-
- public static void main(String[] args) {
-
- ExceptionHandler handler = new DefaultExceptionHandler();
- ProcessedData processedData = null;
- FinishedData finishedData = null;
- ExecutionResult executionResult = new ExecutionResultImpl(null, ExecutionStatusEnum.UNDEFINED);
- PreparedData preparedData = null;
-
- try {
- preparedData = prepare();
- } catch (Exception e) {
- handler.handle(e);
- executionResult.setExecutionStatus(ExecutionStatusEnum.FAILED);
- }
-
- try {
- processedData = processInput(args, preparedData);
- } catch (CommandException ce) {
- new CommandExceptionHandler().handle(ce);
- executionResult.setExecutionStatus(ExecutionStatusEnum.FAILED);
- } catch (Exception e) {
- handler.handle(e);
- executionResult.setExecutionStatus(ExecutionStatusEnum.FAILED);
- }
-
- try {
- finishedData = exec(processedData);
- } catch (Exception e) {
- handler.handle(e);
- executionResult.setExecutionStatus(ExecutionStatusEnum.FAILED);
- }
-
- if (finishedData != null) {
- executionResult = finishedData.getExecutionResult();
- if (executionResult == null) {
- executionResult = new ExecutionResultImpl(null, ExecutionStatusEnum.UNDEFINED);
- }
- if (executionResult.getException() != null) {
- handler.handle(executionResult.getException());
- new DefaultResultHandler().process(executionResult);
- } else {
- if (finishedData.getResultHandlers() != null) {
- for (ResultHandler resultHandler : finishedData.getResultHandlers()) {
- if (resultHandler != null) {
- resultHandler.process(executionResult);
- }
- }
- }
- }
- } else {
- executionResult.setExecutionStatus(ExecutionStatusEnum.FAILED);
- new DefaultResultHandler().process(executionResult);
- }
-
- SchedulerUtils.shutDown();
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/data/FinishedData.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/data/FinishedData.java
deleted file mode 100644
index 4438cf301b..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/data/FinishedData.java
+++ /dev/null
@@ -1,47 +0,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.apache.linkis.cli.application.data;
-
-import org.apache.linkis.cli.common.entity.result.ExecutionResult;
-import org.apache.linkis.cli.common.entity.result.ResultHandler;
-
-public class FinishedData {
- ExecutionResult executionResult;
- ResultHandler[] resultHandlers;
-
- public FinishedData(ExecutionResult executionResult, ResultHandler[] resultHandlers) {
- this.executionResult = executionResult;
- this.resultHandlers = resultHandlers;
- }
-
- public ExecutionResult getExecutionResult() {
- return executionResult;
- }
-
- public void setExecutionResult(ExecutionResult executionResult) {
- this.executionResult = executionResult;
- }
-
- public ResultHandler[] getResultHandlers() {
- return resultHandlers;
- }
-
- public void setResultHandlers(ResultHandler[] resultHandlers) {
- this.resultHandlers = resultHandlers;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/data/ProcessedData.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/data/ProcessedData.java
deleted file mode 100644
index a69b7c4b63..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/data/ProcessedData.java
+++ /dev/null
@@ -1,52 +0,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.apache.linkis.cli.application.data;
-
-import org.apache.linkis.cli.common.entity.command.CmdType;
-import org.apache.linkis.cli.common.entity.var.VarAccess;
-
-public class ProcessedData {
- String cid;
- CmdType cmdType;
- VarAccess stdVarAccess;
- VarAccess sysVarAccess;
-
- public ProcessedData(
- String cid, CmdType cmdType, VarAccess stdVarAccess, VarAccess sysVarAccess) {
- this.cid = cid;
- this.cmdType = cmdType;
- this.stdVarAccess = stdVarAccess;
- this.sysVarAccess = sysVarAccess;
- }
-
- public String getCid() {
- return cid;
- }
-
- public CmdType getCmdType() {
- return cmdType;
- }
-
- public VarAccess getStdVarAccess() {
- return stdVarAccess;
- }
-
- public VarAccess getSysVarAccess() {
- return sysVarAccess;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisManageJob.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisManageJob.java
deleted file mode 100644
index 7dbcaca88d..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisManageJob.java
+++ /dev/null
@@ -1,522 +0,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.apache.linkis.cli.application.interactor.job;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisLogData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisResultData;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisJobManDesc;
-import org.apache.linkis.cli.application.interactor.job.subtype.LinkisManSubType;
-import org.apache.linkis.cli.application.operator.ujes.LinkisJobOperator;
-import org.apache.linkis.cli.application.utils.Utils;
-import org.apache.linkis.cli.common.entity.job.JobData;
-import org.apache.linkis.cli.common.entity.operator.JobOperator;
-import org.apache.linkis.cli.common.exception.LinkisClientRuntimeException;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.constants.CommonConstants;
-import org.apache.linkis.cli.core.exception.LinkisClientExecutionException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.interactor.job.*;
-import org.apache.linkis.cli.core.utils.CommonUtils;
-import org.apache.linkis.cli.core.utils.LogUtils;
-import org.apache.linkis.cli.core.utils.SchedulerUtils;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.text.MessageFormat;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisManageJob extends LinkisJob
- implements ManagableBackendJob, TerminatableJob, LogAccessibleJob, ResultAccessibleJob {
- private static final Logger logger = LoggerFactory.getLogger(LinkisManageJob.class);
-
- private LinkisJobManDesc jobDesc;
- private LinkisJobData data;
- private TerminateToken terminateToken = new TerminateToken();
-
- @Override
- public LinkisJobOperator getJobOperator() {
- if (!(super.getJobOperator() instanceof LinkisJobOperator)) {
- throw new LinkisClientExecutionException(
- "EXE0003",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionInitErr,
- "JobOperator of LinkisManageJob should be instance of LinkisJobOperator");
- }
- return (LinkisJobOperator) super.getJobOperator();
- }
-
- @Override
- public void setOperator(JobOperator operator) {
- if (!(operator instanceof LinkisJobOperator)) {
- throw new LinkisClientExecutionException(
- "EXE0003",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionInitErr,
- "JobOperator of LinkisManageJob should be instance of LinkisJobOperator");
- }
- super.setOperator(operator);
- }
-
- @Override
- public LinkisJobManDesc getJobDesc() {
- return jobDesc;
- }
-
- public void setJobDesc(LinkisJobManDesc jobDesc) {
- this.jobDesc = jobDesc;
- }
-
- @Override
- public LinkisJobData getJobData() {
- return data;
- }
-
- public void setJobData(LinkisJobData data) {
- this.data = data;
- }
-
- @Override
- public boolean isSuccess() {
- return data.isSuccess();
- }
-
- @Override
- public void doManage() throws LinkisClientRuntimeException {
- LinkisManSubType subType = (LinkisManSubType) getSubType();
- if (!(subType instanceof LinkisManSubType)) {
- throw new LinkisClientExecutionException(
- "EXE0030",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "JobSubType is not instance of JobManSubType");
- }
- switch (subType) {
- case STATUS:
- try {
- data.updateByOperResult(
- getJobOperator().queryJobInfo(jobDesc.getUser(), jobDesc.getJobID()));
- if (data.getJobStatus() != null) {
- data.setSuccess(true);
- }
- } catch (Exception e) {
- data.setSuccess(false);
- data.setException(e);
- }
- break;
- // case JOB_DESC:
- // result = jobManagableBackendExecutor.queryJobDesc(job);
- // break;
- case LOG:
- try {
- ((LinkisLogData) data).setIncLogMode(false);
- startRetrieveLog();
- waitLogFin();
- data.setSuccess(true);
- } catch (Exception e) {
- data.setSuccess(false);
- data.setException(e);
- }
- break;
- case RESULT:
- try {
- startRetrieveResult();
- data.setSuccess(true);
- } catch (LinkisClientExecutionException e) {
- if (e.getCode().equals("EXE0037")) {
- ((LinkisResultData) data).sendResultFin(); // inform listener to stop
- data.setSuccess(true);
- } else {
- data.setSuccess(false);
- data.setException(e);
- }
- LogUtils.getInformationLogger().warn(e.getMessage());
- } catch (Exception e) {
- data.setSuccess(false);
- data.setException(e);
- LogUtils.getInformationLogger().warn(e.getMessage());
- }
- break;
- // case LIST:
- // resultData = jobManExecutor.queryJobList(job);
- // break;
- case KILL:
- doKill();
- break;
- default:
- throw new LinkisClientExecutionException(
- "EXE0002",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "JobSubType + \"" + subType + "\" is not supported");
- }
- }
-
- @Override
- public void startRetrieveLog() {
- if (jobDesc.getUser() == null || jobDesc.getJobID() == null) {
- throw new LinkisClientExecutionException(
- "EXE0036", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "user or jobID is null");
- }
- data.updateByOperResult(getJobOperator().queryJobInfo(jobDesc.getUser(), jobDesc.getJobID()));
- startRetrieveLogInternal(data);
- }
-
- public void waitLogFin() {
- if (!(data instanceof LinkisLogData)) {
- return;
- }
- int retry = 0;
- int MAX_RETRY = 300; // wait for 10 minutes after job finish
- while (retry++ < MAX_RETRY) {
- if (((LinkisLogData) data).logFinReceived()) {
- return;
- }
- CommonUtils.doSleepQuietly(CommonConstants.JOB_QUERY_SLEEP_MILLS);
- }
- }
-
- public void startRetrieveLogInternal(JobData jobData) {
- if (!(jobData instanceof LinkisLogData)) {
- throw new LinkisClientExecutionException(
- "EXE0034", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "JobData is not LinkisLogData");
- }
- if (jobData.getUser() == null || jobData.getJobID() == null) {
- throw new LinkisClientExecutionException(
- "EXE0036", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "user or jobID is null");
- }
- LinkisLogData logData = (LinkisLogData) jobData;
- if (logData.getJobStatus() != null) {
- try {
- Thread logConsumer = new Thread(() -> logData.notifyLogListener(), "Log-Consumer");
- Thread logRetriever = new Thread(() -> queryLogLoop(logData), "Log-Retriever");
- SchedulerUtils.getCachedThreadPoolExecutor().execute(logRetriever);
- SchedulerUtils.getCachedThreadPoolExecutor().execute(logConsumer);
- } catch (Exception e) {
- logger.warn("Failed to retrieve log", e);
- }
- }
- }
-
- public void queryLogLoop(LinkisLogData data) {
- int curLogIdx;
- int nextLogIdx;
- boolean hasNext = true;
- int retryCnt = 0;
- final int MAX_RETRY = 12; // continues fails for 90s, then exit thread
- try {
- while (hasNext) {
- curLogIdx = data.getNextLogLineIdx() == null ? 0 : data.getNextLogLineIdx();
- try {
- data.updateByOperResult(getJobOperator().queryJobInfo(data.getUser(), data.getJobID()));
- queryJobLogFromLine(data, curLogIdx);
- } catch (Exception e) {
- logger.error("Cannot get inc-log:", e);
- // and yes sometimes server may not be able to prepare persisted-log
- retryCnt++;
- if (retryCnt >= MAX_RETRY) {
- logger.error(
- "Continuously failing to query inc-log for "
- + MAX_RETRY * (MAX_RETRY + 2) * 500 / 1000
- + "s. Will no longer try to query log",
- e);
- break;
- }
- Utils.doSleepQuietly(500l + 500l * retryCnt); // maybe server problem. sleep longer
- continue;
- }
- retryCnt = 0;
- nextLogIdx = data.getNextLogLineIdx() == null ? curLogIdx : data.getNextLogLineIdx();
- if (data.isIncLogMode()) {
- hasNext = data.hasNextLogLine() == null ? curLogIdx < nextLogIdx : data.hasNextLogLine();
- } else {
- hasNext = curLogIdx < nextLogIdx;
- }
- if (curLogIdx >= nextLogIdx) {
- String msg =
- MessageFormat.format(
- "Job is still running, status={0}, progress={1}",
- data.getJobStatus(), String.valueOf(data.getJobProgress() * 100) + "%");
- logger.info(msg);
- }
- Utils.doSleepQuietly(AppConstants.JOB_QUERY_SLEEP_MILLS);
- }
- } catch (Exception e) {
- logger.error("Something goes wrong. Job Log may be incomplete", e);
- } finally {
- data.sendLogFin();
- }
- }
-
- private void queryJobLogFromLine(LinkisLogData data, int fromLine)
- throws LinkisClientRuntimeException {
- if (!data.getJobStatus().isJobFinishedState()) {
- try {
- data.updateByOperResult(
- getJobOperator()
- .queryRunTimeLogFromLine(
- data.getUser(), data.getJobID(), data.getExecID(), fromLine));
- } catch (Exception e) {
- // job is finished while we start query log(but request is not send).
- // then probably server cache is gone and we got a exception here.
- // however we cannot know if this happens based on the exception message
- logger.warn(
- "Caught exception when querying runtime-log. Probably server-side has close stream. Will try openLog api if Job is completed.",
- e);
- if (data.getJobStatus().isJobFinishedState()) {
- CommonUtils.doSleepQuietly(500l);
- data.updateByOperResult(
- getJobOperator()
- .queryPersistedLogFromLine(
- data.getUser(), data.getJobID(), data.getExecID(), fromLine));
- }
- }
- } else {
- try {
- data.updateByOperResult(
- getJobOperator()
- .queryPersistedLogFromLine(
- data.getLogPath(), data.getUser(), data.getJobID(), fromLine));
- } catch (Exception e) {
- logger.error("Cannot get persisted-inc-log:", e);
- // and yes sometimes server may not be able to prepare persisted-log
- throw e;
- }
- }
- }
-
- @Override
- public void startRetrieveResult() {
- if (!(data instanceof LinkisResultData)) {
- throw new LinkisClientExecutionException(
- "EXE0034",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "JobData is not LinkisResultData");
- }
- if (jobDesc.getUser() == null || jobDesc.getJobID() == null) {
- throw new LinkisClientExecutionException(
- "EXE0036", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "user or jobID is null");
- }
- data.updateByOperResult(getJobOperator().queryJobInfo(jobDesc.getUser(), jobDesc.getJobID()));
- if (data.getJobStatus() == null) {
- throw new LinkisClientExecutionException(
- "EXE0038", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "jobStatus is null");
- }
- LinkisResultData resultData = (LinkisResultData) data;
- if (!resultData.getJobStatus().isJobSuccess()
- || StringUtils.isBlank(resultData.getResultLocation())) {
- resultData.updateByOperResult(
- getJobOperator().queryJobInfo(resultData.getUser(), resultData.getJobID()));
- }
- if (!resultData.getJobStatus().isJobSuccess()) {
- // throw new LinkisClientExecutionException("EXE0035", ErrorLevel.ERROR,
- // CommonErrMsg.ExecutionErr, "Job status is not success but \'" +
- // resultData.getJobStatus() + "\'. Will not try to retrieve any Result");
- LogUtils.getInformationLogger()
- .info(
- "Job status is not success but \'"
- + resultData.getJobStatus()
- + "\'. Will not try to retrieve any Result");
- resultData.sendResultFin(); // inform listener to stop
- return;
- }
- if (StringUtils.isBlank(resultData.getResultLocation())) {
- throw new LinkisClientExecutionException(
- "EXE0037",
- ErrorLevel.WARN,
- CommonErrMsg.ExecutionErr,
- "Got blank ResultLocation from server. Job may not have result-set. Will not try to retrieve any Result");
- }
-
- resultData.updateByOperResult(
- getJobOperator()
- .queryResultSetPaths(
- resultData.getUser(), resultData.getJobID(), resultData.getResultLocation()));
- if (resultData.getResultSetPaths() == null || resultData.getResultSetPaths().length == 0) {
- String msg = "Your job got no result.";
- logger.warn(msg);
- resultData.sendResultFin(); // inform listener to stop
- resultData.setHasResult(false);
- return;
- }
-
- try {
- resultData.setHasResult(true);
- Thread resultRetriever = new Thread(() -> queryResultLoop(resultData), "Result-Retriever");
- SchedulerUtils.getCachedThreadPoolExecutor().execute(resultRetriever);
- } catch (Exception e) {
- logger.error("Failed to retrieve result", e);
- throw e;
- }
- }
-
- public void queryResultLoop(LinkisResultData data) {
- boolean hasNext = true;
- int retryCnt = 0;
- final int MAX_RETRY = 30; // continues fails for 250s, then exit
- int idx = 0;
- try {
- while (hasNext) {
- try {
- hasNext = queryOneResult(data, idx);
- } catch (LinkisClientRuntimeException e) {
- logger.error("Cannot get result:", e);
- retryCnt++;
- if (retryCnt >= MAX_RETRY) {
- logger.error(
- "Continuously failing to query result for "
- + MAX_RETRY * (MAX_RETRY + 2) * 500 / 1000
- + "s. Will no longer try to query result",
- e);
- return;
- } else {
- hasNext = true;
- }
- Utils.doSleepQuietly(500l + 500l * retryCnt); // maybe server problem. sleep longer
- continue;
- }
- idx++;
- }
- } catch (Exception e) {
- logger.error("Something goes wrong. Job Result may be incomplete", e);
- throw e;
- } finally {
- data.sendResultFin();
- }
- }
-
- private boolean queryOneResult(LinkisResultData data, int idxResultSet) {
- Integer curPage = 1;
- boolean hasNextResult = true;
- boolean hasNextPage = true;
- while (hasNextPage) {
- data.updateByOperResult(
- getJobOperator()
- .queryResultSetGivenResultSetPath(
- data.getResultSetPaths(),
- idxResultSet,
- data.getUser(),
- curPage,
- AppConstants.RESULTSET_PAGE_SIZE));
- if (data.hasNextResultPage() == null) {
- throw new LinkisClientExecutionException(
- "EXE0040",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionResultErr,
- "Something foes wrong. Got null as \'hasNextPage\'.");
- }
- hasNextPage = data.hasNextResultPage();
-
- curPage++;
- hasNextResult = idxResultSet + 1 < data.getResultSetPaths().length;
- }
- return hasNextResult;
- }
-
- public void doKill() {
- data.updateByOperResult(getJobOperator().queryJobInfo(jobDesc.getUser(), jobDesc.getJobID()));
- if (data.getUser() == null || data.getJobID() == null) {
- throw new LinkisClientExecutionException(
- "EXE0036", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "user or jobID is null");
- }
- if (data.getJobStatus() == null) {
- throw new LinkisClientExecutionException(
- "EXE0038", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "jobStatus is null");
- }
- String msg;
- if (data.getJobStatus().isJobCancelled()) {
- msg = "Kill job aborted: Job has already been canceled.";
- data.setSuccess(false);
- data.setMessage(msg);
- } else if (data.getJobStatus().isJobFinishedState()) {
- msg = "Kill job aborted: Job is already in finished-state(SUCCEED/FAILED).";
- data.setSuccess(false);
- data.setMessage(msg);
- // throw new LinkisClientExecutionException(JobStatus.FAILED, "EXE0004",
- // ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, msg);
- } else {
- try {
- data.updateByOperResult(
- getJobOperator().queryJobInfo(jobDesc.getUser(), jobDesc.getJobID()));
- data.updateByOperResult(
- getJobOperator().kill(data.getUser(), data.getJobID(), data.getExecID()));
- } catch (Exception e) {
- data.setSuccess(false);
- data.setMessage("Exception thrown when trying to send kill request");
- data.setException(e);
- }
- msg = "Kill request has been sent";
- LogUtils.getPlaintTextLogger().info(msg);
- int retryCnt = 0;
- final int MAX_RETRY = 5 * 6;
- while (!data.getJobStatus().isJobFinishedState() && !data.getJobStatus().isJobCancelled()) {
- CommonUtils.doSleepQuietly(CommonConstants.JOB_QUERY_SLEEP_MILLS);
- try {
- data.updateByOperResult(
- getJobOperator().queryJobInfo(jobDesc.getUser(), jobDesc.getJobID()));
- retryCnt = 0; // if exception then will not go here
- } catch (Exception e) {
- retryCnt++;
- CommonUtils.doSleepQuietly(5 * CommonConstants.JOB_QUERY_SLEEP_MILLS);
- if (retryCnt >= MAX_RETRY) {
- data.setSuccess(false);
- data.setMessage(
- MessageFormat.format(
- "After send kill. Client cannot get jobStatus from server continuously for {0} seconds. Client aborted. Assume kill failed! Error message: \n",
- MAX_RETRY * 5 * CommonConstants.JOB_QUERY_SLEEP_MILLS));
- data.setException(e);
- return;
- }
- }
- }
- if (data.getJobStatus().isJobFinishedState() && !data.getJobStatus().isJobCancelled()) {
- msg = "Kill Failed: Job Current status: " + data.getJobStatus();
- data.setSuccess(false);
- data.setMessage(msg);
- // throw new LinkisClientExecutionException(JobStatus.FAILED,
- // "EXE0004", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, msg);
- } else if (data.getJobStatus().isJobCancelled()) {
- msg =
- MessageFormat.format(
- "Kill successful: jobId={0}, status={1}.", data.getJobID(), data.getJobStatus());
- data.setSuccess(true);
- data.setMessage(msg);
- // LogUtils.getPlaintTextLogger().info(msg);
- }
- }
- return;
- }
-
- @Override
- public TerminateToken getTerminateToken() {
- return terminateToken;
- }
-
- public void setTerminateToken(TerminateToken terminateToken) {
- this.terminateToken = terminateToken;
- }
-
- @Override
- public void terminate() throws LinkisClientRuntimeException {
- return;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisOnceJob.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisOnceJob.java
deleted file mode 100644
index 505b08cf26..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisOnceJob.java
+++ /dev/null
@@ -1,308 +0,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.apache.linkis.cli.application.interactor.job;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisLogData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisOnceJobData;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisOnceDesc;
-import org.apache.linkis.cli.application.utils.Utils;
-import org.apache.linkis.cli.common.entity.job.JobDescription;
-import org.apache.linkis.cli.common.entity.operator.JobOperator;
-import org.apache.linkis.cli.common.exception.LinkisClientRuntimeException;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.constants.CommonConstants;
-import org.apache.linkis.cli.core.exception.LinkisClientExecutionException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.interactor.job.*;
-import org.apache.linkis.cli.core.utils.CommonUtils;
-import org.apache.linkis.cli.core.utils.LogUtils;
-import org.apache.linkis.cli.core.utils.SchedulerUtils;
-
-import java.text.MessageFormat;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisOnceJob extends LinkisJob
- implements ManagableBackendJob,
- LogAccessibleJob,
- ResultAccessibleJob,
- AsyncBackendJob,
- TerminatableJob {
-
- private static final Logger logger = LoggerFactory.getLogger(LinkisOnceJob.class);
-
- private LinkisOnceDesc jobDesc;
- private LinkisOnceJobData data;
- private TerminateToken terminateToken = new TerminateToken();
- private Boolean isAsync = false;
-
- public void setAsync(Boolean async) {
- isAsync = async;
- }
-
- public Boolean isAsync() {
- return isAsync;
- }
-
- @Override
- public JobDescription getJobDesc() {
- return jobDesc;
- }
-
- public void setJobDesc(LinkisOnceDesc desc) {
- this.jobDesc = desc;
- }
-
- @Override
- public TerminateToken getTerminateToken() {
- return terminateToken;
- }
-
- @Override
- public LinkisJobData getJobData() {
- return data;
- }
-
- public void setJobData(LinkisOnceJobData data) {
- this.data = data;
- }
-
- @Override
- public JobOperator getJobOperator() {
- return null;
- }
-
- /** AsyncBackendJob */
- @Override
- public void submit() throws LinkisClientRuntimeException {
- StringBuilder infoBuilder = new StringBuilder();
- infoBuilder
- .append("connecting to linkis gateway:")
- .append(data.getOnceJobAdapter().getServerUrl());
- LogUtils.getInformationLogger().info(infoBuilder.toString());
- data.getOnceJobAdapter().submit();
- data.getOnceJobAdapter().updateStatus();
- infoBuilder.setLength(0);
- infoBuilder
- .append("JobId:")
- .append(data.getJobID())
- .append(System.lineSeparator())
- .append("ExecId:")
- .append(data.getExecID());
- LogUtils.getPlaintTextLogger().info(infoBuilder.toString());
- if (isAsync) {
- data.setSuccess(data.getJobStatus() != null && data.getJobStatus().isJobSubmitted());
- }
- }
-
- @Override
- public void updateJobStatus() throws LinkisClientRuntimeException {
- if (!data.getJobStatus().isJobFinishedState()) {
- data.getOnceJobAdapter().updateStatus();
- String log2 =
- "\n---------------------------------------------------\n"
- + "\ttask "
- + data.getJobID()
- + " status is "
- + data.getJobStatus()
- + ", progress : "
- + data.getJobProgress()
- + "\n---------------------------------------------------";
- logger.info(log2);
- }
- }
-
- @Override
- public void waitJobComplete() throws LinkisClientRuntimeException {
- data.getOnceJobAdapter().waitForComplete();
- updateJobStatus();
- data.setSuccess(data.getJobStatus() != null && data.getJobStatus().isJobSuccess());
- waitIncLogComplete(data);
- }
-
- /** TerminatableJob */
- @Override
- public void terminate() throws LinkisClientRuntimeException {
- terminateToken.setTerminate();
- doKill();
- }
-
- @Override
- public void startRetrieveResult() {
- // TODO:wait for OnceJob to support this feature
- data.sendResultFin();
- }
-
- @Override
- public void startRetrieveLog() {
- data.setIncLogMode(true);
- startRetrieveLogInternal(data);
- }
-
- public void startRetrieveLogInternal(LinkisOnceJobData jobData) {
- if (!(jobData instanceof LinkisLogData)) {
- throw new LinkisClientExecutionException(
- "EXE0034", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "JobData is not LinkisLogData");
- }
- if (jobData.getUser() == null || jobData.getJobID() == null) {
- throw new LinkisClientExecutionException(
- "EXE0036", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "user or jobID is null");
- }
- LinkisOnceJobData logData = jobData;
- if (logData.getJobStatus() != null) {
- try {
- Thread logConsumer = new Thread(() -> logData.notifyLogListener(), "Log-Consumer");
- Thread logRetriever = new Thread(() -> queryLogLoop(logData), "Log-Retriever");
- SchedulerUtils.getCachedThreadPoolExecutor().execute(logRetriever);
- SchedulerUtils.getCachedThreadPoolExecutor().execute(logConsumer);
- } catch (Exception e) {
- logger.warn("Failed to retrieve log", e);
- }
- }
- }
-
- private void queryJobLogOneIteration(LinkisOnceJobData data) throws LinkisClientRuntimeException {
- try {
- data.getOnceJobAdapter().queryJobLogOneIteration();
- //
- // data.updateByOperResult(getJobOperator().queryRunTimeLogFromLine(data.getUser(),
- // data.getJobID(), data.getExecID(), fromLine));
- } catch (Exception e) {
- // job is finished while we start query log(but request is not send).
- // then probably server cache is gone and we got a exception here.
- // however we cannot know if this happens based on the exception message
- logger.warn(
- "Caught exception when querying runtime-log. Probably server-side has close stream. Will try openLog api if Job is completed.",
- e);
- if (data.getJobStatus().isJobFinishedState()) {
- CommonUtils.doSleepQuietly(500l);
- //
- // data.updateByOperResult(getJobOperator().queryPersistedLogFromLine(data.getUser(),
- // data.getJobID(), data.getExecID(), fromLine));
- }
- }
- }
-
- public void queryLogLoop(LinkisOnceJobData data) {
- boolean hasNext = true;
- int retryCnt = 0;
- final int MAX_RETRY = 12; // continues fails for 90s, then exit thread
- try {
- while (hasNext) {
- try {
- queryJobLogOneIteration(data);
- } catch (Exception e) {
- logger.error("Cannot get inc-log:", e);
- // and yes sometimes server may not be able to prepare persisted-log
- retryCnt++;
- if (retryCnt >= MAX_RETRY) {
- logger.error(
- "Continuously failing to query inc-log for "
- + MAX_RETRY * (MAX_RETRY + 2) * 500 / 1000
- + "s. Will no longer try to query log",
- e);
- break;
- }
- Utils.doSleepQuietly(500l + 500l * retryCnt); // maybe server problem. sleep longer
- continue;
- }
- retryCnt = 0;
- if (data.isIncLogMode()) {
- hasNext =
- data.hasNextLogLine() == null
- ? !data.getJobStatus().isJobFinishedState()
- : data.hasNextLogLine();
- } else {
- hasNext = false;
- }
- if (hasNext) {
- String msg =
- MessageFormat.format(
- "Job is still running, status={0}, progress={1}",
- data.getJobStatus(), String.valueOf(data.getJobProgress() * 100) + "%");
- logger.info(msg);
- }
- Utils.doSleepQuietly(AppConstants.JOB_QUERY_SLEEP_MILLS);
- }
- } catch (Exception e) {
- logger.error("Something goes wrong. Job Log may be incomplete", e);
- } finally {
- data.sendLogFin();
- }
- }
-
- private void waitIncLogComplete(LinkisJobData data) {
- if (!(data instanceof LinkisOnceJobData)) {
- return;
- }
- int retry = 0;
- int MAX_RETRY = 300; // wait for 10 minutes after job finish
- while (retry++ < MAX_RETRY) {
- if (((LinkisOnceJobData) data).logFinReceived()) {
- return;
- }
- CommonUtils.doSleepQuietly(CommonConstants.JOB_QUERY_SLEEP_MILLS);
- }
- String msg =
- "Job is in Finished state(SUCCEED/FAILED/CANCELED) but client keep querying inclog for "
- + (MAX_RETRY * CommonConstants.JOB_QUERY_SLEEP_MILLS / 1000)
- + "seconds. Execution ends forcefully. Next will try handle execution result.";
- logger.warn(msg);
- LogUtils.getInformationLogger().warn(msg);
- }
-
- // /**
- // * LogAccessibleJob
- // */
- // @Override
- // public void startRetrieveLog() {
-
- // }
-
- /** ManagableBackendJob */
- @Override
- public void doManage() throws LinkisClientRuntimeException {}
-
- @Override
- public boolean isSuccess() {
- return data.isSuccess();
- }
-
- private void doKill() {
- String msg;
- if (data.getJobStatus().isJobCancelled()) {
- msg = "Kill job aborted: Job is failed or has already been canceled.";
- data.setSuccess(false);
- data.setMessage(msg);
- } else if (data.getJobStatus().isJobFinishedState()) {
- msg = "Kill job aborted: Job is already in finished-state(SUCCEED/FAILED).";
- data.setSuccess(false);
- data.setMessage(msg);
- // throw new LinkisClientExecutionException(JobStatus.FAILED, "EXE0004",
- // ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, msg);
- } else {
- data.getOnceJobAdapter().kill();
- updateJobStatus();
- data.setSuccess(true);
- data.setMessage("successfully killed job");
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisSubmitJob.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisSubmitJob.java
deleted file mode 100644
index d1e71e4e8d..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/LinkisSubmitJob.java
+++ /dev/null
@@ -1,282 +0,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.apache.linkis.cli.application.interactor.job;
-
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisLogData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisResultData;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisJobManDesc;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisSubmitDesc;
-import org.apache.linkis.cli.application.operator.ujes.LinkisJobOperator;
-import org.apache.linkis.cli.common.entity.operator.JobOperator;
-import org.apache.linkis.cli.common.exception.LinkisClientRuntimeException;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.constants.CommonConstants;
-import org.apache.linkis.cli.core.exception.LinkisClientExecutionException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.interactor.job.*;
-import org.apache.linkis.cli.core.utils.CommonUtils;
-import org.apache.linkis.cli.core.utils.LogUtils;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.exception.ExceptionUtils;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisSubmitJob extends LinkisJob
- implements AsyncBackendJob, LogAccessibleJob, ResultAccessibleJob, TerminatableJob {
- private static final Logger logger = LoggerFactory.getLogger(LinkisSubmitJob.class);
-
- private LinkisSubmitDesc jobDesc;
- private LinkisJobData data;
- private TerminateToken terminateToken = new TerminateToken();
- private LinkisManageJob manageJob = new LinkisManageJob();
- private Boolean isAsync = false;
-
- public void setAsync(Boolean async) {
- isAsync = async;
- }
-
- public Boolean isAsync() {
- return isAsync;
- }
-
- @Override
- public LinkisJobOperator getJobOperator() {
- if (!(super.getJobOperator() instanceof LinkisJobOperator)) {
- throw new LinkisClientExecutionException(
- "EXE0003",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionInitErr,
- "JobOperator of LinkisManageJob should be instance of LinkisJobOperator");
- }
- return (LinkisJobOperator) super.getJobOperator();
- }
-
- @Override
- public void setOperator(JobOperator operator) {
- if (!(operator instanceof LinkisJobOperator)) {
- throw new LinkisClientExecutionException(
- "EXE0003",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionInitErr,
- "JobOperator of LinkisManageJob should be instance of LinkisJobOperator");
- }
- manageJob.setOperator(operator);
- super.setOperator(operator);
- }
-
- @Override
- public LinkisSubmitDesc getJobDesc() {
- return jobDesc;
- }
-
- public void setJobDesc(LinkisSubmitDesc jobDesc) {
- this.jobDesc = jobDesc;
- }
-
- @Override
- public LinkisJobData getJobData() {
- return data;
- }
-
- public void setJobData(LinkisJobData data) {
- manageJob.setJobData(data);
- this.data = data;
- }
-
- @Override
- public TerminateToken getTerminateToken() {
- return terminateToken;
- }
-
- public void setTerminateToken(TerminateToken terminateToken) {
- this.terminateToken = terminateToken;
- }
-
- @Override
- public void submit() throws LinkisClientRuntimeException {
- StringBuilder infoBuilder = new StringBuilder();
- infoBuilder.append("connecting to linkis gateway:").append(getJobOperator().getServerUrl());
- LogUtils.getInformationLogger().info(infoBuilder.toString());
- data.updateByOperResult(getJobOperator().submit(jobDesc));
- CommonUtils.doSleepQuietly(2000l);
- LinkisJobManDesc jobManDesc = new LinkisJobManDesc();
- jobManDesc.setJobId(data.getJobID());
- jobManDesc.setUser(data.getUser());
- manageJob.setJobDesc(jobManDesc);
- data.updateByOperResult(getJobOperator().queryJobInfo(data.getUser(), data.getJobID()));
- infoBuilder.setLength(0);
- infoBuilder
- .append("JobId:")
- .append(data.getJobID())
- .append(System.lineSeparator())
- .append("TaskId:")
- .append(data.getJobID())
- .append(System.lineSeparator())
- .append("ExecId:")
- .append(data.getExecID());
- LogUtils.getPlaintTextLogger().info(infoBuilder.toString());
- if (isAsync) {
- data.setSuccess(data.getJobStatus() != null && data.getJobStatus().isJobSubmitted());
- }
- }
-
- @Override
- public void updateJobStatus() throws LinkisClientRuntimeException {
- data.updateByOperResult(getJobOperator().queryJobInfo(data.getUser(), data.getJobID()));
- getJobOperator().queryJobStatus(data.getUser(), data.getJobID(), data.getExecID());
- String log2 =
- "\n---------------------------------------------------\n"
- + "\ttask "
- + data.getJobID()
- + " status is "
- + data.getJobStatus()
- + ", progress : "
- + data.getJobProgress()
- + "\n---------------------------------------------------";
- logger.info(log2);
- }
-
- @Override
- public void waitJobComplete() throws LinkisClientRuntimeException {
- int retryCnt = 0;
- final int MAX_RETRY = 30;
- while (!data.getJobStatus().isJobFinishedState()) {
- // query progress
- try {
- data.updateByOperResult(getJobOperator().queryJobInfo(data.getUser(), data.getJobID()));
- getJobOperator().queryJobStatus(data.getUser(), data.getJobID(), data.getExecID());
- } catch (Exception e) {
- logger.warn("", e);
- retryCnt++;
- if (retryCnt >= MAX_RETRY) {
- throw new LinkisClientExecutionException(
- "EXE0013",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "Cannot get jobStatus from server continuously for {0} seconds. Client aborted! Error message: \n",
- MAX_RETRY * 5 * CommonConstants.JOB_QUERY_SLEEP_MILLS,
- e);
- }
- CommonUtils.doSleepQuietly(
- 5 * CommonConstants.JOB_QUERY_SLEEP_MILLS); // maybe server problem. sleep
- // longer
- continue;
- }
- retryCnt = 0; // reset counter
- checkJobAvailability(data);
- CommonUtils.doSleepQuietly(CommonConstants.JOB_QUERY_SLEEP_MILLS);
- }
- data.setSuccess(data.getJobStatus() != null && data.getJobStatus().isJobSuccess());
- waitIncLogComplete(data);
- }
-
- private void waitIncLogComplete(LinkisJobData data) {
- if (!(data instanceof LinkisLogData)) {
- return;
- }
- int retry = 0;
- int MAX_RETRY = 300; // wait for 10 minutes after job finish
- while (retry++ < MAX_RETRY) {
- if (((LinkisLogData) data).logFinReceived()) {
- return;
- }
- CommonUtils.doSleepQuietly(CommonConstants.JOB_QUERY_SLEEP_MILLS);
- }
- String msg =
- "Job is in Finished state(SUCCEED/FAILED/CANCELED) but client keep querying inclog for "
- + (MAX_RETRY * CommonConstants.JOB_QUERY_SLEEP_MILLS / 1000)
- + "seconds. Execution ends forcefully. Next will try handle execution result.";
- logger.warn(msg);
- LogUtils.getInformationLogger().warn(msg);
- }
-
- @Override
- public void startRetrieveResult() {
- try {
- manageJob.startRetrieveResult();
- data.setSuccess(true);
- } catch (LinkisClientExecutionException e) {
- if (e.getCode().equals("EXE0037")) {
- data.setSuccess(true);
- LogUtils.getInformationLogger().warn(e.getMessage());
- } else {
- data.setSuccess(false);
- data.setException(e);
- }
- ((LinkisResultData) data).sendResultFin(); // inform listener to stop
- } catch (Exception e) {
- data.setSuccess(false);
- data.setException(e);
- ((LinkisResultData) data).sendResultFin(); // inform listener to stop
- }
- }
-
- @Override
- public void startRetrieveLog() {
- if (!(data instanceof LinkisLogData)) {
- throw new LinkisClientExecutionException(
- "EXE0034", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "JobData is not LinkisLogData");
- }
- LinkisLogData dataCopy;
- try {
- dataCopy = ((LinkisLogData) data).clone(); // make a copy to avoid race condition
- } catch (CloneNotSupportedException e) {
- throw new LinkisClientExecutionException(
- "EXE0035", ErrorLevel.ERROR, CommonErrMsg.ExecutionErr, "logData is not Cloneable", e);
- }
- dataCopy.setIncLogMode(true);
- manageJob.startRetrieveLogInternal(dataCopy);
- }
-
- @Override
- public void terminate() throws LinkisClientRuntimeException {
- terminateToken.setTerminate();
- // kill job if job is submitted
- if (StringUtils.isNotBlank(data.getJobID())) {
- System.out.println("\nKilling job: " + data.getJobID());
- try {
- manageJob.doKill();
- if (data.getJobStatus().isJobCancelled()) {
- System.out.println("Successfully killed job: " + data.getJobID() + " on exit");
- } else {
- System.out.println(
- "Failed to kill job: "
- + data.getJobID()
- + " on exit. Current job status: "
- + data.getJobStatus());
- }
- } catch (Exception e) {
- System.out.println("Failed to kill job: " + data.getJobID() + " on exit");
- System.out.println(ExceptionUtils.getStackTrace(e));
- }
- }
- }
-
- private void checkJobAvailability(LinkisJobData data) throws LinkisClientRuntimeException {
- if (data.getJobStatus().isJobAbnormalStatus()) {
- throw new LinkisClientExecutionException(
- "EXE0006",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "Job is in abnormal status: " + CommonUtils.GSON.toJson(data));
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisManageJobBuilder.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisManageJobBuilder.java
deleted file mode 100644
index ef5648b993..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisManageJobBuilder.java
+++ /dev/null
@@ -1,140 +0,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.apache.linkis.cli.application.interactor.job.builder;
-
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.interactor.job.LinkisManageJob;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobDataImpl;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisJobManDesc;
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-import org.apache.linkis.cli.application.operator.ujes.LinkisJobOperator;
-import org.apache.linkis.cli.application.utils.ExecutionUtils;
-import org.apache.linkis.cli.common.entity.present.PresentWay;
-import org.apache.linkis.cli.common.exception.LinkisClientRuntimeException;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.interactor.job.JobBuilder;
-import org.apache.linkis.cli.core.operator.JobOperatorFactory;
-import org.apache.linkis.cli.core.present.PresentModeImpl;
-import org.apache.linkis.cli.core.present.PresentWayImpl;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisManageJobBuilder extends JobBuilder {
- private static Logger logger = LoggerFactory.getLogger(LinkisSubmitJobBuilder.class);
-
- LinkisClientListener logListener;
-
- public LinkisManageJobBuilder setLogListener(LinkisClientListener observer) {
- this.logListener = observer;
- return this;
- }
-
- @Override
- protected LinkisJobManDesc buildJobDesc() {
- LinkisJobManDesc desc = new LinkisJobManDesc();
- String osUser = sysVarAccess.getVar(String.class, AppKeys.LINUX_USER_KEY);
- String[] adminUsers = StringUtils.split(AppKeys.ADMIN_USERS, ',');
- Set adminSet = new HashSet<>();
- for (String admin : adminUsers) {
- adminSet.add(admin);
- }
- String submitUsr = ExecutionUtils.getSubmitUser(stdVarAccess, osUser, adminSet);
-
- String jobId = null;
- if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_KILL_OPT)) {
- jobId = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_KILL_OPT);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_STATUS_OPT)) {
- jobId = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_STATUS_OPT);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_DESC_OPT)) {
- jobId = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_DESC_OPT);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_LOG_OPT)) {
- jobId = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_LOG_OPT);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_RESULT_OPT)) {
- jobId = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_RESULT_OPT);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_LIST_OPT)) {
- jobId = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_LIST_OPT);
- }
-
- desc.setJobId(jobId);
- desc.setUser(submitUsr);
- return desc;
- }
-
- @Override
- protected LinkisJobData buildJobData() {
- LinkisJobDataImpl data = new LinkisJobDataImpl();
- if (logListener == null) {
- logger.warn("logListener is not registered, will not be able to display log");
- } else {
- data.registerincLogListener(logListener);
- }
- return data;
- }
-
- @Override
- protected LinkisJobOperator buildJobOperator() {
- LinkisJobOperator oper;
- try {
- oper = (LinkisJobOperator) JobOperatorFactory.getReusable(AppKeys.REUSABLE_UJES_CLIENT);
- } catch (Exception e) {
- throw new LinkisClientRuntimeException(
- "BLD0012",
- ErrorLevel.ERROR,
- CommonErrMsg.BuilderBuildErr,
- "Failed to get a valid operator.",
- e);
- }
- return oper;
- }
-
- @Override
- protected PresentWay buildPresentWay() {
- PresentWayImpl presentWay = new PresentWayImpl();
- String outputPath = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_COMMON_OUTPUT_PATH);
-
- presentWay.setPath(outputPath);
- presentWay.setMode(PresentModeImpl.STDOUT);
- if (StringUtils.isNotBlank(outputPath)) {
- presentWay.setMode(PresentModeImpl.TEXT_FILE);
- }
-
- return presentWay;
- }
-
- @Override
- protected LinkisManageJob getTargetNewInstance() {
- return new LinkisManageJob();
- }
-
- @Override
- public LinkisManageJob build() {
- ((LinkisManageJob) targetObj).setJobDesc(buildJobDesc());
- ((LinkisManageJob) targetObj).setJobData(buildJobData());
- targetObj.setOperator(buildJobOperator());
- targetObj.setPresentWay(buildPresentWay());
- return (LinkisManageJob) super.build();
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisOnceJobBuilder.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisOnceJobBuilder.java
deleted file mode 100644
index 15a2eb3ac3..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisOnceJobBuilder.java
+++ /dev/null
@@ -1,239 +0,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.apache.linkis.cli.application.interactor.job.builder;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.constants.LinkisKeys;
-import org.apache.linkis.cli.application.interactor.job.LinkisOnceJob;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisOnceJobData;
-import org.apache.linkis.cli.application.interactor.job.data.SimpleOnceJobAdapter;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisOnceDesc;
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-import org.apache.linkis.cli.application.utils.ExecutionUtils;
-import org.apache.linkis.cli.common.entity.operator.JobOperator;
-import org.apache.linkis.cli.common.entity.present.PresentWay;
-import org.apache.linkis.cli.core.interactor.job.JobBuilder;
-import org.apache.linkis.cli.core.present.PresentModeImpl;
-import org.apache.linkis.cli.core.present.PresentWayImpl;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.*;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisOnceJobBuilder extends JobBuilder {
- private static Logger logger = LoggerFactory.getLogger(LinkisSubmitJobBuilder.class);
-
- private LinkisClientListener logListener;
- private Boolean isAsync = false;
- private SimpleOnceJobAdapter onceJobAdapter = new SimpleOnceJobAdapter();
-
- public LinkisOnceJobBuilder setLogListener(LinkisClientListener observer) {
- this.logListener = observer;
- return this;
- }
-
- public LinkisOnceJobBuilder setAsync(Boolean async) {
- isAsync = async;
- return this;
- }
-
- @Override
- protected LinkisOnceJob getTargetNewInstance() {
- return new LinkisOnceJob();
- }
-
- @Override
- protected LinkisOnceDesc buildJobDesc() {
- LinkisOnceDesc desc = new LinkisOnceDesc();
-
- desc.setStdVarAccess(stdVarAccess);
- desc.setSysVarAccess(sysVarAccess);
-
- Map confMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_PARAM_CONF);
- Map runtimeMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_PARAM_RUNTIME);
- Map varMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_PARAM_VAR);
- Map labelMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_LABEL);
- Map sourceMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_SOURCE);
- Map executionMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_EXEC);
- Map jobContentMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_CONTENT);
-
- confMap = confMap == null ? new HashMap<>() : confMap;
- runtimeMap = runtimeMap == null ? new HashMap<>() : runtimeMap;
- varMap = varMap == null ? new HashMap<>() : varMap;
- labelMap = labelMap == null ? new HashMap<>() : labelMap;
- sourceMap = sourceMap == null ? new HashMap<>() : sourceMap;
- executionMap = executionMap == null ? new HashMap<>() : executionMap;
- jobContentMap = jobContentMap == null ? new HashMap<>() : jobContentMap;
-
- confMap = ProcessKeyUtils.removePrefixForKeysInMap(confMap);
- runtimeMap = ProcessKeyUtils.removePrefixForKeysInMap(runtimeMap);
- labelMap = ProcessKeyUtils.removePrefixForKeysInMap(labelMap);
- sourceMap = ProcessKeyUtils.removePrefixForKeysInMap(sourceMap);
- executionMap = ProcessKeyUtils.removePrefixForKeysInMap(executionMap);
- jobContentMap = ProcessKeyUtils.removePrefixForKeysInMap(jobContentMap);
-
- for (String key : stdVarAccess.getAllVarKeys()) {
- Object val = stdVarAccess.getVar(Object.class, key);
- if (!(val instanceof Map) && val != null) {
- // note that we allow it to overwrite existing values in map
- if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_PARAM_CONF)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(confMap, key, val, AppKeys.JOB_PARAM_CONF);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_PARAM_VAR)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(varMap, key, val, AppKeys.JOB_PARAM_VAR);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_PARAM_RUNTIME)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(
- runtimeMap, key, val, AppKeys.JOB_PARAM_RUNTIME);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_EXEC)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(executionMap, key, val, AppKeys.JOB_EXEC);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_LABEL)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(labelMap, key, val, AppKeys.JOB_LABEL);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_SOURCE)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(sourceMap, key, val, AppKeys.JOB_SOURCE);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_CONTENT)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(jobContentMap, key, val, AppKeys.JOB_CONTENT);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.LINKIS_CLIENT_COMMON)) {
- // do nothing
- } else {
- // confMap.put(key, stdVarAccess.getVar(Object.class, key));
- }
- }
- }
-
- String creator;
- if (!isAsync) {
- creator =
- stdVarAccess.getVarOrDefault(
- String.class, AppKeys.JOB_COMMON_CREATOR, AppConstants.JOB_CREATOR_DEFAULT);
- } else {
- creator =
- stdVarAccess.getVarOrDefault(
- String.class, AppKeys.JOB_COMMON_CREATOR, AppConstants.JOB_CREATOR_ASYNC_DEFAULT);
- }
- String code = stdVarAccess.getVar(String.class, AppKeys.JOB_EXEC_CODE);
- String engineType = stdVarAccess.getVar(String.class, AppKeys.JOB_LABEL_ENGINE_TYPE);
- String runType = stdVarAccess.getVar(String.class, AppKeys.JOB_LABEL_CODE_TYPE);
- String scriptPath =
- stdVarAccess.getVarOrDefault(String.class, AppKeys.JOB_SOURCE_SCRIPT_PATH, "LinkisCli");
-
- String osUser = sysVarAccess.getVar(String.class, AppKeys.LINUX_USER_KEY);
- String[] adminUsers = StringUtils.split(AppKeys.ADMIN_USERS, ',');
- Set adminSet = new HashSet<>();
- for (String admin : adminUsers) {
- adminSet.add(admin);
- }
- String submitUsr = ExecutionUtils.getSubmitUser(stdVarAccess, osUser, adminSet);
- String proxyUsr = ExecutionUtils.getProxyUser(stdVarAccess, submitUsr, adminSet);
-
- String enableExecuteOnce =
- stdVarAccess.getVarOrDefault(String.class, AppKeys.JOB_LABEL_EXECUTEONCE, "true");
- // default executeOnce-mode
- if (Boolean.parseBoolean(enableExecuteOnce)) {
- labelMap.put(LinkisKeys.KEY_EXECUTEONCE, "");
- } else {
- labelMap.remove(LinkisKeys.KEY_EXECUTEONCE);
- }
- String codePath = stdVarAccess.getVar(String.class, AppKeys.JOB_COMMON_CODE_PATH);
- Object extraArgsObj = stdVarAccess.getVar(Object.class, AppKeys.JOB_EXTRA_ARGUMENTS);
- if (extraArgsObj != null
- && extraArgsObj instanceof String[]
- && StringUtils.isBlank(code)
- && StringUtils.isBlank(codePath)) {
- String[] extraArgs = (String[]) extraArgsObj;
- codePath = extraArgs[0];
- if (extraArgs.length > 1) {
- runtimeMap.put(
- LinkisKeys.EXTRA_ARGUMENTS, Arrays.copyOfRange(extraArgs, 1, extraArgs.length));
- }
- }
-
- if (StringUtils.isBlank(code) && StringUtils.isNotBlank(codePath)) {
- code = ExecutionUtils.readFile(codePath);
- }
-
- executionMap.put(LinkisKeys.KEY_CODE, code);
- labelMap.put(LinkisKeys.KEY_ENGINETYPE, engineType);
- labelMap.put(LinkisKeys.KEY_CODETYPE, runType);
- labelMap.put(LinkisKeys.KEY_USER_CREATOR, proxyUsr + "-" + creator);
- sourceMap.put(LinkisKeys.KEY_SCRIPT_PATH, scriptPath);
- runtimeMap.put(LinkisKeys.KEY_HIVE_RESULT_DISPLAY_TBALE, true);
-
- desc.setCreator(creator);
- desc.setParamConfMap(confMap);
- desc.setParamRunTimeMap(runtimeMap);
- desc.setParamVarsMap(varMap);
- desc.setLabelMap(labelMap);
- desc.setSourceMap(sourceMap);
- desc.setExecutionMap(executionMap);
- desc.setSubmitUser(submitUsr);
- desc.setProxyUser(proxyUsr);
- desc.setJobContentMap(jobContentMap);
-
- return desc;
- }
-
- @Override
- protected LinkisOnceJobData buildJobData() {
- LinkisOnceJobData data = new LinkisOnceJobData();
- data.setOnceJobAdapter(this.onceJobAdapter);
- if (logListener == null) {
- logger.warn("logListener is not registered, will not be able to display log");
- } else {
- data.registerincLogListener(logListener);
- }
- return data;
- }
-
- @Override
- protected JobOperator buildJobOperator() {
- // OnceJob is Stateful, should not have an operator
- return null;
- }
-
- @Override
- protected PresentWay buildPresentWay() {
- PresentWayImpl presentWay = new PresentWayImpl();
- String outputPath = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_COMMON_OUTPUT_PATH);
-
- presentWay.setPath(outputPath);
- presentWay.setMode(PresentModeImpl.STDOUT);
- presentWay.setDisplayMetaAndLogo(
- stdVarAccess.getVarOrDefault(Boolean.class, AppKeys.LINKIS_COMMON_DIAPLAY_META_LOGO, true));
- if (StringUtils.isNotBlank(outputPath)) {
- presentWay.setMode(PresentModeImpl.TEXT_FILE);
- }
-
- return presentWay;
- }
-
- @Override
- public LinkisOnceJob build() {
- LinkisOnceDesc desc = buildJobDesc();
- ((LinkisOnceJob) targetObj).setJobDesc(desc);
- LinkisOnceJobData data = buildJobData();
- ((LinkisOnceJob) targetObj).setJobData(data);
- data.getOnceJobAdapter().init(desc);
- ((LinkisOnceJob) targetObj).setAsync(isAsync);
- targetObj.setOperator(buildJobOperator());
- targetObj.setPresentWay(buildPresentWay());
- return (LinkisOnceJob) super.build();
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisSubmitJobBuilder.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisSubmitJobBuilder.java
deleted file mode 100644
index 6804f09056..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/builder/LinkisSubmitJobBuilder.java
+++ /dev/null
@@ -1,241 +0,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.apache.linkis.cli.application.interactor.job.builder;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.constants.LinkisKeys;
-import org.apache.linkis.cli.application.interactor.job.LinkisSubmitJob;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobData;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobDataImpl;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisSubmitDesc;
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-import org.apache.linkis.cli.application.operator.ujes.LinkisJobOperator;
-import org.apache.linkis.cli.application.utils.ExecutionUtils;
-import org.apache.linkis.cli.common.entity.present.PresentWay;
-import org.apache.linkis.cli.common.exception.LinkisClientRuntimeException;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.interactor.job.JobBuilder;
-import org.apache.linkis.cli.core.operator.JobOperatorFactory;
-import org.apache.linkis.cli.core.present.PresentModeImpl;
-import org.apache.linkis.cli.core.present.PresentWayImpl;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.*;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class LinkisSubmitJobBuilder extends JobBuilder {
- private static Logger logger = LoggerFactory.getLogger(LinkisSubmitJobBuilder.class);
-
- private LinkisClientListener logListener;
- private Boolean isAsync = false;
-
- public LinkisSubmitJobBuilder setLogListener(LinkisClientListener observer) {
- this.logListener = observer;
- return this;
- }
-
- public LinkisSubmitJobBuilder setAsync(Boolean async) {
- isAsync = async;
- return this;
- }
-
- @Override
- protected LinkisSubmitJob getTargetNewInstance() {
- return new LinkisSubmitJob();
- }
-
- @Override
- protected LinkisSubmitDesc buildJobDesc() {
- LinkisSubmitDesc desc = new LinkisSubmitDesc();
-
- Map confMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_PARAM_CONF);
- Map runtimeMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_PARAM_RUNTIME);
- Map varMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_PARAM_VAR);
- Map labelMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_LABEL);
- Map sourceMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_SOURCE);
- Map executionMap = stdVarAccess.getVar(Map.class, AppKeys.JOB_EXEC);
-
- confMap = confMap == null ? new HashMap<>() : confMap;
- runtimeMap = runtimeMap == null ? new HashMap<>() : runtimeMap;
- varMap = varMap == null ? new HashMap<>() : varMap;
- labelMap = labelMap == null ? new HashMap<>() : labelMap;
- sourceMap = sourceMap == null ? new HashMap<>() : sourceMap;
- executionMap = executionMap == null ? new HashMap<>() : executionMap;
-
- /** remove key prefix of all keys in map type params. e.g. kv in confMap, labelMap etc. */
- confMap = ProcessKeyUtils.removePrefixForKeysInMap(confMap);
- runtimeMap = ProcessKeyUtils.removePrefixForKeysInMap(runtimeMap);
- labelMap = ProcessKeyUtils.removePrefixForKeysInMap(labelMap);
- sourceMap = ProcessKeyUtils.removePrefixForKeysInMap(sourceMap);
- executionMap = ProcessKeyUtils.removePrefixForKeysInMap(executionMap);
-
- /** remove key prefix of non-map type params */
- for (String key : stdVarAccess.getAllVarKeys()) {
- Object val = stdVarAccess.getVar(Object.class, key);
- if (!(val instanceof Map) && val != null) {
- // note that we allow it to overwrite existing values in map
- if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_PARAM_CONF)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(confMap, key, val, AppKeys.JOB_PARAM_CONF);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_PARAM_VAR)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(varMap, key, val, AppKeys.JOB_PARAM_VAR);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_PARAM_RUNTIME)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(
- runtimeMap, key, val, AppKeys.JOB_PARAM_RUNTIME);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_EXEC)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(executionMap, key, val, AppKeys.JOB_EXEC);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_LABEL)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(labelMap, key, val, AppKeys.JOB_LABEL);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.JOB_SOURCE)) {
- ProcessKeyUtils.removePrefixAndPutValToMap(sourceMap, key, val, AppKeys.JOB_SOURCE);
- } else if (StringUtils.startsWithIgnoreCase(key, AppKeys.LINKIS_CLIENT_COMMON)) {
- // do nothing
- } else {
- // confMap.put(key, stdVarAccess.getVar(Object.class, key));
- }
- }
- }
-
- String creator;
- if (!isAsync) {
- creator =
- stdVarAccess.getVarOrDefault(
- String.class, AppKeys.JOB_COMMON_CREATOR, AppConstants.JOB_CREATOR_DEFAULT);
- } else {
- creator =
- stdVarAccess.getVarOrDefault(
- String.class, AppKeys.JOB_COMMON_CREATOR, AppConstants.JOB_CREATOR_ASYNC_DEFAULT);
- }
- String code = stdVarAccess.getVar(String.class, AppKeys.JOB_EXEC_CODE);
- String engineType = stdVarAccess.getVar(String.class, AppKeys.JOB_LABEL_ENGINE_TYPE);
- String runType = stdVarAccess.getVar(String.class, AppKeys.JOB_LABEL_CODE_TYPE);
- String scriptPath =
- stdVarAccess.getVarOrDefault(String.class, AppKeys.JOB_SOURCE_SCRIPT_PATH, "LinkisCli");
-
- String osUser = sysVarAccess.getVar(String.class, AppKeys.LINUX_USER_KEY);
- String[] adminUsers = StringUtils.split(AppKeys.ADMIN_USERS, ',');
- Set adminSet = new HashSet<>();
- for (String admin : adminUsers) {
- adminSet.add(admin);
- }
- String submitUsr = ExecutionUtils.getSubmitUser(stdVarAccess, osUser, adminSet);
- String proxyUsr = ExecutionUtils.getProxyUser(stdVarAccess, submitUsr, adminSet);
-
- String enableExecuteOnce =
- stdVarAccess.getVarOrDefault(String.class, AppKeys.JOB_LABEL_EXECUTEONCE, "true");
- // default executeOnce-mode
- if (Boolean.parseBoolean(enableExecuteOnce)) {
- labelMap.put(LinkisKeys.KEY_EXECUTEONCE, "");
- } else {
- labelMap.remove(LinkisKeys.KEY_EXECUTEONCE);
- }
- String codePath = stdVarAccess.getVar(String.class, AppKeys.JOB_COMMON_CODE_PATH);
- Object extraArgsObj = stdVarAccess.getVar(Object.class, AppKeys.JOB_EXTRA_ARGUMENTS);
- if (extraArgsObj != null
- && extraArgsObj instanceof String[]
- && StringUtils.isBlank(code)
- && StringUtils.isBlank(codePath)) {
- String[] extraArgs = (String[]) extraArgsObj;
- codePath = extraArgs[0];
- if (extraArgs.length > 1) {
- runtimeMap.put(
- LinkisKeys.EXTRA_ARGUMENTS, Arrays.copyOfRange(extraArgs, 1, extraArgs.length));
- }
- }
-
- if (StringUtils.isBlank(code) && StringUtils.isNotBlank(codePath)) {
- code = ExecutionUtils.readFile(codePath);
- }
-
- executionMap.put(LinkisKeys.KEY_CODE, code);
- labelMap.put(LinkisKeys.KEY_ENGINETYPE, engineType);
- labelMap.put(LinkisKeys.KEY_CODETYPE, runType);
- labelMap.put(LinkisKeys.KEY_USER_CREATOR, proxyUsr + "-" + creator);
- sourceMap.put(LinkisKeys.KEY_SCRIPT_PATH, scriptPath);
- runtimeMap.put(LinkisKeys.KEY_HIVE_RESULT_DISPLAY_TBALE, true);
-
- desc.setCreator(creator);
- desc.setParamConfMap(confMap);
- desc.setParamRunTimeMap(runtimeMap);
- desc.setParamVarsMap(varMap);
- desc.setLabelMap(labelMap);
- desc.setSourceMap(sourceMap);
- desc.setExecutionMap(executionMap);
- desc.setSubmitUser(submitUsr);
- desc.setProxyUser(proxyUsr);
-
- return desc;
- }
-
- @Override
- protected LinkisJobData buildJobData() {
- LinkisJobDataImpl data = new LinkisJobDataImpl();
- if (logListener == null) {
- logger.warn("logListener is not registered, will not be able to display log");
- } else {
- data.registerincLogListener(logListener);
- }
- return data;
- }
-
- @Override
- protected LinkisJobOperator buildJobOperator() {
- LinkisJobOperator oper;
- try {
- oper = (LinkisJobOperator) JobOperatorFactory.getReusable(AppKeys.REUSABLE_UJES_CLIENT);
- } catch (Exception e) {
- throw new LinkisClientRuntimeException(
- "BLD0012",
- ErrorLevel.ERROR,
- CommonErrMsg.BuilderBuildErr,
- "Failed to get a valid operator.",
- e);
- }
- return oper;
- }
-
- @Override
- protected PresentWay buildPresentWay() {
- PresentWayImpl presentWay = new PresentWayImpl();
- String outputPath = stdVarAccess.getVar(String.class, AppKeys.LINKIS_CLIENT_COMMON_OUTPUT_PATH);
-
- presentWay.setPath(outputPath);
- presentWay.setMode(PresentModeImpl.STDOUT);
- presentWay.setDisplayMetaAndLogo(
- stdVarAccess.getVarOrDefault(Boolean.class, AppKeys.LINKIS_COMMON_DIAPLAY_META_LOGO, true));
- if (StringUtils.isNotBlank(outputPath)) {
- presentWay.setMode(PresentModeImpl.TEXT_FILE);
- }
-
- return presentWay;
- }
-
- @Override
- public LinkisSubmitJob build() {
- ((LinkisSubmitJob) targetObj).setJobDesc(buildJobDesc());
- ((LinkisSubmitJob) targetObj).setJobData(buildJobData());
- ((LinkisSubmitJob) targetObj).setAsync(isAsync);
- targetObj.setOperator(buildJobOperator());
- targetObj.setPresentWay(buildPresentWay());
- return (LinkisSubmitJob) super.build();
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisJobDataImpl.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisJobDataImpl.java
deleted file mode 100644
index 227e8c2170..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisJobDataImpl.java
+++ /dev/null
@@ -1,514 +0,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.apache.linkis.cli.application.interactor.job.data;
-
-import org.apache.linkis.cli.application.observer.event.LinkisClientEvent;
-import org.apache.linkis.cli.application.observer.event.LogStartEvent;
-import org.apache.linkis.cli.application.observer.event.TriggerEvent;
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-import org.apache.linkis.cli.application.observer.listener.TriggerEventListener;
-import org.apache.linkis.cli.application.operator.ujes.LinkisOperResultAdapter;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-
-import java.util.Arrays;
-import java.util.Date;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.LinkedBlockingDeque;
-
-public class LinkisJobDataImpl
- implements LinkisJobData, LinkisLogData, LinkisResultData, Cloneable {
-
- private String jobID;
- private String user;
- private JobStatus jobStatus = null;
- private String message;
- private Exception exception;
- private String execID;
- private float progress = 0.0f;
- private Boolean incLogMode;
- private LinkedBlockingDeque logBuffer = new LinkedBlockingDeque();
- private String logPath; // remote path for job log
- private Integer nextLogLineIdx;
- private Boolean hasNextLogLine;
- private String resultLocation;
- private String[] resultSetPaths = null; // remote paths for job result set
- private LinkedBlockingDeque resultContent = new LinkedBlockingDeque<>();
- private Boolean hasNextResultPage;
- private Integer errCode = null;
- private String errDesc = null;
- private boolean success = false;
- private String instance;
- private String umUser;
- private String simpleExecId;
- private String executionCode;
- private String engineType;
- private String runType;
- private Long costTime;
- private Date createdTime;
- private Date updatedTime;
- private Date engineStartTime;
- private String executeApplicationName;
- private String requestApplicationName;
-
- private LinkisClientEvent logstartEvent = new LogStartEvent();
- private TriggerEvent logFinevent = new TriggerEvent();
- private TriggerEventListener logFinListener = new TriggerEventListener();
- private TriggerEvent resultFinEvent = new TriggerEvent();
- private TriggerEventListener resultFinListener = new TriggerEventListener();
-
- private boolean hasResult = true;
-
- {
- logFinevent.register(logFinListener);
- resultFinEvent.register(resultFinListener);
- }
-
- @Override
- public String getJobID() {
- return jobID;
- }
-
- public void setJobId(String jobId) {
- this.jobID = jobId;
- }
-
- @Override
- public String getUser() {
- return user;
- }
-
- public void setUser(String user) {
- this.user = user;
- }
-
- @Override
- public JobStatus getJobStatus() {
- return jobStatus;
- }
-
- public void setJobStatus(JobStatus jobStatus) {
- this.jobStatus = jobStatus;
- }
-
- @Override
- public String getMessage() {
- return message;
- }
-
- @Override
- public void setMessage(String message) {
- this.message = message;
- }
-
- @Override
- public Exception getException() {
- return exception;
- }
-
- @Override
- public void setException(Exception exception) {
- this.exception = exception;
- }
-
- @Override
- public final String getExecID() {
- return execID;
- }
-
- public final void setExecID(String execID) {
- this.execID = execID;
- }
-
- @Override
- public final float getJobProgress() {
- return progress;
- }
-
- public final void setJobProgress(float progress) {
- this.progress = progress;
- }
-
- @Override
- public final String getLogPath() {
- return logPath;
- }
-
- public final void setLogPath(String logPath) {
- this.logPath = logPath;
- }
-
- @Override
- public final String getResultLocation() {
- return resultLocation;
- }
-
- public final void setResultLocation(String resultLocation) {
- this.resultLocation = resultLocation;
- }
-
- @Override
- public String[] getResultSetPaths() {
- return resultSetPaths;
- }
-
- public final void setResultSetPaths(String[] resultSetPaths) {
- this.resultSetPaths = resultSetPaths;
- }
-
- @Override
- public Integer getErrCode() {
- return errCode;
- }
-
- public void setErrCode(Integer errCode) {
- this.errCode = errCode;
- }
-
- @Override
- public String getErrDesc() {
- return errDesc;
- }
-
- public void setErrDesc(String errDesc) {
- this.errDesc = errDesc;
- }
-
- @Override
- public void registerincLogListener(LinkisClientListener observer) {
- this.logstartEvent.register(observer);
- }
-
- @Override
- public void notifyLogListener() {
- if (this.logstartEvent.isRegistered()) {
- logstartEvent.notifyObserver(logstartEvent, this);
- }
- }
-
- @Override
- public boolean isIncLogMode() {
- return this.incLogMode;
- }
-
- @Override
- public void setIncLogMode(boolean incLogMode) {
- this.incLogMode = incLogMode;
- }
-
- @Override
- public String consumeLog() {
- List logs = new LinkedList<>();
- this.logBuffer.drainTo(logs, this.logBuffer.size());
- StringBuilder tmp = new StringBuilder();
- for (String str : logs) {
- tmp.append(str);
- }
- return tmp.toString();
- }
-
- public void appendLog(String log) {
- this.logBuffer.add(log);
- }
-
- @Override
- public Integer getNextLogLineIdx() {
- return nextLogLineIdx;
- }
-
- public void setNextLogLineIdx(Integer nextLogLineIdx) {
- this.nextLogLineIdx = nextLogLineIdx;
- }
-
- @Override
- public Boolean hasNextLogLine() {
- return hasNextLogLine;
- }
-
- @Override
- public void setHasNextLogLine(Boolean hasNextLogLine) {
- this.hasNextLogLine = hasNextLogLine;
- }
-
- @Override
- public List consumeResultContent() {
- List ret = new LinkedList<>();
- resultContent.drainTo(ret, resultContent.size());
- return ret;
- }
-
- public void appendResultContent(LinkisResultSet resultContent) {
- this.resultContent.add(resultContent);
- }
-
- @Override
- public Boolean hasNextResultPage() {
- return hasNextResultPage;
- }
-
- public void setHasNextResultPage(Boolean hasNextResultPage) {
- this.hasNextResultPage = hasNextResultPage;
- }
-
- @Override
- public void sendLogFin() {
- if (this.logFinevent != null && this.logFinevent.isRegistered()) {
- this.logFinevent.notifyObserver(resultFinEvent, null);
- }
- }
-
- @Override
- public boolean logFinReceived() {
- return this.logFinListener.isTriggered();
- }
-
- @Override
- public void sendResultFin() {
- if (this.resultFinEvent != null && this.resultFinEvent.isRegistered()) {
- this.resultFinEvent.notifyObserver(resultFinEvent, null);
- }
- }
-
- @Override
- public boolean resultFinReceived() {
- return this.resultFinListener.isTriggered();
- }
-
- @Override
- public boolean hasResult() {
- return hasResult;
- }
-
- @Override
- public void setHasResult(boolean hasResult) {
- this.hasResult = hasResult;
- }
-
- @Override
- public boolean isSuccess() {
- return success;
- }
-
- @Override
- public void setSuccess(boolean success) {
- this.success = success;
- }
-
- public String getInstance() {
- return instance;
- }
-
- public void setInstance(String instance) {
- this.instance = instance;
- }
-
- public String getUmUser() {
- return umUser;
- }
-
- public void setUmUser(String umUser) {
- this.umUser = umUser;
- }
-
- public String getSimpleExecId() {
- return simpleExecId;
- }
-
- public void setSimpleExecId(String simpleExecId) {
- this.simpleExecId = simpleExecId;
- }
-
- public String getExecutionCode() {
- return executionCode;
- }
-
- public void setExecutionCode(String executionCode) {
- this.executionCode = executionCode;
- }
-
- public String getEngineType() {
- return engineType;
- }
-
- public void setEngineType(String engineType) {
- this.engineType = engineType;
- }
-
- public String getRunType() {
- return runType;
- }
-
- public void setRunType(String runType) {
- this.runType = runType;
- }
-
- public Long getCostTime() {
- return costTime;
- }
-
- public void setCostTime(Long costTime) {
- this.costTime = costTime;
- }
-
- public Date getCreatedTime() {
- return createdTime;
- }
-
- public void setCreatedTime(Date createdTime) {
- this.createdTime = createdTime;
- }
-
- public Date getUpdatedTime() {
- return updatedTime;
- }
-
- public void setUpdatedTime(Date updatedTime) {
- this.updatedTime = updatedTime;
- }
-
- public Date getEngineStartTime() {
- return engineStartTime;
- }
-
- public void setEngineStartTime(Date engineStartTime) {
- this.engineStartTime = engineStartTime;
- }
-
- public String getExecuteApplicationName() {
- return executeApplicationName;
- }
-
- public void setExecuteApplicationName(String executeApplicationName) {
- this.executeApplicationName = executeApplicationName;
- }
-
- public String getRequestApplicationName() {
- return requestApplicationName;
- }
-
- public void setRequestApplicationName(String requestApplicationName) {
- this.requestApplicationName = requestApplicationName;
- }
-
- @Override
- public void updateByOperResult(LinkisOperResultAdapter adapter) {
- if (adapter.getJobID() != null) {
- setJobId(adapter.getJobID());
- }
- if (adapter.getUser() != null) {
- setUser(adapter.getUser());
- }
- if (adapter.getJobStatus() != null) {
- setJobStatus(adapter.getJobStatus());
- }
- if (adapter.getStrongerExecId() != null) {
- setExecID(adapter.getStrongerExecId());
- }
- if (adapter.getJobProgress() != null) {
- setJobProgress(adapter.getJobProgress());
- }
- if (adapter.getLogPath() != null) {
- setLogPath(adapter.getLogPath());
- }
- if (adapter.getResultLocation() != null) {
- setResultLocation(adapter.getResultLocation());
- }
- if (adapter.getResultSetPaths() != null) {
- setResultSetPaths(adapter.getResultSetPaths());
- }
- if (adapter.getErrCode() != null) {
- setErrCode(adapter.getErrCode());
- }
- if (adapter.getErrDesc() != null) {
- setErrDesc(adapter.getErrDesc());
- }
- if (adapter.getLog() != null
- && adapter.getNextLogLine() != null
- && adapter.hasNextLogLine() != null) {
- setNextLogLineIdx(adapter.getNextLogLine());
- setHasNextLogLine(adapter.hasNextLogLine());
- appendLog(adapter.getLog());
- }
- if (adapter.getResultContent() != null && adapter.resultHasNextPage() != null) {
- setHasNextResultPage(adapter.resultHasNextPage());
- appendResultContent(adapter.getResultContent());
- }
- if (adapter.getInstance() != null) {
- setInstance(adapter.getInstance());
- }
- if (adapter.getUmUser() != null) {
- setUmUser(adapter.getUmUser());
- }
- if (adapter.getSimpleExecId() != null) {
- setSimpleExecId(adapter.getSimpleExecId());
- }
- if (adapter.getExecutionCode() != null) {
- setExecutionCode(adapter.getExecutionCode());
- }
- if (adapter.getEngineType() != null) {
- setEngineType(adapter.getEngineType());
- }
- if (adapter.getRunType() != null) {
- setRunType(adapter.getRunType());
- }
- if (adapter.getCostTime() != null) {
- setCostTime(adapter.getCostTime());
- }
- if (adapter.getCreatedTime() != null) {
- setCreatedTime(adapter.getCreatedTime());
- }
- if (adapter.getUpdatedTime() != null) {
- setUpdatedTime(adapter.getUpdatedTime());
- }
- if (adapter.getEngineStartTime() != null) {
- setEngineStartTime(adapter.getEngineStartTime());
- }
- if (adapter.getExecuteApplicationName() != null) {
- setExecuteApplicationName(adapter.getExecuteApplicationName());
- }
- if (adapter.getRequestApplicationName() != null) {
- setRequestApplicationName(adapter.getRequestApplicationName());
- }
- }
-
- @Override
- public LinkisJobDataImpl clone() throws CloneNotSupportedException {
- LinkisJobDataImpl ret = (LinkisJobDataImpl) super.clone();
- if (logBuffer != null) {
- ret.logBuffer = new LinkedBlockingDeque(this.logBuffer);
- }
- if (this.resultContent != null) {
- ret.resultContent = new LinkedBlockingDeque<>();
- for (LinkisResultSet r1 : resultContent) {
- ret.resultContent.add(r1.clone());
- }
- }
- if (this.resultSetPaths != null) {
- ret.setResultSetPaths(Arrays.copyOf(this.resultSetPaths, this.resultSetPaths.length));
- }
- /*
- These be shared and hence should not be deep copied.
- */
- ret.logFinevent = this.logFinevent;
- ret.logFinListener = this.logFinListener;
- ret.resultFinEvent = this.resultFinEvent;
- ret.resultFinListener = this.resultFinListener;
-
- return ret;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisLogData.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisLogData.java
deleted file mode 100644
index 3df7cc5a47..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisLogData.java
+++ /dev/null
@@ -1,51 +0,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.apache.linkis.cli.application.interactor.job.data;
-
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-
-public interface LinkisLogData extends LinkisJobData, Cloneable {
-
- void notifyLogListener();
-
- void registerincLogListener(LinkisClientListener observer);
-
- String getLogPath();
-
- Integer getNextLogLineIdx();
-
- void setHasNextLogLine(Boolean hasNextLog);
-
- Boolean hasNextLogLine();
-
- String consumeLog();
-
- boolean isIncLogMode();
-
- /*
- incLogMode = true: for sync-submission, wait for job complete while get incremental log
- incLogMode = false: for async-submission, output all log we have currently
- */
- void setIncLogMode(boolean incLogMode);
-
- void sendLogFin();
-
- boolean logFinReceived();
-
- LinkisLogData clone() throws CloneNotSupportedException;
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisOnceJobData.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisOnceJobData.java
deleted file mode 100644
index 89130b62af..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/LinkisOnceJobData.java
+++ /dev/null
@@ -1,242 +0,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.apache.linkis.cli.application.interactor.job.data;
-
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-import org.apache.linkis.cli.application.operator.ujes.LinkisOperResultAdapter;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-
-import java.util.List;
-
-public class LinkisOnceJobData implements LinkisJobData, LinkisLogData, LinkisResultData {
-
- private SimpleOnceJobAdapter onceJobAdapter;
-
- private boolean hasResult = true;
-
- public SimpleOnceJobAdapter getOnceJobAdapter() {
- return onceJobAdapter;
- }
-
- public void setOnceJobAdapter(SimpleOnceJobAdapter onceJobAdapter) {
- this.onceJobAdapter = onceJobAdapter;
- }
-
- @Override
- public void registerincLogListener(LinkisClientListener observer) {
- onceJobAdapter.registerincLogListener(observer);
- }
-
- @Override
- public void notifyLogListener() {
- onceJobAdapter.notifyLogListener();
- }
-
- @Override
- public boolean isIncLogMode() {
- return onceJobAdapter.isIncLogMode();
- }
-
- @Override
- public void setIncLogMode(boolean incLogMode) {
- onceJobAdapter.setIncLogMode(incLogMode);
- }
-
- @Override
- public String consumeLog() {
- return onceJobAdapter.consumeLog();
- }
-
- public void appendLog(String log) {
- onceJobAdapter.appendLog(log);
- }
-
- @Override
- public final String getLogPath() {
- return onceJobAdapter.getLogPath();
- }
-
- public final void setLogPath(String logPath) {
- onceJobAdapter.setLogPath(logPath);
- }
-
- @Override
- public Integer getNextLogLineIdx() {
- return onceJobAdapter.getNextLogLineIdx();
- }
-
- public void setNextLogLineIdx(Integer nextLogLineIdx) {
- onceJobAdapter.setNextLogLineIdx(nextLogLineIdx);
- }
-
- @Override
- public Boolean hasNextLogLine() {
- return onceJobAdapter.hasNextLogLine();
- }
-
- @Override
- public void setHasNextLogLine(Boolean hasNextLogLine) {
- onceJobAdapter.setHasNextLogLine(hasNextLogLine);
- }
-
- @Override
- public List consumeResultContent() {
- return onceJobAdapter.consumeResultContent();
- }
-
- public void appendResultContent(LinkisResultSet resultContent) {
- onceJobAdapter.appendResultContent(resultContent);
- }
-
- @Override
- public Boolean hasNextResultPage() {
- return onceJobAdapter.hasNextResultPage();
- }
-
- public void setHasNextResultPage(Boolean hasNextResultPage) {
- onceJobAdapter.setHasNextResultPage(hasNextResultPage);
- }
-
- @Override
- public final String getResultLocation() {
- return onceJobAdapter.getResultLocation();
- }
-
- public final void setResultLocation(String resultLocation) {
- onceJobAdapter.setResultLocation(resultLocation);
- }
-
- @Override
- public String[] getResultSetPaths() {
- return onceJobAdapter.getResultSetPaths();
- }
-
- public final void setResultSetPaths(String[] resultSetPaths) {
- onceJobAdapter.setResultSetPaths(resultSetPaths);
- }
-
- @Override
- public void sendLogFin() {
- onceJobAdapter.sendLogFin();
- }
-
- @Override
- public boolean logFinReceived() {
- return onceJobAdapter.logFinReceived();
- }
-
- @Override
- public void sendResultFin() {
- onceJobAdapter.sendResultFin();
- }
-
- @Override
- public boolean resultFinReceived() {
- return onceJobAdapter.resultFinReceived();
- }
-
- @Override
- public boolean hasResult() {
- return hasResult;
- }
-
- @Override
- public void setHasResult(boolean hasResult) {
- this.hasResult = hasResult;
- }
-
- @Override
- public JobStatus getJobStatus() {
- return onceJobAdapter.getJobStatus();
- }
-
- public void setJobStatus(JobStatus jobStatus) {
- onceJobAdapter.setJobStatus(jobStatus);
- }
-
- @Override
- public String getJobID() {
- return onceJobAdapter.getJobID();
- }
-
- @Override
- public String getUser() {
- return onceJobAdapter.getUser();
- }
-
- @Override
- public String getMessage() {
- return onceJobAdapter.getMessage();
- }
-
- @Override
- public void setMessage(String message) {
- onceJobAdapter.setMessage(message);
- }
-
- @Override
- public Exception getException() {
- return onceJobAdapter.getException();
- }
-
- @Override
- public void setException(Exception e) {
- onceJobAdapter.setException(e);
- }
-
- @Override
- public String getExecID() {
- return onceJobAdapter.getJobID();
- } // No Need
-
- @Override
- public float getJobProgress() {
- return 0;
- }
-
- @Override
- public Integer getErrCode() {
- return onceJobAdapter.getErrCode();
- }
-
- @Override
- public String getErrDesc() {
- return onceJobAdapter.getErrDesc();
- }
-
- @Override
- public boolean isSuccess() {
- return onceJobAdapter.isSuccess();
- }
-
- @Override
- public void setSuccess(boolean success) {
- onceJobAdapter.setSuccess(success);
- }
-
- @Override
- public void updateByOperResult(LinkisOperResultAdapter adapter) {
- // No need
- }
-
- @Override
- public LinkisOnceJobData clone() throws CloneNotSupportedException {
- throw new CloneNotSupportedException();
- // return null;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/SimpleOnceJobAdapter.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/SimpleOnceJobAdapter.java
deleted file mode 100644
index 69a76d6240..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/interactor/job/data/SimpleOnceJobAdapter.java
+++ /dev/null
@@ -1,377 +0,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.apache.linkis.cli.application.interactor.job.data;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.constants.LinkisKeys;
-import org.apache.linkis.cli.application.interactor.job.LinkisJobStatus;
-import org.apache.linkis.cli.application.interactor.job.desc.LinkisOnceDesc;
-import org.apache.linkis.cli.application.observer.event.LinkisClientEvent;
-import org.apache.linkis.cli.application.observer.event.LogStartEvent;
-import org.apache.linkis.cli.application.observer.event.TriggerEvent;
-import org.apache.linkis.cli.application.observer.listener.LinkisClientListener;
-import org.apache.linkis.cli.application.observer.listener.TriggerEventListener;
-import org.apache.linkis.cli.application.operator.once.OnceJobConstants;
-import org.apache.linkis.cli.application.operator.ujes.LinkisOperResultAdapter;
-import org.apache.linkis.cli.application.operator.ujes.UJESClientFactory;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-import org.apache.linkis.cli.common.entity.var.VarAccess;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.LinkisClientExecutionException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.computation.client.LinkisJobBuilder$;
-import org.apache.linkis.computation.client.once.simple.SimpleOnceJob;
-import org.apache.linkis.computation.client.once.simple.SimpleOnceJobBuilder;
-import org.apache.linkis.computation.client.once.simple.SubmittableSimpleOnceJob;
-import org.apache.linkis.computation.client.operator.impl.EngineConnLogOperator;
-import org.apache.linkis.computation.client.operator.impl.EngineConnLogs;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.LinkedBlockingDeque;
-
-public class SimpleOnceJobAdapter implements LinkisLogData {
- LinkisJobStatus jobStatus = LinkisJobStatus.UNSUBMITTED;
- EngineConnLogOperator logOperator = null;
- private String serverUrl;
- private SimpleOnceJob onceJob;
- private String engineTypeForECM;
- private String message;
- private Exception exception;
- private boolean success;
- private Boolean incLogMode;
- private LinkedBlockingDeque logBuffer = new LinkedBlockingDeque();
- // private String logPath; // remote path for job log
- // private Integer nextLogLineIdx = 0;
- private Boolean hasNextLogLine = true;
- private String resultLocation;
- private String[] resultSetPaths = null; // remote paths for job result set
- private LinkedBlockingDeque resultContent = new LinkedBlockingDeque<>();
- private Boolean hasNextResultPage;
- private LinkisClientEvent logstartEvent = new LogStartEvent();
- private TriggerEvent logFinEvent = new TriggerEvent();
- private TriggerEventListener logFinListener = new TriggerEventListener();
- private TriggerEvent resultFinEvent = new TriggerEvent();
- private TriggerEventListener resultFinListener = new TriggerEventListener();
-
- {
- logFinEvent.register(logFinListener);
- resultFinEvent.register(resultFinListener);
- }
-
- public void init(LinkisOnceDesc desc) {
- VarAccess stdVarAccess = desc.getStdVarAccess();
- VarAccess sysVarAccess = desc.getSysVarAccess();
-
- serverUrl = stdVarAccess.getVar(String.class, AppKeys.LINKIS_COMMON_GATEWAY_URL);
-
- LinkisJobBuilder$.MODULE$.setDefaultClientConfig(
- UJESClientFactory.generateDWSClientConfig(stdVarAccess, sysVarAccess));
- LinkisJobBuilder$.MODULE$.setDefaultUJESClient(
- UJESClientFactory.getReusable(stdVarAccess, sysVarAccess));
-
- String engineTypeRaw = (String) desc.getLabelMap().get(LinkisKeys.KEY_ENGINETYPE);
- engineTypeForECM = engineTypeRaw;
-
- if (StringUtils.isNotBlank(engineTypeRaw)) {
- engineTypeForECM = StringUtils.split(engineTypeRaw, "-")[0];
- } else {
- engineTypeForECM = "";
- } // TODO: remove parsing and let server side parse engineType
-
- onceJob =
- new SimpleOnceJobBuilder()
- .setCreateService(AppConstants.LINKIS_CLI)
- .addExecuteUser(desc.getProxyUser())
- .setStartupParams(desc.getParamConfMap())
- .setLabels(desc.getLabelMap())
- .setRuntimeParams(desc.getParamRunTimeMap())
- .setSource(desc.getSourceMap())
- .setVariableMap(desc.getParamVarsMap())
- .setJobContent(desc.getJobContentMap())
- .build();
- }
-
- public String getServerUrl() {
- return serverUrl;
- }
-
- public SimpleOnceJob getOnceJob() {
- return onceJob;
- }
-
- public void setOnceJob(SimpleOnceJob onceJob) {
- this.onceJob = onceJob;
- }
-
- private void panicIfNull(Object obj) {
- if (obj == null) {
- throw new LinkisClientExecutionException(
- "EXE0040",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "Instance of " + obj.getClass().getCanonicalName() + " is null");
- }
- }
-
- public void submit() {
- panicIfNull(onceJob);
- if (!(onceJob instanceof SubmittableSimpleOnceJob)) {
- throw new LinkisClientExecutionException(
- "EXE0041",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionErr,
- "onceJob is not properly initiated");
- }
- ((SubmittableSimpleOnceJob) onceJob).submit();
- }
-
- public void kill() {
- panicIfNull(onceJob);
- onceJob.kill();
- }
-
- public String getJobID() {
- return onceJob.getId();
- }
-
- @Override
- public String getUser() {
- return "TODO";
- }
-
- public void updateStatus() {
- panicIfNull(onceJob);
- String status = onceJob.getStatus();
- panicIfNull(status);
- jobStatus = LinkisJobStatus.convertFromNodeStatusString(onceJob.getStatus());
- }
-
- public LinkisJobStatus getJobStatus() {
- return this.jobStatus;
- }
-
- public void setJobStatus(JobStatus jobStatus) {
- this.jobStatus = (LinkisJobStatus) jobStatus;
- }
-
- public void waitForComplete() {
- panicIfNull(onceJob);
- onceJob.waitForCompleted();
- }
-
- public void queryJobLogOneIteration() {
- panicIfNull(onceJob);
- updateStatus();
- if (logOperator == null) {
- logOperator =
- (EngineConnLogOperator) onceJob.getOperator(EngineConnLogOperator.OPERATOR_NAME());
- logOperator.setECMServiceInstance(
- ((SubmittableSimpleOnceJob) onceJob).getECMServiceInstance());
- logOperator.setEngineConnType(engineTypeForECM);
- // logOperator.setPageSize(OnceJobConstants.MAX_LOG_SIZE_ONCE);
- logOperator.setIgnoreKeywords(OnceJobConstants.LOG_IGNORE_KEYWORDS);
- }
- EngineConnLogs logs =
- (EngineConnLogs) logOperator.apply(); // for some reason we have to add type conversion,
- // otherwise mvn testCompile fails
- StringBuilder logBuilder = new StringBuilder();
- for (String log : logs.logs()) {
- logBuilder.append(log).append(System.lineSeparator());
- }
- appendLog(logBuilder.toString());
- if ((logs.logs() == null || logs.logs().size() <= 0) && jobStatus.isJobFinishedState()) {
- setHasNextLogLine(false);
- }
- // System.out.println(logs.logs().size());
- }
-
- public void registerincLogListener(LinkisClientListener observer) {
- this.logstartEvent.register(observer);
- }
-
- public void notifyLogListener() {
- if (this.logstartEvent.isRegistered()) {
- logstartEvent.notifyObserver(logstartEvent, this);
- }
- }
-
- public boolean isIncLogMode() {
- return this.incLogMode;
- }
-
- public void setIncLogMode(boolean incLogMode) {
- this.incLogMode = incLogMode;
- }
-
- public String consumeLog() {
- List logs = new LinkedList<>();
- this.logBuffer.drainTo(logs, this.logBuffer.size());
- StringBuilder tmp = new StringBuilder();
- for (String str : logs) {
- tmp.append(str);
- }
- return tmp.toString();
- }
-
- public void appendLog(String log) {
- this.logBuffer.add(log);
- }
-
- public final String getLogPath() {
- return null;
- }
-
- public final void setLogPath(String logPath) {
- return;
- }
-
- public Integer getNextLogLineIdx() {
- return null;
- }
-
- public void setNextLogLineIdx(Integer nextLogLineIdx) {
- return;
- }
-
- public Boolean hasNextLogLine() {
- return hasNextLogLine;
- }
-
- public void setHasNextLogLine(Boolean hasNextLogLine) {
- this.hasNextLogLine = hasNextLogLine;
- }
-
- public List consumeResultContent() {
- List ret = new LinkedList<>();
- resultContent.drainTo(ret, resultContent.size());
- return ret;
- }
-
- public void appendResultContent(LinkisResultSet resultContent) {
- this.resultContent.add(resultContent);
- }
-
- public Boolean hasNextResultPage() {
- return hasNextResultPage;
- }
-
- public void setHasNextResultPage(Boolean hasNextResultPage) {
- this.hasNextResultPage = hasNextResultPage;
- }
-
- public final String getResultLocation() {
- return resultLocation;
- }
-
- public final void setResultLocation(String resultLocation) {
- this.resultLocation = resultLocation;
- }
-
- public String[] getResultSetPaths() {
- return resultSetPaths;
- }
-
- public final void setResultSetPaths(String[] resultSetPaths) {
- this.resultSetPaths = resultSetPaths;
- }
-
- public void sendLogFin() {
- if (this.logFinEvent != null && this.logFinEvent.isRegistered()) {
- this.logFinEvent.notifyObserver(resultFinEvent, null);
- }
- }
-
- public boolean logFinReceived() {
- return this.logFinListener.isTriggered();
- }
-
- public void sendResultFin() {
- if (this.resultFinEvent != null && this.resultFinEvent.isRegistered()) {
- this.resultFinEvent.notifyObserver(resultFinEvent, null);
- }
- }
-
- public boolean resultFinReceived() {
- return this.resultFinListener.isTriggered();
- }
-
- @Override
- public String getMessage() {
- return message;
- }
-
- @Override
- public void setMessage(String message) {
- this.message = message;
- }
-
- @Override
- public Exception getException() {
- return exception;
- }
-
- @Override
- public void setException(Exception e) {
- this.exception = e;
- }
-
- @Override
- public String getExecID() {
- return getJobID();
- } // No Need
-
- @Override
- public float getJobProgress() {
- return 0;
- }
-
- @Override
- public Integer getErrCode() {
- return null;
- }
-
- @Override
- public String getErrDesc() {
- return null;
- }
-
- @Override
- public boolean isSuccess() {
- return success;
- }
-
- @Override
- public void setSuccess(boolean success) {
- this.success = success;
- }
-
- @Override
- public void updateByOperResult(LinkisOperResultAdapter adapter) {
- // No need
- }
-
- @Override
- public LinkisLogData clone() throws CloneNotSupportedException {
- throw new CloneNotSupportedException();
- // return null;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/operator/OperatorUtils.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/operator/OperatorUtils.java
deleted file mode 100644
index 767d44aea1..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/operator/OperatorUtils.java
+++ /dev/null
@@ -1,70 +0,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.apache.linkis.cli.application.operator;
-
-public class OperatorUtils {
- public static int getNumOfLines(String str) {
- if (str == null || str.length() == 0) {
- return 0;
- }
- int lines = 1;
- int len = str.length();
- for (int pos = 0; pos < len; pos++) {
- char c = str.charAt(pos);
- if (c == '\r') {
- lines++;
- if (pos + 1 < len && str.charAt(pos + 1) == '\n') {
- pos++;
- }
- } else if (c == '\n') {
- lines++;
- }
- }
- return lines;
- }
-
- public static int getFirstIndexSkippingLines(String str, Integer lines) {
- if (str == null || str.length() == 0 || lines < 0) {
- return -1;
- }
- if (lines == 0) {
- return 0;
- }
-
- int curLineIdx = 0;
- int len = str.length();
- for (int pos = 0; pos < len; pos++) {
- char c = str.charAt(pos);
- if (c == '\r') {
- curLineIdx++;
- if (pos + 1 < len && str.charAt(pos + 1) == '\n') {
- pos++;
- }
- } else if (c == '\n') {
- curLineIdx++;
- } else {
- continue;
- }
-
- if (curLineIdx >= lines) {
- return pos + 1;
- }
- }
- return -1;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/LinkisResultInfoPresenter.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/LinkisResultInfoPresenter.java
deleted file mode 100644
index 5a953fa5d7..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/LinkisResultInfoPresenter.java
+++ /dev/null
@@ -1,114 +0,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.apache.linkis.cli.application.present;
-
-import org.apache.linkis.cli.application.present.model.LinkisResultInfoModel;
-import org.apache.linkis.cli.common.entity.present.Model;
-import org.apache.linkis.cli.common.entity.present.PresentWay;
-import org.apache.linkis.cli.common.entity.present.Presenter;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.PresenterException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.present.PresentModeImpl;
-import org.apache.linkis.cli.core.present.display.DisplayOperFactory;
-import org.apache.linkis.cli.core.present.display.data.StdoutDisplayData;
-import org.apache.linkis.cli.core.utils.LogUtils;
-
-import org.apache.commons.lang3.StringUtils;
-
-public class LinkisResultInfoPresenter implements Presenter {
- @Override
- public void present(Model model, PresentWay presentWay) {
- if (!(model instanceof LinkisResultInfoModel)) {
- throw new PresenterException(
- "PST0001",
- ErrorLevel.ERROR,
- CommonErrMsg.PresenterErr,
- "Input model for \"LinkisResultInfoPresenter\" is not instance of \"LinkisResultInfoModel\"");
- }
- DisplayOperFactory.getDisplayOper(PresentModeImpl.STDOUT)
- .doOutput(new StdoutDisplayData(formatResultIndicator((LinkisResultInfoModel) model)));
- }
-
- protected String formatResultIndicator(LinkisResultInfoModel model) {
- StringBuilder infoBuilder = new StringBuilder();
- String extraMsgStr = "";
-
- if (model.getMessage() != null) {
- extraMsgStr = model.getMessage().toString();
- }
- if (model.getJobStatus().isJobSuccess()) {
-
- LogUtils.getInformationLogger().info("Job execute successfully! Will try get execute result");
- infoBuilder
- .append("============Result:================")
- .append(System.lineSeparator())
- .append("TaskId:")
- .append(model.getJobID())
- .append(System.lineSeparator())
- .append("ExecId: ")
- .append(model.getExecID())
- .append(System.lineSeparator())
- .append("User:")
- .append(model.getUser())
- .append(System.lineSeparator())
- .append("Current job status:")
- .append(model.getJobStatus())
- .append(System.lineSeparator())
- .append("extraMsg: ")
- .append(extraMsgStr)
- .append(System.lineSeparator())
- .append("result: ")
- .append(extraMsgStr)
- .append(System.lineSeparator());
- } else if (model.getJobStatus().isJobFinishedState()) {
- LogUtils.getInformationLogger().info("Job failed! Will not try get execute result.");
- infoBuilder
- .append("============Result:================")
- .append(System.lineSeparator())
- .append("TaskId:")
- .append(model.getJobID())
- .append(System.lineSeparator())
- .append("ExecId: ")
- .append(model.getExecID())
- .append(System.lineSeparator())
- .append("User:")
- .append(model.getUser())
- .append(System.lineSeparator())
- .append("Current job status:")
- .append(model.getJobStatus())
- .append(System.lineSeparator())
- .append("extraMsg: ")
- .append(extraMsgStr)
- .append(System.lineSeparator());
- if (model.getErrCode() != null) {
- infoBuilder.append("errCode: ").append(model.getErrCode()).append(System.lineSeparator());
- }
- if (StringUtils.isNotBlank(model.getErrDesc())) {
- infoBuilder.append("errDesc: ").append(model.getErrDesc()).append(System.lineSeparator());
- }
- } else {
- throw new PresenterException(
- "PST0011",
- ErrorLevel.ERROR,
- CommonErrMsg.PresenterErr,
- "Job is not completed but triggered ResultPresenter");
- }
- return infoBuilder.toString();
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/LinkisResultPresenter.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/LinkisResultPresenter.java
deleted file mode 100644
index b5e39c4e2e..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/LinkisResultPresenter.java
+++ /dev/null
@@ -1,232 +0,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.apache.linkis.cli.application.present;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.interactor.job.data.LinkisResultSet;
-import org.apache.linkis.cli.application.present.model.LinkisResultModel;
-import org.apache.linkis.cli.common.entity.present.Model;
-import org.apache.linkis.cli.common.entity.present.PresentWay;
-import org.apache.linkis.cli.common.entity.present.Presenter;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.PresenterException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.present.PresentModeImpl;
-import org.apache.linkis.cli.core.present.PresentWayImpl;
-import org.apache.linkis.cli.core.present.display.DisplayOperFactory;
-import org.apache.linkis.cli.core.present.display.DisplayOperator;
-import org.apache.linkis.cli.core.present.display.data.FileDisplayData;
-import org.apache.linkis.cli.core.utils.CommonUtils;
-import org.apache.linkis.cli.core.utils.LogUtils;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.text.MessageFormat;
-import java.util.*;
-
-public class LinkisResultPresenter implements Presenter {
-
- @Override
- public void present(Model model, PresentWay presentWay) {
- if (!(model instanceof LinkisResultModel)) {
- throw new PresenterException(
- "PST0001",
- ErrorLevel.ERROR,
- CommonErrMsg.PresenterErr,
- "Input model for \"LinkisResultPresenter\" is not instance of \"LinkisResultModel\"");
- }
- if (!(presentWay instanceof PresentWayImpl)) {
- throw new PresenterException(
- "PST0002",
- ErrorLevel.ERROR,
- CommonErrMsg.PresenterErr,
- "Input PresentWay for \"LinkisResultPresenter\" is not instance of \"PresentWayImpl\"");
- }
- LinkisResultModel resultModel = (LinkisResultModel) model;
- PresentWayImpl presentWay1 = (PresentWayImpl) presentWay;
-
- if (!resultModel.getJobStatus().isJobSuccess()) {
- LogUtils.getInformationLogger()
- .info("JobStatus is not \'success\'. Will not retrieve result-set.");
- return;
- }
- String msg = "";
- if (resultModel.hasResult()) {
- msg =
- "Retrieving result-set, may take time if result-set is large, please do not exit program.";
- } else {
- msg = "Your job has no result.";
- }
- LogUtils.getInformationLogger().info(msg);
-
- final DisplayOperator displayOperator =
- DisplayOperFactory.getDisplayOper(
- presentWay1.getMode()); // currently we don't allow printing log to file here
-
- int preIdx = -1;
- StringBuilder resultSb = new StringBuilder();
-
- while (!resultModel.resultFinReceived()) {
- preIdx = presentOneIteration(resultModel, preIdx, presentWay1, resultSb, displayOperator);
- CommonUtils.doSleepQuietly(500l);
- }
- presentOneIteration(resultModel, preIdx, presentWay1, resultSb, displayOperator);
-
- if (presentWay1.getMode() == PresentModeImpl.TEXT_FILE
- || StringUtils.isNotBlank(presentWay1.getPath())) {
- LogUtils.getInformationLogger()
- .info("ResultSet has been successfully written to path: " + presentWay1.getPath());
- }
- }
-
- protected int presentOneIteration(
- LinkisResultModel resultModel,
- int preIdx,
- PresentWayImpl presentWay,
- StringBuilder resultSb,
- DisplayOperator displayOperator) {
- List linkisResultSets = resultModel.consumeResultContent();
- if (linkisResultSets != null && !linkisResultSets.isEmpty()) {
- for (LinkisResultSet c : linkisResultSets) {
- int idxResultset = c.getResultsetIdx();
- /**
- * Notice: we assume result-sets are visited one by one in non-descending order!!! i.e.
- * either idxResultset == preIdx or idxResultset - preIdx == 1 i.e. resultsets[0] ->
- * resultsets[1] -> ...
- */
- if (idxResultset - preIdx != 0 && idxResultset - preIdx != 1) {
- throw new PresenterException(
- "PST0002",
- ErrorLevel.ERROR,
- CommonErrMsg.PresenterErr,
- "Linkis resultsets are visited in descending order or are not visited one-by-one");
- }
-
- boolean flag = idxResultset > preIdx;
- if (presentWay.isDisplayMetaAndLogo()) {
- if (idxResultset - preIdx == 1) {
- resultSb.setLength(0);
- resultSb
- .append(MessageFormat.format(AppConstants.RESULTSET_LOGO, idxResultset + 1))
- .append(System.lineSeparator());
- if (c.getResultMeta() != null) {
- resultSb
- .append(AppConstants.RESULTSET_META_BEGIN_LOGO)
- .append(System.lineSeparator());
- resultSb.append(formatResultMeta(c.getResultMeta()));
- resultSb.append(AppConstants.RESULTSET_META_END_LOGO).append(System.lineSeparator());
- }
- }
- }
- preIdx = idxResultset;
- String contentStr = formatResultContent(c.getResultMeta(), c.getContent());
- if (contentStr != null) {
- resultSb.append(contentStr);
- }
- if (resultSb.length() != 0) {
- String resultFileName =
- resultModel.getUser()
- + "-task-"
- + resultModel.getJobID()
- + "-result-"
- + String.valueOf(idxResultset + 1)
- + ".txt";
- displayOperator.doOutput(
- new FileDisplayData(presentWay.getPath(), resultFileName, resultSb.toString(), flag));
- resultSb.setLength(0);
- }
- }
- }
- return preIdx;
- }
-
- protected String formatResultMeta(List> metaData) {
-
- StringBuilder outputBuilder = new StringBuilder();
-
- if (metaData == null || metaData.size() == 0) {
- return null;
- }
-
- List titles = new ArrayList<>();
-
- // gather keys as title
- for (LinkedHashMap mapElement : metaData) {
- if (mapElement == null || mapElement.size() == 0) {
- continue;
- }
-
- Set> entrySet = mapElement.entrySet();
- if (entrySet == null) {
- break;
- }
- for (Map.Entry entry : entrySet) {
- String key = entry.getKey();
- if (key != null && !titles.contains(key)) {
- titles.add(key);
- outputBuilder.append(key).append("\t");
- }
- }
- }
-
- outputBuilder.append(System.lineSeparator());
-
- // gather value and print to output
- for (LinkedHashMap mapElement : metaData) {
- if (mapElement == null || mapElement.size() == 0) {
- continue;
- }
- String candidate;
- for (String title : titles) {
- if (mapElement.containsKey(title)) {
- candidate = mapElement.get(title);
- } else {
- candidate = "NULL";
- }
- outputBuilder.append(candidate).append("\t");
- }
- outputBuilder.append(System.lineSeparator());
- }
- return outputBuilder.toString();
- }
-
- protected String formatResultContent(
- List> metaData, List> contentData) {
-
- StringBuilder outputBuilder = new StringBuilder();
- if (contentData == null || contentData.size() == 0) { // finished
- return null;
- }
-
- int listLen = contentData.size();
- for (int i = 0; i < listLen; i++) {
- List listElement = contentData.get(i);
- if (listElement == null || listElement.size() == 0) {
- continue;
- }
- for (String element : listElement) {
- outputBuilder.append(element).append("\t");
- }
- if (i < listLen - 1) {
- outputBuilder.append(System.lineSeparator());
- }
- }
-
- return outputBuilder.toString();
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisJobInfoModel.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisJobInfoModel.java
deleted file mode 100644
index acfc392e48..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisJobInfoModel.java
+++ /dev/null
@@ -1,97 +0,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.apache.linkis.cli.application.present.model;
-
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobDataImpl;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-import org.apache.linkis.cli.common.entity.present.Model;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.TransformerException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-
-import org.apache.commons.lang3.exception.ExceptionUtils;
-
-import java.util.Date;
-
-public class LinkisJobInfoModel implements Model {
-
- private String cid;
- private String jobId;
- private String message;
- private String exception;
- private String cause;
-
- private String taskID;
- private String instance;
- private String simpleExecId;
- private String execId;
- private String umUser;
- private String executionCode;
- private String logPath;
- private JobStatus status;
- private String engineType;
- private String runType;
- private Long costTime;
- private Date createdTime;
- private Date updatedTime;
- private Date engineStartTime;
- private Integer errCode;
- private String errMsg;
- private String executeApplicationName;
- private String requestApplicationName;
- private Float progress;
-
- @Override
- public void buildModel(Object data) {
- if (!(data instanceof LinkisJobDataImpl)) {
- throw new TransformerException(
- "TFM0010",
- ErrorLevel.ERROR,
- CommonErrMsg.TransformerException,
- "Failed to init LinkisJobInfoModel: "
- + data.getClass().getCanonicalName()
- + "is not instance of \"LinkisJobDataImpl\"");
- }
- this.jobId = ((LinkisJobDataImpl) data).getJobID();
- this.message = ((LinkisJobDataImpl) data).getMessage();
- this.taskID = ((LinkisJobDataImpl) data).getJobID();
- this.instance = ((LinkisJobDataImpl) data).getInstance();
- this.simpleExecId = ((LinkisJobDataImpl) data).getSimpleExecId();
- this.execId = ((LinkisJobDataImpl) data).getExecID();
- this.umUser = ((LinkisJobDataImpl) data).getUmUser();
- this.executionCode = ((LinkisJobDataImpl) data).getExecutionCode();
- this.logPath = ((LinkisJobDataImpl) data).getLogPath();
- this.status = ((LinkisJobDataImpl) data).getJobStatus();
- this.engineType = ((LinkisJobDataImpl) data).getEngineType();
- this.runType = ((LinkisJobDataImpl) data).getRunType();
- this.costTime = ((LinkisJobDataImpl) data).getCostTime();
- this.createdTime = ((LinkisJobDataImpl) data).getCreatedTime();
- this.updatedTime = ((LinkisJobDataImpl) data).getUpdatedTime();
- this.engineStartTime = ((LinkisJobDataImpl) data).getEngineStartTime();
- this.errCode = ((LinkisJobDataImpl) data).getErrCode();
- this.errMsg = ((LinkisJobDataImpl) data).getErrDesc();
- this.executeApplicationName = ((LinkisJobDataImpl) data).getExecuteApplicationName();
- this.requestApplicationName = ((LinkisJobDataImpl) data).getRequestApplicationName();
- this.progress = ((LinkisJobDataImpl) data).getJobProgress();
- Exception e = ((LinkisJobDataImpl) data).getException();
- if (e != null) {
- this.exception = ExceptionUtils.getMessage(e);
- this.cause = ExceptionUtils.getRootCauseMessage(e);
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisJobKillModel.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisJobKillModel.java
deleted file mode 100644
index 95eb7d03c2..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisJobKillModel.java
+++ /dev/null
@@ -1,63 +0,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.apache.linkis.cli.application.present.model;
-
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobDataImpl;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-import org.apache.linkis.cli.common.entity.present.Model;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.TransformerException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-
-import org.apache.commons.lang3.exception.ExceptionUtils;
-
-public class LinkisJobKillModel implements Model {
-
- private String cid;
- private String jobId;
- private String message;
- private String exception;
- private String cause;
-
- private String execID;
- private String user;
- private JobStatus jobStatus;
-
- @Override
- public void buildModel(Object data) {
- if (!(data instanceof LinkisJobDataImpl)) {
- throw new TransformerException(
- "TFM0010",
- ErrorLevel.ERROR,
- CommonErrMsg.TransformerException,
- "Failed to init LinkisJobKillModel: "
- + data.getClass().getCanonicalName()
- + "is not instance of \"LinkisJobDataImpl\"");
- }
- this.jobId = ((LinkisJobDataImpl) data).getJobID();
- this.message = ((LinkisJobDataImpl) data).getMessage();
- this.execID = ((LinkisJobDataImpl) data).getExecID();
- this.user = ((LinkisJobDataImpl) data).getUser();
- this.jobStatus = ((LinkisJobDataImpl) data).getJobStatus();
- Exception e = ((LinkisJobDataImpl) data).getException();
- if (e != null) {
- this.exception = ExceptionUtils.getMessage(e);
- this.cause = ExceptionUtils.getRootCauseMessage(e);
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisResultInfoModel.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisResultInfoModel.java
deleted file mode 100644
index bfa0ae6cc8..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisResultInfoModel.java
+++ /dev/null
@@ -1,84 +0,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.apache.linkis.cli.application.present.model;
-
-import org.apache.linkis.cli.application.interactor.job.data.LinkisResultData;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-import org.apache.linkis.cli.common.entity.present.Model;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.TransformerException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-
-public class LinkisResultInfoModel implements Model {
- private String jobID;
- private String execID;
- private String user;
- private JobStatus jobStatus;
- private String message;
- private Integer errCode;
- private String errDesc;
-
- @Override
- public void buildModel(Object data) {
- if (!(data instanceof LinkisResultData)) {
- throw new TransformerException(
- "TFM0010",
- ErrorLevel.ERROR,
- CommonErrMsg.TransformerException,
- "Failed to init LinkisResultInfoModel: "
- + data.getClass().getCanonicalName()
- + "is not instance of \"LinkisResultData\"");
- }
- LinkisResultData jobData = (LinkisResultData) data;
- jobID = jobData.getJobID();
- execID = jobData.getExecID();
- user = jobData.getUser();
- jobStatus = jobData.getJobStatus();
- message = jobData.getMessage();
- errCode = jobData.getErrCode();
- errDesc = jobData.getErrDesc();
- }
-
- public String getJobID() {
- return jobID;
- }
-
- public String getExecID() {
- return execID;
- }
-
- public String getUser() {
- return user;
- }
-
- public JobStatus getJobStatus() {
- return jobStatus;
- }
-
- public String getMessage() {
- return message;
- }
-
- public Integer getErrCode() {
- return errCode;
- }
-
- public String getErrDesc() {
- return errDesc;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisSubmitResultModel.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisSubmitResultModel.java
deleted file mode 100644
index 6b622e1453..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/present/model/LinkisSubmitResultModel.java
+++ /dev/null
@@ -1,56 +0,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.apache.linkis.cli.application.present.model;
-
-import org.apache.linkis.cli.application.interactor.job.data.LinkisJobDataImpl;
-import org.apache.linkis.cli.common.entity.job.JobStatus;
-import org.apache.linkis.cli.common.entity.present.Model;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.TransformerException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-
-import org.apache.commons.lang3.exception.ExceptionUtils;
-
-public class LinkisSubmitResultModel implements Model {
- private String jobId;
- private JobStatus status;
- private String message;
- private String exception;
- private String cause;
-
- @Override
- public void buildModel(Object data) {
- if (!(data instanceof LinkisJobDataImpl)) {
- throw new TransformerException(
- "TFM0010",
- ErrorLevel.ERROR,
- CommonErrMsg.TransformerException,
- "Failed to init LinkisJobInfoModel: "
- + data.getClass().getCanonicalName()
- + "is not instance of \"LinkisJobDataImpl\"");
- }
- this.jobId = ((LinkisJobDataImpl) data).getJobID();
- this.status = ((LinkisJobDataImpl) data).getJobStatus();
- this.message = ((LinkisJobDataImpl) data).getMessage();
- Exception e = ((LinkisJobDataImpl) data).getException();
- if (e != null) {
- this.exception = ExceptionUtils.getMessage(e);
- this.cause = ExceptionUtils.getRootCauseMessage(e);
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/suite/ExecutionSuite.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/suite/ExecutionSuite.java
deleted file mode 100644
index 8b05a7cf78..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/suite/ExecutionSuite.java
+++ /dev/null
@@ -1,61 +0,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.apache.linkis.cli.application.suite;
-
-import org.apache.linkis.cli.common.entity.execution.Execution;
-import org.apache.linkis.cli.common.entity.job.Job;
-import org.apache.linkis.cli.common.entity.result.ResultHandler;
-
-import java.util.Map;
-
-public class ExecutionSuite {
- Execution execution;
- Map jobs;
- ResultHandler[] resultHandlers;
-
- public ExecutionSuite(
- Execution execution, Map jobs, ResultHandler... resultHandlers) {
- this.execution = execution;
- this.jobs = jobs;
- this.resultHandlers = resultHandlers;
- }
-
- public Execution getExecution() {
- return execution;
- }
-
- public void setExecution(Execution execution) {
- this.execution = execution;
- }
-
- public Map getJobs() {
- return jobs;
- }
-
- public void setJobs(Map jobs) {
- this.jobs = jobs;
- }
-
- public ResultHandler[] getResultHandlers() {
- return resultHandlers;
- }
-
- public void setResultHandlers(ResultHandler[] resultHandlers) {
- this.resultHandlers = resultHandlers;
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/suite/ExecutionSuiteFactory.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/suite/ExecutionSuiteFactory.java
deleted file mode 100644
index c55ee7b9e4..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/suite/ExecutionSuiteFactory.java
+++ /dev/null
@@ -1,225 +0,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.apache.linkis.cli.application.suite;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.interactor.command.LinkisCmdType;
-import org.apache.linkis.cli.application.interactor.job.builder.LinkisManageJobBuilder;
-import org.apache.linkis.cli.application.interactor.job.builder.LinkisOnceJobBuilder;
-import org.apache.linkis.cli.application.interactor.job.builder.LinkisSubmitJobBuilder;
-import org.apache.linkis.cli.application.interactor.job.subtype.LinkisManSubType;
-import org.apache.linkis.cli.application.interactor.job.subtype.LinkisSubmitSubType;
-import org.apache.linkis.cli.application.interactor.validate.LinkisManageValidator;
-import org.apache.linkis.cli.application.interactor.validate.LinkisOnceSubmitValidator;
-import org.apache.linkis.cli.application.interactor.validate.LinkisSubmitValidator;
-import org.apache.linkis.cli.application.present.LinkisLogPresenter;
-import org.apache.linkis.cli.application.present.LinkisResultInfoPresenter;
-import org.apache.linkis.cli.application.present.LinkisResultPresenter;
-import org.apache.linkis.cli.application.present.model.LinkisJobInfoModel;
-import org.apache.linkis.cli.application.present.model.LinkisJobKillModel;
-import org.apache.linkis.cli.application.present.model.LinkisResultInfoModel;
-import org.apache.linkis.cli.application.present.model.LinkisResultModel;
-import org.apache.linkis.cli.application.utils.Utils;
-import org.apache.linkis.cli.common.entity.command.CmdType;
-import org.apache.linkis.cli.common.entity.execution.Execution;
-import org.apache.linkis.cli.common.entity.job.Job;
-import org.apache.linkis.cli.common.entity.job.JobData;
-import org.apache.linkis.cli.common.entity.job.JobDescription;
-import org.apache.linkis.cli.common.entity.job.JobSubType;
-import org.apache.linkis.cli.common.entity.operator.JobOperator;
-import org.apache.linkis.cli.common.entity.present.PresentWay;
-import org.apache.linkis.cli.common.entity.result.ResultHandler;
-import org.apache.linkis.cli.common.entity.validate.Validator;
-import org.apache.linkis.cli.common.entity.var.VarAccess;
-import org.apache.linkis.cli.common.exception.error.ErrorLevel;
-import org.apache.linkis.cli.core.exception.LinkisClientExecutionException;
-import org.apache.linkis.cli.core.exception.error.CommonErrMsg;
-import org.apache.linkis.cli.core.interactor.execution.AsyncSubmission;
-import org.apache.linkis.cli.core.interactor.execution.Help;
-import org.apache.linkis.cli.core.interactor.execution.JobManagement;
-import org.apache.linkis.cli.core.interactor.execution.SyncSubmission;
-import org.apache.linkis.cli.core.interactor.job.JobBuilder;
-import org.apache.linkis.cli.core.interactor.result.DefaultResultHandler;
-import org.apache.linkis.cli.core.interactor.result.PresentResultHandler;
-import org.apache.linkis.cli.core.present.DefaultStdOutPresenter;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ExecutionSuiteFactory {
- private static Logger logger = LoggerFactory.getLogger(ExecutionSuiteFactory.class);
-
- public static ExecutionSuite getSuite(
- CmdType cmdType, VarAccess stdVarAccess, VarAccess sysVarAccess) {
-
- ExecutionSuite suite;
- Execution execution;
- Map jobs = new HashMap<>();
- JobSubType subType;
- JobBuilder jobBuilder;
- Validator validator;
- ResultHandler defaultHandler = new DefaultResultHandler();
-
- /*
- Prepare Builders and command-specific components
- */
- if (cmdType == LinkisCmdType.UNIVERSAL) {
- if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_KILL_OPT)) {
- execution = new JobManagement();
- jobBuilder = new LinkisManageJobBuilder();
- PresentResultHandler handler = new PresentResultHandler();
- handler.setPresenter(new DefaultStdOutPresenter());
- handler.setModel(new LinkisJobKillModel());
- validator = new LinkisManageValidator();
- subType = LinkisManSubType.KILL;
- suite = new ExecutionSuite(execution, jobs, handler, defaultHandler);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_STATUS_OPT)) {
- execution = new JobManagement();
- jobBuilder = new LinkisManageJobBuilder();
- PresentResultHandler handler = new PresentResultHandler();
- handler.setPresenter(new DefaultStdOutPresenter());
- handler.setModel(new LinkisJobInfoModel());
- validator = new LinkisManageValidator();
- subType = LinkisManSubType.STATUS;
- suite = new ExecutionSuite(execution, jobs, handler, defaultHandler);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_LOG_OPT)) {
- execution = new JobManagement();
- jobBuilder = new LinkisManageJobBuilder().setLogListener(new LinkisLogPresenter());
- validator = new LinkisManageValidator();
- subType = LinkisManSubType.LOG;
- suite = new ExecutionSuite(execution, jobs, null, defaultHandler);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_RESULT_OPT)) {
- execution = new JobManagement();
- jobBuilder = new LinkisManageJobBuilder();
- PresentResultHandler handler = new PresentResultHandler();
- handler.setPresenter(new LinkisResultPresenter());
- handler.setModel(new LinkisResultModel());
- validator = new LinkisManageValidator();
- subType = LinkisManSubType.RESULT;
- suite = new ExecutionSuite(execution, jobs, handler, defaultHandler);
- } else if (stdVarAccess.hasVar(AppKeys.LINKIS_CLIENT_HELP_OPT)) {
- execution = new Help();
- jobs.put(
- "help",
- new Job() {
- @Override
- public String getCid() {
- return null;
- }
-
- @Override
- public CmdType getCmdType() {
- return cmdType;
- }
-
- @Override
- public JobSubType getSubType() {
- return null;
- }
-
- @Override
- public JobDescription getJobDesc() {
- return null;
- }
-
- @Override
- public JobData getJobData() {
- return null;
- }
-
- @Override
- public JobOperator getJobOperator() {
- return null;
- }
-
- @Override
- public PresentWay getPresentWay() {
- return null;
- }
- });
- return new ExecutionSuite(execution, jobs, null, defaultHandler);
- } else {
- Boolean asyncSubmission =
- stdVarAccess.getVarOrDefault(Boolean.class, AppKeys.LINKIS_CLIENT_ASYNC_OPT, false);
- if (asyncSubmission) {
- execution = new AsyncSubmission();
- PresentResultHandler handler = new PresentResultHandler();
- handler.setPresenter(new DefaultStdOutPresenter());
- handler.setModel(new LinkisJobInfoModel());
- jobBuilder = new LinkisSubmitJobBuilder().setAsync(true);
- subType = LinkisSubmitSubType.SUBMIT;
- suite = new ExecutionSuite(execution, jobs, handler, defaultHandler);
- validator = new LinkisSubmitValidator();
- } else {
- execution = new SyncSubmission();
- subType = LinkisSubmitSubType.SUBMIT;
- PresentResultHandler handler1 = new PresentResultHandler();
- handler1.setPresenter(new LinkisResultInfoPresenter());
- handler1.setModel(new LinkisResultInfoModel());
- PresentResultHandler handler2 = new PresentResultHandler();
- handler2.setPresenter(new LinkisResultPresenter());
- handler2.setModel(new LinkisResultModel());
-
- String mode =
- stdVarAccess.getVarOrDefault(
- String.class, AppKeys.LINKIS_CLIENT_MODE_OPT, AppConstants.UJES_MODE);
- if (StringUtils.equalsIgnoreCase(mode, AppConstants.ONCE_MODE)) {
- jobBuilder = new LinkisOnceJobBuilder().setLogListener(new LinkisLogPresenter());
- ;
- validator = new LinkisOnceSubmitValidator();
- } else {
- jobBuilder = new LinkisSubmitJobBuilder().setLogListener(new LinkisLogPresenter());
- validator = new LinkisSubmitValidator();
- }
- suite = new ExecutionSuite(execution, jobs, handler1, handler2, defaultHandler);
- }
- }
- /*
- build job
- */
- Job job =
- jobBuilder
- .setCid(AppConstants.DUMMY_CID) // currently we don't need this
- .setCmdType(cmdType)
- .setJobSubType(subType)
- .setStdVarAccess(stdVarAccess)
- .setSysVarAccess(sysVarAccess)
- .build();
- logger.info("==========JOB============\n" + Utils.GSON.toJson(job.getJobDesc()));
- if (validator != null) {
- validator.doValidation(job);
- }
-
- jobs.put(job.getCid(), job);
-
- return suite;
- } else {
- throw new LinkisClientExecutionException(
- "EXE0029",
- ErrorLevel.ERROR,
- CommonErrMsg.ExecutionInitErr,
- "Command Type is not supported");
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/utils/Utils.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/utils/Utils.java
deleted file mode 100644
index e70c32a37b..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/main/java/org/apache/linkis/cli/application/utils/Utils.java
+++ /dev/null
@@ -1,52 +0,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.apache.linkis.cli.application.utils;
-
-import org.apache.commons.lang3.StringUtils;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class Utils {
-
- public static final Gson GSON =
- new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
- private static final Logger logger = LoggerFactory.getLogger(Utils.class);
-
- public static boolean isValidExecId(String execId) {
- boolean ret = false;
- if (StringUtils.isNotBlank(execId)) {
- ret = true;
- }
- return ret;
- }
-
- public static String progressInPercentage(float progress) {
- return String.valueOf(progress * 100) + "%";
- }
-
- public static void doSleepQuietly(Long sleepMills) {
- try {
- Thread.sleep(sleepMills);
- } catch (Exception ignore) {
- // ignored
- }
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/test/java/org/apache/linkis/cli/application/interactor/command/template/ProcessInputUtil.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/test/java/org/apache/linkis/cli/application/interactor/command/template/ProcessInputUtil.java
deleted file mode 100644
index 33af32bb4b..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/test/java/org/apache/linkis/cli/application/interactor/command/template/ProcessInputUtil.java
+++ /dev/null
@@ -1,127 +0,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.apache.linkis.cli.application.interactor.command.template;
-
-import org.apache.linkis.cli.application.constants.AppConstants;
-import org.apache.linkis.cli.application.constants.AppKeys;
-import org.apache.linkis.cli.application.data.ProcessedData;
-import org.apache.linkis.cli.application.utils.Utils;
-import org.apache.linkis.cli.common.entity.command.CmdTemplate;
-import org.apache.linkis.cli.common.entity.command.Params;
-import org.apache.linkis.cli.common.entity.properties.ClientProperties;
-import org.apache.linkis.cli.common.entity.var.VarAccess;
-import org.apache.linkis.cli.core.constants.CommonConstants;
-import org.apache.linkis.cli.core.interactor.command.fitter.SingleTplFitter;
-import org.apache.linkis.cli.core.interactor.command.parser.Parser;
-import org.apache.linkis.cli.core.interactor.command.parser.SingleCmdParser;
-import org.apache.linkis.cli.core.interactor.command.parser.result.ParseResult;
-import org.apache.linkis.cli.core.interactor.properties.PropertiesLoader;
-import org.apache.linkis.cli.core.interactor.properties.PropsFilesScanner;
-import org.apache.linkis.cli.core.interactor.properties.StdPropsLoader;
-import org.apache.linkis.cli.core.interactor.properties.reader.PropertiesReader;
-import org.apache.linkis.cli.core.interactor.properties.reader.PropsFileReader;
-import org.apache.linkis.cli.core.interactor.properties.reader.SysEnvReader;
-import org.apache.linkis.cli.core.interactor.properties.reader.SysPropsReader;
-import org.apache.linkis.cli.core.interactor.validate.ParsedTplValidator;
-import org.apache.linkis.cli.core.interactor.var.StdVarAccess;
-import org.apache.linkis.cli.core.interactor.var.SysVarAccess;
-import org.apache.linkis.cli.core.utils.LogUtils;
-
-import org.apache.commons.lang3.StringUtils;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ProcessInputUtil {
- private static Logger logger = LoggerFactory.getLogger(ProcessInputUtil.class);
-
- public static ProcessedData generateProcessedData(String[] cmdStr, CmdTemplate template) {
- /*
- user input
- */
- Parser parser =
- new SingleCmdParser()
- .setMapper(null)
- .setTemplate(template)
- .setFitter(new SingleTplFitter());
-
- ParseResult result = parser.parse(cmdStr);
-
- ParsedTplValidator parsedTplValidator = new ParsedTplValidator();
- parsedTplValidator.doValidation(result.getParsedTemplate());
-
- Params params = result.getParams();
- logger.debug("==========params============\n" + Utils.GSON.toJson(params));
-
- Map propertiesMap = new HashMap<>();
- /*
- default config, -Dconf.root & -Dconf.file specifies config path
- */
- System.setProperty("conf.root", "src/test/resources/conf/");
- System.setProperty("conf.file", "linkis-cli.properties");
- String configPath = System.getProperty("conf.root");
- String defaultConfFileName = System.getProperty("conf.file");
- List readersList =
- new PropsFilesScanner().getPropsReaders(configPath); // +1 user config
- /*
- user defined config
- */
- String userConfPath = null;
- if (params.containsParam(AppKeys.LINKIS_CLIENT_USER_CONFIG)) {
- userConfPath =
- (String) params.getParamItemMap().get(AppKeys.LINKIS_CLIENT_USER_CONFIG).getValue();
- }
- if (StringUtils.isNotBlank(userConfPath)) {
- PropertiesReader reader =
- new PropsFileReader()
- .setPropsId(AppKeys.LINKIS_CLIENT_USER_CONFIG)
- .setPropsPath(userConfPath);
- readersList.add(reader);
- } else {
- LogUtils.getInformationLogger()
- .info("User does not provide usr-configuration file. Will use default config");
- }
- readersList.add(new SysPropsReader());
- readersList.add(new SysEnvReader());
- PropertiesLoader loader =
- new StdPropsLoader()
- .addPropertiesReaders(readersList.toArray(new PropertiesReader[readersList.size()]));
- ClientProperties[] loaderResult = loader.loadProperties();
- for (ClientProperties properties : loaderResult) {
- propertiesMap.put(properties.getPropsId(), properties);
- }
-
- VarAccess stdVarAccess =
- new StdVarAccess()
- .setCmdParams(params)
- .setUserConf(propertiesMap.get(AppKeys.LINKIS_CLIENT_USER_CONFIG))
- .setDefaultConf(propertiesMap.get(AppConstants.DEFAULT_CONFIG_NAME))
- .init();
-
- VarAccess sysVarAccess =
- new SysVarAccess()
- .setSysProp(propertiesMap.get(CommonConstants.SYSTEM_PROPERTIES_IDENTIFIER))
- .setSysEnv(propertiesMap.get(CommonConstants.SYSTEM_ENV_IDENTIFIER));
-
- return new ProcessedData(null, params.getCmdType(), stdVarAccess, sysVarAccess);
- }
-}
diff --git a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/test/java/org/apache/linkis/cli/application/interactor/execution/LinkisExecutorTest.java b/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/test/java/org/apache/linkis/cli/application/interactor/execution/LinkisExecutorTest.java
deleted file mode 100644
index b2571049d3..0000000000
--- a/linkis-computation-governance/linkis-client/linkis-cli/linkis-cli-application/src/test/java/org/apache/linkis/cli/application/interactor/execution/LinkisExecutorTest.java
+++ /dev/null
@@ -1,113 +0,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.apache.linkis.cli.application.interactor.execution;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-public class LinkisExecutorTest {
-
- @BeforeEach
- public void before() {}
-
- @AfterEach
- public void after() {}
-
- /** Method: setDriver(LinkisClientDriver driver) */
- @Test
- public void testSetDriver() {
- // TODO: Test goes here...
- }
-
- /** Method: setDriverTransformer(DriverTransformer driverTransformer) */
- @Test
- public void testSetDriverTransformer() {
- // TODO: Test goes here...
- }
-
- /** Method: getJobID(JobSubmitExec execData) */
- @Test
- public void testGetJobID() {
- // TODO: Test goes here...
- }
-
- /** Method: submit(Job job) */
- @Test
- public void testDoAsyncSubmit() {
- // TODO: Test goes here...
- }
-
- /** Method: updateJobStatus(JobSubmitExec execData) */
- @Test
- public void testDoUpdateProgress() {
- // TODO: Test goes here...
- }
-
- /** Method: checkSubmit(JobSubmitExec execData) */
- @Test
- public void testDoCheckSubmit() {
- // TODO: Test goes here...
- }
-
- /** Method: doGetFinalResult(JobSubmitExec execData) */
- @Test
- public void testDoGetFinalResult() {
- // TODO: Test goes here...
- }
-
- /** Method: checkInit() */
- @Test
- public void testCheckInit() {
- // TODO: Test goes here...
- }
-
- /** Method: doKill(Job job) */
- @Test
- public void testDoKill() {
- // TODO: Test goes here...
- }
-
- /** Method: doQuery(Job job) */
- @Test
- public void testDoQuery() {
- // TODO: Test goes here...
- }
-
- /** Method: doTransform(Job job) */
- @Test
- public void testDoTransform() {
- // TODO: Test goes here...
- }
-
- /** Method: updateExecDataByDwsResult(JobSubmitExec execData, DWSResult result) */
- @Test
- public void testUpdateExecDataByDwsResult() {
- // TODO: Test goes here...
- /*
- try {
- Method method = LinkisSubmitExecutor.getClass().getMethod("updateExecDataByDwsResult", JobSubmitExec.class, DWSResult.class);
- method.setAccessible(true);
- method.invoke(