You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kyuubi.apache.org by GitBox <gi...@apache.org> on 2021/09/03 05:05:58 UTC

[GitHub] [incubator-kyuubi] ulysses-you commented on a change in pull request #1015: [KYUUBI #1007] Implement delegation token renewal framework

ulysses-you commented on a change in pull request #1015:
URL: https://github.com/apache/incubator-kyuubi/pull/1015#discussion_r701578597



##########
File path: kyuubi-common/src/main/scala/org/apache/kyuubi/util/KyuubiHadoopUtils.scala
##########
@@ -33,4 +35,24 @@ object KyuubiHadoopUtils {
   def getServerPrincipal(principal: String): String = {
     SecurityUtil.getServerPrincipal(principal, "0.0.0.0")
   }
+
+  def encodeCredentials(creds: Credentials): String = {
+    val buf = new DataOutputBuffer
+    creds.write(buf)
+    val encoder = new Base64(0, null, false)
+    val raw = new Array[Byte](buf.getLength)
+    System.arraycopy(buf.getData, 0, raw, 0, buf.getLength)

Review comment:
       why we need copy bytes again ?

##########
File path: kyuubi-server/src/main/scala/org/apache/kyuubi/credentials/HadoopCredentialsManager.scala
##########
@@ -0,0 +1,242 @@
+/*
+ * 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.credentials
+
+import java.util.ServiceLoader
+import java.util.concurrent._
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.security.Credentials
+
+import org.apache.kyuubi.Logging
+import org.apache.kyuubi.config.KyuubiConf
+import org.apache.kyuubi.config.KyuubiConf._
+import org.apache.kyuubi.service.AbstractService
+import org.apache.kyuubi.util.{KyuubiHadoopUtils, ThreadUtils}
+
+/**
+ * [[HadoopCredentialsManager]] manages and renews delegation tokens, which are used by SQL engines
+ * to access kerberos secured services.
+ *
+ * Delegation tokens are sent to SQL engines by calling [[sendCredentialsIfNeeded]].
+ * [[sendCredentialsIfNeeded]] executes the following steps:
+ * <ol>
+ * <li>
+ *   Get or create a cached [[CredentialsRef]](contains delegation tokens) object by key
+ *   appUser. If [[CredentialsRef]] is newly created, spawn a scheduled task to renew the
+ *   delegation tokens.
+ * </li>
+ * <li>
+ *   Get or create a cached session credentials epoch object by key sessionId.
+ * </li>
+ * <li>
+ *   Compare [[CredentialsRef]] epoch with session credentials epoch. (Both epochs are set
+ *   to -1 when created. [[CredentialsRef]] epoch is increased when delegation tokens are
+ *   renewed.)
+ * </li>
+ * <li>
+ *   If epochs are equal, return. Else, send delegation tokens to the SQL engine.
+ * </li>
+ * <li>
+ *   If sending succeeds, set session credentials epoch to [[CredentialsRef]] epoch. Else,
+ *   record the exception and return.
+ * </li>
+ * </ol>
+ *
+ * @note Session credentials epochs are created in session scope and should be removed using
+ *       [[removeSessionCredentialsEpoch]] when session closes.
+ */
+class HadoopCredentialsManager private (name: String) extends AbstractService(name)
+    with Logging {
+
+  def this() = this(classOf[HadoopCredentialsManager].getSimpleName)
+
+  private val userCredentialsRefMap = new ConcurrentHashMap[String, CredentialsRef]()
+  private val sessionCredentialsEpochMap = new ConcurrentHashMap[String, Long]()
+
+  private var providers: Map[String, HadoopDelegationTokenProvider] = _
+  private var renewalInterval: Long = _
+  private var renewalRetryWait: Long = _
+  private var renewalExecutor: ScheduledExecutorService = _
+  private var hadoopConf: Configuration = _
+
+  override def initialize(conf: KyuubiConf): Unit = {
+    hadoopConf = KyuubiHadoopUtils.newHadoopConf(conf)
+    providers = HadoopCredentialsManager.loadProviders(conf)
+      .filter { case (_, provider) =>
+        val required = provider.delegationTokensRequired(hadoopConf, conf)
+        if (!required) {
+          info(s"Service ${provider.serviceName} does not require a token." +

Review comment:
       warn

##########
File path: kyuubi-server/src/main/scala/org/apache/kyuubi/credentials/HadoopDelegationProvider.scala
##########
@@ -0,0 +1,53 @@
+/*
+ * 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.credentials
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.security.Credentials
+
+import org.apache.kyuubi.Logging
+import org.apache.kyuubi.config.KyuubiConf
+
+trait HadoopDelegationTokenProvider extends Logging {
+
+  /**
+   * Name of the service to provide delegation tokens. This name should be unique. Kyuubi will
+   * internally use this name to differentiate delegation token providers.
+   */
+  def serviceName: String
+
+  /**
+   * Returns true if delegation tokens are required for this service. By default, it is based on
+   * whether Hadoop security is enabled.
+   */
+  def delegationTokensRequired(hadoopConf: Configuration, kyuubiConf: KyuubiConf): Boolean

Review comment:
       in general, one configuration is enough. Is there a chance that we can remove one ?

##########
File path: kyuubi-server/src/main/scala/org/apache/kyuubi/credentials/HadoopCredentialsManager.scala
##########
@@ -0,0 +1,242 @@
+/*
+ * 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.credentials
+
+import java.util.ServiceLoader
+import java.util.concurrent._
+
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.security.Credentials
+
+import org.apache.kyuubi.Logging
+import org.apache.kyuubi.config.KyuubiConf
+import org.apache.kyuubi.config.KyuubiConf._
+import org.apache.kyuubi.service.AbstractService
+import org.apache.kyuubi.util.{KyuubiHadoopUtils, ThreadUtils}
+
+/**
+ * [[HadoopCredentialsManager]] manages and renews delegation tokens, which are used by SQL engines
+ * to access kerberos secured services.
+ *
+ * Delegation tokens are sent to SQL engines by calling [[sendCredentialsIfNeeded]].
+ * [[sendCredentialsIfNeeded]] executes the following steps:
+ * <ol>
+ * <li>
+ *   Get or create a cached [[CredentialsRef]](contains delegation tokens) object by key
+ *   appUser. If [[CredentialsRef]] is newly created, spawn a scheduled task to renew the
+ *   delegation tokens.
+ * </li>
+ * <li>
+ *   Get or create a cached session credentials epoch object by key sessionId.
+ * </li>
+ * <li>
+ *   Compare [[CredentialsRef]] epoch with session credentials epoch. (Both epochs are set
+ *   to -1 when created. [[CredentialsRef]] epoch is increased when delegation tokens are
+ *   renewed.)
+ * </li>
+ * <li>
+ *   If epochs are equal, return. Else, send delegation tokens to the SQL engine.
+ * </li>
+ * <li>
+ *   If sending succeeds, set session credentials epoch to [[CredentialsRef]] epoch. Else,
+ *   record the exception and return.
+ * </li>
+ * </ol>
+ *
+ * @note Session credentials epochs are created in session scope and should be removed using
+ *       [[removeSessionCredentialsEpoch]] when session closes.
+ */
+class HadoopCredentialsManager private (name: String) extends AbstractService(name)
+    with Logging {
+
+  def this() = this(classOf[HadoopCredentialsManager].getSimpleName)
+
+  private val userCredentialsRefMap = new ConcurrentHashMap[String, CredentialsRef]()
+  private val sessionCredentialsEpochMap = new ConcurrentHashMap[String, Long]()
+
+  private var providers: Map[String, HadoopDelegationTokenProvider] = _
+  private var renewalInterval: Long = _
+  private var renewalRetryWait: Long = _
+  private var renewalExecutor: ScheduledExecutorService = _
+  private var hadoopConf: Configuration = _
+
+  override def initialize(conf: KyuubiConf): Unit = {
+    hadoopConf = KyuubiHadoopUtils.newHadoopConf(conf)
+    providers = HadoopCredentialsManager.loadProviders(conf)
+      .filter { case (_, provider) =>
+        val required = provider.delegationTokensRequired(hadoopConf, conf)
+        if (!required) {
+          info(s"Service ${provider.serviceName} does not require a token." +
+            s" Check your configuration to see if security is disabled or not.")
+        }
+        required
+      }
+    info("Using the following builtin delegation token providers: " +
+      s"${providers.keys.mkString(", ")}.")
+
+    renewalInterval = conf.get(CREDENTIALS_RENEWAL_INTERVAL)
+    renewalRetryWait = conf.get(CREDENTIALS_RENEWAL_RETRY_WAIT)
+    super.initialize(conf)
+  }
+
+  override def start(): Unit = {
+    renewalExecutor =
+      ThreadUtils.newDaemonSingleThreadScheduledExecutor("Delegation Token Renewal Thread")
+    super.start()
+  }
+
+  override def stop(): Unit = {
+    if (renewalExecutor != null) {
+      renewalExecutor.shutdownNow()
+      try {
+        renewalExecutor.awaitTermination(10, TimeUnit.SECONDS)
+      } catch {
+        case _: InterruptedException =>
+      }
+    }
+    super.stop()
+  }
+
+  /**
+   * Send credentials to SQL engine which the specified session is talking to if
+   * [[HadoopCredentialsManager]] has a newer credentials.
+   *
+   * @param sessionId Specify the session which is talking with SQL engine
+   * @param appUser  User identity that the SQL engine uses.
+   * @param send     Function to send encoded credentials to SQL engine
+   */
+  def sendCredentialsIfNeeded(
+      sessionId: String,
+      appUser: String,
+      send: String => Unit): Unit = {
+    require(renewalExecutor != null, "renewalExecutor should be initialized")
+
+    val userRef = getOrCreateUserCredentialsRef(appUser)
+    val sessionEpoch = getSessionCredentialsEpoch(sessionId)
+
+    if (userRef.getEpoch != sessionEpoch) {

Review comment:
       so there are two cases the user epoch can be lager than session epoch
   * the new created user cred
   * we failed to send created before
   
   How about use `if (userRef.getEpoch > sessionEpoch)` ?

##########
File path: kyuubi-server/src/main/scala/org/apache/kyuubi/credentials/CredentialsRef.scala
##########
@@ -0,0 +1,49 @@
+/*
+ * 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.credentials
+
+import org.apache.hadoop.security.Credentials
+
+import org.apache.kyuubi.credentials.CredentialsRef.UNSET_EPOCH
+import org.apache.kyuubi.util.KyuubiHadoopUtils
+
+class CredentialsRef(appUser: String) {
+
+  @volatile
+  private var epoch = UNSET_EPOCH
+
+  private var encodedCredentials: String = _
+
+  def getEpoch: Long = epoch
+
+  def getAppUser: String = appUser
+
+  def getEncodedCredentials: String = {
+    encodedCredentials
+  }
+
+  def updateCredentials(creds: Credentials): Unit = {
+    encodedCredentials = KyuubiHadoopUtils.encodeCredentials(creds)
+    epoch += 1
+  }
+
+}
+
+object CredentialsRef {
+  val UNSET_EPOCH: Long = -1L

Review comment:
       the initial value should be 0 ? otherwise after the first update the epoch is still 0.




-- 
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: commits-unsubscribe@kyuubi.apache.org

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