/
cloud_run.py
355 lines (306 loc) · 15.2 KB
/
cloud_run.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
#
# 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
from typing import TYPE_CHECKING, Any, Sequence
from google.cloud.run_v2 import Job
from airflow.configuration import conf
from airflow.exceptions import AirflowException
from airflow.providers.google.cloud.hooks.cloud_run import CloudRunHook
from airflow.providers.google.cloud.operators.cloud_base import GoogleCloudBaseOperator
from airflow.providers.google.cloud.triggers.cloud_run import CloudRunJobFinishedTrigger, RunJobStatus
if TYPE_CHECKING:
from google.api_core import operation
from google.cloud.run_v2.types import Execution
from airflow.utils.context import Context
class CloudRunCreateJobOperator(GoogleCloudBaseOperator):
"""
Creates a job without executing it. Pushes the created job to xcom.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param job_name: Required. The name of the job to create.
:param job: Required. The job descriptor containing the configuration of the job to submit.
:param gcp_conn_id: The connection ID used to connect 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).
"""
template_fields = ("project_id", "region", "gcp_conn_id", "impersonation_chain", "job_name")
def __init__(
self,
project_id: str,
region: str,
job_name: str,
job: dict | Job,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.job_name = job_name
self.job = job
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook: CloudRunHook = CloudRunHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
job = hook.create_job(
job_name=self.job_name, job=self.job, region=self.region, project_id=self.project_id
)
return Job.to_dict(job)
class CloudRunUpdateJobOperator(GoogleCloudBaseOperator):
"""
Updates a job and wait for the operation to be completed. Pushes the updated job to xcom.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param job_name: Required. The name of the job to update.
:param job: Required. The job descriptor containing the new configuration of the job to update.
The name field will be replaced by job_name
:param gcp_conn_id: The connection ID used to connect 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).
"""
template_fields = ("project_id", "region", "gcp_conn_id", "impersonation_chain", "job_name")
def __init__(
self,
project_id: str,
region: str,
job_name: str,
job: dict | Job,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.job_name = job_name
self.job = job
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook: CloudRunHook = CloudRunHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
job = hook.update_job(
job_name=self.job_name, job=self.job, region=self.region, project_id=self.project_id
)
return Job.to_dict(job)
class CloudRunDeleteJobOperator(GoogleCloudBaseOperator):
"""
Deletes a job and wait for the the operation to be completed. Pushes the deleted job to xcom.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param job_name: Required. The name of the job to delete.
:param gcp_conn_id: The connection ID used to connect 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).
"""
template_fields = ("project_id", "region", "gcp_conn_id", "impersonation_chain", "job_name")
def __init__(
self,
project_id: str,
region: str,
job_name: str,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.job_name = job_name
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook: CloudRunHook = CloudRunHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
job = hook.delete_job(job_name=self.job_name, region=self.region, project_id=self.project_id)
return Job.to_dict(job)
class CloudRunListJobsOperator(GoogleCloudBaseOperator):
"""
Lists jobs.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param show_deleted: If true, returns deleted (but unexpired)
resources along with active ones.
:param limit: The number of jobs to list. If left empty,
all the jobs will be returned.
:param gcp_conn_id: The connection ID used to connect 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).
"""
template_fields = (
"project_id",
"region",
"gcp_conn_id",
"impersonation_chain",
)
def __init__(
self,
project_id: str,
region: str,
show_deleted: bool = False,
limit: int | None = None,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
self.show_deleted = show_deleted
self.limit = limit
if limit is not None and limit < 0:
raise AirflowException("The limit for the list jobs request should be greater or equal to zero")
def execute(self, context: Context):
hook: CloudRunHook = CloudRunHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
jobs = hook.list_jobs(
region=self.region, project_id=self.project_id, show_deleted=self.show_deleted, limit=self.limit
)
return [Job.to_dict(job) for job in jobs]
class CloudRunExecuteJobOperator(GoogleCloudBaseOperator):
"""
Executes a job and wait for the operation to be completed. Pushes the executed job to xcom.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param job_name: Required. The name of the job to update.
:param job: Required. The job descriptor containing the new configuration of the job to update.
The name field will be replaced by job_name
:param overrides: Optional map of override values.
:param gcp_conn_id: The connection ID used to connect to Google Cloud.
:param polling_period_seconds: Optional: Control the rate of the poll for the result of deferrable run.
By default, the trigger will poll every 10 seconds.
:param timeout: The timeout for this request.
: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 deferrable: Run operator in the deferrable mode
"""
template_fields = ("project_id", "region", "gcp_conn_id", "impersonation_chain", "job_name")
def __init__(
self,
project_id: str,
region: str,
job_name: str,
overrides: dict[str, Any] | None = None,
polling_period_seconds: float = 10,
timeout_seconds: float | None = None,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(**kwargs)
self.project_id = project_id
self.region = region
self.job_name = job_name
self.overrides = overrides
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
self.polling_period_seconds = polling_period_seconds
self.timeout_seconds = timeout_seconds
self.deferrable = deferrable
self.operation: operation.Operation | None = None
def execute(self, context: Context):
hook: CloudRunHook = CloudRunHook(
gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain
)
self.operation = hook.execute_job(
region=self.region, project_id=self.project_id, job_name=self.job_name, overrides=self.overrides
)
if not self.deferrable:
result: Execution = self._wait_for_operation(self.operation)
self._fail_if_execution_failed(result)
job = hook.get_job(job_name=result.job, region=self.region)
return Job.to_dict(job)
else:
self.defer(
trigger=CloudRunJobFinishedTrigger(
operation_name=self.operation.operation.name,
job_name=self.job_name,
project_id=self.project_id,
location=self.region,
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
polling_period_seconds=self.polling_period_seconds,
),
method_name="execute_complete",
)
def execute_complete(self, context: Context, event: dict):
status = event["status"]
if status == RunJobStatus.TIMEOUT:
raise AirflowException("Operation timed out")
if status == RunJobStatus.FAIL:
error_code = event["operation_error_code"]
error_message = event["operation_error_message"]
raise AirflowException(
f"Operation failed with error code [{error_code}] and error message [{error_message}]"
)
hook: CloudRunHook = CloudRunHook(self.gcp_conn_id, self.impersonation_chain)
job = hook.get_job(job_name=event["job_name"], region=self.region)
return Job.to_dict(job)
def _fail_if_execution_failed(self, execution: Execution):
task_count = execution.task_count
succeeded_count = execution.succeeded_count
failed_count = execution.failed_count
if succeeded_count + failed_count != task_count:
raise AirflowException("Not all tasks finished execution")
if failed_count > 0:
raise AirflowException("Some tasks failed execution")
def _wait_for_operation(self, operation: operation.Operation):
try:
return operation.result(timeout=self.timeout_seconds)
except Exception:
error = operation.exception(timeout=self.timeout_seconds)
raise AirflowException(error)