apache-airflow-providers-google 10.18.0rc2__py3-none-any.whl → 10.19.0rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. airflow/providers/google/__init__.py +1 -1
  2. airflow/providers/google/cloud/hooks/bigquery.py +11 -10
  3. airflow/providers/google/cloud/links/automl.py +38 -0
  4. airflow/providers/google/cloud/links/translate.py +180 -0
  5. airflow/providers/google/cloud/log/stackdriver_task_handler.py +1 -2
  6. airflow/providers/google/cloud/openlineage/BigQueryErrorRunFacet.json +30 -0
  7. airflow/providers/google/cloud/openlineage/BigQueryJobRunFacet.json +37 -0
  8. airflow/providers/google/cloud/openlineage/__init__.py +16 -0
  9. airflow/providers/google/cloud/openlineage/utils.py +388 -0
  10. airflow/providers/google/cloud/operators/automl.py +75 -63
  11. airflow/providers/google/cloud/operators/bigquery.py +1 -62
  12. airflow/providers/google/cloud/operators/vertex_ai/auto_ml.py +5 -0
  13. airflow/providers/google/cloud/operators/vertex_ai/custom_job.py +6 -0
  14. airflow/providers/google/cloud/transfers/azure_fileshare_to_gcs.py +7 -4
  15. airflow/providers/google/cloud/transfers/bigquery_to_gcs.py +1 -1
  16. airflow/providers/google/cloud/transfers/gcs_to_bigquery.py +1 -1
  17. airflow/providers/google/cloud/triggers/pubsub.py +8 -11
  18. airflow/providers/google/cloud/utils/credentials_provider.py +41 -32
  19. airflow/providers/google/common/hooks/base_google.py +11 -5
  20. airflow/providers/google/get_provider_info.py +8 -2
  21. {apache_airflow_providers_google-10.18.0rc2.dist-info → apache_airflow_providers_google-10.19.0rc1.dist-info}/METADATA +8 -8
  22. {apache_airflow_providers_google-10.18.0rc2.dist-info → apache_airflow_providers_google-10.19.0rc1.dist-info}/RECORD +24 -20
  23. airflow/providers/google/cloud/utils/openlineage.py +0 -81
  24. {apache_airflow_providers_google-10.18.0rc2.dist-info → apache_airflow_providers_google-10.19.0rc1.dist-info}/WHEEL +0 -0
  25. {apache_airflow_providers_google-10.18.0rc2.dist-info → apache_airflow_providers_google-10.19.0rc1.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,388 @@
1
+ #
2
+ # Licensed to the Apache Software Foundation (ASF) under one
3
+ # or more contributor license agreements. See the NOTICE file
4
+ # distributed with this work for additional information
5
+ # regarding copyright ownership. The ASF licenses this file
6
+ # to you under the Apache License, Version 2.0 (the
7
+ # "License"); you may not use this file except in compliance
8
+ # with the License. You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing,
13
+ # software distributed under the License is distributed on an
14
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ # KIND, either express or implied. See the License for the
16
+ # specific language governing permissions and limitations
17
+ # under the License.
18
+ from __future__ import annotations
19
+
20
+ import copy
21
+ import json
22
+ import traceback
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from attr import define, field
26
+ from openlineage.client.facet import (
27
+ BaseFacet,
28
+ ColumnLineageDatasetFacet,
29
+ ColumnLineageDatasetFacetFieldsAdditional,
30
+ ColumnLineageDatasetFacetFieldsAdditionalInputFields,
31
+ DocumentationDatasetFacet,
32
+ ErrorMessageRunFacet,
33
+ OutputStatisticsOutputDatasetFacet,
34
+ SchemaDatasetFacet,
35
+ SchemaField,
36
+ )
37
+ from openlineage.client.run import Dataset
38
+
39
+ from airflow.providers.google import __version__ as provider_version
40
+
41
+ if TYPE_CHECKING:
42
+ from google.cloud.bigquery.table import Table
43
+
44
+
45
+ BIGQUERY_NAMESPACE = "bigquery"
46
+ BIGQUERY_URI = "bigquery"
47
+
48
+
49
+ def get_facets_from_bq_table(table: Table) -> dict[Any, Any]:
50
+ """Get facets from BigQuery table object."""
51
+ facets = {
52
+ "schema": SchemaDatasetFacet(
53
+ fields=[
54
+ SchemaField(name=field.name, type=field.field_type, description=field.description)
55
+ for field in table.schema
56
+ ]
57
+ ),
58
+ "documentation": DocumentationDatasetFacet(description=table.description or ""),
59
+ }
60
+
61
+ return facets
62
+
63
+
64
+ def get_identity_column_lineage_facet(
65
+ field_names: list[str],
66
+ input_datasets: list[Dataset],
67
+ ) -> ColumnLineageDatasetFacet:
68
+ """
69
+ Get column lineage facet.
70
+
71
+ Simple lineage will be created, where each source column corresponds to single destination column
72
+ in each input dataset and there are no transformations made.
73
+ """
74
+ if field_names and not input_datasets:
75
+ raise ValueError("When providing `field_names` You must provide at least one `input_dataset`.")
76
+
77
+ column_lineage_facet = ColumnLineageDatasetFacet(
78
+ fields={
79
+ field: ColumnLineageDatasetFacetFieldsAdditional(
80
+ inputFields=[
81
+ ColumnLineageDatasetFacetFieldsAdditionalInputFields(
82
+ namespace=dataset.namespace, name=dataset.name, field=field
83
+ )
84
+ for dataset in input_datasets
85
+ ],
86
+ transformationType="IDENTITY",
87
+ transformationDescription="identical",
88
+ )
89
+ for field in field_names
90
+ }
91
+ )
92
+ return column_lineage_facet
93
+
94
+
95
+ @define
96
+ class BigQueryJobRunFacet(BaseFacet):
97
+ """Facet that represents relevant statistics of bigquery run.
98
+
99
+ This facet is used to provide statistics about bigquery run.
100
+
101
+ :param cached: BigQuery caches query results. Rest of the statistics will not be provided for cached queries.
102
+ :param billedBytes: How many bytes BigQuery bills for.
103
+ :param properties: Full property tree of BigQUery run.
104
+ """
105
+
106
+ cached: bool
107
+ billedBytes: int | None = field(default=None)
108
+ properties: str | None = field(default=None)
109
+
110
+ @staticmethod
111
+ def _get_schema() -> str:
112
+ return (
113
+ "https://raw.githubusercontent.com/apache/airflow/"
114
+ f"providers-google/{provider_version}/airflow/providers/google/"
115
+ "openlineage/BigQueryJobRunFacet.json"
116
+ )
117
+
118
+
119
+ # TODO: remove BigQueryErrorRunFacet in next release
120
+ @define
121
+ class BigQueryErrorRunFacet(BaseFacet):
122
+ """
123
+ Represents errors that can happen during execution of BigqueryExtractor.
124
+
125
+ :param clientError: represents errors originating in bigquery client
126
+ :param parserError: represents errors that happened during parsing SQL provided to bigquery
127
+ """
128
+
129
+ clientError: str | None = field(default=None)
130
+ parserError: str | None = field(default=None)
131
+
132
+ @staticmethod
133
+ def _get_schema() -> str:
134
+ return (
135
+ "https://raw.githubusercontent.com/apache/airflow/"
136
+ f"providers-google/{provider_version}/airflow/providers/google/"
137
+ "openlineage/BigQueryErrorRunFacet.json"
138
+ )
139
+
140
+
141
+ def get_from_nullable_chain(source: Any, chain: list[str]) -> Any | None:
142
+ """Get object from nested structure of objects, where it's not guaranteed that all keys in the nested structure exist.
143
+
144
+ Intended to replace chain of `dict.get()` statements.
145
+
146
+ Example usage:
147
+
148
+ .. code-block:: python
149
+
150
+ if (
151
+ not job._properties.get("statistics")
152
+ or not job._properties.get("statistics").get("query")
153
+ or not job._properties.get("statistics").get("query").get("referencedTables")
154
+ ):
155
+ return None
156
+ result = job._properties.get("statistics").get("query").get("referencedTables")
157
+
158
+ becomes:
159
+
160
+ .. code-block:: python
161
+
162
+ result = get_from_nullable_chain(properties, ["statistics", "query", "queryPlan"])
163
+ if not result:
164
+ return None
165
+ """
166
+ chain.reverse()
167
+ try:
168
+ while chain:
169
+ next_key = chain.pop()
170
+ if isinstance(source, dict):
171
+ source = source.get(next_key)
172
+ else:
173
+ source = getattr(source, next_key)
174
+ return source
175
+ except AttributeError:
176
+ return None
177
+
178
+
179
+ class _BigQueryOpenLineageMixin:
180
+ def get_openlineage_facets_on_complete(self, _):
181
+ """
182
+ Retrieve OpenLineage data for a COMPLETE BigQuery job.
183
+
184
+ This method retrieves statistics for the specified job_ids using the BigQueryDatasetsProvider.
185
+ It calls BigQuery API, retrieving input and output dataset info from it, as well as run-level
186
+ usage statistics.
187
+
188
+ Run facets should contain:
189
+ - ExternalQueryRunFacet
190
+ - BigQueryJobRunFacet
191
+
192
+ Run facets may contain:
193
+ - ErrorMessageRunFacet
194
+
195
+ Job facets should contain:
196
+ - SqlJobFacet if operator has self.sql
197
+
198
+ Input datasets should contain facets:
199
+ - DataSourceDatasetFacet
200
+ - SchemaDatasetFacet
201
+
202
+ Output datasets should contain facets:
203
+ - DataSourceDatasetFacet
204
+ - SchemaDatasetFacet
205
+ - OutputStatisticsOutputDatasetFacet
206
+ """
207
+ from openlineage.client.facet import ExternalQueryRunFacet, SqlJobFacet
208
+
209
+ from airflow.providers.openlineage.extractors import OperatorLineage
210
+ from airflow.providers.openlineage.sqlparser import SQLParser
211
+
212
+ if not self.job_id:
213
+ return OperatorLineage()
214
+
215
+ run_facets: dict[str, BaseFacet] = {
216
+ "externalQuery": ExternalQueryRunFacet(externalQueryId=self.job_id, source="bigquery")
217
+ }
218
+
219
+ job_facets = {"sql": SqlJobFacet(query=SQLParser.normalize_sql(self.sql))}
220
+
221
+ self.client = self.hook.get_client(project_id=self.hook.project_id)
222
+ job_ids = self.job_id
223
+ if isinstance(self.job_id, str):
224
+ job_ids = [self.job_id]
225
+ inputs, outputs = [], []
226
+ for job_id in job_ids:
227
+ inner_inputs, inner_outputs, inner_run_facets = self.get_facets(job_id=job_id)
228
+ inputs.extend(inner_inputs)
229
+ outputs.extend(inner_outputs)
230
+ run_facets.update(inner_run_facets)
231
+
232
+ return OperatorLineage(
233
+ inputs=inputs,
234
+ outputs=outputs,
235
+ run_facets=run_facets,
236
+ job_facets=job_facets,
237
+ )
238
+
239
+ def get_facets(self, job_id: str):
240
+ inputs = []
241
+ outputs = []
242
+ run_facets: dict[str, BaseFacet] = {}
243
+ if hasattr(self, "log"):
244
+ self.log.debug("Extracting data from bigquery job: `%s`", job_id)
245
+ try:
246
+ job = self.client.get_job(job_id=job_id) # type: ignore
247
+ props = job._properties
248
+
249
+ if get_from_nullable_chain(props, ["status", "state"]) != "DONE":
250
+ raise ValueError(f"Trying to extract data from running bigquery job: `{job_id}`")
251
+
252
+ # TODO: remove bigQuery_job in next release
253
+ run_facets["bigQuery_job"] = run_facets["bigQueryJob"] = self._get_bigquery_job_run_facet(props)
254
+
255
+ if get_from_nullable_chain(props, ["statistics", "numChildJobs"]):
256
+ if hasattr(self, "log"):
257
+ self.log.debug("Found SCRIPT job. Extracting lineage from child jobs instead.")
258
+ # SCRIPT job type has no input / output information but spawns child jobs that have one
259
+ # https://cloud.google.com/bigquery/docs/information-schema-jobs#multi-statement_query_job
260
+ for child_job_id in self.client.list_jobs(parent_job=job_id):
261
+ child_job = self.client.get_job(job_id=child_job_id) # type: ignore
262
+ child_inputs, child_output = self._get_inputs_outputs_from_job(child_job._properties)
263
+ inputs.extend(child_inputs)
264
+ outputs.append(child_output)
265
+ else:
266
+ inputs, _output = self._get_inputs_outputs_from_job(props)
267
+ outputs.append(_output)
268
+ except Exception as e:
269
+ if hasattr(self, "log"):
270
+ self.log.warning("Cannot retrieve job details from BigQuery.Client. %s", e, exc_info=True)
271
+ exception_msg = traceback.format_exc()
272
+ # TODO: remove BigQueryErrorRunFacet in next release
273
+ run_facets.update(
274
+ {
275
+ "errorMessage": ErrorMessageRunFacet(
276
+ message=f"{e}: {exception_msg}",
277
+ programmingLanguage="python",
278
+ ),
279
+ "bigQuery_error": BigQueryErrorRunFacet(
280
+ clientError=f"{e}: {exception_msg}",
281
+ ),
282
+ }
283
+ )
284
+ deduplicated_outputs = self._deduplicate_outputs(outputs)
285
+ return inputs, deduplicated_outputs, run_facets
286
+
287
+ def _deduplicate_outputs(self, outputs: list[Dataset | None]) -> list[Dataset]:
288
+ # Sources are the same so we can compare only names
289
+ final_outputs = {}
290
+ for single_output in outputs:
291
+ if not single_output:
292
+ continue
293
+ key = single_output.name
294
+ if key not in final_outputs:
295
+ final_outputs[key] = single_output
296
+ continue
297
+
298
+ # No OutputStatisticsOutputDatasetFacet is added to duplicated outputs as we can not determine
299
+ # if the rowCount or size can be summed together.
300
+ single_output.facets.pop("outputStatistics", None)
301
+ final_outputs[key] = single_output
302
+
303
+ return list(final_outputs.values())
304
+
305
+ def _get_inputs_outputs_from_job(self, properties: dict) -> tuple[list[Dataset], Dataset | None]:
306
+ input_tables = get_from_nullable_chain(properties, ["statistics", "query", "referencedTables"]) or []
307
+ output_table = get_from_nullable_chain(properties, ["configuration", "query", "destinationTable"])
308
+ inputs = [self._get_dataset(input_table) for input_table in input_tables]
309
+ if output_table:
310
+ output = self._get_dataset(output_table)
311
+ dataset_stat_facet = self._get_statistics_dataset_facet(properties)
312
+ if dataset_stat_facet:
313
+ output.facets.update({"outputStatistics": dataset_stat_facet})
314
+
315
+ return inputs, output
316
+
317
+ @staticmethod
318
+ def _get_bigquery_job_run_facet(properties: dict) -> BigQueryJobRunFacet:
319
+ if get_from_nullable_chain(properties, ["configuration", "query", "query"]):
320
+ # Exclude the query to avoid event size issues and duplicating SqlJobFacet information.
321
+ properties = copy.deepcopy(properties)
322
+ properties["configuration"]["query"].pop("query")
323
+ cache_hit = get_from_nullable_chain(properties, ["statistics", "query", "cacheHit"])
324
+ billed_bytes = get_from_nullable_chain(properties, ["statistics", "query", "totalBytesBilled"])
325
+ return BigQueryJobRunFacet(
326
+ cached=str(cache_hit).lower() == "true",
327
+ billedBytes=int(billed_bytes) if billed_bytes else None,
328
+ properties=json.dumps(properties),
329
+ )
330
+
331
+ @staticmethod
332
+ def _get_statistics_dataset_facet(properties) -> OutputStatisticsOutputDatasetFacet | None:
333
+ query_plan = get_from_nullable_chain(properties, chain=["statistics", "query", "queryPlan"])
334
+ if not query_plan:
335
+ return None
336
+
337
+ out_stage = query_plan[-1]
338
+ out_rows = out_stage.get("recordsWritten", None)
339
+ out_bytes = out_stage.get("shuffleOutputBytes", None)
340
+ if out_bytes and out_rows:
341
+ return OutputStatisticsOutputDatasetFacet(rowCount=int(out_rows), size=int(out_bytes))
342
+ return None
343
+
344
+ def _get_dataset(self, table: dict) -> Dataset:
345
+ project = table.get("projectId")
346
+ dataset = table.get("datasetId")
347
+ table_name = table.get("tableId")
348
+ dataset_name = f"{project}.{dataset}.{table_name}"
349
+
350
+ dataset_schema = self._get_table_schema_safely(dataset_name)
351
+ return Dataset(
352
+ namespace=BIGQUERY_NAMESPACE,
353
+ name=dataset_name,
354
+ facets={
355
+ "schema": dataset_schema,
356
+ }
357
+ if dataset_schema
358
+ else {},
359
+ )
360
+
361
+ def _get_table_schema_safely(self, table_name: str) -> SchemaDatasetFacet | None:
362
+ try:
363
+ return self._get_table_schema(table_name)
364
+ except Exception as e:
365
+ if hasattr(self, "log"):
366
+ self.log.warning("Could not extract output schema from bigquery. %s", e)
367
+ return None
368
+
369
+ def _get_table_schema(self, table: str) -> SchemaDatasetFacet | None:
370
+ bq_table = self.client.get_table(table)
371
+
372
+ if not bq_table._properties:
373
+ return None
374
+
375
+ fields = get_from_nullable_chain(bq_table._properties, ["schema", "fields"])
376
+ if not fields:
377
+ return None
378
+
379
+ return SchemaDatasetFacet(
380
+ fields=[
381
+ SchemaField(
382
+ name=field.get("name"),
383
+ type=field.get("type"),
384
+ description=field.get("description"),
385
+ )
386
+ for field in fields
387
+ ]
388
+ )