Debian Codegraph @

adjutantclient/common/http.py

raw
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 import logging
17 import os
18
19 from keystoneauth1 import adapter
20 from keystoneauth1.identity import v3
21 from keystoneauth1 import session as ks_session
22 from oslo_utils import importutils
23 import requests
24
25 from adjutantclient._i18n import _
26 from adjutantclient import exc
27
28 LOG = logging.getLogger(__name__)
29 USER_AGENT = 'python-adjutantclient'
30 CHUNKSIZE = 1024 * 64 # 64kB
31 SENSITIVE_HEADERS = ('X-Auth-Token',)
32 osprofiler_web = importutils.try_import("osprofiler.web")
33
34
35 def get_response_body(resp):
36 body = resp.content
37 if 'application/json' in resp.headers.get('content-type', ''):
38 try:
39 body = resp.json()
40 except ValueError:
41 LOG.error('Could not decode response body as JSON')
42 else:
43 body = None
44 return body
45
46
47 def get_system_ca_file():
48 """Return path to system default CA file."""
49 # Standard CA file locations for Debian/Ubuntu, RedHat/Fedora,
50 # Suse, FreeBSD/OpenBSD, MacOSX, and the bundled ca
51 ca_path = ['/etc/ssl/certs/ca-certificates.crt',
52 '/etc/pki/tls/certs/ca-bundle.crt',
53 '/etc/ssl/ca-bundle.pem',
54 '/etc/ssl/cert.pem',
55 '/System/Library/OpenSSL/certs/cacert.pem',
56 requests.certs.where()]
57 for ca in ca_path:
58 LOG.debug("Looking for ca file %s", ca)
59 if os.path.exists(ca):
60 LOG.debug("Using ca file %s", ca)
61 return ca
62 LOG.warning("System ca file could not be found.")
63
64
65 class SessionClient(adapter.LegacyJsonAdapter):
66 """HTTP client based on Keystone client session."""
67
68 def request(self, url, method, **kwargs):
69 redirect = kwargs.get('redirect')
70 kwargs.setdefault('user_agent', USER_AGENT)
71
72 if 'data' in kwargs:
73 kwargs['json'] = kwargs.pop('data')
74
75 resp, body = super(SessionClient, self).request(
76 url, method,
77 raise_exc=False,
78 **kwargs)
79
80 if 400 <= resp.status_code < 600:
81 raise exc.from_response(resp)
82 elif resp.status_code in (301, 302, 305):
83 if redirect:
84 location = resp.headers.get('location')
85 path = self.strip_endpoint(location)
86 resp = self.request(path, method, **kwargs)
87 elif resp.status_code == 300:
88 raise exc.from_response(resp)
89
90 return resp
91
92 def credentials_headers(self):
93 return {}
94
95 def strip_endpoint(self, location):
96 if location is None:
97 message = _("Location not returned with 302")
98 raise exc.InvalidEndpoint(message=message)
99 if (self.endpoint_override is not None and
100 location.lower().startswith(self.endpoint_override.lower())):
101 return location[len(self.endpoint_override):]
102 else:
103 return location
104
105
106 def _construct_http_client(endpoint=None, username=None, password=None,
107 include_pass=None, endpoint_type=None,
108 auth_url=None, **kwargs):
109 session = kwargs.pop('session', None)
110 auth = kwargs.pop('auth', None)
111
112 if not session:
113 if not auth and password:
114 auth = v3.Password(auth_url=auth_url,
115 username=username,
116 password=password,
117 **kwargs)
118 kwargs.pop('project_id', None)
119 kwargs.pop('project_name', None)
120 kwargs.pop('domain_id', None)
121 kwargs.pop('domain_name', None)
122 kwargs.pop('project_domain_id', None)
123 kwargs.pop('project_domain_name', None)
124 kwargs.pop('user_domain_id', None)
125 kwargs.pop('user_domain_name', None)
126
127 ca_path = kwargs.get('ca_file') or get_system_ca_file()
128 session = ks_session.Session(auth=auth,
129 verify=ca_path)
130
131 if 'endpoint_override' not in kwargs and endpoint:
132 kwargs['endpoint_override'] = endpoint
133
134 if 'service_type' not in kwargs:
135 kwargs['service_type'] = 'admin-logic'
136
137 if 'interface' not in kwargs and endpoint_type:
138 kwargs['interface'] = endpoint_type
139
140 return SessionClient(session, auth=auth, **kwargs)