dongjoon-hyun commented on code in PR #58965:
URL: https://github.com/apache/spark/pull/58965#discussion_r4499699765


##########
core/src/main/scala/org/apache/spark/deploy/history/FsHistoryProvider.scala:
##########
@@ -447,7 +447,7 @@ private[history] class FsHistoryProvider(conf: SparkConf, 
clock: Clock)
       attempt.info.startTime.getTime(), attempt.info.appSparkVersion)
 
     // place the tab in UI based on the display order
-    loadPlugins().toSeq.sortBy(_.displayOrder).foreach(_.setupUI(ui))
+    
AppHistoryServerPlugin.loadPlugins().sortBy(_.displayOrder).foreach(_.setupUI(ui))

Review Comment:
   **[21] With the default in-memory store, a broken plugin still fails every 
application UI load.**
   
   This line now skips a plugin that fails to load, but with such a plugin it 
is never reached. Before it, L432-443 build the store. With 
`spark.history.store.path` unset, which is the default, that is 
`createInMemoryStore`, which replays the event log through `rebuildAppStore`, 
and there `loadPluginsOrFail()` (L1442) throws the `ServiceConfigurationError` 
or `NoClassDefFoundError`. It is an `Error`, so it passes the `case e: 
Exception` of `createInMemoryStore`, the `FileNotFoundException` catch at 
L440-442, `ApplicationCache.get`, which unwraps only `ExecutionException` and 
`UncheckedExecutionException`, and `loadAppUi`, which handles only 
`NoSuchElementException`. So every `/history/<appId>` request fails with a 500, 
as before this PR, while the startup warning from `skipUnloadable` makes it 
look as if the plugin had been skipped. The skip here takes effect only when 
`loadDiskStore` reopens a store that is already on disk, and then the UI is 
cached without that plugin's tabs until 
 it is evicted.
   
   This comes from the caveat in my item 13, which was about a store kept on 
