| 1 |
# Copyright 2012 OpenStack Foundation. |
| 2 |
# All Rights Reserved |
| 3 |
# |
| 4 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 |
# not use this file except in compliance with the License. You may obtain |
| 6 |
# a copy of the License at |
| 7 |
# |
| 8 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
# |
| 10 |
# Unless required by applicable law or agreed to in writing, software |
| 11 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 |
# License for the specific language governing permissions and limitations |
| 14 |
# under the License. |
| 15 |
# |
| 16 |
|
| 17 |
import logging |
| 18 |
import os |
| 19 |
|
| 20 |
import debtcollector.renames |
| 21 |
from keystoneauth1 import access |
| 22 |
from keystoneauth1 import adapter |
| 23 |
from oslo_serialization import jsonutils |
| 24 |
from oslo_utils import importutils |
| 25 |
import requests |
| 26 |
|
| 27 |
from neutronclient._i18n import _ |
| 28 |
from neutronclient.common import exceptions |
| 29 |
from neutronclient.common import utils |
| 30 |
|
| 31 |
osprofiler_web = importutils.try_import("osprofiler.web") |
| 32 |
|
| 33 |
_logger = logging.getLogger(__name__) |
| 34 |
|
| 35 |
if os.environ.get('NEUTRONCLIENT_DEBUG'): |
| 36 |
ch = logging.StreamHandler() |
| 37 |
_logger.setLevel(logging.DEBUG) |
| 38 |
_logger.addHandler(ch) |
| 39 |
_requests_log_level = logging.DEBUG |
| 40 |
else: |
| 41 |
_requests_log_level = logging.WARNING |
| 42 |
|
| 43 |
logging.getLogger("requests").setLevel(_requests_log_level) |
| 44 |
MAX_URI_LEN = 8192 |
| 45 |
USER_AGENT = 'python-neutronclient' |
| 46 |
REQ_ID_HEADER = 'X-OpenStack-Request-ID' |
| 47 |
|
| 48 |
|
| 49 |
class HTTPClient(object): |
| 50 |
"""Handles the REST calls and responses, include authn.""" |
| 51 |
|
| 52 |
CONTENT_TYPE = 'application/json' |
| 53 |
|
| 54 |
@debtcollector.renames.renamed_kwarg( |
| 55 |
'tenant_id', 'project_id', replace=True) |
| 56 |
@debtcollector.renames.renamed_kwarg( |
| 57 |
'tenant_name', 'project_name', replace=True) |
| 58 |
def __init__(self, username=None, user_id=None, |
| 59 |
project_name=None, project_id=None, |
| 60 |
password=None, auth_url=None, |
| 61 |
token=None, region_name=None, timeout=None, |
| 62 |
endpoint_url=None, insecure=False, |
| 63 |
endpoint_type='publicURL', |
| 64 |
auth_strategy='keystone', ca_cert=None, cert=None, |
| 65 |
log_credentials=False, service_type='network', |
| 66 |
global_request_id=None, **kwargs): |
| 67 |
|
| 68 |
self.username = username |
| 69 |
self.user_id = user_id |
| 70 |
self.project_name = project_name |
| 71 |
self.project_id = project_id |
| 72 |
self.password = password |
| 73 |
self.auth_url = auth_url.rstrip('/') if auth_url else None |
| 74 |
self.service_type = service_type |
| 75 |
self.endpoint_type = endpoint_type |
| 76 |
self.region_name = region_name |
| 77 |
self.timeout = timeout |
| 78 |
self.auth_token = token |
| 79 |
self.auth_tenant_id = None |
| 80 |
self.auth_user_id = None |
| 81 |
self.endpoint_url = endpoint_url |
| 82 |
self.auth_strategy = auth_strategy |
| 83 |
self.log_credentials = log_credentials |
| 84 |
self.global_request_id = global_request_id |
| 85 |
self.cert = cert |
| 86 |
if insecure: |
| 87 |
self.verify_cert = False |
| 88 |
else: |
| 89 |
self.verify_cert = ca_cert if ca_cert else True |
| 90 |
|
| 91 |
def _cs_request(self, *args, **kwargs): |
| 92 |
kargs = {} |
| 93 |
kargs.setdefault('headers', kwargs.get('headers', {})) |
| 94 |
kargs['headers']['User-Agent'] = USER_AGENT |
| 95 |
|
| 96 |
if 'body' in kwargs: |
| 97 |
kargs['body'] = kwargs['body'] |
| 98 |
|
| 99 |
if self.log_credentials: |
| 100 |
log_kargs = kargs |
| 101 |
else: |
| 102 |
log_kargs = self._strip_credentials(kargs) |
| 103 |
|
| 104 |
utils.http_log_req(_logger, args, log_kargs) |
| 105 |
try: |
| 106 |
resp, body = self.request(*args, **kargs) |
| 107 |
except requests.exceptions.SSLError as e: |
| 108 |
raise exceptions.SslCertificateValidationError(reason=str(e)) |
| 109 |
except Exception as e: |
| 110 |
# Wrap the low-level connection error (socket timeout, redirect |
| 111 |
# limit, decompression error, etc) into our custom high-level |
| 112 |
# connection exception (it is excepted in the upper layers of code) |
| 113 |
_logger.debug("throwing ConnectionFailed : %s", e) |
| 114 |
raise exceptions.ConnectionFailed(reason=str(e)) |
| 115 |
utils.http_log_resp(_logger, resp, body) |
| 116 |
|
| 117 |
# log request-id for each api call |
| 118 |
request_id = resp.headers.get('x-openstack-request-id') |
| 119 |
if request_id: |
| 120 |
_logger.debug('%(method)s call to neutron for ' |
| 121 |
'%(url)s used request id ' |
| 122 |
'%(response_request_id)s', |
| 123 |
{'method': resp.request.method, |
| 124 |
'url': resp.url, |
| 125 |
'response_request_id': request_id}) |
| 126 |
|
| 127 |
if resp.status_code == 401: |
| 128 |
raise exceptions.Unauthorized(message=body) |
| 129 |
return resp, body |
| 130 |
|
| 131 |
def _strip_credentials(self, kwargs): |
| 132 |
if kwargs.get('body') and self.password: |
| 133 |
log_kwargs = kwargs.copy() |
| 134 |
log_kwargs['body'] = kwargs['body'].replace(self.password, |
| 135 |
'REDACTED') |
| 136 |
return log_kwargs |
| 137 |
else: |
| 138 |
return kwargs |
| 139 |
|
| 140 |
def authenticate_and_fetch_endpoint_url(self): |
| 141 |
if not self.auth_token: |
| 142 |
self.authenticate() |
| 143 |
elif not self.endpoint_url: |
| 144 |
self.endpoint_url = self._get_endpoint_url() |
| 145 |
|
| 146 |
def request(self, url, method, body=None, headers=None, **kwargs): |
| 147 |
"""Request without authentication.""" |
| 148 |
|
| 149 |
content_type = kwargs.pop('content_type', None) or 'application/json' |
| 150 |
headers = headers or {} |
| 151 |
headers.setdefault('Accept', content_type) |
| 152 |
|
| 153 |
if body: |
| 154 |
headers.setdefault('Content-Type', content_type) |
| 155 |
|
| 156 |
if self.global_request_id: |
| 157 |
headers.setdefault(REQ_ID_HEADER, self.global_request_id) |
| 158 |
|
| 159 |
headers['User-Agent'] = USER_AGENT |
| 160 |
# NOTE(dbelova): osprofiler_web.get_trace_id_headers does not add any |
| 161 |
# headers in case if osprofiler is not initialized. |
| 162 |
if osprofiler_web: |
| 163 |
headers.update(osprofiler_web.get_trace_id_headers()) |
| 164 |
|
| 165 |
resp = requests.request( |
| 166 |
method, |
| 167 |
url, |
| 168 |
data=body, |
| 169 |
headers=headers, |
| 170 |
verify=self.verify_cert, |
| 171 |
cert=self.cert, |
| 172 |
timeout=self.timeout, |
| 173 |
**kwargs) |
| 174 |
|
| 175 |
return resp, resp.text |
| 176 |
|
| 177 |
def _check_uri_length(self, action): |
| 178 |
uri_len = len(self.endpoint_url) + len(action) |
| 179 |
if uri_len > MAX_URI_LEN: |
| 180 |
raise exceptions.RequestURITooLong( |
| 181 |
excess=uri_len - MAX_URI_LEN) |
| 182 |
|
| 183 |
def do_request(self, url, method, **kwargs): |
| 184 |
# Ensure client always has correct uri - do not guesstimate anything |
| 185 |
self.authenticate_and_fetch_endpoint_url() |
| 186 |
self._check_uri_length(url) |
| 187 |
|
| 188 |
# Perform the request once. If we get a 401 back then it |
| 189 |
# might be because the auth token expired, so try to |
| 190 |
# re-authenticate and try again. If it still fails, bail. |
| 191 |
try: |
| 192 |
kwargs['headers'] = kwargs.get('headers') or {} |
| 193 |
if self.auth_token is None: |
| 194 |
self.auth_token = "" |
| 195 |
kwargs['headers']['X-Auth-Token'] = self.auth_token |
| 196 |
resp, body = self._cs_request(self.endpoint_url + url, method, |
| 197 |
**kwargs) |
| 198 |
return resp, body |
| 199 |
except exceptions.Unauthorized: |
| 200 |
self.authenticate() |
| 201 |
kwargs['headers'] = kwargs.get('headers') or {} |
| 202 |
kwargs['headers']['X-Auth-Token'] = self.auth_token |
| 203 |
resp, body = self._cs_request( |
| 204 |
self.endpoint_url + url, method, **kwargs) |
| 205 |
return resp, body |
| 206 |
|
| 207 |
def _extract_service_catalog(self, body): |
| 208 |
"""Set the client's service catalog from the response data.""" |
| 209 |
self.auth_ref = access.create(body=body) |
| 210 |
self.service_catalog = self.auth_ref.service_catalog |
| 211 |
self.auth_token = self.auth_ref.auth_token |
| 212 |
self.auth_tenant_id = self.auth_ref.tenant_id |
| 213 |
self.auth_user_id = self.auth_ref.user_id |
| 214 |
|
| 215 |
if not self.endpoint_url: |
| 216 |
self.endpoint_url = self.service_catalog.url_for( |
| 217 |
region_name=self.region_name, |
| 218 |
service_type=self.service_type, |
| 219 |
interface=self.endpoint_type) |
| 220 |
|
| 221 |
def _authenticate_keystone(self): |
| 222 |
if self.user_id: |
| 223 |
creds = {'userId': self.user_id, |
| 224 |
'password': self.password} |
| 225 |
else: |
| 226 |
creds = {'username': self.username, |
| 227 |
'password': self.password} |
| 228 |
|
| 229 |
if self.project_id: |
| 230 |
body = {'auth': {'passwordCredentials': creds, |
| 231 |
'tenantId': self.project_id, }, } |
| 232 |
else: |
| 233 |
body = {'auth': {'passwordCredentials': creds, |
| 234 |
'tenantName': self.project_name, }, } |
| 235 |
|
| 236 |
if self.auth_url is None: |
| 237 |
raise exceptions.NoAuthURLProvided() |
| 238 |
|
| 239 |
token_url = self.auth_url + "/tokens" |
| 240 |
resp, resp_body = self._cs_request(token_url, "POST", |
| 241 |
body=jsonutils.dumps(body), |
| 242 |
content_type="application/json", |
| 243 |
allow_redirects=True) |
| 244 |
if resp.status_code != 200: |
| 245 |
raise exceptions.Unauthorized(message=resp_body) |
| 246 |
if resp_body: |
| 247 |
try: |
| 248 |
resp_body = jsonutils.loads(resp_body) |
| 249 |
except ValueError: |
| 250 |
pass |
| 251 |
else: |
| 252 |
resp_body = None |
| 253 |
self._extract_service_catalog(resp_body) |
| 254 |
|
| 255 |
def _authenticate_noauth(self): |
| 256 |
if not self.endpoint_url: |
| 257 |
message = _('For "noauth" authentication strategy, the endpoint ' |
| 258 |
'must be specified either in the constructor or ' |
| 259 |
'using --os-url') |
| 260 |
raise exceptions.Unauthorized(message=message) |
| 261 |
|
| 262 |
def authenticate(self): |
| 263 |
if self.auth_strategy == 'keystone': |
| 264 |
self._authenticate_keystone() |
| 265 |
elif self.auth_strategy == 'noauth': |
| 266 |
self._authenticate_noauth() |
| 267 |
else: |
| 268 |
err_msg = _('Unknown auth strategy: %s') % self.auth_strategy |
| 269 |
raise exceptions.Unauthorized(message=err_msg) |
| 270 |
|
| 271 |
def _get_endpoint_url(self): |
| 272 |
if self.auth_url is None: |
| 273 |
raise exceptions.NoAuthURLProvided() |
| 274 |
|
| 275 |
url = self.auth_url + '/tokens/%s/endpoints' % self.auth_token |
| 276 |
try: |
| 277 |
resp, body = self._cs_request(url, "GET") |
| 278 |
except exceptions.Unauthorized: |
| 279 |
# rollback to authenticate() to handle case when neutron client |
| 280 |
# is initialized just before the token is expired |
| 281 |
self.authenticate() |
| 282 |
return self.endpoint_url |
| 283 |
|
| 284 |
body = jsonutils.loads(body) |
| 285 |
for endpoint in body.get('endpoints', []): |
| 286 |
if (endpoint['type'] == 'network' and |
| 287 |
endpoint.get('region') == self.region_name): |
| 288 |
if self.endpoint_type not in endpoint: |
| 289 |
raise exceptions.EndpointTypeNotFound( |
| 290 |
type_=self.endpoint_type) |
| 291 |
return endpoint[self.endpoint_type] |
| 292 |
|
| 293 |
raise exceptions.EndpointNotFound() |
| 294 |
|
| 295 |
def get_auth_info(self): |
| 296 |
return {'auth_token': self.auth_token, |
| 297 |
'auth_tenant_id': self.auth_tenant_id, |
| 298 |
'auth_user_id': self.auth_user_id, |
| 299 |
'endpoint_url': self.endpoint_url} |
| 300 |
|
| 301 |
def get_auth_ref(self): |
| 302 |
return getattr(self, 'auth_ref', None) |
| 303 |
|
| 304 |
|
| 305 |
class SessionClient(adapter.Adapter): |
| 306 |
|
| 307 |
def request(self, *args, **kwargs): |
| 308 |
kwargs.setdefault('authenticated', False) |
| 309 |
kwargs.setdefault('raise_exc', False) |
| 310 |
|
| 311 |
content_type = kwargs.pop('content_type', None) or 'application/json' |
| 312 |
|
| 313 |
headers = kwargs.get('headers') or {} |
| 314 |
headers.setdefault('Accept', content_type) |
| 315 |
|
| 316 |
# NOTE(dbelova): osprofiler_web.get_trace_id_headers does not add any |
| 317 |
# headers in case if osprofiler is not initialized. |
| 318 |
if osprofiler_web: |
| 319 |
headers.update(osprofiler_web.get_trace_id_headers()) |
| 320 |
|
| 321 |
try: |
| 322 |
kwargs.setdefault('data', kwargs.pop('body')) |
| 323 |
except KeyError: |
| 324 |
pass |
| 325 |
|
| 326 |
if kwargs.get('data'): |
| 327 |
headers.setdefault('Content-Type', content_type) |
| 328 |
|
| 329 |
kwargs['headers'] = headers |
| 330 |
resp = super(SessionClient, self).request(*args, **kwargs) |
| 331 |
return resp, resp.text |
| 332 |
|
| 333 |
def _check_uri_length(self, url): |
| 334 |
uri_len = len(self.endpoint_url) + len(url) |
| 335 |
if uri_len > MAX_URI_LEN: |
| 336 |
raise exceptions.RequestURITooLong( |
| 337 |
excess=uri_len - MAX_URI_LEN) |
| 338 |
|
| 339 |
def do_request(self, url, method, **kwargs): |
| 340 |
kwargs.setdefault('authenticated', True) |
| 341 |
self._check_uri_length(url) |
| 342 |
return self.request(url, method, **kwargs) |
| 343 |
|
| 344 |
@property |
| 345 |
def endpoint_url(self): |
| 346 |
# NOTE(jamielennox): This is used purely by the CLI and should be |
| 347 |
# removed when the CLI gets smarter. |
| 348 |
return self.get_endpoint() |
| 349 |
|
| 350 |
@property |
| 351 |
def auth_token(self): |
| 352 |
# NOTE(jamielennox): This is used purely by the CLI and should be |
| 353 |
# removed when the CLI gets smarter. |
| 354 |
return self.get_token() |
| 355 |
|
| 356 |
def authenticate(self): |
| 357 |
# NOTE(jamielennox): This is used purely by the CLI and should be |
| 358 |
# removed when the CLI gets smarter. |
| 359 |
self.get_token() |
| 360 |
|
| 361 |
def get_auth_info(self): |
| 362 |
auth_info = {'auth_token': self.auth_token, |
| 363 |
'endpoint_url': self.endpoint_url} |
| 364 |
|
| 365 |
# NOTE(jamielennox): This is the best we can do here. It will work |
| 366 |
# with identity plugins which is the primary case but we should |
| 367 |
# deprecate it's usage as much as possible. |
| 368 |
try: |
| 369 |
get_access = (self.auth or self.session.auth).get_access |
| 370 |
except AttributeError: |
| 371 |
pass |
| 372 |
else: |
| 373 |
auth_ref = get_access(self.session) |
| 374 |
|
| 375 |
auth_info['auth_tenant_id'] = auth_ref.project_id |
| 376 |
auth_info['auth_user_id'] = auth_ref.user_id |
| 377 |
|
| 378 |
return auth_info |
| 379 |
|
| 380 |
def get_auth_ref(self): |
| 381 |
return self.session.auth.get_auth_ref(self.session) |
| 382 |
|
| 383 |
|
| 384 |
# FIXME(bklei): Should refactor this to use kwargs and only |
| 385 |
# explicitly list arguments that are not None. |
| 386 |
@debtcollector.renames.renamed_kwarg('tenant_id', 'project_id', replace=True) |
| 387 |
@debtcollector.renames.renamed_kwarg( |
| 388 |
'tenant_name', 'project_name', replace=True) |
| 389 |
def construct_http_client(username=None, |
| 390 |
user_id=None, |
| 391 |
project_name=None, |
| 392 |
project_id=None, |
| 393 |
password=None, |
| 394 |
auth_url=None, |
| 395 |
token=None, |
| 396 |
region_name=None, |
| 397 |
timeout=None, |
| 398 |
endpoint_url=None, |
| 399 |
insecure=False, |
| 400 |
endpoint_type='public', |
| 401 |
log_credentials=None, |
| 402 |
auth_strategy='keystone', |
| 403 |
ca_cert=None, |
| 404 |
cert=None, |
| 405 |
service_type='network', |
| 406 |
session=None, |
| 407 |
global_request_id=None, |
| 408 |
**kwargs): |
| 409 |
|
| 410 |
if session: |
| 411 |
kwargs.setdefault('user_agent', USER_AGENT) |
| 412 |
kwargs.setdefault('interface', endpoint_type) |
| 413 |
return SessionClient(session=session, |
| 414 |
service_type=service_type, |
| 415 |
region_name=region_name, |
| 416 |
global_request_id=global_request_id, |
| 417 |
**kwargs) |
| 418 |
else: |
| 419 |
# FIXME(bklei): username and password are now optional. Need |
| 420 |
# to test that they were provided in this mode. Should also |
| 421 |
# refactor to use kwargs. |
| 422 |
return HTTPClient(username=username, |
| 423 |
password=password, |
| 424 |
project_id=project_id, |
| 425 |
project_name=project_name, |
| 426 |
user_id=user_id, |
| 427 |
auth_url=auth_url, |
| 428 |
token=token, |
| 429 |
endpoint_url=endpoint_url, |
| 430 |
insecure=insecure, |
| 431 |
timeout=timeout, |
| 432 |
region_name=region_name, |
| 433 |
endpoint_type=endpoint_type, |
| 434 |
service_type=service_type, |
| 435 |
ca_cert=ca_cert, |
| 436 |
cert=cert, |
| 437 |
log_credentials=log_credentials, |
| 438 |
auth_strategy=auth_strategy, |
| 439 |
global_request_id=global_request_id) |