unixconn.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright 2013 dotCloud inc.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. from fig.packages import six
  12. if six.PY3:
  13. import http.client as httplib
  14. else:
  15. import httplib
  16. import requests.adapters
  17. import socket
  18. try:
  19. import requests.packages.urllib3.connectionpool as connectionpool
  20. except ImportError:
  21. import urllib3.connectionpool as connectionpool
  22. class UnixHTTPConnection(httplib.HTTPConnection, object):
  23. def __init__(self, base_url, unix_socket, timeout=60):
  24. httplib.HTTPConnection.__init__(self, 'localhost', timeout=timeout)
  25. self.base_url = base_url
  26. self.unix_socket = unix_socket
  27. self.timeout = timeout
  28. def connect(self):
  29. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  30. sock.settimeout(self.timeout)
  31. sock.connect(self.base_url.replace("http+unix:/", ""))
  32. self.sock = sock
  33. def _extract_path(self, url):
  34. #remove the base_url entirely..
  35. return url.replace(self.base_url, "")
  36. def request(self, method, url, **kwargs):
  37. url = self._extract_path(self.unix_socket)
  38. super(UnixHTTPConnection, self).request(method, url, **kwargs)
  39. class UnixHTTPConnectionPool(connectionpool.HTTPConnectionPool):
  40. def __init__(self, base_url, socket_path, timeout=60):
  41. connectionpool.HTTPConnectionPool.__init__(self, 'localhost',
  42. timeout=timeout)
  43. self.base_url = base_url
  44. self.socket_path = socket_path
  45. self.timeout = timeout
  46. def _new_conn(self):
  47. return UnixHTTPConnection(self.base_url, self.socket_path,
  48. self.timeout)
  49. class UnixAdapter(requests.adapters.HTTPAdapter):
  50. def __init__(self, base_url, timeout=60):
  51. self.base_url = base_url
  52. self.timeout = timeout
  53. super(UnixAdapter, self).__init__()
  54. def get_connection(self, socket_path, proxies=None):
  55. return UnixHTTPConnectionPool(self.base_url, socket_path, self.timeout)