-
Notifications
You must be signed in to change notification settings - Fork 13.7k
/
dataflow.py
644 lines (579 loc) · 28 KB
/
dataflow.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# http://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.
from __future__ import annotations
import asyncio
from functools import cached_property
from typing import TYPE_CHECKING, Any, Sequence
from google.cloud.dataflow_v1beta3 import JobState
from google.cloud.dataflow_v1beta3.types import (
AutoscalingEvent,
JobMessage,
JobMetrics,
MetricUpdate,
)
from airflow.providers.google.cloud.hooks.dataflow import AsyncDataflowHook, DataflowJobStatus
from airflow.triggers.base import BaseTrigger, TriggerEvent
if TYPE_CHECKING:
from google.cloud.dataflow_v1beta3.services.messages_v1_beta3.pagers import ListJobMessagesAsyncPager
DEFAULT_DATAFLOW_LOCATION = "us-central1"
class TemplateJobStartTrigger(BaseTrigger):
"""Dataflow trigger to check if templated job has been finished.
:param project_id: Required. the Google Cloud project ID in which the job was started.
:param job_id: Required. ID of the job.
:param location: Optional. the location where job is executed. If set to None then
the value of DEFAULT_DATAFLOW_LOCATION will be used
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional. Service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:param cancel_timeout: Optional. How long (in seconds) operator should wait for the pipeline to be
successfully cancelled when task is being killed.
"""
def __init__(
self,
job_id: str,
project_id: str | None,
location: str = DEFAULT_DATAFLOW_LOCATION,
gcp_conn_id: str = "google_cloud_default",
poll_sleep: int = 10,
impersonation_chain: str | Sequence[str] | None = None,
cancel_timeout: int | None = 5 * 60,
):
super().__init__()
self.project_id = project_id
self.job_id = job_id
self.location = location
self.gcp_conn_id = gcp_conn_id
self.poll_sleep = poll_sleep
self.impersonation_chain = impersonation_chain
self.cancel_timeout = cancel_timeout
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize class arguments and classpath."""
return (
"airflow.providers.google.cloud.triggers.dataflow.TemplateJobStartTrigger",
{
"project_id": self.project_id,
"job_id": self.job_id,
"location": self.location,
"gcp_conn_id": self.gcp_conn_id,
"poll_sleep": self.poll_sleep,
"impersonation_chain": self.impersonation_chain,
"cancel_timeout": self.cancel_timeout,
},
)
async def run(self):
"""
Fetch job status or yield certain Events.
Main loop of the class in where it is fetching the job status and yields certain Event.
If the job has status success then it yields TriggerEvent with success status, if job has
status failed - with error status. In any other case Trigger will wait for specified
amount of time stored in self.poll_sleep variable.
"""
hook = self._get_async_hook()
try:
while True:
status = await hook.get_job_status(
project_id=self.project_id,
job_id=self.job_id,
location=self.location,
)
if status == JobState.JOB_STATE_DONE:
yield TriggerEvent(
{
"job_id": self.job_id,
"status": "success",
"message": "Job completed",
}
)
return
elif status == JobState.JOB_STATE_FAILED:
yield TriggerEvent(
{
"status": "error",
"message": f"Dataflow job with id {self.job_id} has failed its execution",
}
)
return
elif status == JobState.JOB_STATE_STOPPED:
yield TriggerEvent(
{
"status": "stopped",
"message": f"Dataflow job with id {self.job_id} was stopped",
}
)
return
else:
self.log.info("Job is still running...")
self.log.info("Current job status is: %s", status.name)
self.log.info("Sleeping for %s seconds.", self.poll_sleep)
await asyncio.sleep(self.poll_sleep)
except Exception as e:
self.log.exception("Exception occurred while checking for job completion.")
yield TriggerEvent({"status": "error", "message": str(e)})
def _get_async_hook(self) -> AsyncDataflowHook:
return AsyncDataflowHook(
gcp_conn_id=self.gcp_conn_id,
poll_sleep=self.poll_sleep,
impersonation_chain=self.impersonation_chain,
cancel_timeout=self.cancel_timeout,
)
class DataflowJobStatusTrigger(BaseTrigger):
"""
Trigger that checks for metrics associated with a Dataflow job.
:param job_id: Required. ID of the job.
:param expected_statuses: The expected state(s) of the operation.
See: https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobState
:param project_id: Required. The Google Cloud project ID in which the job was started.
:param location: Optional. The location where the job is executed. If set to None then
the value of DEFAULT_DATAFLOW_LOCATION will be used.
:param gcp_conn_id: The connection ID to use for connecting to Google Cloud.
:param poll_sleep: Time (seconds) to wait between two consecutive calls to check the job.
:param impersonation_chain: Optional. Service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
def __init__(
self,
job_id: str,
expected_statuses: set[str],
project_id: str | None,
location: str = DEFAULT_DATAFLOW_LOCATION,
gcp_conn_id: str = "google_cloud_default",
poll_sleep: int = 10,
impersonation_chain: str | Sequence[str] | None = None,
):
super().__init__()
self.job_id = job_id
self.expected_statuses = expected_statuses
self.project_id = project_id
self.location = location
self.gcp_conn_id = gcp_conn_id
self.poll_sleep = poll_sleep
self.impersonation_chain = impersonation_chain
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize class arguments and classpath."""
return (
"airflow.providers.google.cloud.triggers.dataflow.DataflowJobStatusTrigger",
{
"job_id": self.job_id,
"expected_statuses": self.expected_statuses,
"project_id": self.project_id,
"location": self.location,
"gcp_conn_id": self.gcp_conn_id,
"poll_sleep": self.poll_sleep,
"impersonation_chain": self.impersonation_chain,
},
)
async def run(self):
"""
Loop until the job reaches an expected or terminal state.
Yields a TriggerEvent with success status, if the client returns an expected job status.
Yields a TriggerEvent with error status, if the client returns an unexpected terminal
job status or any exception is raised while looping.
In any other case the Trigger will wait for a specified amount of time
stored in self.poll_sleep variable.
"""
try:
while True:
job_status = await self.async_hook.get_job_status(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
if job_status.name in self.expected_statuses:
yield TriggerEvent(
{
"status": "success",
"message": f"Job with id '{self.job_id}' has reached an expected state: {job_status.name}",
}
)
return
elif job_status.name in DataflowJobStatus.TERMINAL_STATES:
yield TriggerEvent(
{
"status": "error",
"message": f"Job with id '{self.job_id}' is already in terminal state: {job_status.name}",
}
)
return
self.log.info("Sleeping for %s seconds.", self.poll_sleep)
await asyncio.sleep(self.poll_sleep)
except Exception as e:
self.log.error("Exception occurred while checking for job status!")
yield TriggerEvent(
{
"status": "error",
"message": str(e),
}
)
@cached_property
def async_hook(self) -> AsyncDataflowHook:
return AsyncDataflowHook(
gcp_conn_id=self.gcp_conn_id,
poll_sleep=self.poll_sleep,
impersonation_chain=self.impersonation_chain,
)
class DataflowJobMetricsTrigger(BaseTrigger):
"""
Trigger that checks for metrics associated with a Dataflow job.
:param job_id: Required. ID of the job.
:param project_id: Required. The Google Cloud project ID in which the job was started.
:param location: Optional. The location where the job is executed. If set to None then
the value of DEFAULT_DATAFLOW_LOCATION will be used.
:param gcp_conn_id: The connection ID to use for connecting to Google Cloud.
:param poll_sleep: Time (seconds) to wait between two consecutive calls to check the job.
:param impersonation_chain: Optional. Service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:param fail_on_terminal_state: If set to True the trigger will yield a TriggerEvent with
error status if the job reaches a terminal state.
"""
def __init__(
self,
job_id: str,
project_id: str | None,
location: str = DEFAULT_DATAFLOW_LOCATION,
gcp_conn_id: str = "google_cloud_default",
poll_sleep: int = 10,
impersonation_chain: str | Sequence[str] | None = None,
fail_on_terminal_state: bool = True,
):
super().__init__()
self.project_id = project_id
self.job_id = job_id
self.location = location
self.gcp_conn_id = gcp_conn_id
self.poll_sleep = poll_sleep
self.impersonation_chain = impersonation_chain
self.fail_on_terminal_state = fail_on_terminal_state
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize class arguments and classpath."""
return (
"airflow.providers.google.cloud.triggers.dataflow.DataflowJobMetricsTrigger",
{
"project_id": self.project_id,
"job_id": self.job_id,
"location": self.location,
"gcp_conn_id": self.gcp_conn_id,
"poll_sleep": self.poll_sleep,
"impersonation_chain": self.impersonation_chain,
"fail_on_terminal_state": self.fail_on_terminal_state,
},
)
async def run(self):
"""
Loop until a terminal job status or any job metrics are returned.
Yields a TriggerEvent with success status, if the client returns any job metrics
and fail_on_terminal_state attribute is False.
Yields a TriggerEvent with error status, if the client returns a job status with
a terminal state value and fail_on_terminal_state attribute is True.
Yields a TriggerEvent with error status, if any exception is raised while looping.
In any other case the Trigger will wait for a specified amount of time
stored in self.poll_sleep variable.
"""
try:
while True:
job_status = await self.async_hook.get_job_status(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
job_metrics = await self.get_job_metrics()
if self.fail_on_terminal_state and job_status.name in DataflowJobStatus.TERMINAL_STATES:
yield TriggerEvent(
{
"status": "error",
"message": f"Job with id '{self.job_id}' is already in terminal state: {job_status.name}",
"result": None,
}
)
return
if job_metrics:
yield TriggerEvent(
{
"status": "success",
"message": f"Detected {len(job_metrics)} metrics for job '{self.job_id}'",
"result": job_metrics,
}
)
return
self.log.info("Sleeping for %s seconds.", self.poll_sleep)
await asyncio.sleep(self.poll_sleep)
except Exception as e:
self.log.error("Exception occurred while checking for job's metrics!")
yield TriggerEvent({"status": "error", "message": str(e), "result": None})
async def get_job_metrics(self) -> list[dict[str, Any]]:
"""Wait for the Dataflow client response and then return it in a serialized list."""
job_response: JobMetrics = await self.async_hook.get_job_metrics(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
return self._get_metrics_from_job_response(job_response)
def _get_metrics_from_job_response(self, job_response: JobMetrics) -> list[dict[str, Any]]:
"""Return a list of serialized MetricUpdate objects."""
return [MetricUpdate.to_dict(metric) for metric in job_response.metrics]
@cached_property
def async_hook(self) -> AsyncDataflowHook:
return AsyncDataflowHook(
gcp_conn_id=self.gcp_conn_id,
poll_sleep=self.poll_sleep,
impersonation_chain=self.impersonation_chain,
)
class DataflowJobAutoScalingEventTrigger(BaseTrigger):
"""
Trigger that checks for autoscaling events associated with a Dataflow job.
:param job_id: Required. ID of the job.
:param project_id: Required. The Google Cloud project ID in which the job was started.
:param location: Optional. The location where the job is executed. If set to None then
the value of DEFAULT_DATAFLOW_LOCATION will be used.
:param gcp_conn_id: The connection ID to use for connecting to Google Cloud.
:param poll_sleep: Time (seconds) to wait between two consecutive calls to check the job.
:param impersonation_chain: Optional. Service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:param fail_on_terminal_state: If set to True the trigger will yield a TriggerEvent with
error status if the job reaches a terminal state.
"""
def __init__(
self,
job_id: str,
project_id: str | None,
location: str = DEFAULT_DATAFLOW_LOCATION,
gcp_conn_id: str = "google_cloud_default",
poll_sleep: int = 10,
impersonation_chain: str | Sequence[str] | None = None,
fail_on_terminal_state: bool = True,
):
super().__init__()
self.project_id = project_id
self.job_id = job_id
self.location = location
self.gcp_conn_id = gcp_conn_id
self.poll_sleep = poll_sleep
self.impersonation_chain = impersonation_chain
self.fail_on_terminal_state = fail_on_terminal_state
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize class arguments and classpath."""
return (
"airflow.providers.google.cloud.triggers.dataflow.DataflowJobAutoScalingEventTrigger",
{
"project_id": self.project_id,
"job_id": self.job_id,
"location": self.location,
"gcp_conn_id": self.gcp_conn_id,
"poll_sleep": self.poll_sleep,
"impersonation_chain": self.impersonation_chain,
"fail_on_terminal_state": self.fail_on_terminal_state,
},
)
async def run(self):
"""
Loop until a terminal job status or any autoscaling events are returned.
Yields a TriggerEvent with success status, if the client returns any autoscaling events
and fail_on_terminal_state attribute is False.
Yields a TriggerEvent with error status, if the client returns a job status with
a terminal state value and fail_on_terminal_state attribute is True.
Yields a TriggerEvent with error status, if any exception is raised while looping.
In any other case the Trigger will wait for a specified amount of time
stored in self.poll_sleep variable.
"""
try:
while True:
job_status = await self.async_hook.get_job_status(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
autoscaling_events = await self.list_job_autoscaling_events()
if self.fail_on_terminal_state and job_status.name in DataflowJobStatus.TERMINAL_STATES:
yield TriggerEvent(
{
"status": "error",
"message": f"Job with id '{self.job_id}' is already in terminal state: {job_status.name}",
"result": None,
}
)
return
if autoscaling_events:
yield TriggerEvent(
{
"status": "success",
"message": f"Detected {len(autoscaling_events)} autoscaling events for job '{self.job_id}'",
"result": autoscaling_events,
}
)
return
self.log.info("Sleeping for %s seconds.", self.poll_sleep)
await asyncio.sleep(self.poll_sleep)
except Exception as e:
self.log.error("Exception occurred while checking for job's autoscaling events!")
yield TriggerEvent({"status": "error", "message": str(e), "result": None})
async def list_job_autoscaling_events(self) -> list[dict[str, str | dict]]:
"""Wait for the Dataflow client response and then return it in a serialized list."""
job_response: ListJobMessagesAsyncPager = await self.async_hook.list_job_messages(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
return self._get_autoscaling_events_from_job_response(job_response)
def _get_autoscaling_events_from_job_response(
self, job_response: ListJobMessagesAsyncPager
) -> list[dict[str, str | dict]]:
"""Return a list of serialized AutoscalingEvent objects."""
return [AutoscalingEvent.to_dict(event) for event in job_response.autoscaling_events]
@cached_property
def async_hook(self) -> AsyncDataflowHook:
return AsyncDataflowHook(
gcp_conn_id=self.gcp_conn_id,
poll_sleep=self.poll_sleep,
impersonation_chain=self.impersonation_chain,
)
class DataflowJobMessagesTrigger(BaseTrigger):
"""
Trigger that checks for job messages associated with a Dataflow job.
:param job_id: Required. ID of the job.
:param project_id: Required. The Google Cloud project ID in which the job was started.
:param location: Optional. The location where the job is executed. If set to None then
the value of DEFAULT_DATAFLOW_LOCATION will be used.
:param gcp_conn_id: The connection ID to use for connecting to Google Cloud.
:param poll_sleep: Time (seconds) to wait between two consecutive calls to check the job.
:param impersonation_chain: Optional. Service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
:param fail_on_terminal_state: If set to True the trigger will yield a TriggerEvent with
error status if the job reaches a terminal state.
"""
def __init__(
self,
job_id: str,
project_id: str | None,
location: str = DEFAULT_DATAFLOW_LOCATION,
gcp_conn_id: str = "google_cloud_default",
poll_sleep: int = 10,
impersonation_chain: str | Sequence[str] | None = None,
fail_on_terminal_state: bool = True,
):
super().__init__()
self.project_id = project_id
self.job_id = job_id
self.location = location
self.gcp_conn_id = gcp_conn_id
self.poll_sleep = poll_sleep
self.impersonation_chain = impersonation_chain
self.fail_on_terminal_state = fail_on_terminal_state
def serialize(self) -> tuple[str, dict[str, Any]]:
"""Serialize class arguments and classpath."""
return (
"airflow.providers.google.cloud.triggers.dataflow.DataflowJobMessagesTrigger",
{
"project_id": self.project_id,
"job_id": self.job_id,
"location": self.location,
"gcp_conn_id": self.gcp_conn_id,
"poll_sleep": self.poll_sleep,
"impersonation_chain": self.impersonation_chain,
"fail_on_terminal_state": self.fail_on_terminal_state,
},
)
async def run(self):
"""
Loop until a terminal job status or any job messages are returned.
Yields a TriggerEvent with success status, if the client returns any job messages
and fail_on_terminal_state attribute is False.
Yields a TriggerEvent with error status, if the client returns a job status with
a terminal state value and fail_on_terminal_state attribute is True.
Yields a TriggerEvent with error status, if any exception is raised while looping.
In any other case the Trigger will wait for a specified amount of time
stored in self.poll_sleep variable.
"""
try:
while True:
job_status = await self.async_hook.get_job_status(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
job_messages = await self.list_job_messages()
if self.fail_on_terminal_state and job_status.name in DataflowJobStatus.TERMINAL_STATES:
yield TriggerEvent(
{
"status": "error",
"message": f"Job with id '{self.job_id}' is already in terminal state: {job_status.name}",
"result": None,
}
)
return
if job_messages:
yield TriggerEvent(
{
"status": "success",
"message": f"Detected {len(job_messages)} job messages for job '{self.job_id}'",
"result": job_messages,
}
)
return
self.log.info("Sleeping for %s seconds.", self.poll_sleep)
await asyncio.sleep(self.poll_sleep)
except Exception as e:
self.log.error("Exception occurred while checking for job's messages!")
yield TriggerEvent({"status": "error", "message": str(e), "result": None})
async def list_job_messages(self) -> list[dict[str, str | dict]]:
"""Wait for the Dataflow client response and then return it in a serialized list."""
job_response: ListJobMessagesAsyncPager = await self.async_hook.list_job_messages(
job_id=self.job_id,
project_id=self.project_id,
location=self.location,
)
return self._get_job_messages_from_job_response(job_response)
def _get_job_messages_from_job_response(
self, job_response: ListJobMessagesAsyncPager
) -> list[dict[str, str | dict]]:
"""Return a list of serialized JobMessage objects."""
return [JobMessage.to_dict(message) for message in job_response.job_messages]
@cached_property
def async_hook(self) -> AsyncDataflowHook:
return AsyncDataflowHook(
gcp_conn_id=self.gcp_conn_id,
poll_sleep=self.poll_sleep,
impersonation_chain=self.impersonation_chain,
)