|
| 1 | +import asyncio |
| 2 | +import dataclasses |
| 3 | +from dataclasses import dataclass |
| 4 | +from datetime import timedelta |
| 5 | +from typing import Dict, List, Optional, Set |
| 6 | + |
| 7 | +from temporalio import workflow |
| 8 | +from temporalio.common import RetryPolicy |
| 9 | +from temporalio.exceptions import ApplicationError |
| 10 | + |
| 11 | +from updates_and_signals.safe_message_handlers.activities import ( |
| 12 | + AssignNodesToJobInput, |
| 13 | + FindBadNodesInput, |
| 14 | + UnassignNodesForJobInput, |
| 15 | + assign_nodes_to_job, |
| 16 | + find_bad_nodes, |
| 17 | + unassign_nodes_for_job, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +# In workflows that continue-as-new, it's convenient to store all your state in one serializable structure |
| 22 | +# to make it easier to pass between runs |
| 23 | +@dataclass |
| 24 | +class ClusterManagerState: |
| 25 | + cluster_started: bool = False |
| 26 | + cluster_shutdown: bool = False |
| 27 | + nodes: Dict[str, Optional[str]] = dataclasses.field(default_factory=dict) |
| 28 | + jobs_assigned: Set[str] = dataclasses.field(default_factory=set) |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class ClusterManagerInput: |
| 33 | + state: Optional[ClusterManagerState] = None |
| 34 | + test_continue_as_new: bool = False |
| 35 | + |
| 36 | + |
| 37 | +@dataclass |
| 38 | +class ClusterManagerResult: |
| 39 | + num_currently_assigned_nodes: int |
| 40 | + num_bad_nodes: int |
| 41 | + |
| 42 | + |
| 43 | +# Be in the habit of storing message inputs and outputs in serializable structures. |
| 44 | +# This makes it easier to add more over time in a backward-compatible way. |
| 45 | +@dataclass |
| 46 | +class ClusterManagerAssignNodesToJobInput: |
| 47 | + # If larger or smaller than previous amounts, will resize the job. |
| 48 | + total_num_nodes: int |
| 49 | + job_name: str |
| 50 | + |
| 51 | + |
| 52 | +@dataclass |
| 53 | +class ClusterManagerDeleteJobInput: |
| 54 | + job_name: str |
| 55 | + |
| 56 | + |
| 57 | +@dataclass |
| 58 | +class ClusterManagerAssignNodesToJobResult: |
| 59 | + nodes_assigned: Set[str] |
| 60 | + |
| 61 | + |
| 62 | +# ClusterManagerWorkflow keeps track of the assignments of a cluster of nodes. |
| 63 | +# Via signals, the cluster can be started and shutdown. |
| 64 | +# Via updates, clients can also assign jobs to nodes and delete jobs. |
| 65 | +# These updates must run atomically. |
| 66 | +@workflow.defn |
| 67 | +class ClusterManagerWorkflow: |
| 68 | + def __init__(self) -> None: |
| 69 | + self.state = ClusterManagerState() |
| 70 | + # Protects workflow state from interleaved access |
| 71 | + self.nodes_lock = asyncio.Lock() |
| 72 | + self.max_history_length: Optional[int] = None |
| 73 | + self.sleep_interval_seconds: int = 600 |
| 74 | + |
| 75 | + @workflow.signal |
| 76 | + async def start_cluster(self) -> None: |
| 77 | + self.state.cluster_started = True |
| 78 | + self.state.nodes = {str(k): None for k in range(25)} |
| 79 | + workflow.logger.info("Cluster started") |
| 80 | + |
| 81 | + @workflow.signal |
| 82 | + async def shutdown_cluster(self) -> None: |
| 83 | + await workflow.wait_condition(lambda: self.state.cluster_started) |
| 84 | + self.state.cluster_shutdown = True |
| 85 | + workflow.logger.info("Cluster shut down") |
| 86 | + |
| 87 | + # This is an update as opposed to a signal because the client may want to wait for nodes to be allocated |
| 88 | + # before sending work to those nodes. |
| 89 | + # Returns the list of node names that were allocated to the job. |
| 90 | + @workflow.update |
| 91 | + async def assign_nodes_to_job( |
| 92 | + self, input: ClusterManagerAssignNodesToJobInput |
| 93 | + ) -> ClusterManagerAssignNodesToJobResult: |
| 94 | + await workflow.wait_condition(lambda: self.state.cluster_started) |
| 95 | + if self.state.cluster_shutdown: |
| 96 | + # If you want the client to receive a failure, either add an update validator and throw the |
| 97 | + # exception from there, or raise an ApplicationError. Other exceptions in the main handler |
| 98 | + # will cause the workflow to keep retrying and get it stuck. |
| 99 | + raise ApplicationError( |
| 100 | + "Cannot assign nodes to a job: Cluster is already shut down" |
| 101 | + ) |
| 102 | + |
| 103 | + async with self.nodes_lock: |
| 104 | + # Idempotency guard. |
| 105 | + if input.job_name in self.state.jobs_assigned: |
| 106 | + return ClusterManagerAssignNodesToJobResult( |
| 107 | + self.get_assigned_nodes(job_name=input.job_name) |
| 108 | + ) |
| 109 | + unassigned_nodes = self.get_unassigned_nodes() |
| 110 | + if len(unassigned_nodes) < input.total_num_nodes: |
| 111 | + # If you want the client to receive a failure, either add an update validator and throw the |
| 112 | + # exception from there, or raise an ApplicationError. Other exceptions in the main handler |
| 113 | + # will cause the workflow to keep retrying and get it stuck. |
| 114 | + raise ApplicationError( |
| 115 | + f"Cannot assign {input.total_num_nodes} nodes; have only {len(unassigned_nodes)} available" |
| 116 | + ) |
| 117 | + nodes_to_assign = unassigned_nodes[: input.total_num_nodes] |
| 118 | + # This await would be dangerous without nodes_lock because it yields control and allows interleaving |
| 119 | + # with delete_job and perform_health_checks, which both touch self.state.nodes. |
| 120 | + await self._assign_nodes_to_job(nodes_to_assign, input.job_name) |
| 121 | + return ClusterManagerAssignNodesToJobResult( |
| 122 | + nodes_assigned=self.get_assigned_nodes(job_name=input.job_name) |
| 123 | + ) |
| 124 | + |
| 125 | + async def _assign_nodes_to_job( |
| 126 | + self, assigned_nodes: List[str], job_name: str |
| 127 | + ) -> None: |
| 128 | + await workflow.execute_activity( |
| 129 | + assign_nodes_to_job, |
| 130 | + AssignNodesToJobInput(nodes=assigned_nodes, job_name=job_name), |
| 131 | + start_to_close_timeout=timedelta(seconds=10), |
| 132 | + ) |
| 133 | + for node in assigned_nodes: |
| 134 | + self.state.nodes[node] = job_name |
| 135 | + self.state.jobs_assigned.add(job_name) |
| 136 | + |
| 137 | + # Even though it returns nothing, this is an update because the client may want to track it, for example |
| 138 | + # to wait for nodes to be unassignd before reassigning them. |
| 139 | + @workflow.update |
| 140 | + async def delete_job(self, input: ClusterManagerDeleteJobInput) -> None: |
| 141 | + await workflow.wait_condition(lambda: self.state.cluster_started) |
| 142 | + if self.state.cluster_shutdown: |
| 143 | + # If you want the client to receive a failure, either add an update validator and throw the |
| 144 | + # exception from there, or raise an ApplicationError. Other exceptions in the main handler |
| 145 | + # will cause the workflow to keep retrying and get it stuck. |
| 146 | + raise ApplicationError("Cannot delete a job: Cluster is already shut down") |
| 147 | + |
| 148 | + async with self.nodes_lock: |
| 149 | + nodes_to_unassign = [ |
| 150 | + k for k, v in self.state.nodes.items() if v == input.job_name |
| 151 | + ] |
| 152 | + # This await would be dangerous without nodes_lock because it yields control and allows interleaving |
| 153 | + # with assign_nodes_to_job and perform_health_checks, which all touch self.state.nodes. |
| 154 | + await self._unassign_nodes_for_job(nodes_to_unassign, input.job_name) |
| 155 | + |
| 156 | + async def _unassign_nodes_for_job( |
| 157 | + self, nodes_to_unassign: List[str], job_name: str |
| 158 | + ): |
| 159 | + await workflow.execute_activity( |
| 160 | + unassign_nodes_for_job, |
| 161 | + UnassignNodesForJobInput(nodes=nodes_to_unassign, job_name=job_name), |
| 162 | + start_to_close_timeout=timedelta(seconds=10), |
| 163 | + ) |
| 164 | + for node in nodes_to_unassign: |
| 165 | + self.state.nodes[node] = None |
| 166 | + |
| 167 | + def get_unassigned_nodes(self) -> List[str]: |
| 168 | + return [k for k, v in self.state.nodes.items() if v is None] |
| 169 | + |
| 170 | + def get_bad_nodes(self) -> Set[str]: |
| 171 | + return set([k for k, v in self.state.nodes.items() if v == "BAD!"]) |
| 172 | + |
| 173 | + def get_assigned_nodes(self, *, job_name: Optional[str] = None) -> Set[str]: |
| 174 | + if job_name: |
| 175 | + return set([k for k, v in self.state.nodes.items() if v == job_name]) |
| 176 | + else: |
| 177 | + return set( |
| 178 | + [ |
| 179 | + k |
| 180 | + for k, v in self.state.nodes.items() |
| 181 | + if v is not None and v != "BAD!" |
| 182 | + ] |
| 183 | + ) |
| 184 | + |
| 185 | + async def perform_health_checks(self) -> None: |
| 186 | + async with self.nodes_lock: |
| 187 | + assigned_nodes = self.get_assigned_nodes() |
| 188 | + try: |
| 189 | + # This await would be dangerous without nodes_lock because it yields control and allows interleaving |
| 190 | + # with assign_nodes_to_job and delete_job, which both touch self.state.nodes. |
| 191 | + bad_nodes = await workflow.execute_activity( |
| 192 | + find_bad_nodes, |
| 193 | + FindBadNodesInput(nodes_to_check=assigned_nodes), |
| 194 | + start_to_close_timeout=timedelta(seconds=10), |
| 195 | + # This health check is optional, and our lock would block the whole workflow if we let it retry forever. |
| 196 | + retry_policy=RetryPolicy(maximum_attempts=1), |
| 197 | + ) |
| 198 | + for node in bad_nodes: |
| 199 | + self.state.nodes[node] = "BAD!" |
| 200 | + except Exception as e: |
| 201 | + workflow.logger.warn( |
| 202 | + f"Health check failed with error {type(e).__name__}:{e}" |
| 203 | + ) |
| 204 | + |
| 205 | + # The cluster manager is a long-running "entity" workflow so we need to periodically checkpoint its state and |
| 206 | + # continue-as-new. |
| 207 | + def init(self, input: ClusterManagerInput) -> None: |
| 208 | + if input.state: |
| 209 | + self.state = input.state |
| 210 | + if input.test_continue_as_new: |
| 211 | + self.max_history_length = 120 |
| 212 | + self.sleep_interval_seconds = 1 |
| 213 | + |
| 214 | + def should_continue_as_new(self) -> bool: |
| 215 | + # We don't want to continue-as-new if we're in the middle of an update |
| 216 | + if self.nodes_lock.locked(): |
| 217 | + return False |
| 218 | + if workflow.info().is_continue_as_new_suggested(): |
| 219 | + return True |
| 220 | + # This is just for ease-of-testing. In production, we trust temporal to tell us when to continue as new. |
| 221 | + if ( |
| 222 | + self.max_history_length |
| 223 | + and workflow.info().get_current_history_length() > self.max_history_length |
| 224 | + ): |
| 225 | + return True |
| 226 | + return False |
| 227 | + |
| 228 | + @workflow.run |
| 229 | + async def run(self, input: ClusterManagerInput) -> ClusterManagerResult: |
| 230 | + self.init(input) |
| 231 | + await workflow.wait_condition(lambda: self.state.cluster_started) |
| 232 | + # Perform health checks at intervals. |
| 233 | + while True: |
| 234 | + await self.perform_health_checks() |
| 235 | + try: |
| 236 | + await workflow.wait_condition( |
| 237 | + lambda: self.state.cluster_shutdown |
| 238 | + or self.should_continue_as_new(), |
| 239 | + timeout=timedelta(seconds=self.sleep_interval_seconds), |
| 240 | + ) |
| 241 | + except asyncio.TimeoutError: |
| 242 | + pass |
| 243 | + if self.state.cluster_shutdown: |
| 244 | + break |
| 245 | + if self.should_continue_as_new(): |
| 246 | + workflow.logger.info("Continuing as new") |
| 247 | + workflow.continue_as_new( |
| 248 | + ClusterManagerInput( |
| 249 | + state=self.state, |
| 250 | + test_continue_as_new=input.test_continue_as_new, |
| 251 | + ) |
| 252 | + ) |
| 253 | + return ClusterManagerResult( |
| 254 | + len(self.get_assigned_nodes()), |
| 255 | + len(self.get_bad_nodes()), |
| 256 | + ) |
0 commit comments