Remove six

We don't need this in a Python 3-only world.

Change-Id: I95ac1e2d63932730206e5290fc38a0b00dad8fb2
This commit is contained in:
jacky06 2020-05-04 13:37:31 +08:00
parent 7130d65e9e
commit b5150230ce
62 changed files with 194 additions and 282 deletions

View File

@ -18,7 +18,6 @@ import functools
import inspect import inspect
from oslo_config import cfg from oslo_config import cfg
import six
import docker import docker
@ -44,7 +43,7 @@ def filter_data(f):
obj = new_list obj = new_list
if isinstance(obj, dict): if isinstance(obj, dict):
for k, v in obj.items(): for k, v in obj.items():
if isinstance(k, six.string_types): if isinstance(k, str):
obj[k.lower()] = _filter(v) obj[k.lower()] = _filter(v)
return obj return obj
return _filter(out) return _filter(out)
@ -76,13 +75,7 @@ class DockerHTTPClient(docker.APIClient):
self._setup_decorators() self._setup_decorators()
def _setup_decorators(self): def _setup_decorators(self):
# NOTE(junbo.li): we need to distinguish class methods types member_type = inspect.isfunction
# for py2 and py3, because the concept of 'unbound methods' has
# been removed from the python3.x
if six.PY3:
member_type = inspect.isfunction
else:
member_type = inspect.ismethod
for name, member in inspect.getmembers(self, member_type): for name, member in inspect.getmembers(self, member_type):
if not name.startswith('_'): if not name.startswith('_'):
setattr(self, name, filter_data(member)) setattr(self, name, filter_data(member))

View File

@ -20,7 +20,6 @@ A Docker Hypervisor which allows running Linux Containers instead of VMs.
import os import os
import shutil import shutil
import six
import socket import socket
import time import time
@ -234,8 +233,6 @@ class DockerDriver(driver.ComputeDriver):
self._stop_firewall(instance, network_info) self._stop_firewall(instance, network_info)
def _encode_utf8(self, value): def _encode_utf8(self, value):
if six.PY2 and not isinstance(value, six.text_type):
value = six.text_type(value)
return value.encode('utf-8') return value.encode('utf-8')
def _find_container_by_instance(self, instance): def _find_container_by_instance(self, instance):

View File

@ -139,7 +139,6 @@ rfc3986==1.1.0
Routes==2.4.1 Routes==2.4.1
simplegeneric==0.8.1 simplegeneric==0.8.1
simplejson==3.13.2 simplejson==3.13.2
six==1.10.0
smmap2==2.0.3 smmap2==2.0.3
snowballstemmer==1.2.1 snowballstemmer==1.2.1
Sphinx==1.6.2 Sphinx==1.6.2

View File

@ -36,7 +36,6 @@ os-brick>=2.2.0 # Apache-2.0
os-resource-classes>=0.1.0 # Apache-2.0 os-resource-classes>=0.1.0 # Apache-2.0
os-traits>=0.15.0 # Apache-2.0 os-traits>=0.15.0 # Apache-2.0
os-vif>=1.15.1 # Apache-2.0 os-vif>=1.15.1 # Apache-2.0
six>=1.10.0 # MIT
SQLAlchemy!=1.1.5,!=1.1.6,!=1.1.7,!=1.1.8,>=1.0.10 # MIT SQLAlchemy!=1.1.5,!=1.1.6,!=1.1.7,!=1.1.8,>=1.0.10 # MIT
stevedore>=1.20.0 # Apache-2.0 stevedore>=1.20.0 # Apache-2.0
docker>=2.4.2 # Apache-2.0 docker>=2.4.2 # Apache-2.0

View File

@ -13,7 +13,6 @@
# under the License. # under the License.
import operator import operator
import six
import pecan import pecan
from pecan import rest from pecan import rest
@ -93,8 +92,7 @@ class ControllerMetaclass(type):
cls_dict) cls_dict)
@six.add_metaclass(ControllerMetaclass) class Controller(rest.RestController, metaclass=ControllerMetaclass):
class Controller(rest.RestController):
"""Base Rest Controller""" """Base Rest Controller"""
@pecan.expose('json') @pecan.expose('json')

View File

@ -15,7 +15,6 @@
from oslo_log import log as logging from oslo_log import log as logging
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import pecan import pecan
import six
from zun.api.controllers import base from zun.api.controllers import base
from zun.api.controllers import link from zun.api.controllers import link
@ -49,7 +48,7 @@ def check_policy_on_capsule(capsule, action):
def check_capsule_template(tpl): def check_capsule_template(tpl):
# TODO(kevinz): add volume spec check # TODO(kevinz): add volume spec check
tpl_json = tpl tpl_json = tpl
if isinstance(tpl, six.string_types): if isinstance(tpl, str):
try: try:
tpl_json = jsonutils.loads(tpl) tpl_json = jsonutils.loads(tpl)
except Exception as e: except Exception as e:
@ -478,7 +477,7 @@ class CapsuleController(base.Controller):
cinder_api.delete_volume(volume.id) cinder_api.delete_volume(volume.id)
except Exception as exc: except Exception as exc:
LOG.error('Error on deleting volume "%s": %s.', LOG.error('Error on deleting volume "%s": %s.',
volume.id, six.text_type(exc)) volume.id, str(exc))
# Since the container and capsule database model has been created, # Since the container and capsule database model has been created,
# we need to delete them here due to the volume create failed. # we need to delete them here due to the volume create failed.

View File

@ -20,7 +20,6 @@ from oslo_log import log as logging
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import pecan import pecan
import six
from zun.api.controllers import base from zun.api.controllers import base
from zun.api.controllers import link from zun.api.controllers import link
@ -258,7 +257,7 @@ class ContainersController(base.Controller):
# '"nginx" "-g" "daemon off;"' -> ["nginx", "-g", "daemon off;"] # '"nginx" "-g" "daemon off;"' -> ["nginx", "-g", "daemon off;"]
command = container_dict.pop('command', None) command = container_dict.pop('command', None)
if command is not None: if command is not None:
if isinstance(command, six.string_types): if isinstance(command, str):
command = shlex.split(command) command = shlex.split(command)
container_dict['command'] = command container_dict['command'] = command
@ -481,7 +480,7 @@ class ContainersController(base.Controller):
project_id) project_id)
total = None total = None
try: try:
if isinstance(count_as_dict[res_name], six.integer_types): if isinstance(count_as_dict[res_name], int):
total = count_as_dict[res_name] + int(res_delta) total = count_as_dict[res_name] + int(res_delta)
else: else:
total = float(count_as_dict[res_name]) + \ total = float(count_as_dict[res_name]) + \

View File

@ -12,8 +12,6 @@
# 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 six
from oslo_serialization import jsonutils as json from oslo_serialization import jsonutils as json
from webob import exc from webob import exc
@ -64,7 +62,7 @@ class HTTPNotAcceptableAPIVersion(exc.HTTPNotAcceptable):
err['links'] = [links] err['links'] = [links]
err['title'] = "Requested microversion is unsupported" err['title'] = "Requested microversion is unsupported"
self.app_iter = [six.b(json.dump_as_bytes(err))] self.app_iter = [json.dump_as_bytes(err).encode("latin-1")]
self.headers['Content-Length'] = str(len(self.app_iter[0])) self.headers['Content-Length'] = str(len(self.app_iter[0]))
return super(HTTPNotAcceptableAPIVersion, self).__call__( return super(HTTPNotAcceptableAPIVersion, self).__call__(

View File

@ -18,8 +18,6 @@ response with one formatted so the client can parse it.
Based on pecan.middleware.errordocument Based on pecan.middleware.errordocument
""" """
import six
from oslo_serialization import jsonutils as json from oslo_serialization import jsonutils as json
from zun.common.i18n import _ from zun.common.i18n import _
@ -90,7 +88,7 @@ class ParsableErrorMiddleware(object):
'links': [] 'links': []
}) })
body = [six.b(json.dumps({'errors': errs}))] body = [json.dumps({'errors': errs}).encode("latin-1")]
state['headers'].append(('Content-Type', 'application/json')) state['headers'].append(('Content-Type', 'application/json'))
state['headers'].append(('Content-Length', str(len(body[0])))) state['headers'].append(('Content-Length', str(len(body[0]))))

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
import jsonschema import jsonschema
import six
from zun.common import exception from zun.common import exception
from zun.common.i18n import _ from zun.common.i18n import _
@ -46,7 +45,7 @@ class SchemaValidator(object):
"'%(path)s'. Value: '%(value)s'. %(message)s") "'%(path)s'. Value: '%(value)s'. %(message)s")
detail = detail % { detail = detail % {
'path': ex.path.pop(), 'value': ex.instance, 'path': ex.path.pop(), 'value': ex.instance,
'message': six.text_type(ex) 'message': str(ex)
} }
else: else:
detail = ex.message detail = ex.message

View File

@ -11,6 +11,7 @@
# under the License. # under the License.
import abc import abc
from http import client as httplib
import requests import requests
import traceback import traceback
@ -18,8 +19,6 @@ from os_vif.objects import base
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 oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from six.moves import http_client as httplib
from zun.common import consts from zun.common import consts
from zun.common import exception from zun.common import exception
@ -30,8 +29,7 @@ LOG = logging.getLogger(__name__)
CONF = cfg.CONF CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta) class CNIRunner(object, metaclass=abc.ABCMeta):
class CNIRunner(object):
# TODO(ivc): extend SUPPORTED_VERSIONS and format output based on # TODO(ivc): extend SUPPORTED_VERSIONS and format output based on
# requested params.CNI_VERSION and/or params.config.cniVersion # requested params.CNI_VERSION and/or params.config.cniVersion
VERSION = '0.3.1' VERSION = '0.3.1'

View File

