-
Notifications
You must be signed in to change notification settings - Fork 13.6k
/
base.py
411 lines (353 loc) · 15.9 KB
/
base.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
#
# 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.
"""
This module contains a Google Cloud API base hook.
"""
import functools
import json
import logging
import os
import tempfile
from contextlib import contextmanager
from typing import Any, Callable, Dict, Optional, Sequence, TypeVar
import google.auth
import google.oauth2.service_account
import google_auth_httplib2
import httplib2
import tenacity
from google.api_core.exceptions import (
AlreadyExists, Forbidden, GoogleAPICallError, ResourceExhausted, RetryError,
)
from google.api_core.gapic_v1.client_info import ClientInfo
from google.auth.environment_vars import CREDENTIALS
from googleapiclient.errors import HttpError
from googleapiclient.http import set_user_agent
from airflow import version
from airflow.exceptions import AirflowException
from airflow.hooks.base_hook import BaseHook
log = logging.getLogger(__name__)
_DEFAULT_SCOPES = ('https://www.googleapis.com/auth/cloud-platform',) # type: Sequence[str]
# Constants used by the mechanism of repeating requests in reaction to exceeding the temporary quota.
INVALID_KEYS = [
'DefaultRequestsPerMinutePerProject',
'DefaultRequestsPerMinutePerUser',
'RequestsPerMinutePerProject',
"Resource has been exhausted (e.g. check quota).",
]
INVALID_REASONS = [
'userRateLimitExceeded',
]
def is_soft_quota_exception(exception: Exception):
"""
API for Google services does not have a standardized way to report quota violation errors.
The function has been adapted by trial and error to the following services:
* Google Translate
* Google Vision
* Google Text-to-Speech
* Google Speech-to-Text
* Google Natural Language
* Google Video Intelligence
"""
if isinstance(exception, Forbidden):
return any(
reason in error["reason"]
for reason in INVALID_REASONS
for error in exception.errors
)
if isinstance(exception, ResourceExhausted):
return any(
key in error.details()
for key in INVALID_KEYS
for error in exception.errors
)
return False
class retry_if_temporary_quota(tenacity.retry_if_exception): # pylint: disable=invalid-name
"""Retries if there was an exception for exceeding the temporary quote limit."""
def __init__(self):
super().__init__(is_soft_quota_exception)
RT = TypeVar('RT') # pylint: disable=invalid-name
class CloudBaseHook(BaseHook):
"""
A base hook for Google cloud-related hooks. Google cloud has a shared REST
API client that is built in the same way no matter which service you use.
This class helps construct and authorize the credentials needed to then
call googleapiclient.discovery.build() to actually discover and build a client
for a Google cloud service.
The class also contains some miscellaneous helper functions.
All hook derived from this base hook use the 'Google Cloud Platform' connection
type. Three ways of authentication are supported:
Default credentials: Only the 'Project Id' is required. You'll need to
have set up default credentials, such as by the
``GOOGLE_APPLICATION_DEFAULT`` environment variable or from the metadata
server on Google Compute Engine.
JSON key file: Specify 'Project Id', 'Keyfile Path' and 'Scope'.
Legacy P12 key files are not supported.
JSON data provided in the UI: Specify 'Keyfile JSON'.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request must have
domain-wide delegation enabled.
:type delegate_to: str
"""
def __init__(self, gcp_conn_id: str = 'google_cloud_default', delegate_to: Optional[str] = None) -> None:
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
self.extras = self.get_connection(self.gcp_conn_id).extra_dejson # type: Dict
def _get_credentials_and_project_id(self) -> google.auth.credentials.Credentials:
"""
Returns the Credentials object for Google API and the associated project_id
"""
key_path = self._get_field('key_path', None) # type: Optional[str]
keyfile_dict = self._get_field('keyfile_dict', None) # type: Optional[str]
if key_path and keyfile_dict:
raise AirflowException(
"The `keyfile_dict` and `key_path` fields are mutually exclusive. "
"Please provide only one value."
)
if not key_path and not keyfile_dict:
self.log.info(
'Getting connection using `google.auth.default()` since no key file is defined for hook.'
)
credentials, project_id = google.auth.default(scopes=self.scopes)
elif key_path:
# Get credentials from a JSON file.
if key_path.endswith('.json'):
self.log.debug('Getting connection using JSON key file %s', key_path)
credentials = (
google.oauth2.service_account.Credentials.from_service_account_file(
key_path, scopes=self.scopes)
)
project_id = credentials.project_id
elif key_path.endswith('.p12'):
raise AirflowException(
'Legacy P12 key file are not supported, use a JSON key file.'
)
else:
raise AirflowException('Unrecognised extension for key file.')
else:
# Get credentials from JSON data provided in the UI.
try:
if not keyfile_dict:
raise ValueError("The keyfile_dict should be set")
keyfile_dict_json: Dict[str, str] = json.loads(keyfile_dict)
# Depending on how the JSON was formatted, it may contain
# escaped newlines. Convert those to actual newlines.
keyfile_dict_json['private_key'] = keyfile_dict_json['private_key'].replace(
'\\n', '\n')
credentials = (
google.oauth2.service_account.Credentials.from_service_account_info(
keyfile_dict_json, scopes=self.scopes)
)
project_id = credentials.project_id
except json.decoder.JSONDecodeError:
raise AirflowException('Invalid key JSON.')
if self.delegate_to:
credentials = credentials.with_subject(self.delegate_to)
overridden_project_id = self._get_field('project')
if overridden_project_id:
project_id = overridden_project_id
return credentials, project_id
def _get_credentials(self) -> google.auth.credentials.Credentials:
"""
Returns the Credentials object for Google API
"""
credentials, _ = self._get_credentials_and_project_id()
return credentials
def _get_access_token(self) -> str:
"""
Returns a valid access token from Google API Credentials
"""
return self._get_credentials().token
def _authorize(self) -> google_auth_httplib2.AuthorizedHttp:
"""
Returns an authorized HTTP object to be used to build a Google cloud
service hook connection.
"""
credentials = self._get_credentials()
http = httplib2.Http()
http = set_user_agent(http, "airflow/" + version.version)
authed_http = google_auth_httplib2.AuthorizedHttp(credentials, http=http)
return authed_http
def _get_field(self, f: str, default: Any = None) -> Any:
"""
Fetches a field from extras, and returns it. This is some Airflow
magic. The google_cloud_platform hook type adds custom UI elements
to the hook page, which allow admins to specify service_account,
key_path, etc. They get formatted as shown below.
"""
long_f = 'extra__google_cloud_platform__{}'.format(f)
if hasattr(self, 'extras') and long_f in self.extras:
return self.extras[long_f]
else:
return default
@property
def project_id(self) -> Optional[str]:
"""
Returns project id.
:return: id of the project
:rtype: str
"""
_, project_id = self._get_credentials_and_project_id()
return project_id
@property
def num_retries(self) -> int:
"""
Returns num_retries from Connection.
:return: the number of times each API request should be retried
:rtype: int
"""
return self._get_field('num_retries') or 5
@property
def client_info(self) -> ClientInfo:
"""
Return client information used to generate a user-agent for API calls.
It allows for better errors tracking.
This object is only used by the google-cloud-* libraries that are built specifically for
the Google Cloud Platform. It is not supported by The Google APIs Python Client that use Discovery
based APIs.
"""
client_info = ClientInfo(client_library_version='airflow_v' + version.version)
return client_info
@property
def scopes(self) -> Sequence[str]:
"""
Return OAuth 2.0 scopes.
:return: Returns the scope defined in the connection configuration, or the default scope
:rtype: Sequence[str]
"""
scope_value = self._get_field('scope', None) # type: Optional[str]
return [s.strip() for s in scope_value.split(',')] \
if scope_value else _DEFAULT_SCOPES
@staticmethod
def quota_retry(*args, **kwargs) -> Callable:
"""
A decorator who provides a mechanism to repeat requests in response to exceeding a temporary quote
limit.
"""
def decorator(fun: Callable):
default_kwargs = {
'wait': tenacity.wait_exponential(multiplier=1, max=100),
'retry': retry_if_temporary_quota(),
'before': tenacity.before_log(log, logging.DEBUG),
'after': tenacity.after_log(log, logging.DEBUG),
}
default_kwargs.update(**kwargs)
return tenacity.retry(
*args, **default_kwargs
)(fun)
return decorator
@staticmethod
def catch_http_exception(func: Callable[..., RT]) -> Callable[..., RT]:
"""
Function decorator that intercepts HTTP Errors and raises AirflowException
with more informative message.
"""
@functools.wraps(func)
def wrapper_decorator(self: CloudBaseHook, *args, **kwargs) -> RT:
try:
return func(self, *args, **kwargs)
except GoogleAPICallError as e:
if isinstance(e, AlreadyExists):
raise e
else:
self.log.error('The request failed:\n%s', str(e))
raise AirflowException(e)
except RetryError as e:
self.log.error('The request failed due to a retryable error and retry attempts failed.')
raise AirflowException(e)
except ValueError as e:
self.log.error('The request failed, the parameters are invalid.')
raise AirflowException(e)
except HttpError as e:
self.log.error('The request failed:\n%s', str(e))
raise AirflowException(e)
return wrapper_decorator
@staticmethod
def fallback_to_default_project_id(func: Callable[..., RT]) -> Callable[..., RT]:
"""
Decorator that provides fallback for Google Cloud Platform project id. If
the project is None it will be replaced with the project_id from the
service account the Hook is authenticated with. Project id can be specified
either via project_id kwarg or via first parameter in positional args.
:param func: function to wrap
:return: result of the function call
"""
@functools.wraps(func)
def inner_wrapper(self: CloudBaseHook, *args, **kwargs) -> RT:
if args:
raise AirflowException(
"You must use keyword arguments in this methods rather than"
" positional")
if 'project_id' in kwargs:
kwargs['project_id'] = kwargs['project_id'] or self.project_id
else:
kwargs['project_id'] = self.project_id
if not kwargs['project_id']:
raise AirflowException("The project id must be passed either as "
"keyword project_id parameter or as project_id extra "
"in GCP connection definition. Both are not set!")
return func(self, *args, **kwargs)
return inner_wrapper
@staticmethod
def provide_gcp_credential_file(func: Callable[..., RT]) -> Callable[..., RT]:
"""
Function decorator that provides a GCP credentials for application supporting Application
Default Credentials (ADC) strategy.
It is recommended to use ``provide_gcp_credential_file_as_context`` context manager to limit the
scope when authorization data is available. Using context manager also
makes it easier to use multiple connection in one function.
"""
@functools.wraps(func)
def wrapper(self: CloudBaseHook, *args, **kwargs) -> RT:
with self.provide_gcp_credential_file_as_context():
return func(self, *args, **kwargs)
return wrapper
@contextmanager
def provide_gcp_credential_file_as_context(self):
"""
Context manager that provides a GCP credentials for application supporting `Application
Default Credentials (ADC) strategy <https://cloud.google.com/docs/authentication/production>`__.
It can be used to provide credentials for external programs (e.g. gcloud) that expect authorization
file in ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable.
"""
with tempfile.NamedTemporaryFile(mode='w+t') as conf_file:
key_path = self._get_field('key_path', None) # type: Optional[str] # noqa: E501 # pylint: disable=protected-access
keyfile_dict = self._get_field('keyfile_dict', None) # type: Optional[Dict] # noqa: E501 # pylint: disable=protected-access
current_env_state = os.environ.get(CREDENTIALS)
try:
if key_path:
if key_path.endswith('.p12'):
raise AirflowException(
'Legacy P12 key file are not supported, use a JSON key file.'
)
os.environ[CREDENTIALS] = key_path
elif keyfile_dict:
conf_file.write(keyfile_dict)
conf_file.flush()
os.environ[CREDENTIALS] = conf_file.name
else:
# We will use the default service account credentials.
pass
yield conf_file
finally:
if current_env_state is None:
if CREDENTIALS in os.environ:
del os.environ[CREDENTIALS]
else:
os.environ[CREDENTIALS] = current_env_state