You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "tardunge (via GitHub)" <gi...@apache.org> on 2026/03/19 16:03:48 UTC
[PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
tardunge opened a new pull request, #63938:
URL: https://github.com/apache/airflow/pull/63938
Adds a `RayKubernetesOperator` that manages RayJob custom resources on Kubernetes via the KubeRay operator, enabling orchestration of Ray workloads (distributed ML training, batch inference, data processing) directly from Airflow DAGs.
**Motivation:** The CNCF Kubernetes provider supports Spark jobs via `SparkKubernetesOperator` but has no equivalent for Ray. The only Ray-related code in Airflow is in the Google Cloud provider (for GCP's managed Ray service), which doesn't help users running KubeRay on self-managed clusters. We've been running this operator in production for ~8 months.
**New components:**
- `RayKubernetesOperator` — creates and monitors RayJob CRDs
- YAML/JSON application file or `template_spec` dict input
- Reattach on scheduler restart (label-based job discovery)
- Dual timeout: cluster startup + job execution
- Log streaming from Ray head pod via `PodManager`
- Automatic cleanup on completion/failure (`delete_on_termination`)
- RFC 1123 compliant name sanitization with optional random suffix
- `RayObjectLauncher` — manages RayJob CRD lifecycle (create, status, delete)
- Tenacity retry for transient 409 conflicts
- `RayJobStatus` / `RayJobDeploymentStatus` constants
**No new dependencies** — uses `kubernetes` client (already required) and `tenacity` (already required by the provider).
---
##### Was generative AI tooling used to co-author this PR?
- [X] Yes — Claude Code (Opus 4.6)
Generated-by: Claude Code (Opus 4.6) following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147417190
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+
+if TYPE_CHECKING:
+ from airflow.providers.common.compat.sdk import Context
+
+RAY_API_GROUP = "ray.io"
+RAY_API_VERSION = "v1"
+RAY_PLURAL = "rayjobs"
+
+
+class RayKubernetesOperator(BaseOperator):
+ """
+ Create a RayJob object in a Kubernetes cluster via the KubeRay operator.
+
+ Submits a RayJob CRD and optionally waits for completion. Uses ``KubernetesHook``
+ for all CRD operations (create, get, delete).
+
+ .. seealso::
+ For more detail about RayJob have a look at the reference:
+ https://docs.ray.io/en/latest/cluster/kubernetes/getting-started/rayjob-quick-start.html
+
+ :param application_file: filepath to a RayJob YAML/JSON definition
+ :param template_spec: RayJob specification as a Python dict
+ :param namespace: kubernetes namespace for the RayJob
+ :param name: name of the RayJob (optional, extracted from spec if not provided)
+ :param wait_for_completion: whether to wait for the job to finish (default: True)
+ :param get_logs: stream logs from the Ray head pod
+ :param startup_timeout_seconds: timeout for Ray cluster startup
+ :param job_timeout_seconds: timeout for the Ray job to complete
+ :param poll_interval: seconds between status polls
+ :param reattach_on_restart: reattach to existing RayJob on scheduler restart
+ :param delete_on_termination: delete the RayJob CRD when done
+ :param kubernetes_conn_id: Kubernetes connection ID
+ :param random_name_suffix: add a random suffix to the job name
+ """
+
+ template_fields = [
+ "application_file",
+ "template_spec",
+ "namespace",
+ "kubernetes_conn_id",
+ ]
+ template_fields_renderers = {"application_file": "yaml", "template_spec": "py"}
+ template_ext = ("yaml", "yml", "json")
+ ui_color = "#028edd"
+
+ BASE_CONTAINER_NAME = "ray-head"
+
+ def __init__(
+ self,
+ *,
+ application_file: str | None = None,
+ template_spec: dict | None = None,
+ namespace: str = "default",
+ name: str | None = None,
+ wait_for_completion: bool = True,
+ get_logs: bool = True,
+ startup_timeout_seconds: int = 600,
+ job_timeout_seconds: int = 7200,
+ poll_interval: int = 10,
+ reattach_on_restart: bool = True,
+ delete_on_termination: bool = True,
+ kubernetes_conn_id: str = "kubernetes_default",
+ in_cluster: bool | None = None,
+ config_file: str | None = None,
+ cluster_context: str | None = None,
+ random_name_suffix: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self.application_file = application_file
+ self.template_spec = template_spec
+ self.namespace = namespace
+ self.kubernetes_conn_id = kubernetes_conn_id
+ self.in_cluster = in_cluster
+ self.config_file = config_file
+ self.cluster_context = cluster_context
+ self.wait_for_completion = wait_for_completion
+ self.startup_timeout_seconds = startup_timeout_seconds
+ self.job_timeout_seconds = job_timeout_seconds
+ self.poll_interval = poll_interval
+ self.reattach_on_restart = reattach_on_restart
+ self.delete_on_termination = delete_on_termination
+ self.get_logs = get_logs
+ self.random_name_suffix = random_name_suffix
+ self.ray_job_name: str | None = None
+
+ @cached_property
+ def hook(self) -> KubernetesHook:
+ """Get KubernetesHook instance."""
+ return KubernetesHook(
+ conn_id=self.kubernetes_conn_id,
+ in_cluster=self.in_cluster,
+ config_file=self.config_file,
+ cluster_context=self.cluster_context,
+ )
+
+ @cached_property
+ def pod_manager(self) -> PodManager:
+ """Get PodManager for log streaming."""
+ return PodManager(kube_client=self.hook.core_v1_client)
+
+ # --- Template & name handling ---
+
+ def _parse_template(self) -> dict:
+ """Parse and validate the RayJob specification."""
+ if self.application_file:
+ try:
+ filepath = Path(self.application_file.rstrip()).resolve(strict=True)
+ except (FileNotFoundError, OSError, RuntimeError, ValueError):
+ application_file_body = self.application_file
+ else:
+ application_file_body = filepath.read_text()
+
+ template_body = _load_body_to_dict(application_file_body)
+ if not isinstance(template_body, dict):
+ raise TypeError(
+ f"application_file body can't be transformed into dictionary:\n{application_file_body}"
+ )
+ elif self.template_spec:
+ template_body = copy.deepcopy(self.template_spec)
+ else:
+ raise AirflowException("Either application_file or template_spec must be provided")
+
+ template_body.setdefault("apiVersion", "ray.io/v1")
+ template_body.setdefault("kind", "RayJob")
+ template_body.setdefault("metadata", {})
+ template_body["metadata"].setdefault("name", self.task_id)
+ template_body["metadata"].setdefault("namespace", self.namespace)
+ return template_body
+
+ def _create_job_name(self) -> str:
+ """Generate a unique, RFC 1123 compliant job name."""
+ name = self.name or self.task_id
+ sanitized = pod_generator.make_safe_label_value(str(name).replace("_", "-"))
+ if self.random_name_suffix:
+ return add_unique_suffix(name=sanitized, max_len=MAX_LABEL_LEN)
+ return sanitized[:MAX_LABEL_LEN]
+
+ @staticmethod
+ def _get_ti_pod_labels(context: Context | None = None) -> dict[str, str]:
+ """Generate labels for reattachment after scheduler restart."""
+ if not context:
+ return {}
+
+ context_dict = cast("dict", context)
+ ti = context_dict["ti"]
+
+ labels = {
+ "dag_id": ti.dag_id,
+ "task_id": ti.task_id,
+ "run_id": context_dict["run_id"],
+ "ray_kubernetes_operator": "True",
+ "try_number": str(ti.try_number),
+ }
+
+ map_index = getattr(ti, "map_index", -1)
+ if map_index is not None and map_index >= 0:
+ labels["map_index"] = str(map_index)
+
+ return {
+ pod_generator.make_safe_label_value(k.replace("_", "-")): pod_generator.make_safe_label_value(
+ str(v)
+ )
+ for k, v in labels.items()
+ }
+
+ def _build_ray_job_body(self, context: Context) -> dict:
+ """Build the RayJob CRD body with labels for reattachment."""
+ body = copy.deepcopy(self._parse_template())
+ body["metadata"]["name"] = self.ray_job_name
+ body["metadata"].setdefault("labels", {})
+ body["metadata"]["labels"].update(self._get_ti_pod_labels(context))
+ return body
+
+ # --- CRD operations (all via KubernetesHook) ---
+
+ def _submit_ray_job(self, context: Context) -> None:
+ """Create the RayJob CRD via KubernetesHook."""
+ body = self._build_ray_job_body(context)
+ self.log.info("Creating RayJob: %s", self.ray_job_name)
+ self.hook.create_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ body=body,
+ namespace=self.namespace,
+ )
+
+ def _get_ray_job_status(self) -> tuple[str, str]:
+ """Get current job and deployment status from the RayJob CRD."""
+ obj = self.hook.get_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ status = obj.get("status", {})
+ return status.get("jobStatus", ""), status.get("jobDeploymentStatus", "")
+
+ def _delete_ray_job(self) -> None:
+ """Delete the RayJob CRD via KubernetesHook."""
+ if not self.ray_job_name:
+ return
+ try:
+ self.hook.delete_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ self.log.info("Deleted RayJob: %s", self.ray_job_name)
+ except Exception:
+ self.log.warning("Failed to delete RayJob %s (may already be deleted)", self.ray_job_name)
+
+ # --- Reattach ---
+
+ def _find_existing_ray_job(self, context: Context) -> str | None:
+ """Find an existing non-terminal RayJob for reattachment."""
+ try:
+ labels = self._get_ti_pod_labels(context)
+ if not labels:
+ return None
+
+ label_selector = ",".join(f"{k}={v}" for k, v in labels.items())
+ ray_jobs = self.hook.list_custom_objects(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ namespace=self.namespace,
+ label_selector=label_selector,
+ )
+
+ for item in ray_jobs.get("items", []):
+ job_name = item["metadata"]["name"]
+ job_status = item.get("status", {}).get("jobStatus", "")
+ dep_status = item.get("status", {}).get("jobDeploymentStatus", "")
+
+ if is_ray_job_terminal(job_status, dep_status):
+ continue
+
+ self.log.info("Reattaching to existing RayJob: %s", job_name)
+ return job_name
+ except Exception as e:
+ self.log.warning("Error searching for existing RayJob: %s", e)
+ return None
+
+ # --- Monitoring ---
+
+ def _wait_for_terminal_state(self) -> str:
+ """Poll the RayJob status until terminal or timeout."""
+ start_time = time.monotonic()
+ cluster_ready = False
+ last_log_time = None
+ head_pod_cache: dict[str, Any] = {}
+
+ while True:
+ elapsed = time.monotonic() - start_time
+
+ try:
+ job_status, dep_status = self._get_ray_job_status()
+ except Exception:
+ self.log.exception("Failed to get RayJob status for %s", self.ray_job_name)
+ raise
+
+ self.log.info(
+ "RayJob %s — job: %s, deployment: %s (%.0fs elapsed)",
+ self.ray_job_name,
+ job_status or "NEW",
+ dep_status or "NEW",
+ elapsed,
+ )
+
+ if is_ray_job_terminal(job_status, dep_status):
+ if is_ray_job_successful(job_status, dep_status):
+ return "SUCCEEDED"
+ raise AirflowException(f"RayJob failed — job: {job_status}, deployment: {dep_status}")
+
+ # Stream logs when running
+ if (
+ dep_status in (RayJobDeploymentStatus.RUNNING, RayJobDeploymentStatus.COMPLETE)
+ and self.get_logs
+ ):
Review Comment:
Fixed in 0407a93f — dropped COMPLETE from the live-streaming gate. Final log fetch on terminal state is handled in the terminal branch above.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147413952
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/utils/ray_job_status.py:
##########
@@ -0,0 +1,60 @@
+#
+# 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.
+"""Status constants and helpers for KubeRay RayJob CRDs."""
+
+from __future__ import annotations
+
+
+class RayJobStatus:
+ """Ray Job status constants from the KubeRay RayJob CRD."""
+
+ PENDING = "PENDING"
+ RUNNING = "RUNNING"
+ STOPPED = "STOPPED"
+ SUCCEEDED = "SUCCEEDED"
+ FAILED = "FAILED"
+
+
+class RayJobDeploymentStatus:
+ """Ray Job deployment status constants from the KubeRay RayJob CRD."""
+
+ INITIALIZING = "Initializing"
+ RUNNING = "Running"
+ COMPLETE = "Complete"
+ FAILED = "Failed"
+ VALIDATION_FAILED = "ValidationFailed"
+ SUSPENDING = "Suspending"
+ SUSPENDED = "Suspended"
+
+
+TERMINAL_JOB_STATUSES = frozenset({RayJobStatus.SUCCEEDED, RayJobStatus.FAILED, RayJobStatus.STOPPED})
+TERMINAL_DEPLOYMENT_STATUSES = frozenset(
+ {RayJobDeploymentStatus.COMPLETE, RayJobDeploymentStatus.FAILED, RayJobDeploymentStatus.VALIDATION_FAILED}
+)
+
+
+def is_ray_job_terminal(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob is in a terminal state."""
+ return job_status in TERMINAL_JOB_STATUSES or deployment_status in TERMINAL_DEPLOYMENT_STATUSES
+
+
+def is_ray_job_successful(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob completed successfully."""
+ return job_status == RayJobStatus.SUCCEEDED or (
+ deployment_status == RayJobDeploymentStatus.COMPLETE and job_status == RayJobStatus.SUCCEEDED
+ )
Review Comment:
Fixed in 0407a93f — collapsed to SUCCEEDED AND COMPLETE to mirror KubeRay's own success check (rayjob_controller.go:537)
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/utils/ray_job_status.py:
##########
@@ -0,0 +1,60 @@
+#
+# 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.
+"""Status constants and helpers for KubeRay RayJob CRDs."""
+
+from __future__ import annotations
+
+
+class RayJobStatus:
+ """Ray Job status constants from the KubeRay RayJob CRD."""
+
+ PENDING = "PENDING"
+ RUNNING = "RUNNING"
+ STOPPED = "STOPPED"
+ SUCCEEDED = "SUCCEEDED"
+ FAILED = "FAILED"
+
+
+class RayJobDeploymentStatus:
+ """Ray Job deployment status constants from the KubeRay RayJob CRD."""
+
+ INITIALIZING = "Initializing"
+ RUNNING = "Running"
+ COMPLETE = "Complete"
+ FAILED = "Failed"
+ VALIDATION_FAILED = "ValidationFailed"
+ SUSPENDING = "Suspending"
+ SUSPENDED = "Suspended"
+
+
+TERMINAL_JOB_STATUSES = frozenset({RayJobStatus.SUCCEEDED, RayJobStatus.FAILED, RayJobStatus.STOPPED})
+TERMINAL_DEPLOYMENT_STATUSES = frozenset(
+ {RayJobDeploymentStatus.COMPLETE, RayJobDeploymentStatus.FAILED, RayJobDeploymentStatus.VALIDATION_FAILED}
+)
+
+
+def is_ray_job_terminal(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob is in a terminal state."""
+ return job_status in TERMINAL_JOB_STATUSES or deployment_status in TERMINAL_DEPLOYMENT_STATUSES
+
+
+def is_ray_job_successful(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob completed successfully."""
+ return job_status == RayJobStatus.SUCCEEDED or (
+ deployment_status == RayJobDeploymentStatus.COMPLETE and job_status == RayJobStatus.SUCCEEDED
+ )
Review Comment:
Fixed in 0407a93f — dropped COMPLETE from the live-streaming gate. Final log fetch on terminal state is handled in the terminal branch above
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "raphaelauv (via GitHub)" <gi...@apache.org>.
raphaelauv commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r2963497931
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray_kubernetes.py:
##########
@@ -0,0 +1,507 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.operators.ray_object_launcher import RayObjectLauncher
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+from airflow.utils.helpers import prune_dict
+
+if TYPE_CHECKING:
+ import jinja2
+ from kubernetes.client import CoreV1Api, CustomObjectsApi
+
+ from airflow.providers.common.compat.sdk import Context
+
+
+class RayKubernetesOperator(BaseOperator):
Review Comment:
there is already the `KubernetesCreateResourceOperator`
```python
job_conf = """
apiVersion: ray.io/v1
kind: RayJob
metadata:
name: super-job
spec:
entrypoint: python -m src.run.train
shutdownAfterJobFinishes: true
ttlSecondsAfterFinished: 1000
rayClusterSpec:
rayVersion: '2.49.1'
# ....
KubernetesCreateResourceOperator(
task_id="create_ray_job",
yaml_conf=job_conf,
custom_resource_definition=True,
kubernetes_conn_id="my_k8s",
)
```
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray_kubernetes.py:
##########
@@ -0,0 +1,507 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.operators.ray_object_launcher import RayObjectLauncher
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+from airflow.utils.helpers import prune_dict
+
+if TYPE_CHECKING:
+ import jinja2
+ from kubernetes.client import CoreV1Api, CustomObjectsApi
+
+ from airflow.providers.common.compat.sdk import Context
+
+
+class RayKubernetesOperator(BaseOperator):
Review Comment:
there is already the `KubernetesCreateResourceOperator`
```python
job_conf = """
apiVersion: ray.io/v1
kind: RayJob
metadata:
name: super-job
spec:
entrypoint: python -m src.run.train
shutdownAfterJobFinishes: true
ttlSecondsAfterFinished: 1000
rayClusterSpec:
rayVersion: '2.49.1'
# ....
"""
KubernetesCreateResourceOperator(
task_id="create_ray_job",
yaml_conf=job_conf,
custom_resource_definition=True,
kubernetes_conn_id="my_k8s",
)
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "eladkal (via GitHub)" <gi...@apache.org>.
eladkal commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r2965754743
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray_kubernetes.py:
##########
Review Comment:
File should be `ray.py` rather than `ray_kubernetes.py`
same for the test files...
I know we have `spark_kubernetes.py` but that is not according to convention :(
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4300878233
@tardunge This PR has been converted to **draft** because it does not yet meet our [Pull Request quality criteria](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-quality-criteria).
**Issues found:**
- :x: **Failing CI**: `CI image checks / Static checks`, `provider distributions tests / Compat 2.11.1:P3.10:`, `provider distributions tests / Compat 3.0.6:P3.10:`, `provider distributions tests / Compat 3.1.8:P3.10:`. Please investigate and fix.
- :x: **Unresolved review comments** (8 threads): please walk through each unresolved review thread. **Even if a suggestion looks incorrect or irrelevant** — and some of them will be, especially any comments left by automated reviewers like GitHub Copilot — it is still the author's responsibility to respond: apply the fix, reply in-thread with a brief explanation of why the suggestion does not apply, or resolve the thread if the feedback is no longer relevant. **Once you believe a thread is resolved — whether by pushing a fix or by explaining why the suggestion doesn't apply — please mark it as resolved yourself by clicking the 'Resolve conversation' button at the bottom of each thread.** Reviewers don't auto-close their own threads, so an addressed-but-unresolved thread reads as 'still waiting on the author' and keeps the PR from moving forward.
**What to do next:**
- Address the items above.
- Make sure static checks pass locally: `prek run --from-ref main --stage pre-commit`.
- Mark the PR as "Ready for review" when you are done.
Converting a PR to draft is **not** a rejection — it is an invitation to bring the PR up to the project's standards so that maintainer review time is spent productively. There is no rush — take your time and work at your own pace. We appreciate your contribution and are happy to wait for updates. If you have questions, feel free to ask on the [Airflow Slack](https://s.apache.org/airflow-slack).
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147426326
##########
providers/cncf/kubernetes/tests/system/cncf/kubernetes/example_ray.py:
##########
@@ -0,0 +1,125 @@
+#
+# 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.
+"""
+Example DAG using RayKubernetesOperator to submit a RayJob on Kubernetes.
+
+KubeRay operator is required to be installed on the Kubernetes cluster.
+https://docs.ray.io/en/latest/cluster/kubernetes/getting-started.html
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from airflow import DAG
+
+# [START import_module]
+from airflow.providers.cncf.kubernetes.operators.ray import RayKubernetesOperator
+
+# [END import_module]
+
+with DAG(
+ dag_id="example_ray_kubernetes",
+ schedule=None,
+ start_date=datetime(2024, 1, 1),
+ catchup=False,
+ tags=["example", "ray", "kubernetes"],
+) as dag:
+ # [START howto_operator_ray_kubernetes_template_spec]
Review Comment:
Fixed in 0407a93f — added ENV_ID, DAG_ID, watcher() chain, and get_test_run per the system-test convention.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4096408818
@tardunge This PR has been converted to **draft** because it does not yet meet our [Pull Request quality criteria](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-quality-criteria).
**Issues found:**
- :x: **Pre-commit / static checks**: Failing: CI image checks / Static checks. Run `prek run --from-ref main` locally to find and fix issues. See [Pre-commit / static checks docs](https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst).
- :x: **mypy (type checking)**: Failing: CI image checks / MyPy checks (mypy-providers). Run `prek --stage manual mypy-providers --all-files` locally to reproduce. You need `breeze ci-image build --python 3.10` for Docker-based mypy. See [mypy (type checking) docs](https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#mypy-checks).
- :x: **Other failing CI checks**: Failing: Non-DB tests: core / Non-DB-core::3.10:API...Serialization, Special tests / Latest Boto test: core / All-core:LatestBoto-Postgres:14:3.10:API...Serialization, Special tests / Pendulum2 test: core / All-core:Pendulum2-Postgres:14:3.10:API...Serialization, Low dep tests:core / All-core:LowestDeps:14:3.10:API...Serialization. Run `prek run --from-ref main` locally to reproduce. See [static checks docs](https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst).
**What to do next:**
- The comment informs you what you need to do.
- Fix each issue, then mark the PR as "Ready for review" in the GitHub UI - but only after making sure that all the issues are fixed.
- There is no rush — take your time and work at your own pace. We appreciate your contribution and are happy to wait for updates.
- Maintainers will then proceed with a normal review.
Converting a PR to draft is **not** a rejection — it is an invitation to bring the PR up to the project's standards so that maintainer review time is spent productively. There is no rush — take your time and work at your own pace. We appreciate your contribution and are happy to wait for updates. If you have questions, feel free to ask on the [Airflow Slack](https://s.apache.org/airflow-slack).
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4477012323
@tardunge This draft PR has been inactive for 7 days since the last triage comment and no response from the author. Closing to keep the queue clean.
You are welcome to reopen this PR when you resume work, or to open a new one addressing the issues previously raised. There is no rush — take your time.
---
_Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this [two-stage triage process](https://github.com/apache/airflow/blob/main/contributing-docs/25_maintainer_pr_triage.md#why-the-first-pass-is-automated) so that our maintainers' limited time is spent where it matters most: the conversation with you._
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "jscheffl (via GitHub)" <gi...@apache.org>.
jscheffl commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4100221631
Also thanks for contributing this to us. I think we should rather consider - as Ray is a more complex ecosystem - to rather make a separate Ray provider.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147421351
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+
+if TYPE_CHECKING:
+ from airflow.providers.common.compat.sdk import Context
+
+RAY_API_GROUP = "ray.io"
+RAY_API_VERSION = "v1"
+RAY_PLURAL = "rayjobs"
+
+
+class RayKubernetesOperator(BaseOperator):
+ """
+ Create a RayJob object in a Kubernetes cluster via the KubeRay operator.
+
+ Submits a RayJob CRD and optionally waits for completion. Uses ``KubernetesHook``
+ for all CRD operations (create, get, delete).
+
+ .. seealso::
+ For more detail about RayJob have a look at the reference:
+ https://docs.ray.io/en/latest/cluster/kubernetes/getting-started/rayjob-quick-start.html
+
+ :param application_file: filepath to a RayJob YAML/JSON definition
+ :param template_spec: RayJob specification as a Python dict
+ :param namespace: kubernetes namespace for the RayJob
+ :param name: name of the RayJob (optional, extracted from spec if not provided)
+ :param wait_for_completion: whether to wait for the job to finish (default: True)
+ :param get_logs: stream logs from the Ray head pod
+ :param startup_timeout_seconds: timeout for Ray cluster startup
+ :param job_timeout_seconds: timeout for the Ray job to complete
+ :param poll_interval: seconds between status polls
+ :param reattach_on_restart: reattach to existing RayJob on scheduler restart
+ :param delete_on_termination: delete the RayJob CRD when done
+ :param kubernetes_conn_id: Kubernetes connection ID
+ :param random_name_suffix: add a random suffix to the job name
+ """
+
+ template_fields = [
+ "application_file",
+ "template_spec",
+ "namespace",
+ "kubernetes_conn_id",
+ ]
+ template_fields_renderers = {"application_file": "yaml", "template_spec": "py"}
+ template_ext = ("yaml", "yml", "json")
+ ui_color = "#028edd"
+
+ BASE_CONTAINER_NAME = "ray-head"
+
+ def __init__(
+ self,
+ *,
+ application_file: str | None = None,
+ template_spec: dict | None = None,
+ namespace: str = "default",
+ name: str | None = None,
+ wait_for_completion: bool = True,
+ get_logs: bool = True,
+ startup_timeout_seconds: int = 600,
+ job_timeout_seconds: int = 7200,
+ poll_interval: int = 10,
+ reattach_on_restart: bool = True,
+ delete_on_termination: bool = True,
+ kubernetes_conn_id: str = "kubernetes_default",
+ in_cluster: bool | None = None,
+ config_file: str | None = None,
+ cluster_context: str | None = None,
+ random_name_suffix: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self.application_file = application_file
+ self.template_spec = template_spec
+ self.namespace = namespace
+ self.kubernetes_conn_id = kubernetes_conn_id
+ self.in_cluster = in_cluster
+ self.config_file = config_file
+ self.cluster_context = cluster_context
+ self.wait_for_completion = wait_for_completion
+ self.startup_timeout_seconds = startup_timeout_seconds
+ self.job_timeout_seconds = job_timeout_seconds
+ self.poll_interval = poll_interval
+ self.reattach_on_restart = reattach_on_restart
+ self.delete_on_termination = delete_on_termination
+ self.get_logs = get_logs
+ self.random_name_suffix = random_name_suffix
+ self.ray_job_name: str | None = None
+
+ @cached_property
+ def hook(self) -> KubernetesHook:
+ """Get KubernetesHook instance."""
+ return KubernetesHook(
+ conn_id=self.kubernetes_conn_id,
+ in_cluster=self.in_cluster,
+ config_file=self.config_file,
+ cluster_context=self.cluster_context,
+ )
+
+ @cached_property
+ def pod_manager(self) -> PodManager:
+ """Get PodManager for log streaming."""
+ return PodManager(kube_client=self.hook.core_v1_client)
+
+ # --- Template & name handling ---
+
+ def _parse_template(self) -> dict:
+ """Parse and validate the RayJob specification."""
+ if self.application_file:
+ try:
+ filepath = Path(self.application_file.rstrip()).resolve(strict=True)
+ except (FileNotFoundError, OSError, RuntimeError, ValueError):
+ application_file_body = self.application_file
+ else:
+ application_file_body = filepath.read_text()
+
+ template_body = _load_body_to_dict(application_file_body)
+ if not isinstance(template_body, dict):
+ raise TypeError(
+ f"application_file body can't be transformed into dictionary:\n{application_file_body}"
+ )
+ elif self.template_spec:
+ template_body = copy.deepcopy(self.template_spec)
+ else:
+ raise AirflowException("Either application_file or template_spec must be provided")
+
+ template_body.setdefault("apiVersion", "ray.io/v1")
+ template_body.setdefault("kind", "RayJob")
+ template_body.setdefault("metadata", {})
+ template_body["metadata"].setdefault("name", self.task_id)
+ template_body["metadata"].setdefault("namespace", self.namespace)
+ return template_body
+
+ def _create_job_name(self) -> str:
+ """Generate a unique, RFC 1123 compliant job name."""
+ name = self.name or self.task_id
+ sanitized = pod_generator.make_safe_label_value(str(name).replace("_", "-"))
+ if self.random_name_suffix:
+ return add_unique_suffix(name=sanitized, max_len=MAX_LABEL_LEN)
+ return sanitized[:MAX_LABEL_LEN]
+
+ @staticmethod
+ def _get_ti_pod_labels(context: Context | None = None) -> dict[str, str]:
+ """Generate labels for reattachment after scheduler restart."""
+ if not context:
+ return {}
+
+ context_dict = cast("dict", context)
+ ti = context_dict["ti"]
+
+ labels = {
+ "dag_id": ti.dag_id,
+ "task_id": ti.task_id,
+ "run_id": context_dict["run_id"],
+ "ray_kubernetes_operator": "True",
+ "try_number": str(ti.try_number),
+ }
+
+ map_index = getattr(ti, "map_index", -1)
+ if map_index is not None and map_index >= 0:
+ labels["map_index"] = str(map_index)
+
+ return {
+ pod_generator.make_safe_label_value(k.replace("_", "-")): pod_generator.make_safe_label_value(
+ str(v)
+ )
+ for k, v in labels.items()
+ }
+
+ def _build_ray_job_body(self, context: Context) -> dict:
+ """Build the RayJob CRD body with labels for reattachment."""
+ body = copy.deepcopy(self._parse_template())
+ body["metadata"]["name"] = self.ray_job_name
+ body["metadata"].setdefault("labels", {})
+ body["metadata"]["labels"].update(self._get_ti_pod_labels(context))
+ return body
+
+ # --- CRD operations (all via KubernetesHook) ---
+
+ def _submit_ray_job(self, context: Context) -> None:
+ """Create the RayJob CRD via KubernetesHook."""
+ body = self._build_ray_job_body(context)
+ self.log.info("Creating RayJob: %s", self.ray_job_name)
+ self.hook.create_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ body=body,
+ namespace=self.namespace,
+ )
+
+ def _get_ray_job_status(self) -> tuple[str, str]:
+ """Get current job and deployment status from the RayJob CRD."""
+ obj = self.hook.get_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ status = obj.get("status", {})
+ return status.get("jobStatus", ""), status.get("jobDeploymentStatus", "")
+
+ def _delete_ray_job(self) -> None:
+ """Delete the RayJob CRD via KubernetesHook."""
+ if not self.ray_job_name:
+ return
+ try:
+ self.hook.delete_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ self.log.info("Deleted RayJob: %s", self.ray_job_name)
+ except Exception:
+ self.log.warning("Failed to delete RayJob %s (may already be deleted)", self.ray_job_name)
+
+ # --- Reattach ---
+
+ def _find_existing_ray_job(self, context: Context) -> str | None:
+ """Find an existing non-terminal RayJob for reattachment."""
+ try:
+ labels = self._get_ti_pod_labels(context)
+ if not labels:
+ return None
+
+ label_selector = ",".join(f"{k}={v}" for k, v in labels.items())
+ ray_jobs = self.hook.list_custom_objects(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ namespace=self.namespace,
+ label_selector=label_selector,
+ )
+
+ for item in ray_jobs.get("items", []):
+ job_name = item["metadata"]["name"]
+ job_status = item.get("status", {}).get("jobStatus", "")
+ dep_status = item.get("status", {}).get("jobDeploymentStatus", "")
+
+ if is_ray_job_terminal(job_status, dep_status):
+ continue
+
+ self.log.info("Reattaching to existing RayJob: %s", job_name)
+ return job_name
Review Comment:
Skipping — TI is idempotent and only one job is spawned per task instance, so the label selector can't match multiple non-terminal RayJobs in practice.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147407002
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/utils/ray_job_status.py:
##########
@@ -0,0 +1,60 @@
+#
+# 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.
+"""Status constants and helpers for KubeRay RayJob CRDs."""
+
+from __future__ import annotations
+
+
+class RayJobStatus:
+ """Ray Job status constants from the KubeRay RayJob CRD."""
+
+ PENDING = "PENDING"
+ RUNNING = "RUNNING"
+ STOPPED = "STOPPED"
+ SUCCEEDED = "SUCCEEDED"
+ FAILED = "FAILED"
+
+
+class RayJobDeploymentStatus:
+ """Ray Job deployment status constants from the KubeRay RayJob CRD."""
+
+ INITIALIZING = "Initializing"
+ RUNNING = "Running"
+ COMPLETE = "Complete"
+ FAILED = "Failed"
+ VALIDATION_FAILED = "ValidationFailed"
+ SUSPENDING = "Suspending"
+ SUSPENDED = "Suspended"
+
+
+TERMINAL_JOB_STATUSES = frozenset({RayJobStatus.SUCCEEDED, RayJobStatus.FAILED, RayJobStatus.STOPPED})
+TERMINAL_DEPLOYMENT_STATUSES = frozenset(
+ {RayJobDeploymentStatus.COMPLETE, RayJobDeploymentStatus.FAILED, RayJobDeploymentStatus.VALIDATION_FAILED}
+)
+
+
+def is_ray_job_terminal(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob is in a terminal state."""
+ return job_status in TERMINAL_JOB_STATUSES or deployment_status in TERMINAL_DEPLOYMENT_STATUSES
+
+
+def is_ray_job_successful(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob completed successfully."""
+ return job_status == RayJobStatus.SUCCEEDED or (
+ deployment_status == RayJobDeploymentStatus.COMPLETE and job_status == RayJobStatus.SUCCEEDED
+ )
Review Comment:
Fixed in 0407a93f — dropped COMPLETE from the live-streaming gate. Final log fetch on terminal state is handled in the terminal branch above
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147424394
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
Review Comment:
The PR description mentions an early RayObjectLauncher design that was later replaced by RayKubernetesOperator; updated PR body.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4100304183
> Also thanks for contributing this to us. I think we should rather consider - as Ray is a more complex ecosystem - to rather make a separate Ray provider.
I think keeping it in the CNCF Kubernetes provider makes sense for now — similar to how `SparkKubernetesOperator` lives here. This operator is specifically for KubeRay (RayJob CRDs on Kubernetes), not for managed Ray services
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r2967364312
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray_kubernetes.py:
##########
@@ -0,0 +1,507 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.operators.ray_object_launcher import RayObjectLauncher
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+from airflow.utils.helpers import prune_dict
+
+if TYPE_CHECKING:
+ import jinja2
+ from kubernetes.client import CoreV1Api, CustomObjectsApi
+
+ from airflow.providers.common.compat.sdk import Context
+
+
+class RayKubernetesOperator(BaseOperator):
Review Comment:
This operator does more than just creating a resource. monitors until its terminal state is reached.
Refactoring it to use the existing k8s hook stubs.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk closed pull request #63938: Add KubeRay (RayJob) operator to CNCF Kubernetes provider
URL: https://github.com/apache/airflow/pull/63938
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4100284049
> I can definitely see how an operator like this can be useful, especially with airflow increasingly being used to orchestrate heavy ML workloads. But a few concerns with the current approach:
>
> 1. This duplicates quite a bit of lifecycle logic from `KubernetesJobOperator` (KPO), unnecessarily. I get that some duplication is unavoidable here since this is a CRD (different API + status model vs Jobs), but this feels like it goes further and reimplements the full lifecycle (polling, retry, terminal state, cleanup) that we usually centralize in Kubernetes operators.
> 2. It bypasses a lot of the existing CRD methods in `KubernetesHook` by introducing bespoke logic in `ray_object_launcher.py` (which is the wrong layer btw), when `KubernetesHook` already provides `create/get/delete_custom_object` with retry and connection handling.
> 3. It doesn’t support deferrable mode (which is CRITICAL for long-running Ray jobs). I understand this can be added later in a follow-up PR, but the lifecycle here is built around a blocking polling loop with tightly coupled retry/state logic. I don’t think deferrable mode can just be tacked on without reworking the execution path.
>
> At a high level, this feels like it’s diverging from existing Kubernetes provider patterns. I would suggest:
>
> * Keep the operator thin (submit + optionally wait)
> * Use `KubernetesHook` directly where possible or, if needed, move the CRD interaction into a (small) hook on top of it
> * Remove `ray_object_launcher.py`
> * Move shared concepts like statuses into utils (similar to `utils/pod_manager.py`)
- Using the k8s hook now. And added list custom object stub to the hook.
- The op is deferrable now.
- Removed the `ray_object_launcher.py` as, we are using the k8s hook stubs now and moved ray lifecycle related stuff to `utils/`
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r2967406178
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray_kubernetes.py:
##########
Review Comment:
Done.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147434940
##########
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_ray.py:
##########
@@ -0,0 +1,183 @@
+#
+# 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.
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from airflow.providers.cncf.kubernetes.operators.ray import RayKubernetesOperator
+from airflow.providers.common.compat.sdk import AirflowException
+
+SAMPLE_TEMPLATE_SPEC = {
+ "apiVersion": "ray.io/v1",
+ "kind": "RayJob",
+ "metadata": {"name": "test-ray-job", "namespace": "default"},
+ "spec": {"entrypoint": "python script.py"},
+}
+
+
+class TestRayKubernetesOperator:
+ def test_init_with_template_spec(self):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ template_spec=SAMPLE_TEMPLATE_SPEC,
+ namespace="test-ns",
+ )
+ assert op.namespace == "test-ns"
+ assert op.wait_for_completion is True
+ assert op.delete_on_termination is True
+ assert op.reattach_on_restart is True
+
+ def test_init_with_application_file(self):
+ op = RayKubernetesOperator(task_id="test_ray", application_file="ray_job.yaml")
+ assert op.application_file == "ray_job.yaml"
+
+ def test_requires_spec_or_file(self):
+ op = RayKubernetesOperator(task_id="test_ray")
+ with pytest.raises(AirflowException, match="Either application_file or template_spec"):
+ op._parse_template()
+
+ def test_template_fields(self):
+ assert "application_file" in RayKubernetesOperator.template_fields
+ assert "template_spec" in RayKubernetesOperator.template_fields
+ assert "namespace" in RayKubernetesOperator.template_fields
+
+ def test_parse_template_adds_defaults(self):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ template_spec={"spec": {"entrypoint": "python script.py"}},
+ )
+ result = op._parse_template()
+ assert result["apiVersion"] == "ray.io/v1"
+ assert result["kind"] == "RayJob"
+ assert "metadata" in result
+
+ @patch(
+ "airflow.providers.cncf.kubernetes.operators.ray.add_unique_suffix",
+ return_value="test-ray-abc123",
+ )
+ def test_create_job_name_with_suffix(self, mock_suffix):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ template_spec=SAMPLE_TEMPLATE_SPEC,
+ random_name_suffix=True,
+ )
+ name = op._create_job_name()
+ assert name == "test-ray-abc123"
+
+ def test_create_job_name_without_suffix(self):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ name="my-ray-job",
+ template_spec=SAMPLE_TEMPLATE_SPEC,
+ random_name_suffix=False,
+ )
+ name = op._create_job_name()
+ assert name == "my-ray-job"
+
+ def test_get_ti_pod_labels_no_context(self):
+ labels = RayKubernetesOperator._get_ti_pod_labels(None)
+ assert labels == {}
+
+ def test_get_ti_pod_labels_with_context(self):
+ mock_ti = MagicMock()
+ mock_ti.dag_id = "test_dag"
+ mock_ti.task_id = "test_task"
+ mock_ti.try_number = 1
+ mock_ti.map_index = -1
+
+ context = {"ti": mock_ti, "run_id": "manual__2024-01-01"}
+ labels = RayKubernetesOperator._get_ti_pod_labels(context)
+ assert "dag-id" in labels
Review Comment:
Fixed in 0407a93f — mock_hook uses MagicMock(spec=KubernetesHook), mock_ti uses SimpleNamespace, mock_context is a plain dict.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3025339372
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+
+if TYPE_CHECKING:
+ from airflow.providers.common.compat.sdk import Context
+
+RAY_API_GROUP = "ray.io"
+RAY_API_VERSION = "v1"
+RAY_PLURAL = "rayjobs"
+
+
+class RayKubernetesOperator(BaseOperator):
+ """
+ Create a RayJob object in a Kubernetes cluster via the KubeRay operator.
+
+ Submits a RayJob CRD and optionally waits for completion. Uses ``KubernetesHook``
+ for all CRD operations (create, get, delete).
+
+ .. seealso::
+ For more detail about RayJob have a look at the reference:
+ https://docs.ray.io/en/latest/cluster/kubernetes/getting-started/rayjob-quick-start.html
+
+ :param application_file: filepath to a RayJob YAML/JSON definition
+ :param template_spec: RayJob specification as a Python dict
+ :param namespace: kubernetes namespace for the RayJob
+ :param name: name of the RayJob (optional, extracted from spec if not provided)
+ :param wait_for_completion: whether to wait for the job to finish (default: True)
+ :param get_logs: stream logs from the Ray head pod
+ :param startup_timeout_seconds: timeout for Ray cluster startup
+ :param job_timeout_seconds: timeout for the Ray job to complete
+ :param poll_interval: seconds between status polls
+ :param reattach_on_restart: reattach to existing RayJob on scheduler restart
+ :param delete_on_termination: delete the RayJob CRD when done
+ :param kubernetes_conn_id: Kubernetes connection ID
+ :param random_name_suffix: add a random suffix to the job name
+ """
+
+ template_fields = [
+ "application_file",
+ "template_spec",
+ "namespace",
+ "kubernetes_conn_id",
+ ]
+ template_fields_renderers = {"application_file": "yaml", "template_spec": "py"}
+ template_ext = ("yaml", "yml", "json")
+ ui_color = "#028edd"
+
+ BASE_CONTAINER_NAME = "ray-head"
+
+ def __init__(
+ self,
+ *,
+ application_file: str | None = None,
+ template_spec: dict | None = None,
+ namespace: str = "default",
+ name: str | None = None,
+ wait_for_completion: bool = True,
+ get_logs: bool = True,
+ startup_timeout_seconds: int = 600,
+ job_timeout_seconds: int = 7200,
+ poll_interval: int = 10,
+ reattach_on_restart: bool = True,
+ delete_on_termination: bool = True,
+ kubernetes_conn_id: str = "kubernetes_default",
+ in_cluster: bool | None = None,
+ config_file: str | None = None,
+ cluster_context: str | None = None,
+ random_name_suffix: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self.application_file = application_file
+ self.template_spec = template_spec
+ self.namespace = namespace
+ self.kubernetes_conn_id = kubernetes_conn_id
+ self.in_cluster = in_cluster
+ self.config_file = config_file
+ self.cluster_context = cluster_context
+ self.wait_for_completion = wait_for_completion
+ self.startup_timeout_seconds = startup_timeout_seconds
+ self.job_timeout_seconds = job_timeout_seconds
+ self.poll_interval = poll_interval
+ self.reattach_on_restart = reattach_on_restart
+ self.delete_on_termination = delete_on_termination
+ self.get_logs = get_logs
+ self.random_name_suffix = random_name_suffix
+ self.ray_job_name: str | None = None
+
+ @cached_property
+ def hook(self) -> KubernetesHook:
+ """Get KubernetesHook instance."""
+ return KubernetesHook(
+ conn_id=self.kubernetes_conn_id,
+ in_cluster=self.in_cluster,
+ config_file=self.config_file,
+ cluster_context=self.cluster_context,
+ )
+
+ @cached_property
+ def pod_manager(self) -> PodManager:
+ """Get PodManager for log streaming."""
+ return PodManager(kube_client=self.hook.core_v1_client)
+
+ # --- Template & name handling ---
+
+ def _parse_template(self) -> dict:
+ """Parse and validate the RayJob specification."""
+ if self.application_file:
+ try:
+ filepath = Path(self.application_file.rstrip()).resolve(strict=True)
+ except (FileNotFoundError, OSError, RuntimeError, ValueError):
+ application_file_body = self.application_file
+ else:
+ application_file_body = filepath.read_text()
+
+ template_body = _load_body_to_dict(application_file_body)
+ if not isinstance(template_body, dict):
+ raise TypeError(
+ f"application_file body can't be transformed into dictionary:\n{application_file_body}"
+ )
+ elif self.template_spec:
+ template_body = copy.deepcopy(self.template_spec)
+ else:
+ raise AirflowException("Either application_file or template_spec must be provided")
+
+ template_body.setdefault("apiVersion", "ray.io/v1")
+ template_body.setdefault("kind", "RayJob")
+ template_body.setdefault("metadata", {})
+ template_body["metadata"].setdefault("name", self.task_id)
+ template_body["metadata"].setdefault("namespace", self.namespace)
+ return template_body
+
+ def _create_job_name(self) -> str:
+ """Generate a unique, RFC 1123 compliant job name."""
+ name = self.name or self.task_id
+ sanitized = pod_generator.make_safe_label_value(str(name).replace("_", "-"))
+ if self.random_name_suffix:
+ return add_unique_suffix(name=sanitized, max_len=MAX_LABEL_LEN)
+ return sanitized[:MAX_LABEL_LEN]
Review Comment:
`_create_job_name()` uses `pod_generator.make_safe_label_value()` which is meant for Kubernetes *label values* and can still produce uppercase characters, underscores, or dots. `metadata.name` for a RayJob must satisfy DNS-1123 label rules (lowercase alphanumeric + `-`, max 63, start/end alphanumeric), so the generated name can be rejected by the Kubernetes API. Consider using the same DNS-1123 sanitization approach as other k8s operators (e.g. lowercasing + replacing invalid chars with `-` before truncation/suffixing).
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/utils/ray_job_status.py:
##########
@@ -0,0 +1,60 @@
+#
+# 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.
+"""Status constants and helpers for KubeRay RayJob CRDs."""
+
+from __future__ import annotations
+
+
+class RayJobStatus:
+ """Ray Job status constants from the KubeRay RayJob CRD."""
+
+ PENDING = "PENDING"
+ RUNNING = "RUNNING"
+ STOPPED = "STOPPED"
+ SUCCEEDED = "SUCCEEDED"
+ FAILED = "FAILED"
+
+
+class RayJobDeploymentStatus:
+ """Ray Job deployment status constants from the KubeRay RayJob CRD."""
+
+ INITIALIZING = "Initializing"
+ RUNNING = "Running"
+ COMPLETE = "Complete"
+ FAILED = "Failed"
+ VALIDATION_FAILED = "ValidationFailed"
+ SUSPENDING = "Suspending"
+ SUSPENDED = "Suspended"
+
+
+TERMINAL_JOB_STATUSES = frozenset({RayJobStatus.SUCCEEDED, RayJobStatus.FAILED, RayJobStatus.STOPPED})
+TERMINAL_DEPLOYMENT_STATUSES = frozenset(
+ {RayJobDeploymentStatus.COMPLETE, RayJobDeploymentStatus.FAILED, RayJobDeploymentStatus.VALIDATION_FAILED}
+)
+
+
+def is_ray_job_terminal(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob is in a terminal state."""
+ return job_status in TERMINAL_JOB_STATUSES or deployment_status in TERMINAL_DEPLOYMENT_STATUSES
+
+
+def is_ray_job_successful(job_status: str, deployment_status: str) -> bool:
+ """Check if a RayJob completed successfully."""
+ return job_status == RayJobStatus.SUCCEEDED or (
+ deployment_status == RayJobDeploymentStatus.COMPLETE and job_status == RayJobStatus.SUCCEEDED
+ )
Review Comment:
`is_ray_job_successful()` currently has a redundant condition: the second clause (`deployment_status == COMPLETE and job_status == SUCCEEDED`) can never make the result `True` beyond the first clause (`job_status == SUCCEEDED`). This is misleading and makes it unclear whether deployment status is supposed to affect success. Suggest simplifying to just `job_status == SUCCEEDED`, or (if intended) adjusting the logic to meaningfully incorporate `deployment_status`.
```suggestion
return job_status == RayJobStatus.SUCCEEDED
```
##########
providers/cncf/kubernetes/tests/system/cncf/kubernetes/example_ray.py:
##########
@@ -0,0 +1,125 @@
+#
+# 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.
+"""
+Example DAG using RayKubernetesOperator to submit a RayJob on Kubernetes.
+
+KubeRay operator is required to be installed on the Kubernetes cluster.
+https://docs.ray.io/en/latest/cluster/kubernetes/getting-started.html
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from airflow import DAG
+
+# [START import_module]
+from airflow.providers.cncf.kubernetes.operators.ray import RayKubernetesOperator
+
+# [END import_module]
+
+with DAG(
+ dag_id="example_ray_kubernetes",
+ schedule=None,
+ start_date=datetime(2024, 1, 1),
+ catchup=False,
+ tags=["example", "ray", "kubernetes"],
+) as dag:
+ # [START howto_operator_ray_kubernetes_template_spec]
+ ray_job_template_spec = RayKubernetesOperator(
+ task_id="ray_job_template_spec",
+ template_spec={
+ "apiVersion": "ray.io/v1",
+ "kind": "RayJob",
+ "metadata": {"name": "ray-job-example"},
+ "spec": {
+ "entrypoint": "python -c 'import ray; ray.init(); print(ray.cluster_resources())'",
+ "rayClusterSpec": {
+ "headGroupSpec": {
+ "rayStartParams": {"dashboard-host": "0.0.0.0"},
+ "template": {
+ "spec": {
+ "containers": [
+ {
+ "name": "ray-head",
+ "image": "rayproject/ray:2.9.0",
+ "resources": {
+ "limits": {"cpu": "1", "memory": "2Gi"},
+ "requests": {"cpu": "500m", "memory": "1Gi"},
+ },
+ }
+ ]
+ }
+ },
+ },
+ },
+ },
+ },
+ namespace="default",
+ kubernetes_conn_id="kubernetes_default",
+ startup_timeout_seconds=300,
+ job_timeout_seconds=600,
+ delete_on_termination=True,
+ )
+ # [END howto_operator_ray_kubernetes_template_spec]
+
+ # [START howto_operator_ray_kubernetes_yaml]
+ ray_job_yaml = RayKubernetesOperator(
+ task_id="ray_job_yaml",
+ application_file="example_ray_job.yaml",
+ namespace="default",
+ kubernetes_conn_id="kubernetes_default",
+ delete_on_termination=True,
+ )
Review Comment:
This system test DAG references `application_file="example_ray_job.yaml"`, but there is no `example_ray_job.yaml` in `providers/cncf/kubernetes/tests/system/cncf/kubernetes/` (and it’s not added in this PR). As written, the example will fail at runtime unless that file is added or the example is changed to use an inline `template_spec` / correct existing path.
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
Review Comment:
The PR description mentions adding a `RayObjectLauncher` (with tenacity retry, status constants, etc.), but this PR’s code changes appear to introduce `RayKubernetesOperator` plus `ray_job_status` helpers and a hook method. If `RayObjectLauncher` is still intended, it’s missing from the implementation; otherwise please update the PR description to match what’s actually being added.
##########
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_ray.py:
##########
@@ -0,0 +1,183 @@
+#
+# 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.
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from airflow.providers.cncf.kubernetes.operators.ray import RayKubernetesOperator
+from airflow.providers.common.compat.sdk import AirflowException
+
+SAMPLE_TEMPLATE_SPEC = {
+ "apiVersion": "ray.io/v1",
+ "kind": "RayJob",
+ "metadata": {"name": "test-ray-job", "namespace": "default"},
+ "spec": {"entrypoint": "python script.py"},
+}
+
+
+class TestRayKubernetesOperator:
+ def test_init_with_template_spec(self):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ template_spec=SAMPLE_TEMPLATE_SPEC,
+ namespace="test-ns",
+ )
+ assert op.namespace == "test-ns"
+ assert op.wait_for_completion is True
+ assert op.delete_on_termination is True
+ assert op.reattach_on_restart is True
+
+ def test_init_with_application_file(self):
+ op = RayKubernetesOperator(task_id="test_ray", application_file="ray_job.yaml")
+ assert op.application_file == "ray_job.yaml"
+
+ def test_requires_spec_or_file(self):
+ op = RayKubernetesOperator(task_id="test_ray")
+ with pytest.raises(AirflowException, match="Either application_file or template_spec"):
+ op._parse_template()
+
+ def test_template_fields(self):
+ assert "application_file" in RayKubernetesOperator.template_fields
+ assert "template_spec" in RayKubernetesOperator.template_fields
+ assert "namespace" in RayKubernetesOperator.template_fields
+
+ def test_parse_template_adds_defaults(self):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ template_spec={"spec": {"entrypoint": "python script.py"}},
+ )
+ result = op._parse_template()
+ assert result["apiVersion"] == "ray.io/v1"
+ assert result["kind"] == "RayJob"
+ assert "metadata" in result
+
+ @patch(
+ "airflow.providers.cncf.kubernetes.operators.ray.add_unique_suffix",
+ return_value="test-ray-abc123",
+ )
+ def test_create_job_name_with_suffix(self, mock_suffix):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ template_spec=SAMPLE_TEMPLATE_SPEC,
+ random_name_suffix=True,
+ )
+ name = op._create_job_name()
+ assert name == "test-ray-abc123"
+
+ def test_create_job_name_without_suffix(self):
+ op = RayKubernetesOperator(
+ task_id="test_ray",
+ name="my-ray-job",
+ template_spec=SAMPLE_TEMPLATE_SPEC,
+ random_name_suffix=False,
+ )
+ name = op._create_job_name()
+ assert name == "my-ray-job"
+
+ def test_get_ti_pod_labels_no_context(self):
+ labels = RayKubernetesOperator._get_ti_pod_labels(None)
+ assert labels == {}
+
+ def test_get_ti_pod_labels_with_context(self):
+ mock_ti = MagicMock()
+ mock_ti.dag_id = "test_dag"
+ mock_ti.task_id = "test_task"
+ mock_ti.try_number = 1
+ mock_ti.map_index = -1
+
+ context = {"ti": mock_ti, "run_id": "manual__2024-01-01"}
+ labels = RayKubernetesOperator._get_ti_pod_labels(context)
+ assert "dag-id" in labels
Review Comment:
Unit tests use `MagicMock()` instances without a `spec`/`autospec`, which can hide real attribute/typo errors (the mock will accept any attribute access). Prefer `MagicMock(spec=...)` (or `create_autospec(...)`) for `ti`/hook/context objects, and consider `patch(..., autospec=True)` where possible.
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+
+if TYPE_CHECKING:
+ from airflow.providers.common.compat.sdk import Context
+
+RAY_API_GROUP = "ray.io"
+RAY_API_VERSION = "v1"
+RAY_PLURAL = "rayjobs"
+
+
+class RayKubernetesOperator(BaseOperator):
+ """
+ Create a RayJob object in a Kubernetes cluster via the KubeRay operator.
+
+ Submits a RayJob CRD and optionally waits for completion. Uses ``KubernetesHook``
+ for all CRD operations (create, get, delete).
+
+ .. seealso::
+ For more detail about RayJob have a look at the reference:
+ https://docs.ray.io/en/latest/cluster/kubernetes/getting-started/rayjob-quick-start.html
+
+ :param application_file: filepath to a RayJob YAML/JSON definition
+ :param template_spec: RayJob specification as a Python dict
+ :param namespace: kubernetes namespace for the RayJob
+ :param name: name of the RayJob (optional, extracted from spec if not provided)
+ :param wait_for_completion: whether to wait for the job to finish (default: True)
+ :param get_logs: stream logs from the Ray head pod
+ :param startup_timeout_seconds: timeout for Ray cluster startup
+ :param job_timeout_seconds: timeout for the Ray job to complete
+ :param poll_interval: seconds between status polls
+ :param reattach_on_restart: reattach to existing RayJob on scheduler restart
+ :param delete_on_termination: delete the RayJob CRD when done
+ :param kubernetes_conn_id: Kubernetes connection ID
+ :param random_name_suffix: add a random suffix to the job name
+ """
+
+ template_fields = [
+ "application_file",
+ "template_spec",
+ "namespace",
+ "kubernetes_conn_id",
+ ]
+ template_fields_renderers = {"application_file": "yaml", "template_spec": "py"}
+ template_ext = ("yaml", "yml", "json")
+ ui_color = "#028edd"
+
+ BASE_CONTAINER_NAME = "ray-head"
+
+ def __init__(
+ self,
+ *,
+ application_file: str | None = None,
+ template_spec: dict | None = None,
+ namespace: str = "default",
+ name: str | None = None,
+ wait_for_completion: bool = True,
+ get_logs: bool = True,
+ startup_timeout_seconds: int = 600,
+ job_timeout_seconds: int = 7200,
+ poll_interval: int = 10,
+ reattach_on_restart: bool = True,
+ delete_on_termination: bool = True,
+ kubernetes_conn_id: str = "kubernetes_default",
+ in_cluster: bool | None = None,
+ config_file: str | None = None,
+ cluster_context: str | None = None,
+ random_name_suffix: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self.application_file = application_file
+ self.template_spec = template_spec
+ self.namespace = namespace
+ self.kubernetes_conn_id = kubernetes_conn_id
+ self.in_cluster = in_cluster
+ self.config_file = config_file
+ self.cluster_context = cluster_context
+ self.wait_for_completion = wait_for_completion
+ self.startup_timeout_seconds = startup_timeout_seconds
+ self.job_timeout_seconds = job_timeout_seconds
+ self.poll_interval = poll_interval
+ self.reattach_on_restart = reattach_on_restart
+ self.delete_on_termination = delete_on_termination
+ self.get_logs = get_logs
+ self.random_name_suffix = random_name_suffix
+ self.ray_job_name: str | None = None
+
+ @cached_property
+ def hook(self) -> KubernetesHook:
+ """Get KubernetesHook instance."""
+ return KubernetesHook(
+ conn_id=self.kubernetes_conn_id,
+ in_cluster=self.in_cluster,
+ config_file=self.config_file,
+ cluster_context=self.cluster_context,
+ )
+
+ @cached_property
+ def pod_manager(self) -> PodManager:
+ """Get PodManager for log streaming."""
+ return PodManager(kube_client=self.hook.core_v1_client)
+
+ # --- Template & name handling ---
+
+ def _parse_template(self) -> dict:
+ """Parse and validate the RayJob specification."""
+ if self.application_file:
+ try:
+ filepath = Path(self.application_file.rstrip()).resolve(strict=True)
+ except (FileNotFoundError, OSError, RuntimeError, ValueError):
+ application_file_body = self.application_file
+ else:
+ application_file_body = filepath.read_text()
+
+ template_body = _load_body_to_dict(application_file_body)
+ if not isinstance(template_body, dict):
+ raise TypeError(
+ f"application_file body can't be transformed into dictionary:\n{application_file_body}"
+ )
+ elif self.template_spec:
+ template_body = copy.deepcopy(self.template_spec)
+ else:
+ raise AirflowException("Either application_file or template_spec must be provided")
+
+ template_body.setdefault("apiVersion", "ray.io/v1")
+ template_body.setdefault("kind", "RayJob")
+ template_body.setdefault("metadata", {})
+ template_body["metadata"].setdefault("name", self.task_id)
+ template_body["metadata"].setdefault("namespace", self.namespace)
+ return template_body
+
+ def _create_job_name(self) -> str:
+ """Generate a unique, RFC 1123 compliant job name."""
+ name = self.name or self.task_id
+ sanitized = pod_generator.make_safe_label_value(str(name).replace("_", "-"))
+ if self.random_name_suffix:
+ return add_unique_suffix(name=sanitized, max_len=MAX_LABEL_LEN)
+ return sanitized[:MAX_LABEL_LEN]
+
+ @staticmethod
+ def _get_ti_pod_labels(context: Context | None = None) -> dict[str, str]:
+ """Generate labels for reattachment after scheduler restart."""
+ if not context:
+ return {}
+
+ context_dict = cast("dict", context)
+ ti = context_dict["ti"]
+
+ labels = {
+ "dag_id": ti.dag_id,
+ "task_id": ti.task_id,
+ "run_id": context_dict["run_id"],
+ "ray_kubernetes_operator": "True",
+ "try_number": str(ti.try_number),
+ }
+
+ map_index = getattr(ti, "map_index", -1)
+ if map_index is not None and map_index >= 0:
+ labels["map_index"] = str(map_index)
+
+ return {
+ pod_generator.make_safe_label_value(k.replace("_", "-")): pod_generator.make_safe_label_value(
+ str(v)
+ )
+ for k, v in labels.items()
+ }
+
+ def _build_ray_job_body(self, context: Context) -> dict:
+ """Build the RayJob CRD body with labels for reattachment."""
+ body = copy.deepcopy(self._parse_template())
+ body["metadata"]["name"] = self.ray_job_name
+ body["metadata"].setdefault("labels", {})
+ body["metadata"]["labels"].update(self._get_ti_pod_labels(context))
+ return body
+
+ # --- CRD operations (all via KubernetesHook) ---
+
+ def _submit_ray_job(self, context: Context) -> None:
+ """Create the RayJob CRD via KubernetesHook."""
+ body = self._build_ray_job_body(context)
+ self.log.info("Creating RayJob: %s", self.ray_job_name)
+ self.hook.create_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ body=body,
+ namespace=self.namespace,
+ )
+
+ def _get_ray_job_status(self) -> tuple[str, str]:
+ """Get current job and deployment status from the RayJob CRD."""
+ obj = self.hook.get_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ status = obj.get("status", {})
+ return status.get("jobStatus", ""), status.get("jobDeploymentStatus", "")
+
+ def _delete_ray_job(self) -> None:
+ """Delete the RayJob CRD via KubernetesHook."""
+ if not self.ray_job_name:
+ return
+ try:
+ self.hook.delete_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ self.log.info("Deleted RayJob: %s", self.ray_job_name)
+ except Exception:
+ self.log.warning("Failed to delete RayJob %s (may already be deleted)", self.ray_job_name)
+
+ # --- Reattach ---
+
+ def _find_existing_ray_job(self, context: Context) -> str | None:
+ """Find an existing non-terminal RayJob for reattachment."""
+ try:
+ labels = self._get_ti_pod_labels(context)
+ if not labels:
+ return None
+
+ label_selector = ",".join(f"{k}={v}" for k, v in labels.items())
+ ray_jobs = self.hook.list_custom_objects(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ namespace=self.namespace,
+ label_selector=label_selector,
+ )
+
+ for item in ray_jobs.get("items", []):
+ job_name = item["metadata"]["name"]
+ job_status = item.get("status", {}).get("jobStatus", "")
+ dep_status = item.get("status", {}).get("jobDeploymentStatus", "")
+
+ if is_ray_job_terminal(job_status, dep_status):
+ continue
+
+ self.log.info("Reattaching to existing RayJob: %s", job_name)
+ return job_name
+ except Exception as e:
+ self.log.warning("Error searching for existing RayJob: %s", e)
+ return None
+
+ # --- Monitoring ---
+
+ def _wait_for_terminal_state(self) -> str:
+ """Poll the RayJob status until terminal or timeout."""
+ start_time = time.monotonic()
+ cluster_ready = False
+ last_log_time = None
+ head_pod_cache: dict[str, Any] = {}
+
+ while True:
+ elapsed = time.monotonic() - start_time
+
+ try:
+ job_status, dep_status = self._get_ray_job_status()
+ except Exception:
+ self.log.exception("Failed to get RayJob status for %s", self.ray_job_name)
+ raise
+
+ self.log.info(
+ "RayJob %s — job: %s, deployment: %s (%.0fs elapsed)",
+ self.ray_job_name,
+ job_status or "NEW",
+ dep_status or "NEW",
+ elapsed,
+ )
+
+ if is_ray_job_terminal(job_status, dep_status):
+ if is_ray_job_successful(job_status, dep_status):
+ return "SUCCEEDED"
+ raise AirflowException(f"RayJob failed — job: {job_status}, deployment: {dep_status}")
+
+ # Stream logs when running
+ if (
+ dep_status in (RayJobDeploymentStatus.RUNNING, RayJobDeploymentStatus.COMPLETE)
+ and self.get_logs
+ ):
Review Comment:
In `_wait_for_terminal_state()`, `RayJobDeploymentStatus.COMPLETE` is treated as terminal by `is_ray_job_terminal()`, so the later log-streaming condition that includes `dep_status == COMPLETE` is unreachable. Either remove `COMPLETE` from the log-stream condition, or adjust the terminal-state logic so that `COMPLETE` isn't considered terminal until the job status is terminal as well (depending on the intended KubeRay semantics).
```suggestion
if dep_status == RayJobDeploymentStatus.RUNNING and self.get_logs:
```
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+
+if TYPE_CHECKING:
+ from airflow.providers.common.compat.sdk import Context
+
+RAY_API_GROUP = "ray.io"
+RAY_API_VERSION = "v1"
+RAY_PLURAL = "rayjobs"
+
+
+class RayKubernetesOperator(BaseOperator):
+ """
+ Create a RayJob object in a Kubernetes cluster via the KubeRay operator.
+
+ Submits a RayJob CRD and optionally waits for completion. Uses ``KubernetesHook``
+ for all CRD operations (create, get, delete).
+
+ .. seealso::
+ For more detail about RayJob have a look at the reference:
+ https://docs.ray.io/en/latest/cluster/kubernetes/getting-started/rayjob-quick-start.html
+
+ :param application_file: filepath to a RayJob YAML/JSON definition
+ :param template_spec: RayJob specification as a Python dict
+ :param namespace: kubernetes namespace for the RayJob
+ :param name: name of the RayJob (optional, extracted from spec if not provided)
+ :param wait_for_completion: whether to wait for the job to finish (default: True)
+ :param get_logs: stream logs from the Ray head pod
+ :param startup_timeout_seconds: timeout for Ray cluster startup
+ :param job_timeout_seconds: timeout for the Ray job to complete
+ :param poll_interval: seconds between status polls
+ :param reattach_on_restart: reattach to existing RayJob on scheduler restart
+ :param delete_on_termination: delete the RayJob CRD when done
+ :param kubernetes_conn_id: Kubernetes connection ID
+ :param random_name_suffix: add a random suffix to the job name
+ """
+
+ template_fields = [
+ "application_file",
+ "template_spec",
+ "namespace",
+ "kubernetes_conn_id",
+ ]
+ template_fields_renderers = {"application_file": "yaml", "template_spec": "py"}
+ template_ext = ("yaml", "yml", "json")
+ ui_color = "#028edd"
+
+ BASE_CONTAINER_NAME = "ray-head"
+
+ def __init__(
+ self,
+ *,
+ application_file: str | None = None,
+ template_spec: dict | None = None,
+ namespace: str = "default",
+ name: str | None = None,
+ wait_for_completion: bool = True,
+ get_logs: bool = True,
+ startup_timeout_seconds: int = 600,
+ job_timeout_seconds: int = 7200,
+ poll_interval: int = 10,
+ reattach_on_restart: bool = True,
+ delete_on_termination: bool = True,
+ kubernetes_conn_id: str = "kubernetes_default",
+ in_cluster: bool | None = None,
+ config_file: str | None = None,
+ cluster_context: str | None = None,
+ random_name_suffix: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self.application_file = application_file
+ self.template_spec = template_spec
+ self.namespace = namespace
+ self.kubernetes_conn_id = kubernetes_conn_id
+ self.in_cluster = in_cluster
+ self.config_file = config_file
+ self.cluster_context = cluster_context
+ self.wait_for_completion = wait_for_completion
+ self.startup_timeout_seconds = startup_timeout_seconds
+ self.job_timeout_seconds = job_timeout_seconds
+ self.poll_interval = poll_interval
+ self.reattach_on_restart = reattach_on_restart
+ self.delete_on_termination = delete_on_termination
+ self.get_logs = get_logs
+ self.random_name_suffix = random_name_suffix
+ self.ray_job_name: str | None = None
+
+ @cached_property
+ def hook(self) -> KubernetesHook:
+ """Get KubernetesHook instance."""
+ return KubernetesHook(
+ conn_id=self.kubernetes_conn_id,
+ in_cluster=self.in_cluster,
+ config_file=self.config_file,
+ cluster_context=self.cluster_context,
+ )
+
+ @cached_property
+ def pod_manager(self) -> PodManager:
+ """Get PodManager for log streaming."""
+ return PodManager(kube_client=self.hook.core_v1_client)
+
+ # --- Template & name handling ---
+
+ def _parse_template(self) -> dict:
+ """Parse and validate the RayJob specification."""
+ if self.application_file:
+ try:
+ filepath = Path(self.application_file.rstrip()).resolve(strict=True)
+ except (FileNotFoundError, OSError, RuntimeError, ValueError):
+ application_file_body = self.application_file
+ else:
+ application_file_body = filepath.read_text()
+
+ template_body = _load_body_to_dict(application_file_body)
+ if not isinstance(template_body, dict):
+ raise TypeError(
+ f"application_file body can't be transformed into dictionary:\n{application_file_body}"
+ )
+ elif self.template_spec:
+ template_body = copy.deepcopy(self.template_spec)
+ else:
+ raise AirflowException("Either application_file or template_spec must be provided")
+
+ template_body.setdefault("apiVersion", "ray.io/v1")
+ template_body.setdefault("kind", "RayJob")
+ template_body.setdefault("metadata", {})
+ template_body["metadata"].setdefault("name", self.task_id)
+ template_body["metadata"].setdefault("namespace", self.namespace)
+ return template_body
+
+ def _create_job_name(self) -> str:
+ """Generate a unique, RFC 1123 compliant job name."""
+ name = self.name or self.task_id
+ sanitized = pod_generator.make_safe_label_value(str(name).replace("_", "-"))
+ if self.random_name_suffix:
+ return add_unique_suffix(name=sanitized, max_len=MAX_LABEL_LEN)
+ return sanitized[:MAX_LABEL_LEN]
+
+ @staticmethod
+ def _get_ti_pod_labels(context: Context | None = None) -> dict[str, str]:
+ """Generate labels for reattachment after scheduler restart."""
+ if not context:
+ return {}
+
+ context_dict = cast("dict", context)
+ ti = context_dict["ti"]
+
+ labels = {
+ "dag_id": ti.dag_id,
+ "task_id": ti.task_id,
+ "run_id": context_dict["run_id"],
+ "ray_kubernetes_operator": "True",
+ "try_number": str(ti.try_number),
+ }
+
+ map_index = getattr(ti, "map_index", -1)
+ if map_index is not None and map_index >= 0:
+ labels["map_index"] = str(map_index)
+
+ return {
+ pod_generator.make_safe_label_value(k.replace("_", "-")): pod_generator.make_safe_label_value(
+ str(v)
+ )
+ for k, v in labels.items()
+ }
+
+ def _build_ray_job_body(self, context: Context) -> dict:
+ """Build the RayJob CRD body with labels for reattachment."""
+ body = copy.deepcopy(self._parse_template())
+ body["metadata"]["name"] = self.ray_job_name
+ body["metadata"].setdefault("labels", {})
+ body["metadata"]["labels"].update(self._get_ti_pod_labels(context))
+ return body
+
+ # --- CRD operations (all via KubernetesHook) ---
+
+ def _submit_ray_job(self, context: Context) -> None:
+ """Create the RayJob CRD via KubernetesHook."""
+ body = self._build_ray_job_body(context)
+ self.log.info("Creating RayJob: %s", self.ray_job_name)
+ self.hook.create_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ body=body,
+ namespace=self.namespace,
+ )
+
+ def _get_ray_job_status(self) -> tuple[str, str]:
+ """Get current job and deployment status from the RayJob CRD."""
+ obj = self.hook.get_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ status = obj.get("status", {})
+ return status.get("jobStatus", ""), status.get("jobDeploymentStatus", "")
+
+ def _delete_ray_job(self) -> None:
+ """Delete the RayJob CRD via KubernetesHook."""
+ if not self.ray_job_name:
+ return
+ try:
+ self.hook.delete_custom_object(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ name=self.ray_job_name,
+ namespace=self.namespace,
+ )
+ self.log.info("Deleted RayJob: %s", self.ray_job_name)
+ except Exception:
+ self.log.warning("Failed to delete RayJob %s (may already be deleted)", self.ray_job_name)
+
+ # --- Reattach ---
+
+ def _find_existing_ray_job(self, context: Context) -> str | None:
+ """Find an existing non-terminal RayJob for reattachment."""
+ try:
+ labels = self._get_ti_pod_labels(context)
+ if not labels:
+ return None
+
+ label_selector = ",".join(f"{k}={v}" for k, v in labels.items())
+ ray_jobs = self.hook.list_custom_objects(
+ group=RAY_API_GROUP,
+ version=RAY_API_VERSION,
+ plural=RAY_PLURAL,
+ namespace=self.namespace,
+ label_selector=label_selector,
+ )
+
+ for item in ray_jobs.get("items", []):
+ job_name = item["metadata"]["name"]
+ job_status = item.get("status", {}).get("jobStatus", "")
+ dep_status = item.get("status", {}).get("jobDeploymentStatus", "")
+
+ if is_ray_job_terminal(job_status, dep_status):
+ continue
+
+ self.log.info("Reattaching to existing RayJob: %s", job_name)
+ return job_name
Review Comment:
`_find_existing_ray_job()` returns the first non-terminal RayJob matching the label selector. If multiple matching RayJobs exist (e.g. a previous attempt created a job but the task crashed before labeling/cleanup, or duplicate creates), this can reattach to an arbitrary job and leave others orphaned. Consider handling the multi-match case explicitly (raise like `KubernetesPodOperator` does on duplicate labels, or deterministically pick the most recent / non-terminating one).
```suggestion
candidate_jobs: list[dict[str, Any]] = []
for item in ray_jobs.get("items", []):
status = item.get("status", {})
job_status = status.get("jobStatus", "")
dep_status = status.get("jobDeploymentStatus", "")
if is_ray_job_terminal(job_status, dep_status):
continue
candidate_jobs.append(item)
if not candidate_jobs:
return None
if len(candidate_jobs) > 1:
job_names = ", ".join(
sorted(job.get("metadata", {}).get("name", "<unknown>") for job in candidate_jobs)
)
raise AirflowException(
f"More than one active RayJob found for labels {label_selector!r}: {job_names}. "
"Please ensure that the labels uniquely identify a single RayJob."
)
job_name = candidate_jobs[0]["metadata"]["name"]
self.log.info("Reattaching to existing RayJob: %s", job_name)
return job_name
except AirflowException:
# Re-raise explicit operator errors so they surface to the task.
raise
```
##########
providers/cncf/kubernetes/tests/system/cncf/kubernetes/example_ray.py:
##########
@@ -0,0 +1,125 @@
+#
+# 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.
+"""
+Example DAG using RayKubernetesOperator to submit a RayJob on Kubernetes.
+
+KubeRay operator is required to be installed on the Kubernetes cluster.
+https://docs.ray.io/en/latest/cluster/kubernetes/getting-started.html
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from airflow import DAG
+
+# [START import_module]
+from airflow.providers.cncf.kubernetes.operators.ray import RayKubernetesOperator
+
+# [END import_module]
+
+with DAG(
+ dag_id="example_ray_kubernetes",
+ schedule=None,
+ start_date=datetime(2024, 1, 1),
+ catchup=False,
+ tags=["example", "ray", "kubernetes"],
+) as dag:
+ # [START howto_operator_ray_kubernetes_template_spec]
Review Comment:
Other Kubernetes provider system tests typically include `ENV_ID`/`DAG_ID` variables and attach `watcher()` to the task list to ensure the system test harness correctly records success/failure (e.g. `example_kubernetes_job.py`, `example_spark_kubernetes.py`). This example DAG omits that pattern, which can make the system test flaky or not integrate with the standard runner. Consider aligning it with the existing system test structure.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147404607
##########
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/ray.py:
##########
@@ -0,0 +1,420 @@
+#
+# 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.
+"""Operator for managing Ray workloads on Kubernetes via KubeRay."""
+
+from __future__ import annotations
+
+import copy
+import time
+from functools import cached_property
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+from airflow.providers.cncf.kubernetes import pod_generator
+from airflow.providers.cncf.kubernetes.hooks.kubernetes import KubernetesHook, _load_body_to_dict
+from airflow.providers.cncf.kubernetes.kubernetes_helper_functions import add_unique_suffix
+from airflow.providers.cncf.kubernetes.pod_generator import MAX_LABEL_LEN
+from airflow.providers.cncf.kubernetes.utils.pod_manager import PodManager
+from airflow.providers.cncf.kubernetes.utils.ray_job_status import (
+ RayJobDeploymentStatus,
+ is_ray_job_successful,
+ is_ray_job_terminal,
+)
+from airflow.providers.common.compat.sdk import AirflowException, BaseOperator
+
+if TYPE_CHECKING:
+ from airflow.providers.common.compat.sdk import Context
+
+RAY_API_GROUP = "ray.io"
+RAY_API_VERSION = "v1"
+RAY_PLURAL = "rayjobs"
+
+
+class RayKubernetesOperator(BaseOperator):
+ """
+ Create a RayJob object in a Kubernetes cluster via the KubeRay operator.
+
+ Submits a RayJob CRD and optionally waits for completion. Uses ``KubernetesHook``
+ for all CRD operations (create, get, delete).
+
+ .. seealso::
+ For more detail about RayJob have a look at the reference:
+ https://docs.ray.io/en/latest/cluster/kubernetes/getting-started/rayjob-quick-start.html
+
+ :param application_file: filepath to a RayJob YAML/JSON definition
+ :param template_spec: RayJob specification as a Python dict
+ :param namespace: kubernetes namespace for the RayJob
+ :param name: name of the RayJob (optional, extracted from spec if not provided)
+ :param wait_for_completion: whether to wait for the job to finish (default: True)
+ :param get_logs: stream logs from the Ray head pod
+ :param startup_timeout_seconds: timeout for Ray cluster startup
+ :param job_timeout_seconds: timeout for the Ray job to complete
+ :param poll_interval: seconds between status polls
+ :param reattach_on_restart: reattach to existing RayJob on scheduler restart
+ :param delete_on_termination: delete the RayJob CRD when done
+ :param kubernetes_conn_id: Kubernetes connection ID
+ :param random_name_suffix: add a random suffix to the job name
+ """
+
+ template_fields = [
+ "application_file",
+ "template_spec",
+ "namespace",
+ "kubernetes_conn_id",
+ ]
+ template_fields_renderers = {"application_file": "yaml", "template_spec": "py"}
+ template_ext = ("yaml", "yml", "json")
+ ui_color = "#028edd"
+
+ BASE_CONTAINER_NAME = "ray-head"
+
+ def __init__(
+ self,
+ *,
+ application_file: str | None = None,
+ template_spec: dict | None = None,
+ namespace: str = "default",
+ name: str | None = None,
+ wait_for_completion: bool = True,
+ get_logs: bool = True,
+ startup_timeout_seconds: int = 600,
+ job_timeout_seconds: int = 7200,
+ poll_interval: int = 10,
+ reattach_on_restart: bool = True,
+ delete_on_termination: bool = True,
+ kubernetes_conn_id: str = "kubernetes_default",
+ in_cluster: bool | None = None,
+ config_file: str | None = None,
+ cluster_context: str | None = None,
+ random_name_suffix: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self.application_file = application_file
+ self.template_spec = template_spec
+ self.namespace = namespace
+ self.kubernetes_conn_id = kubernetes_conn_id
+ self.in_cluster = in_cluster
+ self.config_file = config_file
+ self.cluster_context = cluster_context
+ self.wait_for_completion = wait_for_completion
+ self.startup_timeout_seconds = startup_timeout_seconds
+ self.job_timeout_seconds = job_timeout_seconds
+ self.poll_interval = poll_interval
+ self.reattach_on_restart = reattach_on_restart
+ self.delete_on_termination = delete_on_termination
+ self.get_logs = get_logs
+ self.random_name_suffix = random_name_suffix
+ self.ray_job_name: str | None = None
+
+ @cached_property
+ def hook(self) -> KubernetesHook:
+ """Get KubernetesHook instance."""
+ return KubernetesHook(
+ conn_id=self.kubernetes_conn_id,
+ in_cluster=self.in_cluster,
+ config_file=self.config_file,
+ cluster_context=self.cluster_context,
+ )
+
+ @cached_property
+ def pod_manager(self) -> PodManager:
+ """Get PodManager for log streaming."""
+ return PodManager(kube_client=self.hook.core_v1_client)
+
+ # --- Template & name handling ---
+
+ def _parse_template(self) -> dict:
+ """Parse and validate the RayJob specification."""
+ if self.application_file:
+ try:
+ filepath = Path(self.application_file.rstrip()).resolve(strict=True)
+ except (FileNotFoundError, OSError, RuntimeError, ValueError):
+ application_file_body = self.application_file
+ else:
+ application_file_body = filepath.read_text()
+
+ template_body = _load_body_to_dict(application_file_body)
+ if not isinstance(template_body, dict):
+ raise TypeError(
+ f"application_file body can't be transformed into dictionary:\n{application_file_body}"
+ )
+ elif self.template_spec:
+ template_body = copy.deepcopy(self.template_spec)
+ else:
+ raise AirflowException("Either application_file or template_spec must be provided")
+
+ template_body.setdefault("apiVersion", "ray.io/v1")
+ template_body.setdefault("kind", "RayJob")
+ template_body.setdefault("metadata", {})
+ template_body["metadata"].setdefault("name", self.task_id)
+ template_body["metadata"].setdefault("namespace", self.namespace)
+ return template_body
+
+ def _create_job_name(self) -> str:
+ """Generate a unique, RFC 1123 compliant job name."""
+ name = self.name or self.task_id
+ sanitized = pod_generator.make_safe_label_value(str(name).replace("_", "-"))
+ if self.random_name_suffix:
+ return add_unique_suffix(name=sanitized, max_len=MAX_LABEL_LEN)
+ return sanitized[:MAX_LABEL_LEN]
Review Comment:
Fixed in 0407a93f — switched to slugify(name, lowercase=True). The make_safe_label_value use at line 195 stays since that's for label values, not names.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "tardunge (via GitHub)" <gi...@apache.org>.
tardunge commented on code in PR #63938:
URL: https://github.com/apache/airflow/pull/63938#discussion_r3147429591
##########
providers/cncf/kubernetes/tests/system/cncf/kubernetes/example_ray.py:
##########
@@ -0,0 +1,125 @@
+#
+# 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.
+"""
+Example DAG using RayKubernetesOperator to submit a RayJob on Kubernetes.
+
+KubeRay operator is required to be installed on the Kubernetes cluster.
+https://docs.ray.io/en/latest/cluster/kubernetes/getting-started.html
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from airflow import DAG
+
+# [START import_module]
+from airflow.providers.cncf.kubernetes.operators.ray import RayKubernetesOperator
+
+# [END import_module]
+
+with DAG(
+ dag_id="example_ray_kubernetes",
+ schedule=None,
+ start_date=datetime(2024, 1, 1),
+ catchup=False,
+ tags=["example", "ray", "kubernetes"],
+) as dag:
+ # [START howto_operator_ray_kubernetes_template_spec]
+ ray_job_template_spec = RayKubernetesOperator(
+ task_id="ray_job_template_spec",
+ template_spec={
+ "apiVersion": "ray.io/v1",
+ "kind": "RayJob",
+ "metadata": {"name": "ray-job-example"},
+ "spec": {
+ "entrypoint": "python -c 'import ray; ray.init(); print(ray.cluster_resources())'",
+ "rayClusterSpec": {
+ "headGroupSpec": {
+ "rayStartParams": {"dashboard-host": "0.0.0.0"},
+ "template": {
+ "spec": {
+ "containers": [
+ {
+ "name": "ray-head",
+ "image": "rayproject/ray:2.9.0",
+ "resources": {
+ "limits": {"cpu": "1", "memory": "2Gi"},
+ "requests": {"cpu": "500m", "memory": "1Gi"},
+ },
+ }
+ ]
+ }
+ },
+ },
+ },
+ },
+ },
+ namespace="default",
+ kubernetes_conn_id="kubernetes_default",
+ startup_timeout_seconds=300,
+ job_timeout_seconds=600,
+ delete_on_termination=True,
+ )
+ # [END howto_operator_ray_kubernetes_template_spec]
+
+ # [START howto_operator_ray_kubernetes_yaml]
+ ray_job_yaml = RayKubernetesOperator(
+ task_id="ray_job_yaml",
+ application_file="example_ray_job.yaml",
+ namespace="default",
+ kubernetes_conn_id="kubernetes_default",
+ delete_on_termination=True,
+ )
Review Comment:
Fixed in 0407a93f — added example_ray_job.yaml and switched application_file to an absolute path via Path(__file__).parent.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add KubeRay (RayJob) operator to CNCF Kubernetes provider [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #63938:
URL: https://github.com/apache/airflow/pull/63938#issuecomment-4416914942
@tardunge Converting to **draft** — this PR doesn't yet meet our [Pull Request quality criteria](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-quality-criteria).
- :x: **Pre-commit / static checks** — Failing: `CI image checks / Static checks`. See [docs](https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst).
- :x: **Provider tests** — Failing: 4 `provider distributions tests / Compat` runs against Airflow 2.11.1, 3.0.6, 3.1.8, 3.2.1 (P3.10). See [docs](https://github.com/apache/airflow/blob/main/contributing-docs/12_provider_distributions.rst).
See the linked criteria for how to fix each item, then mark the PR "Ready for review". This is **not** a rejection — just an invitation to bring the PR up to standard. No rush.
---
_Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this [two-stage triage process](https://github.com/apache/airflow/blob/main/contributing-docs/25_maintainer_pr_triage.md#why-the-first-pass-is-automated) so that our maintainers' limited time is spent where it matters most: the conversation with you._
---
Drafted-by: Claude Code (Opus 4.7); reviewed by @potiuk before posting
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org