Use six to fix imports on Python 3

Replace Python 2 imports with six.moves import to make code compatible
with Python 2 and Python 3.

Replaced imports:

* BaseHTTPServer
* __builtin__
* cookielib
* httplib

This patch was generated by the six_moves operation of the sixer tool
version 0.4:
https://pypi.python.org/pypi/sixer

Manual changes:

* Disable pylint warnings on the HTTPSConnection classes because pylint
  doesn't support importing from six.moves yet, see:
  https://bitbucket.org/logilab/pylint/issue/550/

Blueprint cinder-python3
Change-Id: Ide6d4e3480f2c0a7eb4500aa88affe152ecc0401
This commit is contained in:
Victor Stinner 2015-05-25 16:56:46 +02:00
parent 6feb65dcf4
commit f484310fe6
19 changed files with 206 additions and 187 deletions

View File

@ -19,13 +19,13 @@ Module dedicated functions/classes dealing with rate limiting requests.
import collections import collections
import copy import copy
import httplib
import math import math
import re import re
import time import time
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import importutils from oslo_utils import importutils
from six.moves import http_client
import webob.dec import webob.dec
import webob.exc import webob.exc
@ -439,7 +439,7 @@ class WsgiLimiterProxy(object):
body = jsonutils.dumps({"verb": verb, "path": path}) body = jsonutils.dumps({"verb": verb, "path": path})
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
conn = httplib.HTTPConnection(self.limiter_address) conn = http_client.HTTPConnection(self.limiter_address)
if username: if username:
conn.request("POST", "/%s" % (username), body, headers) conn.request("POST", "/%s" % (username), body, headers)

View File

@ -19,13 +19,13 @@ Module dedicated functions/classes dealing with rate limiting requests.
import collections import collections
import copy import copy
import httplib
import math import math
import re import re
import time import time
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import importutils from oslo_utils import importutils
from six.moves import http_client
import webob.dec import webob.dec
import webob.exc import webob.exc
@ -437,7 +437,7 @@ class WsgiLimiterProxy(object):
body = jsonutils.dumps({"verb": verb, "path": path}) body = jsonutils.dumps({"verb": verb, "path": path})
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
conn = httplib.HTTPConnection(self.limiter_address) conn = http_client.HTTPConnection(self.limiter_address)
if username: if username:
conn.request("POST", "/%s" % (username), body, headers) conn.request("POST", "/%s" % (username), body, headers)

View File

@ -29,10 +29,10 @@
""" """
import eventlet import eventlet
from six.moves import builtins
eventlet.monkey_patch() eventlet.monkey_patch()
# See http://code.google.com/p/python-nose/issues/detail?id=373 # See http://code.google.com/p/python-nose/issues/detail?id=373
# The code below enables nosetests to work with i18n _() blocks # The code below enables nosetests to work with i18n _() blocks
import __builtin__ setattr(builtins, '_', lambda x: x)
setattr(__builtin__, '_', lambda x: x)

View File

@ -17,12 +17,12 @@
Tests dealing with HTTP rate-limiting. Tests dealing with HTTP rate-limiting.
""" """
import httplib
from xml.dom import minidom from xml.dom import minidom
from lxml import etree from lxml import etree
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six import six
from six.moves import http_client
import webob import webob
from cinder.api.v1 import limits from cinder.api.v1 import limits
@ -631,7 +631,7 @@ class WsgiLimiterTest(BaseLimitTestSuite):
class FakeHttplibSocket(object): class FakeHttplibSocket(object):
"""Fake `httplib.HTTPResponse` replacement.""" """Fake `http_client.HTTPResponse` replacement."""
def __init__(self, response_string): def __init__(self, response_string):
"""Initialize new `FakeHttplibSocket`.""" """Initialize new `FakeHttplibSocket`."""
@ -643,7 +643,7 @@ class FakeHttplibSocket(object):
class FakeHttplibConnection(object): class FakeHttplibConnection(object):
"""Fake `httplib.HTTPConnection`.""" """Fake `http_client.HTTPConnection`."""
def __init__(self, app, host): def __init__(self, app, host):
"""Initialize `FakeHttplibConnection`.""" """Initialize `FakeHttplibConnection`."""
@ -655,7 +655,7 @@ class FakeHttplibConnection(object):
Requests made via this connection actually get translated and Requests made via this connection actually get translated and
routed into our WSGI app, we then wait for the response and turn routed into our WSGI app, we then wait for the response and turn
it back into an `httplib.HTTPResponse`. it back into an `http_client.HTTPResponse`.
""" """
if not headers: if not headers:
headers = {} headers = {}
@ -669,7 +669,7 @@ class FakeHttplibConnection(object):
resp = str(req.get_response(self.app)) resp = str(req.get_response(self.app))
resp = "HTTP/1.0 %s" % resp resp = "HTTP/1.0 %s" % resp
sock = FakeHttplibSocket(resp) sock = FakeHttplibSocket(resp)
self.http_response = httplib.HTTPResponse(sock) self.http_response = http_client.HTTPResponse(sock)
self.http_response.begin() self.http_response.begin()
def getresponse(self): def getresponse(self):
@ -683,7 +683,7 @@ def wire_HTTPConnection_to_WSGI(host, app):
After calling this method, when any code calls After calling this method, when any code calls
httplib.HTTPConnection(host) http_client.HTTPConnection(host)
the connection object will be a fake. Its requests will be sent directly the connection object will be a fake. Its requests will be sent directly
to the given WSGI app rather than through a socket. to the given WSGI app rather than through a socket.
@ -710,8 +710,9 @@ def wire_HTTPConnection_to_WSGI(host, app):
else: else:
return self.wrapped(connection_host, *args, **kwargs) return self.wrapped(connection_host, *args, **kwargs)
oldHTTPConnection = httplib.HTTPConnection oldHTTPConnection = http_client.HTTPConnection
httplib.HTTPConnection = HTTPConnectionDecorator(httplib.HTTPConnection) new_http_connection = HTTPConnectionDecorator(http_client.HTTPConnection)
http_client.HTTPConnection = new_http_connection
return oldHTTPConnection return oldHTTPConnection
@ -722,7 +723,7 @@ class WsgiLimiterProxyTest(BaseLimitTestSuite):
"""setUp for test suite. """setUp for test suite.
Do some nifty HTTP/WSGI magic which allows for WSGI to be called Do some nifty HTTP/WSGI magic which allows for WSGI to be called
directly by something like the `httplib` library. directly by something like the `http_client` library.
""" """
super(WsgiLimiterProxyTest, self).setUp() super(WsgiLimiterProxyTest, self).setUp()
self.app = limits.WsgiLimiter(TEST_LIMITS) self.app = limits.WsgiLimiter(TEST_LIMITS)
@ -733,7 +734,7 @@ class WsgiLimiterProxyTest(BaseLimitTestSuite):
def _restore(self, oldHTTPConnection): def _restore(self, oldHTTPConnection):
# restore original HTTPConnection object # restore original HTTPConnection object
httplib.HTTPConnection = oldHTTPConnection http_client.HTTPConnection = oldHTTPConnection
def test_200(self): def test_200(self):
"""Successful request test.""" """Successful request test."""

View File