@ -12,7 +12,6 @@
import abc import abc
import errno import errno
import six
import os_vif import os_vif
from oslo_config import cfg from oslo_config import cfg
@ -30,8 +29,7 @@ LOG = logging.getLogger(__name__)
CONF = cfg.CONF CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta) class BaseBindingDriver(object, metaclass=abc.ABCMeta):
class BaseBindingDriver(object):
"""Interface to attach ports to capsules.""" """Interface to attach ports to capsules."""
@abc.abstractmethod @abc.abstractmethod

View File

@ -12,7 +12,6 @@
import os import os
import signal import signal
import six
import sys import sys
import os_vif import os_vif
@ -32,10 +31,7 @@ _CNI_TIMEOUT = 180
def main(): def main():
if six.PY3: d = jsonutils.load(sys.stdin.buffer)
d = jsonutils.load(sys.stdin.buffer)
else:
d = jsonutils.load(sys.stdin)
cni_conf = utils.CNIConfig(d) cni_conf = utils.CNIConfig(d)
args = (['--config-file', cni_conf.zun_conf] if 'zun_conf' in d args = (['--config-file', cni_conf.zun_conf] if 'zun_conf' in d
else []) else [])

View File

@ -19,12 +19,12 @@ import time
import cotyledon import cotyledon
import flask import flask
from futurist import periodics from futurist import periodics
from http import client as httplib
from oslo_concurrency import lockutils from oslo_concurrency import lockutils
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 oslo_serialization import jsonutils from oslo_serialization import jsonutils
from pyroute2.ipdb import transactional from pyroute2.ipdb import transactional
from six.moves import http_client as httplib
from zun.cni.plugins import zun_cni_registry from zun.cni.plugins import zun_cni_registry
from zun.cni import utils as cni_utils from zun.cni import utils as cni_utils

View File

@ -15,7 +15,6 @@ import functools
import copy import copy
from oslo_context import context from oslo_context import context
from oslo_utils import timeutils from oslo_utils import timeutils
import six
from zun.common import exception from zun.common import exception
from zun.common import policy from zun.common import policy
@ -69,7 +68,7 @@ class RequestContext(context.RequestContext):
if not timestamp: if not timestamp:
timestamp = timeutils.utcnow() timestamp = timeutils.utcnow()
if isinstance(timestamp, six.string_types): if isinstance(timestamp, str):
timestamp = timeutils.parse_strtime(timestamp) timestamp = timeutils.parse_strtime(timestamp)
self.timestamp = timestamp self.timestamp = timestamp

View File

@ -29,7 +29,6 @@ from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import pecan import pecan
import six
from webob import util as woutil from webob import util as woutil
from zun.common.i18n import _ from zun.common.i18n import _
@ -145,7 +144,7 @@ def wrap_pecan_controller_exception(func):
'faultcode': 'Server', 'faultcode': 'Server',
'status_code': status_code, 'status_code': status_code,
'title': woutil.status_reasons[status_code], 'title': woutil.status_reasons[status_code],
'description': six.text_type(OBFUSCATED_MSG % log_correlation_id), 'description': str(OBFUSCATED_MSG % log_correlation_id),
} }
def _func_client_error(excp, status_code): def _func_client_error(excp, status_code):
@ -154,8 +153,8 @@ def wrap_pecan_controller_exception(func):
'faultcode': 'Client', 'faultcode': 'Client',
'faultstring': convert_excp_to_err_code(excp.__class__.__name__), 'faultstring': convert_excp_to_err_code(excp.__class__.__name__),
'status_code': status_code, 'status_code': status_code,
'title': six.text_type(excp), 'title': str(excp),
'description': six.text_type(excp), 'description': str(excp),
} }
return wrap_controller_exception(func, return wrap_controller_exception(func,
@ -217,9 +216,7 @@ class ZunException(Exception):
super(ZunException, self).__init__(self.message) super(ZunException, self).__init__(self.message)
def __str__(self): def __str__(self):
if six.PY3: return self.message
return self.message
return self.message.encode('utf-8')
def __unicode__(self): def __unicode__(self):
return self.message return self.message
@ -228,7 +225,7 @@ class ZunException(Exception):
if self.__class__.__name__.endswith('_Remote'): if self.__class__.__name__.endswith('_Remote'):
return self.args[0] return self.args[0]
else: else:
return six.text_type(self) return str(self)
class ObjectNotFound(ZunException): class ObjectNotFound(ZunException):

View File

@ -17,10 +17,9 @@ The IDs each comprise 12 (lower-case) alphanumeric characters.
import base64 import base64
from oslo_utils import uuidutils from oslo_utils import uuidutils
import struct
import uuid import uuid
import six
from zun.common.i18n import _ from zun.common.i18n import _
@ -31,10 +30,11 @@ def _to_byte_string(value, num_bits):
required. required.
""" """
shifts = six.moves.xrange(num_bits - 8, -8, -8) shifts = range(num_bits - 8, -8, -8)
byte_at = lambda off: ( # noqa: E731 byte_at = lambda off: ( # noqa: E731
(value >> off if off >= 0 else value << -off) & 0xff) (value >> off if off >= 0 else value << -off) & 0xff)
return ''.join(six.int2byte(byte_at(offset)) for offset in shifts) return ''.join(struct.Struct(">B").pack(byte_at(offset))
for offset in shifts)
def get_id(source_uuid): def get_id(source_uuid):
@ -43,7 +43,7 @@ def get_id(source_uuid):
The supplied UUID must be a version 4 UUID object. The supplied UUID must be a version 4 UUID object.
""" """
if isinstance(source_uuid, six.string_types): if isinstance(source_uuid, str):
source_uuid = uuid.UUID(source_uuid) source_uuid = uuid.UUID(source_uuid)
if source_uuid.version != 4: if source_uuid.version != 4:
raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version) raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)
@ -52,12 +52,9 @@ def get_id(source_uuid):
# (see RFC4122, Section 4.4) # (see RFC4122, Section 4.4)
random_bytes = _to_byte_string(source_uuid.time, 60) random_bytes = _to_byte_string(source_uuid.time, 60)
# The first 12 bytes (= 60 bits) of base32-encoded output is our data # The first 12 bytes (= 60 bits) of base32-encoded output is our data
encoded = base64.b32encode(six.b(random_bytes))[:12] encoded = base64.b32encode(random_bytes.encode("latin-1"))[:12]
if six.PY3: return encoded.lower().decode('utf-8')
return encoded.lower().decode('utf-8')
else:
return encoded.lower()
def generate_id(): def generate_id():

View File

@ -33,7 +33,6 @@ from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import strutils from oslo_utils import strutils
import pecan import pecan
import six
from zun.api import utils as api_utils from zun.api import utils as api_utils
from zun.common import clients from zun.common import clients
@ -139,7 +138,7 @@ def safe_rstrip(value, chars=None):
:return: Stripped value. :return: Stripped value.
""" """
if not isinstance(value, six.string_types): if not isinstance(value, str):
LOG.warning( LOG.warning(
"Failed to remove trailing character. Returning original object. " "Failed to remove trailing character. Returning original object. "
"Supplied object is not a string: %s.", value) "Supplied object is not a string: %s.", value)
@ -227,9 +226,9 @@ def translate_exception(function):
return function(self, context, *args, **kwargs) return function(self, context, *args, **kwargs)
except Exception as e: except Exception as e:
if not isinstance(e, exception.ZunException): if not isinstance(e, exception.ZunException):
LOG.exception("Unexpected error: %s", six.text_type(e)) LOG.exception("Unexpected error: %s", str(e))
e = exception.ZunException("Unexpected error: %s" e = exception.ZunException("Unexpected error: %s"
% six.text_type(e)) % str(e))
raise e raise e
raise raise
@ -338,7 +337,7 @@ def custom_execute(*cmd, **kwargs):
except processutils.ProcessExecutionError as e: except processutils.ProcessExecutionError as e:
sanitized_cmd = strutils.mask_password(' '.join(cmd)) sanitized_cmd = strutils.mask_password(' '.join(cmd))
raise exception.CommandError(cmd=sanitized_cmd, raise exception.CommandError(cmd=sanitized_cmd,
error=six.text_type(e)) error=str(e))
def get_root_helper(): def get_root_helper():
@ -670,10 +669,10 @@ def wrap_exception():
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(reraise=False): with excutils.save_and_reraise_exception(reraise=False):
LOG.error("Error occurred while calling Docker API: %s", LOG.error("Error occurred while calling Docker API: %s",
six.text_type(e)) str(e))
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(reraise=False): with excutils.save_and_reraise_exception(reraise=False):
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
return decorated_function return decorated_function
return helper return helper
@ -690,7 +689,7 @@ def is_less_than(x, y):
def encode_file_data(data): def encode_file_data(data):
if six.PY3 and isinstance(data, str): if isinstance(data, str):
data = data.encode('utf-8') data = data.encode('utf-8')
return base64.b64encode(data).decode('utf-8') return base64.b64encode(data).decode('utf-8')
@ -707,13 +706,10 @@ def strtime(at):
return at.strftime("%Y-%m-%dT%H:%M:%S.%f") return at.strftime("%Y-%m-%dT%H:%M:%S.%f")
if six.PY2: @contextlib.contextmanager
nested_contexts = contextlib.nested def nested_contexts(*contexts):
else: with contextlib.ExitStack() as stack:
@contextlib.contextmanager yield [stack.enter_context(c) for c in contexts]
def nested_contexts(*contexts):
with contextlib.ExitStack() as stack:
yield [stack.enter_context(c) for c in contexts]
def convert_mb_to_ceil_gb(mb_value): def convert_mb_to_ceil_gb(mb_value):

View File

