JAVA SDK 方式使用

Linkis 提供了方便的JAVA和SCALA调用的接口,只需要引入linkis-computation-client的模块就可以进行使用,1.0后新增支持带Label提交的方式,下面将对兼容0.X的方式和1.0新增的方式进行介绍

1. 引入依赖模块

  1. <dependency>
  2. <groupId>org.apache.linkis</groupId>
  3. <artifactId>linkis-computation-client</artifactId>
  4. <version>${linkis.version}</version>
  5. </dependency>
  6. 如:
  7. <dependency>
  8. <groupId>org.apache.linkis</groupId>
  9. <artifactId>linkis-computation-client</artifactId>
  10. <version>1.0.3</version>
  11. </dependency>

2. Java测试代码

建立Java的测试类LinkisClientTest,具体接口含义可以见注释:

  1. package org.apache.linkis.client.test;
  2. import org.apache.linkis.common.utils.Utils;
  3. import org.apache.linkis.httpclient.dws.authentication.StaticAuthenticationStrategy;
  4. import org.apache.linkis.httpclient.dws.config.DWSClientConfig;
  5. import org.apache.linkis.httpclient.dws.config.DWSClientConfigBuilder;
  6. import org.apache.linkis.manager.label.constant.LabelKeyConstant;
  7. import org.apache.linkis.protocol.constants.TaskConstant;
  8. import org.apache.linkis.ujes.client.UJESClient;
  9. import org.apache.linkis.ujes.client.UJESClientImpl;
  10. import org.apache.linkis.ujes.client.request.JobSubmitAction;
  11. import org.apache.linkis.ujes.client.request.JobExecuteAction;
  12. import org.apache.linkis.ujes.client.request.ResultSetAction;
  13. import org.apache.linkis.ujes.client.response.*;
  14. import org.apache.commons.io.IOUtils;
  15. import java.util.HashMap;
  16. import java.util.Map;
  17. import java.util.concurrent.TimeUnit;
  18. public class LinkisClientTest {
  19. // 1. build config: linkis gateway url
  20. private static DWSClientConfig clientConfig = ((DWSClientConfigBuilder) (DWSClientConfigBuilder.newBuilder()
  21. .addServerUrl("http://127.0.0.1:9001/") //set linkis-mg-gateway url: http://{ip}:{port}
  22. .connectionTimeout(30000) //connectionTimeOut
  23. .discoveryEnabled(false) //disable discovery
  24. .discoveryFrequency(1, TimeUnit.MINUTES) // discovery frequency
  25. .loadbalancerEnabled(true) // enable loadbalance
  26. .maxConnectionSize(5) // set max Connection
  27. .retryEnabled(false) // set retry
  28. .readTimeout(30000) //set read timeout
  29. .setAuthenticationStrategy(new StaticAuthenticationStrategy()) //AuthenticationStrategy Linkis authen suppory static and Token
  30. .setAuthTokenKey("hadoop") // set submit user
  31. .setAuthTokenValue("hadoop"))) // set passwd or token (setAuthTokenValue("test"))
  32. .setDWSVersion("v1") //linkis rest version v1
  33. .build();
  34. // 2. new Client(Linkis Client) by clientConfig
  35. private static UJESClient client = new UJESClientImpl(clientConfig);
  36. public static void main(String[] args){
  37. String user = "hadoop"; // execute user
  38. String executeCode = "df=spark.sql(\"show tables\")\n" +
  39. "show(df)"; // code support:sql/hql/py/scala
  40. try {
  41. System.out.println("user : " + user + ", code : [" + executeCode + "]");
  42. // 3.推荐用submit的方式,可以指定任务相关的label支持更多特性
  43. JobExecuteResult jobExecuteResult = toSubmit(user, executeCode);
  44. //0.x兼容的方式,不推荐使用:JobExecuteResult jobExecuteResult = toExecute(user, executeCode);
  45. System.out.println("execId: " + jobExecuteResult.getExecID() + ", taskId: " + jobExecuteResult.taskID());
  46. // 4. get job jonfo
  47. JobInfoResult jobInfoResult = client.getJobInfo(jobExecuteResult);
  48. int sleepTimeMills = 1000;
  49. int logFromLen = 0;
  50. int logSize = 100;
  51. while(!jobInfoResult.isCompleted()) {
  52. // 5. get progress and log
  53. JobProgressResult progress = client.progress(jobExecuteResult);
  54. System.out.println("progress: " + progress.getProgress());
  55. JobLogResult logRes = client.log(jobExecuteResult, logFromLen, logSize);
  56. logFromLen = logRes.fromLine();
  57. // 0: info 1: warn 2: error 3: all
  58. System.out.println(logRes.log().get(3));
  59. Utils.sleepQuietly(sleepTimeMills);
  60. jobInfoResult = client.getJobInfo(jobExecuteResult);
  61. }
  62. JobInfoResult jobInfo = client.getJobInfo(jobExecuteResult);
  63. // 6. Get the result set list (if the user submits multiple SQLs at a time,
  64. // multiple result sets will be generated)
  65. String resultSet = jobInfo.getResultSetList(client)[0];
  66. // 7. get resultContent
  67. Object fileContents = client.resultSet(ResultSetAction.builder().setPath(resultSet).setUser(jobExecuteResult.getUser()).build()).getFileContent();
  68. System.out.println("res: " + fileContents);
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. IOUtils.closeQuietly(client);
  72. }
  73. IOUtils.closeQuietly(client);
  74. }
  75. /**
  76. * Linkis 1.0 recommends the use of Submit method
  77. */
  78. private static JobExecuteResult toSubmit(String user, String code) {
  79. // 1. build params
  80. // set label map :EngineTypeLabel/UserCreatorLabel/EngineRunTypeLabel/Tenant
  81. Map<String, Object> labels = new HashMap<String, Object>();
  82. labels.put(LabelKeyConstant.ENGINE_TYPE_KEY, "spark-2.4.3"); // required engineType Label
  83. labels.put(LabelKeyConstant.USER_CREATOR_TYPE_KEY, user + "-APPName");// 请求的用户和应用名,两个参数都不能少,其中APPName不能带有"-"建议替换为"_"
  84. labels.put(LabelKeyConstant.CODE_TYPE_KEY, "py"); // 指定脚本类型
  85. // set start up map :engineConn start params
  86. Map<String, Object> startupMap = new HashMap<String, Object>(16);
  87. // Support setting engine native parameters,For example: parameters of engines such as spark/hive
  88. startupMap.put("spark.executor.instances", 2);
  89. // setting linkis params
  90. startupMap.put("wds.linkis.rm.yarnqueue", "dws");
  91. // 2. build jobSubmitAction
  92. JobSubmitAction jobSubmitAction = JobSubmitAction.builder()
  93. .addExecuteCode(code)
  94. .setStartupParams(startupMap)
  95. .setUser(user) //submit user
  96. .addExecuteUser(user) // execute user
  97. .setLabels(labels)
  98. .build();
  99. // 3. to execute
  100. return client.submit(jobSubmitAction);
  101. }
  102. /**
  103. * Compatible with 0.X execution mode
  104. */
  105. private static JobExecuteResult toExecute(String user, String code) {
  106. // 1. build params
  107. // set label map :EngineTypeLabel/UserCreatorLabel/EngineRunTypeLabel/Tenant
  108. Map<String, Object> labels = new HashMap<String, Object>();
  109. // labels.put(LabelKeyConstant.TENANT_KEY, "fate");
  110. // set start up map :engineConn start params
  111. Map<String, Object> startupMap = new HashMap<String, Object>(16);
  112. // Support setting engine native parameters,For example: parameters of engines such as spark/hive
  113. startupMap.put("spark.executor.instances", 2);
  114. // setting linkis params
  115. startupMap.put("wds.linkis.rm.yarnqueue", "dws");
  116. // 2. build JobExecuteAction (0.X old way of using)
  117. JobExecuteAction executionAction = JobExecuteAction.builder()
  118. .setCreator("AppName") //creator, the system name of the client requesting linkis, used for system-level isolation
  119. .addExecuteCode(code) //Execution Code
  120. .setEngineTypeStr("spark") // engineConn type
  121. .setRunTypeStr("py") // code type
  122. .setUser(user) //execute user
  123. .setStartupParams(startupMap) // start up params
  124. .build();
  125. executionAction.addRequestPayload(TaskConstant.LABELS, labels);
  126. String body = executionAction.getRequestPayload();
  127. System.out.println(body);
  128. // 3. to execute
  129. return client.execute(executionAction);
  130. }
  131. }