@ -17,12 +17,12 @@
Tests dealing with HTTP rate-limiting. Tests dealing with HTTP rate-limiting.
""" """
import httplib
from xml.dom import minidom from xml.dom import minidom
from lxml import etree from lxml import etree
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six import six
from six.moves import http_client
import webob import webob
from cinder.api.v2 import limits from cinder.api.v2 import limits
@ -634,7 +634,7 @@ class WsgiLimiterTest(BaseLimitTestSuite):
class FakeHttplibSocket(object): class FakeHttplibSocket(object):
"""Fake `httplib.HTTPResponse` replacement.""" """Fake `http_client.HTTPResponse` replacement."""
def __init__(self, response_string): def __init__(self, response_string):
"""Initialize new `FakeHttplibSocket`.""" """Initialize new `FakeHttplibSocket`."""
@ -647,7 +647,7 @@ class FakeHttplibSocket(object):
class FakeHttplibConnection(object): class FakeHttplibConnection(object):
"""Fake `httplib.HTTPConnection`.""" """Fake `http_client.HTTPConnection`."""
def __init__(self, app, host): def __init__(self, app, host):
"""Initialize `FakeHttplibConnection`.""" """Initialize `FakeHttplibConnection`."""
@ -659,7 +659,7 @@ class FakeHttplibConnection(object):
Requests made via this connection actually get translated and Requests made via this connection actually get translated and
routed into our WSGI app, we then wait for the response and turn routed into our WSGI app, we then wait for the response and turn
it back into an `httplib.HTTPResponse`. it back into an `http_client.HTTPResponse`.
""" """
if not headers: if not headers:
headers = {} headers = {}
@ -673,7 +673,7 @@ class FakeHttplibConnection(object):
resp = str(req.get_response(self.app)) resp = str(req.get_response(self.app))
resp = "HTTP/1.0 %s" % resp resp = "HTTP/1.0 %s" % resp
sock = FakeHttplibSocket(resp) sock = FakeHttplibSocket(resp)
self.http_response = httplib.HTTPResponse(sock) self.http_response = http_client.HTTPResponse(sock)
self.http_response.begin() self.http_response.begin()
def getresponse(self): def getresponse(self):
@ -687,7 +687,7 @@ def wire_HTTPConnection_to_WSGI(host, app):
After calling this method, when any code calls After calling this method, when any code calls
httplib.HTTPConnection(host) http_client.HTTPConnection(host)
the connection object will be a fake. Its requests will be sent directly the connection object will be a fake. Its requests will be sent directly
to the given WSGI app rather than through a socket. to the given WSGI app rather than through a socket.
@ -714,8 +714,9 @@ def wire_HTTPConnection_to_WSGI(host, app):
else: else:
return self.wrapped(connection_host, *args, **kwargs) return self.wrapped(connection_host, *args, **kwargs)
oldHTTPConnection = httplib.HTTPConnection oldHTTPConnection = http_client.HTTPConnection
httplib.HTTPConnection = HTTPConnectionDecorator(httplib.HTTPConnection) new_http_connection = HTTPConnectionDecorator(http_client.HTTPConnection)
http_client.HTTPConnection = new_http_connection
return oldHTTPConnection return oldHTTPConnection
@ -727,7 +728,7 @@ class WsgiLimiterProxyTest(BaseLimitTestSuite):
"""setUp() for WsgiLimiterProxyTest. """setUp() for WsgiLimiterProxyTest.
Do some nifty HTTP/WSGI magic which allows for WSGI to be called Do some nifty HTTP/WSGI magic which allows for WSGI to be called
directly by something like the `httplib` library. directly by something like the `http_client` library.
""" """
super(WsgiLimiterProxyTest, self).setUp() super(WsgiLimiterProxyTest, self).setUp()
self.app = limits.WsgiLimiter(TEST_LIMITS) self.app = limits.WsgiLimiter(TEST_LIMITS)
@ -738,7 +739,7 @@ class WsgiLimiterProxyTest(BaseLimitTestSuite):
def _restore(self, oldHTTPConnection): def _restore(self, oldHTTPConnection):
# restore original HTTPConnection object # restore original HTTPConnection object
httplib.HTTPConnection = oldHTTPConnection http_client.HTTPConnection = oldHTTPConnection
def test_200(self): def test_200(self):
"""Successful request test.""" """Successful request test."""

View File

@ -16,7 +16,6 @@
Tests for Backup NFS driver. Tests for Backup NFS driver.
""" """
import __builtin__
import bz2 import bz2
import exceptions import exceptions
import filecmp import filecmp
@ -30,6 +29,7 @@ import mock
from os_brick.remotefs import remotefs as remotefs_brick from os_brick.remotefs import remotefs as remotefs_brick
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log as logging from oslo_log import log as logging
from six.moves import builtins
from cinder.backup.drivers import nfs from cinder.backup.drivers import nfs
from cinder import context from cinder import context
@ -214,20 +214,20 @@ class BackupNFSTestCase(test.TestCase):
self.assertEqual([], result) self.assertEqual([], result)
def test_get_object_writer(self): def test_get_object_writer(self):
self.mock_object(__builtin__, 'open', mock.mock_open()) self.mock_object(builtins, 'open', mock.mock_open())
self.mock_object(os, 'chmod') self.mock_object(os, 'chmod')
self.driver.get_object_writer(FAKE_CONTAINER, FAKE_OBJECT_NAME) self.driver.get_object_writer(FAKE_CONTAINER, FAKE_OBJECT_NAME)
os.chmod.assert_called_once_with(FAKE_OBJECT_PATH, 0o660) os.chmod.assert_called_once_with(FAKE_OBJECT_PATH, 0o660)
__builtin__.open.assert_called_once_with(FAKE_OBJECT_PATH, 'w') builtins.open.assert_called_once_with(FAKE_OBJECT_PATH, 'w')
def test_get_object_reader(self): def test_get_object_reader(self):
self.mock_object(__builtin__, 'open', mock.mock_open()) self.mock_object(builtins, 'open', mock.mock_open())
self.driver.get_object_reader(FAKE_CONTAINER, FAKE_OBJECT_NAME) self.driver.get_object_reader(FAKE_CONTAINER, FAKE_OBJECT_NAME)
__builtin__.open.assert_called_once_with(FAKE_OBJECT_PATH, 'r') builtins.open.assert_called_once_with(FAKE_OBJECT_PATH, 'r')
def test_delete_object(self): def test_delete_object(self):
self.mock_object(os, 'remove') self.mock_object(os, 'remove')

View File

@ -13,13 +13,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import httplib
import json import json
import os import os
import socket import socket
import zlib import zlib
from oslo_log import log as logging from oslo_log import log as logging
from six.moves import http_client
from swiftclient import client as swift from swiftclient import client as swift
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -45,10 +45,10 @@ class FakeSwiftConnection(object):
LOG.debug("fake head_container(%s)" % container) LOG.debug("fake head_container(%s)" % container)
if container == 'missing_container': if container == 'missing_container':
raise swift.ClientException('fake exception', raise swift.ClientException('fake exception',
http_status=httplib.NOT_FOUND) http_status=http_client.NOT_FOUND)
elif container == 'unauthorized_container': elif container == 'unauthorized_container':
raise swift.ClientException('fake exception', raise swift.ClientException('fake exception',
http_status=httplib.UNAUTHORIZED) http_status=http_client.UNAUTHORIZED)
elif container == 'socket_error_on_head': elif container == 'socket_error_on_head':
raise socket.error(111, 'ECONNREFUSED') raise socket.error(111, 'ECONNREFUSED')
pass pass

View File

@ -15,12 +15,12 @@
# under the License. # under the License.
import hashlib import hashlib
import httplib
import os import os
import socket import socket
import tempfile import tempfile
from oslo_log import log as logging from oslo_log import log as logging
from six.moves import http_client
from swiftclient import client as swift from swiftclient import client as swift
from cinder.openstack.common import fileutils from cinder.openstack.common import fileutils
@ -48,10 +48,10 @@ class FakeSwiftConnection2(object):
LOG.debug("fake head_container(%s)", container) LOG.debug("fake head_container(%s)", container)
if container == 'missing_container': if container == 'missing_container':
raise swift.ClientException('fake exception', raise swift.ClientException('fake exception',
http_status=httplib.NOT_FOUND) http_status=http_client.NOT_FOUND)
elif container == 'unauthorized_container': elif container == 'unauthorized_container':
raise swift.ClientException('fake exception', raise swift.ClientException('fake exception',
http_status=httplib.UNAUTHORIZED) http_status=http_client.UNAUTHORIZED)
elif container == 'socket_error_on_head': elif container == 'socket_error_on_head':
raise socket.error(111, 'ECONNREFUSED') raise socket.error(111, 'ECONNREFUSED')

View File

