HyukjinKwon commented on code in PR #59232:
URL: https://github.com/apache/spark/pull/59232#discussion_r4231761207


##########
udf/worker/grpc/src/test/scala/org/apache/spark/udf/worker/grpc/testing/ForwardingWorkerMain.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.udf.worker.grpc.testing
+
+import java.io.IOException
+import java.net.{StandardProtocolFamily, UnixDomainSocketAddress}
+import java.nio.ByteBuffer
+import java.nio.channels.{ServerSocketChannel, SocketChannel}
+import java.nio.file.{Files, Paths}
+import java.util.concurrent.TimeUnit
+
+import scala.jdk.CollectionConverters._
+import scala.util.control.NonFatal
+
+/**
+ * Test-only launcher that stands in for a sandbox or container launcher. It
+ * receives the engine's `--id` and `--connection`, starts the real worker on a
+ * different socket, and forwards each engine connection to it. This is the
+ * shape a launcher has when the worker cannot bind the engine's socket itself:
+ *
+ *   java -cp <classpath> ...ForwardingWorkerMain <worker command...>
+ *     --id <id> --connection <uds-path>
+ *
+ * The inner worker exits when this launcher exits, including by `SIGKILL`.

Review Comment:
   **Nit (P3):** Nothing in `ForwardingWorkerMain` makes this true by itself. A 
SIGKILLed JVM runs no shutdown hook, and the worker is started with a plain 
`ProcessBuilder`, so after the launcher is killed the inner worker stops only 
because `EchoGrpcWorkerMain` watches its parent 
(`EchoGrpcWorkerMain.scala:133-135`). If this launcher wraps any other worker 
command, that worker is orphaned on SIGKILL. The next line also leaves out that 
the SIGTERM wait is capped at 2 seconds and then followed by 
`destroyForcibly()`.
   
   Since this file is meant to stand in for sandbox and container launchers, 
readers may copy it as the way to meet the new `ProcessCallable` clause. The 
earlier thread asked for the scaladoc to say how the SIGKILL clause is met. 
Something like:
   
   ```
    * On `SIGTERM`, the shutdown hook sends `SIGTERM` to the inner worker, 
waits up
    * to 2 seconds, and then kills it with `SIGKILL`. A `SIGKILL` of this 
launcher
    * runs no hook, so the inner worker must watch its parent and exit on its 
own;
    * `EchoGrpcWorkerMain` does this.
   ```
   
   **Verification:**
   - **Inspection:** Reading the scaladoc against the shutdown hook and 
EchoGrpcWorkerMain's parent watch, every lifecycle claim matches the code: the 
2 s bounded SIGTERM wait with SIGKILL fallback, and that the SIGKILL guarantee 
comes from the inner worker.



##########
udf/worker/grpc/src/test/scala/org/apache/spark/udf/worker/grpc/DirectGrpcDispatcherIntegrationSuite.scala:
##########
@@ -160,6 +162,65 @@ class DirectGrpcDispatcherIntegrationSuite
     assert(!socketDir.exists(), "dispatcher close should remove its socket 
directory")
   }
 
+  test("a launcher command that forwards the connection serves sessions") {
+    val launcher = ProcessCallable.newBuilder()
+      .addCommand(javaExecutable)
+      .addCommand("-cp")
+      .addCommand(javaClasspath)
+      .addCommand(classOf[ForwardingWorkerMain.type].getName.stripSuffix("$"))
+      .addAllCommand(echoRunner.getCommandList)
+      .build()
+    dispatcher = new DirectGrpcDispatcher(workerSpec(launcher))
+    val sessions = Seq.fill(2)(dispatcher.createSession(None))
+    val processes = sessions.map(workerProcess)
+    val workers = processes.flatMap(_.process.descendants().iterator().asScala)
+    val payloads = Seq(
+      ByteString.copyFrom(Array.fill[Byte](5 * 1024 * 1024)(3)),
+      ByteString.copyFromUtf8("small"))
+
+    try {
+      assert(workers.size == 2, s"each launcher should start one worker, got 
$workers")
+      sessions.zip(payloads).foreach { case (session, payload) =>
+        session.init(basicInit)
+        val input = DataRequest.newBuilder().setData(payload).build()
+        assert(session.process(Iterator.single(input), 
emptyFinish).map(_.getData).toList ==
+          List(payload))
+      }
+    } finally {
+      sessions.foreach(_.close(emptyCancel))
+    }
+
+    assert(processes.forall(!_.process.isAlive), "session close should 
terminate the launcher")
+    workers.foreach { worker =>
+      worker.onExit().get(10, TimeUnit.SECONDS)
+      assert(!worker.isAlive, s"session close should stop the launched worker 
${worker.pid}")
+    }
+  }
+
+  test("SIGKILL of the forwarding launcher stops the inner worker") {
+    val launcher = ProcessCallable.newBuilder()
+      .addCommand(javaExecutable)
+      .addCommand("-cp")
+      .addCommand(javaClasspath)
+      .addCommand(classOf[ForwardingWorkerMain.type].getName.stripSuffix("$"))
+      .addAllCommand(echoRunner.getCommandList)
+      .build()
+    dispatcher = new DirectGrpcDispatcher(workerSpec(launcher))
+    val session = dispatcher.createSession(None)
+    val process = workerProcess(session)
+    val workers = process.process.descendants().iterator().asScala.toList
+    assert(workers.size == 1, s"the launcher should start one worker, got 
$workers")
+    val worker = workers.head
+    try {
+      session.init(basicInit)
+      process.process.destroyForcibly()
+      worker.onExit().get(10, TimeUnit.SECONDS)

Review Comment:
   **Nit (P3):** Once the launcher is SIGKILLed, this inner worker is no longer 
a child of anything that waits for it. It is reparented to PID 1 (or a 
subreaper), and after it exits it stays a zombie until that process reaps it. 
JDK `ProcessHandle` counts a non-child zombie as alive. I checked on OpenJDK 
11.0.32: for a zombie that is not a child of the JVM, 
`ProcessHandle.of(pid).isAlive()` returned `true` and `onExit().get(2, 
SECONDS)` timed out. So on a host whose PID 1 does not reap orphans, this line 
fails with `TimeoutException` even though the parent watch worked and the 
worker exited. Examples are a container started without `--init` with the build 
JVM as PID 1, or a GitHub Actions job container. The session-close test hits 
the same thing at line 195 whenever the inner worker takes longer than the 
launcher's 2 s grace and gets SIGKILLed.
   
   A small suite helper for both waits would avoid this. It would wait a 
bounded time until the handle is no longer alive or is a zombie (on Linux, 
state `Z` in `/proc/<pid>/stat`), and destroy the handle before failing if it 
is still running. The destroy-before-failing part also covers the leaked-worker 
finding on this test.
   
   See **Shared repair plan 1** in the review body.



##########
udf/worker/grpc/src/test/scala/org/apache/spark/udf/worker/grpc/testing/ForwardingWorkerMain.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.udf.worker.grpc.testing
+
+import java.io.IOException
+import java.net.{StandardProtocolFamily, UnixDomainSocketAddress}
+import java.nio.ByteBuffer
+import java.nio.channels.{ServerSocketChannel, SocketChannel}
+import java.nio.file.{Files, Paths}
+import java.util.concurrent.TimeUnit
+
+import scala.jdk.CollectionConverters._
+import scala.util.control.NonFatal
+
+/**
+ * Test-only launcher that stands in for a sandbox or container launcher. It
+ * receives the engine's `--id` and `--connection`, starts the real worker on a
+ * different socket, and forwards each engine connection to it. This is the
+ * shape a launcher has when the worker cannot bind the engine's socket itself:
+ *
+ *   java -cp <classpath> ...ForwardingWorkerMain <worker command...>
+ *     --id <id> --connection <uds-path>
+ *
+ * `SIGTERM` stops the inner worker with `SIGTERM` and waits for it.
+ */
+object ForwardingWorkerMain {
+
+  def main(args: Array[String]): Unit = {
+    val connection = args.indexOf("--connection")
+    require(connection >= 0 && connection + 1 < args.length, "--connection is 
required")
+    val socketPath = args(connection + 1)
+    val innerPath = socketPath + ".inner"
+    val workerCommand =
+      args.take(connection) ++ args.drop(connection + 2) ++ 
Seq("--connection", innerPath)
+
+    Files.deleteIfExists(Paths.get(innerPath))
+    val worker = new 
ProcessBuilder(workerCommand.toSeq.asJava).inheritIO().start()
+    // This standalone test-worker main has no Spark on its classpath, so it
+    // cannot use Spark's ShutdownHookManager and registers directly.
+    // scalastyle:off runtimeaddshutdownhook
+    Runtime.getRuntime.addShutdownHook(new Thread(() => {

Review Comment:
   Thanks, I checked acb3771b. EchoGrpcWorkerMain now registers the parent 
onExit watch before it parks. ForwardingWorkerMain's 2 s SIGTERM wait now 
finishes before the suite's 10 s graceful timeout. The new test SIGKILLs the 
launcher with no SIGTERM and checks that the inner worker exits. That fixes the 
orphaned inner worker this thread was about.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4226908183","thread_id":"inline:4226908183","verdict_sha256":"115e561e8987ebf66c34b52efa7fa104d464522610163613e77351f7e1863a2b"}
 -->



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