| 
 | 1 | +#  Copyright (c) ZenML GmbH 2022. All Rights Reserved.  | 
 | 2 | +#  | 
 | 3 | +#  Licensed under the Apache License, Version 2.0 (the "License");  | 
 | 4 | +#  you may not use this file except in compliance with the License.  | 
 | 5 | +#  You may obtain a copy of the License at:  | 
 | 6 | +#  | 
 | 7 | +#       https://www.apache.org/licenses/LICENSE-2.0  | 
 | 8 | +#  | 
 | 9 | +#  Unless required by applicable law or agreed to in writing, software  | 
 | 10 | +#  distributed under the License is distributed on an "AS IS" BASIS,  | 
 | 11 | +#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express  | 
 | 12 | +#  or implied. See the License for the specific language governing  | 
 | 13 | +#  permissions and limitations under the License.  | 
 | 14 | +"""ZenML Step HeartBeat functionality."""  | 
 | 15 | + | 
 | 16 | +import _thread  | 
 | 17 | +import logging  | 
 | 18 | +import threading  | 
 | 19 | +import time  | 
 | 20 | +from typing import Annotated  | 
 | 21 | +from uuid import UUID  | 
 | 22 | + | 
 | 23 | +from pydantic import BaseModel, conint, model_validator  | 
 | 24 | + | 
 | 25 | +from zenml.enums import ExecutionStatus  | 
 | 26 | + | 
 | 27 | +logger = logging.getLogger(__name__)  | 
 | 28 | + | 
 | 29 | + | 
 | 30 | +class StepHeartBeatTerminationException(Exception):  | 
 | 31 | +    """Custom exception class for heartbeat termination."""  | 
 | 32 | + | 
 | 33 | +    pass  | 
 | 34 | + | 
 | 35 | + | 
 | 36 | +class StepHeartBeatOptions(BaseModel):  | 
 | 37 | +    """Options group for step heartbeat execution."""  | 
 | 38 | + | 
 | 39 | +    step_id: UUID  | 
 | 40 | +    interval: Annotated[int, conint(ge=10, le=60)]  | 
 | 41 | +    name: str | None = None  | 
 | 42 | + | 
 | 43 | +    @model_validator(mode="after")  | 
 | 44 | +    def set_default_name(self) -> "StepHeartBeatOptions":  | 
 | 45 | +        """Model validator - set name value if missing.  | 
 | 46 | +
  | 
 | 47 | +        Returns:  | 
 | 48 | +            The validated step heartbeat options.  | 
 | 49 | +        """  | 
 | 50 | +        if not self.name:  | 
 | 51 | +            self.name = f"HeartBeatWorker-{self.step_id}"  | 
 | 52 | + | 
 | 53 | +        return self  | 
 | 54 | + | 
 | 55 | + | 
 | 56 | +class HeartbeatWorker:  | 
 | 57 | +    """Worker class implementing heartbeat polling and remote termination."""  | 
 | 58 | + | 
 | 59 | +    def __init__(self, options: StepHeartBeatOptions):  | 
 | 60 | +        """Heartbeat worker constructor.  | 
 | 61 | +
  | 
 | 62 | +        Args:  | 
 | 63 | +            options: Parameter group - polling interval, step id, etc.  | 
 | 64 | +        """  | 
 | 65 | +        self.options = options  | 
 | 66 | + | 
 | 67 | +        self._thread: threading.Thread | None = None  | 
 | 68 | +        self._running: bool = False  | 
 | 69 | +        self._terminated: bool = (  | 
 | 70 | +            False  # one-shot guard to avoid repeated interrupts  | 
 | 71 | +        )  | 
 | 72 | + | 
 | 73 | +    # properties  | 
 | 74 | + | 
 | 75 | +    @property  | 
 | 76 | +    def interval(self) -> int:  | 
 | 77 | +        """Property function for heartbeat interval.  | 
 | 78 | +
  | 
 | 79 | +        Returns:  | 
 | 80 | +            The heartbeat polling interval value.  | 
 | 81 | +        """  | 
 | 82 | +        return self.options.interval  | 
 | 83 | + | 
 | 84 | +    @property  | 
 | 85 | +    def name(self) -> str:  | 
 | 86 | +        """Property function for heartbeat worker name.  | 
 | 87 | +
  | 
 | 88 | +        Returns:  | 
 | 89 | +            The name of the heartbeat worker.  | 
 | 90 | +        """  | 
 | 91 | +        return str(self.options.name)  | 
 | 92 | + | 
 | 93 | +    @property  | 
 | 94 | +    def step_id(self) -> UUID:  | 
 | 95 | +        """Property function for heartbeat worker step ID.  | 
 | 96 | +
  | 
 | 97 | +        Returns:  | 
 | 98 | +            The id of the step heartbeat is running for.  | 
 | 99 | +        """  | 
 | 100 | +        return self.options.step_id  | 
 | 101 | + | 
 | 102 | +    # public functions  | 
 | 103 | + | 
 | 104 | +    def start(self) -> None:  | 
 | 105 | +        """Start the heartbeat worker on a background thread."""  | 
 | 106 | +        if self._thread and self._thread.is_alive():  | 
 | 107 | +            logger.info("%s already running; start() is a no-op", self.name)  | 
 | 108 | +            return  | 
 | 109 | + | 
 | 110 | +        self._running = True  | 
 | 111 | +        self._terminated = False  | 
 | 112 | +        self._thread = threading.Thread(  | 
 | 113 | +            target=self._run, name=self.name, daemon=True  | 
 | 114 | +        )  | 
 | 115 | +        self._thread.start()  | 
 | 116 | +        logger.info(  | 
 | 117 | +            "Daemon thread %s started (interval=%s)", self.name, self.interval  | 
 | 118 | +        )  | 
 | 119 | + | 
 | 120 | +    def stop(self) -> None:  | 
 | 121 | +        """Stops the heartbeat worker."""  | 
 | 122 | +        if not self._running:  | 
 | 123 | +            return  | 
 | 124 | +        self._running = False  | 
 | 125 | +        logger.info("%s stop requested", self.name)  | 
 | 126 | + | 
 | 127 | +    def is_alive(self) -> bool:  | 
 | 128 | +        """Liveness of the heartbeat worker thread.  | 
 | 129 | +
  | 
 | 130 | +        Returns:  | 
 | 131 | +            True if the heartbeat worker thread is alive, False otherwise.  | 
 | 132 | +        """  | 
 | 133 | +        t = self._thread  | 
 | 134 | +        return bool(t and t.is_alive())  | 
 | 135 | + | 
 | 136 | +    def _run(self) -> None:  | 
 | 137 | +        logger.info("%s run() loop entered", self.name)  | 
 | 138 | +        try:  | 
 | 139 | +            while self._running:  | 
 | 140 | +                try:  | 
 | 141 | +                    self._heartbeat()  | 
 | 142 | +                except StepHeartBeatTerminationException:  | 
 | 143 | +                    # One-shot: signal the main thread and stop the loop.  | 
 | 144 | +                    if not self._terminated:  | 
 | 145 | +                        self._terminated = True  | 
 | 146 | +                        logger.info(  | 
 | 147 | +                            "%s received HeartBeatTerminationException; "  | 
 | 148 | +                            "interrupting main thread",  | 
 | 149 | +                            self.name,  | 
 | 150 | +                        )  | 
 | 151 | +                        _thread.interrupt_main()  # raises KeyboardInterrupt in main thread  | 
 | 152 | +                    # Ensure we stop our own loop as well.  | 
 | 153 | +                    self._running = False  | 
 | 154 | +                except Exception:  | 
 | 155 | +                    # Log-and-continue policy for all other errors.  | 
 | 156 | +                    logger.exception(  | 
 | 157 | +                        "%s heartbeat() failed; continuing", self.name  | 
 | 158 | +                    )  | 
 | 159 | +                # Sleep after each attempt (even after errors, unless stopped).  | 
 | 160 | +                if self._running:  | 
 | 161 | +                    time.sleep(self.interval)  | 
 | 162 | +        finally:  | 
 | 163 | +            logger.info("%s run() loop exiting", self.name)  | 
 | 164 | + | 
 | 165 | +    def _heartbeat(self) -> None:  | 
 | 166 | +        from zenml.config.global_config import GlobalConfiguration  | 
 | 167 | + | 
 | 168 | +        store = GlobalConfiguration().zen_store  | 
 | 169 | + | 
 | 170 | +        response = store.update_step_heartbeat(step_run_id=self.step_id)  | 
 | 171 | + | 
 | 172 | +        if response.status in {  | 
 | 173 | +            ExecutionStatus.STOPPED,  | 
 | 174 | +            ExecutionStatus.STOPPING,  | 
 | 175 | +        }:  | 
 | 176 | +            raise StepHeartBeatTerminationException(  | 
 | 177 | +                f"Step {self.step_id} remotely stopped with status {response.status}."  | 
 | 178 | +            )  | 
0 commit comments