@ -17,14 +17,13 @@
"""Unit tests for the API endpoint.""" """Unit tests for the API endpoint."""
import httplib
import six import six
from six.moves import http_client
import webob import webob
class FakeHttplibSocket(object): class FakeHttplibSocket(object):
"""A fake socket implementation for httplib.HTTPResponse, trivial.""" """A fake socket implementation for http_client.HTTPResponse, trivial."""
def __init__(self, response_string): def __init__(self, response_string):
self.response_string = response_string self.response_string = response_string
self._buffer = six.StringIO(response_string) self._buffer = six.StringIO(response_string)
@ -35,11 +34,11 @@ class FakeHttplibSocket(object):
class FakeHttplibConnection(object): class FakeHttplibConnection(object):
"""A fake httplib.HTTPConnection for boto. """A fake http_client.HTTPConnection for boto.
requests made via this connection actually get translated and routed into requests made via this connection actually get translated and routed into
our WSGI app, we then wait for the response and turn it back into our WSGI app, we then wait for the response and turn it back into
the httplib.HTTPResponse that boto expects. the http_client.HTTPResponse that boto expects.
""" """
def __init__(self, app, host, is_secure=False): def __init__(self, app, host, is_secure=False):
self.app = app self.app = app
@ -58,7 +57,7 @@ class FakeHttplibConnection(object):
# guess that's a function the web server usually provides. # guess that's a function the web server usually provides.
resp = "HTTP/1.0 %s" % resp resp = "HTTP/1.0 %s" % resp
self.sock = FakeHttplibSocket(resp) self.sock = FakeHttplibSocket(resp)
self.http_response = httplib.HTTPResponse(self.sock) self.http_response = http_client.HTTPResponse(self.sock)
# NOTE(vish): boto is accessing private variables for some reason # NOTE(vish): boto is accessing private variables for some reason
self._HTTPConnection__response = self.http_response self._HTTPConnection__response = self.http_response
self.http_response.begin() self.http_response.begin()

View File