@ -22,7 +22,6 @@ from oslo_service import periodic_task
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import timeutils from oslo_utils import timeutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import consts from zun.common import consts
from zun.common import context from zun.common import context
@ -165,7 +164,7 @@ class Manager(periodic_task.PeriodicTasks):
self._detach_volumes(context, container) self._detach_volumes(context, container)
except Exception as e: except Exception as e:
LOG.exception("Failed to detach volumes: %s", LOG.exception("Failed to detach volumes: %s",
six.text_type(e)) str(e))
container.status = consts.ERROR container.status = consts.ERROR
container.status_reason = error container.status_reason = error
@ -322,18 +321,18 @@ class Manager(periodic_task.PeriodicTasks):
self.driver.load_image(image['path']) self.driver.load_image(image['path'])
except exception.ImageNotFound as e: except exception.ImageNotFound as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error(six.text_type(e)) LOG.error(str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error("Error occurred while calling Docker image " LOG.error("Error occurred while calling Docker image "
"API: %s", six.text_type(e)) "API: %s", str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception("Unexpected exception: %s", LOG.exception("Unexpected exception: %s",
six.text_type(e)) str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
container.image_driver = image.get('driver') container.image_driver = image.get('driver')
container.save(context) container.save(context)
@ -355,14 +354,14 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error("Error occurred while calling Docker create " LOG.error("Error occurred while calling Docker create "
"API: %s", six.text_type(e)) "API: %s", str(e))
self._fail_container(context, container, six.text_type(e), self._fail_container(context, container, str(e),
unset_host=True) unset_host=True)
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception("Unexpected exception: %s", LOG.exception("Unexpected exception: %s",
six.text_type(e)) str(e))
self._fail_container(context, container, six.text_type(e), self._fail_container(context, container, str(e),
unset_host=True) unset_host=True)
@wrap_container_event(prefix='compute') @wrap_container_event(prefix='compute')
@ -381,8 +380,8 @@ class Manager(periodic_task.PeriodicTasks):
except exception.ResourcesUnavailable as e: except exception.ResourcesUnavailable as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception("Container resource claim failed: %s", LOG.exception("Container resource claim failed: %s",
six.text_type(e)) str(e))
self._fail_container(context, container, six.text_type(e), self._fail_container(context, container, str(e),
unset_host=True) unset_host=True)
self.reportclient.delete_allocation_for_container( self.reportclient.delete_allocation_for_container(
context, container.uuid) context, container.uuid)
@ -417,7 +416,7 @@ class Manager(periodic_task.PeriodicTasks):
self._refresh_attached_volumes(requested_volumes, volmap) self._refresh_attached_volumes(requested_volumes, volmap)
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
self._fail_container(context, container, six.text_type(e), self._fail_container(context, container, str(e),
unset_host=True) unset_host=True)
def _attach_volume(self, context, container, volmap): def _attach_volume(self, context, container, volmap):
@ -503,13 +502,13 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error("Error occurred while calling Docker start " LOG.error("Error occurred while calling Docker start "
"API: %s", six.text_type(e)) "API: %s", str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception("Unexpected exception: %s", LOG.exception("Unexpected exception: %s",
six.text_type(e)) str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
@translate_exception @translate_exception
def container_delete(self, context, container, force=False): def container_delete(self, context, container, force=False):
@ -533,12 +532,12 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
with excutils.save_and_reraise_exception(reraise=reraise): with excutils.save_and_reraise_exception(reraise=reraise):
LOG.error("Error occurred while calling Docker " LOG.error("Error occurred while calling Docker "
"delete API: %s", six.text_type(e)) "delete API: %s", str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(reraise=reraise): with excutils.save_and_reraise_exception(reraise=reraise):
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
self._detach_volumes(context, container, reraise=reraise) self._detach_volumes(context, container, reraise=reraise)
@ -602,10 +601,10 @@ class Manager(periodic_task.PeriodicTasks):
return container return container
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker show API: %s", LOG.error("Error occurred while calling Docker show API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@wrap_exception() @wrap_exception()
@ -667,7 +666,7 @@ class Manager(periodic_task.PeriodicTasks):
network_info = self._get_network_info(context, container) network_info = self._get_network_info(context, container)
except Exception as e: except Exception as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
# NOTE(hongbin): capsule shouldn't reach here # NOTE(hongbin): capsule shouldn't reach here
if self.driver.check_container_exist(container): if self.driver.check_container_exist(container):
for addr in container.addresses.values(): for addr in container.addresses.values():
@ -682,9 +681,9 @@ class Manager(periodic_task.PeriodicTasks):
LOG.error("Rebuild container: %s failed, " LOG.error("Rebuild container: %s failed, "
"reason of failure is: %s", "reason of failure is: %s",
container.uuid, container.uuid,
six.text_type(e)) str(e))
self._fail_container(context, container, self._fail_container(context, container,
six.text_type(e)) str(e))
try: try:
created_container = self._do_container_create_base( created_container = self._do_container_create_base(
@ -696,7 +695,7 @@ class Manager(periodic_task.PeriodicTasks):
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error("Rebuild container:%s failed, " LOG.error("Rebuild container:%s failed, "
"reason of failure is: %s", container.uuid, e) "reason of failure is: %s", container.uuid, e)
self._fail_container(context, container, six.text_type(e)) self._fail_container(context, container, str(e))
LOG.info("rebuild container: %s success", created_container.uuid) LOG.info("rebuild container: %s success", created_container.uuid)
if run: if run:
@ -793,10 +792,10 @@ class Manager(periodic_task.PeriodicTasks):
since=since) since=since)
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker logs API: %s", LOG.error("Error occurred while calling Docker logs API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@translate_exception @translate_exception
@ -826,10 +825,10 @@ class Manager(periodic_task.PeriodicTasks):
'token': token} 'token': token}
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker exec API: %s", LOG.error("Error occurred while calling Docker exec API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@translate_exception @translate_exception
@ -840,10 +839,10 @@ class Manager(periodic_task.PeriodicTasks):
return self.driver.execute_resize(exec_id, height, width) return self.driver.execute_resize(exec_id, height, width)
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker exec API: %s", LOG.error("Error occurred while calling Docker exec API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@wrap_exception() @wrap_exception()
@ -891,10 +890,10 @@ class Manager(periodic_task.PeriodicTasks):
except exception.ResourcesUnavailable as e: except exception.ResourcesUnavailable as e:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.exception("Update container resource claim failed: %s", LOG.exception("Update container resource claim failed: %s",
six.text_type(e)) str(e))
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling docker API: %s", LOG.error("Error occurred while calling docker API: %s",
six.text_type(e)) str(e))
raise raise
@translate_exception @translate_exception
@ -911,7 +910,7 @@ class Manager(periodic_task.PeriodicTasks):
except Exception as e: except Exception as e:
LOG.error("Error occurred while calling " LOG.error("Error occurred while calling "
"get websocket url function: %s", "get websocket url function: %s",
six.text_type(e)) str(e))
raise raise
@translate_exception @translate_exception
@ -924,7 +923,7 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling docker " LOG.error("Error occurred while calling docker "
"resize API: %s", "resize API: %s",
six.text_type(e)) str(e))
raise raise
@translate_exception @translate_exception
@ -936,10 +935,10 @@ class Manager(periodic_task.PeriodicTasks):
return self.driver.top(context, container, ps_args) return self.driver.top(context, container, ps_args)
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker top API: %s", LOG.error("Error occurred while calling Docker top API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@translate_exception @translate_exception
@ -954,10 +953,10 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
LOG.error( LOG.error(
"Error occurred while calling Docker get_archive API: %s", "Error occurred while calling Docker get_archive API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@translate_exception @translate_exception
@ -972,10 +971,10 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
LOG.error( LOG.error(
"Error occurred while calling Docker put_archive API: %s", "Error occurred while calling Docker put_archive API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@translate_exception @translate_exception
@ -986,10 +985,10 @@ class Manager(periodic_task.PeriodicTasks):
return self.driver.stats(context, container) return self.driver.stats(context, container)
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker stats API: %s", LOG.error("Error occurred while calling Docker stats API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
raise raise
@translate_exception @translate_exception
@ -1006,7 +1005,7 @@ class Manager(periodic_task.PeriodicTasks):
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling glance " LOG.error("Error occurred while calling glance "
"create_image API: %s", "create_image API: %s",
six.text_type(e)) str(e))
@utils.synchronized(container.uuid) @utils.synchronized(container.uuid)
def do_container_commit(): def do_container_commit():
@ -1024,7 +1023,7 @@ class Manager(periodic_task.PeriodicTasks):
tag, data, glance.GlanceDriver()) tag, data, glance.GlanceDriver())
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception while uploading image: %s", LOG.exception("Unexpected exception while uploading image: %s",
six.text_type(e)) str(e))
# NOTE(hongbin): capsule shouldn't reach here # NOTE(hongbin): capsule shouldn't reach here
self.driver.delete_committed_image(context, snapshot_image.id, self.driver.delete_committed_image(context, snapshot_image.id,
glance.GlanceDriver()) glance.GlanceDriver())
@ -1056,7 +1055,7 @@ class Manager(periodic_task.PeriodicTasks):
container_image = self.driver.get_image(repository + ':' + tag) container_image = self.driver.get_image(repository + ':' + tag)
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling docker commit API: %s", LOG.error("Error occurred while calling docker commit API: %s",
six.text_type(e)) str(e))
# NOTE(hongbin): capsule shouldn't reach here # NOTE(hongbin): capsule shouldn't reach here
self.driver.delete_committed_image(context, snapshot_image.id, self.driver.delete_committed_image(context, snapshot_image.id,
glance.GlanceDriver()) glance.GlanceDriver())
@ -1068,7 +1067,7 @@ class Manager(periodic_task.PeriodicTasks):
container = self.driver.unpause(context, container) container = self.driver.unpause(context, container)
container.save(context) container.save(context)
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", six.text_type(e)) LOG.exception("Unexpected exception: %s", str(e))
LOG.debug('Upload image %s to glance', container_image_id) LOG.debug('Upload image %s to glance', container_image_id)
self._do_container_image_upload(context, snapshot_image, self._do_container_image_upload(context, snapshot_image,
@ -1123,15 +1122,15 @@ class Manager(periodic_task.PeriodicTasks):
image.size = image_dict['Size'] image.size = image_dict['Size']
image.save() image.save()
except exception.ImageNotFound as e: except exception.ImageNotFound as e:
LOG.error(six.text_type(e)) LOG.error(str(e))
return return
except exception.DockerError as e: except exception.DockerError as e:
LOG.error("Error occurred while calling Docker image API: %s", LOG.error("Error occurred while calling Docker image API: %s",
six.text_type(e)) str(e))
raise raise
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception: %s", LOG.exception("Unexpected exception: %s",
six.text_type(e)) str(e))
raise raise
@translate_exception @translate_exception
@ -1145,7 +1144,7 @@ class Manager(periodic_task.PeriodicTasks):
image_driver_name, exact_match) image_driver_name, exact_match)
except Exception as e: except Exception as e:
LOG.exception("Unexpected exception while searching image: %s", LOG.exception("Unexpected exception while searching image: %s",
six.text_type(e)) str(e))
raise raise
@periodic_task.periodic_task(run_immediately=True) @periodic_task.periodic_task(run_immediately=True)

