OpenStack Storage (Swift) Client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

2005 lines
81 KiB

  1. # Copyright (c) 2010-2012 OpenStack, LLC.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. # implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. OpenStack Swift client library used internally
  17. """
  18. import socket
  19. import re
  20. import requests
  21. import logging
  22. import warnings
  23. from distutils.version import StrictVersion
  24. from requests.exceptions import RequestException, SSLError
  25. from six.moves import http_client
  26. from six.moves.urllib.parse import quote as _quote, unquote
  27. from six.moves.urllib.parse import urljoin, urlparse, urlunparse
  28. from time import sleep, time
  29. import six
  30. from swiftclient import version as swiftclient_version
  31. from swiftclient.exceptions import ClientException
  32. from swiftclient.utils import (
  33. iter_wrapper, LengthWrapper, ReadableToIterable, parse_api_response,
  34. get_body)
  35. # Default is 100, increase to 256
  36. http_client._MAXHEADERS = 256
  37. VERSIONFUL_AUTH_PATH = re.compile(r'v[2-3](?:\.0)?$')
  38. AUTH_VERSIONS_V1 = ('1.0', '1', 1)
  39. AUTH_VERSIONS_V2 = ('2.0', '2', 2)
  40. AUTH_VERSIONS_V3 = ('3.0', '3', 3)
  41. USER_METADATA_TYPE = tuple('x-%s-meta-' % type_ for type_ in
  42. ('container', 'account', 'object'))
  43. URI_PATTERN_INFO = re.compile(r'/info')
  44. URI_PATTERN_VERSION = re.compile(r'\/v\d+\.?\d*(\/.*)?')
  45. try:
  46. from logging import NullHandler
  47. except ImportError:
  48. # Added in Python 2.7
  49. class NullHandler(logging.Handler):
  50. def handle(self, record):
  51. pass
  52. def emit(self, record):
  53. pass
  54. def createLock(self):
  55. self.lock = None
  56. ksexceptions = ksclient_v2 = ksclient_v3 = ksa_v3 = None
  57. try:
  58. from keystoneclient import exceptions as ksexceptions
  59. # prevent keystoneclient warning us that it has no log handlers
  60. logging.getLogger('keystoneclient').addHandler(NullHandler())
  61. from keystoneclient.v2_0 import client as ksclient_v2
  62. except ImportError:
  63. pass
  64. try:
  65. from keystoneclient.v3 import client as ksclient_v3
  66. from keystoneauth1.identity import v3 as ksa_v3
  67. from keystoneauth1 import session as ksa_session
  68. from keystoneauth1 import exceptions as ksauthexceptions
  69. except ImportError:
  70. pass
  71. # requests version 1.2.3 try to encode headers in ascii, preventing
  72. # utf-8 encoded header to be 'prepared'. This also affects all
  73. # (or at least most) versions of requests on py3
  74. if StrictVersion(requests.__version__) < StrictVersion('2.0.0') \
  75. or not six.PY2:
  76. from requests.structures import CaseInsensitiveDict
  77. def prepare_unicode_headers(self, headers):
  78. if headers:
  79. self.headers = CaseInsensitiveDict(headers)
  80. else:
  81. self.headers = CaseInsensitiveDict()
  82. requests.models.PreparedRequest.prepare_headers = prepare_unicode_headers
  83. logger = logging.getLogger("swiftclient")
  84. logger.addHandler(NullHandler())
  85. #: Default behaviour is to redact header values known to contain secrets,
  86. #: such as ``X-Auth-Key`` and ``X-Auth-Token``. Up to the first 16 chars
  87. #: may be revealed.
  88. #:
  89. #: To disable, set the value of ``redact_sensitive_headers`` to ``False``.
  90. #:
  91. #: When header redaction is enabled, ``reveal_sensitive_prefix`` configures the
  92. #: maximum length of any sensitive header data sent to the logs. If the header
  93. #: is less than twice this length, only ``int(len(value)/2)`` chars will be
  94. #: logged; if it is less than 15 chars long, even less will be logged.
  95. logger_settings = {
  96. 'redact_sensitive_headers': True,
  97. 'reveal_sensitive_prefix': 16
  98. }
  99. #: A list of sensitive headers to redact in logs. Note that when extending this
  100. #: list, the header names must be added in all lower case.
  101. LOGGER_SENSITIVE_HEADERS = [
  102. 'x-auth-token', 'x-auth-key', 'x-service-token', 'x-storage-token',
  103. 'x-account-meta-temp-url-key', 'x-account-meta-temp-url-key-2',
  104. 'x-container-meta-temp-url-key', 'x-container-meta-temp-url-key-2',
  105. 'set-cookie'
  106. ]
  107. def safe_value(name, value):
  108. """
  109. Only show up to logger_settings['reveal_sensitive_prefix'] characters
  110. from a sensitive header.
  111. :param name: Header name
  112. :param value: Header value
  113. :return: Safe header value
  114. """
  115. if name.lower() in LOGGER_SENSITIVE_HEADERS:
  116. prefix_length = logger_settings.get('reveal_sensitive_prefix', 16)
  117. prefix_length = int(
  118. min(prefix_length, (len(value) ** 2) / 32, len(value) / 2)
  119. )
  120. redacted_value = value[0:prefix_length]
  121. return redacted_value + '...'
  122. return value
  123. def scrub_headers(headers):
  124. """
  125. Redact header values that can contain sensitive information that
  126. should not be logged.
  127. :param headers: Either a dict or an iterable of two-element tuples
  128. :return: Safe dictionary of headers with sensitive information removed
  129. """
  130. if isinstance(headers, dict):
  131. headers = headers.items()
  132. headers = [
  133. (parse_header_string(key), parse_header_string(val))
  134. for (key, val) in headers
  135. ]
  136. if not logger_settings.get('redact_sensitive_headers', True):
  137. return dict(headers)
  138. if logger_settings.get('reveal_sensitive_prefix', 16) < 0:
  139. logger_settings['reveal_sensitive_prefix'] = 16
  140. return {key: safe_value(key, val) for (key, val) in headers}
  141. def http_log(args, kwargs, resp, body):
  142. if not logger.isEnabledFor(logging.INFO):
  143. return
  144. # create and log equivalent curl command
  145. string_parts = ['curl -i']
  146. for element in args:
  147. if element == 'HEAD':
  148. string_parts.append(' -I')
  149. elif element in ('GET', 'POST', 'PUT'):
  150. string_parts.append(' -X %s' % element)
  151. else:
  152. string_parts.append(' %s' % parse_header_string(element))
  153. if 'headers' in kwargs:
  154. headers = scrub_headers(kwargs['headers'])
  155. for element in headers:
  156. header = ' -H "%s: %s"' % (element, headers[element])
  157. string_parts.append(header)
  158. # log response as debug if good, or info if error
  159. if resp.status < 300:
  160. log_method = logger.debug
  161. else:
  162. log_method = logger.info
  163. log_method("REQ: %s", "".join(string_parts))
  164. log_method("RESP STATUS: %s %s", resp.status, resp.reason)
  165. log_method("RESP HEADERS: %s", scrub_headers(resp.getheaders()))
  166. if body:
  167. resp_headers = resp_header_dict(resp)
  168. nbody = get_body(resp_headers, body)
  169. log_method("RESP BODY: %s", nbody)
  170. def parse_header_string(data):
  171. if not isinstance(data, (six.text_type, six.binary_type)):
  172. data = str(data)
  173. if six.PY2:
  174. if isinstance(data, six.text_type):
  175. # Under Python2 requests only returns binary_type, but if we get
  176. # some stray text_type input, this should prevent unquote from
  177. # interpreting %-encoded data as raw code-points.
  178. data = data.encode('utf8')
  179. try:
  180. unquoted = unquote(data).decode('utf8')
  181. except UnicodeDecodeError:
  182. try:
  183. return data.decode('utf8')
  184. except UnicodeDecodeError:
  185. return quote(data).decode('utf8')
  186. else:
  187. if isinstance(data, six.binary_type):
  188. # Under Python3 requests only returns text_type and tosses (!) the
  189. # rest of the headers. If that ever changes, this should be a sane
  190. # approach.
  191. try:
  192. data = data.decode('ascii')
  193. except UnicodeDecodeError:
  194. data = quote(data)
  195. try:
  196. unquoted = unquote(data, errors='strict')
  197. except UnicodeDecodeError:
  198. return data
  199. return unquoted
  200. def quote(value, safe='/'):
  201. """
  202. Patched version of urllib.quote that encodes utf8 strings before quoting.
  203. On Python 3, call directly urllib.parse.quote().
  204. """
  205. if six.PY3:
  206. return _quote(value, safe=safe)
  207. return _quote(encode_utf8(value), safe)
  208. def encode_utf8(value):
  209. if type(value) in six.integer_types + (float, bool):
  210. # As of requests 2.11.0, headers must be byte- or unicode-strings.
  211. # Convert some known-good types as a convenience for developers.
  212. # Note that we *don't* convert subclasses, as they may have overriddden
  213. # __str__ or __repr__.
  214. # See https://github.com/kennethreitz/requests/pull/3366 for more info
  215. value = str(value)
  216. if isinstance(value, six.text_type):
  217. value = value.encode('utf8')
  218. return value
  219. def encode_meta_headers(headers):
  220. """Only encode metadata headers keys"""
  221. ret = {}
  222. for header, value in headers.items():
  223. value = encode_utf8(value)
  224. header = header.lower()
  225. if (isinstance(header, six.string_types) and
  226. header.startswith(USER_METADATA_TYPE)):
  227. header = encode_utf8(header)
  228. ret[header] = value
  229. return ret
  230. class _ObjectBody(object):
  231. """
  232. Readable and iterable object body response wrapper.
  233. """
  234. def __init__(self, resp, chunk_size):
  235. """
  236. Wrap the underlying response
  237. :param resp: the response to wrap
  238. :param chunk_size: number of bytes to return each iteration/next call
  239. """
  240. self.resp = resp
  241. self.chunk_size = chunk_size
  242. def read(self, length=None):
  243. return self.resp.read(length)
  244. def __iter__(self):
  245. return self
  246. def next(self):
  247. buf = self.read(self.chunk_size)
  248. if not buf:
  249. raise StopIteration()
  250. return buf
  251. def __next__(self):
  252. return self.next()
  253. def close(self):
  254. self.resp.close()
  255. class _RetryBody(_ObjectBody):
  256. """
  257. Wrapper for object body response which triggers a retry
  258. (from offset) if the connection is dropped after partially
  259. downloading the object.
  260. """
  261. def __init__(self, resp, connection, container, obj,
  262. resp_chunk_size=None, query_string=None, response_dict=None,
  263. headers=None):
  264. """
  265. Wrap the underlying response
  266. :param resp: the response to wrap
  267. :param connection: Connection class instance
  268. :param container: the name of the container the object is in
  269. :param obj: the name of object we are downloading
  270. :param resp_chunk_size: if defined, chunk size of data to read
  271. :param query_string: if set will be appended with '?' to generated path
  272. :param response_dict: an optional dictionary into which to place
  273. the response - status, reason and headers
  274. :param headers: an optional dictionary with additional headers to
  275. include in the request
  276. """
  277. super(_RetryBody, self).__init__(resp, resp_chunk_size)
  278. self.expected_length = int(self.resp.getheader('Content-Length'))
  279. self.conn = connection
  280. self.container = container
  281. self.obj = obj
  282. self.query_string = query_string
  283. self.response_dict = response_dict
  284. self.headers = dict(headers) if headers is not None else {}
  285. self.bytes_read = 0
  286. def read(self, length=None):
  287. buf = None
  288. try:
  289. buf = self.resp.read(length)
  290. self.bytes_read += len(buf)
  291. except (socket.error, RequestException):
  292. if self.conn.attempts > self.conn.retries:
  293. raise
  294. if (not buf and self.bytes_read < self.expected_length and
  295. self.conn.attempts <= self.conn.retries):
  296. self.headers['Range'] = 'bytes=%d-' % self.bytes_read
  297. self.headers['If-Match'] = self.resp.getheader('ETag')
  298. hdrs, body = self.conn._retry(None, get_object,
  299. self.container, self.obj,
  300. resp_chunk_size=self.chunk_size,
  301. query_string=self.query_string,
  302. response_dict=self.response_dict,
  303. headers=self.headers,
  304. attempts=self.conn.attempts)
  305. expected_range = 'bytes %d-%d/%d' % (
  306. self.bytes_read,
  307. self.expected_length - 1,
  308. self.expected_length)
  309. if 'content-range' not in hdrs:
  310. # Server didn't respond with partial content; manually seek
  311. logger.warning('Received 200 while retrying %s/%s; seeking...',
  312. self.container, self.obj)
  313. to_read = self.bytes_read
  314. while to_read > 0:
  315. buf = body.resp.read(min(to_read, self.chunk_size))
  316. to_read -= len(buf)
  317. elif hdrs['content-range'] != expected_range:
  318. msg = ('Expected range "%s" while retrying %s/%s '
  319. 'but got "%s"' % (expected_range, self.container,
  320. self.obj, hdrs['content-range']))
  321. raise ClientException(msg)
  322. self.resp = body.resp
  323. buf = self.read(length)
  324. return buf
  325. class HTTPConnection(object):
  326. def __init__(self, url, proxy=None, cacert=None, insecure=False,
  327. cert=None, cert_key=None, ssl_compression=False,
  328. default_user_agent=None, timeout=None):
  329. """
  330. Make an HTTPConnection or HTTPSConnection
  331. :param url: url to connect to
  332. :param proxy: proxy to connect through, if any; None by default; str
  333. of the format 'http://127.0.0.1:8888' to set one
  334. :param cacert: A CA bundle file to use in verifying a TLS server
  335. certificate.
  336. :param insecure: Allow to access servers without checking SSL certs.
  337. The server's certificate will not be verified.
  338. :param cert: Client certificate file to connect on SSL server
  339. requiring SSL client certificate.
  340. :param cert_key: Client certificate private key file.
  341. :param ssl_compression: SSL compression should be disabled by default
  342. and this setting is not usable as of now. The
  343. parameter is kept for backward compatibility.
  344. :param default_user_agent: Set the User-Agent header on every request.
  345. If set to None (default), the user agent
  346. will be "python-swiftclient-<version>". This
  347. may be overridden on a per-request basis by
  348. explicitly setting the user-agent header on
  349. a call to request().
  350. :param timeout: socket read timeout value, passed directly to
  351. the requests library.
  352. :raises ClientException: Unable to handle protocol scheme
  353. """
  354. self.url = url
  355. self.parsed_url = urlparse(url)
  356. self.host = self.parsed_url.netloc
  357. self.port = self.parsed_url.port
  358. self.requests_args = {}
  359. self.request_session = requests.Session()
  360. # Don't use requests's default headers
  361. self.request_session.headers = None
  362. self.resp = None
  363. if self.parsed_url.scheme not in ('http', 'https'):
  364. raise ClientException('Unsupported scheme "%s" in url "%s"'
  365. % (self.parsed_url.scheme, url))
  366. self.requests_args['verify'] = not insecure
  367. if cacert and not insecure:
  368. # verify requests parameter is used to pass the CA_BUNDLE file
  369. # see: http://docs.python-requests.org/en/latest/user/advanced/
  370. self.requests_args['verify'] = cacert
  371. if cert:
  372. # NOTE(cbrandily): cert requests parameter is used to pass client
  373. # cert path or a tuple with client certificate/key paths.
  374. if cert_key:
  375. self.requests_args['cert'] = cert, cert_key
  376. else:
  377. self.requests_args['cert'] = cert
  378. if proxy:
  379. proxy_parsed = urlparse(proxy)
  380. if not proxy_parsed.scheme:
  381. raise ClientException("Proxy's missing scheme")
  382. self.requests_args['proxies'] = {
  383. proxy_parsed.scheme: '%s://%s' % (
  384. proxy_parsed.scheme, proxy_parsed.netloc
  385. )
  386. }
  387. self.requests_args['stream'] = True
  388. if default_user_agent is None:
  389. default_user_agent = \
  390. 'python-swiftclient-%s' % swiftclient_version.version_string
  391. self.default_user_agent = default_user_agent
  392. if timeout:
  393. self.requests_args['timeout'] = timeout
  394. def __del__(self):
  395. """Cleanup resources other than memory"""
  396. if self.request_session:
  397. # The session we create must be closed to free up file descriptors
  398. try:
  399. self.request_session.close()
  400. finally:
  401. self.request_session = None
  402. def _request(self, *arg, **kwarg):
  403. """Final wrapper before requests call, to be patched in tests"""
  404. return self.request_session.request(*arg, **kwarg)
  405. def request(self, method, full_path, data=None, headers=None, files=None):
  406. """Encode url and header, then call requests.request"""
  407. if headers is None:
  408. headers = {}
  409. else:
  410. headers = encode_meta_headers(headers)
  411. # set a default User-Agent header if it wasn't passed in
  412. if 'user-agent' not in headers:
  413. headers['user-agent'] = self.default_user_agent
  414. url = "%s://%s%s" % (
  415. self.parsed_url.scheme,
  416. self.parsed_url.netloc,
  417. full_path)
  418. self.resp = self._request(method, url, headers=headers, data=data,
  419. files=files, **self.requests_args)
  420. return self.resp
  421. def putrequest(self, full_path, data=None, headers=None, files=None):
  422. """
  423. Use python-requests files upload
  424. :param data: Use data generator for chunked-transfer
  425. :param files: Use files for default transfer
  426. """
  427. return self.request('PUT', full_path, data, headers, files)
  428. def getresponse(self):
  429. """Adapt requests response to httplib interface"""
  430. self.resp.status = self.resp.status_code
  431. old_getheader = self.resp.raw.getheader
  432. def _decode_header(string):
  433. if string is None or six.PY2:
  434. return string
  435. return string.encode('iso-8859-1').decode('utf-8')
  436. def _encode_header(string):
  437. if string is None or six.PY2:
  438. return string
  439. return string.encode('utf-8').decode('iso-8859-1')
  440. def getheaders():
  441. return [(_decode_header(k), _decode_header(v))
  442. for k, v in self.resp.headers.items()]
  443. def getheader(k, v=None):
  444. return _decode_header(old_getheader(
  445. _encode_header(k.lower()), _encode_header(v)))
  446. def releasing_read(*args, **kwargs):
  447. chunk = self.resp.raw.read(*args, **kwargs)
  448. if not chunk:
  449. # NOTE(sigmavirus24): Release the connection back to the
  450. # urllib3's connection pool. This will reduce the number of
  451. # log messages seen in bug #1341777. This does not actually
  452. # close a socket. It will also prevent people from being
  453. # mislead as to the cause of a bug as in bug #1424732.
  454. self.resp.close()
  455. return chunk
  456. self.resp.getheaders = getheaders
  457. self.resp.getheader = getheader
  458. self.resp.read = releasing_read
  459. return self.resp
  460. def close(self):
  461. if self.resp:
  462. self.resp.close()
  463. self.request_session.close()
  464. def http_connection(*arg, **kwarg):
  465. """:returns: tuple of (parsed url, connection object)"""
  466. conn = HTTPConnection(*arg, **kwarg)
  467. return conn.parsed_url, conn
  468. def get_auth_1_0(url, user, key, snet, **kwargs):
  469. cacert = kwargs.get('cacert', None)
  470. insecure = kwargs.get('insecure', False)
  471. cert = kwargs.get('cert')
  472. cert_key = kwargs.get('cert_key')
  473. timeout = kwargs.get('timeout', None)
  474. parsed, conn = http_connection(url, cacert=cacert, insecure=insecure,
  475. cert=cert, cert_key=cert_key,
  476. timeout=timeout)
  477. method = 'GET'
  478. headers = {'X-Auth-User': user, 'X-Auth-Key': key}
  479. conn.request(method, parsed.path, '', headers)
  480. resp = conn.getresponse()
  481. body = resp.read()
  482. resp.close()
  483. conn.close()
  484. http_log((url, method,), headers, resp, body)
  485. url = resp.getheader('x-storage-url')
  486. # There is a side-effect on current Rackspace 1.0 server where a
  487. # bad URL would get you that document page and a 200. We error out
  488. # if we don't have a x-storage-url header and if we get a body.
  489. if resp.status < 200 or resp.status >= 300 or (body and not url):
  490. raise ClientException.from_response(resp, 'Auth GET failed', body)
  491. if snet:
  492. parsed = list(urlparse(url))
  493. # Second item in the list is the netloc
  494. netloc = parsed[1]
  495. parsed[1] = 'snet-' + netloc
  496. url = urlunparse(parsed)
  497. token = resp.getheader('x-storage-token', resp.getheader('x-auth-token'))
  498. return url, token
  499. def get_keystoneclient_2_0(auth_url, user, key, os_options, **kwargs):
  500. # this function is only here to preserve the historic 'public'
  501. # interface of this module
  502. kwargs.update({'auth_version': '2.0'})
  503. return get_auth_keystone(auth_url, user, key, os_options, **kwargs)
  504. def get_auth_keystone(auth_url, user, key, os_options, **kwargs):
  505. """
  506. Authenticate against a keystone server.
  507. We are using the keystoneclient library for authentication.
  508. """
  509. insecure = kwargs.get('insecure', False)
  510. timeout = kwargs.get('timeout', None)
  511. auth_version = kwargs.get('auth_version', None)
  512. debug = logger.isEnabledFor(logging.DEBUG)
  513. # Add the version suffix in case of versionless Keystone endpoints. If
  514. # auth_version is also unset it is likely that it is v3
  515. if not VERSIONFUL_AUTH_PATH.match(
  516. urlparse(auth_url).path.rstrip('/').rsplit('/', 1)[-1]):
  517. # Normalize auth_url to end in a slash because urljoin
  518. auth_url = auth_url.rstrip('/') + '/'
  519. if auth_version and auth_version in AUTH_VERSIONS_V2:
  520. auth_url = urljoin(auth_url, "v2.0")
  521. else:
  522. auth_url = urljoin(auth_url, "v3")
  523. auth_version = '3'
  524. logger.debug("Versionless auth_url - using %s as endpoint" % auth_url)
  525. # Legacy default if not set
  526. if auth_version is None:
  527. auth_version = '2'
  528. ksclient = None
  529. if auth_version in AUTH_VERSIONS_V3:
  530. if ksclient_v3 is not None:
  531. ksclient = ksclient_v3
  532. else:
  533. if ksclient_v2 is not None:
  534. ksclient = ksclient_v2
  535. if ksclient is None:
  536. raise ClientException('''
  537. Auth versions 2.0 and 3 require python-keystoneclient, install it or use Auth
  538. version 1.0 which requires ST_AUTH, ST_USER, and ST_KEY environment
  539. variables to be set or overridden with -A, -U, or -K.''')
  540. filter_kwargs = {}
  541. service_type = os_options.get('service_type') or 'object-store'
  542. endpoint_type = os_options.get('endpoint_type') or 'publicURL'
  543. if os_options.get('region_name'):
  544. filter_kwargs['attr'] = 'region'
  545. filter_kwargs['filter_value'] = os_options['region_name']
  546. if os_options.get('auth_type') and os_options['auth_type'] not in (
  547. 'password', 'v2password', 'v3password',
  548. 'v3applicationcredential'):
  549. raise ClientException(
  550. 'Swiftclient currently only supports v3applicationcredential '
  551. 'for auth_type')
  552. elif os_options.get('auth_type') == 'v3applicationcredential':
  553. if ksa_v3 is None:
  554. raise ClientException('Auth v3applicationcredential requires '
  555. 'keystoneauth1 package; consider upgrading '
  556. 'to python-keystoneclient>=2.0.0')
  557. try:
  558. auth = ksa_v3.ApplicationCredential(
  559. auth_url=auth_url,
  560. application_credential_secret=os_options.get(
  561. 'application_credential_secret'),
  562. application_credential_id=os_options.get(
  563. 'application_credential_id'))
  564. sess = ksa_session.Session(auth=auth)
  565. token = sess.get_token()
  566. except ksauthexceptions.Unauthorized:
  567. msg = 'Unauthorized. Check application credential id and secret.'
  568. raise ClientException(msg)
  569. except ksauthexceptions.AuthorizationFailure as err:
  570. raise ClientException('Authorization Failure. %s' % err)
  571. try:
  572. endpoint = sess.get_endpoint_data(service_type=service_type,
  573. endpoint_type=endpoint_type,
  574. **filter_kwargs)
  575. return endpoint.catalog_url, token
  576. except ksauthexceptions.EndpointNotFound:
  577. raise ClientException(
  578. 'Endpoint for %s not found - '
  579. 'have you specified a region?' % service_type)
  580. try:
  581. _ksclient = ksclient.Client(
  582. username=user,
  583. password=key,
  584. token=os_options.get('auth_token'),
  585. tenant_name=os_options.get('tenant_name'),
  586. tenant_id=os_options.get('tenant_id'),
  587. user_id=os_options.get('user_id'),
  588. user_domain_name=os_options.get('user_domain_name'),
  589. user_domain_id=os_options.get('user_domain_id'),
  590. project_name=os_options.get('project_name'),
  591. project_id=os_options.get('project_id'),
  592. project_domain_name=os_options.get('project_domain_name'),
  593. project_domain_id=os_options.get('project_domain_id'),
  594. debug=debug,
  595. cacert=kwargs.get('cacert'),
  596. cert=kwargs.get('cert'),
  597. key=kwargs.get('cert_key'),
  598. auth_url=auth_url, insecure=insecure, timeout=timeout)
  599. except ksexceptions.Unauthorized:
  600. msg = 'Unauthorized. Check username, password and tenant name/id.'
  601. if auth_version in AUTH_VERSIONS_V3:
  602. msg = ('Unauthorized. Check username/id, password, '
  603. 'tenant name/id and user/tenant domain name/id.')
  604. raise ClientException(msg)
  605. except ksexceptions.AuthorizationFailure as err:
  606. raise ClientException('Authorization Failure. %s' % err)
  607. try:
  608. endpoint = _ksclient.service_catalog.url_for(
  609. service_type=service_type,
  610. endpoint_type=endpoint_type,
  611. **filter_kwargs)
  612. except ksexceptions.EndpointNotFound:
  613. raise ClientException('Endpoint for %s not found - '
  614. 'have you specified a region?' % service_type)
  615. return endpoint, _ksclient.auth_token
  616. def get_auth(auth_url, user, key, **kwargs):
  617. """
  618. Get authentication/authorization credentials.
  619. :kwarg auth_version: the api version of the supplied auth params
  620. :kwarg os_options: a dict, the openstack identity service options
  621. :returns: a tuple, (storage_url, token)
  622. N.B. if the optional os_options parameter includes a non-empty
  623. 'object_storage_url' key it will override the default storage url returned
  624. by the auth service.
  625. The snet parameter is used for Rackspace's ServiceNet internal network
  626. implementation. In this function, it simply adds *snet-* to the beginning
  627. of the host name for the returned storage URL. With Rackspace Cloud Files,
  628. use of this network path causes no bandwidth charges but requires the
  629. client to be running on Rackspace's ServiceNet network.
  630. """
  631. session = kwargs.get('session', None)
  632. auth_version = kwargs.get('auth_version', '1')
  633. os_options = kwargs.get('os_options', {})
  634. cacert = kwargs.get('cacert', None)
  635. insecure = kwargs.get('insecure', False)
  636. cert = kwargs.get('cert')
  637. cert_key = kwargs.get('cert_key')
  638. timeout = kwargs.get('timeout', None)
  639. if session:
  640. service_type = os_options.get('service_type', 'object-store')
  641. interface = os_options.get('endpoint_type', 'public')
  642. region_name = os_options.get('region_name')
  643. storage_url = session.get_endpoint(service_type=service_type,
  644. interface=interface,
  645. region_name=region_name)
  646. token = session.get_token()
  647. elif auth_version in AUTH_VERSIONS_V1:
  648. storage_url, token = get_auth_1_0(auth_url,
  649. user,
  650. key,
  651. kwargs.get('snet'),
  652. cacert=cacert,
  653. insecure=insecure,
  654. cert=cert,
  655. cert_key=cert_key,
  656. timeout=timeout)
  657. elif auth_version in AUTH_VERSIONS_V2 + AUTH_VERSIONS_V3:
  658. # We are handling a special use case here where the user argument
  659. # specifies both the user name and tenant name in the form tenant:user
  660. if user and not kwargs.get('tenant_name') and ':' in user:
  661. os_options['tenant_name'], user = user.split(':')
  662. # We are allowing to have a tenant_name argument in get_auth
  663. # directly without having os_options
  664. if kwargs.get('tenant_name'):
  665. os_options['tenant_name'] = kwargs['tenant_name']
  666. if os_options.get('auth_type') == 'v3applicationcredential':
  667. pass
  668. elif not (os_options.get('tenant_name') or
  669. os_options.get('tenant_id') or
  670. os_options.get('project_name') or
  671. os_options.get('project_id')):
  672. if auth_version in AUTH_VERSIONS_V2:
  673. raise ClientException('No tenant specified')
  674. raise ClientException('No project name or project id specified.')
  675. storage_url, token = get_auth_keystone(auth_url, user,
  676. key, os_options,
  677. cacert=cacert,
  678. insecure=insecure,
  679. cert=cert,
  680. cert_key=cert_key,
  681. timeout=timeout,
  682. auth_version=auth_version)
  683. else:
  684. raise ClientException('Unknown auth_version %s specified and no '
  685. 'session found.' % auth_version)
  686. # Override storage url, if necessary
  687. if os_options.get('object_storage_url'):
  688. return os_options['object_storage_url'], token
  689. else:
  690. return storage_url, token
  691. def resp_header_dict(resp):
  692. resp_headers = {}
  693. for header, value in resp.getheaders():
  694. header = parse_header_string(header).lower()
  695. resp_headers[header] = parse_header_string(value)
  696. return resp_headers
  697. def store_response(resp, response_dict):
  698. """
  699. store information about an operation into a dict
  700. :param resp: an http response object containing the response
  701. headers
  702. :param response_dict: a dict into which are placed the
  703. status, reason and a dict of lower-cased headers
  704. """
  705. if response_dict is not None:
  706. response_dict['status'] = resp.status
  707. response_dict['reason'] = resp.reason
  708. response_dict['headers'] = resp_header_dict(resp)
  709. def get_account(url, token, marker=None, limit=None, prefix=None,
  710. end_marker=None, http_conn=None, full_listing=False,
  711. service_token=None, headers=None, delimiter=None):
  712. """
  713. Get a listing of containers for the account.
  714. :param url: storage URL
  715. :param token: auth token
  716. :param marker: marker query
  717. :param limit: limit query
  718. :param prefix: prefix query
  719. :param end_marker: end_marker query
  720. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  721. (If None, it will create the conn object)
  722. :param full_listing: if True, return a full listing, else returns a max
  723. of 10000 listings
  724. :param service_token: service auth token
  725. :param headers: additional headers to include in the request
  726. :param delimiter: delimiter query
  727. :returns: a tuple of (response headers, a list of containers) The response
  728. headers will be a dict and all header names will be lowercase.
  729. :raises ClientException: HTTP GET request failed
  730. """
  731. req_headers = {'X-Auth-Token': token, 'Accept-Encoding': 'gzip'}
  732. if service_token:
  733. req_headers['X-Service-Token'] = service_token
  734. if headers:
  735. req_headers.update(headers)
  736. if not http_conn:
  737. http_conn = http_connection(url)
  738. if full_listing:
  739. rv = get_account(url, token, marker, limit, prefix, end_marker,
  740. http_conn, headers=req_headers, delimiter=delimiter)
  741. listing = rv[1]
  742. while listing:
  743. marker = listing[-1]['name']
  744. listing = get_account(url, token, marker, limit, prefix,
  745. end_marker, http_conn, headers=req_headers,
  746. delimiter=delimiter)[1]
  747. if listing:
  748. rv[1].extend(listing)
  749. return rv
  750. parsed, conn = http_conn
  751. qs = 'format=json'
  752. if marker:
  753. qs += '&marker=%s' % quote(marker)
  754. if limit:
  755. qs += '&limit=%d' % limit
  756. if prefix:
  757. qs += '&prefix=%s' % quote(prefix)
  758. if delimiter:
  759. qs += '&delimiter=%s' % quote(delimiter)
  760. if end_marker:
  761. qs += '&end_marker=%s' % quote(end_marker)
  762. full_path = '%s?%s' % (parsed.path, qs)
  763. method = 'GET'
  764. conn.request(method, full_path, '', req_headers)
  765. resp = conn.getresponse()
  766. body = resp.read()
  767. http_log(("%s?%s" % (url, qs), method,), {'headers': req_headers},
  768. resp, body)
  769. resp_headers = resp_header_dict(resp)
  770. if resp.status < 200 or resp.status >= 300:
  771. raise ClientException.from_response(resp, 'Account GET failed', body)
  772. if resp.status == 204:
  773. return resp_headers, []
  774. return resp_headers, parse_api_response(resp_headers, body)
  775. def head_account(url, token, http_conn=None, headers=None,
  776. service_token=None):
  777. """
  778. Get account stats.
  779. :param url: storage URL
  780. :param token: auth token
  781. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  782. (If None, it will create the conn object)
  783. :param headers: additional headers to include in the request
  784. :param service_token: service auth token
  785. :returns: a dict containing the response's headers (all header names will
  786. be lowercase)
  787. :raises ClientException: HTTP HEAD request failed
  788. """
  789. if http_conn:
  790. parsed, conn = http_conn
  791. else:
  792. parsed, conn = http_connection(url)
  793. method = "HEAD"
  794. req_headers = {'X-Auth-Token': token}
  795. if service_token:
  796. req_headers['X-Service-Token'] = service_token
  797. if headers:
  798. req_headers.update(headers)
  799. conn.request(method, parsed.path, '', req_headers)
  800. resp = conn.getresponse()
  801. body = resp.read()
  802. http_log((url, method,), {'headers': req_headers}, resp, body)
  803. if resp.status < 200 or resp.status >= 300:
  804. raise ClientException.from_response(resp, 'Account HEAD failed', body)
  805. resp_headers = resp_header_dict(resp)
  806. return resp_headers
  807. def post_account(url, token, headers, http_conn=None, response_dict=None,
  808. service_token=None, query_string=None, data=None):
  809. """
  810. Update an account's metadata.
  811. :param url: storage URL
  812. :param token: auth token
  813. :param headers: additional headers to include in the request
  814. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  815. (If None, it will create the conn object)
  816. :param response_dict: an optional dictionary into which to place
  817. the response - status, reason and headers
  818. :param service_token: service auth token
  819. :param query_string: if set will be appended with '?' to generated path
  820. :param data: an optional message body for the request
  821. :raises ClientException: HTTP POST request failed
  822. :returns: resp_headers, body
  823. """
  824. if http_conn:
  825. parsed, conn = http_conn
  826. else:
  827. parsed, conn = http_connection(url)
  828. method = 'POST'
  829. path = parsed.path
  830. if query_string:
  831. path += '?' + query_string
  832. req_headers = {'X-Auth-Token': token}
  833. if service_token:
  834. req_headers['X-Service-Token'] = service_token
  835. if headers:
  836. req_headers.update(headers)
  837. conn.request(method, path, data, req_headers)
  838. resp = conn.getresponse()
  839. body = resp.read()
  840. http_log((url, method,), {'headers': req_headers}, resp, body)
  841. store_response(resp, response_dict)
  842. if resp.status < 200 or resp.status >= 300:
  843. raise ClientException.from_response(resp, 'Account POST failed', body)
  844. resp_headers = {}
  845. for header, value in resp.getheaders():
  846. resp_headers[header.lower()] = value
  847. return resp_headers, body
  848. def get_container(url, token, container, marker=None, limit=None,
  849. prefix=None, delimiter=None, end_marker=None,
  850. version_marker=None, path=None, http_conn=None,
  851. full_listing=False, service_token=None, headers=None,
  852. query_string=None):
  853. """
  854. Get a listing of objects for the container.
  855. :param url: storage URL
  856. :param token: auth token
  857. :param container: container name to get a listing for
  858. :param marker: marker query
  859. :param limit: limit query
  860. :param prefix: prefix query
  861. :param delimiter: string to delimit the queries on
  862. :param end_marker: marker query
  863. :param version_marker: version marker query
  864. :param path: path query (equivalent: "delimiter=/" and "prefix=path/")
  865. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  866. (If None, it will create the conn object)
  867. :param full_listing: if True, return a full listing, else returns a max
  868. of 10000 listings
  869. :param service_token: service auth token
  870. :param headers: additional headers to include in the request
  871. :param query_string: if set will be appended with '?' to generated path
  872. :returns: a tuple of (response headers, a list of objects) The response
  873. headers will be a dict and all header names will be lowercase.
  874. :raises ClientException: HTTP GET request failed
  875. """
  876. if not http_conn:
  877. http_conn = http_connection(url)
  878. if full_listing:
  879. rv = get_container(url, token, container, marker, limit, prefix,
  880. delimiter, end_marker, version_marker, path=path,
  881. http_conn=http_conn, service_token=service_token,
  882. headers=headers)
  883. listing = rv[1]
  884. while listing:
  885. if not delimiter:
  886. marker = listing[-1]['name']
  887. else:
  888. marker = listing[-1].get('name', listing[-1].get('subdir'))
  889. version_marker = listing[-1].get('version_id')
  890. listing = get_container(url, token, container, marker, limit,
  891. prefix, delimiter, end_marker,
  892. version_marker, path, http_conn,
  893. service_token=service_token,
  894. headers=headers)[1]
  895. if listing:
  896. rv[1].extend(listing)
  897. return rv
  898. parsed, conn = http_conn
  899. cont_path = '%s/%s' % (parsed.path, quote(container))
  900. qs = 'format=json'
  901. if marker:
  902. qs += '&marker=%s' % quote(marker)
  903. if limit:
  904. qs += '&limit=%d' % limit
  905. if prefix:
  906. qs += '&prefix=%s' % quote(prefix)
  907. if delimiter:
  908. qs += '&delimiter=%s' % quote(delimiter)
  909. if end_marker:
  910. qs += '&end_marker=%s' % quote(end_marker)
  911. if version_marker:
  912. qs += '&version_marker=%s' % quote(version_marker)
  913. if path:
  914. qs += '&path=%s' % quote(path)
  915. if query_string:
  916. qs += '&%s' % query_string.lstrip('?')
  917. req_headers = {'X-Auth-Token': token, 'Accept-Encoding': 'gzip'}
  918. if service_token:
  919. req_headers['X-Service-Token'] = service_token
  920. if headers:
  921. req_headers.update(headers)
  922. method = 'GET'
  923. conn.request(method, '%s?%s' % (cont_path, qs), '', req_headers)
  924. resp = conn.getresponse()
  925. body = resp.read()
  926. http_log(('%(url)s%(cont_path)s?%(qs)s' %
  927. {'url': url.replace(parsed.path, ''),
  928. 'cont_path': cont_path,
  929. 'qs': qs}, method,),
  930. {'headers': req_headers}, resp, body)
  931. if resp.status < 200 or resp.status >= 300:
  932. raise ClientException.from_response(resp, 'Container GET failed', body)
  933. resp_headers = resp_header_dict(resp)
  934. if resp.status == 204:
  935. return resp_headers, []
  936. return resp_headers, parse_api_response(resp_headers, body)
  937. def head_container(url, token, container, http_conn=None, headers=None,
  938. service_token=None):
  939. """
  940. Get container stats.
  941. :param url: storage URL
  942. :param token: auth token
  943. :param container: container name to get stats for
  944. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  945. (If None, it will create the conn object)
  946. :param headers: additional headers to include in the request
  947. :param service_token: service auth token
  948. :returns: a dict containing the response's headers (all header names will
  949. be lowercase)
  950. :raises ClientException: HTTP HEAD request failed
  951. """
  952. if http_conn:
  953. parsed, conn = http_conn
  954. else:
  955. parsed, conn = http_connection(url)
  956. path = '%s/%s' % (parsed.path, quote(container))
  957. method = 'HEAD'
  958. req_headers = {'X-Auth-Token': token}
  959. if service_token:
  960. req_headers['X-Service-Token'] = service_token
  961. if headers:
  962. req_headers.update(headers)
  963. conn.request(method, path, '', req_headers)
  964. resp = conn.getresponse()
  965. body = resp.read()
  966. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  967. {'headers': req_headers}, resp, body)
  968. if resp.status < 200 or resp.status >= 300:
  969. raise ClientException.from_response(
  970. resp, 'Container HEAD failed', body)
  971. resp_headers = resp_header_dict(resp)
  972. return resp_headers
  973. def put_container(url, token, container, headers=None, http_conn=None,
  974. response_dict=None, service_token=None, query_string=None):
  975. """
  976. Create a container
  977. :param url: storage URL
  978. :param token: auth token
  979. :param container: container name to create
  980. :param headers: additional headers to include in the request
  981. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  982. (If None, it will create the conn object)
  983. :param response_dict: an optional dictionary into which to place
  984. the response - status, reason and headers
  985. :param service_token: service auth token
  986. :param query_string: if set will be appended with '?' to generated path
  987. :raises ClientException: HTTP PUT request failed
  988. """
  989. if http_conn:
  990. parsed, conn = http_conn
  991. else:
  992. parsed, conn = http_connection(url)
  993. path = '%s/%s' % (parsed.path, quote(container))
  994. method = 'PUT'
  995. req_headers = {'X-Auth-Token': token}
  996. if service_token:
  997. req_headers['X-Service-Token'] = service_token
  998. if headers:
  999. req_headers.update(headers)
  1000. if 'content-length' not in (k.lower() for k in req_headers):
  1001. req_headers['Content-Length'] = '0'
  1002. if query_string:
  1003. path += '?' + query_string.lstrip('?')
  1004. conn.request(method, path, '', req_headers)
  1005. resp = conn.getresponse()
  1006. body = resp.read()
  1007. store_response(resp, response_dict)
  1008. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  1009. {'headers': req_headers}, resp, body)
  1010. if resp.status < 200 or resp.status >= 300:
  1011. raise ClientException.from_response(resp, 'Container PUT failed', body)
  1012. def post_container(url, token, container, headers, http_conn=None,
  1013. response_dict=None, service_token=None):
  1014. """
  1015. Update a container's metadata.
  1016. :param url: storage URL
  1017. :param token: auth token
  1018. :param container: container name to update
  1019. :param headers: additional headers to include in the request
  1020. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1021. (If None, it will create the conn object)
  1022. :param response_dict: an optional dictionary into which to place
  1023. the response - status, reason and headers
  1024. :param service_token: service auth token
  1025. :raises ClientException: HTTP POST request failed
  1026. """
  1027. if http_conn:
  1028. parsed, conn = http_conn
  1029. else:
  1030. parsed, conn = http_connection(url)
  1031. path = '%s/%s' % (parsed.path, quote(container))
  1032. method = 'POST'
  1033. req_headers = {'X-Auth-Token': token}
  1034. if service_token:
  1035. req_headers['X-Service-Token'] = service_token
  1036. if headers:
  1037. req_headers.update(headers)
  1038. if 'content-length' not in (k.lower() for k in headers):
  1039. req_headers['Content-Length'] = '0'
  1040. conn.request(method, path, '', req_headers)
  1041. resp = conn.getresponse()
  1042. body = resp.read()
  1043. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  1044. {'headers': req_headers}, resp, body)
  1045. store_response(resp, response_dict)
  1046. if resp.status < 200 or resp.status >= 300:
  1047. raise ClientException.from_response(
  1048. resp, 'Container POST failed', body)
  1049. def delete_container(url, token, container, http_conn=None,
  1050. response_dict=None, service_token=None,
  1051. query_string=None, headers=None):
  1052. """
  1053. Delete a container
  1054. :param url: storage URL
  1055. :param token: auth token
  1056. :param container: container name to delete
  1057. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1058. (If None, it will create the conn object)
  1059. :param response_dict: an optional dictionary into which to place
  1060. the response - status, reason and headers
  1061. :param service_token: service auth token
  1062. :param query_string: if set will be appended with '?' to generated path
  1063. :param headers: additional headers to include in the request
  1064. :raises ClientException: HTTP DELETE request failed
  1065. """
  1066. if http_conn:
  1067. parsed, conn = http_conn
  1068. else:
  1069. parsed, conn = http_connection(url)
  1070. path = '%s/%s' % (parsed.path, quote(container))
  1071. if headers:
  1072. headers = dict(headers)
  1073. else:
  1074. headers = {}
  1075. headers['X-Auth-Token'] = token
  1076. if service_token:
  1077. headers['X-Service-Token'] = service_token
  1078. if query_string:
  1079. path += '?' + query_string.lstrip('?')
  1080. method = 'DELETE'
  1081. conn.request(method, path, '', headers)
  1082. resp = conn.getresponse()
  1083. body = resp.read()
  1084. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  1085. {'headers': headers}, resp, body)
  1086. store_response(resp, response_dict)
  1087. if resp.status < 200 or resp.status >= 300:
  1088. raise ClientException.from_response(
  1089. resp, 'Container DELETE failed', body)
  1090. def get_object(url, token, container, name, http_conn=None,
  1091. resp_chunk_size=None, query_string=None,
  1092. response_dict=None, headers=None, service_token=None):
  1093. """
  1094. Get an object
  1095. :param url: storage URL
  1096. :param token: auth token
  1097. :param container: container name that the object is in
  1098. :param name: object name to get
  1099. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1100. (If None, it will create the conn object)
  1101. :param resp_chunk_size: if defined, chunk size of data to read. NOTE: If
  1102. you specify a resp_chunk_size you must fully read
  1103. the object's contents before making another
  1104. request.
  1105. :param query_string: if set will be appended with '?' to generated path
  1106. :param response_dict: an optional dictionary into which to place
  1107. the response - status, reason and headers
  1108. :param headers: an optional dictionary with additional headers to include
  1109. in the request
  1110. :param service_token: service auth token
  1111. :returns: a tuple of (response headers, the object's contents) The response
  1112. headers will be a dict and all header names will be lowercase.
  1113. :raises ClientException: HTTP GET request failed
  1114. """
  1115. if http_conn:
  1116. parsed, conn = http_conn
  1117. else:
  1118. parsed, conn = http_connection(url)
  1119. path = '%s/%s/%s' % (parsed.path, quote(container), quote(name))
  1120. if query_string:
  1121. path += '?' + query_string
  1122. method = 'GET'
  1123. headers = headers.copy() if headers else {}
  1124. headers['X-Auth-Token'] = token
  1125. if service_token:
  1126. headers['X-Service-Token'] = service_token
  1127. conn.request(method, path, '', headers)
  1128. resp = conn.getresponse()
  1129. parsed_response = {}
  1130. store_response(resp, parsed_response)
  1131. if response_dict is not None:
  1132. response_dict.update(parsed_response)
  1133. if resp.status < 200 or resp.status >= 300:
  1134. body = resp.read()
  1135. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  1136. {'headers': headers}, resp, body)
  1137. raise ClientException.from_response(resp, 'Object GET failed', body)
  1138. if resp_chunk_size:
  1139. object_body = _ObjectBody(resp, resp_chunk_size)
  1140. else:
  1141. object_body = resp.read()
  1142. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  1143. {'headers': headers}, resp, None)
  1144. return parsed_response['headers'], object_body
  1145. def head_object(url, token, container, name, http_conn=None,
  1146. service_token=None, headers=None, query_string=None):
  1147. """
  1148. Get object info
  1149. :param url: storage URL
  1150. :param token: auth token
  1151. :param container: container name that the object is in
  1152. :param name: object name to get info for
  1153. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1154. (If None, it will create the conn object)
  1155. :param service_token: service auth token
  1156. :param headers: additional headers to include in the request
  1157. :returns: a dict containing the response's headers (all header names will
  1158. be lowercase)
  1159. :raises ClientException: HTTP HEAD request failed
  1160. """
  1161. if http_conn:
  1162. parsed, conn = http_conn
  1163. else:
  1164. parsed, conn = http_connection(url)
  1165. path = '%s/%s/%s' % (parsed.path, quote(container), quote(name))
  1166. if query_string:
  1167. path += '?' + query_string
  1168. if headers:
  1169. headers = dict(headers)
  1170. else:
  1171. headers = {}
  1172. headers['X-Auth-Token'] = token
  1173. method = 'HEAD'
  1174. if service_token:
  1175. headers['X-Service-Token'] = service_token
  1176. conn.request(method, path, '', headers)
  1177. resp = conn.getresponse()
  1178. body = resp.read()
  1179. http_log(('%s%s' % (url.replace(parsed.path, ''), path), method,),
  1180. {'headers': headers}, resp, body)
  1181. if resp.status < 200 or resp.status >= 300:
  1182. raise ClientException.from_response(resp, 'Object HEAD failed', body)
  1183. resp_headers = resp_header_dict(resp)
  1184. return resp_headers
  1185. def put_object(url, token=None, container=None, name=None, contents=None,
  1186. content_length=None, etag=None, chunk_size=None,
  1187. content_type=None, headers=None, http_conn=None, proxy=None,
  1188. query_string=None, response_dict=None, service_token=None):
  1189. """
  1190. Put an object
  1191. :param url: storage URL
  1192. :param token: auth token; if None, no token will be sent
  1193. :param container: container name that the object is in; if None, the
  1194. container name is expected to be part of the url
  1195. :param name: object name to put; if None, the object name is expected to be
  1196. part of the url
  1197. :param contents: a string, a file-like object or an iterable
  1198. to read object data from;
  1199. if None, a zero-byte put will be done
  1200. :param content_length: value to send as content-length header; also limits
  1201. the amount read from contents; if None, it will be
  1202. computed via the contents or chunked transfer
  1203. encoding will be used
  1204. :param etag: etag of contents; if None, no etag will be sent
  1205. :param chunk_size: chunk size of data to write; it defaults to 65536;
  1206. used only if the contents object has a 'read'
  1207. method, e.g. file-like objects, ignored otherwise
  1208. :param content_type: value to send as content-type header, overriding any
  1209. value included in the headers param; if None and no
  1210. value is found in the headers param, an empty string
  1211. value will be sent
  1212. :param headers: additional headers to include in the request, if any
  1213. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1214. (If None, it will create the conn object)
  1215. :param proxy: proxy to connect through, if any; None by default; str of the
  1216. format 'http://127.0.0.1:8888' to set one
  1217. :param query_string: if set will be appended with '?' to generated path
  1218. :param response_dict: an optional dictionary into which to place
  1219. the response - status, reason and headers
  1220. :param service_token: service auth token
  1221. :returns: etag
  1222. :raises ClientException: HTTP PUT request failed
  1223. """
  1224. if http_conn:
  1225. parsed, conn = http_conn
  1226. else:
  1227. parsed, conn = http_connection(url, proxy=proxy)
  1228. path = parsed.path
  1229. if container:
  1230. path = '%s/%s' % (path.rstrip('/'), quote(container))
  1231. if name:
  1232. path = '%s/%s' % (path.rstrip('/'), quote(name))
  1233. if query_string:
  1234. path += '?' + query_string
  1235. if headers:
  1236. headers = dict(headers)
  1237. else:
  1238. headers = {}
  1239. if token:
  1240. headers['X-Auth-Token'] = token
  1241. if service_token:
  1242. headers['X-Service-Token'] = service_token
  1243. if etag:
  1244. headers['ETag'] = etag.strip('"')
  1245. if content_length is not None:
  1246. headers['Content-Length'] = str(content_length)
  1247. else:
  1248. for n, v in headers.items():
  1249. if n.lower() == 'content-length':
  1250. content_length = int(v)
  1251. if content_type is not None:
  1252. headers['Content-Type'] = content_type
  1253. elif 'Content-Type' not in headers:
  1254. if StrictVersion(requests.__version__) < StrictVersion('2.4.0'):
  1255. # python-requests sets application/x-www-form-urlencoded otherwise
  1256. # if using python3.
  1257. headers['Content-Type'] = ''
  1258. if not contents:
  1259. headers['Content-Length'] = '0'
  1260. if isinstance(contents, (ReadableToIterable, LengthWrapper)):
  1261. conn.putrequest(path, headers=headers, data=contents)
  1262. elif hasattr(contents, 'read'):
  1263. if chunk_size is None:
  1264. chunk_size = 65536
  1265. if content_length is None:
  1266. data = ReadableToIterable(contents, chunk_size, md5=False)
  1267. else:
  1268. data = LengthWrapper(contents, content_length, md5=False)
  1269. conn.putrequest(path, headers=headers, data=data)
  1270. else:
  1271. if chunk_size is not None:
  1272. warn_msg = ('%s object has no "read" method, ignoring chunk_size'
  1273. % type(contents).__name__)
  1274. warnings.warn(warn_msg, stacklevel=2)
  1275. # Match requests's is_stream test
  1276. if hasattr(contents, '__iter__') and not isinstance(contents, (
  1277. six.text_type, six.binary_type, list, tuple, dict)):
  1278. contents = iter_wrapper(contents)
  1279. conn.request('PUT', path, contents, headers)
  1280. resp = conn.getresponse()
  1281. body = resp.read()
  1282. http_log(('%s%s' % (url.replace(parsed.path, ''), path), 'PUT',),
  1283. {'headers': headers}, resp, body)
  1284. store_response(resp, response_dict)
  1285. if resp.status < 200 or resp.status >= 300:
  1286. raise ClientException.from_response(resp, 'Object PUT failed', body)
  1287. etag = resp.getheader('etag', '').strip('"')
  1288. return etag
  1289. def post_object(url, token, container, name, headers, http_conn=None,
  1290. response_dict=None, service_token=None):
  1291. """
  1292. Update object metadata
  1293. :param url: storage URL
  1294. :param token: auth token
  1295. :param container: container name that the object is in
  1296. :param name: name of the object to update
  1297. :param headers: additional headers to include in the request
  1298. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1299. (If None, it will create the conn object)
  1300. :param response_dict: an optional dictionary into which to place
  1301. the response - status, reason and headers
  1302. :param service_token: service auth token
  1303. :raises ClientException: HTTP POST request failed
  1304. """
  1305. if http_conn:
  1306. parsed, conn = http_conn
  1307. else:
  1308. parsed, conn = http_connection(url)
  1309. path = '%s/%s/%s' % (parsed.path, quote(container), quote(name))
  1310. req_headers = {'X-Auth-Token': token}
  1311. if service_token:
  1312. req_headers['X-Service-Token'] = service_token
  1313. if headers:
  1314. req_headers.update(headers)
  1315. conn.request('POST', path, '', req_headers)
  1316. resp = conn.getresponse()
  1317. body = resp.read()
  1318. http_log(('%s%s' % (url.replace(parsed.path, ''), path), 'POST',),
  1319. {'headers': req_headers}, resp, body)
  1320. store_response(resp, response_dict)
  1321. if resp.status < 200 or resp.status >= 300:
  1322. raise ClientException.from_response(resp, 'Object POST failed', body)
  1323. def copy_object(url, token, container, name, destination=None,
  1324. headers=None, fresh_metadata=None, http_conn=None,
  1325. response_dict=None, service_token=None):
  1326. """
  1327. Copy object
  1328. :param url: storage URL
  1329. :param token: auth token; if None, no token will be sent
  1330. :param container: container name that the source object is in
  1331. :param name: source object name
  1332. :param destination: The container and object name of the destination object
  1333. in the form of /container/object; if None, the copy
  1334. will use the source as the destination.
  1335. :param headers: additional headers to include in the request
  1336. :param fresh_metadata: Enables object creation that omits existing user
  1337. metadata, default None
  1338. :param http_conn: HTTP connection object (If None, it will create the
  1339. conn object)
  1340. :param response_dict: an optional dictionary into which to place
  1341. the response - status, reason and headers
  1342. :param service_token: service auth token
  1343. :raises ClientException: HTTP COPY request failed
  1344. """
  1345. if http_conn:
  1346. parsed, conn = http_conn
  1347. else:
  1348. parsed, conn = http_connection(url)
  1349. path = parsed.path
  1350. container = quote(container)
  1351. name = quote(name)
  1352. path = '%s/%s/%s' % (path.rstrip('/'), container, name)
  1353. headers = dict(headers) if headers else {}
  1354. if destination is not None:
  1355. headers['Destination'] = quote(destination)
  1356. elif container and name:
  1357. headers['Destination'] = '/%s/%s' % (container, name)
  1358. if token is not None:
  1359. headers['X-Auth-Token'] = token
  1360. if service_token is not None:
  1361. headers['X-Service-Token'] = service_token
  1362. if fresh_metadata is not None:
  1363. # remove potential fresh metadata headers
  1364. for fresh_hdr in [hdr for hdr in headers.keys()
  1365. if hdr.lower() == 'x-fresh-metadata']:
  1366. headers.pop(fresh_hdr)
  1367. headers['X-Fresh-Metadata'] = 'true' if fresh_metadata else 'false'
  1368. conn.request('COPY', path, '', headers)
  1369. resp = conn.getresponse()
  1370. body = resp.read()
  1371. http_log(('%s%s' % (url.replace(parsed.path, ''), path), 'COPY',),
  1372. {'headers': headers}, resp, body)
  1373. store_response(resp, response_dict)
  1374. if resp.status < 200 or resp.status >= 300:
  1375. raise ClientException.from_response(resp, 'Object COPY failed', body)
  1376. def delete_object(url, token=None, container=None, name=None, http_conn=None,
  1377. headers=None, proxy=None, query_string=None,
  1378. response_dict=None, service_token=None):
  1379. """
  1380. Delete object
  1381. :param url: storage URL
  1382. :param token: auth token; if None, no token will be sent
  1383. :param container: container name that the object is in; if None, the
  1384. container name is expected to be part of the url
  1385. :param name: object name to delete; if None, the object name is expected to
  1386. be part of the url
  1387. :param http_conn: a tuple of (parsed url, HTTPConnection object),
  1388. (If None, it will create the conn object)
  1389. :param headers: additional headers to include in the request
  1390. :param proxy: proxy to connect through, if any; None by default; str of the
  1391. format 'http://127.0.0.1:8888' to set one
  1392. :param query_string: if set will be appended with '?' to generated path
  1393. :param response_dict: an optional dictionary into which to place
  1394. the response - status, reason and headers
  1395. :param service_token: service auth token
  1396. :raises ClientException: HTTP DELETE request failed
  1397. """
  1398. if http_conn:
  1399. parsed, conn = http_conn
  1400. else:
  1401. parsed, conn = http_connection(url, proxy=proxy)
  1402. path = parsed.path
  1403. if container:
  1404. path = '%s/%s' % (path.rstrip('/'), quote(container))
  1405. if name:
  1406. path = '%s/%s' % (path.rstrip('/'), quote(name))
  1407. if query_string:
  1408. path += '?' + query_string
  1409. if headers:
  1410. headers = dict(headers)
  1411. else:
  1412. headers = {}
  1413. if token:
  1414. headers['X-Auth-Token'] = token
  1415. if service_token:
  1416. headers['X-Service-Token'] = service_token
  1417. conn.request('DELETE', path, '', headers)
  1418. resp = conn.getresponse()
  1419. body = resp.read()
  1420. http_log(('%s%s' % (url.replace(parsed.path, ''), path), 'DELETE',),
  1421. {'headers': headers}, resp, body)
  1422. store_response(resp, response_dict)
  1423. if resp.status < 200 or resp.status >= 300:
  1424. raise ClientException.from_response(resp, 'Object DELETE failed', body)
  1425. def get_capabilities(http_conn):
  1426. """
  1427. Get cluster capability infos.
  1428. :param http_conn: a tuple of (parsed url, HTTPConnection object)
  1429. :returns: a dict containing the cluster capabilities
  1430. :raises ClientException: HTTP Capabilities GET failed
  1431. """
  1432. parsed, conn = http_conn
  1433. headers = {'Accept-Encoding': 'gzip'}
  1434. conn.request('GET', parsed.path, '', headers)
  1435. resp = conn.getresponse()
  1436. body = resp.read()
  1437. http_log((parsed.geturl(), 'GET',), {'headers': headers}, resp, body)
  1438. if resp.status < 200 or resp.status >= 300:
  1439. raise ClientException.from_response(
  1440. resp, 'Capabilities GET failed', body)
  1441. resp_headers = resp_header_dict(resp)
  1442. return parse_api_response(resp_headers, body)
  1443. class Connection(object):
  1444. """
  1445. Convenience class to make requests that will also retry the request
  1446. Requests will have an X-Auth-Token header whose value is either
  1447. the preauthtoken or a token obtained from the auth service using
  1448. the user credentials provided as args to the constructor. If
  1449. os_options includes a service_username then requests will also have
  1450. an X-Service-Token header whose value is a token obtained from the
  1451. auth service using the service credentials. In this case the request
  1452. url will be set to the storage_url obtained from the auth service
  1453. for the service user, unless this is overridden by a preauthurl.
  1454. """
  1455. def __init__(self, authurl=None, user=None, key=None, retries=5,
  1456. preauthurl=None, preauthtoken=None, snet=False,
  1457. starting_backoff=1, max_backoff=64, tenant_name=None,
  1458. os_options=None, auth_version="1", cacert=None,
  1459. insecure=False, cert=None, cert_key=None,
  1460. ssl_compression=True, retry_on_ratelimit=False,
  1461. timeout=None, session=None, force_auth_retry=False):
  1462. """
  1463. :param authurl: authentication URL
  1464. :param user: user name to authenticate as
  1465. :param key: key/password to authenticate with
  1466. :param retries: Number of times to retry the request before failing
  1467. :param preauthurl: storage URL (if you have already authenticated)
  1468. :param preauthtoken: authentication token (if you have already
  1469. authenticated) note authurl/user/key/tenant_name
  1470. are not required when specifying preauthtoken
  1471. :param snet: use SERVICENET internal network default is False
  1472. :param starting_backoff: initial delay between retries (seconds)
  1473. :param max_backoff: maximum delay between retries (seconds)
  1474. :param auth_version: OpenStack auth version, default is 1.0
  1475. :param tenant_name: The tenant/account name, required when connecting
  1476. to an auth 2.0 system.
  1477. :param os_options: The OpenStack options which can have tenant_id,
  1478. auth_token, service_type, endpoint_type,
  1479. tenant_name, object_storage_url, region_name,
  1480. service_username, service_project_name, service_key
  1481. :param insecure: Allow to access servers without checking SSL certs.
  1482. The server's certificate will not be verified.
  1483. :param cert: Client certificate file to connect on SSL server
  1484. requiring SSL client certificate.
  1485. :param cert_key: Client certificate private key file.
  1486. :param ssl_compression: Whether to enable compression at the SSL layer.
  1487. If set to 'False' and the pyOpenSSL library is
  1488. present an attempt to disable SSL compression
  1489. will be made. This may provide a performance
  1490. increase for https upload/download operations.
  1491. :param retry_on_ratelimit: by default, a ratelimited connection will
  1492. raise an exception to the caller. Setting
  1493. this parameter to True will cause a retry
  1494. after a backoff.
  1495. :param timeout: The connect timeout for the HTTP connection.
  1496. :param session: A keystoneauth session object.
  1497. :param force_auth_retry: reset auth info even if client got unexpected
  1498. error except 401 Unauthorized.
  1499. """
  1500. self.session = session
  1501. self.authurl = authurl
  1502. self.user = user
  1503. self.key = key
  1504. self.retries = retries
  1505. self.http_conn = None
  1506. self.attempts = 0
  1507. self.snet = snet
  1508. self.starting_backoff = starting_backoff
  1509. self.max_backoff = max_backoff
  1510. self.auth_version = auth_version
  1511. self.os_options = dict(os_options or {})
  1512. if tenant_name:
  1513. self.os_options['tenant_name'] = tenant_name
  1514. if preauthurl:
  1515. self.os_options['object_storage_url'] = preauthurl
  1516. self.url = preauthurl or self.os_options.get('object_storage_url')
  1517. self.token = preauthtoken or self.os_options.get('auth_token')
  1518. if self.os_options.get('service_username', None):
  1519. self.service_auth = True
  1520. else:
  1521. self.service_auth = False
  1522. self.service_token = None
  1523. self.cacert = cacert
  1524. self.insecure = insecure
  1525. self.cert = cert
  1526. self.cert_key = cert_key
  1527. self.ssl_compression = ssl_compression
  1528. self.auth_end_time = 0
  1529. self.retry_on_ratelimit = retry_on_ratelimit
  1530. self.timeout = timeout
  1531. self.force_auth_retry = force_auth_retry
  1532. def close(self):
  1533. if (self.http_conn and isinstance(self.http_conn, tuple) and
  1534. len(self.http_conn) > 1):
  1535. conn = self.http_conn[1]
  1536. conn.close()
  1537. self.http_conn = None
  1538. def get_auth(self):
  1539. self.url, self.token = get_auth(self.authurl, self.user, self.key,
  1540. session=self.session, snet=self.snet,
  1541. auth_version=self.auth_version,
  1542. os_options=self.os_options,
  1543. cacert=self.cacert,
  1544. insecure=self.insecure,
  1545. cert=self.cert,
  1546. cert_key=self.cert_key,
  1547. timeout=self.timeout)
  1548. return self.url, self.token
  1549. def get_service_auth(self):
  1550. opts = self.os_options
  1551. service_options = {}
  1552. service_options['tenant_name'] = opts.get('service_project_name', None)
  1553. service_options['region_name'] = opts.get('region_name', None)
  1554. service_options['object_storage_url'] = opts.get('object_storage_url',
  1555. None)
  1556. service_user = opts.get('service_username', None)
  1557. service_key = opts.get('service_key', None)
  1558. return get_auth(self.authurl, service_user, service_key,
  1559. session=self.session,
  1560. snet=self.snet,
  1561. auth_version=self.auth_version,
  1562. os_options=service_options,
  1563. cacert=self.cacert,
  1564. insecure=self.insecure,
  1565. timeout=self.timeout)
  1566. def http_connection(self, url=None):
  1567. return http_connection(url if url else self.url,
  1568. cacert=self.cacert,
  1569. insecure=self.insecure,
  1570. cert=self.cert,
  1571. cert_key=self.cert_key,
  1572. ssl_compression=self.ssl_compression,
  1573. timeout=self.timeout)
  1574. def _add_response_dict(self, target_dict, kwargs):
  1575. if target_dict is not None and 'response_dict' in kwargs:
  1576. response_dict = kwargs['response_dict']
  1577. if 'response_dicts' in target_dict:
  1578. target_dict['response_dicts'].append(response_dict)
  1579. else:
  1580. target_dict['response_dicts'] = [response_dict]
  1581. target_dict.update(response_dict)
  1582. def _retry(self, reset_func, func, *args, **kwargs):
  1583. retried_auth = False
  1584. backoff = self.starting_backoff
  1585. caller_response_dict = kwargs.pop('response_dict', None)
  1586. self.attempts = kwargs.pop('attempts', 0)
  1587. while self.attempts <= self.retries or retried_auth:
  1588. self.attempts += 1
  1589. try:
  1590. if not self.url or not self.token:
  1591. self.url, self.token = self.get_auth()
  1592. self.close()
  1593. if self.service_auth and not self.service_token:
  1594. self.url, self.service_token = self.get_service_auth()
  1595. self.close()
  1596. self.auth_end_time = time()
  1597. if not self.http_conn:
  1598. self.http_conn = self.http_connection()
  1599. kwargs['http_conn'] = self.http_conn
  1600. if caller_response_dict is not None:
  1601. kwargs['response_dict'] = {}
  1602. rv = func(self.url, self.token, *args,
  1603. service_token=self.service_token, **kwargs)
  1604. self._add_response_dict(caller_response_dict, kwargs)
  1605. return rv
  1606. except SSLError:
  1607. raise
  1608. except (socket.error, RequestException):
  1609. self._add_response_dict(caller_response_dict, kwargs)
  1610. if self.attempts > self.retries:
  1611. raise
  1612. self.http_conn = None
  1613. except ClientException as err:
  1614. self._add_response_dict(caller_response_dict, kwargs)
  1615. if err.http_status == 401:
  1616. if self.session:
  1617. should_retry = self.session.invalidate()
  1618. else:
  1619. # Without a proper session, just check for auth creds
  1620. should_retry = all((self.authurl, self.user, self.key))
  1621. self.url = self.token = self.service_token = None
  1622. if retried_auth or not should_retry:
  1623. raise
  1624. retried_auth = True
  1625. elif self.attempts > self.retries or err.http_status is None:
  1626. raise
  1627. elif err.http_status == 408:
  1628. self.http_conn = None
  1629. elif 500 <= err.http_status <= 599:
  1630. pass
  1631. elif self.retry_on_ratelimit and err.http_status == 498:
  1632. pass
  1633. else:
  1634. raise
  1635. if self.force_auth_retry:
  1636. self.url = self.token = self.service_token = None
  1637. sleep(backoff)
  1638. backoff = min(backoff * 2, self.max_backoff)
  1639. if reset_func:
  1640. reset_func(func, *args, **kwargs)
  1641. def head_account(self, headers=None):
  1642. """Wrapper for :func:`head_account`"""
  1643. return self._retry(None, head_account, headers=headers)
  1644. def get_account(self, marker=None, limit=None, prefix=None,
  1645. end_marker=None, full_listing=False, headers=None,
  1646. delimiter=None):
  1647. """Wrapper for :func:`get_account`"""
  1648. # TODO(unknown): With full_listing=True this will restart the entire
  1649. # listing with each retry. Need to make a better version that just
  1650. # retries where it left off.
  1651. return self._retry(None, get_account, marker=marker, limit=limit,
  1652. prefix=prefix, end_marker=end_marker,
  1653. full_listing=full_listing, headers=headers,
  1654. delimiter=delimiter)
  1655. def post_account(self, headers, response_dict=None,
  1656. query_string=None, data=None):
  1657. """Wrapper for :func:`post_account`"""
  1658. return self._retry(None, post_account, headers,
  1659. query_string=query_string, data=data,
  1660. response_dict=response_dict)
  1661. def head_container(self, container, headers=None):
  1662. """Wrapper for :func:`head_container`"""
  1663. return self._retry(None, head_container, container, headers=headers)
  1664. def get_container(self, container, marker=None, limit=None, prefix=None,
  1665. delimiter=None, end_marker=None, version_marker=None,
  1666. path=None, full_listing=False, headers=None,
  1667. query_string=None):
  1668. """Wrapper for :func:`get_container`"""
  1669. # TODO(unknown): With full_listing=True this will restart the entire
  1670. # listing with each retry. Need to make a better version that just
  1671. # retries where it left off.
  1672. return self._retry(None, get_container, container, marker=marker,
  1673. limit=limit, prefix=prefix, delimiter=delimiter,
  1674. end_marker=end_marker,
  1675. version_marker=version_marker, path=path,
  1676. full_listing=full_listing, headers=headers,
  1677. query_string=query_string)
  1678. def put_container(self, container, headers=None, response_dict=None,
  1679. query_string=None):
  1680. """Wrapper for :func:`put_container`"""
  1681. return self._retry(None, put_container, container, headers=headers,
  1682. response_dict=response_dict,
  1683. query_string=query_string)
  1684. def post_container(self, container, headers, response_dict=None):
  1685. """Wrapper for :func:`post_container`"""
  1686. return self._retry(None, post_container, container, headers,
  1687. response_dict=response_dict)
  1688. def delete_container(self, container, response_dict=None,
  1689. query_string=None, headers={}):
  1690. """Wrapper for :func:`delete_container`"""
  1691. return self._retry(None, delete_container, container,
  1692. response_dict=response_dict,
  1693. query_string=query_string,
  1694. headers=headers)
  1695. def head_object(self, container, obj, headers=None, query_string=None):
  1696. """Wrapper for :func:`head_object`"""
  1697. return self._retry(None, head_object, container, obj, headers=headers,
  1698. query_string=query_string)
  1699. def get_object(self, container, obj, resp_chunk_size=None,
  1700. query_string=None, response_dict=None, headers=None):
  1701. """Wrapper for :func:`get_object`"""
  1702. rheaders, body = self._retry(None, get_object, container, obj,
  1703. resp_chunk_size=resp_chunk_size,
  1704. query_string=query_string,
  1705. response_dict=response_dict,
  1706. headers=headers)
  1707. is_not_range_request = (
  1708. not headers or 'range' not in (k.lower() for k in headers))
  1709. retry_is_possible = (
  1710. is_not_range_request and resp_chunk_size and
  1711. self.attempts <= self.retries and
  1712. rheaders.get('transfer-encoding') is None)
  1713. if retry_is_possible:
  1714. body = _RetryBody(body.resp, self, container, obj,
  1715. resp_chunk_size=resp_chunk_size,
  1716. query_string=query_string,
  1717. response_dict=response_dict,
  1718. headers=headers)
  1719. return rheaders, body
  1720. def put_object(self, container, obj, contents, content_length=None,
  1721. etag=None, chunk_size=None, content_type=None,
  1722. headers=None, query_string=None, response_dict=None):
  1723. """Wrapper for :func:`put_object`"""
  1724. def _default_reset(*args, **kwargs):
  1725. raise ClientException('put_object(%r, %r, ...) failure and no '
  1726. 'ability to reset contents for reupload.'
  1727. % (container, obj))
  1728. if isinstance(contents, str) or not contents:
  1729. # if its a str or None then you can retry as much as you want
  1730. reset_func = None
  1731. else:
  1732. reset_func = _default_reset
  1733. if self.retries > 0:
  1734. tell = getattr(contents, 'tell', None)
  1735. seek = getattr(contents, 'seek', None)
  1736. reset = getattr(contents, 'reset', None)
  1737. if tell and seek:
  1738. orig_pos = tell()
  1739. def reset_func(*a, **kw):
  1740. seek(orig_pos)
  1741. elif reset:
  1742. reset_func = reset
  1743. return self._retry(reset_func, put_object, container, obj, contents,
  1744. content_length=content_length, etag=etag,
  1745. chunk_size=chunk_size, content_type=content_type,
  1746. headers=headers, query_string=query_string,
  1747. response_dict=response_dict)
  1748. def post_object(self, container, obj, headers, response_dict=None):
  1749. """Wrapper for :func:`post_object`"""
  1750. return self._retry(None, post_object, container, obj, headers,
  1751. response_dict=response_dict)
  1752. def copy_object(self, container, obj, destination=None, headers=None,
  1753. fresh_metadata=None, response_dict=None):
  1754. """Wrapper for :func:`copy_object`"""
  1755. return self._retry(None, copy_object, container, obj, destination,
  1756. headers, fresh_metadata,
  1757. response_dict=response_dict)
  1758. def delete_object(self, container, obj, query_string=None,
  1759. response_dict=None, headers=None):
  1760. """Wrapper for :func:`delete_object`"""
  1761. return self._retry(None, delete_object, container, obj,
  1762. query_string=query_string,
  1763. response_dict=response_dict,
  1764. headers=headers)
  1765. def _map_url(self, url):
  1766. url = url or self.url
  1767. if not url:
  1768. url, _ = self.get_auth()
  1769. scheme, netloc, path, params, query, fragment = urlparse(url)
  1770. if URI_PATTERN_VERSION.search(path):
  1771. path = URI_PATTERN_VERSION.sub('/info', path)
  1772. elif not URI_PATTERN_INFO.search(path):
  1773. if path.endswith('/'):
  1774. path += 'info'
  1775. else:
  1776. path += '/info'
  1777. return urlunparse((scheme, netloc, path, params, query, fragment))
  1778. def get_capabilities(self, url=None):
  1779. parsed = urlparse(self._map_url(url))
  1780. if not self.http_conn:
  1781. self.http_conn = self.http_connection(url)
  1782. return get_capabilities((parsed, self.http_conn[1]))