@ -17,13 +17,12 @@ Tests for NetApp volume driver
""" """
import BaseHTTPServer
import httplib
from lxml import etree from lxml import etree
import mock import mock
from oslo_log import log as logging from oslo_log import log as logging
import six import six
from six.moves import BaseHTTPServer
from six.moves import http_client
from cinder import exception from cinder import exception
from cinder import test from cinder import test
@ -58,7 +57,7 @@ class FakeHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
class FakeHttplibSocket(object): class FakeHttplibSocket(object):
"""A fake socket implementation for httplib.HTTPResponse.""" """A fake socket implementation for http_client.HTTPResponse."""
def __init__(self, value): def __init__(self, value):
self._rbuffer = six.StringIO(value) self._rbuffer = six.StringIO(value)
self._wbuffer = six.StringIO('') self._wbuffer = six.StringIO('')
@ -444,11 +443,11 @@ class FakeDirectCMODEServerHandler(FakeHTTPRequestHandler):
class FakeDirectCmodeHTTPConnection(object): class FakeDirectCmodeHTTPConnection(object):
"""A fake httplib.HTTPConnection for netapp tests """A fake http_client.HTTPConnection for netapp tests
Requests made via this connection actually get translated and routed into Requests made via this connection actually get translated and routed into
the fake direct handler above, we then turn the response into the fake direct handler above, we then turn the response into
the httplib.HTTPResponse that the caller expects. the http_client.HTTPResponse that the caller expects.
""" """
def __init__(self, host, timeout=None): def __init__(self, host, timeout=None):
self.host = host self.host = host
@ -470,7 +469,7 @@ class FakeDirectCmodeHTTPConnection(object):
self.app = FakeDirectCMODEServerHandler(sock, '127.0.0.1:80', None) self.app = FakeDirectCMODEServerHandler(sock, '127.0.0.1:80', None)
self.sock = FakeHttplibSocket(sock.result) self.sock = FakeHttplibSocket(sock.result)
self.http_response = httplib.HTTPResponse(self.sock) self.http_response = http_client.HTTPResponse(self.sock)
def set_debuglevel(self, level): def set_debuglevel(self, level):
pass pass
@ -553,7 +552,7 @@ class NetAppDirectCmodeISCSIDriverTestCase(test.TestCase):
self.mock_object(utils, 'OpenStackInfo') self.mock_object(utils, 'OpenStackInfo')
configuration = self._set_config(create_configuration()) configuration = self._set_config(create_configuration())
driver = common.NetAppDriver(configuration=configuration) driver = common.NetAppDriver(configuration=configuration)
self.stubs.Set(httplib, 'HTTPConnection', self.stubs.Set(http_client, 'HTTPConnection',
FakeDirectCmodeHTTPConnection) FakeDirectCmodeHTTPConnection)
driver.do_setup(context='') driver.do_setup(context='')
self.driver = driver self.driver = driver
@ -1126,11 +1125,11 @@ class FakeDirect7MODEServerHandler(FakeHTTPRequestHandler):
class FakeDirect7modeHTTPConnection(object): class FakeDirect7modeHTTPConnection(object):
"""A fake httplib.HTTPConnection for netapp tests """A fake http_client.HTTPConnection for netapp tests
Requests made via this connection actually get translated and routed into Requests made via this connection actually get translated and routed into
the fake direct handler above, we then turn the response into the fake direct handler above, we then turn the response into
the httplib.HTTPResponse that the caller expects. the http_client.HTTPResponse that the caller expects.
""" """
def __init__(self, host, timeout=None): def __init__(self, host, timeout=None):
self.host = host self.host = host
@ -1152,7 +1151,7 @@ class FakeDirect7modeHTTPConnection(object):
self.app = FakeDirect7MODEServerHandler(sock, '127.0.0.1:80', None) self.app = FakeDirect7MODEServerHandler(sock, '127.0.0.1:80', None)
self.sock = FakeHttplibSocket(sock.result) self.sock = FakeHttplibSocket(sock.result)
self.http_response = httplib.HTTPResponse(self.sock) self.http_response = http_client.HTTPResponse(self.sock)
def set_debuglevel(self, level): def set_debuglevel(self, level):
pass pass
@ -1177,7 +1176,7 @@ class NetAppDirect7modeISCSIDriverTestCase_NV(
self.mock_object(utils, 'OpenStackInfo') self.mock_object(utils, 'OpenStackInfo')
configuration = self._set_config(create_configuration()) configuration = self._set_config(create_configuration())
driver = common.NetAppDriver(configuration=configuration) driver = common.NetAppDriver(configuration=configuration)
self.stubs.Set(httplib, 'HTTPConnection', self.stubs.Set(http_client, 'HTTPConnection',
FakeDirect7modeHTTPConnection) FakeDirect7modeHTTPConnection)
driver.do_setup(context='') driver.do_setup(context='')
driver.root_volume_name = 'root' driver.root_volume_name = 'root'
@ -1233,7 +1232,7 @@ class NetAppDirect7modeISCSIDriverTestCase_WV(
self.mock_object(utils, 'OpenStackInfo') self.mock_object(utils, 'OpenStackInfo')
configuration = self._set_config(create_configuration()) configuration = self._set_config(create_configuration())
driver = common.NetAppDriver(configuration=configuration) driver = common.NetAppDriver(configuration=configuration)
self.stubs.Set(httplib, 'HTTPConnection', self.stubs.Set(http_client, 'HTTPConnection',
FakeDirect7modeHTTPConnection) FakeDirect7modeHTTPConnection)
driver.do_setup(context='') driver.do_setup(context='')
self.driver = driver self.driver = driver

View File

@ -14,13 +14,12 @@
# under the License. # under the License.
"""Unit tests for the NetApp-specific ssc module.""" """Unit tests for the NetApp-specific ssc module."""
import BaseHTTPServer
import copy import copy
import httplib
from lxml import etree from lxml import etree
from mox3 import mox from mox3 import mox
import six import six
from six.moves import BaseHTTPServer
from six.moves import http_client
from cinder import exception from cinder import exception
from cinder import test from cinder import test
@ -36,7 +35,7 @@ class FakeHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
class FakeHttplibSocket(object): class FakeHttplibSocket(object):
"""A fake socket implementation for httplib.HTTPResponse.""" """A fake socket implementation for http_client.HTTPResponse."""
def __init__(self, value): def __init__(self, value):
self._rbuffer = six.StringIO(value) self._rbuffer = six.StringIO(value)
self._wbuffer = six.StringIO('') self._wbuffer = six.StringIO('')
@ -252,11 +251,11 @@ class FakeDirectCMODEServerHandler(FakeHTTPRequestHandler):
class FakeDirectCmodeHTTPConnection(object): class FakeDirectCmodeHTTPConnection(object):
"""A fake httplib.HTTPConnection for netapp tests. """A fake http_client.HTTPConnection for netapp tests.
Requests made via this connection actually get translated and routed into Requests made via this connection actually get translated and routed into
the fake direct handler above, we then turn the response into the fake direct handler above, we then turn the response into
the httplib.HTTPResponse that the caller expects. the http_client.HTTPResponse that the caller expects.
""" """
def __init__(self, host, timeout=None): def __init__(self, host, timeout=None):
self.host = host self.host = host
@ -278,7 +277,7 @@ class FakeDirectCmodeHTTPConnection(object):
self.app = FakeDirectCMODEServerHandler(sock, '127.0.0.1:80', None) self.app = FakeDirectCMODEServerHandler(sock, '127.0.0.1:80', None)
self.sock = FakeHttplibSocket(sock.result) self.sock = FakeHttplibSocket(sock.result)
self.http_response = httplib.HTTPResponse(self.sock) self.http_response = http_client.HTTPResponse(self.sock)
def set_debuglevel(self, level): def set_debuglevel(self, level):
pass pass
@ -372,7 +371,7 @@ class SscUtilsTestCase(test.TestCase):
def setUp(self): def setUp(self):
super(SscUtilsTestCase, self).setUp() super(SscUtilsTestCase, self).setUp()
self.stubs.Set(httplib, 'HTTPConnection', self.stubs.Set(http_client, 'HTTPConnection',
FakeDirectCmodeHTTPConnection) FakeDirectCmodeHTTPConnection)
def test_cl_vols_ssc_all(self): def test_cl_vols_ssc_all(self):

View File

@ -14,11 +14,11 @@
import copy import copy
import errno import errno
import httplib
import re import re
import mock import mock
from oslo_utils import units from oslo_utils import units
from six.moves import http_client
from cinder import exception from cinder import exception
from cinder import test from cinder import test
@ -206,7 +206,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'GET', 'GET',
'/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_SYSTEM), '/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_SYSTEM),
None, None,
[httplib.OK, httplib.ACCEPTED]) [http_client.OK, http_client.ACCEPTED])
def test_createvdev(self): def test_createvdev(self):
self.dplcmd.create_vdev(DATA_IN_VOLUME['id'], self.dplcmd.create_vdev(DATA_IN_VOLUME['id'],
@ -229,7 +229,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED, http_client.CREATED])
def test_extendvdev(self): def test_extendvdev(self):
self.dplcmd.extend_vdev(DATA_IN_VOLUME['id'], self.dplcmd.extend_vdev(DATA_IN_VOLUME['id'],
@ -248,7 +248,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED, http_client.CREATED])
def test_deletevdev(self): def test_deletevdev(self):
self.dplcmd.delete_vdev(DATA_IN_VOLUME['id'], True) self.dplcmd.delete_vdev(DATA_IN_VOLUME['id'], True)
@ -261,8 +261,8 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.ACCEPTED, httplib.NOT_FOUND, [http_client.OK, http_client.ACCEPTED, http_client.NOT_FOUND,
httplib.NO_CONTENT]) http_client.NO_CONTENT])
def test_createvdevfromsnapshot(self): def test_createvdevfromsnapshot(self):
self.dplcmd.create_vdev_from_snapshot( self.dplcmd.create_vdev_from_snapshot(
@ -287,7 +287,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED, http_client.CREATED])
def test_getpool(self): def test_getpool(self):
self.dplcmd.get_pool(POOLUUID) self.dplcmd.get_pool(POOLUUID)
@ -296,7 +296,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_POOL, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_POOL,
POOLUUID), POOLUUID),
None, None,
[httplib.OK, httplib.ACCEPTED]) [http_client.OK, http_client.ACCEPTED])
def test_clonevdev(self): def test_clonevdev(self):
self.dplcmd.clone_vdev( self.dplcmd.clone_vdev(
@ -324,7 +324,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME1['id']), DATA_IN_VOLUME1['id']),
params, params,
[httplib.OK, httplib.CREATED, httplib.ACCEPTED]) [http_client.OK, http_client.CREATED, http_client.ACCEPTED])
def test_createvdevsnapshot(self): def test_createvdevsnapshot(self):
self.dplcmd.create_vdev_snapshot( self.dplcmd.create_vdev_snapshot(
@ -346,7 +346,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.CREATED, httplib.ACCEPTED]) [http_client.OK, http_client.CREATED, http_client.ACCEPTED])
def test_getvdev(self): def test_getvdev(self):
self.dplcmd.get_vdev(DATA_IN_VOLUME['id']) self.dplcmd.get_vdev(DATA_IN_VOLUME['id'])
@ -355,7 +355,7 @@ class TestProphetStorDPLVolume(test.TestCase):
'/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME, '/%s/%s/%s/' % (DPLCOMMON.DPL_VER_V1, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
None, None,
[httplib.OK, httplib.ACCEPTED, httplib.NOT_FOUND]) [http_client.OK, http_client.ACCEPTED, http_client.NOT_FOUND])
def test_getvdevstatus(self): def test_getvdevstatus(self):
self.dplcmd.get_vdev_status(DATA_IN_VOLUME['id'], '123456') self.dplcmd.get_vdev_status(DATA_IN_VOLUME['id'], '123456')
@ -366,7 +366,7 @@ class TestProphetStorDPLVolume(test.TestCase):
DATA_IN_VOLUME['id'], DATA_IN_VOLUME['id'],
'123456'), '123456'),
None, None,
[httplib.OK, httplib.NOT_FOUND]) [http_client.OK, http_client.NOT_FOUND])
def test_getpoolstatus(self): def test_getpoolstatus(self):
self.dplcmd.get_pool_status(POOLUUID, '123456') self.dplcmd.get_pool_status(POOLUUID, '123456')
@ -377,7 +377,7 @@ class TestProphetStorDPLVolume(test.TestCase):
POOLUUID, POOLUUID,
'123456'), '123456'),
None, None,
[httplib.OK, httplib.NOT_FOUND]) [http_client.OK, http_client.NOT_FOUND])
def test_assignvdev(self): def test_assignvdev(self):
self.dplcmd.assign_vdev( self.dplcmd.assign_vdev(
@ -411,7 +411,7 @@ class TestProphetStorDPLVolume(test.TestCase):
DPLCOMMON.DPL_OBJ_VOLUME, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED, http_client.CREATED])
def test_unassignvdev(self): def test_unassignvdev(self):
self.dplcmd.unassign_vdev(DATA_IN_VOLUME['id'], self.dplcmd.unassign_vdev(DATA_IN_VOLUME['id'],
@ -436,8 +436,8 @@ class TestProphetStorDPLVolume(test.TestCase):
DPLCOMMON.DPL_OBJ_VOLUME, DPLCOMMON.DPL_OBJ_VOLUME,
DATA_IN_VOLUME['id']), DATA_IN_VOLUME['id']),
params, params,
[httplib.OK, httplib.ACCEPTED, [http_client.OK, http_client.ACCEPTED,
httplib.NO_CONTENT, httplib.NOT_FOUND]) http_client.NO_CONTENT, http_client.NOT_FOUND])
def test_deletevdevsnapshot(self): def test_deletevdevsnapshot(self):
self.dplcmd.delete_vdev_snapshot(DATA_IN_VOLUME['id'], self.dplcmd.delete_vdev_snapshot(DATA_IN_VOLUME['id'],
@ -453,8 +453,8 @@ class TestProphetStorDPLVolume(test.TestCase):
DPLCOMMON.DPL_OBJ_SNAPSHOT, DPLCOMMON.DPL_OBJ_SNAPSHOT,
DATA_IN_SNAPSHOT['id']), DATA_IN_SNAPSHOT['id']),
None, None,
[httplib.OK, httplib.ACCEPTED, httplib.NO_CONTENT, [http_client.OK, http_client.ACCEPTED, http_client.NO_CONTENT,
httplib.NOT_FOUND]) http_client.NOT_FOUND])
def test_listvdevsnapshots(self): def test_listvdevsnapshots(self):
self.dplcmd.list_vdev_snapshots(DATA_IN_VOLUME['id']) self.dplcmd.list_vdev_snapshots(DATA_IN_VOLUME['id'])
@ -465,7 +465,7 @@ class TestProphetStorDPLVolume(test.TestCase):
DATA_IN_VOLUME['id'], DATA_IN_VOLUME['id'],
DPLCOMMON.DPL_OBJ_SNAPSHOT), DPLCOMMON.DPL_OBJ_SNAPSHOT),
None, None,
[httplib.OK]) [http_client.OK])
class TestProphetStorDPLDriver(test.TestCase): class TestProphetStorDPLDriver(test.TestCase):

View File