View File

@ -23,7 +23,6 @@ from oslo_log import log as logging
from oslo_utils import timeutils from oslo_utils import timeutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import psutil import psutil
import six
import tenacity import tenacity
from zun.common import consts from zun.common import consts
@ -77,7 +76,7 @@ def handle_not_found(e, context, container, do_not_raise=False):
container.status = consts.DELETED container.status = consts.DELETED
else: else:
container.status = consts.ERROR container.status = consts.ERROR
container.status_reason = six.text_type(e) container.status_reason = str(e)
container.save(context) container.save(context)
if do_not_raise: if do_not_raise:
return return
@ -169,8 +168,8 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
LOG.exception('Unknown exception occurred while ' LOG.exception('Unknown exception occurred while '
'deleting image %s: %s', 'deleting image %s: %s',
img_id, img_id,
six.text_type(e)) str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def images(self, repo, quiet=False): def images(self, repo, quiet=False):
with docker_utils.docker_client() as docker: with docker_utils.docker_client() as docker:
@ -191,8 +190,8 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
raise raise
except Exception as e: except Exception as e:
LOG.exception('Unknown exception occurred while loading ' LOG.exception('Unknown exception occurred while loading '
'image: %s', six.text_type(e)) 'image: %s', str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
return image, image_loaded return image, image_loaded
@ -208,16 +207,16 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
raise raise
except Exception as e: except Exception as e:
LOG.exception('Unknown exception occurred while searching ' LOG.exception('Unknown exception occurred while searching '
'for image: %s', six.text_type(e)) 'for image: %s', str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def create_image(self, context, image_name, image_driver): def create_image(self, context, image_name, image_driver):
try: try:
img = image_driver.create_image(context, image_name) img = image_driver.create_image(context, image_name)
except Exception as e: except Exception as e:
LOG.exception('Unknown exception occurred while creating ' LOG.exception('Unknown exception occurred while creating '
'image: %s', six.text_type(e)) 'image: %s', str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
return img return img
def upload_image_data(self, context, image, image_tag, image_data, def upload_image_data(self, context, image, image_tag, image_data,
@ -234,8 +233,8 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
image_data) image_data)
except Exception as e: except Exception as e:
LOG.exception('Unknown exception occurred while uploading ' LOG.exception('Unknown exception occurred while uploading '
'image: %s', six.text_type(e)) 'image: %s', str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
return img return img
def read_tar_image(self, image): def read_tar_image(self, image):
@ -547,7 +546,7 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
container.status = consts.ERROR container.status = consts.ERROR
msg = "No such container: %s in docker" % \ msg = "No such container: %s in docker" % \
(container.container_id) (container.container_id)
container.status_reason = six.text_type(msg) container.status_reason = str(msg)
container.save(context) container.save(context)
except Exception as e: except Exception as e:
LOG.warning("heal container with rebuilding failed, " LOG.warning("heal container with rebuilding failed, "
@ -579,8 +578,8 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
for container in containers for container in containers
if container.container_id} if container.container_id}
for cid in (six.viewkeys(id_to_container_map) & for cid in (id_to_container_map.keys() &
six.viewkeys(id_to_local_container_map)): id_to_local_container_map.keys()):
container = id_to_container_map[cid] container = id_to_container_map[cid]
# sync status # sync status
local_container = id_to_local_container_map[cid] local_container = id_to_local_container_map[cid]
@ -957,7 +956,7 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
stream, stat = docker.get_archive( stream, stat = docker.get_archive(
container.container_id, path) container.container_id, path)
if isinstance(stream, types.GeneratorType): if isinstance(stream, types.GeneratorType):
filedata = six.b("").join(stream) filedata = ''.encode("latin-1").join(stream)
else: else:
filedata = stream.read() filedata = stream.read()
return filedata, stat return filedata, stat
@ -1028,8 +1027,6 @@ class DockerDriver(driver.BaseDriver, driver.ContainerDriver,
return docker.commit(container.container_id, repository, tag) return docker.commit(container.container_id, repository, tag)
def _encode_utf8(self, value): def _encode_utf8(self, value):
if six.PY2 and not isinstance(value, six.text_type):
value = six.text_type(value)
return value.encode('utf-8') return value.encode('utf-8')
def _get_or_create_docker_network(self, context, network_api, def _get_or_create_docker_network(self, context, network_api,

View File

@ -45,7 +45,7 @@ def docker_client():
**client_kwargs **client_kwargs
) )
except errors.APIError as e: except errors.APIError as e:
desired_exc = exception.DockerError(error_msg=six.text_type(e)) desired_exc = exception.DockerError(error_msg=str(e))
six.reraise(type(desired_exc), desired_exc, sys.exc_info()[2]) six.reraise(type(desired_exc), desired_exc, sys.exc_info()[2])
@ -99,5 +99,5 @@ class DockerHTTPClient(docker.APIClient):
except errors.APIError as e: except errors.APIError as e:
if "process not found for container" in str(e): if "process not found for container" in str(e):
raise exception.Invalid(_( raise exception.Invalid(_(
"no such exec instance: %s") % six.text_type(e)) "no such exec instance: %s") % str(e))
raise raise

View File

@ -15,7 +15,6 @@
from oslo_concurrency import processutils from oslo_concurrency import processutils
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from zun.common import exception from zun.common import exception
from zun.common import utils from zun.common import utils
@ -92,7 +91,7 @@ class Host(object):
addresses.append(address) addresses.append(address)
except processutils.ProcessExecutionError as e: except processutils.ProcessExecutionError as e:
raise exception.CommandError(cmd='lspci', raise exception.CommandError(cmd='lspci',
error=six.text_type(e)) error=str(e))
pci_info = [] pci_info = []
for addr in addresses: for addr in addresses:

View File

@ -17,7 +17,6 @@ SQLAlchemy models for container service
from oslo_db.sqlalchemy import models from oslo_db.sqlalchemy import models
from oslo_serialization import jsonutils as json from oslo_serialization import jsonutils as json
from oslo_utils import timeutils from oslo_utils import timeutils
import six.moves.urllib.parse as urlparse
from sqlalchemy import Boolean from sqlalchemy import Boolean
from sqlalchemy import Column from sqlalchemy import Column
from sqlalchemy import DateTime from sqlalchemy import DateTime
@ -33,6 +32,7 @@ from sqlalchemy import sql
from sqlalchemy import String from sqlalchemy import String
from sqlalchemy import Text from sqlalchemy import Text
from sqlalchemy.types import TypeDecorator, TEXT from sqlalchemy.types import TypeDecorator, TEXT
from urllib import parse as urlparse
from zun.common import consts from zun.common import consts
import zun.conf import zun.conf

View File

@ -14,8 +14,6 @@
# limitations under the License. # limitations under the License.
from docker import errors from docker import errors
import six
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
@ -45,13 +43,13 @@ class DockerDriver(driver.ContainerImageDriver):
except errors.ImageNotFound: except errors.ImageNotFound:
return return
except errors.APIError as api_error: except errors.APIError as api_error:
raise exception.ZunException(six.text_type(api_error)) raise exception.ZunException(str(api_error))
except Exception as e: except Exception as e:
LOG.exception('Unknown exception occurred while deleting ' LOG.exception('Unknown exception occurred while deleting '
'image %s in glance:%s', 'image %s in glance:%s',
img_id, img_id,
six.text_type(e)) str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def _search_image_on_host(self, repo, tag): def _search_image_on_host(self, repo, tag):
with docker_utils.docker_client() as docker: with docker_utils.docker_client() as docker:
@ -82,7 +80,7 @@ class DockerDriver(driver.ContainerImageDriver):
try: try:
docker.pull(repo, tag=tag, auth_config=auth_config) docker.pull(repo, tag=tag, auth_config=auth_config)
except errors.NotFound as e: except errors.NotFound as e:
raise exception.ImageNotFound(message=six.text_type(e)) raise exception.ImageNotFound(message=str(e))
except errors.APIError: except errors.APIError:
LOG.exception('Error on pulling image') LOG.exception('Error on pulling image')
message = _('Error on pulling image: %(repo)s:%(tag)s') % { message = _('Error on pulling image: %(repo)s:%(tag)s') % {
@ -131,7 +129,7 @@ class DockerDriver(driver.ContainerImageDriver):
# TODO(hongbin): search image by both name and tag # TODO(hongbin): search image by both name and tag
images = docker.search(image_name) images = docker.search(image_name)
except errors.APIError as api_error: except errors.APIError as api_error:
raise exception.ZunException(six.text_type(api_error)) raise exception.ZunException(str(api_error))
except Exception as e: except Exception as e:
msg = _('Cannot search image in docker: {0}') msg = _('Cannot search image in docker: {0}')
raise exception.ZunException(msg.format(e)) raise exception.ZunException(msg.format(e))

View File

@ -12,7 +12,6 @@
# 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 six
import sys import sys
from oslo_log import log as logging from oslo_log import log as logging
@ -50,7 +49,7 @@ def load_image_driver(image_driver=None):
if not isinstance(driver, ContainerImageDriver): if not isinstance(driver, ContainerImageDriver):
raise Exception(_('Expected driver of type: %s') % raise Exception(_('Expected driver of type: %s') %
six.text_type(ContainerImageDriver)) str(ContainerImageDriver))
return driver return driver
except Exception: except Exception:

View File

@ -12,12 +12,12 @@
# limitations under the License. # limitations under the License.
import hashlib import hashlib
import io
import os import os
import types import types
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import fileutils from oslo_utils import fileutils
import six
from zun.common import exception from zun.common import exception
from zun.common.i18n import _ from zun.common.i18n import _
@ -118,7 +118,7 @@ class GlanceDriver(driver.ContainerImageDriver):
try: try:
return utils.find_images(context, repo, tag, exact_match) return utils.find_images(context, repo, tag, exact_match)
except Exception as e: except Exception as e:
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def create_image(self, context, image_name): def create_image(self, context, image_name):
"""Create an image.""" """Create an image."""
@ -127,7 +127,7 @@ class GlanceDriver(driver.ContainerImageDriver):
# Return a created image # Return a created image
return utils.create_image(context, image_name) return utils.create_image(context, image_name)
except Exception as e: except Exception as e:
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def update_image(self, context, img_id, disk_format='qcow2', def update_image(self, context, img_id, disk_format='qcow2',
container_format='docker', tag=None): container_format='docker', tag=None):
@ -140,7 +140,7 @@ class GlanceDriver(driver.ContainerImageDriver):
return utils.update_image(context, img_id, disk_format, return utils.update_image(context, img_id, disk_format,
container_format, tags=tags) container_format, tags=tags)
except Exception as e: except Exception as e:
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def upload_image_data(self, context, img_id, data): def upload_image_data(self, context, img_id, data):
"""Upload an image.""" """Upload an image."""
@ -151,12 +151,12 @@ class GlanceDriver(driver.ContainerImageDriver):
# returns generator - related bugs [1]. # returns generator - related bugs [1].
# These lines makes image_data readable. # These lines makes image_data readable.
# [1] https://bugs.launchpad.net/zun/+bug/1753080 # [1] https://bugs.launchpad.net/zun/+bug/1753080
data = six.b('').join(data) data = ''.encode("latin-1").join(data)
data = six.BytesIO(data) data = io.BytesIO(data)
return utils.upload_image_data(context, img_id, data) return utils.upload_image_data(context, img_id, data)
except Exception as e: except Exception as e:
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def delete_committed_image(self, context, img_id): def delete_committed_image(self, context, img_id):
"""Delete a committed image.""" """Delete a committed image."""
@ -167,8 +167,8 @@ class GlanceDriver(driver.ContainerImageDriver):
LOG.exception('Unknown exception occurred while deleting ' LOG.exception('Unknown exception occurred while deleting '
'image %s in glance: %s', 'image %s in glance: %s',
img_id, img_id,
six.text_type(e)) str(e))
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))
def delete_image_tar(self, context, image): def delete_image_tar(self, context, image):
"""Delete image tar file that pull from glance""" """Delete image tar file that pull from glance"""
@ -181,4 +181,4 @@ class GlanceDriver(driver.ContainerImageDriver):
os.unlink(tarfile) os.unlink(tarfile)
except Exception as e: except Exception as e:
LOG.exception('Cannot delete tar file %s', tarfile) LOG.exception('Cannot delete tar file %s', tarfile)
raise exception.ZunException(six.text_type(e)) raise exception.ZunException(str(e))

View File

@ -315,7 +315,7 @@ class KuryrNetwork(network.Network):
exc_info = sys.exc_info() exc_info = sys.exc_info()
if e.status_code == 400: if e.status_code == 400:
raise exception.SecurityGroupCannotBeApplied( raise exception.SecurityGroupCannotBeApplied(
six.text_type(e)) str(e))
else: else:
six.reraise(*exc_info) six.reraise(*exc_info)
except Exception: except Exception:
@ -348,7 +348,7 @@ class KuryrNetwork(network.Network):
exc_info = sys.exc_info() exc_info = sys.exc_info()
if e.status_code == 400: if e.status_code == 400:
raise exception.SecurityGroupCannotBeRemoved( raise exception.SecurityGroupCannotBeRemoved(
six.text_type(e)) str(e))
else: else:
six.reraise(*exc_info) six.reraise(*exc_info)
except Exception: except Exception:

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
import abc import abc
import six
from stevedore import driver from stevedore import driver
@ -32,8 +31,7 @@ def api(*args, **kwargs):
return network_api return network_api
@six.add_metaclass(abc.ABCMeta) class Network(object, metaclass=abc.ABCMeta):
class Network(object):
"""The base class that all Network classes should inherit from.""" """The base class that all Network classes should inherit from."""
def init(self, context, *args, **kwargs): def init(self, context, *args, **kwargs):

View File

@ -18,7 +18,6 @@ from neutronclient.common import exceptions as n_exceptions
from neutronclient.neutron import v2_0 as neutronv20 from neutronclient.neutron import v2_0 as neutronv20
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import clients from zun.common import clients
from zun.common import consts from zun.common import consts
@ -118,7 +117,7 @@ class NeutronAPI(object):
addresses = [] addresses = []
for fixed_ip in neutron_port['fixed_ips']: for fixed_ip in neutron_port['fixed_ips']:
ip_address = fixed_ip['ip_address'] ip_address = fixed_ip['ip_address']
ip = ipaddress.ip_address(six.text_type(ip_address)) ip = ipaddress.ip_address(str(ip_address))
if ip.version == 4: if ip.version == 4:
addresses.append({ addresses.append({
'addr': ip_address, 'addr': ip_address,

View File

@ -15,7 +15,6 @@ import traceback
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import timeutils from oslo_utils import timeutils
from oslo_versionedobjects import fields from oslo_versionedobjects import fields
import six
from zun.db import api as dbapi from zun.db import api as dbapi
from zun.objects import base from zun.objects import base
@ -173,8 +172,8 @@ class ContainerActionEvent(base.ZunPersistentObject, base.ZunObject):
def event_finish(cls, context, container_uuid, event_name, exc_val=None, def event_finish(cls, context, container_uuid, event_name, exc_val=None,
exc_tb=None, want_result=None): exc_tb=None, want_result=None):
if exc_val: if exc_val:
exc_val = six.text_type(exc_val) exc_val = str(exc_val)
if exc_tb and not isinstance(exc_tb, six.string_types): if exc_tb and not isinstance(exc_tb, str):
exc_tb = ''.join(traceback.format_tb(exc_tb)) exc_tb = ''.join(traceback.format_tb(exc_tb))
values = cls.pack_action_event_finish(context, container_uuid, values = cls.pack_action_event_finish(context, container_uuid,
event_name, exc_val=exc_val, event_name, exc_val=exc_val,

View File

@ -13,7 +13,6 @@
from os_vif.objects import vif from os_vif.objects import vif
from oslo_serialization import jsonutils as json from oslo_serialization import jsonutils as json
from oslo_versionedobjects import fields from oslo_versionedobjects import fields
import six
from zun.common import consts from zun.common import consts
@ -67,7 +66,7 @@ class ListOfIntegersField(fields.AutoTypedField):
class Json(fields.FieldType): class Json(fields.FieldType):
def coerce(self, obj, attr, value): def coerce(self, obj, attr, value):
if isinstance(value, six.string_types): if isinstance(value, str):
loaded = json.loads(value) loaded = json.loads(value)
return loaded return loaded
return value return value

View File

@ -19,7 +19,6 @@ from oslo_log import log as logging
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
from oslo_versionedobjects import fields from oslo_versionedobjects import fields
import six
from zun.common import exception from zun.common import exception
from zun.db import api as dbapi from zun.db import api as dbapi
@ -134,7 +133,7 @@ class PciDevice(base.ZunPersistentObject, base.ZunObject):
# "extra_info" dict: # "extra_info" dict:
# - "capabilities": dict of (strings/list of strings) # - "capabilities": dict of (strings/list of strings)
extra_info = self.extra_info extra_info = self.extra_info
data = (v if isinstance(v, six.string_types) else data = (v if isinstance(v, str) else
jsonutils.dumps(v)) jsonutils.dumps(v))
extra_info.update({k: data}) extra_info.update({k: data})
self.extra_info = extra_info self.extra_info = extra_info

View File

@ -17,7 +17,6 @@ import copy
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_versionedobjects import fields from oslo_versionedobjects import fields
import six
from zun.objects import base from zun.objects import base
@ -74,7 +73,7 @@ def from_pci_stats(pci_stats):
device pool objects, a simple dict or a list of such dicts. device pool objects, a simple dict or a list of such dicts.
""" """
pools = [] pools = []
if isinstance(pci_stats, six.string_types): if isinstance(pci_stats, str):
try: try:
pci_stats = jsonutils.loads(pci_stats) pci_stats = jsonutils.loads(pci_stats)
except (ValueError, TypeError): except (ValueError, TypeError):

View File

@ -15,8 +15,6 @@ import abc
import re import re
import string import string
import six
from zun.common import exception from zun.common import exception
from zun.pci import utils from zun.pci import utils
@ -46,8 +44,7 @@ def get_pci_dev_info(pci_obj, property, max, hex_value):
setattr(pci_obj, property, hex_value % v) setattr(pci_obj, property, hex_value % v)
@six.add_metaclass(abc.ABCMeta) class PciAddressSpec(object, metaclass=abc.ABCMeta):
class PciAddressSpec(object):
"""Abstract class for all PCI address spec styles """Abstract class for all PCI address spec styles
This class checks the address fields of the pci.passthrough_whitelist This class checks the address fields of the pci.passthrough_whitelist
@ -203,7 +200,7 @@ class WhitelistPciAddress(object):
def _init_address_fields(self, pci_addr): def _init_address_fields(self, pci_addr):
if not self.is_physical_function: if not self.is_physical_function:
if isinstance(pci_addr, six.string_types): if isinstance(pci_addr, str):
self.pci_address_spec = PciAddressGlobSpec(pci_addr) self.pci_address_spec = PciAddressGlobSpec(pci_addr)
elif isinstance(pci_addr, dict): elif isinstance(pci_addr, dict):
self.pci_address_spec = PciAddressRegexSpec(pci_addr) self.pci_address_spec = PciAddressRegexSpec(pci_addr)

View File

@ -18,7 +18,6 @@ import copy
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log as logging from oslo_log import log as logging
import six
from zun.common import exception from zun.common import exception
from zun.objects import fields from zun.objects import fields
@ -298,10 +297,6 @@ class PciDeviceStats(object):
def __eq__(self, other): def __eq__(self, other):
return self.pools == other.pools return self.pools == other.pools
if six.PY2:
def __ne__(self, other):
return not (self == other)
def to_device_pools_obj(self): def to_device_pools_obj(self):
"""Return the contents of the pools as a PciDevicePoolList object.""" """Return the contents of the pools as a PciDevicePoolList object."""
stats = [x for x in self] stats = [x for x in self]

View File

@ -27,7 +27,6 @@ from oslo_middleware import request_id
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import versionutils from oslo_utils import versionutils
import retrying import retrying
import six
from zun.common import clients from zun.common import clients
from zun.common import context as zun_context from zun.common import context as zun_context
@ -2111,7 +2110,7 @@ class SchedulerReportClient(object):
global_request_id=context.global_id) global_request_id=context.global_id)
except ks_exc.ClientException as ex: except ks_exc.ClientException as ex:
LOG.error('Failed to get resource provider by name: %s. Error: %s', LOG.error('Failed to get resource provider by name: %s. Error: %s',
name, six.text_type(ex)) name, str(ex))
raise exception.PlacementAPIConnectFailure() raise exception.PlacementAPIConnectFailure()
if resp.status_code == 200: if resp.status_code == 200:

View File

@ -21,14 +21,11 @@ Scheduler base class that all Schedulers should inherit from
import abc import abc
import six
from zun.api import servicegroup from zun.api import servicegroup
from zun import objects from zun import objects
@six.add_metaclass(abc.ABCMeta) class Scheduler(object, metaclass=abc.ABCMeta):
class Scheduler(object):
"""The base class that all Scheduler classes should inherit from.""" """The base class that all Scheduler classes should inherit from."""
def __init__(self): def __init__(self):

View File

@ -20,7 +20,7 @@ import re
import os_resource_classes as orc import os_resource_classes as orc
from oslo_log import log as logging from oslo_log import log as logging
from six.moves.urllib import parse from urllib import parse
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf

View File

@ -20,7 +20,7 @@ from unittest import mock
from keystonemiddleware import auth_token # noqa from keystonemiddleware import auth_token # noqa
import pecan import pecan
import pecan.testing import pecan.testing
from six.moves.urllib import parse as urlparse from urllib import parse as urlparse
from zun.api import hooks from zun.api import hooks
import zun.conf import zun.conf

View File

@ -13,7 +13,6 @@
import collections import collections
from unittest import mock from unittest import mock
import six
from webob import exc from webob import exc
from zun.api.controllers import base from zun.api.controllers import base
@ -86,8 +85,8 @@ class TestAPIBase(test_base.BaseTestCase):
]) ])
actual_value = collections.OrderedDict( actual_value = collections.OrderedDict(
sorted(test_api.as_dict().items())) sorted(test_api.as_dict().items()))
self.assertEqual(six.text_type(expected_value), self.assertEqual(str(expected_value),
six.text_type(actual_value)) str(actual_value))
class TestVersion(test_base.TestCase): class TestVersion(test_base.TestCase):

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
import collections import collections
import six
from zun.api.controllers import link as link_module from zun.api.controllers import link as link_module
from zun.tests import base as test_base from zun.tests import base as test_base
@ -29,5 +28,5 @@ class TestLink(test_base.BaseTestCase):
('href', 'http://localhost:8080/v1/'), ('href', 'http://localhost:8080/v1/'),
('rel', 'self') ('rel', 'self')
]) ])
self.assertEqual(six.text_type(expected_value), self.assertEqual(str(expected_value),
six.text_type(ordered_link)) str(ordered_link))

View File

@ -15,7 +15,6 @@ from unittest.mock import patch
from neutronclient.common import exceptions as n_exc from neutronclient.common import exceptions as n_exc
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from webtest.app import AppError from webtest.app import AppError
from zun.common import exception from zun.common import exception
@ -331,7 +330,7 @@ class TestContainerController(api_base.FunctionalTest):
self.assertEqual(1, len(requested_volumes)) self.assertEqual(1, len(requested_volumes))
self.assertEqual( self.assertEqual(
fake_volume_id, fake_volume_id,
six.next(six.itervalues(requested_volumes))[0].cinder_volume_id) next(iter(requested_volumes.values()))[0].cinder_volume_id)
exposed_ports = mock_container_create.call_args[0][1].exposed_ports exposed_ports = mock_container_create.call_args[0][1].exposed_ports
self.assertEqual(2, len(exposed_ports)) self.assertEqual(2, len(exposed_ports))
self.assertIn("80/tcp", exposed_ports) self.assertIn("80/tcp", exposed_ports)

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 imp
import inspect import inspect
from unittest import mock from unittest import mock
from oslo_utils import importutils from oslo_utils import importutils
from osprofiler import initializer as profiler_init from osprofiler import initializer as profiler_init
from osprofiler import opts as profiler_opts from osprofiler import opts as profiler_opts
import six.moves as six
from zun.common import profiler from zun.common import profiler
from zun import conf from zun import conf
@ -39,7 +39,7 @@ class TestProfiler(base.TestCase):
for clsname in classes: for clsname in classes:
# give the metaclass and trace_cls() decorator a chance to patch # give the metaclass and trace_cls() decorator a chance to patch
# methods of the classes above # methods of the classes above
six.reload_module( imp.reload(
importutils.import_module(clsname.rsplit('.', 1)[0])) importutils.import_module(clsname.rsplit('.', 1)[0]))
cls = importutils.import_class(clsname) cls = importutils.import_class(clsname)

View File

@ -14,8 +14,8 @@
from unittest import mock from unittest import mock
from io import StringIO
from oslo_utils import uuidutils from oslo_utils import uuidutils
from six import StringIO
from zun.common import consts from zun.common import consts
from zun.common import exception from zun.common import exception

View File

@ -14,7 +14,6 @@ import collections
from unittest import mock from unittest import mock
from oslo_config import cfg from oslo_config import cfg
import six
from zun.conf import opts from zun.conf import opts
from zun.tests import base from zun.tests import base
@ -24,7 +23,7 @@ class ConfTestCase(base.TestCase):
def test_list_opts(self): def test_list_opts(self):
for group, opt_list in opts.list_opts(): for group, opt_list in opts.list_opts():
if isinstance(group, six.string_types): if isinstance(group, str):
self.assertEqual('DEFAULT', group) self.assertEqual('DEFAULT', group)
else: else:
self.assertIsInstance(group, cfg.OptGroup) self.assertIsInstance(group, cfg.OptGroup)

View File

@ -12,11 +12,11 @@
# 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 builtins
from unittest import mock from unittest import mock
from unittest.mock import mock_open from unittest.mock import mock_open
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from zun.common import exception from zun.common import exception
from zun.container.os_capability.linux import os_capability_linux from zun.container.os_capability.linux import os_capability_linux
@ -68,7 +68,7 @@ class TestOSCapability(base.BaseTestCase):
data = ('MemTotal: 3882464 kB\nMemFree: 3514608 kB\n' data = ('MemTotal: 3882464 kB\nMemFree: 3514608 kB\n'
'MemAvailable: 3556372 kB\n') 'MemAvailable: 3556372 kB\n')
m_open = mock_open(read_data=data) m_open = mock_open(read_data=data)
with mock.patch.object(six.moves.builtins, "open", m_open, with mock.patch.object(builtins, "open", m_open,
create=True): create=True):
output = os_capability_linux.LinuxHost().get_host_mem() output = os_capability_linux.LinuxHost().get_host_mem()
used = (3882464 - 3556372) used = (3882464 - 3556372)

View File

@ -13,7 +13,6 @@
"""Tests for manipulating compute nodes via the DB API""" """Tests for manipulating compute nodes via the DB API"""
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -68,7 +67,7 @@ class DbComputeNodeTestCase(base.DbTestCase):
rp_uuid=uuidutils.generate_uuid(), rp_uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
hostname='node' + str(i)) hostname='node' + str(i))
uuids.append(six.text_type(node['uuid'])) uuids.append(str(node['uuid']))
res = dbapi.list_compute_nodes(self.context) res = dbapi.list_compute_nodes(self.context)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))
@ -81,7 +80,7 @@ class DbComputeNodeTestCase(base.DbTestCase):
rp_uuid=uuidutils.generate_uuid(), rp_uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
hostname='node' + str(i)) hostname='node' + str(i))
uuids.append(six.text_type(node.uuid)) uuids.append(str(node.uuid))
res = dbapi.list_compute_nodes(self.context, sort_key='uuid') res = dbapi.list_compute_nodes(self.context, sort_key='uuid')
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids) self.assertEqual(sorted(uuids), res_uuids)

