Remove six[7]

Since our code will only support py3. So remove six is necessary.

Change-Id: I3738118b1898421ee41e9e2902c255ead73f3915
This commit is contained in:
chenke
2020-04-21 21:22:31 +08:00
committed by chenker
parent 25f313a3ef
commit 0ef0f165cb
51 changed files with 86 additions and 172 deletions

View File

@@ -26,7 +26,7 @@ passenv = http_proxy HTTP_PROXY https_proxy HTTPS_PROXY no_proxy NO_PROXY
commands = commands =
doc8 doc/source/ CONTRIBUTING.rst HACKING.rst README.rst doc8 doc/source/ CONTRIBUTING.rst HACKING.rst README.rst
flake8 flake8
bandit -r watcher -x watcher/tests/* -n5 -ll -s B320 bandit -r watcher -x watcher/tests/* -n5 -ll -s B320,B322
[testenv:venv] [testenv:venv]
setenv = PYTHONHASHSEED=0 setenv = PYTHONHASHSEED=0

View File

@@ -15,9 +15,9 @@
# under the License. # under the License.
from http import client as http_client
from oslo_config import cfg from oslo_config import cfg
from pecan import hooks from pecan import hooks
from six.moves import http_client
from watcher.common import context from watcher.common import context

View File

@@ -24,7 +24,6 @@ from xml import etree as et
from oslo_log import log from oslo_log import log
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
import webob import webob
from watcher._i18n import _ from watcher._i18n import _
@@ -84,12 +83,10 @@ class ParsableErrorMiddleware(object):
'</error_message>' % state['status_code']] '</error_message>' % state['status_code']]
state['headers'].append(('Content-Type', 'application/xml')) state['headers'].append(('Content-Type', 'application/xml'))
else: else:
if six.PY3: app_iter = [i.decode('utf-8') for i in app_iter]
app_iter = [i.decode('utf-8') for i in app_iter]
body = [jsonutils.dumps( body = [jsonutils.dumps(
{'error_message': '\n'.join(app_iter)})] {'error_message': '\n'.join(app_iter)})]
if six.PY3: body = [item.encode('utf-8') for item in body]
body = [item.encode('utf-8') for item in body]
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]))))
else: else:

View File

@@ -20,7 +20,6 @@ import itertools
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import timeutils from oslo_utils import timeutils
import six
from watcher.common import context as watcher_context from watcher.common import context as watcher_context
from watcher.common import scheduling from watcher.common import scheduling
@@ -83,7 +82,7 @@ class APISchedulingService(scheduling.BackgroundSchedulerService):
service = objects.Service.get(context, service_id) service = objects.Service.get(context, service_id)
last_heartbeat = (service.last_seen_up or service.updated_at or last_heartbeat = (service.last_seen_up or service.updated_at or
service.created_at) service.created_at)
if isinstance(last_heartbeat, six.string_types): if isinstance(last_heartbeat, str):
# NOTE(russellb) If this service came in over rpc via # NOTE(russellb) If this service came in over rpc via
# conductor, then the timestamp will be a string and needs to be # conductor, then the timestamp will be a string and needs to be
# converted back to a datetime. # converted back to a datetime.

View File

@@ -18,11 +18,9 @@
# #
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class BaseActionPlanHandler(object, metaclass=abc.ABCMeta):
class BaseActionPlanHandler(object):
@abc.abstractmethod @abc.abstractmethod
def execute(self): def execute(self):
raise NotImplementedError() raise NotImplementedError()

View File

@@ -19,14 +19,12 @@
import abc import abc
import jsonschema import jsonschema
import six
from watcher.common import clients from watcher.common import clients
from watcher.common.loader import loadable from watcher.common.loader import loadable
@six.add_metaclass(abc.ABCMeta) class BaseAction(loadable.Loadable, metaclass=abc.ABCMeta):
class BaseAction(loadable.Loadable):
# NOTE(jed): by convention we decided # NOTE(jed): by convention we decided
# that the attribute "resource_id" is the unique id of # that the attribute "resource_id" is the unique id of
# the resource to which the Action applies to allow us to use it in the # the resource to which the Action applies to allow us to use it in the

View File

@@ -26,11 +26,9 @@ See: :doc:`../architecture` for more details on this component.
""" """
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class BaseApplier(object, metaclass=abc.ABCMeta):
class BaseApplier(object):
@abc.abstractmethod @abc.abstractmethod
def execute(self, action_plan_uuid): def execute(self, action_plan_uuid):
raise NotImplementedError() raise NotImplementedError()

View File

@@ -17,7 +17,6 @@
# #
import abc import abc
import six
import time import time
import eventlet import eventlet
@@ -40,8 +39,7 @@ CANCEL_STATE = [objects.action_plan.State.CANCELLING,
objects.action_plan.State.CANCELLED] objects.action_plan.State.CANCELLED]
@six.add_metaclass(abc.ABCMeta) class BaseWorkFlowEngine(loadable.Loadable, metaclass=abc.ABCMeta):
class BaseWorkFlowEngine(loadable.Loadable):
def __init__(self, config, context=None, applier_manager=None): def __init__(self, config, context=None, applier_manager=None):
"""Constructor """Constructor

View File

@@ -13,7 +13,6 @@
from oslo_context import context from oslo_context import context
from oslo_log import log from oslo_log import log
from oslo_utils import timeutils from oslo_utils import timeutils
import six
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
@@ -69,7 +68,7 @@ class RequestContext(context.RequestContext):
self.project_id = project_id self.project_id = project_id
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_isotime(timestamp) timestamp = timeutils.parse_isotime(timestamp)
self.timestamp = timestamp self.timestamp = timestamp
self.user_name = user_name self.user_name = user_name

View File

@@ -17,11 +17,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class BaseLoader(object, metaclass=abc.ABCMeta):
class BaseLoader(object):
@abc.abstractmethod @abc.abstractmethod
def list_available(self): def list_available(self):

View File

@@ -16,13 +16,10 @@
import abc import abc
import six
from watcher.common import service from watcher.common import service
@six.add_metaclass(abc.ABCMeta) class Loadable(object, metaclass=abc.ABCMeta):
class Loadable(object):
"""Generic interface for dynamically loading a driver/entry point. """Generic interface for dynamically loading a driver/entry point.
This defines the contract in order to let the loader manager inject This defines the contract in order to let the loader manager inject
@@ -48,8 +45,7 @@ LoadableSingletonMeta = type(
"LoadableSingletonMeta", (abc.ABCMeta, service.Singleton), {}) "LoadableSingletonMeta", (abc.ABCMeta, service.Singleton), {})
@six.add_metaclass(LoadableSingletonMeta) class LoadableSingleton(object, metaclass=LoadableSingletonMeta):
class LoadableSingleton(object):
"""Generic interface for dynamically loading a driver as a singleton. """Generic interface for dynamically loading a driver as a singleton.
This defines the contract in order to let the loader manager inject This defines the contract in order to let the loader manager inject

View File

@@ -15,11 +15,9 @@
# under the License. # under the License.
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class ServiceManager(object, metaclass=abc.ABCMeta):
class ServiceManager(object):
@abc.abstractproperty @abc.abstractproperty
def service_name(self): def service_name(self):

View File

@@ -28,7 +28,6 @@ from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from watcher.common import exception from watcher.common import exception
@@ -82,7 +81,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)
@@ -104,7 +103,7 @@ def is_hostname_safe(hostname):
""" """
m = r'^[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?$' m = r'^[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?$'
return (isinstance(hostname, six.string_types) and return (isinstance(hostname, str) and
(re.match(m, hostname) is not None)) (re.match(m, hostname) is not None))

View File

@@ -18,7 +18,6 @@ Base classes for storage engines
import abc import abc
from oslo_config import cfg from oslo_config import cfg
from oslo_db import api as db_api from oslo_db import api as db_api
import six
_BACKEND_MAPPING = {'sqlalchemy': 'watcher.db.sqlalchemy.api'} _BACKEND_MAPPING = {'sqlalchemy': 'watcher.db.sqlalchemy.api'}
IMPL = db_api.DBAPI.from_config(cfg.CONF, backend_mapping=_BACKEND_MAPPING, IMPL = db_api.DBAPI.from_config(cfg.CONF, backend_mapping=_BACKEND_MAPPING,
@@ -30,8 +29,7 @@ def get_instance():
return IMPL return IMPL
@six.add_metaclass(abc.ABCMeta) class BaseConnection(object, metaclass=abc.ABCMeta):
class BaseConnection(object):
"""Base class for storage system connections.""" """Base class for storage system connections."""
@abc.abstractmethod @abc.abstractmethod

View File

@@ -25,7 +25,6 @@ import sys
from oslo_log import log from oslo_log import log
from oslo_utils import strutils from oslo_utils import strutils
import prettytable as ptable import prettytable as ptable
from six.moves import input
from watcher._i18n import _ from watcher._i18n import _
from watcher._i18n import lazy_translation_enabled from watcher._i18n import lazy_translation_enabled

View File

@@ -18,7 +18,6 @@
# limitations under the License. # limitations under the License.
# #
import abc import abc
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@@ -36,9 +35,11 @@ CONF = cfg.CONF
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta) class BaseMetaClass(service.Singleton, abc.ABCMeta):
@six.add_metaclass(service.Singleton) pass
class BaseAuditHandler(object):
class BaseAuditHandler(object, metaclass=BaseMetaClass):
@abc.abstractmethod @abc.abstractmethod
def execute(self, audit, request_context): def execute(self, audit, request_context):
@@ -57,8 +58,7 @@ class BaseAuditHandler(object):
raise NotImplementedError() raise NotImplementedError()
@six.add_metaclass(abc.ABCMeta) class AuditHandler(BaseAuditHandler, metaclass=abc.ABCMeta):
class AuditHandler(BaseAuditHandler):
def __init__(self): def __init__(self):
super(AuditHandler, self).__init__() super(AuditHandler, self).__init__()

View File

@@ -16,9 +16,10 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from urllib import parse as urlparse
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
import six.moves.urllib.parse as urlparse
from watcher.common import clients from watcher.common import clients
from watcher.common import exception from watcher.common import exception

View File

@@ -15,13 +15,11 @@
# limitations under the License. # limitations under the License.
import abc import abc
import six
from watcher.common.loader import loadable from watcher.common.loader import loadable
@six.add_metaclass(abc.ABCMeta) class Goal(loadable.Loadable, metaclass=abc.ABCMeta):
class Goal(loadable.Loadable):
def __init__(self, config): def __init__(self, config):
super(Goal, self).__init__(config) super(Goal, self).__init__(config)

View File

@@ -27,11 +27,8 @@ import abc
import jsonschema import jsonschema
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
class EfficacySpecification(object, metaclass=abc.ABCMeta):
@six.add_metaclass(abc.ABCMeta)
class EfficacySpecification(object):
def __init__(self): def __init__(self):
self._indicators_specs = self.get_indicators_specifications() self._indicators_specs = self.get_indicators_specifications()

View File

@@ -18,7 +18,6 @@ import abc
import jsonschema import jsonschema
from jsonschema import SchemaError from jsonschema import SchemaError
from jsonschema import ValidationError from jsonschema import ValidationError
import six
from oslo_log import log from oslo_log import log
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
@@ -29,8 +28,7 @@ from watcher.common import exception
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta) class IndicatorSpecification(object, metaclass=abc.ABCMeta):
class IndicatorSpecification(object):
def __init__(self, name=None, description=None, unit=None, required=True): def __init__(self, name=None, description=None, unit=None, required=True):
self.name = name self.name = name

View File

@@ -25,11 +25,9 @@ See: :doc:`../architecture` for more details on this component.
""" """
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class Model(object, metaclass=abc.ABCMeta):
class Model(object):
@abc.abstractmethod @abc.abstractmethod
def to_string(self): def to_string(self):

View File

@@ -110,7 +110,6 @@ import time
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
import six
from watcher.common import clients from watcher.common import clients
from watcher.common.loader import loadable from watcher.common.loader import loadable
@@ -120,8 +119,8 @@ LOG = log.getLogger(__name__)
CONF = cfg.CONF CONF = cfg.CONF
@six.add_metaclass(abc.ABCMeta) class BaseClusterDataModelCollector(loadable.LoadableSingleton,
class BaseClusterDataModelCollector(loadable.LoadableSingleton): metaclass=abc.ABCMeta):
STALE_MODEL = model_root.ModelRoot(stale=True) STALE_MODEL = model_root.ModelRoot(stale=True)

View File

@@ -13,8 +13,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import six
from oslo_log import log from oslo_log import log
from watcher.common import cinder_helper from watcher.common import cinder_helper
@@ -286,7 +284,7 @@ class CinderModelBuilder(base.BaseModelBuilder):
:param instance: Cinder Volume object. :param instance: Cinder Volume object.
:return: A volume node for the graph. :return: A volume node for the graph.
""" """
attachments = [{k: v for k, v in six.iteritems(d) if k in ( attachments = [{k: v for k, v in iter(d.items()) if k in (
'server_id', 'attachment_id')} for d in volume.attachments] 'server_id', 'attachment_id')} for d in volume.attachments]
volume_attributes = { volume_attributes = {

View File

@@ -16,14 +16,12 @@
import abc import abc
import six
from watcher.decision_engine.model.element import base from watcher.decision_engine.model.element import base
from watcher.objects import fields as wfields from watcher.objects import fields as wfields
@six.add_metaclass(abc.ABCMeta) class BaremetalResource(base.Element, metaclass=abc.ABCMeta):
class BaremetalResource(base.Element):
VERSION = '1.0' VERSION = '1.0'

View File

@@ -21,7 +21,6 @@ import collections
from lxml import etree from lxml import etree
from oslo_log import log from oslo_log import log
import six
from watcher.objects import base from watcher.objects import base
from watcher.objects import fields as wfields from watcher.objects import fields as wfields
@@ -29,9 +28,8 @@ from watcher.objects import fields as wfields
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class Element(base.WatcherObject, base.WatcherObjectDictCompat, class Element(base.WatcherObject, base.WatcherObjectDictCompat,
base.WatcherComparableObject): base.WatcherComparableObject, metaclass=abc.ABCMeta):
# Initial version # Initial version
VERSION = '1.0' VERSION = '1.0'

View File

@@ -16,14 +16,12 @@
import abc import abc
import six
from watcher.decision_engine.model.element import base from watcher.decision_engine.model.element import base
from watcher.objects import fields as wfields from watcher.objects import fields as wfields
@six.add_metaclass(abc.ABCMeta) class ComputeResource(base.Element, metaclass=abc.ABCMeta):
class ComputeResource(base.Element):
VERSION = '1.0' VERSION = '1.0'

View File

@@ -16,14 +16,12 @@
import abc import abc
import six
from watcher.decision_engine.model.element import base from watcher.decision_engine.model.element import base
from watcher.objects import fields as wfields from watcher.objects import fields as wfields
@six.add_metaclass(abc.ABCMeta) class StorageResource(base.Element, metaclass=abc.ABCMeta):
class StorageResource(base.Element):
VERSION = '1.0' VERSION = '1.0'

View File

@@ -21,7 +21,6 @@ from lxml import etree
import networkx as nx import networkx as nx
from oslo_concurrency import lockutils from oslo_concurrency import lockutils
from oslo_log import log from oslo_log import log
import six
from watcher._i18n import _ from watcher._i18n import _
from watcher.common import exception from watcher.common import exception
@@ -93,9 +92,9 @@ class ModelRoot(nx.DiGraph, base.Model):
:param node: :py:class:`~.node.ComputeNode` object or node UUID :param node: :py:class:`~.node.ComputeNode` object or node UUID
:type node: str or :py:class:`~.instance.Instance` :type node: str or :py:class:`~.instance.Instance`
""" """
if isinstance(instance, six.string_types): if isinstance(instance, str):
instance = self.get_instance_by_uuid(instance) instance = self.get_instance_by_uuid(instance)
if isinstance(node, six.string_types): if isinstance(node, str):
node = self.get_node_by_uuid(node) node = self.get_node_by_uuid(node)
self.assert_node(node) self.assert_node(node)
self.assert_instance(instance) self.assert_instance(instance)
@@ -104,9 +103,9 @@ class ModelRoot(nx.DiGraph, base.Model):
@lockutils.synchronized("model_root") @lockutils.synchronized("model_root")
def unmap_instance(self, instance, node): def unmap_instance(self, instance, node):
if isinstance(instance, six.string_types): if isinstance(instance, str):
instance = self.get_instance_by_uuid(instance) instance = self.get_instance_by_uuid(instance)
if isinstance(node, six.string_types): if isinstance(node, str):
node = self.get_node_by_uuid(node) node = self.get_node_by_uuid(node)
self.remove_edge(instance.uuid, node.uuid) self.remove_edge(instance.uuid, node.uuid)
@@ -367,9 +366,9 @@ class StorageModelRoot(nx.DiGraph, base.Model):
:param pool: :py:class:`~.node.Pool` object or pool name :param pool: :py:class:`~.node.Pool` object or pool name
:param node: :py:class:`~.node.StorageNode` object or node host :param node: :py:class:`~.node.StorageNode` object or node host
""" """
if isinstance(pool, six.string_types): if isinstance(pool, str):
pool = self.get_pool_by_pool_name(pool) pool = self.get_pool_by_pool_name(pool)
if isinstance(node, six.string_types): if isinstance(node, str):
node = self.get_node_by_name(node) node = self.get_node_by_name(node)
self.assert_node(node) self.assert_node(node)
self.assert_pool(pool) self.assert_pool(pool)
@@ -383,9 +382,9 @@ class StorageModelRoot(nx.DiGraph, base.Model):
:param pool: :py:class:`~.node.Pool` object or pool name :param pool: :py:class:`~.node.Pool` object or pool name
:param node: :py:class:`~.node.StorageNode` object or node name :param node: :py:class:`~.node.StorageNode` object or node name
""" """
if isinstance(pool, six.string_types): if isinstance(pool, str):
pool = self.get_pool_by_pool_name(pool) pool = self.get_pool_by_pool_name(pool)
if isinstance(node, six.string_types): if isinstance(node, str):
node = self.get_node_by_name(node) node = self.get_node_by_name(node)
self.remove_edge(pool.name, node.host) self.remove_edge(pool.name, node.host)
@@ -411,9 +410,9 @@ class StorageModelRoot(nx.DiGraph, base.Model):
:param volume: :py:class:`~.volume.Volume` object or volume UUID :param volume: :py:class:`~.volume.Volume` object or volume UUID
:param pool: :py:class:`~.node.Pool` object or pool name :param pool: :py:class:`~.node.Pool` object or pool name
""" """
if isinstance(volume, six.string_types): if isinstance(volume, str):
volume = self.get_volume_by_uuid(volume) volume = self.get_volume_by_uuid(volume)
if isinstance(pool, six.string_types): if isinstance(pool, str):
pool = self.get_pool_by_pool_name(pool) pool = self.get_pool_by_pool_name(pool)
self.assert_pool(pool) self.assert_pool(pool)
self.assert_volume(volume) self.assert_volume(volume)
@@ -427,9 +426,9 @@ class StorageModelRoot(nx.DiGraph, base.Model):
:param volume: :py:class:`~.volume.Volume` object or volume UUID :param volume: :py:class:`~.volume.Volume` object or volume UUID
:param pool: :py:class:`~.node.Pool` object or pool name :param pool: :py:class:`~.node.Pool` object or pool name
""" """
if isinstance(volume, six.string_types): if isinstance(volume, str):
volume = self.get_volume_by_uuid(volume) volume = self.get_volume_by_uuid(volume)
if isinstance(pool, six.string_types): if isinstance(pool, str):
pool = self.get_pool_by_pool_name(pool) pool = self.get_pool_by_pool_name(pool)
self.remove_edge(volume.uuid, pool.name) self.remove_edge(volume.uuid, pool.name)

View File

@@ -17,11 +17,9 @@
# limitations under the License. # limitations under the License.
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class NotificationEndpoint(object, metaclass=abc.ABCMeta):
class NotificationEndpoint(object):
def __init__(self, collector): def __init__(self, collector):
super(NotificationEndpoint, self).__init__() super(NotificationEndpoint, self).__init__()

View File

@@ -14,8 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import six
from oslo_log import log from oslo_log import log
from watcher.common import cinder_helper from watcher.common import cinder_helper
from watcher.common import exception from watcher.common import exception
@@ -161,7 +159,7 @@ class CinderNotification(base.NotificationEndpoint):
return 'attachment_id' return 'attachment_id'
attachments = [ attachments = [
{_keyReplace(k): v for k, v in six.iteritems(d) {_keyReplace(k): v for k, v in iter(d.items())
if k in ('instance_uuid', 'id')} if k in ('instance_uuid', 'id')}
for d in data['volume_attachment'] for d in data['volume_attachment']
] ]

View File

@@ -19,7 +19,6 @@
import re import re
import oslo_messaging as om import oslo_messaging as om
import six
class NotificationFilter(om.NotificationFilter): class NotificationFilter(om.NotificationFilter):
@@ -81,7 +80,7 @@ class NotificationFilter(om.NotificationFilter):
elif regex is not None and data is None: elif regex is not None and data is None:
return True return True
elif (regex is not None and elif (regex is not None and
isinstance(data, six.string_types) and isinstance(data, str) and
not regex.match(data)): not regex.match(data)):
return True return True

View File

@@ -45,13 +45,11 @@ See :doc:`../architecture` for more details on this component.
""" """
import abc import abc
import six
from watcher.common.loader import loadable from watcher.common.loader import loadable
@six.add_metaclass(abc.ABCMeta) class BasePlanner(loadable.Loadable, metaclass=abc.ABCMeta):
class BasePlanner(loadable.Loadable):
@classmethod @classmethod
def get_config_opts(cls): def get_config_opts(cls):

View File

@@ -16,13 +16,11 @@
# #
import abc import abc
import six
from watcher.common import context from watcher.common import context
@six.add_metaclass(abc.ABCMeta) class BaseScope(object, metaclass=abc.ABCMeta):
class BaseScope(object):
"""A base class for Scope mechanism """A base class for Scope mechanism
Child of this class is called when audit launches strategy. This strategy Child of this class is called when audit launches strategy. This strategy

View File

@@ -17,13 +17,11 @@
# limitations under the License. # limitations under the License.
import abc import abc
import six
from watcher.common.loader import loadable from watcher.common.loader import loadable
@six.add_metaclass(abc.ABCMeta) class ScoringEngine(loadable.Loadable, metaclass=abc.ABCMeta):
class ScoringEngine(loadable.Loadable):
"""A base class for all the Scoring Engines. """A base class for all the Scoring Engines.
A Scoring Engine is an instance of a data model, to which the learning A Scoring Engine is an instance of a data model, to which the learning
@@ -97,8 +95,7 @@ class ScoringEngine(loadable.Loadable):
return [] return []
@six.add_metaclass(abc.ABCMeta) class ScoringEngineContainer(loadable.Loadable, metaclass=abc.ABCMeta):
class ScoringEngineContainer(loadable.Loadable):
"""A base class for all the Scoring Engines Containers. """A base class for all the Scoring Engines Containers.
A Scoring Engine Container is an abstraction which allows to plugin A Scoring Engine Container is an abstraction which allows to plugin

View File

@@ -56,13 +56,11 @@ Two approaches to dealing with this can be envisaged:
""" """
import abc import abc
import six
from watcher.decision_engine.solution import efficacy from watcher.decision_engine.solution import efficacy
@six.add_metaclass(abc.ABCMeta) class BaseSolution(object, metaclass=abc.ABCMeta):
class BaseSolution(object):
def __init__(self, goal, strategy): def __init__(self, goal, strategy):
"""Base Solution constructor """Base Solution constructor

View File

@@ -17,11 +17,9 @@
# limitations under the License. # limitations under the License.
# #
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class BaseSolutionComparator(object, metaclass=abc.ABCMeta):
class BaseSolutionComparator(object):
@abc.abstractmethod @abc.abstractmethod
def compare(self, sol1, sol2): def compare(self, sol1, sol2):
raise NotImplementedError() raise NotImplementedError()

View File

@@ -17,11 +17,9 @@
# limitations under the License. # limitations under the License.
# #
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class BaseSolutionEvaluator(object, metaclass=abc.ABCMeta):
class BaseSolutionEvaluator(object):
@abc.abstractmethod @abc.abstractmethod
def evaluate(self, solution): def evaluate(self, solution):
raise NotImplementedError() raise NotImplementedError()

View File

@@ -18,14 +18,12 @@
# limitations under the License. # limitations under the License.
import abc import abc
import six
from watcher import notifications from watcher import notifications
from watcher.objects import fields from watcher.objects import fields
@six.add_metaclass(abc.ABCMeta) class StrategyContext(object, metaclass=abc.ABCMeta):
class StrategyContext(object):
def execute_strategy(self, audit, request_context): def execute_strategy(self, audit, request_context):
"""Execute the strategy for the given an audit """Execute the strategy for the given an audit

View File

@@ -17,11 +17,9 @@
# limitations under the License. # limitations under the License.
# #
import abc import abc
import six
@six.add_metaclass(abc.ABCMeta) class BaseSelector(object, metaclass=abc.ABCMeta):
class BaseSelector(object):
@abc.abstractmethod @abc.abstractmethod
def select(self): def select(self):

View File

@@ -37,7 +37,6 @@ which are dynamically loaded by Watcher at launch time.
""" """
import abc import abc
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@@ -121,8 +120,7 @@ class StrategyEndpoint(object):
return [available_datasource, available_metrics, available_cdm] return [available_datasource, available_metrics, available_cdm]
@six.add_metaclass(abc.ABCMeta) class BaseStrategy(loadable.Loadable, metaclass=abc.ABCMeta):
class BaseStrategy(loadable.Loadable):
"""A base class for all the strategies """A base class for all the strategies
A Strategy is an algorithm implementation which is able to find a A Strategy is an algorithm implementation which is able to find a
@@ -471,8 +469,7 @@ class BaseStrategy(loadable.Loadable):
input_parameters=parameters) input_parameters=parameters)
@six.add_metaclass(abc.ABCMeta) class DummyBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class DummyBaseStrategy(BaseStrategy):
@classmethod @classmethod
def get_goal_name(cls): def get_goal_name(cls):
@@ -485,8 +482,7 @@ class DummyBaseStrategy(BaseStrategy):
return [] return []
@six.add_metaclass(abc.ABCMeta) class UnclassifiedStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class UnclassifiedStrategy(BaseStrategy):
"""This base class is used to ease the development of new strategies """This base class is used to ease the development of new strategies
The goal defined within this strategy can be used to simplify the The goal defined within this strategy can be used to simplify the
@@ -500,8 +496,7 @@ class UnclassifiedStrategy(BaseStrategy):
return "unclassified" return "unclassified"
@six.add_metaclass(abc.ABCMeta) class ServerConsolidationBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class ServerConsolidationBaseStrategy(BaseStrategy):
REASON_FOR_DISABLE = 'watcher_disabled' REASON_FOR_DISABLE = 'watcher_disabled'
@@ -510,16 +505,14 @@ class ServerConsolidationBaseStrategy(BaseStrategy):
return "server_consolidation" return "server_consolidation"
@six.add_metaclass(abc.ABCMeta) class ThermalOptimizationBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class ThermalOptimizationBaseStrategy(BaseStrategy):
@classmethod @classmethod
def get_goal_name(cls): def get_goal_name(cls):
return "thermal_optimization" return "thermal_optimization"
@six.add_metaclass(abc.ABCMeta) class WorkloadStabilizationBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class WorkloadStabilizationBaseStrategy(BaseStrategy):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(WorkloadStabilizationBaseStrategy, self super(WorkloadStabilizationBaseStrategy, self
@@ -531,16 +524,14 @@ class WorkloadStabilizationBaseStrategy(BaseStrategy):
return "workload_balancing" return "workload_balancing"
@six.add_metaclass(abc.ABCMeta) class NoisyNeighborBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class NoisyNeighborBaseStrategy(BaseStrategy):
@classmethod @classmethod
def get_goal_name(cls): def get_goal_name(cls):
return "noisy_neighbor" return "noisy_neighbor"
@six.add_metaclass(abc.ABCMeta) class SavingEnergyBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class SavingEnergyBaseStrategy(BaseStrategy):
@classmethod @classmethod
def get_goal_name(cls): def get_goal_name(cls):
@@ -553,8 +544,7 @@ class SavingEnergyBaseStrategy(BaseStrategy):
return [] return []
@six.add_metaclass(abc.ABCMeta) class ZoneMigrationBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class ZoneMigrationBaseStrategy(BaseStrategy):
@classmethod @classmethod
def get_goal_name(cls): def get_goal_name(cls):
@@ -567,8 +557,7 @@ class ZoneMigrationBaseStrategy(BaseStrategy):
return [] return []
@six.add_metaclass(abc.ABCMeta) class HostMaintenanceBaseStrategy(BaseStrategy, metaclass=abc.ABCMeta):
class HostMaintenanceBaseStrategy(BaseStrategy):
REASON_FOR_MAINTAINING = 'watcher_maintaining' REASON_FOR_MAINTAINING = 'watcher_maintaining'

View File

@@ -19,7 +19,6 @@
# #
from oslo_log import log from oslo_log import log
import six
from watcher._i18n import _ from watcher._i18n import _
from watcher.common import exception from watcher.common import exception
@@ -132,7 +131,7 @@ class VMWorkloadConsolidation(base.ServerConsolidationBaseStrategy):
:param instance: :param instance:
""" """
if isinstance(instance.state, six.string_types): if isinstance(instance.state, str):
return instance.state return instance.state
elif isinstance(instance.state, element.InstanceState): elif isinstance(instance.state, element.InstanceState):
return instance.state.value return instance.state.value
@@ -148,7 +147,7 @@ class VMWorkloadConsolidation(base.ServerConsolidationBaseStrategy):
:param node: :param node:
""" """
if isinstance(node.status, six.string_types): if isinstance(node.status, str):
return node.status return node.status
elif isinstance(node.status, element.ServiceState): elif isinstance(node.status, element.ServiceState):
return node.status.value return node.status.value

View File

@@ -13,7 +13,6 @@
# #
from dateutil.parser import parse from dateutil.parser import parse
import six
from oslo_log import log from oslo_log import log
@@ -282,7 +281,7 @@ class ZoneMigration(base.ZoneMigrationBaseStrategy):
action_counter = ActionCounter(total_limit, action_counter = ActionCounter(total_limit,
per_pool_limit, per_node_limit) per_pool_limit, per_node_limit)
for k, targets in six.iteritems(filtered_targets): for k, targets in iter(filtered_targets.items()):
if k == VOLUME: if k == VOLUME:
self.volumes_migration(targets, action_counter) self.volumes_migration(targets, action_counter)
elif k == INSTANCE: elif k == INSTANCE:
@@ -580,7 +579,7 @@ class ZoneMigration(base.ZoneMigrationBaseStrategy):
filter_list = [] filter_list = []
priority_filter_map = self.get_priority_filter_map() priority_filter_map = self.get_priority_filter_map()
for k, v in six.iteritems(self.priority): for k, v in iter(self.priority.items()):
if k in priority_filter_map: if k in priority_filter_map:
filter_list.append(priority_filter_map[k](v)) filter_list.append(priority_filter_map[k](v))
@@ -710,7 +709,7 @@ class BaseFilter(object):
return {} return {}
for cond in list(reversed(self.condition)): for cond in list(reversed(self.condition)):
for k, v in six.iteritems(targets): for k, v in iter(targets.items()):
if not self.is_allowed(k): if not self.is_allowed(k):
continue continue
LOG.debug("filter:%s with the key: %s", cond, k) LOG.debug("filter:%s with the key: %s", cond, k)

View File

@@ -19,7 +19,6 @@
import copy import copy
import futurist import futurist
from futurist import waiters from futurist import waiters
import six
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
@@ -29,8 +28,7 @@ CONF = cfg.CONF
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
@six.add_metaclass(service.Singleton) class DecisionEngineThreadPool(object, metaclass=service.Singleton):
class DecisionEngineThreadPool(object):
"""Singleton threadpool to submit general tasks to""" """Singleton threadpool to submit general tasks to"""
def __init__(self): def __init__(self):

View File

@@ -15,7 +15,6 @@
"""Utility methods for objects""" """Utility methods for objects"""
import ast import ast
import six
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_versionedobjects import fields from oslo_versionedobjects import fields
@@ -67,7 +66,7 @@ class ListOfUUIDsField(fields.AutoTypedField):
class FlexibleDict(fields.FieldType): class FlexibleDict(fields.FieldType):
@staticmethod @staticmethod
def coerce(obj, attr, value): def coerce(obj, attr, value):
if isinstance(value, six.string_types): if isinstance(value, str):
value = ast.literal_eval(value) value = ast.literal_eval(value)
return dict(value) return dict(value)
@@ -87,7 +86,7 @@ class FlexibleDictField(fields.AutoTypedField):
class FlexibleListOfDict(fields.FieldType): class FlexibleListOfDict(fields.FieldType):
@staticmethod @staticmethod
def coerce(obj, attr, value): def coerce(obj, attr, value):
if isinstance(value, six.string_types): if isinstance(value, str):
value = ast.literal_eval(value) value = ast.literal_eval(value)
return list(value) return list(value)
@@ -106,7 +105,7 @@ class FlexibleListOfDictField(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 = jsonutils.loads(value) loaded = jsonutils.loads(value)
return loaded return loaded
return value return value

View File

@@ -24,11 +24,11 @@
import copy import copy
import mock import mock
from urllib import parse as urlparse
from oslo_config import cfg from oslo_config import cfg
import pecan import pecan
import pecan.testing import pecan.testing
from six.moves.urllib import parse as urlparse
from watcher.api import hooks from watcher.api import hooks
from watcher.common import context as watcher_context from watcher.common import context as watcher_context

View File

@@ -13,12 +13,12 @@
import datetime import datetime
import itertools import itertools
import mock import mock
from urllib import parse as urlparse
from webtest.app import AppError from webtest.app import AppError
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import timeutils from oslo_utils import timeutils
from six.moves.urllib import parse as urlparse
from wsme import types as wtypes from wsme import types as wtypes
from watcher.api.controllers.v1 import audit_template as api_audit_template from watcher.api.controllers.v1 import audit_template as api_audit_template

View File

@@ -14,13 +14,13 @@ import datetime
from dateutil import tz from dateutil import tz
import itertools import itertools
import mock import mock
from urllib import parse as urlparse
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import timeutils from oslo_utils import timeutils
from wsme import types as wtypes from wsme import types as wtypes
from six.moves.urllib import parse as urlparse
from watcher.api.controllers.v1 import audit as api_audit from watcher.api.controllers.v1 import audit as api_audit
from watcher.common import utils from watcher.common import utils
from watcher.db import api as db_api from watcher.db import api as db_api

View File

@@ -12,7 +12,7 @@
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from six.moves.urllib import parse as urlparse from urllib import parse as urlparse
from watcher.common import utils from watcher.common import utils
from watcher.tests.api import base as api_base from watcher.tests.api import base as api_base

View File

@@ -12,7 +12,7 @@
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from six.moves.urllib import parse as urlparse from urllib import parse as urlparse
from watcher.tests.api import base as api_base from watcher.tests.api import base as api_base
from watcher.tests.objects import utils as obj_utils from watcher.tests.objects import utils as obj_utils

View File

@@ -11,10 +11,10 @@
# limitations under the License. # limitations under the License.
import mock import mock
from urllib import parse as urlparse
from oslo_config import cfg from oslo_config import cfg
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from six.moves.urllib import parse as urlparse
from watcher.common import utils from watcher.common import utils
from watcher.decision_engine import rpcapi as deapi from watcher.decision_engine import rpcapi as deapi

View File

@@ -19,8 +19,6 @@
import abc import abc
import mock import mock
import six
from watcher.applier.actions import base as abase from watcher.applier.actions import base as abase
from watcher.applier.actions import factory from watcher.applier.actions import factory
from watcher.applier.workflow_engine import default as tflow from watcher.applier.workflow_engine import default as tflow
@@ -36,8 +34,7 @@ class ExpectedException(Exception):
pass pass
@six.add_metaclass(abc.ABCMeta) class FakeAction(abase.BaseAction, metaclass=abc.ABCMeta):
class FakeAction(abase.BaseAction):
def schema(self): def schema(self):
pass pass