运行上述的代码即可以完成任务提交/执行/日志/结果集获取等

3. Scala测试代码:

  1. package org.apache.linkis.client.test
  2. import java.util
  3. import java.util.concurrent.TimeUnit
  4. import org.apache.linkis.common.utils.Utils
  5. import org.apache.linkis.httpclient.dws.authentication.StaticAuthenticationStrategy
  6. import org.apache.linkis.httpclient.dws.config.DWSClientConfigBuilder
  7. import org.apache.linkis.manager.label.constant.LabelKeyConstant
  8. import org.apache.linkis.protocol.constants.TaskConstant
  9. import org.apache.linkis.ujes.client.UJESClient
  10. import org.apache.linkis.ujes.client.request._
  11. import org.apache.linkis.ujes.client.response._
  12. import org.apache.commons.io.IOUtils
  13. import org.apache.commons.lang.StringUtils
  14. object LinkisClientTest {
  15. // 1. build config: linkis gateway url
  16. val clientConfig = DWSClientConfigBuilder.newBuilder()
  17. .addServerUrl("http://127.0.0.1:9001/") //set linkis-mg-gateway url: http://{ip}:{port}
  18. .connectionTimeout(30000) //connectionTimeOut
  19. .discoveryEnabled(false) //disable discovery
  20. .discoveryFrequency(1, TimeUnit.MINUTES) // discovery frequency
  21. .loadbalancerEnabled(true) // enable loadbalance
  22. .maxConnectionSize(5) // set max Connection
  23. .retryEnabled(false) // set retry
  24. .readTimeout(30000) //set read timeout
  25. .setAuthenticationStrategy(new StaticAuthenticationStrategy()) //AuthenticationStrategy Linkis authen suppory static and Token
  26. .setAuthTokenKey("hadoop") // set submit user
  27. .setAuthTokenValue("hadoop") // set passwd or token (setAuthTokenValue("BML-AUTH"))
  28. .setDWSVersion("v1") //linkis rest version v1
  29. .build();
  30. // 2. new Client(Linkis Client) by clientConfig
  31. val client = UJESClient(clientConfig)
  32. def main(args: Array[String]): Unit = {
  33. val user = "hadoop" // execute user
  34. val executeCode = "df=spark.sql(\"show tables\")\n" +
  35. "show(df)"; // code support:sql/hql/py/scala
  36. try {
  37. // 3. build job and execute
  38. println("user : " + user + ", code : [" + executeCode + "]")
  39. //推荐使用submit,支持传递任务label
  40. val jobExecuteResult = toSubmit(user, executeCode)
  41. //0.X: val jobExecuteResult = toExecute(user, executeCode)
  42. println("execId: " + jobExecuteResult.getExecID + ", taskId: " + jobExecuteResult.taskID)
  43. // 4. get job jonfo
  44. var jobInfoResult = client.getJobInfo(jobExecuteResult)
  45. var logFromLen = 0
  46. val logSize = 100
  47. val sleepTimeMills : Int = 1000
  48. while (!jobInfoResult.isCompleted) {
  49. // 5. get progress and log
  50. val progress = client.progress(jobExecuteResult)
  51. println("progress: " + progress.getProgress)
  52. val logObj = client .log(jobExecuteResult, logFromLen, logSize)
  53. logFromLen = logObj.fromLine
  54. val logArray = logObj.getLog
  55. // 0: info 1: warn 2: error 3: all
  56. if (logArray != null && logArray.size >= 4 && StringUtils.isNotEmpty(logArray.get(3))) {
  57. println(s"log: ${logArray.get(3)}")
  58. }
  59. Utils.sleepQuietly(sleepTimeMills)
  60. jobInfoResult = client.getJobInfo(jobExecuteResult)
  61. }
  62. if (!jobInfoResult.isSucceed) {
  63. println("Failed to execute job: " + jobInfoResult.getMessage)
  64. throw new Exception(jobInfoResult.getMessage)
  65. }
  66. // 6. Get the result set list (if the user submits multiple SQLs at a time,
  67. // multiple result sets will be generated)
  68. val jobInfo = client.getJobInfo(jobExecuteResult)
  69. val resultSetList = jobInfoResult.getResultSetList(client)
  70. println("All result set list:")
  71. resultSetList.foreach(println)
  72. val oneResultSet = jobInfo.getResultSetList(client).head
  73. // 7. get resultContent
  74. val fileContents = client.resultSet(ResultSetAction.builder().setPath(oneResultSet).setUser(jobExecuteResult.getUser).build()).getFileContent
  75. println("First fileContents: ")
  76. println(fileContents)
  77. } catch {
  78. case e: Exception => {
  79. e.printStackTrace()
  80. }
  81. }
  82. IOUtils.closeQuietly(client)
  83. }
  84. /**
  85. * Linkis 1.0 recommends the use of Submit method
  86. */
  87. def toSubmit(user: String, code: String): JobExecuteResult = {
  88. // 1. build params
  89. // set label map :EngineTypeLabel/UserCreatorLabel/EngineRunTypeLabel/Tenant
  90. val labels: util.Map[String, Any] = new util.HashMap[String, Any]
  91. labels.put(LabelKeyConstant.ENGINE_TYPE_KEY, "spark-2.4.3"); // required engineType Label
  92. labels.put(LabelKeyConstant.USER_CREATOR_TYPE_KEY, user + "-APPName");// 请求的用户和应用名,两个参数都不能少,其中APPName不能带有"-"建议替换为"_"
  93. labels.put(LabelKeyConstant.CODE_TYPE_KEY, "py"); // 指定脚本类型
  94. val startupMap = new java.util.HashMap[String, Any]()
  95. // Support setting engine native parameters,For example: parameters of engines such as spark/hive
  96. startupMap.put("spark.executor.instances", 2);
  97. // setting linkis params
  98. startupMap.put("wds.linkis.rm.yarnqueue", "default");
  99. // 2. build jobSubmitAction
  100. val jobSubmitAction = JobSubmitAction.builder
  101. .addExecuteCode(code)
  102. .setStartupParams(startupMap)
  103. .setUser(user) //submit user
  104. .addExecuteUser(user) //execute user
  105. .setLabels(labels)
  106. .build
  107. // 3. to execute
  108. client.submit(jobSubmitAction)
  109. }
  110. /**
  111. * Compatible with 0.X execution mode
  112. */
  113. def toExecute(user: String, code: String): JobExecuteResult = {
  114. // 1. build params
  115. // set label map :EngineTypeLabel/UserCreatorLabel/EngineRunTypeLabel/Tenant
  116. val labels = new util.HashMap[String, Any]
  117. // labels.put(LabelKeyConstant.TENANT_KEY, "fate");
  118. val startupMap = new java.util.HashMap[String, Any]()
  119. // Support setting engine native parameters,For example: parameters of engines such as spark/hive
  120. startupMap.put("spark.executor.instances", 2)
  121. // setting linkis params
  122. startupMap.put("wds.linkis.rm.yarnqueue", "default")
  123. // 2. build JobExecuteAction (0.X old way of using)
  124. val executionAction = JobExecuteAction.builder()
  125. .setCreator("APPName") //creator, the system name of the client requesting linkis, used for system-level isolation
  126. .addExecuteCode(code) //Execution Code
  127. .setEngineTypeStr("spark") // engineConn type
  128. .setRunTypeStr("py") // code type
  129. .setUser(user) //execute user
  130. .setStartupParams(startupMap) // start up params
  131. .build();
  132. executionAction.addRequestPayload(TaskConstant.LABELS, labels);
  133. // 3. to execute
  134. client.execute(executionAction)
  135. }
  136. }