- 
                Notifications
    
You must be signed in to change notification settings  - Fork 551
 
Feature:3963 Step HeartBeat components #4073
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| # Copyright (c) ZenML GmbH 2022. All Rights Reserved. | ||
| # | ||
| # Licensed 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: | ||
| # | ||
| # https://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. | ||
| """ZenML Step HeartBeat functionality.""" | ||
| 
     | 
||
| import _thread | ||
| import logging | ||
| import threading | ||
| import time | ||
| from uuid import UUID | ||
| 
     | 
||
| from zenml.enums import ExecutionStatus | ||
| 
     | 
||
| logger = logging.getLogger(__name__) | ||
| 
     | 
||
| 
     | 
||
| class StepHeartBeatTerminationException(Exception): | ||
| """Custom exception class for heartbeat termination.""" | ||
| 
     | 
||
| pass | ||
| 
     | 
||
| 
     | 
||
| class StepHeartbeatWorker: | ||
| """Worker class implementing heartbeat polling and remote termination.""" | ||
| 
     | 
||
| STEP_HEARTBEAT_INTERVAL_SECONDS = 30 | ||
| 
     | 
||
| def __init__(self, step_id: UUID): | ||
| """Heartbeat worker constructor. | ||
| Args: | ||
| options: Parameter group - polling interval, step id, etc. | ||
| """ | ||
| 
     | 
||
| self._step_id = step_id | ||
| 
     | 
||
| self._thread: threading.Thread | None = None | ||
| self._running: bool = False | ||
| self._terminated: bool = ( | ||
| False # one-shot guard to avoid repeated interrupts | ||
| ) | ||
| 
     | 
||
| # properties | ||
| 
     | 
||
| @property | ||
| def interval(self) -> int: | ||
| """Property function for heartbeat interval. | ||
| Returns: | ||
| The heartbeat polling interval value. | ||
| """ | ||
| return self.STEP_HEARTBEAT_INTERVAL_SECONDS | ||
| 
     | 
||
| @property | ||
| def name(self) -> str: | ||
| """Property function for heartbeat worker name. | ||
| Returns: | ||
| The name of the heartbeat worker. | ||
| """ | ||
| return f"HeartBeatWorker-{self.step_id}" | ||
| 
     | 
||
| @property | ||
| def step_id(self) -> UUID: | ||
| """Property function for heartbeat worker step ID. | ||
| Returns: | ||
| The id of the step heartbeat is running for. | ||
| """ | ||
| return self.step_id | ||
| 
     | 
||
| # public functions | ||
| 
     | 
||
| def start(self) -> None: | ||
| """Start the heartbeat worker on a background thread.""" | ||
| if self._thread and self._thread.is_alive(): | ||
| logger.info("%s already running; start() is a no-op", self.name) | ||
| return | ||
| 
     | 
||
| self._running = True | ||
| self._terminated = False | ||
| self._thread = threading.Thread( | ||
| target=self._run, name=self.name, daemon=True | ||
| ) | ||
| self._thread.start() | ||
| logger.info( | ||
| "Daemon thread %s started (interval=%s)", self.name, self.interval | ||
| ) | ||
| 
     | 
||
| def stop(self) -> None: | ||
| """Stops the heartbeat worker.""" | ||
| if not self._running: | ||
| return | ||
| self._running = False | ||
| logger.info("%s stop requested", self.name) | ||
| 
     | 
||
| def is_alive(self) -> bool: | ||
| """Liveness of the heartbeat worker thread. | ||
| Returns: | ||
| True if the heartbeat worker thread is alive, False otherwise. | ||
| """ | ||
| t = self._thread | ||
| return bool(t and t.is_alive()) | ||
| 
     | 
||
| def _run(self) -> None: | ||
| logger.info("%s run() loop entered", self.name) | ||
| try: | ||
| while self._running: | ||
| try: | ||
| self._heartbeat() | ||
| except StepHeartBeatTerminationException: | ||
| # One-shot: signal the main thread and stop the loop. | ||
| if not self._terminated: | ||
| self._terminated = True | ||
| logger.info( | ||
| "%s received HeartBeatTerminationException; " | ||
| "interrupting main thread", | ||
| self.name, | ||
| ) | ||
| _thread.interrupt_main() # raises KeyboardInterrupt in main thread | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. My dynamic pipelines PR introduces running multiple steps in different threads, which doesn't work with this I think. Can we somehow store the thread from which the heartbeat worker was started, and then interrupt that thread instead of the main one? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah that is an important change, good point. interrupt_main will not work here, we will need to change the pattern a bit. Should I work my changes from your branch?  | 
||
| # Ensure we stop our own loop as well. | ||
| self._running = False | ||
| except Exception: | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: Improve this. For sure try to capture HTTP errors in more verbose logs to avoid excessive log generation if the error is for instance server raising 500 status code.  | 
||
| # Log-and-continue policy for all other errors. | ||
| logger.exception( | ||
| "%s heartbeat() failed; continuing", self.name | ||
| ) | ||
| # Sleep after each attempt (even after errors, unless stopped). | ||
| if self._running: | ||
| time.sleep(self.interval) | ||
| finally: | ||
| logger.info("%s run() loop exiting", self.name) | ||
| 
     | 
||
| def _heartbeat(self) -> None: | ||
| from zenml.config.global_config import GlobalConfiguration | ||
| 
     | 
||
| store = GlobalConfiguration().zen_store | ||
| 
     | 
||
| response = store.update_step_heartbeat(step_run_id=self.step_id) | ||
| 
     | 
||
| if response.status in { | ||
| ExecutionStatus.STOPPED, | ||
| ExecutionStatus.STOPPING, | ||
| }: | ||
| raise StepHeartBeatTerminationException( | ||
| f"Step {self.step_id} remotely stopped with status {response.status}." | ||
| ) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should probably be of type
ExecutionStatus?