disk. An in-memory store is never persisted, so the reason to fail fast does 
not apply to it. Could `getAppUI` load the plugins once, pass the same list to 
the store rebuild and to `setupUI`, and fail fast only when the store is 
persisted? If that is too much for this PR, the description ("a broken plugin 
no longer fails every application UI load") and the doc at 
AppHistoryServerPlugin.scala:72-73 could say that this holds only for a store 
that is already on disk.



##########
core/src/main/scala/org/apache/spark/deploy/history/HistoryServer.scala:
##########
@@ -163,6 +165,43 @@ class HistoryServer(
     attachHandler(contextHandler)
   }
 
+  /**
+   * Registers the static resources declared by the given plugins, as 
(classpath resource
+   * directory, URL path) pairs.
+   *
+   * A failure never prevents the History Server from starting. It is logged 
as a warning and
+   * the rest is still registered:
+   *  - if reading a plugin's `staticResources` throws, that plugin is skipped;
+   *  - each declared entry is registered independently, so one failing entry 
(for example a
+   *    missing directory) does not skip the plugin's later entries.
+   *
+   * A path that is not under `/static/` is rejected as a failing entry, 
because it could
+   * otherwise shadow the History Server's own routes.
+   */
+  private[history] def setupPluginStaticResources(
+      plugins: Seq[AppHistoryServerPlugin]): Unit = {
+    plugins.foreach { plugin =>
+      try {
+        plugin.staticResources.foreach { case (dir, path) =>
+          try {
+            require(path.startsWith(HistoryServer.PLUGIN_STATIC_PATH_PREFIX),

Review Comment:
   **[19] The `/static/` check runs on the raw path, but Jetty normalizes it 
afterwards.**
   
   In Jetty 12.1.13, `setContextPath` canonicalizes the path with 
`URIUtil.canonicalPath`, which also decodes `%2e`, and drops a trailing `/` or 
`/*`. So a path that passes `startsWith("/static/")` can still end up outside 
`/static/`, or on a path that the server already serves:
   
   - `/static/../history` (or `/static/%2e%2e/history`) becomes `/history`. 
`initialize()` attaches plugin handlers (L159) before the `/history` loader 
(L162-165), and of two handlers with the same path Jetty picks the one attached 
first. So every request for an application that is not loaded yet gets a 404 
from the plugin's `DefaultServlet`, and no application UI can be opened.
   - `/static/../api/v1` becomes `/api/v1`, the longest match for 
`/api/v1/applications`, which then returns 404.
   - `/static/` becomes `/static` and is silently shadowed by the core handler, 
while the test rejects `/static` itself.
   - `/static/webui.js` stays under `/static/`, but takes over that URL: it 
answers with a redirect to a listing of the plugin directory instead of serving 
the core `webui.js`.
   
   I checked these with a Jetty 12.1.13 `LocalConnector`. As in item 12, 
plugins are trusted code, so this is only about catching a mistake early. Could 
the check run on the created handler's `getContextPath`, which is the 
normalized path, and also reject a path that the server already serves? A 
stricter pattern would be simpler, for example 
`path.matches("/static/[\\w-]+")`, which rejects `..`, `%2e`, a trailing `/` 
and file names. Until then, L178-179 and AppHistoryServerPlugin.scala:49-50, 
which say that such paths cannot shadow the History Server's own routes, do not 
quite hold.



##########
core/src/main/scala/org/apache/spark/status/AppHistoryServerPlugin.scala:
##########
@@ -36,8 +44,82 @@ private[spark] trait AppHistoryServerPlugin {
    */
   def setupUI(ui: SparkUI): Unit
 
+  /**
+   * Static resources (JS/CSS) to serve from the History Server's own UI, as 
(classpath resource
+   * directory, URL path) pairs. They are registered once at startup. The URL 
path must be under
+   * /static/; other paths are rejected so they cannot shadow the History 
Server's own routes.
+   * The directory is resolved with Spark's class loader, not the plugin's, so 
it must be on
+   * Spark's class path. Unlike a handler attached in [[setupUI]], which is 
torn down when the
+   * application cache evicts that application, these live as long as the 
History Server.
+   *
+   * This does not replace the registration in [[setupUI]] or in the tabs: the 
live driver UI
+   * never calls this hook, so tabs must still register their own handlers.
+   */
+  def staticResources: Seq[(String, String)] = Nil
+
   /**
    * The position of a plugin tab relative to the other plugin tabs in the 
history UI.
    */
   def displayOrder: Int = Integer.MAX_VALUE
 }
+
+private[spark] object AppHistoryServerPlugin extends Logging {
+
+  // Consecutive load failures tolerated before giving up on the remaining 
plugins
+  private[spark] val MAX_LOAD_FAILURES = 10
+
+  /**
+   * Loads the available plugins, skipping with a warning any that cannot be 
loaded, so that a
+   * broken plugin does not take down the History Server or the loading of an 
application UI.
+   */
+  def loadPlugins(): Seq[AppHistoryServerPlugin] = 
skipUnloadable(loadPluginsOrFail())
+
+  /**
+   * Lazily loads the available plugins. A plugin that cannot be loaded makes 
iteration throw.
+   * Use this where a missing plugin must not go unnoticed.
+   */
+  def loadPluginsOrFail(): Iterable[AppHistoryServerPlugin] = {
+    ServiceLoader.load(classOf[AppHistoryServerPlugin], 
Utils.getContextOrSparkClassLoader).asScala
+  }
+
+  /**
+   * Iterates through the plugins and attempts to load them one by one. If a 
plugin
+   * fails to load, it increments a failure counter. If the number of 
consecutive failures reaches
+   * MAX_LOAD_FAILURES, the loading process is aborted and remaining plugins 
are skipped.
+   *
+   * @param plugins an iterable collection of AppHistoryServerPlugin instances 
to load
+   * @return a sequence of successfully loaded AppHistoryServerPlugin instances
+   *
+   * @note This method will stop loading after MAX_LOAD_FAILURES consecutive 
failures to prevent
+   *       infinite loops or excessive error conditions
+   * @note Successfully loading a plugin resets the consecutive failure counter
+   * @note Non-fatal exceptions and LinkageErrors are caught and logged as 
warnings
+   */
+  private[spark] def skipUnloadable(
+      plugins: Iterable[AppHistoryServerPlugin]): Seq[AppHistoryServerPlugin] 
= {
+    val iterator = plugins.iterator
+    val loaded = Seq.newBuilder[AppHistoryServerPlugin]
+    var keepLoading = true
+    var failuresInARow = 0
+    while (keepLoading && failuresInARow < MAX_LOAD_FAILURES) {
+      try {
+        if (iterator.hasNext) {
+          loaded += iterator.next()
+          failuresInARow = 0
+        } else {
+          keepLoading = false
+        }
+      } catch {
+        case t if NonFatal(t) || t.isInstanceOf[LinkageError] =>

Review Comment:
   **[23] A fatal error from a plugin's constructor is still skipped as a 
plugin that failed to load.**
   
   In item 9 I wrote that `NonFatal(t) || t.isInstanceOf[LinkageError]` would 
let a fatal error stop the startup, and the description now says "Fatal errors 
such as OutOfMemoryError are not caught". That holds for an error thrown by the 
iterator itself, but not for one thrown by a plugin's constructor or static 
initializer. There, the JDK's `ServiceLoader` (`ProviderImpl.newInstance`) 
catches any `Throwable`, `OutOfMemoryError` and `StackOverflowError` included, 
and rethrows it as the cause of a `ServiceConfigurationError`, for which 
`NonFatal` returns true. So such a plugin is skipped with a warning, at startup 
and in every `getAppUI`. I checked this with JDK 21 and Scala 2.13.18, also 
with a real heap OOM under `-Xmx64m`.
   
   This is minor, since the in-tree plugins have trivial constructors. Could a 
case such as `case e: ServiceConfigurationError if 
e.getCause.isInstanceOf[VirtualMachineError] => throw e.getCause` come first? 
Otherwise, the description could say that such errors are skipped too.



##########
sql/core/src/test/scala/org/apache/spark/deploy/history/SQLHistoryServerStaticResourceSuite.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * 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.spark.deploy.history
+
+import java.net.{URI, URL}
+
+import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
+import org.apache.spark.internal.config.History.HISTORY_LOG_DIR
+import org.apache.spark.util.Utils
+
+/**
+ * Verifies that the SQL plugin's static resources are served by the History 
Server itself, so
+ * they are available before any application UI has been loaded, while one is 
attached, and
+ * after it is detached (as happens when it is evicted from the application 
cache).
+ *
+ * The application's own SQL tab declares a handler for the same /static/sql 
path.
+ * HistoryServer.attachSparkUI skips it, since the History Server already 
serves that path, and
+ * the application's other pages must keep working.
+ */
+class SQLHistoryServerStaticResourceSuite extends SparkFunSuite {
+
+  private val staticResource = "/static/sql/spark-sql-viz.js"
+
+  private def withHistoryServer(logDir: String)(
+      fn: (HistoryServer, FsHistoryProvider) => Unit): Unit = {
+    val conf = new SparkConf().set(HISTORY_LOG_DIR, logDir)
+    val provider = new FsHistoryProvider(conf)
+    val server = new HistoryServer(conf, provider, new SecurityManager(conf), 
0)
+    try {
+      server.bind()
+      provider.checkForLogs()
+      fn(server, provider)
+    } finally {
+      server.stop()
+    }
+  }
+
+  private def urlOf(server: HistoryServer, path: String): URL = {
+    val host = Utils.localHostNameForURI()
+    new URI(s"http://$host:${server.boundPort}$path";).toURL
+  }
+
+  private def assertResourceServed(server: HistoryServer): Unit = {
+    val (code, body, _) = HistoryServerSuite.getContentAndCode(urlOf(server, 
staticResource))
+    assert(code === 200)
+    assert(body.exists(_.nonEmpty))
+  }
+
+  test("/static/sql resources are served before any application is loaded") {
+    withTempDir { logDir =>
+      withHistoryServer(logDir.getAbsolutePath) { (server, _) =>
+        assertResourceServed(server)
+      }
+    }
+  }
+
+  test("/static/sql resources are served while an application UI is attached 
and after " +
+      "it is detached") {
+    val appId = "local-1596020211915"
+    val logDir = 
Thread.currentThread().getContextClassLoader.getResource("spark-events").toString
+    withHistoryServer(logDir) { (server, provider) =>
+      val ui = provider.getAppUI(appId, None).getOrElse(fail(s"Failed to load 
$appId")).ui
+      // The application's own SQL tab declares a handler for the same path. 
attachSparkUI skips
+      // it because the History Server already serves that path, so the 
History Server's
+      // handler answers while the UI is attached and after it is detached.
+      assert(ui.getHandlers.exists(_.getContextPath == "/static/sql"))
+
+      server.attachSparkUI(appId, None, ui, completed = true)

Review Comment:
   **[26] Nothing here fails if `attachSparkUI` stops skipping the duplicate 
handler.**
   
   The class doc (L31-33) and the comment at L78-80 say that `attachSparkUI` 
skips the application's `/static/sql` handler, but every assertion here would 
still pass with the filter at HistoryServer.scala:230-231 removed. The server's 
own `/static/sql` handler is attached first and answers either way, the jobs 
page is served by the application's own handlers, and `detachSparkUI` removes 
only the application's handler instances, so L96 still gets 200. No other test 
covers the filter, which also skips the application's `/static` and `/api` 
handlers.
   
   Could the test assert, after `attachSparkUI`, that the application's 
`/static/sql` handler was not started? For example, 
`assert(!ui.getHandlers.find(_.getContextPath == 
"/static/sql").get.isStarted)`. `ServerInfo.addHandler` starts every handler it 
attaches, and the History Server never binds the application's `SparkUI`.



##########
core/src/main/scala/org/apache/spark/status/AppHistoryServerPlugin.scala:
##########
@@ -36,8 +44,82 @@ private[spark] trait AppHistoryServerPlugin {
    */
   def setupUI(ui: SparkUI): Unit
 
+  /**
+   * Static resources (JS/CSS) to serve from the History Server's own UI, as 
(classpath resource
+   * directory, URL path) pairs. They are registered once at startup. The URL 
path must be under
+   * /static/; other paths are rejected so they cannot shadow the History 
Server's own routes.
+   * The directory is resolved with Spark's class loader, not the plugin's, so 
it must be on
+   * Spark's class path. Unlike a handler attached in [[setupUI]], which is 
torn down when the
+   * application cache evicts that application, these live as long as the 
History Server.
+   *
+   * This does not replace the registration in [[setupUI]] or in the tabs: the 
live driver UI
+   * never calls this hook, so tabs must still register their own handlers.
+   */
+  def staticResources: Seq[(String, String)] = Nil
+
   /**
    * The position of a plugin tab relative to the other plugin tabs in the 
history UI.
    */
   def displayOrder: Int = Integer.MAX_VALUE
 }
+
+private[spark] object AppHistoryServerPlugin extends Logging {
+
+  // Consecutive load failures tolerated before giving up on the remaining 
plugins
+  private[spark] val MAX_LOAD_FAILURES = 10
+
+  /**
+   * Loads the available plugins, skipping with a warning any that cannot be 
loaded, so that a
+   * broken plugin does not take down the History Server or the loading of an 
application UI.
+   */
+  def loadPlugins(): Seq[AppHistoryServerPlugin] = 
skipUnloadable(loadPluginsOrFail())
+
+  /**
+   * Lazily loads the available plugins. A plugin that cannot be loaded makes 
iteration throw.
+   * Use this where a missing plugin must not go unnoticed.
+   */
+  def loadPluginsOrFail(): Iterable[AppHistoryServerPlugin] = {
+    ServiceLoader.load(classOf[AppHistoryServerPlugin], 
Utils.getContextOrSparkClassLoader).asScala
+  }
+
+  /**
+   * Iterates through the plugins and attempts to load them one by one. If a 
plugin
+   * fails to load, it increments a failure counter. If the number of 
consecutive failures reaches
+   * MAX_LOAD_FAILURES, the loading process is aborted and remaining plugins 
are skipped.
+   *
+   * @param plugins an iterable collection of AppHistoryServerPlugin instances 
to load
+   * @return a sequence of successfully loaded AppHistoryServerPlugin instances
+   *
+   * @note This method will stop loading after MAX_LOAD_FAILURES consecutive 
failures to prevent
+   *       infinite loops or excessive error conditions
+   * @note Successfully loading a plugin resets the consecutive failure counter
+   * @note Non-fatal exceptions and LinkageErrors are caught and logged as 
warnings
+   */
+  private[spark] def skipUnloadable(

Review Comment:
   **[30] On your question about `HadoopDelegationTokenManager.loadProviders`: 
I would leave the shared helper for a follow-up.**
   
   `skipUnloadable` is now the fourth copy of this loop, after 
`HadoopDelegationTokenManager.loadProviders` 
(HadoopDelegationTokenManager.scala:339-352), `loadExtensions` of the classic 
`SparkSession` (SparkSession.scala:1296-1311) and 
`ConnectionProviderBase.loadProviders` (ConnectionProvider.scala:41-57). All 
three catch `Throwable` and have no limit on failures, so they can loop forever 
in the case of item 9, where the iterator does not move on. A generic 
`skipUnloadable[T]` in `Utils` could give all four the `MAX_LOAD_FAILURES` 
limit. Two details for that change: `SparkSession` applies `ext(extensions)` 
inside its `try`, so it would need a callback, and the sites log at different 
levels. Since this is outside the scope of this PR, a separate JIRA seems 
better to me.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/ui/SQLTab.scala:
##########
@@ -34,11 +34,20 @@ class SQLTab(val sqlStore: SQLAppStatusStore, sparkUI: 
SparkUI)
   attachPage(new ExecutionPage(this))
   parent.attachTab(this)
 
-  parent.addStaticHandler(SQLTab.STATIC_RESOURCE_DIR, "/static/sql")
+  SQLTab.addStaticHandler(parent)
 
   override def displayOrder: Int = 0
 }
 
 object SQLTab {
   private val STATIC_RESOURCE_DIR = "org/apache/spark/sql/execution/ui/static"
+  private val STATIC_RESOURCE_PATH = "/static/sql"
+
+  /** The (classpath directory, URL path) pair under which the SQL static 
resources are served. */
+  private[sql] val STATIC_RESOURCE: (String, String) = STATIC_RESOURCE_DIR -> 
STATIC_RESOURCE_PATH

Review Comment:
   **[32] Nit: `object SQLTab` now exposes the same location twice.**
   
   The `STATIC_RESOURCE` pair is used only by SQLHistoryServerPlugin.scala:38, 
and `addStaticHandler` only by L37 and StreamingQueryTab.scala:36 (see item 
31). The helper also reads the two private `val`s rather than the pair, and the 
`WebUI` import is there only for its parameter type, while both callers pass a 
`SparkUI`. Could the two `val`s become `private[sql]`, and the pair and the 
helper go? Then L37 would be 
`parent.addStaticHandler(SQLTab.STATIC_RESOURCE_DIR, 
SQLTab.STATIC_RESOURCE_PATH)` and the plugin would declare 
`Seq(SQLTab.STATIC_RESOURCE_DIR -> SQLTab.STATIC_RESOURCE_PATH)`, close to 
master, with the path still defined in one place.



##########
core/src/main/scala/org/apache/spark/deploy/history/HistoryServer.scala:
##########
@@ -163,6 +165,43 @@ class HistoryServer(
     attachHandler(contextHandler)
   }
 
+  /**
+   * Registers the static resources declared by the given plugins, as 
(classpath resource
+   * directory, URL path) pairs.
+   *
+   * A failure never prevents the History Server from starting. It is logged 
as a warning and
+   * the rest is still registered:
+   *  - if reading a plugin's `staticResources` throws, that plugin is skipped;
+   *  - each declared entry is registered independently, so one failing entry 
(for example a
+   *    missing directory) does not skip the plugin's later entries.
+   *
+   * A path that is not under `/static/` is rejected as a failing entry, 
because it could
+   * otherwise shadow the History Server's own routes.
+   */
+  private[history] def setupPluginStaticResources(
+      plugins: Seq[AppHistoryServerPlugin]): Unit = {
+    plugins.foreach { plugin =>
+      try {
+        plugin.staticResources.foreach { case (dir, path) =>
+          try {
+            require(path.startsWith(HistoryServer.PLUGIN_STATIC_PATH_PREFIX),
+              s"path must be under ${HistoryServer.PLUGIN_STATIC_PATH_PREFIX}")
+            addStaticHandler(dir, path)

Review Comment:
   **[20] A failure while adding or starting a handler still exits the History 
Server.**
   
   In the History Server, `setupPluginStaticResources` runs in the constructor, 
before `bind()`. So the per-entry `try` covers only creating the handler and 
appending it to `handlers`. Adding it to Jetty and starting it happen later, in 
`WebUI.bind()` (WebUI.scala:160), where any exception leads to `System.exit(1)` 
(WebUI.scala:167-169). The doc at L172, "A failure never prevents the History 
Server from starting", does not hold for that part.
   
   For example, `/static/../../x` passes `startsWith` and 
`createStaticHandler`, but Jetty normalizes it to a `null` context path. Then 
`rootHandler.addHandler(compressionHandler)` in `bind()` throws a 
`NullPointerException` from `ContextHandlerCollection`, and the process exits. 
I checked this with Jetty 12.1.13. The tests call `setupPluginStaticResources` 
after `bind()`, so there the same exception is caught per entry, and this path 
is not covered. Before this PR, the `/static/sql` handlers were started only in 
`attachSparkUI`, where a failure affected one request.
   
   The check from item 19 on the normalized path would reject this example. 
Could the doc also say that the per-entry handling does not cover starting the 
handler in `bind()`?



##########
core/src/main/scala/org/apache/spark/deploy/history/HistoryServer.scala:
##########
@@ -174,14 +213,22 @@ class HistoryServer(
     provider.stop()
   }
 
-  /** Attach a reconstructed UI to this server. Only valid after bind(). */
+  /**
+   * Attach a reconstructed UI to this server. Only valid after bind().
+   *
+   * A handler whose context path the History Server already serves (e.g. 
/static/sql) is not
+   * attached: the server's own handler is attached first and always answers, 
so the
+   * application's copy could never receive a request. Skipping it avoids 
wrapping, starting and
+   * adding it to the root handler on every UI load.
+   */
   override def attachSparkUI(
       appId: String,
       attemptId: Option[String],
       ui: SparkUI,
       completed: Boolean): Unit = {
     assert(serverInfo.isDefined, "HistoryServer must be bound before attaching 
SparkUIs")
-    ui.getHandlers.foreach { handler =>
+    val servedPaths = getHandlers.map(_.getContextPath).toSet

Review Comment:
   **[33] Nit: `detachSparkUI` still detaches the handlers that this filter 
skips.**
   
   `attachSparkUI` now skips the application's handlers whose path the server 
already serves (`/static`, `/api`, and up to two `/static/sql`), but 
`detachSparkUI` (L237-241, unchanged) still calls `detachHandler` for each of 
them. Each call takes the `HistoryServer` lock, scans `handlers` for `handlers 
-= handler`, and has the synchronized `ServerInfo.removeHandler` scan the root 
handlers for a `CompressionHandler` that does not exist. It does nothing and 
costs little, but the two methods no longer mirror each other, which makes this 
harder to follow. Also, `servedPaths` does not change after `initialize()`, but 
is computed again on every attach. Could it be a `lazy val` used by both 
methods? Alternatively, the server could remember which handlers it attached 
for each UI and detach only those.



##########
core/src/main/scala/org/apache/spark/deploy/history/HistoryServer.scala:
##########
@@ -163,6 +165,43 @@ class HistoryServer(
     attachHandler(contextHandler)
   }
 
+  /**
+   * Registers the static resources declared by the given plugins, as 
(classpath resource
+   * directory, URL path) pairs.
+   *
+   * A failure never prevents the History Server from starting. It is logged 
as a warning and
+   * the rest is still registered:
+   *  - if reading a plugin's `staticResources` throws, that plugin is skipped;
+   *  - each declared entry is registered independently, so one failing entry 
(for example a
+   *    missing directory) does not skip the plugin's later entries.
+   *
+   * A path that is not under `/static/` is rejected as a failing entry, 
because it could
+   * otherwise shadow the History Server's own routes.
+   */
+  private[history] def setupPluginStaticResources(
+      plugins: Seq[AppHistoryServerPlugin]): Unit = {
+    plugins.foreach { plugin =>
+      try {
+        plugin.staticResources.foreach { case (dir, path) =>

Review Comment:
   **[24] Nit: the `case (dir, path)` match runs outside the per-entry `try`.**
   
   The pattern in `foreach { case (dir, path) => try { ... } }` is matched 
before the inner `try` is entered. So an entry that does not match, such as a 
`null` element, throws a `MatchError` into the outer catch at L197-200. The 
warning then says "Failed to get the static resources declared by ...", and the 
plugin's later entries are skipped, unlike what L175-176 say. For example, with 
`Seq(null, dir -> "/static/x")`, `/static/x` is not registered. The in-tree 
plugin returns a constant, so this is only about the contract. Could the 
`foreach` take each entry as it is and destructure it inside the `try`?



##########
core/src/main/scala/org/apache/spark/deploy/history/FsHistoryProvider.scala:
##########
@@ -1439,7 +1439,7 @@ private[history] class FsHistoryProvider(conf: SparkConf, 
clock: Clock)
     replayBus.addListener(listener)
 
     for {
-      plugin <- loadPlugins()
+      plugin <- AppHistoryServerPlugin.loadPluginsOrFail()

Review Comment:
   **[22] An `Error` from `loadPluginsOrFail()` skips the cleanup of the store 
that is being rebuilt.**
   
   This is not new: the old `loadPlugins()` threw from the same place. But the 
PR now makes it the intended fail-fast path, so I am raising it here. This line 
runs before the `try` at L1446, and what it throws is an `Error`, so both 
`trackingStore.close()` and the `case e: Exception` cleanup of the callers are 
skipped:
   
   - `createDiskStore` does not call `lease.rollback()` (L1686-1688). The 
application cache does not keep failed loads, so each request for an 
application without a committed store leaks one more lease: the usage that 
`HistoryServerDiskManager` tracks grows, and a `temp/appstore-*` directory is 
left behind each time. `makeRoom` then deletes good committed stores to make 
room, including the ones that L450 could still open.
   - `createHybridStore` calls neither `store.close()` nor 
`memoryManager.release(...)` (L1613-1616), so after a few such requests every 
application falls back from the hybrid store with "Not enough memory to create 
hybrid store".
   
   Could the plugin loading move into the `try`, and an `Error` from it be 
rethrown wrapped in an exception, for example with 
`SparkException.internalError(msg, e)`? Then the rebuild still fails fast, and 
the cleanup runs. A follow-up is fine too.



##########
core/src/test/scala/org/apache/spark/deploy/history/HistoryServerPluginSuite.scala:
##########
@@ -0,0 +1,193 @@
+/*
+ * 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.spark.deploy.history
+
+import java.net.URI
+import java.util.ServiceConfigurationError
+
+import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
+import org.apache.spark.internal.config.History.HISTORY_LOG_DIR
+import org.apache.spark.scheduler.SparkListener
+import org.apache.spark.status.{AppHistoryServerPlugin, ElementTrackingStore}
+import org.apache.spark.ui.SparkUI
+import org.apache.spark.util.Utils
+
+class HistoryServerPluginSuite extends SparkFunSuite {
+
+  private val staticDir = "org/apache/spark/ui/static"
+  private val staticFile = "spark-dag-viz.js"
+
+  /** A plugin that declares one static resource path, or throws when asked 
for it. */
+  private class StaticPlugin(path: String, fail: Boolean = false) extends 
AppHistoryServerPlugin {

Review Comment:
   **[27] Nit: the test plugin and the fake iterator could be smaller.**
   
   `StaticPlugin` is used in three ways: with the path of its constructor, with 
the `fail` flag, and as `new StaticPlugin("unused") { override ... }`, which 
ignores its argument (L148 and L162). A by-name parameter, 
`StaticPlugin(resources: => Seq[(String, String)])`, would cover all three, 
without the flag, the placeholder argument and the two anonymous subclasses.
   
   I agree that a real `ServiceLoader` is not worth it here, as you explained 
in the thread of item 13. Still, four of the five server tests (L114, L136, 
L146 and L160) pass only `Right` values, for which `loadedFrom` returns its 
input, so they could call `server.setupPluginStaticResources(Seq(p1, p2))` 
directly. `skipUnloadable` handles a failure from `hasNext` and from `next()` 
in the same catch, so the split between them in `PluginIterator` is not 
observable. For the test at L124, 
`AppHistoryServerPlugin.skipUnloadable(elements.view.map { case Left(e) => 
throw e; case Right(p) => p })` would be enough, which would replace L56-98.



##########
core/src/main/scala/org/apache/spark/status/AppHistoryServerPlugin.scala:
##########
@@ -36,8 +44,82 @@ private[spark] trait AppHistoryServerPlugin {
    */
   def setupUI(ui: SparkUI): Unit
 
+  /**
+   * Static resources (JS/CSS) to serve from the History Server's own UI, as 
(classpath resource
+   * directory, URL path) pairs. They are registered once at startup. The URL 
path must be under
+   * /static/; other paths are rejected so they cannot shadow the History 
Server's own routes.
+   * The directory is resolved with Spark's class loader, not the plugin's, so 
it must be on
+   * Spark's class path. Unlike a handler attached in [[setupUI]], which is 
torn down when the
+   * application cache evicts that application, these live as long as the 
History Server.
+   *
+   * This does not replace the registration in [[setupUI]] or in the tabs: the 
live driver UI
+   * never calls this hook, so tabs must still register their own handlers.
+   */
+  def staticResources: Seq[(String, String)] = Nil

Review Comment:
   **[29] Could the SQL files move into core's static directory instead?**
   
   This is a different direction, so please take it only as a question; the 
current approach works too. To serve one directory, the PR adds this hook, 
loads every plugin when the History Server is created (which in turn needs 
`skipUnloadable`, `MAX_LOAD_FAILURES` and the `LinkageError` catch), the 
`/static/` check, two levels of `try`, and the filter in `attachSparkUI`. The 
five files in sql/core's `org/apache/spark/sql/execution/ui/static/` are all 
Spark's own code, so moving them to core's `org/apache/spark/ui/static/sql/` 
would not change LICENSE. The core `/static` handler, which every History 
Server registers at startup (HistoryServer.scala:158), would then serve 
`/static/sql/...` as it is. That removes both the eviction and the load 
balancer 404s, and the per-application handlers in `SQLTab` and 
`StreamingQueryTab` could go as well. Core already holds 
`structured-streaming-page.js` for the sql module (SPARK-29543).
   
   The cost is that core would own SQL UI files, and the paths in `dev/lint-js` 
(L27) and `ui-test/tests/spark-sql-viz.test.js` (L32) would change. Today 
`SQLHistoryServerPlugin` is the only user of this hook.



##########
sql/core/src/test/scala/org/apache/spark/deploy/history/SQLHistoryServerStaticResourceSuite.scala:
##########
@@ -0,0 +1,99 @@
+/*
+ * 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.spark.deploy.history
+
+import java.net.{URI, URL}
+
+import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
+import org.apache.spark.internal.config.History.HISTORY_LOG_DIR
+import org.apache.spark.util.Utils
+
+/**
+ * Verifies that the SQL plugin's static resources are served by the History 
Server itself, so
+ * they are available before any application UI has been loaded, while one is 
attached, and
+ * after it is detached (as happens when it is evicted from the application 
cache).
+ *
+ * The application's own SQL tab declares a handler for the same /static/sql 
path.
+ * HistoryServer.attachSparkUI skips it, since the History Server already 
serves that path, and
+ * the application's other pages must keep working.
+ */
+class SQLHistoryServerStaticResourceSuite extends SparkFunSuite {
+
+  private val staticResource = "/static/sql/spark-sql-viz.js"
+
+  private def withHistoryServer(logDir: String)(

Review Comment:
   **[28] Nit: the two new suites could share the History Server setup and use 
the existing HTTP helpers.**
   
   `withHistoryServer` and `urlOf` here (L39-56) repeat `withHistoryServer` and 
`statusOf` in HistoryServerPluginSuite.scala (L100-112 and L50-54) with small 
differences. sql/core tests already use `object HistoryServerSuite` from the 
core test jar, as L59 and L90 do, so it could hold one 
`withHistoryServer(logDir)(fn)` and one `url(server, path)` for both suites. 
For the checks, `TestUtils.httpResponseCode(url)` returns only the status code, 
without reading the body as `getContentAndCode(url)._1` does, and 
`HistoryServerSuite.getUrl(url)` returns the body on 200 and throws with the 
code and the error otherwise, so it could replace `assertResourceServed` and 
the jobs page check (L58-62 and L89-92).



##########
core/src/test/scala/org/apache/spark/deploy/history/HistoryServerPluginSuite.scala:
##########
@@ -0,0 +1,193 @@
+/*
+ * 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.spark.deploy.history
+
+import java.net.URI
+import java.util.ServiceConfigurationError
+
+import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
+import org.apache.spark.internal.config.History.HISTORY_LOG_DIR
+import org.apache.spark.scheduler.SparkListener
+import org.apache.spark.status.{AppHistoryServerPlugin, ElementTrackingStore}
+import org.apache.spark.ui.SparkUI
+import org.apache.spark.util.Utils
+
+class HistoryServerPluginSuite extends SparkFunSuite {
+
+  private val staticDir = "org/apache/spark/ui/static"
+  private val staticFile = "spark-dag-viz.js"
+
+  /** A plugin that declares one static resource path, or throws when asked 
for it. */
+  private class StaticPlugin(path: String, fail: Boolean = false) extends 
AppHistoryServerPlugin {
+    override def createListeners(conf: SparkConf, store: 
ElementTrackingStore): Seq[SparkListener] =
+      Nil
+
+    override def setupUI(ui: SparkUI): Unit = {}
+
+    override def staticResources: Seq[(String, String)] = {
+      if (fail) {
+        throw new IllegalStateException("staticResources failed")
+      }
+      Seq(staticDir -> path)
+    }
+  }
+
+  private def statusOf(server: HistoryServer, path: String): Int = {
+    val host = Utils.localHostNameForURI()
+    val url = new 
URI(s"http://$host:${server.boundPort}$path/$staticFile";).toURL
+    HistoryServerSuite.getContentAndCode(url)._1
+  }
+
+  /**
+   * An iterable that yields the given elements in order, throwing the Left 
ones instead.
+   * LinkageErrors surface from hasNext and the rest from next(), like a 
ServiceLoader iterator.
+   */
+  private def pluginsWithErrors(
+      elements: Seq[Either[Throwable, AppHistoryServerPlugin]]): 
Iterable[AppHistoryServerPlugin] =
+    new Iterable[AppHistoryServerPlugin] {
+      override def iterator: Iterator[AppHistoryServerPlugin] = new 
PluginIterator(elements)
+    }
+
+  /** The plugins that load from the given elements, skipping the ones that 
fail. */
+  private def loadedFrom(
+      elements: Seq[Either[Throwable, AppHistoryServerPlugin]]): 
Seq[AppHistoryServerPlugin] =
+    AppHistoryServerPlugin.skipUnloadable(pluginsWithErrors(elements))
+
+  private class PluginIterator(elements: Seq[Either[Throwable, 
AppHistoryServerPlugin]])
+    extends Iterator[AppHistoryServerPlugin] {
+
+    private val underlying = elements.iterator
+    private var pending: Option[Either[Throwable, AppHistoryServerPlugin]] = 
None
+
+    override def hasNext: Boolean = {
+      if (pending.isEmpty && underlying.hasNext) {
+        pending = Some(underlying.next())
+      }
+      pending match {
+        case Some(Left(e: LinkageError)) =>
+          pending = None
+          throw e
+        case Some(_) => true
+        case None => false
+      }
+    }
+
+    override def next(): AppHistoryServerPlugin = {
+      val element = pending.get
+      pending = None
+      element match {
+        case Left(e) => throw e
+        case Right(p) => p
+      }
+    }
+  }
+
+  private def withHistoryServer(fn: HistoryServer => Unit): Unit = {
+    withTempDir { logDir =>
+      val conf = new SparkConf().set(HISTORY_LOG_DIR, logDir.getAbsolutePath)
+      val provider = new FsHistoryProvider(conf)
+      val server = new HistoryServer(conf, provider, new 
SecurityManager(conf), 0)
+      try {
+        server.bind()
+        fn(server)
+      } finally {
+        server.stop()
+      }
+    }
+  }
+
+  test("static resources declared by plugins are served") {
+    withHistoryServer { server =>
+      server.setupPluginStaticResources(loadedFrom(Seq(
+        Right(new StaticPlugin("/static/test-a")),
+        Right(new StaticPlugin("/static/test-b")))))
+      assert(statusOf(server, "/static/test-a") === 200)
+      assert(statusOf(server, "/static/test-b") === 200)
+    }
+  }
+
+  test("a plugin that fails to load is skipped and the others are still set 
up") {
+    withHistoryServer { server =>
+      server.setupPluginStaticResources(loadedFrom(Seq(
+        Right(new StaticPlugin("/static/test-before")),
+        Left(new ServiceConfigurationError("provider constructor failed")),
+        Left(new NoClassDefFoundError("missing class")),
+        Right(new StaticPlugin("/static/test-after")))))
+      assert(statusOf(server, "/static/test-before") === 200)
+      assert(statusOf(server, "/static/test-after") === 200)
+    }
+  }
+
+  test("a plugin whose staticResources throws does not affect the others") {
+    withHistoryServer { server =>
+      server.setupPluginStaticResources(loadedFrom(Seq(
+        Right(new StaticPlugin("/static/test-failing", fail = true)),
+        Right(new StaticPlugin("/static/test-healthy")))))
+      assert(statusOf(server, "/static/test-failing") === 404)
+      assert(statusOf(server, "/static/test-healthy") === 200)
+    }
+  }
+
+  test("a failing entry does not skip the later entries of the same plugin") {
+    withHistoryServer { server =>
+      val plugin = new StaticPlugin("unused") {
+        override def staticResources: Seq[(String, String)] = Seq(
+          staticDir -> "/static/test-first",
+          "org/apache/spark/ui/no-such-dir" -> "/static/test-missing",
+          staticDir -> "/static/test-third")
+      }
+      server.setupPluginStaticResources(loadedFrom(Seq(Right(plugin))))
+      assert(statusOf(server, "/static/test-first") === 200)
+      assert(statusOf(server, "/static/test-third") === 200)
+    }
+  }
+
+  test("paths outside /static/ are rejected and do not take over the server's 
routes") {
+    withHistoryServer { server =>
+      val plugin = new StaticPlugin("unused") {
+        override def staticResources: Seq[(String, String)] = Seq(
+          staticDir -> "/history",
+          staticDir -> "/api/v1/x",
+          staticDir -> "/static",
+          staticDir -> "/static/test-ok")
+      }
+      server.setupPluginStaticResources(loadedFrom(Seq(Right(plugin))))
+      assert(statusOf(server, "/static/test-ok") === 200)
+      assert(statusOf(server, "/history") !== 200)

Review Comment:
   **[25] The `/history` assert cannot fail.**
   
   The test adds the plugin's handlers after `bind()`, so a `/history` handler 
from the plugin comes after the server's `/history` loader, and Jetty gives the 
request to the loader. The loader reads `spark-dag-viz.js` in 
`/history/spark-dag-viz.js` as an application ID and returns 404. So this line 
still passes if HistoryServer.scala:187 lets `/history` through, for example 
with `require(!path.startsWith("/api/"))`. The takeover from item 12 needs the 
order of `initialize()`, where plugin handlers come before the loader, and the 
test cannot get that order. With Jetty 12.1.13, the loader answered 404 in the 
order of the test, and was shadowed in the order of `initialize()`. Only the 
`/api/v1/x` assert at L172 checks the guard, and the `/static` entry has no 
assert.
   
   Could the test check what was registered instead, for example 
`assert(server.getHandlers.count(_.getContextPath == "/history") === 1)`, and 
the same for `/static`?



##########
sql/core/src/main/scala/org/apache/spark/sql/streaming/ui/StreamingQueryTab.scala:
##########
@@ -32,11 +32,8 @@ private[sql] class StreamingQueryTab(
   attachPage(new StreamingQueryStatisticsPage(this))
   parent.attachTab(this)
 
-  parent.addStaticHandler(StreamingQueryTab.STATIC_RESOURCE_DIR, "/static/sql")
+  // Not needed by this tab's pages (they load no files from /static/sql).
+  SQLTab.addStaticHandler(parent)

Review Comment:
   **[31] Nit: this registration could go instead of being rewritten.**
   
   In item 16 I said that keeping it was fine for this PR. Now that the PR 
rewrites this line and adds a comment saying that it is not needed, removing it 
may be simpler. In the live UI, `SharedState.statusStore` is a strict `val` 
that creates `SQLTab` (SharedState.scala:122-127), before the lazy 
`streamingQueryStatusListener` creates this tab (SharedState.scala:135-139). So 
`SQLTab`'s handler is always attached first, and this one never receives a 
request; it is only built, given its filters and started. In the History 
Server, the new filter in `attachSparkUI` drops it. Removing L35-36 and the 
`SQLTab` import would leave `SQLTab.addStaticHandler` with one caller (see item 
32), and the description would no longer need to explain this registration.



-- 
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]

Reply via email to