| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# coding=utf-8 |
| 3 |
# -------------------------------------------------------------------------- |
| 4 |
# Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 |
# Licensed under the MIT License. See License.txt in the project root for |
| 6 |
# license information. |
| 7 |
# -------------------------------------------------------------------------- |
| 8 |
|
| 9 |
""" |
| 10 |
Low-level calls to REST end-points. |
| 11 |
|
| 12 |
Specific interfaces to the Data-lake Store filesystem layer and authentication code. |
| 13 |
""" |
| 14 |
|
| 15 |
# standard imports |
| 16 |
import logging |
| 17 |
import os |
| 18 |
import threading |
| 19 |
import time |
| 20 |
import uuid |
| 21 |
import platform |
| 22 |
import warnings |
| 23 |
import time |
| 24 |
import urllib.parse as urllib |
| 25 |
from .retry import ExponentialRetryPolicy |
| 26 |
|
| 27 |
# 3rd party imports |
| 28 |
import requests |
| 29 |
import requests.exceptions |
| 30 |
|
| 31 |
_http_cache = {} # Useful for MSAL. https://msal-python.readthedocs.io/en/latest/#msal.PublicClientApplication.params.http_cache |
| 32 |
|
| 33 |
# this is required due to github issue, to ensure we don't lose perf from openPySSL: https://github.com/pyca/pyopenssl/issues/625 |
| 34 |
def enforce_no_py_open_ssl(): |
| 35 |
try: |
| 36 |
from requests.packages.urllib3.contrib.pyopenssl import extract_from_urllib3 |
| 37 |
except ImportError: |
| 38 |
# in the case of debian/ubuntu system packages, the import is slightly different |
| 39 |
try: |
| 40 |
from urllib3.contrib.pyopenssl import extract_from_urllib3 |
| 41 |
except ImportError: |
| 42 |
# if OpenSSL is unavailable in both cases then there is no need to "undo" it. |
| 43 |
return |
| 44 |
extract_from_urllib3() |
| 45 |
|
| 46 |
# Suppress urllib3 warning when accessing pyopenssl. This module is being removed |
| 47 |
# soon, but we already handle its absence. |
| 48 |
with warnings.catch_warnings(): |
| 49 |
warnings.filterwarnings( |
| 50 |
"ignore", |
| 51 |
category=DeprecationWarning, |
| 52 |
message=r"'urllib3.contrib.pyopenssl' module is deprecated and will be removed.+", |
| 53 |
) |
| 54 |
enforce_no_py_open_ssl() |
| 55 |
|
| 56 |
from .exceptions import DatalakeBadOffsetException, DatalakeRESTException |
| 57 |
from .exceptions import FileNotFoundError, PermissionError |
| 58 |
from . import __version__ |
| 59 |
|
| 60 |
logger = logging.getLogger(__name__) |
| 61 |
|
| 62 |
default_store = os.environ.get('azure_data_lake_store_name', None) |
| 63 |
default_adls_suffix = os.environ.get('azure_data_lake_store_url_suffix', 'azuredatalakestore.net') |
| 64 |
|
| 65 |
# Constants |
| 66 |
DEFAULT_RESOURCE_ENDPOINT = "https://datalake.azure.net/" |
| 67 |
MAX_CONTENT_LENGTH = 2**16 |
| 68 |
|
| 69 |
# This is the maximum number of active pool connections |
| 70 |
# that are supported during a single operation (such as upload or download of a file). |
| 71 |
# This ensures that no connections are prematurely evicted, which has negative performance implications. |
| 72 |
MAX_POOL_CONNECTIONS = 1024 |
| 73 |
|
| 74 |
class DatalakeRESTInterface: |
| 75 |
""" Call factory for webHDFS endpoints on ADLS |
| 76 |
|
| 77 |
Parameters |
| 78 |
---------- |
| 79 |
store_name: str |
| 80 |
The name of the Data Lake Store account to execute operations against. |
| 81 |
token: dict |
| 82 |
from `auth()` or `refresh_token()` or other MSAL source |
| 83 |
url_suffix: str (None) |
| 84 |
Domain to send REST requests to. The end-point URL is constructed |
| 85 |
using this and the store_name. If None, use default. |
| 86 |
api_version: str (2018-09-01) |
| 87 |
The API version to target with requests. Changing this value will |
| 88 |
change the behavior of the requests, and can cause unexpected behavior or |
| 89 |
breaking changes. Changes to this value should be undergone with caution. |
| 90 |
req_timeout_s: float(60) |
| 91 |
This is the timeout for each requests library call. |
| 92 |
scopes: str (None) |
| 93 |
The scopes to use for the token. If not provided, the default https://datalake.azure.net//.default is used. |
| 94 |
""" |
| 95 |
|
| 96 |
ends = { |
| 97 |
# OP: (HTTP method, required fields, allowed fields) |
| 98 |
'APPEND': ('post', set(), {'append', 'offset', 'syncFlag', 'filesessionid', 'leaseid'}), |
| 99 |
'CHECKACCESS': ('get', set(), {'fsaction'}), |
| 100 |
'CONCAT': ('post', {'sources'}, {'sources'}), |
| 101 |
'MSCONCAT': ('post', set(), {'deleteSourceDirectory'}), |
| 102 |
'CREATE': ('put', set(), {'overwrite', 'write', 'syncFlag', 'filesessionid', 'leaseid'}), |
| 103 |
'DELETE': ('delete', set(), {'recursive'}), |
| 104 |
'GETCONTENTSUMMARY': ('get', set(), set()), |
| 105 |
'GETFILESTATUS': ('get', set(), set()), |
| 106 |
'LISTSTATUS': ('get', set(), {'listSize', 'listAfter'}), |
| 107 |
'MKDIRS': ('put', set(), set()), |
| 108 |
'OPEN': ('get', set(), {'offset', 'length', 'read', 'filesessionid'}), |
| 109 |
'RENAME': ('put', {'destination'}, {'destination'}), |
| 110 |
'SETOWNER': ('put', set(), {'owner', 'group'}), |
| 111 |
'SETPERMISSION': ('put', set(), {'permission'}), |
| 112 |
'SETEXPIRY': ('put', {'expiryOption'}, {'expiryOption', 'expireTime'}), |
| 113 |
'SETACL': ('put', {'aclSpec'}, {'aclSpec'}), |
| 114 |
'MODIFYACLENTRIES': ('put', {'aclSpec'}, {'aclSpec'}), |
| 115 |
'REMOVEACLENTRIES': ('put', {'aclSpec'}, {'aclSpec'}), |
| 116 |
'REMOVEACL': ('put', set(), set()), |
| 117 |
'MSGETACLSTATUS': ('get', set(), set()), |
| 118 |
'REMOVEDEFAULTACL': ('put', set(), set()) |
| 119 |
} |
| 120 |
|
| 121 |
def __init__(self, store_name=default_store, token_credential=None, scopes=None, url_suffix=default_adls_suffix, **kwargs): |
| 122 |
# in the case where an empty string is passed for the url suffix, it must be replaced with the default. |
| 123 |
url_suffix = url_suffix or default_adls_suffix |
| 124 |
self.local = threading.local() |
| 125 |
self.token_credential = token_credential |
| 126 |
self.scopes = scopes or "https://datalake.azure.net//.default" |
| 127 |
self.AccessToken = None |
| 128 |
|
| 129 |
# There is a case where the user can opt to exclude an API version, in which case |
| 130 |
# the service itself decides on the API version to use (it's default). |
| 131 |
self.api_version = kwargs.pop('api_version', '2018-09-01') |
| 132 |
self.req_timeout_s = kwargs.pop('req_timeout_s', 60) |
| 133 |
|
| 134 |
self.url = 'https://%s.%s/' % (store_name, url_suffix) |
| 135 |
|
| 136 |
self.webhdfs = 'webhdfs/v1/' |
| 137 |
self.extended_operations = 'webhdfsext/' |
| 138 |
self.user_agent = "python/{} ({}) {}/{} Azure-Data-Lake-Store-SDK-For-Python".format( |
| 139 |
platform.python_version(), |
| 140 |
platform.platform(), |
| 141 |
__name__, |
| 142 |
__version__) |
| 143 |
|
| 144 |
def get_refreshed_bearer_token(self): |
| 145 |
# Check if the token is about to expire in 300 seconds and refresh it if necessary |
| 146 |
if self.AccessToken is None or time.time() > self.AccessToken.expires_on - 300: |
| 147 |
self.AccessToken = self.token_credential.get_token(self.scopes) |
| 148 |
return self.AccessToken.token |
| 149 |
|
| 150 |
@property |
| 151 |
def session(self): |
| 152 |
bearer_token = self.get_refreshed_bearer_token() |
| 153 |
try: |
| 154 |
s = self.local.session |
| 155 |
s.headers['Authorization'] = "Bearer " + bearer_token |
| 156 |
except AttributeError: |
| 157 |
s = None |
| 158 |
if not s: |
| 159 |
adapter = requests.adapters.HTTPAdapter( |
| 160 |
pool_connections=MAX_POOL_CONNECTIONS, |
| 161 |
pool_maxsize=MAX_POOL_CONNECTIONS) |
| 162 |
s = requests.Session() |
| 163 |
s.mount(self.url, adapter) |
| 164 |
s.headers['Authorization'] = "Bearer " + bearer_token |
| 165 |
self.local.session = s |
| 166 |
return s |
| 167 |
|
| 168 |
def _log_request(self, method, url, op, path, params, headers, retry_count): |
| 169 |
msg = u"HTTP Request\n{} {}\n".format(method.upper(), url) |
| 170 |
param_str = u" ".join([u"{}={}".format(key, params[key]) for key in params]) |
| 171 |
msg += u"{} '{}' {}\n\n".format( |
| 172 |
op, path, param_str) |
| 173 |
msg += u"\n".join([u"{}: {}".format(header, headers[header]) |
| 174 |
for header in headers if header != 'Authorization']) |
| 175 |
msg += u"\nAuthorization header length:" + str(len(headers['Authorization'])) |
| 176 |
if retry_count > 0: |
| 177 |
msg += u"retry-count:{}".format(retry_count) |
| 178 |
logger.debug(msg) |
| 179 |
|
| 180 |
def _content_truncated(self, response): |
| 181 |
if 'content-length' not in response.headers: |
| 182 |
return False |
| 183 |
return int(response.headers['content-length']) > MAX_CONTENT_LENGTH |
| 184 |
|
| 185 |
def _log_response(self, response, payload=False): |
| 186 |
msg = u"HTTP Response\n{}\n{}".format( |
| 187 |
response.status_code, |
| 188 |
u"\n".join([u"{}: {}".format(header, response.headers[header]) |
| 189 |
for header in response.headers])) |
| 190 |
if payload: |
| 191 |
msg += u"\n\n{}".format(response.content[:MAX_CONTENT_LENGTH]) |
| 192 |
if self._content_truncated(response): |
| 193 |
msg += u"\n(Response body was truncated)" |
| 194 |
logger.debug(msg) |
| 195 |
|
| 196 |
def log_response_and_raise(self, response, exception, level=logging.ERROR): |
| 197 |
msg = u"Exception " + repr(exception) |
| 198 |
if response is not None: |
| 199 |
msg += u"\n{}\n{}".format( |
| 200 |
response.status_code, |
| 201 |
u"\n".join([ |
| 202 |
u"{}: {}".format(header, response.headers[header]) |
| 203 |
for header in response.headers])) |
| 204 |
msg += u"\n\n{}".format(response.content[:MAX_CONTENT_LENGTH]) |
| 205 |
if self._content_truncated(response): |
| 206 |
msg += u"\n(Response body was truncated)" |
| 207 |
logger.log(level, msg) |
| 208 |
raise exception |
| 209 |
|
| 210 |
def _is_json_response(self, response): |
| 211 |
if 'content-type' not in response.headers: |
| 212 |
return False |
| 213 |
return response.headers['content-type'].startswith('application/json') |
| 214 |
|
| 215 |
def call(self, op, path='', is_extended=False, expected_error_code=None, retry_policy=None, headers = {}, **kwargs): |
| 216 |
""" Execute a REST call |
| 217 |
|
| 218 |
Parameters |
| 219 |
---------- |
| 220 |
op: str |
| 221 |
webHDFS operation to perform, one of `DatalakeRESTInterface.ends` |
| 222 |
path: str |
| 223 |
filepath on the remote system |
| 224 |
is_extended: bool (False) |
| 225 |
Indicates if the API call comes from the webhdfs extensions path or the basic webhdfs path. |
| 226 |
By default, all requests target the official webhdfs path. A small subset of custom convenience |
| 227 |
methods specific to Azure Data Lake Store target the extension path (such as SETEXPIRY). |
| 228 |
expected_error_code: int |
| 229 |
Optionally indicates a specific, expected error code, if any. In the event that this error |
| 230 |
is returned, the exception will be logged to DEBUG instead of ERROR stream. The exception |
| 231 |
will still be raised, however, as it is expected that the caller will expect to handle it |
| 232 |
and do something different if it is raised. |
| 233 |
kwargs: dict |
| 234 |
other parameters, as defined by the webHDFS standard and |
| 235 |
https://msdn.microsoft.com/en-us/library/mt710547.aspx |
| 236 |
""" |
| 237 |
retry_policy = ExponentialRetryPolicy() if retry_policy is None else retry_policy |
| 238 |
if op not in self.ends: |
| 239 |
raise ValueError("No such op: %s", op) |
| 240 |
method, required, allowed = self.ends[op] |
| 241 |
allowed.add('api-version') |
| 242 |
data = kwargs.pop('data', b'') |
| 243 |
stream = kwargs.pop('stream', False) |
| 244 |
keys = set(kwargs) |
| 245 |
if required > keys: |
| 246 |
raise ValueError("Required parameters missing: %s", |
| 247 |
required - keys) |
| 248 |
if keys - allowed > set(): |
| 249 |
raise ValueError("Extra parameters given: %s", |
| 250 |
keys - allowed) |
| 251 |
params = {'OP': op} |
| 252 |
if self.api_version: |
| 253 |
params['api-version'] = self.api_version |
| 254 |
|
| 255 |
params.update(kwargs) |
| 256 |
|
| 257 |
if is_extended: |
| 258 |
url = self.url + self.extended_operations |
| 259 |
else: |
| 260 |
url = self.url + self.webhdfs |
| 261 |
url += urllib.quote(path) |
| 262 |
retry_count = -1 |
| 263 |
request_id = str(uuid.uuid1()) |
| 264 |
while True: |
| 265 |
retry_count += 1 |
| 266 |
last_exception = None |
| 267 |
try: |
| 268 |
response = self.__call_once(method=method, |
| 269 |
url=url, |
| 270 |
params=params, |
| 271 |
data=data, |
| 272 |
stream=stream, |
| 273 |
request_id=request_id, |
| 274 |
retry_count=retry_count, |
| 275 |
op=op, |
| 276 |
path=path, |
| 277 |
headers=headers, |
| 278 |
**kwargs) |
| 279 |
# Trigger download here so any errors can be retried. response.content is cached for future use. |
| 280 |
temp_download = response.content |
| 281 |
except requests.exceptions.RequestException as e: |
| 282 |
last_exception = e |
| 283 |
response = None |
| 284 |
|
| 285 |
request_successful = self.is_successful_response(response, last_exception) |
| 286 |
if request_successful or not retry_policy.should_retry(response, last_exception, retry_count): |
| 287 |
break |
| 288 |
|
| 289 |
if not request_successful and last_exception is not None: |
| 290 |
raise DatalakeRESTException('HTTP error: ' + repr(last_exception)) |
| 291 |
|
| 292 |
exception_log_level = logging.ERROR |
| 293 |
if expected_error_code and response.status_code == expected_error_code: |
| 294 |
logger.log(logging.DEBUG, 'Error code: {} was an expected potential error from the caller. Logging the exception to the debug stream'.format(response.status_code)) |
| 295 |
exception_log_level = logging.DEBUG |
| 296 |
|
| 297 |
if response.status_code == 403: |
| 298 |
self.log_response_and_raise(response, PermissionError(path), level=exception_log_level) |
| 299 |
elif response.status_code == 404: |
| 300 |
self.log_response_and_raise(response, FileNotFoundError(path), level=exception_log_level) |
| 301 |
elif response.status_code >= 400: |
| 302 |
err = DatalakeRESTException( |
| 303 |
'Data-lake REST exception: %s, %s' % (op, path)) |
| 304 |
if self._is_json_response(response): |
| 305 |
out = response.json() |
| 306 |
if 'RemoteException' in out: |
| 307 |
exception = out['RemoteException']['exception'] |
| 308 |
if exception == 'BadOffsetException': |
| 309 |
err = DatalakeBadOffsetException(path) |
| 310 |
self.log_response_and_raise(response, err, level=logging.DEBUG) |
| 311 |
self.log_response_and_raise(response, err, level=exception_log_level) |
| 312 |
else: |
| 313 |
self._log_response(response) |
| 314 |
|
| 315 |
if self._is_json_response(response): |
| 316 |
out = response.json() |
| 317 |
if out.get('boolean', True) is False: |
| 318 |
err = DatalakeRESTException( |
| 319 |
'Operation failed: %s, %s' % (op, path)) |
| 320 |
self.log_response_and_raise(response, err) |
| 321 |
return out |
| 322 |
return response |
| 323 |
|
| 324 |
def is_successful_response(self, response, exception): |
| 325 |
if exception is not None: |
| 326 |
return False |
| 327 |
if 100 <= response.status_code < 300: |
| 328 |
return True |
| 329 |
return False |
| 330 |
|
| 331 |
def __call_once(self, method, url, params, data, stream, request_id, retry_count, op, path='', headers={}, **kwargs): |
| 332 |
func = getattr(self.session, method) |
| 333 |
req_headers = {'Authorization': self.session.headers['Authorization']} |
| 334 |
req_headers['x-ms-client-request-id'] = request_id + "." + str(retry_count) |
| 335 |
req_headers['User-Agent'] = self.user_agent |
| 336 |
req_headers.update(headers) |
| 337 |
self._log_request(method, url, op, urllib.quote(path), kwargs, req_headers, retry_count) |
| 338 |
return func(url, params=params, headers=req_headers, data=data, stream=stream, timeout=self.req_timeout_s) |
| 339 |
|
| 340 |
def __getstate__(self): |
| 341 |
state = self.__dict__.copy() |
| 342 |
state.pop('local', None) |
| 343 |
return state |
| 344 |
|
| 345 |
""" |
| 346 |
Not yet implemented (or not applicable) |
| 347 |
https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/WebHDFS.html |
| 348 |
|
| 349 |
GETFILECHECKSUM |
| 350 |
GETHOMEDIRECTORY |
| 351 |
GETDELEGATIONTOKEN n/a - use auth |
| 352 |
GETDELEGATIONTOKENS n/a - use auth |
| 353 |
GETXATTRS |
| 354 |
LISTXATTRS |
| 355 |
CREATESYMLINK n/a |
| 356 |
SETREPLICATION n/a |
| 357 |
SETTIMES |
| 358 |
RENEWDELEGATIONTOKEN n/a - use auth |
| 359 |
CANCELDELEGATIONTOKEN n/a - use auth |
| 360 |
CREATESNAPSHOT |
| 361 |
RENAMESNAPSHOT |
| 362 |
SETXATTR |
| 363 |
REMOVEXATTR |
| 364 |
""" |