dongjoon-hyun commented on code in PR #794:
URL:
https://github.com/apache/spark-kubernetes-operator/pull/794#discussion_r4012465885
##########
spark-submission-worker/src/main/java/org/apache/spark/k8s/operator/SparkClusterResourceSpec.java:
##########
@@ -467,35 +469,67 @@ private static Optional<PodDisruptionBudget>
buildPodDisruptionBudget(
* resource and does not carry the cluster label, yet the driver must reach
the executors' block
* manager to fetch task results larger than {@code
spark.task.maxDirectResultSize}.
*
+ * <p>If both {@link WorkerNetworkPolicySpec#getMetricsPort()} and {@link
+ * WorkerNetworkPolicySpec#getMetricsIngress()} are set, a separate rule
admits the listed peers
+ * on that port only. Both are required: the port alone would open the
endpoint to every source in
+ * the cluster, and the peers alone would grant them every port. The worker
web UI port is
+ * deliberately not usable as the metrics port: it is served by the same
embedded HTTP server as
+ * the UI itself, so admitting it would also expose the full UI, not just a
metrics endpoint. A
+ * dedicated metrics port (e.g. a JMX-to-Prometheus exporter agent) keeps
metrics scraping
+ * separate from the UI.
+ *
* @param clusterName The name of the SparkCluster.
* @param namespace The namespace of the SparkApplication.
+ * @param workerSpec The WorkerSpec, used to look up the optional metrics
port and its peers.
* @return A NetworkPolicy object.
+ * @throws IllegalArgumentException if a metrics ingress rule is requested
on the worker web UI
+ * port.
*/
- private NetworkPolicy buildWorkerNetworkPolicy(String clusterName, String
namespace) {
- return new NetworkPolicyBuilder()
- .withNewMetadata()
- .withName(clusterName + "-worker")
- .withNamespace(namespace)
- .addToLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endMetadata()
- .withNewSpec()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_ROLE_NAME, LABEL_SPARK_ROLE_WORKER_VALUE)
- .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endPodSelector()
- .addNewIngress()
- .addNewFrom()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endPodSelector()
- .endFrom()
- .addNewFrom()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_ROLE_NAME, LABEL_SPARK_ROLE_DRIVER_VALUE)
- .endPodSelector()
- .endFrom()
- .endIngress()
- .endSpec()
- .build();
+ private NetworkPolicy buildWorkerNetworkPolicy(
+ String clusterName, String namespace, WorkerSpec workerSpec) {
+ var builder =
Review Comment:
Nit: the `builder = builder.addNewIngress()...endIngress();` reassignment
below is a no-op. fabric8's `endIngress()` calls `setToIngress` on the
enclosing fluent and returns that same instance, so a plain statement works. An
early `return builder.endSpec().build();` when the block is absent would also
put the rule-add at one nesting level.
##########
spark-submission-worker/src/main/java/org/apache/spark/k8s/operator/SparkClusterResourceSpec.java:
##########
@@ -467,35 +469,67 @@ private static Optional<PodDisruptionBudget>
buildPodDisruptionBudget(
* resource and does not carry the cluster label, yet the driver must reach
the executors' block
* manager to fetch task results larger than {@code
spark.task.maxDirectResultSize}.
*
+ * <p>If both {@link WorkerNetworkPolicySpec#getMetricsPort()} and {@link
+ * WorkerNetworkPolicySpec#getMetricsIngress()} are set, a separate rule
admits the listed peers
+ * on that port only. Both are required: the port alone would open the
endpoint to every source in
+ * the cluster, and the peers alone would grant them every port. The worker
web UI port is
+ * deliberately not usable as the metrics port: it is served by the same
embedded HTTP server as
+ * the UI itself, so admitting it would also expose the full UI, not just a
metrics endpoint. A
+ * dedicated metrics port (e.g. a JMX-to-Prometheus exporter agent) keeps
metrics scraping
+ * separate from the UI.
+ *
* @param clusterName The name of the SparkCluster.
* @param namespace The namespace of the SparkApplication.
+ * @param workerSpec The WorkerSpec, used to look up the optional metrics
port and its peers.
* @return A NetworkPolicy object.
+ * @throws IllegalArgumentException if a metrics ingress rule is requested
on the worker web UI
+ * port.
*/
- private NetworkPolicy buildWorkerNetworkPolicy(String clusterName, String
namespace) {
- return new NetworkPolicyBuilder()
- .withNewMetadata()
- .withName(clusterName + "-worker")
- .withNamespace(namespace)
- .addToLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endMetadata()
- .withNewSpec()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_ROLE_NAME, LABEL_SPARK_ROLE_WORKER_VALUE)
- .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endPodSelector()
- .addNewIngress()
- .addNewFrom()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endPodSelector()
- .endFrom()
- .addNewFrom()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_ROLE_NAME, LABEL_SPARK_ROLE_DRIVER_VALUE)
- .endPodSelector()
- .endFrom()
- .endIngress()
- .endSpec()
- .build();
+ private NetworkPolicy buildWorkerNetworkPolicy(
+ String clusterName, String namespace, WorkerSpec workerSpec) {
+ var builder =
+ new NetworkPolicyBuilder()
+ .withNewMetadata()
+ .withName(clusterName + "-worker")
+ .withNamespace(namespace)
+ .addToLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
+ .endMetadata()
+ .withNewSpec()
+ .withNewPodSelector()
+ .addToMatchLabels(LABEL_SPARK_ROLE_NAME,
LABEL_SPARK_ROLE_WORKER_VALUE)
+ .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
+ .endPodSelector()
+ .addNewIngress()
+ .addNewFrom()
+ .withNewPodSelector()
+ .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
+ .endPodSelector()
+ .endFrom()
+ .addNewFrom()
+ .withNewPodSelector()
+ .addToMatchLabels(LABEL_SPARK_ROLE_NAME,
LABEL_SPARK_ROLE_DRIVER_VALUE)
+ .endPodSelector()
+ .endFrom()
+ .endIngress();
+ WorkerNetworkPolicySpec networkPolicy = workerSpec.getNetworkPolicy();
+ if (networkPolicy != null
+ && networkPolicy.getMetricsPort() != null
+ && networkPolicy.getMetricsIngress() != null
+ && !networkPolicy.getMetricsIngress().isEmpty()) {
+ if (networkPolicy.getMetricsPort() == 8081) {
Review Comment:
This compares against a literal, not against the worker UI port. Line 77
above forwards every `sparkConf` entry as `-D` into `SPARK_WORKER_OPTS`, and
Spark's `WorkerArguments` reads `spark.worker.ui.port` (and
`SPARK_WORKER_WEBUI_PORT`), so `spark.worker.ui.port: "9404"` + `metricsPort:
9404` passes here and opens the whole UI to the peers. I would drop the throw
and soften the docs/Javadoc instead. If a check is kept, derive it from `conf`
and share one constant with the `8081` at lines 190/350.
##########
spark-submission-worker/src/main/java/org/apache/spark/k8s/operator/SparkClusterResourceSpec.java:
##########
@@ -467,35 +469,67 @@ private static Optional<PodDisruptionBudget>
buildPodDisruptionBudget(
* resource and does not carry the cluster label, yet the driver must reach
the executors' block
* manager to fetch task results larger than {@code
spark.task.maxDirectResultSize}.
*
+ * <p>If both {@link WorkerNetworkPolicySpec#getMetricsPort()} and {@link
+ * WorkerNetworkPolicySpec#getMetricsIngress()} are set, a separate rule
admits the listed peers
+ * on that port only. Both are required: the port alone would open the
endpoint to every source in
+ * the cluster, and the peers alone would grant them every port. The worker
web UI port is
+ * deliberately not usable as the metrics port: it is served by the same
embedded HTTP server as
+ * the UI itself, so admitting it would also expose the full UI, not just a
metrics endpoint. A
+ * dedicated metrics port (e.g. a JMX-to-Prometheus exporter agent) keeps
metrics scraping
+ * separate from the UI.
+ *
* @param clusterName The name of the SparkCluster.
* @param namespace The namespace of the SparkApplication.
+ * @param workerSpec The WorkerSpec, used to look up the optional metrics
port and its peers.
* @return A NetworkPolicy object.
+ * @throws IllegalArgumentException if a metrics ingress rule is requested
on the worker web UI
+ * port.
*/
- private NetworkPolicy buildWorkerNetworkPolicy(String clusterName, String
namespace) {
- return new NetworkPolicyBuilder()
- .withNewMetadata()
- .withName(clusterName + "-worker")
- .withNamespace(namespace)
- .addToLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endMetadata()
- .withNewSpec()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_ROLE_NAME, LABEL_SPARK_ROLE_WORKER_VALUE)
- .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endPodSelector()
- .addNewIngress()
- .addNewFrom()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
- .endPodSelector()
- .endFrom()
- .addNewFrom()
- .withNewPodSelector()
- .addToMatchLabels(LABEL_SPARK_ROLE_NAME, LABEL_SPARK_ROLE_DRIVER_VALUE)
- .endPodSelector()
- .endFrom()
- .endIngress()
- .endSpec()
- .build();
+ private NetworkPolicy buildWorkerNetworkPolicy(
+ String clusterName, String namespace, WorkerSpec workerSpec) {
+ var builder =
+ new NetworkPolicyBuilder()
+ .withNewMetadata()
+ .withName(clusterName + "-worker")
+ .withNamespace(namespace)
+ .addToLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
+ .endMetadata()
+ .withNewSpec()
+ .withNewPodSelector()
+ .addToMatchLabels(LABEL_SPARK_ROLE_NAME,
LABEL_SPARK_ROLE_WORKER_VALUE)
+ .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
+ .endPodSelector()
+ .addNewIngress()
+ .addNewFrom()
+ .withNewPodSelector()
+ .addToMatchLabels(LABEL_SPARK_CLUSTER_NAME, clusterName)
+ .endPodSelector()
+ .endFrom()
+ .addNewFrom()
+ .withNewPodSelector()
+ .addToMatchLabels(LABEL_SPARK_ROLE_NAME,
LABEL_SPARK_ROLE_DRIVER_VALUE)
+ .endPodSelector()
+ .endFrom()
+ .endIngress();
+ WorkerNetworkPolicySpec networkPolicy = workerSpec.getNetworkPolicy();
+ if (networkPolicy != null
+ && networkPolicy.getMetricsPort() != null
+ && networkPolicy.getMetricsIngress() != null
+ && !networkPolicy.getMetricsIngress().isEmpty()) {
+ if (networkPolicy.getMetricsPort() == 8081) {
+ throw new IllegalArgumentException(
Review Comment:
Throwing from the resource-spec constructor surfaces as a generic
`SchedulingFailure` (stack trace in the status message) in `ClusterInitStep`,
and from the next reconcile on as `Failed` / `Cannot process cluster status`
via `ClusterUnknownStateStep`, which immediate-requeues forever and appends a
`Failed` entry to `stateTransitionHistory` each time. Spec validation belongs
in `ClusterValidateStep` (currently a no-op placeholder;
`AppValidateStep.validateGatewayRoutes` shows the pattern) or in the CRD
schema, so this constructor keeps no exception path.
##########
docs/operations.md:
##########
@@ -174,6 +174,123 @@ Note that this requires a CNI plugin that enforces
NetworkPolicy; on clusters wi
a plugin the policy is silently ignored. Egress traffic of the operator
(Kubernetes API
server, DNS) is not restricted by this policy.
+## Exposing SparkCluster Worker Metrics
+
+Every `SparkCluster` gets a generated worker `NetworkPolicy` that only admits
ingress from pods
+carrying the cluster label or the driver-role label, so a Prometheus scraper
is locked out by
+default. Opening the worker web UI port (`8081`) is not a safe fix: Spark's
built-in
+`PrometheusServlet` metrics endpoint is served by the same embedded HTTP
server as the web UI, so
+admitting that port to any source would expose the whole UI, not just metrics.
+
+The recommended approach is to attach the community
+[Prometheus JMX Exporter](https://github.com/prometheus/jmx_exporter)
+(`jmx_prometheus_javaagent`) to the worker JVM as a `-javaagent`. The agent
opens its own
+dedicated HTTP port that serves Prometheus-format metrics, completely
decoupled from the web UI
+port. Setting this up takes four steps:
+
+1. Bake the exporter jar into the Spark image used by the cluster:
+
+ ```dockerfile
+ FROM apache/spark:4.2.0
+ ADD
https://repo1.maven.org/maven2/io/prometheus/jmx/jmx_prometheus_javaagent/1.0.1/jmx_prometheus_javaagent-1.0.1.jar
\
+ /opt/jmx_exporter/jmx_prometheus_javaagent.jar
+ ```
+
+2. Create a `ConfigMap` holding the exporter's mapping/rules config (which
MBeans to expose and
+ how to name them), and mount it into the worker container via a `volumes` /
`volumeMounts`
+ override under `workerSpec.statefulSetSpec.template.spec`:
+
+ ```yaml
+ apiVersion: v1
+ kind: ConfigMap
+ metadata:
+ name: jmx-exporter-config
+ data:
+ jmx-exporter-config.yaml: |
+ lowercaseOutputName: true
+ rules:
+ - pattern: ".*"
Review Comment:
This catch-all config differs from the targeted rules in
`examples/cluster-with-jmx-exporter.yaml`, and it exports every MBean attribute
on each scrape. I would keep the full CR in the example only and show just the
`networkPolicy` fragment here.
##########
spark-operator-api/src/main/java/org/apache/spark/k8s/operator/spec/WorkerNetworkPolicySpec.java:
##########
@@ -0,0 +1,56 @@
+/*
+ * 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.k8s.operator.spec;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Network policy for the Spark workers.
+ *
+ * @since 0.1.0
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+@Builder
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class WorkerNetworkPolicySpec {
+ /**
+ * Port of a metrics endpoint (e.g. a JMX-to-Prometheus exporter agent)
running in the worker
+ * container, outside Spark's own web UI. The caller is responsible for
making the container
+ * actually listen on this port. Takes effect only together with {@link
#metricsIngress}.
+ */
+ protected Integer metricsPort;
Review Comment:
Setting only one of `metricsPort` / `metricsIngress` is silently ignored: no
rule, no status, no event. Since this block is optional as a whole, `@Required`
on both fields (already used on `RuntimeVersions.sparkVersion`; nested
`required:` lists exist under the optional `workerSpec.instanceConfig`) plus
`@Min(1) @Max(65535)` on `metricsPort` lets the API server reject a partial or
out-of-range block at apply time while leaving an omitted block valid. The
null-guard, the "both required" docs paragraph, and
`testWorkerNetworkPolicyWith*ButNo*` can then go.
##########
examples/cluster-with-jmx-exporter.yaml:
##########
@@ -0,0 +1,77 @@
+# 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.
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: jmx-exporter-config
+data:
+ jmx-exporter-config.yaml: |
+ rules:
+ - pattern: 'java.lang<type=Memory><HeapMemoryUsage>(\w+)'
+ name: jvm_memory_heap_$1
+ type: GAUGE
+ - pattern: 'java.lang<type=GarbageCollector, name=(\w+)><>CollectionCount'
+ name: jvm_gc_collection_count
+ labels:
+ gc: "$1"
+ type: COUNTER
+ - pattern: 'metrics<name=(\S+)><>Value'
Review Comment:
This rule matches nothing as configured. Spark's `MetricsConfig` registers
only the servlet sink by default, so the `metrics` JMX domain stays empty
unless `spark.metrics.conf.*.sink.jmx.class:
org.apache.spark.metrics.sink.JmxSink` is added to `sparkConf` (it is forwarded
to the worker as `-D`). Without it the exporter serves `jvm_*` only and no
`spark_worker_*` series.
##########
spark-operator-api/src/main/java/org/apache/spark/k8s/operator/spec/WorkerNetworkPolicySpec.java:
##########
@@ -0,0 +1,56 @@
+/*
+ * 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.k8s.operator.spec;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicyPeer;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * Network policy for the Spark workers.
+ *
+ * @since 0.1.0
Review Comment:
This class is new; `@since 1.1.0`.
##########
spark-submission-worker/src/test/java/org/apache/spark/k8s/operator/SparkClusterResourceSpecTest.java:
##########
@@ -337,6 +344,62 @@ void testWorkerNetworkPolicy() {
from.get(1).getPodSelector().getMatchLabels());
}
+ @Test
+ void testWorkerNetworkPolicyWithMetricsIngress() {
+ var scraper = new NetworkPolicyPeerBuilder()
+ .withNewNamespaceSelector()
+ .addToMatchLabels("kubernetes.io/metadata.name", "monitoring")
+ .endNamespaceSelector()
+ .build();
+ var networkPolicySpec = mock(WorkerNetworkPolicySpec.class);
Review Comment:
`WorkerNetworkPolicySpec` is a Lombok `@Builder` POJO;
`WorkerNetworkPolicySpec.builder().metricsPort(9404).metricsIngress(List.of(scraper)).build()`
removes the getter stubs in all four tests, the `Mockito defaults Integer to
0` comment, and the redundant `thenReturn(null)` added to `setUp` (that is
already Mockito's default). `KueueWorkloadFactoryTest` uses
`WorkerSpec.builder()` the same way.
--
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]