View File

@ -13,7 +13,6 @@
"""Tests for manipulating Containers via the DB API""" """Tests for manipulating Containers via the DB API"""
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import consts from zun.common import consts
from zun.common import exception from zun.common import exception
@ -115,7 +114,7 @@ class DbContainerTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
name='container' + str(i)) name='container' + str(i))
uuids.append(six.text_type(container['uuid'])) uuids.append(str(container['uuid']))
res = dbapi.list_containers(self.context, consts.TYPE_CONTAINER) res = dbapi.list_containers(self.context, consts.TYPE_CONTAINER)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))
@ -127,7 +126,7 @@ class DbContainerTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
name='container' + str(i)) name='container' + str(i))
uuids.append(six.text_type(container.uuid)) uuids.append(str(container.uuid))
res = dbapi.list_containers( res = dbapi.list_containers(
self.context, consts.TYPE_CONTAINER, sort_key='uuid') self.context, consts.TYPE_CONTAINER, sort_key='uuid')
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -47,7 +46,7 @@ class DbExecInstanceTestCase(base.DbTestCase):
context=self.context, context=self.context,
container_id=1, container_id=1,
exec_id=uuidutils.generate_uuid()) exec_id=uuidutils.generate_uuid())
exec_ids.append(six.text_type(exec_inst['exec_id'])) exec_ids.append(str(exec_inst['exec_id']))
res = dbapi.list_exec_instances(self.context) res = dbapi.list_exec_instances(self.context)
res_exec_ids = [r.exec_id for r in res] res_exec_ids = [r.exec_id for r in res]
self.assertEqual(sorted(exec_ids), sorted(res_exec_ids)) self.assertEqual(sorted(exec_ids), sorted(res_exec_ids))
@ -60,7 +59,7 @@ class DbExecInstanceTestCase(base.DbTestCase):
context=self.context, context=self.context,
container_id=1, container_id=1,
exec_id=uuidutils.generate_uuid()) exec_id=uuidutils.generate_uuid())
exec_ids.append(six.text_type(exec_inst['exec_id'])) exec_ids.append(str(exec_inst['exec_id']))
res = dbapi.list_exec_instances(self.context, sort_key='exec_id') res = dbapi.list_exec_instances(self.context, sort_key='exec_id')
res_exec_ids = [r.exec_id for r in res] res_exec_ids = [r.exec_id for r in res]
self.assertEqual(sorted(exec_ids), res_exec_ids) self.assertEqual(sorted(exec_ids), res_exec_ids)

