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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to