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


##########
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/deploy/k8s/submit/KubernetesClientApplication.scala:
##########
@@ -135,6 +136,24 @@ private[spark] class Client(
       .build()
     val driverPodName = resolvedDriverPod.getMetadata.getName
 
+    // The API server rejects a pod that has both spec.nodeName and scheduling 
gates, and a pod
+    // with spec.nodeName skips the scheduler anyway, so only pods the 
scheduler places are gated.
+    // The check cannot see a nodeName that an admission webhook sets after 
this point.
+    val gateDriverPod = conf.get(USE_DRIVER_SCHEDULING_GATE) &&
+      Option(resolvedDriverPod.getSpec.getNodeName).forall(_.isEmpty)
+    val podToCreate =
+      if (gateDriverPod) {
+        // A gate of the same name would be rejected as a duplicate, and the 
patch clears it.
+        new PodBuilder(resolvedDriverPod)
+          .editSpec()
+            .removeMatchingFromSchedulingGates(_.getName == 
DRIVER_RESOURCES_SCHEDULING_GATE)
+            .addNewSchedulingGate(DRIVER_RESOURCES_SCHEDULING_GATE)
+            .endSpec()
+          .build()
+      } else {
+        resolvedDriverPod

Review Comment:
   **When the driver pod isn't gated, a gate named 
`spark.apache.org/driver-resources` that the resolved pod already has stays on 
it, and nothing removes it.** L149 removes such a gate only on the gated path. 
With the default `false`, or when the pod sets `spec.nodeName`, a template or a 
feature step that carries the gate, e.g. a template copied from a gated driver 
pod's spec, is created as is:
   
   - without `nodeName`, the driver stays `SchedulingGated` forever, and with 
`spark.kubernetes.submission.waitAppCompletion=true` (the default), 
`spark-submit` waits forever too;
   - with `nodeName`, the API server rejects the CREATE, since a pod can't have 
both, and the log asks for `kubectl auth can-i create pod`.
   
   The `schedulingGates` row in `running-on-kubernetes.md` (L2326-L2327) says 
"Spark removes only its own gate", which reads as if Spark always handles it. 
Could we remove a gate of that name in both branches, and add ours only when 
`gateDriverPod` is true?



##########
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/deploy/k8s/submit/KubernetesClientApplication.scala:
##########
@@ -177,10 +196,36 @@ private[spark] class Client(
       kubernetesClient.resourceList(otherKubernetesResources: 
_*).forceConflicts().serverSideApply()
     } catch {
       case NonFatal(e) =>
-        kubernetesClient.pods().resource(createdDriverPod).delete()
+        Utils.tryLogNonFatalError {
+          kubernetesClient.pods().resource(createdDriverPod).delete()
+        }
         throw e
     }
 
+    // The resources spark-submit creates for the driver exist now, so let the 
scheduler place the
+    // pod. The strategic merge patch names the gate, so it is idempotent and 
leaves other gates
+    // alone.
+    if (gateDriverPod) {
+      try {
+        kubernetesClient.pods().resource(createdDriverPod).patch(
+          PatchContext.of(PatchType.STRATEGIC_MERGE),
+          """{"spec":{"schedulingGates":[""" +
+            
s"""{"$$patch":"delete","name":"$DRIVER_RESOURCES_SCHEDULING_GATE"}]}}""")
+      } catch {
+        case NonFatal(e) =>
+          e match {
+            case ke: KubernetesClientException if ke.getCode == 403 =>
+              logError("Please check \"kubectl auth can-i patch pod\" first. 
It should be yes." +
+                s" Or set ${USE_DRIVER_SCHEDULING_GATE.key} to false.")

Review Comment:
   Minor: this new message interpolates the config key with `s"..."`, but the 
Structured Logging guideline in `Logging.scala` asks to wrap variables in `MDC` 
and use the `log"..."` interpolator, as this module does elsewhere (e.g. 
`KubernetesClientUtils.scala:197`, 
`DriverKubernetesCredentialsFeatureStep.scala:91`). The "Scala structured 
logging check" step didn't catch it, because `dev/structured_logging_style.py` 
matches no files at the moment, which is a separate issue. Could it be 
`log"""Please check "kubectl auth can-i patch pod" first. It should be yes.""" 
+ log" Or set ${MDC(CONFIG, USE_DRIVER_SCHEDULING_GATE.key)} to false."`, with 
`CONFIG` added to the `LogKeys` import at L36?



##########
resource-managers/kubernetes/core/src/test/scala/org/apache/spark/deploy/k8s/submit/ClientSuite.scala:
##########
@@ -223,22 +364,212 @@ class ClientSuite extends SparkFunSuite with 
BeforeAndAfter {
     val configMap = configMaps.head
     assert(configMap.getMetadata.getName ===
       KubernetesClientUtils.configMapNameDriver)
+    assert(configMap.getMetadata.getName === mountedConfigMapName)
     assert(configMap.getImmutable())
     assert(configMap.getData.containsKey(SPARK_CONF_FILE_NAME))
     
assert(configMap.getData.get(SPARK_CONF_FILE_NAME).contains("conf1key=conf1value"))
     
assert(configMap.getData.get(SPARK_CONF_FILE_NAME).contains("conf2key=conf2value"))
   }
 
+  test("SPARK-38079: the driver pod is created gated, and the gate is removed 
last") {
+    newClient().run()
+
+    assert(events.toSeq === submissionEvents())
+    assert(gateNames(createdPodArgumentCaptor.getValue) === 
Seq(DRIVER_RESOURCES_SCHEDULING_GATE))
+  }
+
+  test("SPARK-38079: pre resources are applied before the gated pod and owned 
after it") {
+    useSpec(BUILT_KUBERNETES_SPEC_WITH_PRERES)
+
+    newClient().run()
+
+    assert(events.toSeq ===
+      submissionEvents(preResource = Some("CustomResourceDefinition/preCRD")))
+  }
+
+  test("SPARK-38079: the gate is removed by name from the pod that create() 
returned") {
+    newClient().run()
+
+    verify(namedPods).patch(
+      ArgumentMatchers.any[PatchContext](), ArgumentMatchers.any[String]())
+    assert(patchContextCaptor.getValue.getPatchType === 
PatchType.STRATEGIC_MERGE)
+    assert(patchBodyCaptor.getValue ===
+      """{"spec":{"schedulingGates":[{"$patch":"delete",""" +
+        s""""name":"$DRIVER_RESOURCES_SCHEDULING_GATE"}]}}""")
+    assert(podTargets.map(_._1).toSeq === Seq("remove gate"))
+    assert(podTargets.map(_._2.getMetadata.getUid).toSet === 
Set(DRIVER_POD_UID))
+  }
+
+  test("SPARK-38079: gates already on the pod template are kept next to the 
Spark gate") {
+    useSpec(specWithPod(withGates(BUILT_DRIVER_POD, TEMPLATE_GATE)))
+
+    newClient().run()
+
+    assert(gateNames(createdPodArgumentCaptor.getValue) ===
+      Seq(TEMPLATE_GATE, DRIVER_RESOURCES_SCHEDULING_GATE))
+    // The patch is a strategic merge patch that names only Spark's gate.
+    assert(patchContextCaptor.getValue.getPatchType === 
PatchType.STRATEGIC_MERGE)
+    assert(!patchBodyCaptor.getValue.contains(TEMPLATE_GATE))
+  }
+
+  test("SPARK-38079: a Spark gate already on the pod is not added a second 
time") {
+    useSpec(specWithPod(
+      withGates(BUILT_DRIVER_POD, TEMPLATE_GATE, 
DRIVER_RESOURCES_SCHEDULING_GATE)))
+
+    newClient().run()
+
+    assert(gateNames(createdPodArgumentCaptor.getValue) ===
+      Seq(TEMPLATE_GATE, DRIVER_RESOURCES_SCHEDULING_GATE))
+    assert(events.last === "remove gate")
+  }
+
+  test("SPARK-38079: the gate is off by default, so the previous flow needs no 
patch") {
+    kconf = KubernetesTestConf.createDriverConf(
+      resourceNamePrefix = Some(KUBERNETES_RESOURCE_PREFIX))
+    assert(!kconf.get(USE_DRIVER_SCHEDULING_GATE))
+    useSpec(BUILT_KUBERNETES_SPEC)
+
+    newClient().run()
+
+    assert(createdPodArgumentCaptor.getValue === fullExpectedPod(gated = 
false))
+    assert(events.toSeq === submissionEvents(gateRemoved = false))
+  }
+
+  test("SPARK-38079: disabling the gate keeps the previous flow and the 
template's gates") {
+    kconf = driverConf(gate = false)
+    useSpec(specWithPod(withGates(BUILT_DRIVER_POD, TEMPLATE_GATE)))
+
+    newClient().run()
+
+    assert(createdPodArgumentCaptor.getValue ===
+      withGates(fullExpectedPod(gated = false), TEMPLATE_GATE))
+    assert(events.toSeq === submissionEvents(gateRemoved = false))
+  }
+
+  test("SPARK-38079: a pod pinned with spec.nodeName is neither gated nor 
patched") {
+    val pinnedPod = new PodBuilder(BUILT_DRIVER_POD)
+      .editSpec()
+        .withNodeName("some-node")
+        .endSpec()
+      .build()
+    useSpec(specWithPod(pinnedPod))
+
+    newClient().run()
+
+    val expected = new PodBuilder(fullExpectedPod(gated = false))
+      .editSpec().withNodeName("some-node").endSpec().build()
+    assert(createdPodArgumentCaptor.getValue === expected)
+    assert(events.toSeq === submissionEvents(gateRemoved = false))
+  }
+
+  test("SPARK-38079: a pinned pod keeps the gates of its template") {
+    val pinnedPod = withGates(new PodBuilder(BUILT_DRIVER_POD)
+      .editSpec().withNodeName("some-node").endSpec().build(), TEMPLATE_GATE)
+    useSpec(specWithPod(pinnedPod))
+
+    newClient().run()
+
+    assert(gateNames(createdPodArgumentCaptor.getValue) === Seq(TEMPLATE_GATE))
+    assert(events.toSeq === submissionEvents(gateRemoved = false))
+  }
+
+  test("SPARK-38079: a failure applying the pre resources deletes them and 
creates no pod") {
+    useSpec(BUILT_KUBERNETES_SPEC_WITH_PRERES)
+    val failure = new RuntimeException("apply failed")
+    failingWhen(failure)(_.exists(_.isInstanceOf[CustomResourceDefinition]))
+
+    val thrown = intercept[RuntimeException](newClient().run())
+
+    assert(thrown eq failure)
+    assert(events.toSeq === Seq(
+      "list(CustomResourceDefinition/preCRD)",
+      "list(CustomResourceDefinition/preCRD)", "delete resources"))
+    assert(podTargets.isEmpty)
+  }
+
+  test("SPARK-38079: a failure creating the pod deletes nothing but the pre 
resources") {
+    val failure = new RuntimeException("create failed")
+    failPodCall(failure)
+
+    val thrown = intercept[RuntimeException](newClient().run())
+
+    assert(thrown eq failure)
+    assert(events.toSeq === Seq("list()", "apply", "create pod", "list()", 
"delete resources"))
+    assert(podTargets.isEmpty)
+  }
+
+  test("SPARK-38079: a failure refreshing the pre resources' owners deletes 
the pod and them") {
+    useSpec(BUILT_KUBERNETES_SPEC_WITH_PRERES)
+    val failure = new RuntimeException("owner refresh failed")
+    failingWhen(failure) { resources =>
+      resources.exists(r => r.isInstanceOf[CustomResourceDefinition] &&
+        r.getMetadata.getOwnerReferences != null && 
!r.getMetadata.getOwnerReferences.isEmpty)
+    }
+
+    val thrown = intercept[RuntimeException](newClient().run())
+
+    assert(thrown eq failure)
+    val owned = "list(CustomResourceDefinition/preCRD+owner)"
+    assert(events.toSeq.drop(3) === Seq(owned, "delete pod", owned, "delete 
resources"))
+    assert(!events.contains("remove gate"))
+  }
+
+  test("SPARK-38079: a failure applying the post resources deletes only the 
pod") {
+    val failure = new RuntimeException("apply failed")
+    failingWhen(failure)(_.exists(_.isInstanceOf[Secret]))
+
+    val thrown = intercept[RuntimeException](newClient().run())
+
+    assert(thrown eq failure)
+    assert(events.last === "delete pod")
+    assert(!events.contains("remove gate"))
+    assert(!events.contains("delete resources"))
+    // The delete goes through the pod returned by create().
+    assert(podTargets.map(_._2.getMetadata.getUid).toSet === 
Set(DRIVER_POD_UID))
+  }
+
+  test("SPARK-38079: a failure deleting the pod does not hide the original 
failure") {
+    val failure = new RuntimeException("apply failed")
+    failingWhen(failure)(_.exists(_.isInstanceOf[Secret]))
+    failPodDelete(new RuntimeException("delete failed"))
+
+    val thrown = intercept[RuntimeException](newClient().run())
+
+    assert(thrown eq failure)
+    assert(events.last === "delete pod")
+  }
+
+  test("SPARK-38079: a failure removing the gate deletes the pod and 
propagates") {
+    val failure = new RuntimeException("patch failed")
+    failGatePatch(failure)
+
+    val thrown = intercept[RuntimeException](newClient().run())
+
+    assert(thrown eq failure)
+    assert(events.takeRight(2) === Seq("remove gate", "delete pod"))
+    assert(podTargets.map(_._1).toSeq === Seq("remove gate", "delete pod"))
+    assert(podTargets.map(_._2.getMetadata.getUid).toSet === 
Set(DRIVER_POD_UID))
+    verify(namedPods, never()).watch(loggingPodStatusWatcher)
+  }
+
+  test("SPARK-38079: a failure removing the gate is not hidden by a failure 
deleting the pod") {
+    val failure = new KubernetesClientException("forbidden", 403, null)

Review Comment:
   **No test checks the 403-only hint.** This test checks the rethrown 
exception and the events, and no test captures the log of a failed PATCH. So 
replacing `case ke: KubernetesClientException if ke.getCode == 403 =>` at 
KubernetesClientApplication.scala:217 with `case _ =>`, which would log the 
hint for every failure again, or removing the `logError`, keeps all 
`ClientSuite` tests green. Could we run `newClient().run()` here inside 
`withLogAppender`, as the SPARK-42813 test at L677 does, and check that the 
hint is logged, and check in the test at L542 that it isn't logged for a 
`RuntimeException`?



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