View File

@ -13,7 +13,6 @@
"""Tests for manipulating Images via the DB API""" """Tests for manipulating Images via the DB API"""
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
from zun.tests.unit.db import base from zun.tests.unit.db import base
@ -73,7 +72,7 @@ class DbImageTestCase(base.DbTestCase):
for i in range(1, 6): for i in range(1, 6):
image = utils.create_test_image( image = utils.create_test_image(
context=self.context, repo="testrepo" + str(i)) context=self.context, repo="testrepo" + str(i))
uuids.append(six.text_type(image['uuid'])) uuids.append(str(image['uuid']))
res = self.dbapi.list_images(self.context) res = self.dbapi.list_images(self.context)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))
@ -84,7 +83,7 @@ class DbImageTestCase(base.DbTestCase):
image = utils.create_test_image( image = utils.create_test_image(
context=self.context, uuid=uuidutils.generate_uuid(), context=self.context, uuid=uuidutils.generate_uuid(),
repo="testrepo" + str(i)) repo="testrepo" + str(i))
uuids.append(six.text_type(image.uuid)) uuids.append(str(image.uuid))
res = self.dbapi.list_images(self.context, sort_key='uuid') res = self.dbapi.list_images(self.context, sort_key='uuid')
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids) self.assertEqual(sorted(uuids), res_uuids)

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -49,7 +48,7 @@ class DbNetworkTestCase(base.DbTestCase):
context=self.context, context=self.context,
neutron_net_id=uuidutils.generate_uuid(), neutron_net_id=uuidutils.generate_uuid(),
name='network' + str(i)) name='network' + str(i))
uuids.append(six.text_type(network['uuid'])) uuids.append(str(network['uuid']))
res = dbapi.list_networks(self.context) res = dbapi.list_networks(self.context)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -88,7 +87,7 @@ class DbRegistryTestCase(base.DbTestCase):
context=self.context, context=self.context,
name='registry' + str(i), name='registry' + str(i),
password=password) password=password)
uuids.append(six.text_type(registry['uuid'])) uuids.append(str(registry['uuid']))
res = dbapi.list_registries(self.context) res = dbapi.list_registries(self.context)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))
@ -102,7 +101,7 @@ class DbRegistryTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
name='registry' + str(i)) name='registry' + str(i))
uuids.append(six.text_type(registry.uuid)) uuids.append(str(registry.uuid))
res = dbapi.list_registries(self.context, sort_key='uuid') res = dbapi.list_registries(self.context, sort_key='uuid')
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids) self.assertEqual(sorted(uuids), res_uuids)

