pan3793 commented on code in PR #7800: URL: https://github.com/apache/kyuubi/pull/7800#discussion_r4625221846
########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyTargetResolver.scala: ########## @@ -0,0 +1,212 @@ +/* + * 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.api + +import java.net.URI +import java.nio.charset.StandardCharsets.UTF_8 +import java.util.{Base64, Locale, UUID} + +import scala.util.Try +import scala.util.control.NonFatal + +import org.apache.kyuubi.Utils +import org.apache.kyuubi.config.KyuubiConf.ENGINE_DO_AS_ENABLED +import org.apache.kyuubi.config.KyuubiReservedKeys.{KYUUBI_ENGINE_APP_MGR_INFO_KEY, KYUUBI_ENGINE_ID, KYUUBI_ENGINE_URL} +import org.apache.kyuubi.engine.{ApplicationManagerInfo, ApplicationState, EngineType} +import org.apache.kyuubi.ha.HighAvailabilityConf.HA_NAMESPACE +import org.apache.kyuubi.ha.client.{DiscoveryClient, DiscoveryPaths, ServiceNodeInfo} +import org.apache.kyuubi.ha.client.DiscoveryClientProvider.createDiscoveryClient +import org.apache.kyuubi.operation.OperationState +import org.apache.kyuubi.server.KyuubiRestFrontendService +import org.apache.kyuubi.session.SessionHandle + +/** Resolves UI destinations from server-owned resource records, never from a client URL. */ +private[api] class EngineUIProxyTargetResolver(fe: KyuubiRestFrontendService) + extends AutoCloseable { + import EngineUIProxyTargetResolver._ + + private var client: Option[DiscoveryClient] = None + @volatile private var closed = false + + private def discoveryClient: DiscoveryClient = synchronized { + require(!closed, "Engine UI target resolver is closed") + client.getOrElse { + val created = createDiscoveryClient(fe.getConf) + try { + created.createClient() + client = Some(created) + created + } catch { + case NonFatal(e) => + Utils.tryLogNonFatalError(created.closeClient()) + throw e + } + } + } + + override def close(): Unit = synchronized { + closed = true + try client.foreach(_.closeClient()) + finally client = None + } + + def resolveResource(kind: String, reference: String): Option[EngineUIProxyTarget] = { + require(!closed, "Engine UI target resolver is closed") + kind match { + case "engines" => resolveEngine(reference) + case "batches" => resolveBatch(reference) + case _ => None + } + } + + private def resolveEngine(reference: String): Option[EngineUIProxyTarget] = { + decodeReference(reference).flatMap { case (namespace, refId) => + engineScope(namespace, fe.getConf.get(HA_NAMESPACE)).flatMap { + case (_, owner) => + val nodes = discoveryClient.getServiceNodesInfo(namespace) + .filter(_.engineRefId.contains(refId)) + // Never pick an arbitrary incarnation when discovery contains duplicate records. + if (nodes.size == 1) engineTarget(nodes.head, refId, owner) else None + } + } + } + + private def engineTarget( + node: ServiceNodeInfo, + refId: String, + owner: String): Option[EngineUIProxyTarget] = { + node.attributes.get(KYUUBI_ENGINE_URL).flatMap(parseTarget).map { uri => + val managerInfo = node.attributes.get(KYUUBI_ENGINE_APP_MGR_INFO_KEY) + .map(ApplicationManagerInfo.deserialize) + if (managerInfo.exists(_.resourceManager.exists( + _.toLowerCase(Locale.ROOT).startsWith("yarn")))) { + val applicationId = node.attributes.get(KYUUBI_ENGINE_ID) + val applicationPath = applicationId.filter(_.matches("application_[0-9]+_[0-9]+")) + .map("/proxy/" + _) + val proxyUser = + if (fe.getConf.get(ENGINE_DO_AS_ENABLED)) { + owner + } else Utils.currentUser + EngineUIProxyTarget( + uri, + applicationPath, + () => { + // Query only when the driver requires its web proxy. A directly accessible UI + // must not depend on the ResourceManager or its web proxy being available. + fe.sessionManager.applicationManager + .getApplicationInfo(managerInfo.get, refId, Some(proxyUser)) + .filter(info => + applicationId.contains(info.id) && + !ApplicationState.isTerminated(info.state)) + .flatMap(_.url).flatMap(parseTarget) + }) + } else EngineUIProxyTarget(uri) + } + } + + private def batchTarget(url: Option[String], applicationId: Option[String]) + : Option[EngineUIProxyTarget] = { + url.flatMap(parseTarget).map { uri => + EngineUIProxyTarget( + uri, + applicationId.filter(_.matches("application_[0-9]+_[0-9]+")).map("/proxy/" + _)) + } + } + + private def resolveBatch(reference: String): Option[EngineUIProxyTarget] = { + Try(SessionHandle.fromUUID(reference)).toOption.flatMap { handle => + val manager = fe.sessionManager + manager.getBatchSession(handle) match { + case Some(session) => + val operation = session.batchJobSubmissionOp + if (OperationState.isTerminal(operation.getStatus.state)) None + else operation.getApplicationInfo.filterNot(info => + ApplicationState.isTerminated(info.state)) + .flatMap(info => batchTarget(info.url, Option(info.id))) + case None => + manager.getBatchMetadata(reference).flatMap { metadata => + if (metadata.state == null || + OperationState.isTerminal(OperationState.withName(metadata.state)) || + metadata.appState.exists(ApplicationState.isTerminated)) { + None + } else { + batchTarget(Option(metadata.engineUrl), Option(metadata.engineId)) + } + } + } + } + } + +} + +private[api] case class EngineUIProxyTarget( + uri: URI, + applicationPath: Option[String] = None, + resolveProxy: () => Option[URI] = () => None) + +private[api] object EngineUIProxyTargetResolver { + val REFERENCE_ATTRIBUTE = "kyuubi.engine.ui.proxy.ref" + private val shareLevels = Seq("SERVER_LOCAL", "CONNECTION", "SERVER", "GROUP", "USER") + + def reference(node: ServiceNodeInfo): Option[String] = node.engineRefId.map { refId => + Base64.getUrlEncoder.withoutPadding().encodeToString( + s"${node.namespace}\n$refId".getBytes(UTF_8)) + } + + private[api] def decodeReference(reference: String): Option[(String, String)] = { + if (reference.length > 4096 || !reference.matches("[A-Za-z0-9_-]+")) return None + Try(new String(Base64.getUrlDecoder.decode(reference), UTF_8)).toOption.flatMap { value => + value.split("\n", -1) match { + case Array(namespace, refId) if Try(UUID.fromString(refId)).isSuccess => + Some(namespace -> refId) + case _ => None + } + } + } + + private[api] def engineScope( + namespace: String, + serverNamespace: String): Option[(String, String)] = { + val prefix = DiscoveryPaths.makePath(null, serverNamespace) + "_" + if (!namespace.startsWith(prefix)) return None + val parts = namespace.substring(prefix.length).split("/", -1) + if (parts.length < 2 || parts.exists(p => + p.isEmpty || p == "." || p == ".." || + p.exists(c => c == '%' || c == '\\' || c.isControl))) { + return None + } + (for { + shareLevel <- shareLevels.iterator + engineType <- EngineType.values.iterator + suffix = s"_${shareLevel}_$engineType" + if parts.head.endsWith(suffix) + version = parts.head.stripSuffix(suffix) + if version.matches("[A-Za-z0-9.-]+") + } yield (shareLevel, parts(1))).take(1).toList.headOption + } + + private[api] def parseTarget(value: String): Option[URI] = { Review Comment: Removing `kyuubi.frontend.rest.engine.ui.proxy.hosts` widens the server's network reach. It shipped in 1.12.0 (#7483) to bound proxy destinations; now the target is whatever `kyuubi.engine.url` the engine publishes in discovery. User code runs in the engine with the engine's discovery credentials, so a user can publish any `host:port` and have the Kyuubi server send arbitrary requests there, including hosts the driver itself cannot reach. `parseTarget` only checks the URL shape, and the test rejecting `/engine-ui/engine-host:10250/pods` only covers the legacy URL format. Suggest keeping the allow-list as an optional extra check on the resolved target and on the approved YARN proxy redirect. CIDR support would cover Kubernetes pod IPs. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyTargetResolver.scala: ########## @@ -0,0 +1,212 @@ +/* + * 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.api + +import java.net.URI +import java.nio.charset.StandardCharsets.UTF_8 +import java.util.{Base64, Locale, UUID} + +import scala.util.Try +import scala.util.control.NonFatal + +import org.apache.kyuubi.Utils +import org.apache.kyuubi.config.KyuubiConf.ENGINE_DO_AS_ENABLED +import org.apache.kyuubi.config.KyuubiReservedKeys.{KYUUBI_ENGINE_APP_MGR_INFO_KEY, KYUUBI_ENGINE_ID, KYUUBI_ENGINE_URL} +import org.apache.kyuubi.engine.{ApplicationManagerInfo, ApplicationState, EngineType} +import org.apache.kyuubi.ha.HighAvailabilityConf.HA_NAMESPACE +import org.apache.kyuubi.ha.client.{DiscoveryClient, DiscoveryPaths, ServiceNodeInfo} +import org.apache.kyuubi.ha.client.DiscoveryClientProvider.createDiscoveryClient +import org.apache.kyuubi.operation.OperationState +import org.apache.kyuubi.server.KyuubiRestFrontendService +import org.apache.kyuubi.session.SessionHandle + +/** Resolves UI destinations from server-owned resource records, never from a client URL. */ +private[api] class EngineUIProxyTargetResolver(fe: KyuubiRestFrontendService) + extends AutoCloseable { + import EngineUIProxyTargetResolver._ + + private var client: Option[DiscoveryClient] = None + @volatile private var closed = false + + private def discoveryClient: DiscoveryClient = synchronized { + require(!closed, "Engine UI target resolver is closed") + client.getOrElse { + val created = createDiscoveryClient(fe.getConf) + try { + created.createClient() + client = Some(created) + created + } catch { + case NonFatal(e) => + Utils.tryLogNonFatalError(created.closeClient()) + throw e + } + } + } + + override def close(): Unit = synchronized { + closed = true + try client.foreach(_.closeClient()) + finally client = None + } + + def resolveResource(kind: String, reference: String): Option[EngineUIProxyTarget] = { + require(!closed, "Engine UI target resolver is closed") + kind match { + case "engines" => resolveEngine(reference) + case "batches" => resolveBatch(reference) + case _ => None + } + } + + private def resolveEngine(reference: String): Option[EngineUIProxyTarget] = { + decodeReference(reference).flatMap { case (namespace, refId) => + engineScope(namespace, fe.getConf.get(HA_NAMESPACE)).flatMap { + case (_, owner) => Review Comment: Design note, not blocking: the engine reference works as the access token. Any authenticated user holding it can open that engine's UI; `owner` is only used as the YARN proxy user. This is fine today because the engine list is filtered per user for non-admins, but it is worth documenting. An owner-or-admin check would be a cheap guard if references leak, e.g., via shared links. ########## kyuubi-ha/src/main/scala/org/apache/kyuubi/ha/client/etcd/EtcdDiscoveryClient.scala: ########## @@ -220,7 +220,8 @@ class EtcdDiscoveryClient(conf: KyuubiConf) extends DiscoveryClient { sizeOpt: Option[Int] = None, silent: Boolean = false): Seq[ServiceNodeInfo] = { try { - val hosts = getChildren(DiscoveryPaths.makePath(null, namespace)) + // Service records are children of this namespace, not keys sharing its name prefix. + val hosts = getChildren(DiscoveryPaths.makePath(null, namespace) + "/") Review Comment: This etcd prefix fix is a standalone bug fix; please move it (with its test) to a separate PR. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/http/authentication/AuthenticationFilter.scala: ########## @@ -123,6 +123,9 @@ class AuthenticationFilter(conf: KyuubiConf) extends Filter with Logging { try { if (matchedHandler == null) { + if (Option(authorization).forall(_.isEmpty) && authSchemeHandlers.contains(NEGOTIATE)) { + httpResponse.setHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE_SCHEME) Review Comment: This adds `WWW-Authenticate: Negotiate` to every REST 401, not only Engine UI proxy requests. Reasonable, but please call it out in the PR description, together with the new `POST /api/v1/logout` endpoint. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyServlet.scala: ########## @@ -17,150 +17,311 @@ package org.apache.kyuubi.server.api -import java.net.{URI, URL} +import java.io.IOException +import java.net.URI +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets.ISO_8859_1 import java.util.Locale import java.util.regex.Pattern import javax.servlet.http.{HttpServletRequest, HttpServletResponse} import scala.util.Try +import scala.util.control.NonFatal -import org.apache.commons.lang3.StringUtils -import org.eclipse.jetty.client.api.Request -import org.eclipse.jetty.proxy.ProxyServlet +import org.eclipse.jetty.client.{HttpClient, HttpRedirector, HttpRequest, RedirectProtocolHandler} +import org.eclipse.jetty.client.api.{Request, Response, Result} +import org.eclipse.jetty.proxy.AsyncMiddleManServlet +import org.eclipse.jetty.proxy.AsyncMiddleManServlet.{ContentTransformer, GZIPContentTransformer} import org.apache.kyuubi.Logging import org.apache.kyuubi.config.KyuubiConf import org.apache.kyuubi.server.KyuubiRestFrontendService private[api] class EngineUIProxyServlet( proxyEnabled: Boolean, - allowedHosts: Set[String]) extends ProxyServlet with Logging { - - private val allowedHostPatterns = - allowedHosts.map(EngineUIProxyServlet.normalizeHost).filter(_.nonEmpty).map( - EngineUIProxyServlet.wildcardHostPattern) + resolveTarget: (String, String) => Option[EngineUIProxyTarget]) extends AsyncMiddleManServlet + with Logging { + import EngineUIProxyServlet._ override def rewriteTarget(request: HttpServletRequest): String = { - val requestURL = request.getRequestURL - val requestURI = request.getRequestURI - // A null target is handled by onProxyRewriteFailed with an actionable 403 response. - val targetURL = allowedTarget(requestURI).map { targetAddress => - val targetURI = targetAddress.path match { - // for some reason, the proxy can not handle redirect well, as a workaround, - // we simulate the Spark UI redirection behavior and forcibly rewrite the - // empty URI to the Spark Jobs page. - case "" | "/" => "/jobs/" - case path => path + if (!proxyEnabled) return null + parseRoute(request.getRequestURI).flatMap { case (kind, reference, path) => + try { + resolveTarget(kind, reference).map { resource => + val target = resource.uri + val basePath = Option(target.getRawPath).getOrElse("").stripSuffix("/") + val suffix = if (path.isEmpty || path == "/") { + if (basePath.isEmpty) "/jobs/" else "/" + } else path + val query = Option(request.getQueryString).filter(_.nonEmpty).map("?" + _).getOrElse("") + val targetURL = s"${target.getScheme}://${target.getRawAuthority}$basePath$suffix$query" + request.setAttribute( + CONTEXT_ATTRIBUTE, + new ProxyContext(resource, s"/engine-ui/$kind/$reference")) + targetURL + } + } catch { + case NonFatal(e) => + error(s"Unable to resolve Engine UI $kind resource $reference", e) + None } - val targetQueryString = - Option( - request.getQueryString).filter(StringUtils.isNotEmpty).map(q => s"?$q").getOrElse("") - new URL( - "http", - targetAddress.host, - targetAddress.port, - targetURI + targetQueryString).toString }.orNull - debug(s"rewrite $requestURL => $targetURL") - targetURL } override def onProxyRewriteFailed( request: HttpServletRequest, response: HttpServletResponse): Unit = { - val (title, message) = deniedRequestMessage(request.getRequestURI) response.setStatus(HttpServletResponse.SC_FORBIDDEN) response.setCharacterEncoding("UTF-8") response.setContentType("text/html") - response.getWriter.write(EngineUIProxyServlet.errorPage( - title, - message, - extractTargetAddress(request.getRequestURI))) + val message = if (!proxyEnabled) { + s"Ask an administrator to enable <code>${ + KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_ENABLED.key + }</code>." + } else { + "Open the UI from an active Engine or Batch in the Kyuubi Web UI." + } + response.getWriter.write(errorPage("Engine UI is not accessible", message)) + } + + override protected def createHttpClient(): HttpClient = { + val client = super.createHttpClient() + val redirector = new ApplicationRedirector(client) + client.getProtocolHandlers.put(new RedirectProtocolHandler(client) { + private def context(request: Request): ProxyContext = + request.asInstanceOf[HttpRequest].getConversation + .getAttribute(CONTEXT_ATTRIBUTE).asInstanceOf[ProxyContext] + + override def accept(proxyRequest: Request, response: Response): Boolean = { + val proxy = context(proxyRequest) + proxy != null && proxy.proxyBase.isEmpty && + Set("GET", "HEAD").contains(proxyRequest.getMethod) && + Set(301, 302, 303, 307, 308).contains(response.getStatus) && + proxy.resource.applicationPath.nonEmpty + } + + override def onComplete(result: Result): Unit = { + if (result.isFailed) { + super.onComplete(result) + return + } + val proxy = context(result.getRequest) + val resource = proxy.resource + try { + val location = Option(result.getResponse.getHeaders.get("Location")) + .getOrElse(throw new IOException("Application redirect has no Location")) + val source = result.getRequest.getURI + val redirect = source.resolve(location) + val destination = + if (rewriteLocation( + proxy.target, + source, + proxy.prefix, + location).nonEmpty) { + Some(redirect) + } else { + resource.resolveProxy().flatMap(approvedProxyRedirect( + _, + redirect)).map { approved => + val proxyBase = new URI( + s"${approved.getScheme}://${approved.getRawAuthority}" + + s"${resource.applicationPath.get}/") + proxy.proxyBase = Some(proxyBase) + approved + } + } + destination match { + case Some(approved) => + result.getResponse.getHeaders.put("Location", approved.toString) + super.onComplete(result) + case None => + redirector.reject( + result, + new IOException("Application redirect is outside its target")) + } + } catch { + case NonFatal(e) => redirector.reject(result, e) + } + } + }) + client + } + + override protected def copyRequestHeaders( + clientRequest: HttpServletRequest, + proxyRequest: Request): Unit = { + super.copyRequestHeaders(clientRequest, proxyRequest) + proxyRequest.asInstanceOf[HttpRequest].getConversation + .setAttribute(CONTEXT_ATTRIBUTE, proxyContext(clientRequest)) + // Kyuubi credentials must never reach the application being proxied. + Seq("Authorization", "Proxy-Authorization", "Cookie", "X-Forwarded-Context") + .foreach(proxyRequest.getHeaders.remove) + // Keep textual responses transformable even when browsers advertise Brotli support. + proxyRequest.header("Accept-Encoding", "identity") } override def addXForwardedHeaders( clientRequest: HttpServletRequest, proxyRequest: Request): Unit = { - allowedTarget(clientRequest.getRequestURI).foreach { - case TargetAddress(host, port, _) => - // SPARK-24209: Knox uses X-Forwarded-Context to notify the application the base path - proxyRequest.header("X-Forwarded-Context", s"/engine-ui/$host:$port") - } super.addXForwardedHeaders(clientRequest, proxyRequest) + proxyRequest.header( + "X-Forwarded-Context", + proxyContext(clientRequest).prefix) } - private def isAllowedHost(host: String): Boolean = - proxyEnabled && { - val normalizedHost = EngineUIProxyServlet.normalizeHost(host) - allowedHostPatterns.exists(_.matcher(normalizedHost).matches()) + override protected def newServerResponseContentTransformer( + request: HttpServletRequest, + proxyResponse: HttpServletResponse, + response: Response): ContentTransformer = { + val context = proxyContext(request) + val base = context.target + val resource = context.resource + val applicationBase = resource.applicationPath.map { path => + new URI(s"${base.getScheme}://${base.getRawAuthority}$path/") + }.getOrElse(base) + val basePath = Option(applicationBase.getRawPath).getOrElse("").stripSuffix("/") + val contentType = Option(response.getHeaders.get("Content-Type")) + .getOrElse("").takeWhile(_ != ';').trim.toLowerCase(Locale.ROOT) + if (basePath.isEmpty || !Set( + "text/html", + "application/xhtml+xml", + "text/css", + "text/javascript", + "application/javascript").contains(contentType)) { + return ContentTransformer.IDENTITY } + val transformer = new ApplicationPathTransformer( + applicationBase, + proxyContext(request).prefix) + Option(response.getHeaders.get("Content-Encoding")).map(_.toLowerCase(Locale.ROOT)) match { + case None | Some("identity") => transformer + case Some("gzip") => new GZIPContentTransformer(transformer) + case _ => ContentTransformer.IDENTITY + } + } - private def allowedTarget(requestURI: String): Option[TargetAddress] = - extractTargetAddress(requestURI).filter(target => isAllowedHost(target.host)) - - private[api] def deniedRequestMessage(requestURI: String): (String, String) = { - if (!proxyEnabled) { - val allowedHost = extractTargetAddress(requestURI) - .map(target => s"add <code>${EngineUIProxyServlet.escapeHtml(target.host)}</code> to") - .getOrElse("add the target host to") - ( - "Engine UI proxy is disabled", - s"Ask an administrator to set <code>${ - KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_ENABLED.key - }</code> to <code>true</code>, then $allowedHost <code>${ - KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_HOSTS.key - }</code>.") - } else { - extractTargetAddress(requestURI) match { - case Some(target) => - val escapedHost = EngineUIProxyServlet.escapeHtml(target.host) - ( - "Engine UI host is not allowed", - s"Ask an administrator to add <code>$escapedHost</code> " + - s"to <code>${KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_HOSTS.key}</code>.") - case None => - ( - "Invalid Engine UI address", - "The URL must include an engine host and port, for example " + - "<code>/engine-ui/spark.example.com:4040/</code>.") - } + override protected def filterServerResponseHeader( + request: HttpServletRequest, + response: Response, + name: String, + value: String): String = { + if (name.equalsIgnoreCase("Set-Cookie")) return null + if (name.equalsIgnoreCase("Location")) { + val context = proxyContext(request) + return rewriteLocation( + context.target, + response.getRequest.getURI, + context.prefix, + value).orNull } + super.filterServerResponseHeader(request, response, name, value) } +} - private[api] def extractTargetAddress(requestURI: String): Option[TargetAddress] = { - val target = requestURI.stripPrefix("/engine-ui/") - if (target == requestURI) { - None - } else { - Try(new URI(s"http://$target")).toOption.flatMap { uri => - for { - host <- Option(uri.getHost) - port <- Option(uri.getPort).filter(_ >= 0) - } yield TargetAddress( - host, - port, - Option(uri.getRawPath).filter(_.nonEmpty).getOrElse("/")) +private[api] object EngineUIProxyServlet { + private val CONTEXT_ATTRIBUTE = "kyuubi.engine.ui.context" + + private class ProxyContext(val resource: EngineUIProxyTarget, val prefix: String) { + var proxyBase: Option[URI] = None Review Comment: Nit: `proxyBase` is written on an HttpClient thread and read on servlet threads; mark it `@volatile`. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyServlet.scala: ########## @@ -17,150 +17,311 @@ package org.apache.kyuubi.server.api -import java.net.{URI, URL} +import java.io.IOException +import java.net.URI +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets.ISO_8859_1 import java.util.Locale import java.util.regex.Pattern import javax.servlet.http.{HttpServletRequest, HttpServletResponse} import scala.util.Try +import scala.util.control.NonFatal -import org.apache.commons.lang3.StringUtils -import org.eclipse.jetty.client.api.Request -import org.eclipse.jetty.proxy.ProxyServlet +import org.eclipse.jetty.client.{HttpClient, HttpRedirector, HttpRequest, RedirectProtocolHandler} +import org.eclipse.jetty.client.api.{Request, Response, Result} +import org.eclipse.jetty.proxy.AsyncMiddleManServlet +import org.eclipse.jetty.proxy.AsyncMiddleManServlet.{ContentTransformer, GZIPContentTransformer} import org.apache.kyuubi.Logging import org.apache.kyuubi.config.KyuubiConf import org.apache.kyuubi.server.KyuubiRestFrontendService private[api] class EngineUIProxyServlet( proxyEnabled: Boolean, - allowedHosts: Set[String]) extends ProxyServlet with Logging { - - private val allowedHostPatterns = - allowedHosts.map(EngineUIProxyServlet.normalizeHost).filter(_.nonEmpty).map( - EngineUIProxyServlet.wildcardHostPattern) + resolveTarget: (String, String) => Option[EngineUIProxyTarget]) extends AsyncMiddleManServlet + with Logging { + import EngineUIProxyServlet._ override def rewriteTarget(request: HttpServletRequest): String = { - val requestURL = request.getRequestURL - val requestURI = request.getRequestURI - // A null target is handled by onProxyRewriteFailed with an actionable 403 response. - val targetURL = allowedTarget(requestURI).map { targetAddress => - val targetURI = targetAddress.path match { - // for some reason, the proxy can not handle redirect well, as a workaround, - // we simulate the Spark UI redirection behavior and forcibly rewrite the - // empty URI to the Spark Jobs page. - case "" | "/" => "/jobs/" - case path => path + if (!proxyEnabled) return null + parseRoute(request.getRequestURI).flatMap { case (kind, reference, path) => + try { + resolveTarget(kind, reference).map { resource => + val target = resource.uri + val basePath = Option(target.getRawPath).getOrElse("").stripSuffix("/") + val suffix = if (path.isEmpty || path == "/") { + if (basePath.isEmpty) "/jobs/" else "/" + } else path + val query = Option(request.getQueryString).filter(_.nonEmpty).map("?" + _).getOrElse("") + val targetURL = s"${target.getScheme}://${target.getRawAuthority}$basePath$suffix$query" + request.setAttribute( + CONTEXT_ATTRIBUTE, + new ProxyContext(resource, s"/engine-ui/$kind/$reference")) + targetURL + } + } catch { + case NonFatal(e) => + error(s"Unable to resolve Engine UI $kind resource $reference", e) + None } - val targetQueryString = - Option( - request.getQueryString).filter(StringUtils.isNotEmpty).map(q => s"?$q").getOrElse("") - new URL( - "http", - targetAddress.host, - targetAddress.port, - targetURI + targetQueryString).toString }.orNull - debug(s"rewrite $requestURL => $targetURL") - targetURL } override def onProxyRewriteFailed( request: HttpServletRequest, response: HttpServletResponse): Unit = { - val (title, message) = deniedRequestMessage(request.getRequestURI) response.setStatus(HttpServletResponse.SC_FORBIDDEN) response.setCharacterEncoding("UTF-8") response.setContentType("text/html") - response.getWriter.write(EngineUIProxyServlet.errorPage( - title, - message, - extractTargetAddress(request.getRequestURI))) + val message = if (!proxyEnabled) { + s"Ask an administrator to enable <code>${ + KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_ENABLED.key + }</code>." + } else { + "Open the UI from an active Engine or Batch in the Kyuubi Web UI." + } + response.getWriter.write(errorPage("Engine UI is not accessible", message)) + } + + override protected def createHttpClient(): HttpClient = { + val client = super.createHttpClient() + val redirector = new ApplicationRedirector(client) + client.getProtocolHandlers.put(new RedirectProtocolHandler(client) { + private def context(request: Request): ProxyContext = + request.asInstanceOf[HttpRequest].getConversation + .getAttribute(CONTEXT_ATTRIBUTE).asInstanceOf[ProxyContext] + + override def accept(proxyRequest: Request, response: Response): Boolean = { + val proxy = context(proxyRequest) + proxy != null && proxy.proxyBase.isEmpty && + Set("GET", "HEAD").contains(proxyRequest.getMethod) && + Set(301, 302, 303, 307, 308).contains(response.getStatus) && + proxy.resource.applicationPath.nonEmpty + } + + override def onComplete(result: Result): Unit = { + if (result.isFailed) { + super.onComplete(result) + return + } + val proxy = context(result.getRequest) + val resource = proxy.resource + try { + val location = Option(result.getResponse.getHeaders.get("Location")) + .getOrElse(throw new IOException("Application redirect has no Location")) + val source = result.getRequest.getURI + val redirect = source.resolve(location) + val destination = + if (rewriteLocation( + proxy.target, + source, + proxy.prefix, + location).nonEmpty) { + Some(redirect) + } else { + resource.resolveProxy().flatMap(approvedProxyRedirect( + _, + redirect)).map { approved => + val proxyBase = new URI( + s"${approved.getScheme}://${approved.getRawAuthority}" + + s"${resource.applicationPath.get}/") + proxy.proxyBase = Some(proxyBase) + approved + } + } + destination match { + case Some(approved) => + result.getResponse.getHeaders.put("Location", approved.toString) + super.onComplete(result) + case None => + redirector.reject( + result, + new IOException("Application redirect is outside its target")) + } + } catch { + case NonFatal(e) => redirector.reject(result, e) + } + } + }) + client + } + + override protected def copyRequestHeaders( + clientRequest: HttpServletRequest, + proxyRequest: Request): Unit = { + super.copyRequestHeaders(clientRequest, proxyRequest) + proxyRequest.asInstanceOf[HttpRequest].getConversation + .setAttribute(CONTEXT_ATTRIBUTE, proxyContext(clientRequest)) + // Kyuubi credentials must never reach the application being proxied. + Seq("Authorization", "Proxy-Authorization", "Cookie", "X-Forwarded-Context") Review Comment: With a Kerberized ResourceManager web proxy (`hadoop.http.authentication.type=kerberos`), the redirect-following path sends no SPNEGO and the `Authorization` header is stripped here, so the RM proxy will likely return 401. Please validate on a secured YARN cluster or document the limitation. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyServlet.scala: ########## @@ -17,150 +17,311 @@ package org.apache.kyuubi.server.api -import java.net.{URI, URL} +import java.io.IOException +import java.net.URI +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets.ISO_8859_1 import java.util.Locale import java.util.regex.Pattern import javax.servlet.http.{HttpServletRequest, HttpServletResponse} import scala.util.Try +import scala.util.control.NonFatal -import org.apache.commons.lang3.StringUtils -import org.eclipse.jetty.client.api.Request -import org.eclipse.jetty.proxy.ProxyServlet +import org.eclipse.jetty.client.{HttpClient, HttpRedirector, HttpRequest, RedirectProtocolHandler} +import org.eclipse.jetty.client.api.{Request, Response, Result} +import org.eclipse.jetty.proxy.AsyncMiddleManServlet +import org.eclipse.jetty.proxy.AsyncMiddleManServlet.{ContentTransformer, GZIPContentTransformer} import org.apache.kyuubi.Logging import org.apache.kyuubi.config.KyuubiConf import org.apache.kyuubi.server.KyuubiRestFrontendService private[api] class EngineUIProxyServlet( proxyEnabled: Boolean, - allowedHosts: Set[String]) extends ProxyServlet with Logging { - - private val allowedHostPatterns = - allowedHosts.map(EngineUIProxyServlet.normalizeHost).filter(_.nonEmpty).map( - EngineUIProxyServlet.wildcardHostPattern) + resolveTarget: (String, String) => Option[EngineUIProxyTarget]) extends AsyncMiddleManServlet + with Logging { + import EngineUIProxyServlet._ override def rewriteTarget(request: HttpServletRequest): String = { - val requestURL = request.getRequestURL - val requestURI = request.getRequestURI - // A null target is handled by onProxyRewriteFailed with an actionable 403 response. - val targetURL = allowedTarget(requestURI).map { targetAddress => - val targetURI = targetAddress.path match { - // for some reason, the proxy can not handle redirect well, as a workaround, - // we simulate the Spark UI redirection behavior and forcibly rewrite the - // empty URI to the Spark Jobs page. - case "" | "/" => "/jobs/" - case path => path + if (!proxyEnabled) return null + parseRoute(request.getRequestURI).flatMap { case (kind, reference, path) => + try { + resolveTarget(kind, reference).map { resource => Review Comment: This resolves the target on every proxied request: a ZooKeeper/etcd read for engines, or a metadata store query for remote batches. With cookie login, Basic authentication also runs on every request, i.e., one LDAP bind per request. A single Spark UI page issues dozens of JS/CSS/REST requests. Suggest a short-lived cache keyed by `(kind, reference)`. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyServlet.scala: ########## @@ -17,150 +17,311 @@ package org.apache.kyuubi.server.api -import java.net.{URI, URL} +import java.io.IOException +import java.net.URI +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets.ISO_8859_1 import java.util.Locale import java.util.regex.Pattern import javax.servlet.http.{HttpServletRequest, HttpServletResponse} import scala.util.Try +import scala.util.control.NonFatal -import org.apache.commons.lang3.StringUtils -import org.eclipse.jetty.client.api.Request -import org.eclipse.jetty.proxy.ProxyServlet +import org.eclipse.jetty.client.{HttpClient, HttpRedirector, HttpRequest, RedirectProtocolHandler} +import org.eclipse.jetty.client.api.{Request, Response, Result} +import org.eclipse.jetty.proxy.AsyncMiddleManServlet +import org.eclipse.jetty.proxy.AsyncMiddleManServlet.{ContentTransformer, GZIPContentTransformer} import org.apache.kyuubi.Logging import org.apache.kyuubi.config.KyuubiConf import org.apache.kyuubi.server.KyuubiRestFrontendService private[api] class EngineUIProxyServlet( proxyEnabled: Boolean, - allowedHosts: Set[String]) extends ProxyServlet with Logging { - - private val allowedHostPatterns = - allowedHosts.map(EngineUIProxyServlet.normalizeHost).filter(_.nonEmpty).map( - EngineUIProxyServlet.wildcardHostPattern) + resolveTarget: (String, String) => Option[EngineUIProxyTarget]) extends AsyncMiddleManServlet + with Logging { + import EngineUIProxyServlet._ override def rewriteTarget(request: HttpServletRequest): String = { - val requestURL = request.getRequestURL - val requestURI = request.getRequestURI - // A null target is handled by onProxyRewriteFailed with an actionable 403 response. - val targetURL = allowedTarget(requestURI).map { targetAddress => - val targetURI = targetAddress.path match { - // for some reason, the proxy can not handle redirect well, as a workaround, - // we simulate the Spark UI redirection behavior and forcibly rewrite the - // empty URI to the Spark Jobs page. - case "" | "/" => "/jobs/" - case path => path + if (!proxyEnabled) return null + parseRoute(request.getRequestURI).flatMap { case (kind, reference, path) => + try { + resolveTarget(kind, reference).map { resource => + val target = resource.uri + val basePath = Option(target.getRawPath).getOrElse("").stripSuffix("/") + val suffix = if (path.isEmpty || path == "/") { + if (basePath.isEmpty) "/jobs/" else "/" + } else path + val query = Option(request.getQueryString).filter(_.nonEmpty).map("?" + _).getOrElse("") + val targetURL = s"${target.getScheme}://${target.getRawAuthority}$basePath$suffix$query" + request.setAttribute( + CONTEXT_ATTRIBUTE, + new ProxyContext(resource, s"/engine-ui/$kind/$reference")) + targetURL + } + } catch { + case NonFatal(e) => + error(s"Unable to resolve Engine UI $kind resource $reference", e) + None } - val targetQueryString = - Option( - request.getQueryString).filter(StringUtils.isNotEmpty).map(q => s"?$q").getOrElse("") - new URL( - "http", - targetAddress.host, - targetAddress.port, - targetURI + targetQueryString).toString }.orNull - debug(s"rewrite $requestURL => $targetURL") - targetURL } override def onProxyRewriteFailed( request: HttpServletRequest, response: HttpServletResponse): Unit = { - val (title, message) = deniedRequestMessage(request.getRequestURI) response.setStatus(HttpServletResponse.SC_FORBIDDEN) response.setCharacterEncoding("UTF-8") response.setContentType("text/html") - response.getWriter.write(EngineUIProxyServlet.errorPage( - title, - message, - extractTargetAddress(request.getRequestURI))) + val message = if (!proxyEnabled) { + s"Ask an administrator to enable <code>${ + KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_ENABLED.key + }</code>." + } else { + "Open the UI from an active Engine or Batch in the Kyuubi Web UI." + } + response.getWriter.write(errorPage("Engine UI is not accessible", message)) + } + + override protected def createHttpClient(): HttpClient = { + val client = super.createHttpClient() + val redirector = new ApplicationRedirector(client) + client.getProtocolHandlers.put(new RedirectProtocolHandler(client) { + private def context(request: Request): ProxyContext = + request.asInstanceOf[HttpRequest].getConversation + .getAttribute(CONTEXT_ATTRIBUTE).asInstanceOf[ProxyContext] + + override def accept(proxyRequest: Request, response: Response): Boolean = { + val proxy = context(proxyRequest) + proxy != null && proxy.proxyBase.isEmpty && + Set("GET", "HEAD").contains(proxyRequest.getMethod) && + Set(301, 302, 303, 307, 308).contains(response.getStatus) && + proxy.resource.applicationPath.nonEmpty + } + + override def onComplete(result: Result): Unit = { + if (result.isFailed) { + super.onComplete(result) + return + } + val proxy = context(result.getRequest) + val resource = proxy.resource + try { + val location = Option(result.getResponse.getHeaders.get("Location")) + .getOrElse(throw new IOException("Application redirect has no Location")) + val source = result.getRequest.getURI + val redirect = source.resolve(location) + val destination = + if (rewriteLocation( + proxy.target, + source, + proxy.prefix, + location).nonEmpty) { + Some(redirect) + } else { + resource.resolveProxy().flatMap(approvedProxyRedirect( + _, + redirect)).map { approved => + val proxyBase = new URI( + s"${approved.getScheme}://${approved.getRawAuthority}" + + s"${resource.applicationPath.get}/") + proxy.proxyBase = Some(proxyBase) + approved + } + } + destination match { + case Some(approved) => + result.getResponse.getHeaders.put("Location", approved.toString) + super.onComplete(result) + case None => + redirector.reject( + result, + new IOException("Application redirect is outside its target")) + } + } catch { + case NonFatal(e) => redirector.reject(result, e) + } + } + }) + client + } + + override protected def copyRequestHeaders( + clientRequest: HttpServletRequest, + proxyRequest: Request): Unit = { + super.copyRequestHeaders(clientRequest, proxyRequest) + proxyRequest.asInstanceOf[HttpRequest].getConversation + .setAttribute(CONTEXT_ATTRIBUTE, proxyContext(clientRequest)) + // Kyuubi credentials must never reach the application being proxied. + Seq("Authorization", "Proxy-Authorization", "Cookie", "X-Forwarded-Context") + .foreach(proxyRequest.getHeaders.remove) + // Keep textual responses transformable even when browsers advertise Brotli support. + proxyRequest.header("Accept-Encoding", "identity") } override def addXForwardedHeaders( clientRequest: HttpServletRequest, proxyRequest: Request): Unit = { - allowedTarget(clientRequest.getRequestURI).foreach { - case TargetAddress(host, port, _) => - // SPARK-24209: Knox uses X-Forwarded-Context to notify the application the base path - proxyRequest.header("X-Forwarded-Context", s"/engine-ui/$host:$port") - } super.addXForwardedHeaders(clientRequest, proxyRequest) + proxyRequest.header( + "X-Forwarded-Context", + proxyContext(clientRequest).prefix) } - private def isAllowedHost(host: String): Boolean = - proxyEnabled && { - val normalizedHost = EngineUIProxyServlet.normalizeHost(host) - allowedHostPatterns.exists(_.matcher(normalizedHost).matches()) + override protected def newServerResponseContentTransformer( + request: HttpServletRequest, + proxyResponse: HttpServletResponse, + response: Response): ContentTransformer = { + val context = proxyContext(request) + val base = context.target + val resource = context.resource + val applicationBase = resource.applicationPath.map { path => + new URI(s"${base.getScheme}://${base.getRawAuthority}$path/") + }.getOrElse(base) + val basePath = Option(applicationBase.getRawPath).getOrElse("").stripSuffix("/") + val contentType = Option(response.getHeaders.get("Content-Type")) + .getOrElse("").takeWhile(_ != ';').trim.toLowerCase(Locale.ROOT) + if (basePath.isEmpty || !Set( + "text/html", + "application/xhtml+xml", + "text/css", + "text/javascript", + "application/javascript").contains(contentType)) { + return ContentTransformer.IDENTITY } + val transformer = new ApplicationPathTransformer( + applicationBase, + proxyContext(request).prefix) + Option(response.getHeaders.get("Content-Encoding")).map(_.toLowerCase(Locale.ROOT)) match { + case None | Some("identity") => transformer + case Some("gzip") => new GZIPContentTransformer(transformer) + case _ => ContentTransformer.IDENTITY + } + } - private def allowedTarget(requestURI: String): Option[TargetAddress] = - extractTargetAddress(requestURI).filter(target => isAllowedHost(target.host)) - - private[api] def deniedRequestMessage(requestURI: String): (String, String) = { - if (!proxyEnabled) { - val allowedHost = extractTargetAddress(requestURI) - .map(target => s"add <code>${EngineUIProxyServlet.escapeHtml(target.host)}</code> to") - .getOrElse("add the target host to") - ( - "Engine UI proxy is disabled", - s"Ask an administrator to set <code>${ - KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_ENABLED.key - }</code> to <code>true</code>, then $allowedHost <code>${ - KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_HOSTS.key - }</code>.") - } else { - extractTargetAddress(requestURI) match { - case Some(target) => - val escapedHost = EngineUIProxyServlet.escapeHtml(target.host) - ( - "Engine UI host is not allowed", - s"Ask an administrator to add <code>$escapedHost</code> " + - s"to <code>${KyuubiConf.FRONTEND_REST_ENGINE_UI_PROXY_HOSTS.key}</code>.") - case None => - ( - "Invalid Engine UI address", - "The URL must include an engine host and port, for example " + - "<code>/engine-ui/spark.example.com:4040/</code>.") - } + override protected def filterServerResponseHeader( + request: HttpServletRequest, + response: Response, + name: String, + value: String): String = { + if (name.equalsIgnoreCase("Set-Cookie")) return null + if (name.equalsIgnoreCase("Location")) { + val context = proxyContext(request) + return rewriteLocation( Review Comment: Returning null drops `Location` but keeps the 3xx status. Verified: a driver answering `302 Location: http://<rm>:8088/cluster` reaches the browser as `302`, `Content-Length: 0`, no `Location`, which is a failed navigation. This hits the RM `/proxy/<app>/` -> `/cluster` case and redirects to the Spark History Server after the app finishes. Returning the 403 error page would be clearer. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/http/authentication/EngineUIAuthenticationFilter.scala: ########## @@ -0,0 +1,185 @@ +/* + * 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.http.authentication + +import java.net.{URI, URLEncoder} +import java.nio.charset.StandardCharsets.UTF_8 +import java.util.Base64 +import javax.servlet.{FilterChain, ServletRequest, ServletResponse} +import javax.servlet.http.{HttpServletRequest, HttpServletRequestWrapper, HttpServletResponse, HttpServletResponseWrapper} + +import scala.util.Try + +import org.apache.kyuubi.config.KyuubiConf +import org.apache.kyuubi.config.KyuubiConf.{FRONTEND_REST_ENGINE_UI_PROXY_AUTH_ENABLED, FRONTEND_REST_ENGINE_UI_PROXY_ENABLED, FRONTEND_REST_UI_ENABLED} + +/** Carries Web UI Basic credentials to the existing authentication chain on every proxy request. */ +private[server] class EngineUIAuthenticationFilter(conf: KyuubiConf, proxy: Boolean) Review Comment: With `proxy = false` this class guards all of `/api/v1/*` and hardcodes `/api/v1/ping` and `/api/v1/logout`. Setting/clearing the cookie in the ping and logout resources, or in a small separate filter, would avoid the boolean-mode class. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/EngineUIProxyTargetResolver.scala: ########## @@ -0,0 +1,212 @@ +/* + * 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.api + +import java.net.URI +import java.nio.charset.StandardCharsets.UTF_8 +import java.util.{Base64, Locale, UUID} + +import scala.util.Try +import scala.util.control.NonFatal + +import org.apache.kyuubi.Utils +import org.apache.kyuubi.config.KyuubiConf.ENGINE_DO_AS_ENABLED +import org.apache.kyuubi.config.KyuubiReservedKeys.{KYUUBI_ENGINE_APP_MGR_INFO_KEY, KYUUBI_ENGINE_ID, KYUUBI_ENGINE_URL} +import org.apache.kyuubi.engine.{ApplicationManagerInfo, ApplicationState, EngineType} +import org.apache.kyuubi.ha.HighAvailabilityConf.HA_NAMESPACE +import org.apache.kyuubi.ha.client.{DiscoveryClient, DiscoveryPaths, ServiceNodeInfo} +import org.apache.kyuubi.ha.client.DiscoveryClientProvider.createDiscoveryClient +import org.apache.kyuubi.operation.OperationState +import org.apache.kyuubi.server.KyuubiRestFrontendService +import org.apache.kyuubi.session.SessionHandle + +/** Resolves UI destinations from server-owned resource records, never from a client URL. */ +private[api] class EngineUIProxyTargetResolver(fe: KyuubiRestFrontendService) + extends AutoCloseable { + import EngineUIProxyTargetResolver._ + + private var client: Option[DiscoveryClient] = None + @volatile private var closed = false + + private def discoveryClient: DiscoveryClient = synchronized { + require(!closed, "Engine UI target resolver is closed") + client.getOrElse { + val created = createDiscoveryClient(fe.getConf) + try { + created.createClient() + client = Some(created) + created + } catch { + case NonFatal(e) => + Utils.tryLogNonFatalError(created.closeClient()) + throw e + } + } + } + + override def close(): Unit = synchronized { + closed = true + try client.foreach(_.closeClient()) + finally client = None + } + + def resolveResource(kind: String, reference: String): Option[EngineUIProxyTarget] = { + require(!closed, "Engine UI target resolver is closed") + kind match { + case "engines" => resolveEngine(reference) + case "batches" => resolveBatch(reference) + case _ => None + } + } + + private def resolveEngine(reference: String): Option[EngineUIProxyTarget] = { + decodeReference(reference).flatMap { case (namespace, refId) => + engineScope(namespace, fe.getConf.get(HA_NAMESPACE)).flatMap { + case (_, owner) => + val nodes = discoveryClient.getServiceNodesInfo(namespace) + .filter(_.engineRefId.contains(refId)) + // Never pick an arbitrary incarnation when discovery contains duplicate records. + if (nodes.size == 1) engineTarget(nodes.head, refId, owner) else None + } + } + } + + private def engineTarget( + node: ServiceNodeInfo, + refId: String, + owner: String): Option[EngineUIProxyTarget] = { + node.attributes.get(KYUUBI_ENGINE_URL).flatMap(parseTarget).map { uri => + val managerInfo = node.attributes.get(KYUUBI_ENGINE_APP_MGR_INFO_KEY) + .map(ApplicationManagerInfo.deserialize) + if (managerInfo.exists(_.resourceManager.exists( + _.toLowerCase(Locale.ROOT).startsWith("yarn")))) { + val applicationId = node.attributes.get(KYUUBI_ENGINE_ID) + val applicationPath = applicationId.filter(_.matches("application_[0-9]+_[0-9]+")) + .map("/proxy/" + _) + val proxyUser = + if (fe.getConf.get(ENGINE_DO_AS_ENABLED)) { + owner + } else Utils.currentUser + EngineUIProxyTarget( + uri, + applicationPath, + () => { + // Query only when the driver requires its web proxy. A directly accessible UI + // must not depend on the ResourceManager or its web proxy being available. + fe.sessionManager.applicationManager + .getApplicationInfo(managerInfo.get, refId, Some(proxyUser)) + .filter(info => + applicationId.contains(info.id) && + !ApplicationState.isTerminated(info.state)) + .flatMap(_.url).flatMap(parseTarget) + }) + } else EngineUIProxyTarget(uri) + } + } + + private def batchTarget(url: Option[String], applicationId: Option[String]) + : Option[EngineUIProxyTarget] = { + url.flatMap(parseTarget).map { uri => + EngineUIProxyTarget( + uri, + applicationId.filter(_.matches("application_[0-9]+_[0-9]+")).map("/proxy/" + _)) + } + } + + private def resolveBatch(reference: String): Option[EngineUIProxyTarget] = { + Try(SessionHandle.fromUUID(reference)).toOption.flatMap { handle => + val manager = fe.sessionManager + manager.getBatchSession(handle) match { + case Some(session) => + val operation = session.batchJobSubmissionOp + if (OperationState.isTerminal(operation.getStatus.state)) None + else operation.getApplicationInfo.filterNot(info => + ApplicationState.isTerminated(info.state)) + .flatMap(info => batchTarget(info.url, Option(info.id))) + case None => + manager.getBatchMetadata(reference).flatMap { metadata => + if (metadata.state == null || + OperationState.isTerminal(OperationState.withName(metadata.state)) || + metadata.appState.exists(ApplicationState.isTerminated)) { + None + } else { + batchTarget(Option(metadata.engineUrl), Option(metadata.engineId)) + } + } + } + } + } + +} + +private[api] case class EngineUIProxyTarget( + uri: URI, + applicationPath: Option[String] = None, + resolveProxy: () => Option[URI] = () => None) + +private[api] object EngineUIProxyTargetResolver { + val REFERENCE_ATTRIBUTE = "kyuubi.engine.ui.proxy.ref" + private val shareLevels = Seq("SERVER_LOCAL", "CONNECTION", "SERVER", "GROUP", "USER") Review Comment: Nit: this duplicates `ShareLevel` in kyuubi-common; use `ShareLevel.values`. The share level returned by `engineScope` is also unused. ########## kyuubi-server/src/main/scala/org/apache/kyuubi/server/api/v1/AdminResource.scala: ########## @@ -374,7 +374,8 @@ private[v1] class AdminResource extends ApiRequestContext with Logging { node.namespace.split("/").last, node.instance, node.namespace, - node.attributes.asJava)) + (node.attributes ++ EngineUIProxyTargetResolver.reference(node).map( + EngineUIProxyTargetResolver.REFERENCE_ATTRIBUTE -> _)).asJava)) Review Comment: Add `kyuubi.engine.ui.proxy.ref` only when the Engine UI proxy is enabled. -- 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
