blob: 86ea26e97e39a8b3546b752eb4193142c8f30300 [file] [log] [blame]
Jordan Pittier00f25962016-03-18 17:10:07 +01001# Copyright 2016 OpenStack Foundation
Matthew Treinish9e26ca82016-02-23 11:43:20 -05002# 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
Jordan Pittier00f25962016-03-18 17:10:07 +010016import urllib3
Matthew Treinish9e26ca82016-02-23 11:43:20 -050017
18
Jordan Pittier00f25962016-03-18 17:10:07 +010019class ClosingHttp(urllib3.poolmanager.PoolManager):
20 def __init__(self, disable_ssl_certificate_validation=False,
zhufl071e94c2016-07-12 10:26:34 +080021 ca_certs=None, timeout=None):
Jordan Pittier00f25962016-03-18 17:10:07 +010022 kwargs = {}
23
24 if disable_ssl_certificate_validation:
25 urllib3.disable_warnings()
26 kwargs['cert_reqs'] = 'CERT_NONE'
27
28 if ca_certs:
29 kwargs['cert_reqs'] = 'CERT_REQUIRED'
30 kwargs['ca_certs'] = ca_certs
31
zhufl071e94c2016-07-12 10:26:34 +080032 if timeout:
33 kwargs['timeout'] = timeout
34
Jordan Pittier00f25962016-03-18 17:10:07 +010035 super(ClosingHttp, self).__init__(**kwargs)
36
37 def request(self, url, method, *args, **kwargs):
38
39 class Response(dict):
40 def __init__(self, info):
41 for key, value in info.getheaders().items():
42 self[key.lower()] = value
43 self.status = info.status
44 self['status'] = str(self.status)
45 self.reason = info.reason
46 self.version = info.version
47 self['content-location'] = url
48
Matthew Treinish9e26ca82016-02-23 11:43:20 -050049 original_headers = kwargs.get('headers', {})
50 new_headers = dict(original_headers, connection='close')
51 new_kwargs = dict(kwargs, headers=new_headers)
Jordan Pittier00f25962016-03-18 17:10:07 +010052
53 # Follow up to 5 redirections. Don't raise an exception if
54 # it's exceeded but return the HTTP 3XX response instead.
55 retry = urllib3.util.Retry(raise_on_redirect=False, redirect=5)
56 r = super(ClosingHttp, self).request(method, url, retries=retry,
57 *args, **new_kwargs)
58 return Response(r), r.data