View File

@ -11,8 +11,8 @@
# under the License. # under the License.
"""Tests for manipulating resource classes via the DB API""" """Tests for manipulating resource classes via the DB API"""
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -63,7 +63,7 @@ class DbResourceClassTestCase(base.DbTestCase):
context=self.context, context=self.context,
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
name='class' + str(i)) name='class' + str(i))
names.append(six.text_type(resource['name'])) names.append(str(resource['name']))
res = dbapi.list_resource_classes(self.context) res = dbapi.list_resource_classes(self.context)
res_names = [r.name for r in res] res_names = [r.name for r in res]
self.assertEqual(sorted(names), sorted(res_names)) self.assertEqual(sorted(names), sorted(res_names))
@ -75,7 +75,7 @@ class DbResourceClassTestCase(base.DbTestCase):
context=self.context, context=self.context,
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
name='class' + str(i)) name='class' + str(i))
names.append(six.text_type(resource.name)) names.append(str(resource.name))
res = dbapi.list_resource_classes(self.context, sort_key='name') res = dbapi.list_resource_classes(self.context, sort_key='name')
res_names = [r.name for r in res] res_names = [r.name for r in res]
self.assertEqual(sorted(names), res_names) self.assertEqual(sorted(names), res_names)

View File

@ -13,7 +13,6 @@
"""Tests for manipulating resource providers via the DB API""" """Tests for manipulating resource providers via the DB API"""
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -67,7 +66,7 @@ class DbResourceProviderTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
name='provider' + str(i)) name='provider' + str(i))
uuids.append(six.text_type(provider['uuid'])) uuids.append(str(provider['uuid']))
res = dbapi.list_resource_providers(self.context) res = dbapi.list_resource_providers(self.context)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))
@ -79,7 +78,7 @@ class DbResourceProviderTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
context=self.context, context=self.context,
name='provider' + str(i)) name='provider' + str(i))
uuids.append(six.text_type(provider.uuid)) uuids.append(str(provider.uuid))
res = dbapi.list_resource_providers(self.context, sort_key='uuid') res = dbapi.list_resource_providers(self.context, sort_key='uuid')
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids) self.assertEqual(sorted(uuids), res_uuids)

View File

@ -11,7 +11,6 @@
# under the License. # under the License.
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from zun.common import exception from zun.common import exception
import zun.conf import zun.conf
@ -61,7 +60,7 @@ class DbVolumeMappingTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
volume_id=volume.id, volume_id=volume.id,
context=self.context) context=self.context)
uuids.append(six.text_type(volume_mapping['uuid'])) uuids.append(str(volume_mapping['uuid']))
res = dbapi.list_volume_mappings(self.context) res = dbapi.list_volume_mappings(self.context)
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), sorted(res_uuids)) self.assertEqual(sorted(uuids), sorted(res_uuids))
@ -76,7 +75,7 @@ class DbVolumeMappingTestCase(base.DbTestCase):
uuid=uuidutils.generate_uuid(), uuid=uuidutils.generate_uuid(),
volume_id=volume.id, volume_id=volume.id,
context=self.context) context=self.context)
uuids.append(six.text_type(volume_mapping.uuid)) uuids.append(str(volume_mapping.uuid))
res = dbapi.list_volume_mappings(self.context, sort_key='uuid') res = dbapi.list_volume_mappings(self.context, sort_key='uuid')
res_uuids = [r.uuid for r in res] res_uuids = [r.uuid for r in res]
self.assertEqual(sorted(uuids), res_uuids) self.assertEqual(sorted(uuids), res_uuids)

View File

