-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdistributed_executor.py
More file actions
189 lines (158 loc) · 7.68 KB
/
distributed_executor.py
File metadata and controls
189 lines (158 loc) · 7.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""Distributed execution dispatcher with optional distributed compute backends."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
import logging
from backend.config import settings
from backend.core.executor import PipelineExecutor
from backend.models.pipeline import Execution, Pipeline
logger = logging.getLogger(__name__)
SUPPORTED_BACKENDS = {"local", "celery", "ray", "spark", "dask"}
@dataclass
class DispatchResult:
"""Result wrapper for execution dispatch metadata."""
execution: Execution
backend_used: str
class DistributedExecutionDispatcher:
"""Run pipeline execution on local runtime or distributed frameworks."""
def __init__(self):
self.executor = PipelineExecutor()
def run(self, pipeline: Pipeline, backend_override: Optional[str] = None) -> DispatchResult:
backend = (backend_override or settings.DISTRIBUTED_EXECUTION_BACKEND or "local").lower().strip()
if backend not in SUPPORTED_BACKENDS:
logger.warning("Unsupported backend '%s'. Falling back to local.", backend)
backend = "local"
if backend == "celery":
execution, used_backend = self._execute_with_celery(pipeline)
return DispatchResult(execution=execution, backend_used=used_backend)
if backend == "ray":
execution, used_backend = self._execute_with_ray(pipeline)
return DispatchResult(execution=execution, backend_used=used_backend)
if backend == "spark":
execution, used_backend = self._execute_with_spark(pipeline)
return DispatchResult(execution=execution, backend_used=used_backend)
if backend == "dask":
execution, used_backend = self._execute_with_dask(pipeline)
return DispatchResult(execution=execution, backend_used=used_backend)
execution = self.executor.execute(pipeline)
return DispatchResult(execution=execution, backend_used="local")
def _execute_with_celery(self, pipeline: Pipeline) -> tuple[Execution, str]:
"""Try Celery path; fallback to local execution when unavailable."""
try:
from celery import Celery
app = Celery(
"flexiroaster",
broker=settings.CELERY_BROKER_URL,
backend=settings.CELERY_RESULT_BACKEND,
)
task_name = settings.CELERY_EXECUTION_TASK
payload = pipeline.model_dump(mode="json")
async_result = app.send_task(task_name, kwargs={"pipeline": payload})
remote_output = async_result.get(timeout=600)
execution = Execution.model_validate(remote_output)
logger.info("Pipeline %s executed via Celery task %s", pipeline.id, task_name)
return execution, "celery"
except Exception as exc:
logger.warning("Celery backend unavailable (%s). Executing locally.", exc)
execution = self.executor.execute(pipeline)
execution.context.setdefault("distributed_execution", {})
execution.context["distributed_execution"].update(
{
"requested_backend": "celery",
"fallback_backend": "local",
"fallback_reason": str(exc),
}
)
return execution, "local"
def _execute_with_ray(self, pipeline: Pipeline) -> tuple[Execution, str]:
"""Try Ray path; fallback to local execution when unavailable."""
try:
import ray
if not ray.is_initialized():
ray.init(address=settings.RAY_ADDRESS, namespace=settings.RAY_NAMESPACE, ignore_reinit_error=True)
@ray.remote
def execute_pipeline_remote(pipeline_payload: dict):
from backend.core.executor import PipelineExecutor
from backend.models.pipeline import Pipeline
model = Pipeline.model_validate(pipeline_payload)
result = PipelineExecutor().execute(model)
return result.model_dump(mode="json")
payload = pipeline.model_dump(mode="json")
remote_ref = execute_pipeline_remote.remote(payload)
remote_output = ray.get(remote_ref)
execution = Execution.model_validate(remote_output)
logger.info("Pipeline %s executed via Ray remote function", pipeline.id)
return execution, "ray"
except Exception as exc:
logger.warning("Ray backend unavailable (%s). Executing locally.", exc)
execution = self.executor.execute(pipeline)
execution.context.setdefault("distributed_execution", {})
execution.context["distributed_execution"].update(
{
"requested_backend": "ray",
"fallback_backend": "local",
"fallback_reason": str(exc),
}
)
return execution, "local"
def _execute_with_spark(self, pipeline: Pipeline) -> tuple[Execution, str]:
"""Try Spark path; fallback to local execution when unavailable."""
try:
from pyspark.sql import SparkSession
spark = (
SparkSession.builder
.master(settings.SPARK_MASTER_URL)
.appName(settings.SPARK_APP_NAME)
.getOrCreate()
)
logger.info("Spark backend initialized for pipeline %s", pipeline.id)
spark.stop()
execution = self.executor.execute(pipeline)
execution.context.setdefault("distributed_execution", {})
execution.context["distributed_execution"].update(
{
"requested_backend": "spark",
"execution_mode": "spark-driver",
}
)
return execution, "spark"
except Exception as exc:
logger.warning("Spark backend unavailable (%s). Executing locally.", exc)
execution = self.executor.execute(pipeline)
execution.context.setdefault("distributed_execution", {})
execution.context["distributed_execution"].update(
{
"requested_backend": "spark",
"fallback_backend": "local",
"fallback_reason": str(exc),
}
)
return execution, "local"
def _execute_with_dask(self, pipeline: Pipeline) -> tuple[Execution, str]:
"""Try Dask path; fallback to local execution when unavailable."""
try:
from dask.distributed import Client
client = Client(settings.DASK_SCHEDULER_ADDRESS) if settings.DASK_SCHEDULER_ADDRESS else Client(processes=False)
logger.info("Dask backend initialized for pipeline %s", pipeline.id)
client.close()
execution = self.executor.execute(pipeline)
execution.context.setdefault("distributed_execution", {})
execution.context["distributed_execution"].update(
{
"requested_backend": "dask",
"execution_mode": "dask-local-cluster",
}
)
return execution, "dask"
except Exception as exc:
logger.warning("Dask backend unavailable (%s). Executing locally.", exc)
execution = self.executor.execute(pipeline)
execution.context.setdefault("distributed_execution", {})
execution.context["distributed_execution"].update(
{
"requested_backend": "dask",
"fallback_backend": "local",
"fallback_reason": str(exc),
}
)
return execution, "local"