@ -13,13 +13,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import httplib
import json import json
import uuid import uuid
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import units from oslo_utils import units
import six import six
from six.moves import http_client
from six.moves import urllib from six.moves import urllib
from cinder import exception from cinder import exception
@ -97,7 +97,7 @@ class CloudByteISCSIDriver(san.SanISCSIDriver):
res_details = {} res_details = {}
try: try:
# Prepare the connection # Prepare the connection
connection = httplib.HTTPSConnection(host) connection = http_client.HTTPSConnection(host)
# Make the connection # Make the connection
connection.request('GET', url) connection.request('GET', url)
# Extract the response as the connection was successful # Extract the response as the connection was successful
@ -153,7 +153,7 @@ class CloudByteISCSIDriver(san.SanISCSIDriver):
error_details = res_obj['error'] error_details = res_obj['error']
http_status = res_obj['http_status'] http_status = res_obj['http_status']
except httplib.HTTPException as ex: except http_client.HTTPException as ex:
msg = (_("Error executing CloudByte API [%(cmd)s], " msg = (_("Error executing CloudByte API [%(cmd)s], "
"Error: %(err)s.") % "Error: %(err)s.") %
{'cmd': cmd, 'err': ex}) {'cmd': cmd, 'err': ex})

View File

@ -14,7 +14,6 @@
# under the License. # under the License.
import base64 import base64
import httplib
import os import os
import socket import socket
import ssl import ssl
@ -25,6 +24,7 @@ from eventlet import patcher
import OpenSSL import OpenSSL
from oslo_log import log as logging from oslo_log import log as logging
import six import six
from six.moves import http_client
from six.moves import urllib from six.moves import urllib
from cinder.i18n import _, _LI from cinder.i18n import _, _LI
@ -74,7 +74,7 @@ def get_default_ca_certs():
class OpenSSLConnectionDelegator(object): class OpenSSLConnectionDelegator(object):
"""An OpenSSL.SSL.Connection delegator. """An OpenSSL.SSL.Connection delegator.
Supplies an additional 'makefile' method which httplib requires Supplies an additional 'makefile' method which http_client requires
and is not present in OpenSSL.SSL.Connection. and is not present in OpenSSL.SSL.Connection.
Note: Since it is not possible to inherit from OpenSSL.SSL.Connection Note: Since it is not possible to inherit from OpenSSL.SSL.Connection
a delegator must be used. a delegator must be used.
@ -89,7 +89,7 @@ class OpenSSLConnectionDelegator(object):
return socket._fileobject(self.connection, *args, **kwargs) return socket._fileobject(self.connection, *args, **kwargs)
class HTTPSConnection(httplib.HTTPSConnection): class HTTPSConnection(http_client.HTTPSConnection):
def __init__(self, host, port=None, key_file=None, cert_file=None, def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, ca_certs=None, no_verification=False): strict=None, ca_certs=None, no_verification=False):
if not pywbemAvailable: if not pywbemAvailable:
@ -101,9 +101,9 @@ class HTTPSConnection(httplib.HTTPSConnection):
else: else:
excp_lst = () excp_lst = ()
try: try:
httplib.HTTPSConnection.__init__(self, host, port, http_client.HTTPSConnection.__init__(self, host, port,
key_file=key_file, key_file=key_file,
cert_file=cert_file) cert_file=cert_file)
self.key_file = None if key_file is None else key_file self.key_file = None if key_file is None else key_file
self.cert_file = None if cert_file is None else cert_file self.cert_file = None if cert_file is None else cert_file
@ -255,7 +255,7 @@ def wbem_request(url, data, creds, headers=None, debug=0, x509=None,
"""Send request over HTTP. """Send request over HTTP.
Send XML data over HTTP to the specified url. Return the Send XML data over HTTP to the specified url. Return the
response in XML. Uses Python's build-in httplib. x509 may be a response in XML. Uses Python's build-in http_client. x509 may be a
dictionary containing the location of the SSL certificate and key dictionary containing the location of the SSL certificate and key
files. files.
""" """
@ -328,7 +328,7 @@ def wbem_request(url, data, creds, headers=None, debug=0, x509=None,
if response.status != 200: if response.status != 200:
raise pywbem.cim_http.Error('HTTP error') raise pywbem.cim_http.Error('HTTP error')
except httplib.BadStatusLine as arg: except http_client.BadStatusLine as arg:
msg = (_("Bad Status line returned: %(arg)s.") msg = (_("Bad Status line returned: %(arg)s.")
% {'arg': arg}) % {'arg': arg})
raise pywbem.cim_http.Error(msg) raise pywbem.cim_http.Error(msg)

View File

@ -15,7 +15,6 @@
"""Common class for Huawei 18000 storage drivers.""" """Common class for Huawei 18000 storage drivers."""
import base64 import base64
import cookielib
import json import json
import socket import socket
import time import time
@ -26,6 +25,7 @@ from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import units from oslo_utils import units
import six import six
from six.moves import http_cookiejar
from six.moves import urllib from six.moves import urllib
from cinder import context from cinder import context
@ -54,7 +54,7 @@ class RestCommon(object):
def __init__(self, configuration): def __init__(self, configuration):
self.configuration = configuration self.configuration = configuration
self.cookie = cookielib.CookieJar() self.cookie = http_cookiejar.CookieJar()
self.url = None self.url = None
self.productversion = None self.productversion = None
self.headers = {"Connection": "keep-alive", self.headers = {"Connection": "keep-alive",

View File

@ -22,7 +22,6 @@ Implementation of the class of ProphetStor DPL storage adapter of Federator.
import base64 import base64
import errno import errno
import httplib
import json import json
import random import random
import time import time
@ -30,6 +29,7 @@ import time
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import units from oslo_utils import units
import six import six
from six.moves import http_client
from cinder import exception from cinder import exception
from cinder.i18n import _, _LI, _LW, _LE from cinder.i18n import _, _LI, _LW, _LE
@ -98,9 +98,9 @@ class DPLCommand(object):
retcode = errno.EINVAL retcode = errno.EINVAL
for i in range(CONNECTION_RETRY): for i in range(CONNECTION_RETRY):
try: try:
connection = httplib.HTTPSConnection(self.ip, connection = http_client.HTTPSConnection(self.ip,
self.port, self.port,
timeout=60) timeout=60)
if connection: if connection:
retcode = 0 retcode = 0
break break
@ -117,12 +117,12 @@ class DPLCommand(object):
while (connection and retry): while (connection and retry):
try: try:
connection.request(method, url, payload, header) connection.request(method, url, payload, header)
except httplib.CannotSendRequest as e: except http_client.CannotSendRequest as e:
connection.close() connection.close()
time.sleep(1) time.sleep(1)
connection = httplib.HTTPSConnection(self.ip, connection = http_client.HTTPSConnection(self.ip,
self.port, self.port,
timeout=60) timeout=60)
retry -= 1 retry -= 1
if connection: if connection:
if retry == 0: if retry == 0:
@ -141,7 +141,7 @@ class DPLCommand(object):
if retcode == 0: if retcode == 0:
try: try:
response = connection.getresponse() response = connection.getresponse()
if response.status == httplib.SERVICE_UNAVAILABLE: if response.status == http_client.SERVICE_UNAVAILABLE:
LOG.error(_LE('The Flexvisor service is unavailable.')) LOG.error(_LE('The Flexvisor service is unavailable.'))
time.sleep(1) time.sleep(1)
retry -= 1 retry -= 1
@ -150,7 +150,7 @@ class DPLCommand(object):
else: else:
retcode = 0 retcode = 0
break break
except httplib.ResponseNotReady as e: except http_client.ResponseNotReady as e:
time.sleep(1) time.sleep(1)
retry -= 1 retry -= 1
retcode = errno.EFAULT retcode = errno.EFAULT
@ -162,23 +162,23 @@ class DPLCommand(object):
break break
if (retcode == 0 and response.status in expected_status if (retcode == 0 and response.status in expected_status
and response.status == httplib.NOT_FOUND): and response.status == http_client.NOT_FOUND):
retcode = errno.ENODATA retcode = errno.ENODATA
elif retcode == 0 and response.status not in expected_status: elif retcode == 0 and response.status not in expected_status:
LOG.error(_LE('%(method)s %(url)s unexpected response status: ' LOG.error(_LE('%(method)s %(url)s unexpected response status: '
'%(response)s (expects: %(expects)s).'), '%(response)s (expects: %(expects)s).'),
{'method': method, {'method': method,
'url': url, 'url': url,
'response': httplib.responses[response.status], 'response': http_client.responses[response.status],
'expects': expected_status}) 'expects': expected_status})
if response.status == httplib.UNAUTHORIZED: if response.status == http_client.UNAUTHORIZED:
raise exception.NotAuthorized raise exception.NotAuthorized
retcode = errno.EACCES retcode = errno.EACCES
else: else:
retcode = errno.EIO retcode = errno.EIO
elif retcode == 0 and response.status is httplib.NOT_FOUND: elif retcode == 0 and response.status is http_client.NOT_FOUND:
retcode = errno.ENODATA retcode = errno.ENODATA
elif retcode == 0 and response.status is httplib.ACCEPTED: elif retcode == 0 and response.status is http_client.ACCEPTED:
retcode = errno.EAGAIN retcode = errno.EAGAIN
try: try:
data = response.read() data = response.read()
@ -192,8 +192,8 @@ class DPLCommand(object):
e) e)
retcode = errno.ENOEXEC retcode = errno.ENOEXEC
elif (retcode == 0 and elif (retcode == 0 and
response.status in [httplib.OK, httplib.CREATED] and response.status in [http_client.OK, http_client.CREATED] and
httplib.NO_CONTENT not in expected_status): http_client.NO_CONTENT not in expected_status):
try: try:
data = response.read() data = response.read()
data = json.loads(data) data = json.loads(data)
@ -229,7 +229,8 @@ class DPLVolume(object):
def get_server_info(self): def get_server_info(self):
method = 'GET' method = 'GET'
url = ('/%s/%s/' % (DPL_VER_V1, DPL_OBJ_SYSTEM)) url = ('/%s/%s/' % (DPL_VER_V1, DPL_OBJ_SYSTEM))
return self._execute(method, url, None, [httplib.OK, httplib.ACCEPTED]) return self._execute(method, url, None,
[http_client.OK, http_client.ACCEPTED])
def create_vdev(self, volumeID, volumeName, volumeDesc, poolID, volumeSize, def create_vdev(self, volumeID, volumeName, volumeDesc, poolID, volumeSize,
fthinprovision=True, maximum_snapshot=MAXSNAPSHOTS, fthinprovision=True, maximum_snapshot=MAXSNAPSHOTS,
@ -253,7 +254,8 @@ class DPLVolume(object):
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def extend_vdev(self, volumeID, volumeName, volumeDesc, volumeSize, def extend_vdev(self, volumeID, volumeName, volumeDesc, volumeSize,
maximum_snapshot=MAXSNAPSHOTS, snapshot_quota=None): maximum_snapshot=MAXSNAPSHOTS, snapshot_quota=None):
@ -274,7 +276,8 @@ class DPLVolume(object):
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def delete_vdev(self, volumeID, force=True): def delete_vdev(self, volumeID, force=True):
method = 'DELETE' method = 'DELETE'
@ -286,8 +289,8 @@ class DPLVolume(object):
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.NOT_FOUND, [http_client.OK, http_client.ACCEPTED,
httplib.NO_CONTENT]) http_client.NOT_FOUND, http_client.NO_CONTENT])
def create_vdev_from_snapshot(self, vdevID, vdevDisplayName, vdevDesc, def create_vdev_from_snapshot(self, vdevID, vdevDisplayName, vdevDesc,
snapshotID, poolID, fthinprovision=True, snapshotID, poolID, fthinprovision=True,
@ -314,7 +317,8 @@ class DPLVolume(object):
params['copy'] = self._gen_snapshot_url(vdevID, snapshotID) params['copy'] = self._gen_snapshot_url(vdevID, snapshotID)
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def spawn_vdev_from_snapshot(self, new_vol_id, src_vol_id, def spawn_vdev_from_snapshot(self, new_vol_id, src_vol_id,
vol_display_name, description, snap_id): vol_display_name, description, snap_id):
@ -333,17 +337,19 @@ class DPLVolume(object):
params['copy'] = self._gen_snapshot_url(src_vol_id, snap_id) params['copy'] = self._gen_snapshot_url(src_vol_id, snap_id)
return self._execute(method, url, params, return self._execute(method, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def get_pools(self): def get_pools(self):
method = 'GET' method = 'GET'
url = '/%s/%s/' % (DPL_VER_V1, DPL_OBJ_POOL) url = '/%s/%s/' % (DPL_VER_V1, DPL_OBJ_POOL)
return self._execute(method, url, None, [httplib.OK]) return self._execute(method, url, None, [http_client.OK])
def get_pool(self, poolid): def get_pool(self, poolid):
method = 'GET' method = 'GET'
url = '/%s/%s/%s/' % (DPL_VER_V1, DPL_OBJ_POOL, poolid) url = '/%s/%s/%s/' % (DPL_VER_V1, DPL_OBJ_POOL, poolid)
return self._execute(method, url, None, [httplib.OK, httplib.ACCEPTED]) return self._execute(method, url, None,
[http_client.OK, http_client.ACCEPTED])
def clone_vdev(self, SourceVolumeID, NewVolumeID, poolID, volumeName, def clone_vdev(self, SourceVolumeID, NewVolumeID, poolID, volumeName,
volumeDesc, volumeSize, fthinprovision=True, volumeDesc, volumeSize, fthinprovision=True,
@ -369,7 +375,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.CREATED, httplib.ACCEPTED]) [http_client.OK, http_client.CREATED,
http_client.ACCEPTED])
def create_vdev_snapshot(self, vdevid, snapshotid, snapshotname='', def create_vdev_snapshot(self, vdevid, snapshotid, snapshotname='',
snapshotdes='', isgroup=False): snapshotdes='', isgroup=False):
@ -392,7 +399,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.CREATED, httplib.ACCEPTED]) [http_client.OK, http_client.CREATED,
http_client.ACCEPTED])
def get_vdev(self, vdevid): def get_vdev(self, vdevid):
method = 'GET' method = 'GET'
@ -400,7 +408,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK, httplib.ACCEPTED, httplib.NOT_FOUND]) [http_client.OK, http_client.ACCEPTED,
http_client.NOT_FOUND])
def get_vdev_status(self, vdevid, eventid): def get_vdev_status(self, vdevid, eventid):
method = 'GET' method = 'GET'
@ -409,7 +418,7 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK, httplib.NOT_FOUND]) [http_client.OK, http_client.NOT_FOUND])
def get_pool_status(self, poolid, eventid): def get_pool_status(self, poolid, eventid):
method = 'GET' method = 'GET'
@ -418,7 +427,7 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK, httplib.NOT_FOUND]) [http_client.OK, http_client.NOT_FOUND])
def assign_vdev(self, vdevid, iqn, lunname, portal, lunid=0): def assign_vdev(self, vdevid, iqn, lunname, portal, lunid=0):
method = 'PUT' method = 'PUT'
@ -445,7 +454,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def assign_vdev_fc(self, vdevid, targetwwpn, initiatorwwpn, lunname, def assign_vdev_fc(self, vdevid, targetwwpn, initiatorwwpn, lunname,
lunid=-1): lunid=-1):
@ -468,7 +478,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def unassign_vdev(self, vdevid, initiatorIqn, targetIqn=''): def unassign_vdev(self, vdevid, initiatorIqn, targetIqn=''):
method = 'PUT' method = 'PUT'
@ -490,8 +501,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, [http_client.OK, http_client.ACCEPTED,
httplib.NO_CONTENT, httplib.NOT_FOUND]) http_client.NO_CONTENT, http_client.NOT_FOUND])
def unassign_vdev_fc(self, vdevid, targetwwpn, initiatorwwpns): def unassign_vdev_fc(self, vdevid, targetwwpn, initiatorwwpns):
method = 'PUT' method = 'PUT'
@ -512,8 +523,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED, [http_client.OK, http_client.ACCEPTED,
httplib.NO_CONTENT, httplib.NOT_FOUND]) http_client.NO_CONTENT, http_client.NOT_FOUND])
def delete_vdev_snapshot(self, objID, snapshotID, isGroup=False): def delete_vdev_snapshot(self, objID, snapshotID, isGroup=False):
method = 'DELETE' method = 'DELETE'
@ -529,8 +540,8 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK, httplib.ACCEPTED, httplib.NO_CONTENT, [http_client.OK, http_client.ACCEPTED,
httplib.NOT_FOUND]) http_client.NO_CONTENT, http_client.NOT_FOUND])
def rollback_vdev(self, vdevid, snapshotid): def rollback_vdev(self, vdevid, snapshotid):
method = 'PUT' method = 'PUT'
@ -541,7 +552,7 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, params, url, params,
[httplib.OK, httplib.ACCEPTED]) [http_client.OK, http_client.ACCEPTED])
def list_vdev_snapshots(self, vdevid, isGroup=False): def list_vdev_snapshots(self, vdevid, isGroup=False):
method = 'GET' method = 'GET'
@ -554,7 +565,7 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK]) [http_client.OK])
def query_vdev_snapshot(self, vdevid, snapshotID, isGroup=False): def query_vdev_snapshot(self, vdevid, snapshotID, isGroup=False):
method = 'GET' method = 'GET'
@ -567,7 +578,7 @@ class DPLVolume(object):
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK]) [http_client.OK])
def create_target(self, targetID, protocol, displayName, targetAddress, def create_target(self, targetID, protocol, displayName, targetAddress,
description=''): description=''):
@ -584,19 +595,20 @@ class DPLVolume(object):
metadata['display_name'] = displayName metadata['display_name'] = displayName
metadata['display_description'] = description metadata['display_description'] = description
metadata['address'] = targetAddress metadata['address'] = targetAddress
return self._execute(method, url, params, [httplib.OK]) return self._execute(method, url, params, [http_client.OK])
def get_target(self, targetID): def get_target(self, targetID):
method = 'GET' method = 'GET'
url = '/%s/%s/%s/' % (DPL_VER_V1, DPL_OBJ_EXPORT, targetID) url = '/%s/%s/%s/' % (DPL_VER_V1, DPL_OBJ_EXPORT, targetID)
return self._execute(method, url, None, [httplib.OK]) return self._execute(method, url, None, [http_client.OK])
def delete_target(self, targetID): def delete_target(self, targetID):
method = 'DELETE' method = 'DELETE'
url = '/%s/%s/%s/' % (DPL_VER_V1, DPL_OBJ_EXPORT, targetID) url = '/%s/%s/%s/' % (DPL_VER_V1, DPL_OBJ_EXPORT, targetID)
return self._execute(method, return self._execute(method,
url, None, url, None,
[httplib.OK, httplib.ACCEPTED, httplib.NOT_FOUND]) [http_client.OK, http_client.ACCEPTED,
http_client.NOT_FOUND])
def get_target_list(self, type='target'): def get_target_list(self, type='target'):
# type = target/initiator # type = target/initiator
@ -605,7 +617,7 @@ class DPLVolume(object):
url = '/%s/%s/' % (DPL_VER_V1, DPL_OBJ_EXPORT) url = '/%s/%s/' % (DPL_VER_V1, DPL_OBJ_EXPORT)
else: else:
url = '/%s/%s/?type=%s' % (DPL_VER_V1, DPL_OBJ_EXPORT, type) url = '/%s/%s/?type=%s' % (DPL_VER_V1, DPL_OBJ_EXPORT, type)
return self._execute(method, url, None, [httplib.OK]) return self._execute(method, url, None, [http_client.OK])
def get_sns_table(self, wwpn): def get_sns_table(self, wwpn):
method = 'PUT' method = 'PUT'
@ -614,7 +626,7 @@ class DPLVolume(object):
params['metadata'] = {} params['metadata'] = {}
params['metadata']['protocol'] = 'fc' params['metadata']['protocol'] = 'fc'
params['metadata']['address'] = str(wwpn) params['metadata']['address'] = str(wwpn)
return self._execute(method, url, params, [httplib.OK]) return self._execute(method, url, params, [http_client.OK])
def create_vg(self, groupID, groupName, groupDesc='', listVolume=None, def create_vg(self, groupID, groupName, groupDesc='', listVolume=None,
maxSnapshots=MAXSNAPSHOTS, rotationSnapshot=True): maxSnapshots=MAXSNAPSHOTS, rotationSnapshot=True):
@ -634,7 +646,8 @@ class DPLVolume(object):
metadata['properties'] = properties metadata['properties'] = properties
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, url, params, return self._execute(method, url, params,
[httplib.OK, httplib.ACCEPTED, httplib.CREATED]) [http_client.OK, http_client.ACCEPTED,
http_client.CREATED])
def get_vg_list(self, vgtype=None): def get_vg_list(self, vgtype=None):
method = 'GET' method = 'GET'
@ -642,12 +655,12 @@ class DPLVolume(object):
url = '/%s/?volume_group_type=%s' % (DPL_OBJ_VOLUMEGROUP, vgtype) url = '/%s/?volume_group_type=%s' % (DPL_OBJ_VOLUMEGROUP, vgtype)
else: else:
url = '/%s/' % (DPL_OBJ_VOLUMEGROUP) url = '/%s/' % (DPL_OBJ_VOLUMEGROUP)
return self._execute(method, url, None, [httplib.OK]) return self._execute(method, url, None, [http_client.OK])
def get_vg(self, groupID): def get_vg(self, groupID):
method = 'GET' method = 'GET'
url = '/%s/%s/' % (DPL_OBJ_VOLUMEGROUP, groupID) url = '/%s/%s/' % (DPL_OBJ_VOLUMEGROUP, groupID)
return self._execute(method, url, None, [httplib.OK]) return self._execute(method, url, None, [http_client.OK])
def delete_vg(self, groupID, force=True): def delete_vg(self, groupID, force=True):
method = 'DELETE' method = 'DELETE'
@ -657,7 +670,7 @@ class DPLVolume(object):
metadata['force'] = force metadata['force'] = force
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, url, params, return self._execute(method, url, params,
[httplib.NO_CONTENT, httplib.NOT_FOUND]) [http_client.NO_CONTENT, http_client.NOT_FOUND])
def join_vg(self, volumeID, groupID): def join_vg(self, volumeID, groupID):
method = 'PUT' method = 'PUT'
@ -669,7 +682,7 @@ class DPLVolume(object):
metadata['volume'].append(volumeID) metadata['volume'].append(volumeID)
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, url, params, return self._execute(method, url, params,
[httplib.OK, httplib.ACCEPTED]) [http_client.OK, http_client.ACCEPTED])
def leave_vg(self, volumeID, groupID): def leave_vg(self, volumeID, groupID):
method = 'PUT' method = 'PUT'
@ -681,7 +694,7 @@ class DPLVolume(object):
metadata['volume'].append(volumeID) metadata['volume'].append(volumeID)
params['metadata'] = metadata params['metadata'] = metadata
return self._execute(method, url, params, return self._execute(method, url, params,
[httplib.OK, httplib.ACCEPTED]) [http_client.OK, http_client.ACCEPTED])
class DPLCOMMONDriver(driver.ConsistencyGroupVD, driver.ExtendVD, class DPLCOMMONDriver(driver.ConsistencyGroupVD, driver.ExtendVD,

View File

@ -15,12 +15,12 @@
ZFS Storage Appliance REST API Client Programmatic Interface ZFS Storage Appliance REST API Client Programmatic Interface
""" """
import httplib
import json import json
import StringIO import StringIO
import time import time
from oslo_log import log from oslo_log import log
from six.moves import http_client
from six.moves import urllib from six.moves import urllib
from cinder.i18n import _LE, _LI from cinder.i18n import _LE, _LI
@ -35,40 +35,40 @@ class Status(object):
pass pass
#: Request return OK #: Request return OK
OK = httplib.OK OK = http_client.OK
#: New resource created successfully #: New resource created successfully
CREATED = httplib.CREATED CREATED = http_client.CREATED
#: Command accepted #: Command accepted
ACCEPTED = httplib.ACCEPTED ACCEPTED = http_client.ACCEPTED
#: Command returned OK but no data will be returned #: Command returned OK but no data will be returned
NO_CONTENT = httplib.NO_CONTENT NO_CONTENT = http_client.NO_CONTENT
#: Bad Request #: Bad Request
BAD_REQUEST = httplib.BAD_REQUEST BAD_REQUEST = http_client.BAD_REQUEST
#: User is not authorized #: User is not authorized
UNAUTHORIZED = httplib.UNAUTHORIZED UNAUTHORIZED = http_client.UNAUTHORIZED
#: The request is not allowed #: The request is not allowed
FORBIDDEN = httplib.FORBIDDEN FORBIDDEN = http_client.FORBIDDEN
#: The requested resource was not found #: The requested resource was not found
NOT_FOUND = httplib.NOT_FOUND NOT_FOUND = http_client.NOT_FOUND
#: The request is not allowed #: The request is not allowed
NOT_ALLOWED = httplib.METHOD_NOT_ALLOWED NOT_ALLOWED = http_client.METHOD_NOT_ALLOWED
#: Request timed out #: Request timed out
TIMEOUT = httplib.REQUEST_TIMEOUT TIMEOUT = http_client.REQUEST_TIMEOUT
#: Invalid request #: Invalid request
CONFLICT = httplib.CONFLICT CONFLICT = http_client.CONFLICT
#: Service Unavailable #: Service Unavailable
BUSY = httplib.SERVICE_UNAVAILABLE BUSY = http_client.SERVICE_UNAVAILABLE
class RestResult(object): class RestResult(object):
@ -90,7 +90,7 @@ class RestResult(object):
if self.error: if self.error:
self.status = self.error.code self.status = self.error.code
self.data = httplib.responses[self.status] self.data = http_client.responses[self.status]
LOG.debug('Response code: %s', self.status) LOG.debug('Response code: %s', self.status)
LOG.debug('Response data: %s', self.data) LOG.debug('Response data: %s', self.data)
@ -121,8 +121,8 @@ class RestClientError(Exception):
self.code = status self.code = status
self.name = name self.name = name
self.msg = message self.msg = message
if status in httplib.responses: if status in http_client.responses:
self.msg = httplib.responses[status] self.msg = http_client.responses[status]
def __str__(self): def __str__(self):
return "%d %s %s" % (self.code, self.name, self.msg) return "%d %s %s" % (self.code, self.name, self.msg)
@ -173,14 +173,14 @@ class RestClientURL(object):
try: try:
result = self.post("/access/v1") result = self.post("/access/v1")
del self.headers['authorization'] del self.headers['authorization']
if result.status == httplib.CREATED: if result.status == http_client.CREATED:
self.headers['x-auth-session'] = \ self.headers['x-auth-session'] = \
result.get_header('x-auth-session') result.get_header('x-auth-session')
self.do_logout = True self.do_logout = True
LOG.info(_LI('ZFSSA version: %s'), LOG.info(_LI('ZFSSA version: %s'),
result.get_header('x-zfssa-version')) result.get_header('x-zfssa-version'))
elif result.status == httplib.NOT_FOUND: elif result.status == http_client.NOT_FOUND:
raise RestClientError(result.status, name="ERR_RESTError", raise RestClientError(result.status, name="ERR_RESTError",
message="REST Not Available: \ message="REST Not Available: \
Please Upgrade") Please Upgrade")
@ -277,19 +277,19 @@ class RestClientURL(object):
try: try:
response = urllib.request.urlopen(req, timeout=self.timeout) response = urllib.request.urlopen(req, timeout=self.timeout)
except urllib.error.HTTPError as err: except urllib.error.HTTPError as err:
if err.code == httplib.NOT_FOUND: if err.code == http_client.NOT_FOUND:
LOG.debug('REST Not Found: %s', err.code) LOG.debug('REST Not Found: %s', err.code)
else: else:
LOG.error(_LE('REST Not Available: %s'), err.code) LOG.error(_LE('REST Not Available: %s'), err.code)
if err.code == httplib.SERVICE_UNAVAILABLE and \ if err.code == http_client.SERVICE_UNAVAILABLE and \
retry < maxreqretries: retry < maxreqretries:
retry += 1 retry += 1
time.sleep(1) time.sleep(1)
LOG.error(_LE('Server Busy retry request: %s'), retry) LOG.error(_LE('Server Busy retry request: %s'), retry)
continue continue
if (err.code == httplib.UNAUTHORIZED or if (err.code == http_client.UNAUTHORIZED or
err.code == httplib.INTERNAL_SERVER_ERROR) and \ err.code == http_client.INTERNAL_SERVER_ERROR) and \
'/access/v1' not in zfssaurl: '/access/v1' not in zfssaurl:
try: try:
LOG.error(_LE('Authorizing request: %(zfssaurl)s ' LOG.error(_LE('Authorizing request: %(zfssaurl)s '
@ -313,7 +313,7 @@ class RestClientURL(object):
break break
if response and response.getcode() == httplib.SERVICE_UNAVAILABLE and \ if response and response.getcode() == http_client.SERVICE_UNAVAILABLE and \
retry >= maxreqretries: retry >= maxreqretries:
raise RestClientError(response.getcode(), name="ERR_HTTPError", raise RestClientError(response.getcode(), name="ERR_HTTPError",
message="REST Not Available: Disabled") message="REST Not Available: Disabled")

View File

@ -15,10 +15,10 @@
ZFS Storage Appliance WebDAV Client ZFS Storage Appliance WebDAV Client
""" """
import httplib
import time import time
from oslo_log import log from oslo_log import log
from six.moves import http_client
from six.moves import urllib from six.moves import urllib
from cinder import exception from cinder import exception
@ -31,15 +31,15 @@ bad_gateway_err = _('Check the state of the http service. Also ensure that '
'in cinder.conf.') 'in cinder.conf.')
WebDAVHTTPErrors = { WebDAVHTTPErrors = {
httplib.UNAUTHORIZED: _('User not authorized to perform WebDAV ' http_client.UNAUTHORIZED: _('User not authorized to perform WebDAV '
'operations.'), 'operations.'),
httplib.BAD_GATEWAY: bad_gateway_err, http_client.BAD_GATEWAY: bad_gateway_err,
httplib.FORBIDDEN: _('Check access permissions for the ZFS share assigned ' http_client.FORBIDDEN: _('Check access permissions for the ZFS share '
'to this driver.'), 'assigned to this driver.'),
httplib.NOT_FOUND: _('The source volume for this WebDAV operation not ' http_client.NOT_FOUND: _('The source volume for this WebDAV operation not '
'found.'), 'found.'),
httplib.INSUFFICIENT_STORAGE: _('Not enough storage space in the ZFS ' http_client.INSUFFICIENT_STORAGE: _('Not enough storage space in the ZFS '
'share to perform this operation.') 'share to perform this operation.')
} }
WebDAVErrors = { WebDAVErrors = {
@ -58,8 +58,8 @@ class ZFSSAWebDAVClient(object):
def _lookup_error(self, error): def _lookup_error(self, error):
msg = '' msg = ''
if error in httplib.responses: if error in http_client.responses:
msg = httplib.responses[error] msg = http_client.responses[error]
if error in WebDAVHTTPErrors: if error in WebDAVHTTPErrors:
msg = WebDAVHTTPErrors[error] msg = WebDAVHTTPErrors[error]
@ -92,7 +92,7 @@ class ZFSSAWebDAVClient(object):
'%(method)s call.'), '%(method)s call.'),
{'code': err.code, 'method': method}) {'code': err.code, 'method': method})
if err.code == httplib.INTERNAL_SERVER_ERROR: if err.code == http_client.INTERNAL_SERVER_ERROR:
LOG.error(_LE('WebDAV operation failed with error code: ' LOG.error(_LE('WebDAV operation failed with error code: '
'%(code)s reason: %(reason)s Retry attempt ' '%(code)s reason: %(reason)s Retry attempt '
'%(retry)s in progress.'), '%(retry)s in progress.'),
@ -109,10 +109,11 @@ class ZFSSAWebDAVClient(object):
src=src_file, dst=dst_file, src=src_file, dst=dst_file,
method=method) method=method)
except httplib.BadStatusLine as err: except http_client.BadStatusLine as err:
msg = self._lookup_error('BadStatusLine') msg = self._lookup_error('BadStatusLine')
code = 'http_client.BadStatusLine'
raise exception.WebDAVClientError(msg=msg, raise exception.WebDAVClientError(msg=msg,
code='httplib.BadStatusLine', code=code,
src=src_file, dst=dst_file, src=src_file, dst=dst_file,
method=method) method=method)

View File

@ -33,3 +33,9 @@ max-args=6
[Variables] [Variables]
dummy-variables-rgx=_ dummy-variables-rgx=_
[Typecheck]
# Disable warnings on the HTTPSConnection classes because pylint doesn't
# support importing from six.moves yet, see:
# https://bitbucket.org/logilab/pylint/issue/550/
ignored-classes=HTTPSConnection