-
Notifications
You must be signed in to change notification settings - Fork 126
/
utils.py
289 lines (241 loc) · 10 KB
/
utils.py
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import asyncio
import logging
import os
import time
from airflow.exceptions import AirflowException
from typing import List, Optional, Tuple
from enum import Enum
from armada.operators.jobservice import JobServiceClient
from armada.operators.jobservice_asyncio import JobServiceAsyncIOClient
from armada.jobservice import jobservice_pb2
from armada_client.armada import submit_pb2
class JobState(Enum):
SUBMITTED = 0
DUPLICATE_FOUND = 1
RUNNING = 2
FAILED = 3
SUCCEEDED = 4
CANCELLED = 5
JOB_ID_NOT_FOUND = 6
CONNECTION_ERR = 7
_pb_to_job_state = {
jobservice_pb2.JobServiceResponse.SUBMITTED: JobState.SUBMITTED,
jobservice_pb2.JobServiceResponse.DUPLICATE_FOUND: JobState.DUPLICATE_FOUND,
jobservice_pb2.JobServiceResponse.RUNNING: JobState.RUNNING,
jobservice_pb2.JobServiceResponse.FAILED: JobState.FAILED,
jobservice_pb2.JobServiceResponse.SUCCEEDED: JobState.SUCCEEDED,
jobservice_pb2.JobServiceResponse.CANCELLED: JobState.CANCELLED,
jobservice_pb2.JobServiceResponse.JOB_ID_NOT_FOUND: JobState.JOB_ID_NOT_FOUND,
# NOTE(Clif): For whatever reason CONNECTION_ERR is not present in the
# generated protobuf.
7: JobState.CONNECTION_ERR,
}
def job_state_from_pb(state) -> JobState:
return _pb_to_job_state[state]
def airflow_error(job_state: JobState, name: str, job_id: str):
"""Throw an error on a terminal event if job errored out
:param job_state: A JobState enum class
:param name: The name of your armada job
:param job_id: The job id that armada assigns to it
:return: No Return or an AirflowFailException.
AirflowFailException tells Airflow Schedule to not reschedule the task
"""
if job_state == JobState.SUCCEEDED:
return
if (
job_state == JobState.FAILED
or job_state == JobState.CANCELLED
or job_state == JobState.JOB_ID_NOT_FOUND
):
job_message = job_state.name
# AirflowException allows operator-level retries. AirflowFailException
# does *not*.
raise AirflowException(f"The Armada job {name}:{job_id} {job_message}")
def default_job_status_callable(
armada_queue: str,
job_set_id: str,
job_id: str,
job_service_client: JobServiceClient,
) -> jobservice_pb2.JobServiceResponse:
return job_service_client.get_job_status(
queue=armada_queue, job_id=job_id, job_set_id=job_set_id
)
armada_logger = logging.getLogger("airflow.task")
def search_for_job_complete(
armada_queue: str,
job_set_id: str,
airflow_task_name: str,
job_id: str,
poll_interval: int = 30,
job_service_client: Optional[JobServiceClient] = None,
job_status_callable=default_job_status_callable,
time_out_for_failure: int = 7200,
) -> Tuple[JobState, str]:
"""
Poll JobService cache until you get a terminated event.
A terminated event is SUCCEEDED, FAILED or CANCELLED
:param armada_queue: The queue for armada
:param job_set_id: Your job_set_id
:param airflow_task_name: The name of your armada job
:param poll_interval: Polling interval for jobservice to get status.
:param job_id: The name of the job id that armada assigns to it
:param job_service_client: A JobServiceClient that is used for polling.
It is optional only for testing
:param job_status_callable: A callable object for test injection.
:param time_out_for_failure: The amount of time a job
can be in job_id_not_found
before we decide it was a invalid job
:return: A tuple of JobStateEnum, message
"""
start_time = time.time()
# Overwrite time_out_for_failure by environment variable for configuration
armada_time_out_env = os.getenv("ARMADA_AIRFLOW_TIME_OUT_JOB_ID")
if armada_time_out_env:
time_out_for_failure = int(armada_time_out_env)
while True:
# The else statement is for testing purposes.
# We want to allow a test callable to be passed
if job_service_client:
job_status_return = job_status_callable(
armada_queue=armada_queue,
job_id=job_id,
job_set_id=job_set_id,
job_service_client=job_service_client,
)
else:
job_status_return = job_status_callable(
armada_queue=armada_queue, job_id=job_id, job_set_id=job_set_id
)
job_state = job_state_from_pb(job_status_return.state)
armada_logger.debug(f"Got job state '{job_state.name}' for job {job_id}")
time.sleep(poll_interval)
if job_state == JobState.SUCCEEDED:
job_message = f"Armada {airflow_task_name}:{job_id} succeeded"
break
if job_state == JobState.FAILED:
job_message = (
f"Armada {airflow_task_name}:{job_id} failed\n"
f"failed with reason {job_status_return.error}"
)
break
if job_state == JobState.CANCELLED:
job_message = f"Armada {airflow_task_name}:{job_id} cancelled"
break
if job_state == JobState.CONNECTION_ERR:
log_messages = (
f"Armada {airflow_task_name}:{job_id} connection error (will retry)"
f"failed with reason {job_status_return.error}"
)
armada_logger.warning(log_messages)
continue
if job_state == JobState.JOB_ID_NOT_FOUND:
end_time = time.time()
time_elasped = int(end_time) - int(start_time)
if time_elasped > time_out_for_failure:
job_state = JobState.JOB_ID_NOT_FOUND
job_message = (
f"Armada {airflow_task_name}:{job_id} could not find a job id and\n"
f"hit a timeout"
)
break
return job_state, job_message
def annotate_job_request_items(
context, job_request_items: List[submit_pb2.JobSubmitRequestItem]
) -> List[submit_pb2.JobSubmitRequestItem]:
"""
Annotates the inbound job request items with Airflow context elements
:param context: The airflow context.
:param job_request_items: The job request items to be sent to armada
:return: annotated job request items for armada
"""
task_instance = context["ti"]
task_id = task_instance.task_id
run_id = context["run_id"]
dag_id = context["dag"].dag_id
for item in job_request_items:
item.annotations[get_annotation_key_prefix() + "taskId"] = task_id
item.annotations[get_annotation_key_prefix() + "taskRunId"] = run_id
item.annotations[get_annotation_key_prefix() + "dagId"] = dag_id
return job_request_items
ANNOTATION_KEY_PREFIX = "armadaproject.io/"
def get_annotation_key_prefix() -> str:
"""
Provides the annotation key prefix,
which can be specified in env var ANNOTATION_KEY_PREFIX.
A default is provided if the env var is not defined
:return: string annotation key prefix
"""
env_var_name = "ANNOTATION_KEY_PREFIX"
if env_var_name in os.environ:
return f"{os.environ.get(env_var_name)}"
else:
return ANNOTATION_KEY_PREFIX
async def search_for_job_complete_async(
armada_queue: str,
job_set_id: str,
airflow_task_name: str,
job_id: str,
job_service_client: JobServiceAsyncIOClient,
log,
poll_interval: int,
time_out_for_failure: int = 7200,
) -> Tuple[JobState, str]:
"""
Poll JobService cache asyncronously until you get a terminated event.
A terminated event is SUCCEEDED, FAILED or CANCELLED
:param armada_queue: The queue for armada
:param job_set_id: Your job_set_id
:param airflow_task_name: The name of your armada job
:param job_id: The name of the job id that armada assigns to it
:param job_service_client: A JobServiceClient that is used for polling.
It is optional only for testing
:param poll_interval: How often to poll jobservice to get status.
:param time_out_for_failure: The amount of time a job
can be in job_id_not_found
before we decide it was a invalid job
:return: A tuple of JobStateEnum, message
"""
start_time = time.time()
# Overwrite time_out_for_failure by environment variable for configuration
armada_time_out_env = os.getenv("ARMADA_AIRFLOW_TIME_OUT_JOB_ID")
if armada_time_out_env:
time_out_for_failure = int(armada_time_out_env)
while True:
job_status_return = await job_service_client.get_job_status(
queue=armada_queue,
job_id=job_id,
job_set_id=job_set_id,
)
job_state = job_state_from_pb(job_status_return.state)
log.debug(f"Got job state '{job_state.name}' for job {job_id}")
await asyncio.sleep(poll_interval)
if job_state == JobState.SUCCEEDED:
job_message = f"Armada {airflow_task_name}:{job_id} succeeded"
break
if job_state == JobState.FAILED:
job_message = (
f"Armada {airflow_task_name}:{job_id} failed\n"
f"failed with reason {job_status_return.error}"
)
break
if job_state == JobState.CANCELLED:
job_message = f"Armada {airflow_task_name}:{job_id} cancelled"
break
if job_state == JobState.CONNECTION_ERR:
log_messages = (
f"Armada {airflow_task_name}:{job_id} connection error (will retry)"
f"failed with reason {job_status_return.error}"
)
log.warning(log_messages)
continue
if job_state == JobState.JOB_ID_NOT_FOUND:
end_time = time.time()
time_elasped = int(end_time) - int(start_time)
if time_elasped > time_out_for_failure:
job_state = JobState.JOB_ID_NOT_FOUND
job_message = (
f"Armada {airflow_task_name}:{job_id} could not find a job id and\n"
f"hit a timeout"
)
break
return job_state, job_message