@ -14,8 +14,6 @@
from unittest import mock from unittest import mock
import six
from zun.common import exception from zun.common import exception
from zun.pci import devspec from zun.pci import devspec
from zun.tests import base from zun.tests import base
@ -211,7 +209,7 @@ class PciAddressTestCase(base.TestCase):
exc = self.assertRaises(exception.PciConfigInvalidWhitelist, exc = self.assertRaises(exception.PciConfigInvalidWhitelist,
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
msg = ('Invalid PCI devices Whitelist config invalid func 12:6') msg = ('Invalid PCI devices Whitelist config invalid func 12:6')
self.assertEqual(msg, six.text_type(exc)) self.assertEqual(msg, str(exc))
def test_max_func(self): def test_max_func(self):
pci_info = {"address": "0000:0a:00.%s" % (devspec.MAX_FUNC + 1), pci_info = {"address": "0000:0a:00.%s" % (devspec.MAX_FUNC + 1),
@ -220,7 +218,7 @@ class PciAddressTestCase(base.TestCase):
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
msg = ('Invalid PCI devices Whitelist config invalid func %x' msg = ('Invalid PCI devices Whitelist config invalid func %x'
% (devspec.MAX_FUNC + 1)) % (devspec.MAX_FUNC + 1))
self.assertEqual(msg, six.text_type(exc)) self.assertEqual(msg, str(exc))
def test_max_domain(self): def test_max_domain(self):
pci_info = {"address": "%x:0a:00.5" % (devspec.MAX_DOMAIN + 1), pci_info = {"address": "%x:0a:00.5" % (devspec.MAX_DOMAIN + 1),
@ -229,7 +227,7 @@ class PciAddressTestCase(base.TestCase):
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
msg = ('Invalid PCI devices Whitelist config invalid domain %x' msg = ('Invalid PCI devices Whitelist config invalid domain %x'
% (devspec.MAX_DOMAIN + 1)) % (devspec.MAX_DOMAIN + 1))
self.assertEqual(msg, six.text_type(exc)) self.assertEqual(msg, str(exc))
def test_max_bus(self): def test_max_bus(self):
pci_info = {"address": "0000:%x:00.5" % (devspec.MAX_BUS + 1), pci_info = {"address": "0000:%x:00.5" % (devspec.MAX_BUS + 1),
@ -238,7 +236,7 @@ class PciAddressTestCase(base.TestCase):
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
msg = ('Invalid PCI devices Whitelist config invalid bus %x' msg = ('Invalid PCI devices Whitelist config invalid bus %x'
% (devspec.MAX_BUS + 1)) % (devspec.MAX_BUS + 1))
self.assertEqual(msg, six.text_type(exc)) self.assertEqual(msg, str(exc))
def test_max_slot(self): def test_max_slot(self):
pci_info = {"address": "0000:0a:%x.5" % (devspec.MAX_SLOT + 1), pci_info = {"address": "0000:0a:%x.5" % (devspec.MAX_SLOT + 1),
@ -247,7 +245,7 @@ class PciAddressTestCase(base.TestCase):
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
msg = ('Invalid PCI devices Whitelist config invalid slot %x' msg = ('Invalid PCI devices Whitelist config invalid slot %x'
% (devspec.MAX_SLOT + 1)) % (devspec.MAX_SLOT + 1))
self.assertEqual(msg, six.text_type(exc)) self.assertEqual(msg, str(exc))
def test_address_is_undefined(self): def test_address_is_undefined(self):
pci_info = {"vendor_id": "8086", "product_id": "5057"} pci_info = {"vendor_id": "8086", "product_id": "5057"}
@ -381,7 +379,7 @@ class PciDevSpecTestCase(base.TestCase):
exc = self.assertRaises(exception.PciConfigInvalidWhitelist, exc = self.assertRaises(exception.PciConfigInvalidWhitelist,
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
self.assertEqual("Invalid PCI devices Whitelist config " self.assertEqual("Invalid PCI devices Whitelist config "
"invalid vendor_id 80860", six.text_type(exc)) "invalid vendor_id 80860", str(exc))
def test_invalid_product_id(self): def test_invalid_product_id(self):
pci_info = {"vendor_id": "8086", "address": "*: *: *.5", pci_info = {"vendor_id": "8086", "address": "*: *: *.5",
@ -395,7 +393,7 @@ class PciDevSpecTestCase(base.TestCase):
exc = self.assertRaises(exception.PciConfigInvalidWhitelist, exc = self.assertRaises(exception.PciConfigInvalidWhitelist,
devspec.PciDeviceSpec, pci_info) devspec.PciDeviceSpec, pci_info)
self.assertEqual("Invalid PCI devices Whitelist config " self.assertEqual("Invalid PCI devices Whitelist config "
"invalid product_id 50570", six.text_type(exc)) "invalid product_id 50570", str(exc))
def test_devname_and_address(self): def test_devname_and_address(self):
pci_info = {"devname": "eth0", "vendor_id": "8086", pci_info = {"devname": "eth0", "vendor_id": "8086",

View File

@ -14,12 +14,12 @@
# 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 builtins
import glob import glob
import os import os
from unittest import mock from unittest import mock
import fixtures import fixtures
from six.moves import builtins
from zun.common import exception from zun.common import exception
from zun.pci import utils from zun.pci import utils

View File

@ -9,6 +9,7 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# 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 copy import copy
import time import time
from unittest import mock from unittest import mock
@ -18,8 +19,7 @@ from keystoneauth1 import exceptions as ks_exc
import os_resource_classes as orc import os_resource_classes as orc
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils.fixture import uuidsentinel as uuids from oslo_utils.fixture import uuidsentinel as uuids
import six from urllib import parse
from six.moves.urllib import parse
from zun.common import context from zun.common import context
from zun.common import exception from zun.common import exception
@ -3363,7 +3363,7 @@ class TestAllocations(SchedulerReportClientTestCase):
exception.AllocationUpdateFailed, exception.AllocationUpdateFailed,
self._test_remove_res_from_alloc, current_allocations, self._test_remove_res_from_alloc, current_allocations,
resources_to_remove, None) resources_to_remove, None)
self.assertIn('The allocation is empty', six.text_type(ex)) self.assertIn('The allocation is empty', str(ex))
@mock.patch("zun.scheduler.client.report.SchedulerReportClient.put") @mock.patch("zun.scheduler.client.report.SchedulerReportClient.put")
@mock.patch("zun.scheduler.client.report.SchedulerReportClient.get") @mock.patch("zun.scheduler.client.report.SchedulerReportClient.get")
@ -3400,7 +3400,7 @@ class TestAllocations(SchedulerReportClientTestCase):
current_allocations, resources_to_remove, None) current_allocations, resources_to_remove, None)
self.assertIn( self.assertIn(
"Key 'VCPU' is missing from the allocation", "Key 'VCPU' is missing from the allocation",
six.text_type(ex)) str(ex))
def test_remove_res_from_alloc_missing_rp(self): def test_remove_res_from_alloc_missing_rp(self):
current_allocations = { current_allocations = {
@ -3427,7 +3427,7 @@ class TestAllocations(SchedulerReportClientTestCase):
current_allocations, resources_to_remove, None) current_allocations, resources_to_remove, None)
self.assertIn( self.assertIn(
"Key '%s' is missing from the allocation" % uuids.other_rp, "Key '%s' is missing from the allocation" % uuids.other_rp,
six.text_type(ex)) str(ex))
def test_remove_res_from_alloc_not_enough_resource_to_remove(self): def test_remove_res_from_alloc_not_enough_resource_to_remove(self):
current_allocations = { current_allocations = {
@ -3457,7 +3457,7 @@ class TestAllocations(SchedulerReportClientTestCase):
'provider to remove 400 amount of NET_BW_EGR_KILOBIT_PER_SEC ' 'provider to remove 400 amount of NET_BW_EGR_KILOBIT_PER_SEC '
'resources' % 'resources' %
uuids.rp1, uuids.rp1,
six.text_type(ex)) str(ex))
@mock.patch('time.sleep', new=mock.Mock()) @mock.patch('time.sleep', new=mock.Mock())
@mock.patch("zun.scheduler.client.report.SchedulerReportClient.put") @mock.patch("zun.scheduler.client.report.SchedulerReportClient.put")
@ -3585,7 +3585,7 @@ class TestAllocations(SchedulerReportClientTestCase):
self.context, uuids.consumer_uuid, resources_to_remove) self.context, uuids.consumer_uuid, resources_to_remove)
self.assertIn( self.assertIn(
'due to multiple successive generation conflicts', 'due to multiple successive generation conflicts',
six.text_type(ex)) str(ex))
get_call = mock.call( get_call = mock.call(
'/allocations/%s' % uuids.consumer_uuid, version='1.28', '/allocations/%s' % uuids.consumer_uuid, version='1.28',

View File

@ -10,8 +10,6 @@
# 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 six
from cinderclient import exceptions as cinder_exception from cinderclient import exceptions as cinder_exception
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
@ -87,7 +85,7 @@ class CinderAPI(object):
'connection.', 'connection.',
{'vol': volume_id, {'vol': volume_id,
'host': connector.get('host'), 'host': connector.get('host'),
'msg': six.text_type(ex), 'msg': str(ex),
'code': ex.code}) 'code': ex.code})
try: try:
self.terminate_connection(volume_id, connector) self.terminate_connection(volume_id, connector)
@ -100,7 +98,7 @@ class CinderAPI(object):
'Code: %(code)s.', 'Code: %(code)s.',
{'vol': volume_id, {'vol': volume_id,
'host': connector.get('host'), 'host': connector.get('host'),
'msg': six.text_type(exc), 'msg': str(exc),
'code': (exc.code 'code': (exc.code
if hasattr(exc, 'code') else None)}) if hasattr(exc, 'code') else None)})

View File

@ -10,8 +10,6 @@
# 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 six
from cinderclient import exceptions as cinder_exception from cinderclient import exceptions as cinder_exception
from os_brick import exception as os_brick_exception from os_brick import exception as os_brick_exception
from os_brick.initiator import connector as brick_connector from os_brick.initiator import connector as brick_connector
@ -155,7 +153,7 @@ class CinderWorkflow(object):
self.cinder_api.begin_detaching(volume_id) self.cinder_api.begin_detaching(volume_id)
except cinder_exception.BadRequest as e: except cinder_exception.BadRequest as e:
raise exception.Invalid(_("Invalid volume: %s") % raise exception.Invalid(_("Invalid volume: %s") %
six.text_type(e)) str(e))
conn_info = jsonutils.loads(volmap.connection_info) conn_info = jsonutils.loads(volmap.connection_info)
if not self._volume_connection_keep(context, volume_id): if not self._volume_connection_keep(context, volume_id):
@ -187,4 +185,4 @@ class CinderWorkflow(object):
self.cinder_api.delete_volume(volume_id) self.cinder_api.delete_volume(volume_id)
except cinder_exception as e: except cinder_exception as e:
raise exception.Invalid(_("Delete Volume failed: %s") % raise exception.Invalid(_("Delete Volume failed: %s") %
six.text_type(e)) str(e))

View File

@ -13,7 +13,6 @@
import abc import abc
import functools import functools
import shutil import shutil
import six
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
@ -63,8 +62,7 @@ def validate_volume_provider(supported_providers):
return decorator return decorator
@six.add_metaclass(abc.ABCMeta) class VolumeDriver(object, metaclass=abc.ABCMeta):
class VolumeDriver(object):
"""The base class that all Volume classes should inherit from.""" """The base class that all Volume classes should inherit from."""
def attach(self, *args, **kwargs): def attach(self, *args, **kwargs):

View File

@ -26,8 +26,7 @@ import time
import docker import docker
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six from urllib import parse as urlparse
import six.moves.urllib.parse as urlparse
import websockify import websockify
from zun.common import context from zun.common import context
@ -121,7 +120,7 @@ class ZunProxyRequestHandlerBase(object):
'host': self.server.target_host, 'host': self.server.target_host,
'port': self.server.target_port}) 'port': self.server.target_port})
raise self.CClose(1000, "Target closed") raise self.CClose(1000, "Target closed")
if isinstance(buf, six.string_types): if isinstance(buf, str):
buf = buf.encode() buf = buf.encode()
self.cqueue.append(buf) self.cqueue.append(buf)