You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@kyuubi.apache.org by GitBox <gi...@apache.org> on 2022/05/23 18:51:27 UTC

[GitHub] [incubator-kyuubi] pan3793 commented on a diff in pull request #2717: [SUB-TASK][KPIP-4] Introduce jdbc session state store for batch session multiple HA

pan3793 commented on code in PR #2717:
URL: https://github.com/apache/incubator-kyuubi/pull/2717#discussion_r879763242


##########
dev/dependencyList:
##########
@@ -15,6 +15,7 @@
 # limitations under the License.
 #
 
+HikariCP/4.0.3//HikariCP-4.0.3.jar

Review Comment:
   Add deps should update LICENSE and NOTICE.



##########
kyuubi-server/src/main/resources/sql/derby/statestore-schema.derby.sql:
##########
@@ -0,0 +1,47 @@
+--
+-- 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.
+--
+
+CREATE TABLE BATCH_METADATA(
+    KEY_ID bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,

Review Comment:
   Use lower case for table name and filed name and upper case for SQL keywords



##########
kyuubi-server/src/main/scala/org/apache/kyuubi/operation/BatchJobSubmission.scala:
##########
@@ -111,11 +117,19 @@ class BatchJobSubmission(session: KyuubiBatchSessionImpl, batchRequest: BatchReq
   }
 
   private def submitBatchJob(): Unit = {
+    var appStatusFirstUpdated = false
     try {
       info(s"Submitting $batchType batch job: $builder")
       val process = builder.start
-      var applicationStatus = currentApplicationState
+      applicationStatus = currentApplicationState
       while (!applicationFailed(applicationStatus) && process.isAlive) {
+        if (!appStatusFirstUpdated && applicationStatus.isDefined) {
+          session.sessionManager.updateBatchStateAppInfo(
+            batchId,
+            getStatus.state.toString,

Review Comment:
   Why cast to String?



##########
kyuubi-server/src/main/scala/org/apache/kyuubi/server/statestore/jdbc/JDBCStateStore.scala:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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.kyuubi.server.statestore.jdbc
+
+import java.io.{BufferedReader, InputStream, InputStreamReader}
+import java.sql.{Connection, PreparedStatement, ResultSet, SQLException}
+import java.util.{Locale, Properties}
+import java.util.stream.Collectors
+
+import scala.collection.mutable.ListBuffer
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.module.scala.DefaultScalaModule
+import com.google.common.annotations.VisibleForTesting
+import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
+
+import org.apache.kyuubi.{KyuubiException, Logging, Utils}
+import org.apache.kyuubi.config.KyuubiConf
+import org.apache.kyuubi.config.KyuubiConf._
+import org.apache.kyuubi.server.statestore.StateStore
+import org.apache.kyuubi.server.statestore.api.BatchMetadata
+import org.apache.kyuubi.server.statestore.jdbc.DatabaseType._
+
+class JDBCStateStore(conf: KyuubiConf) extends StateStore with Logging {
+  import JDBCStateStore._
+
+  private val dbType = DatabaseType.withName(conf.get(SERVER_STATE_STORE_JDBC_DATABASE_TYPE))
+  private val driverClassOpt = conf.get(SERVER_STATE_STORE_JDBC_DRIVER)
+  private val driverClass = dbType match {
+    case DERBY => driverClassOpt.getOrElse("org.apache.derby.jdbc.AutoloadedDriver")
+    case MYSQL => driverClassOpt.getOrElse("com.mysql.jdbc.Driver")
+    case CUSTOM => driverClassOpt.getOrElse(
+        throw new IllegalArgumentException("No jdbc driver defined"))
+  }
+
+  private val datasourceProperties = new Properties()
+  conf.getStateStoreJDBCDataSourceProperties.foreach { case (key, value) =>
+    datasourceProperties.put(key, value)
+  }
+
+  private val hikariConfig = new HikariConfig(datasourceProperties)
+  hikariConfig.setDriverClassName(driverClass)
+  hikariConfig.setJdbcUrl(conf.get(SERVER_STATE_STORE_JDBC_URL))
+  hikariConfig.setUsername(conf.get(SERVER_STATE_STORE_JDBC_USER))
+  hikariConfig.setPassword(conf.get(SERVER_STATE_STORE_JDBC_PASSWORD))
+  hikariConfig.setPoolName("kyuubi-state-store-pool")
+
+  @VisibleForTesting
+  private[kyuubi] val hikariDataSource = new HikariDataSource(hikariConfig)
+  private val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
+  private val stateMaxAge = conf.get(SERVER_STATE_STORE_MAX_AGE)
+
+  if (conf.get(SERVER_STATE_STORE_JDBC_DATABASE_SCHEMA_INIT)) {
+    initSchema()
+  }
+
+  private def initSchema(): Unit = {
+    val classLoader = getClass.getClassLoader
+    val initSchemaStream: Option[InputStream] = dbType match {
+      case DERBY =>
+        Option(classLoader.getResourceAsStream("sql/derby/statestore-schema.derby.sql"))
+      case MYSQL =>
+        Option(classLoader.getResourceAsStream("sql/mysql/statestore-schema.mysql.sql"))
+      case CUSTOM => None
+    }
+    initSchemaStream.foreach { inputStream =>
+      try {
+        val statements = new BufferedReader(new InputStreamReader(inputStream)).lines()
+          .filter(!_.trim.startsWith("--")).collect(Collectors.joining("\n")).trim.split(";")
+        withConnection() { connection =>
+          Utils.tryLogNonFatalError {
+            statements.foreach { statement =>
+              execute(connection, statement)
+              info(s"Execute init schema query: $statement successfully.")
+            }
+          }
+        }
+      } finally {
+        inputStream.close()
+      }
+    }
+  }
+
+  override def close(): Unit = {
+    hikariDataSource.close()
+  }
+
+  override def insertBatch(batch: BatchMetadata): Unit = {
+    val query =
+      s"""
+         |INSERT INTO $BATCH_METADATA_TABLE(
+         |BATCH_ID,
+         |BATCH_OWNER,
+         |IP_ADDRESS,
+         |SESSION_CONF,
+         |KYUUBI_INSTANCE,
+         |BATCH_TYPE,
+         |RESOURCE,
+         |CLASS_NAME,
+         |NAME,
+         |CONF,
+         |ARGS,
+         |STATE,
+         |CREATE_TIME
+         |)
+         |VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""".stripMargin
+    executeQuery(
+      query,
+      batch.batchId,
+      batch.batchOwner,
+      batch.ipAddress,
+      valueAsString(batch.sessionConf),
+      batch.kyuubiInstance,
+      batch.batchType,
+      batch.resource,
+      batch.className,
+      batch.name,
+      valueAsString(batch.conf),
+      valueAsString(batch.args),
+      batch.state,
+      batch.createTime)
+  }
+
+  override def getBatch(batchId: String, stateOnly: Boolean): BatchMetadata = {
+    val query =
+      if (stateOnly) {
+        s"SELECT $STATE_ONLY_COLUMNS FROM $BATCH_METADATA_TABLE WHERE BATCH_ID = ?"
+      } else {
+        s"SELECT * FROM $BATCH_METADATA_TABLE WHERE BATCH_ID = ?"

Review Comment:
   Avoid using select star



##########
kyuubi-server/src/main/scala/org/apache/kyuubi/server/statestore/jdbc/JDBCStateStore.scala:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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.kyuubi.server.statestore.jdbc
+
+import java.io.{BufferedReader, InputStream, InputStreamReader}
+import java.sql.{Connection, PreparedStatement, ResultSet, SQLException}
+import java.util.{Locale, Properties}
+import java.util.stream.Collectors
+
+import scala.collection.mutable.ListBuffer
+
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.module.scala.DefaultScalaModule
+import com.google.common.annotations.VisibleForTesting
+import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
+
+import org.apache.kyuubi.{KyuubiException, Logging, Utils}
+import org.apache.kyuubi.config.KyuubiConf
+import org.apache.kyuubi.config.KyuubiConf._
+import org.apache.kyuubi.server.statestore.StateStore
+import org.apache.kyuubi.server.statestore.api.BatchMetadata
+import org.apache.kyuubi.server.statestore.jdbc.DatabaseType._
+
+class JDBCStateStore(conf: KyuubiConf) extends StateStore with Logging {
+  import JDBCStateStore._
+
+  private val dbType = DatabaseType.withName(conf.get(SERVER_STATE_STORE_JDBC_DATABASE_TYPE))
+  private val driverClassOpt = conf.get(SERVER_STATE_STORE_JDBC_DRIVER)
+  private val driverClass = dbType match {
+    case DERBY => driverClassOpt.getOrElse("org.apache.derby.jdbc.AutoloadedDriver")
+    case MYSQL => driverClassOpt.getOrElse("com.mysql.jdbc.Driver")
+    case CUSTOM => driverClassOpt.getOrElse(
+        throw new IllegalArgumentException("No jdbc driver defined"))
+  }
+
+  private val datasourceProperties = new Properties()
+  conf.getStateStoreJDBCDataSourceProperties.foreach { case (key, value) =>
+    datasourceProperties.put(key, value)
+  }
+
+  private val hikariConfig = new HikariConfig(datasourceProperties)
+  hikariConfig.setDriverClassName(driverClass)
+  hikariConfig.setJdbcUrl(conf.get(SERVER_STATE_STORE_JDBC_URL))
+  hikariConfig.setUsername(conf.get(SERVER_STATE_STORE_JDBC_USER))
+  hikariConfig.setPassword(conf.get(SERVER_STATE_STORE_JDBC_PASSWORD))
+  hikariConfig.setPoolName("kyuubi-state-store-pool")
+
+  @VisibleForTesting
+  private[kyuubi] val hikariDataSource = new HikariDataSource(hikariConfig)
+  private val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
+  private val stateMaxAge = conf.get(SERVER_STATE_STORE_MAX_AGE)
+
+  if (conf.get(SERVER_STATE_STORE_JDBC_DATABASE_SCHEMA_INIT)) {
+    initSchema()
+  }
+
+  private def initSchema(): Unit = {
+    val classLoader = getClass.getClassLoader
+    val initSchemaStream: Option[InputStream] = dbType match {
+      case DERBY =>
+        Option(classLoader.getResourceAsStream("sql/derby/statestore-schema.derby.sql"))
+      case MYSQL =>
+        Option(classLoader.getResourceAsStream("sql/mysql/statestore-schema.mysql.sql"))
+      case CUSTOM => None
+    }
+    initSchemaStream.foreach { inputStream =>
+      try {
+        val statements = new BufferedReader(new InputStreamReader(inputStream)).lines()
+          .filter(!_.trim.startsWith("--")).collect(Collectors.joining("\n")).trim.split(";")
+        withConnection() { connection =>
+          Utils.tryLogNonFatalError {
+            statements.foreach { statement =>
+              execute(connection, statement)
+              info(s"Execute init schema query: $statement successfully.")
+            }
+          }
+        }
+      } finally {
+        inputStream.close()
+      }
+    }
+  }
+
+  override def close(): Unit = {
+    hikariDataSource.close()
+  }
+
+  override def insertBatch(batch: BatchMetadata): Unit = {
+    val query =
+      s"""
+         |INSERT INTO $BATCH_METADATA_TABLE(
+         |BATCH_ID,
+         |BATCH_OWNER,
+         |IP_ADDRESS,
+         |SESSION_CONF,
+         |KYUUBI_INSTANCE,
+         |BATCH_TYPE,
+         |RESOURCE,
+         |CLASS_NAME,
+         |NAME,
+         |CONF,
+         |ARGS,
+         |STATE,
+         |CREATE_TIME
+         |)
+         |VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""".stripMargin
+    executeQuery(
+      query,
+      batch.batchId,
+      batch.batchOwner,
+      batch.ipAddress,
+      valueAsString(batch.sessionConf),
+      batch.kyuubiInstance,
+      batch.batchType,
+      batch.resource,
+      batch.className,
+      batch.name,
+      valueAsString(batch.conf),
+      valueAsString(batch.args),
+      batch.state,
+      batch.createTime)
+  }
+
+  override def getBatch(batchId: String, stateOnly: Boolean): BatchMetadata = {
+    val query =
+      if (stateOnly) {
+        s"SELECT $STATE_ONLY_COLUMNS FROM $BATCH_METADATA_TABLE WHERE BATCH_ID = ?"
+      } else {
+        s"SELECT * FROM $BATCH_METADATA_TABLE WHERE BATCH_ID = ?"
+      }
+    withConnection() { connection =>
+      val rs = execute(connection, query, batchId)
+      buildBatches(rs, stateOnly).headOption.orNull
+    }
+  }
+
+  override def getBatches(
+      batchType: String,
+      batchOwner: String,
+      batchState: String,
+      kyuubiInstance: String,
+      from: Int,
+      size: Int,
+      stateOnly: Boolean): Seq[BatchMetadata] = {
+    val queryBuilder = new StringBuilder
+    val params = ListBuffer[Any]()
+    if (stateOnly) {
+      queryBuilder.append(s"SELECT $STATE_ONLY_COLUMNS FROM $BATCH_METADATA_TABLE")
+    } else {
+      queryBuilder.append(s"SELECT * FROM $BATCH_METADATA_TABLE")
+    }
+    val whereConditions = ListBuffer[String]()
+    Option(batchType).filter(_.nonEmpty).foreach { _ =>
+      whereConditions += " UPPER(BATCH_TYPE) = ? "
+      params += batchType.toUpperCase(Locale.ROOT)
+    }
+    Option(batchOwner).filter(_.nonEmpty).foreach { _ =>
+      whereConditions += " BATCH_OWNER = ? "
+      params += batchOwner
+    }
+    Option(batchState).filter(_.nonEmpty).foreach { _ =>
+      whereConditions += " STATE = ? "
+      params += batchState
+    }
+    Option(kyuubiInstance).filter(_.nonEmpty).foreach { _ =>
+      whereConditions += " KYUUBI_INSTANCE = ? "
+      params += kyuubiInstance
+    }
+    if (whereConditions.nonEmpty) {
+      queryBuilder.append(whereConditions.mkString(" WHERE ", " AND ", " "))
+    }
+    queryBuilder.append(" ORDER BY KEY_ID ")
+    queryBuilder.append(" {LIMIT ? OFFSET ? } ")

Review Comment:
   Whay does `{ }` do?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@kyuubi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@kyuubi.apache.org
For additional commands, e-mail: notifications-help@kyuubi.apache.org