WIP - Remove six and python2.7 compatibility

Change-Id: I923476edaa09ae8ccaa9cd2392ff5e3cf5a0cc87
This commit is contained in:
Hervé Beraud 2019-11-08 11:51:24 +01:00
parent e0dbb3f7fa
commit 23f2bfd091
75 changed files with 254 additions and 350 deletions

View File

@ -24,7 +24,6 @@ from oslo_config import cfg
import oslo_i18n as i18n import oslo_i18n as i18n
from oslo_log import log as logging from oslo_log import log as logging
from oslo_service import systemd from oslo_service import systemd
import six
from heat.cmd import api from heat.cmd import api
from heat.cmd import api_cfn from heat.cmd import api_cfn
@ -83,5 +82,5 @@ def main():
systemd.notify_once() systemd.notify_once()
[service.wait() for service in services] [service.wait() for service in services]
except RuntimeError as e: except RuntimeError as e:
msg = six.text_type(e) msg = str(e)
sys.exit("ERROR: %s" % msg) sys.exit("ERROR: %s" % msg)

View File

@ -26,7 +26,6 @@ import oslo_i18n as i18n
from oslo_log import log as logging from oslo_log import log as logging
from oslo_reports import guru_meditation_report as gmr from oslo_reports import guru_meditation_report as gmr
from oslo_service import systemd from oslo_service import systemd
import six
from heat.common import config from heat.common import config
from heat.common import messaging from heat.common import messaging
@ -70,5 +69,5 @@ def main():
systemd.notify_once() systemd.notify_once()
server.wait() server.wait()
except RuntimeError as e: except RuntimeError as e:
msg = six.text_type(e) msg = str(e)
sys.exit("ERROR: %s" % msg) sys.exit("ERROR: %s" % msg)

View File

@ -28,7 +28,6 @@ import oslo_i18n as i18n
from oslo_log import log as logging from oslo_log import log as logging
from oslo_reports import guru_meditation_report as gmr from oslo_reports import guru_meditation_report as gmr
from oslo_service import systemd from oslo_service import systemd
import six
from heat.common import config from heat.common import config
from heat.common import messaging from heat.common import messaging
@ -74,5 +73,5 @@ def main():
systemd.notify_once() systemd.notify_once()
server.wait() server.wait()
except RuntimeError as e: except RuntimeError as e:
msg = six.text_type(e) msg = str(e)
sys.exit("ERROR: %s" % msg) sys.exit("ERROR: %s" % msg)

View File

@ -19,7 +19,6 @@ import sys
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
from six import moves
from heat.common import context from heat.common import context
from heat.common import exception from heat.common import exception
@ -106,7 +105,7 @@ def do_reset_stack_status():
"intended to recover from specific crashes.")) "intended to recover from specific crashes."))
print(_("It is advised to shutdown all Heat engines beforehand.")) print(_("It is advised to shutdown all Heat engines beforehand."))
print(_("Continue ? [y/N]")) print(_("Continue ? [y/N]"))
data = moves.input() data = input()
if not data.lower().startswith('y'): if not data.lower().startswith('y'):
return return
ctxt = context.get_admin_context() ctxt = context.get_admin_context()

View File

@ -26,7 +26,6 @@ from oslo_log import log as logging
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslo_utils import timeutils from oslo_utils import timeutils
import osprofiler.sqlalchemy import osprofiler.sqlalchemy
import six
import sqlalchemy import sqlalchemy
from sqlalchemy import and_ from sqlalchemy import and_
from sqlalchemy import func from sqlalchemy import func
@ -90,7 +89,7 @@ def get_session():
def update_and_save(context, obj, values): def update_and_save(context, obj, values):
with context.session.begin(subtransactions=True): with context.session.begin(subtransactions=True):
for k, v in six.iteritems(values): for k, v in values.items():
setattr(obj, k, v) setattr(obj, k, v)
@ -640,7 +639,7 @@ def _get_sort_keys(sort_keys, mapping):
:param mapping: a mapping from keys to DB column names :param mapping: a mapping from keys to DB column names
:returns: filtered list of sort keys :returns: filtered list of sort keys
""" """
if isinstance(sort_keys, six.string_types): if isinstance(sort_keys, str):
sort_keys = [sort_keys] sort_keys = [sort_keys]
return [mapping[key] for key in sort_keys or [] if key in mapping] return [mapping[key] for key in sort_keys or [] if key in mapping]
@ -929,7 +928,7 @@ def user_creds_create(context):
else: else:
user_creds_ref.update(values) user_creds_ref.update(values)
method, password = crypt.encrypt(values['password']) method, password = crypt.encrypt(values['password'])
if len(six.text_type(password)) > 255: if len(str(password)) > 255:
raise exception.Error(_("Length of OS_PASSWORD after encryption" raise exception.Error(_("Length of OS_PASSWORD after encryption"
" exceeds Heat limit (255 chars)")) " exceeds Heat limit (255 chars)"))
user_creds_ref.password = password user_creds_ref.password = password
@ -1156,7 +1155,7 @@ def event_create(context, values):
_delete_event_rows(context, values['stack_id'], _delete_event_rows(context, values['stack_id'],
cfg.CONF.event_purge_batch_size) cfg.CONF.event_purge_batch_size)
except db_exception.DBError as exc: except db_exception.DBError as exc:
LOG.error('Failed to purge events: %s', six.text_type(exc)) LOG.error('Failed to purge events: %s', str(exc))
event_ref = models.Event() event_ref = models.Event()
event_ref.update(values) event_ref.update(values)
event_ref.save(context.session) event_ref.save(context.session)
@ -1647,7 +1646,7 @@ def _db_encrypt_or_decrypt_template_params(
not param_schemata[param_name].hidden): not param_schemata[param_name].hidden):
continue continue
encrypted_val = crypt.encrypt( encrypted_val = crypt.encrypt(
six.text_type(param_val), encryption_key) str(param_val), encryption_key)
env['parameters'][param_name] = encrypted_val env['parameters'][param_name] = encrypted_val
encrypted_params.append(param_name) encrypted_params.append(param_name)
needs_update = True needs_update = True

View File

@ -11,8 +11,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
def exact_filter(query, model, filters): def exact_filter(query, model, filters):
"""Applies exact match filtering to a query. """Applies exact match filtering to a query.
@ -33,7 +31,7 @@ def exact_filter(query, model, filters):
if filters is None: if filters is None:
filters = {} filters = {}
for key, value in six.iteritems(filters): for key, value in filters.items():
if isinstance(value, (list, tuple, set, frozenset)): if isinstance(value, (list, tuple, set, frozenset)):
column_attr = getattr(model, key) column_attr = getattr(model, key)
query = query.filter(column_attr.in_(value)) query = query.filter(column_attr.in_(value))

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
import eventlet.queue import eventlet.queue
import functools import functools
@ -83,7 +81,7 @@ class CheckResource(object):
'during resource %s' % rsrc.action) 'during resource %s' % rsrc.action)
rsrc.state_set(rsrc.action, rsrc.state_set(rsrc.action,
rsrc.FAILED, rsrc.FAILED,
six.text_type(status_reason)) str(status_reason))
return True return True
elif (rs_obj.engine_id is None and elif (rs_obj.engine_id is None and
rs_obj.current_template_id == prev_template_id): rs_obj.current_template_id == prev_template_id):
@ -173,7 +171,7 @@ class CheckResource(object):
except exception.ResourceFailure as ex: except exception.ResourceFailure as ex:
action = ex.action or rsrc.action action = ex.action or rsrc.action
reason = 'Resource %s failed: %s' % (action, reason = 'Resource %s failed: %s' % (action,
six.text_type(ex)) str(ex))
self._handle_resource_failure(cnxt, is_update, rsrc.id, self._handle_resource_failure(cnxt, is_update, rsrc.id,
stack, reason) stack, reason)
except scheduler.Timeout: except scheduler.Timeout:
@ -319,7 +317,7 @@ class CheckResource(object):
rsrc, stack) rsrc, stack)
except BaseException as exc: except BaseException as exc:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
msg = six.text_type(exc) msg = str(exc)
LOG.exception("Unexpected exception in resource check.") LOG.exception("Unexpected exception in resource check.")
self._handle_resource_failure(cnxt, is_update, rsrc.id, self._handle_resource_failure(cnxt, is_update, rsrc.id,
stack, msg) stack, msg)

View File

@ -21,7 +21,6 @@ from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import reflection from oslo_utils import reflection
from oslo_utils import strutils from oslo_utils import strutils
import six
from heat.common import cache from heat.common import cache
from heat.common import exception from heat.common import exception
@ -149,7 +148,7 @@ class Schema(collections.Mapping):
if isinstance(self.schema, AnyIndexDict): if isinstance(self.schema, AnyIndexDict):
self.schema.value.validate(context) self.schema.value.validate(context)
else: else:
for nested_schema in six.itervalues(self.schema): for nested_schema in self.schema.values():
nested_schema.validate(context) nested_schema.validate(context)
def _validate_default(self, context): def _validate_default(self, context):
@ -195,9 +194,9 @@ class Schema(collections.Mapping):
elif self.type == self.NUMBER: elif self.type == self.NUMBER:
return Schema.str_to_num(value) return Schema.str_to_num(value)
elif self.type == self.STRING: elif self.type == self.STRING:
return six.text_type(value) return str(value)
elif self.type == self.BOOLEAN: elif self.type == self.BOOLEAN:
return strutils.bool_from_string(six.text_type(value), return strutils.bool_from_string(str(value),
strict=True) strict=True)
except ValueError: except ValueError:
raise ValueError(_('Value "%(val)s" is invalid for data type ' raise ValueError(_('Value "%(val)s" is invalid for data type '
@ -215,7 +214,7 @@ class Schema(collections.Mapping):
if type(constraint) not in skipped: if type(constraint) not in skipped:
constraint.validate(value, self, context) constraint.validate(value, self, context)
except ValueError as ex: except ValueError as ex:
raise exception.StackValidationFailed(message=six.text_type(ex)) raise exception.StackValidationFailed(message=str(ex))
def __getitem__(self, key): def __getitem__(self, key):
if key == self.TYPE: if key == self.TYPE:
@ -265,7 +264,7 @@ class AnyIndexDict(collections.Mapping):
self.value = value self.value = value
def __getitem__(self, key): def __getitem__(self, key):
if key != self.ANYTHING and not isinstance(key, six.integer_types): if key != self.ANYTHING and not isinstance(key, int):
raise KeyError(_('Invalid key %s') % key) raise KeyError(_('Invalid key %s') % key)
return self.value return self.value
@ -277,7 +276,6 @@ class AnyIndexDict(collections.Mapping):
return 1 return 1
@six.python_2_unicode_compatible
class Constraint(collections.Mapping): class Constraint(collections.Mapping):
"""Parent class for constraints on allowable values for a Property. """Parent class for constraints on allowable values for a Property.
@ -353,7 +351,7 @@ class Range(Constraint):
self.max = max self.max = max
for param in (min, max): for param in (min, max):
if not isinstance(param, (float, six.integer_types, type(None))): if not isinstance(param, (float, int, type(None))):
raise exception.InvalidSchemaError( raise exception.InvalidSchemaError(
message=_('min/max must be numeric')) message=_('min/max must be numeric'))
@ -422,7 +420,7 @@ class Length(Range):
super(Length, self).__init__(min, max, description) super(Length, self).__init__(min, max, description)
for param in (min, max): for param in (min, max):
if not isinstance(param, (six.integer_types, type(None))): if not isinstance(param, (int, type(None))):
msg = _('min/max length must be integral') msg = _('min/max length must be integral')
raise exception.InvalidSchemaError(message=msg) raise exception.InvalidSchemaError(message=msg)
@ -471,7 +469,7 @@ class Modulo(Constraint):
'an offset value specified.')) 'an offset value specified.'))
for param in (step, offset): for param in (step, offset):
if not isinstance(param, (float, six.integer_types, type(None))): if not isinstance(param, (float, int, type(None))):
raise exception.InvalidSchemaError( raise exception.InvalidSchemaError(
message=_('step/offset must be numeric')) message=_('step/offset must be numeric'))
@ -543,7 +541,7 @@ class AllowedValues(Constraint):
def __init__(self, allowed, description=None): def __init__(self, allowed, description=None):
super(AllowedValues, self).__init__(description) super(AllowedValues, self).__init__(description)
if (not isinstance(allowed, collections.Sequence) or if (not isinstance(allowed, collections.Sequence) or
isinstance(allowed, six.string_types)): isinstance(allowed, str)):
raise exception.InvalidSchemaError( raise exception.InvalidSchemaError(
message=_('AllowedValues must be a list')) message=_('AllowedValues must be a list'))
self.allowed = tuple(allowed) self.allowed = tuple(allowed)
@ -589,7 +587,7 @@ class AllowedPattern(Constraint):
def __init__(self, pattern, description=None): def __init__(self, pattern, description=None):
super(AllowedPattern, self).__init__(description) super(AllowedPattern, self).__init__(description)
if not isinstance(pattern, six.string_types): if not isinstance(pattern, str):
raise exception.InvalidSchemaError( raise exception.InvalidSchemaError(
message=_('AllowedPattern must be a string')) message=_('AllowedPattern must be a string'))
self.pattern = pattern self.pattern = pattern
@ -701,13 +699,13 @@ class BaseCustomConstraint(object):
try: try:
self.validate_with_client(context.clients, value_to_validate) self.validate_with_client(context.clients, value_to_validate)
except self.expected_exceptions as e: except self.expected_exceptions as e:
self._error_message = six.text_type(e) self._error_message = str(e)
return False return False
else: else:
return True return True
class_name = reflection.get_class_name(self, fully_qualified=False) class_name = reflection.get_class_name(self, fully_qualified=False)
cache_value_prefix = "{0}:{1}".format(class_name, cache_value_prefix = "{0}:{1}".format(class_name,
six.text_type(context.tenant_id)) str(context.tenant_id))
validation_result = check_cache_or_validate_value( validation_result = check_cache_or_validate_value(
cache_value_prefix, value) cache_value_prefix, value)
# if validation failed we should not store it in cache # if validation failed we should not store it in cache

View File

@ -14,8 +14,6 @@
import collections import collections
import itertools import itertools
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.common.i18n import repr_wrapper from heat.common.i18n import repr_wrapper
@ -26,7 +24,6 @@ class CircularDependencyException(exception.HeatException):
@repr_wrapper @repr_wrapper
@six.python_2_unicode_compatible
class Node(object): class Node(object):
"""A node in a dependency graph.""" """A node in a dependency graph."""
@ -94,15 +91,14 @@ class Node(object):
def __str__(self): def __str__(self):
"""Return a human-readable string representation of the node.""" """Return a human-readable string representation of the node."""
text = '{%s}' % ', '.join(six.text_type(n) for n in self) text = '{%s}' % ', '.join(str(n) for n in self)
return six.text_type(text) return str(text)
def __repr__(self): def __repr__(self):
"""Return a string representation of the node.""" """Return a string representation of the node."""
return repr(self.require) return repr(self.require)
@six.python_2_unicode_compatible
class Graph(collections.defaultdict): class Graph(collections.defaultdict):
"""A mutable mapping of objects to nodes in a dependency graph.""" """A mutable mapping of objects to nodes in a dependency graph."""
@ -134,7 +130,7 @@ class Graph(collections.defaultdict):
for rqd in node: for rqd in node:
yield (rqr, rqd) yield (rqr, rqd)
return itertools.chain.from_iterable(outgoing_edges(*i) return itertools.chain.from_iterable(outgoing_edges(*i)
for i in six.iteritems(self)) for i in self.items())
def __delitem__(self, key): def __delitem__(self, key):
"""Delete the node given by the specified key from the graph.""" """Delete the node given by the specified key from the graph."""
@ -149,10 +145,10 @@ class Graph(collections.defaultdict):
def __str__(self): def __str__(self):
"""Convert the graph to a human-readable string.""" """Convert the graph to a human-readable string."""
pairs = ('%s: %s' % (six.text_type(k), six.text_type(v)) pairs = ('%s: %s' % (str(k), str(v))
for k, v in six.iteritems(self)) for k, v in self.items())
text = '{%s}' % ', '.join(pairs) text = '{%s}' % ', '.join(pairs)
return six.text_type(text) return str(text)
@staticmethod @staticmethod
def toposort(graph): def toposort(graph):
@ -160,8 +156,8 @@ class Graph(collections.defaultdict):
This is a destructive operation for the graph. This is a destructive operation for the graph.
""" """
for iteration in six.moves.xrange(len(graph)): for iteration in range(len(graph)):
for key, node in six.iteritems(graph): for key, node in graph.items():
if not node: if not node:
yield key yield key
del graph[key] del graph[key]
@ -169,11 +165,10 @@ class Graph(collections.defaultdict):
else: else:
# There are nodes remaining, but none without # There are nodes remaining, but none without
# dependencies: a cycle # dependencies: a cycle
raise CircularDependencyException(cycle=six.text_type(graph)) raise CircularDependencyException(cycle=str(graph))
@repr_wrapper @repr_wrapper
@six.python_2_unicode_compatible
class Dependencies(object): class Dependencies(object):
"""Helper class for calculating a dependency graph.""" """Helper class for calculating a dependency graph."""
@ -230,7 +225,7 @@ class Dependencies(object):
return itertools.chain([(rqr, key)], get_edges(rqr)) return itertools.chain([(rqr, key)], get_edges(rqr))
# Get the edge list for each node that requires the current node # Get the edge list for each node that requires the current node
edge_lists = six.moves.map(requirer_edges, edge_lists = map(requirer_edges,
self._graph[key].required_by()) self._graph[key].required_by())
# Combine the lists into one long list # Combine the lists into one long list
return itertools.chain.from_iterable(edge_lists) return itertools.chain.from_iterable(edge_lists)
@ -266,7 +261,7 @@ class Dependencies(object):
def __str__(self): def __str__(self):
"""Return a human-readable string repr of the dependency graph.""" """Return a human-readable string repr of the dependency graph."""
return six.text_type(self._graph) return str(self._graph)
def __repr__(self): def __repr__(self):
"""Return a consistent string representation of the object.""" """Return a consistent string representation of the object."""

View File

@ -21,7 +21,6 @@ import weakref
from oslo_config import cfg from oslo_config import cfg
from oslo_log import log from oslo_log import log
from oslo_utils import fnmatch from oslo_utils import fnmatch
import six
from heat.common import environment_format as env_fmt from heat.common import environment_format as env_fmt
from heat.common import exception from heat.common import exception
@ -54,7 +53,7 @@ def valid_restricted_actions(action):
def is_hook_definition(key, value): def is_hook_definition(key, value):
is_valid_hook = False is_valid_hook = False
if key == 'hooks': if key == 'hooks':
if isinstance(value, six.string_types): if isinstance(value, str):
is_valid_hook = valid_hook_type(value) is_valid_hook = valid_hook_type(value)
elif isinstance(value, collections.Sequence): elif isinstance(value, collections.Sequence):
is_valid_hook = all(valid_hook_type(hook) for hook in value) is_valid_hook = all(valid_hook_type(hook) for hook in value)
@ -71,7 +70,7 @@ def is_hook_definition(key, value):
def is_valid_restricted_action(key, value): def is_valid_restricted_action(key, value):
valid_action = False valid_action = False
if key == 'restricted_actions': if key == 'restricted_actions':
if isinstance(value, six.string_types): if isinstance(value, str):
valid_action = valid_restricted_actions(value) valid_action = valid_restricted_actions(value)
elif isinstance(value, collections.Sequence): elif isinstance(value, collections.Sequence):
valid_action = all(valid_restricted_actions( valid_action = all(valid_restricted_actions(
@ -101,7 +100,7 @@ class ResourceInfo(object):
if name.endswith(('.yaml', '.template')): if name.endswith(('.yaml', '.template')):
# a template url for the resource "Type" # a template url for the resource "Type"
klass = TemplateResourceInfo klass = TemplateResourceInfo
elif not isinstance(value, six.string_types): elif not isinstance(value, str):
klass = ClassResourceInfo klass = ClassResourceInfo
elif value.endswith(('.yaml', '.template')): elif value.endswith(('.yaml', '.template')):
# a registered template # a registered template
@ -344,9 +343,9 @@ class ResourceRegistry(object):
if info.value.support_status.message is not None: if info.value.support_status.message is not None:
details = { details = {
'name': info.name, 'name': info.name,
'status': six.text_type( 'status': str(
info.value.support_status.status), info.value.support_status.status),
'message': six.text_type( 'message': str(
info.value.support_status.message) info.value.support_status.message)
} }
LOG.warning('%(name)s is %(status)s. %(message)s', LOG.warning('%(name)s is %(status)s. %(message)s',
@ -364,7 +363,7 @@ class ResourceRegistry(object):
if show_all or isinstance(registry[name], TemplateResourceInfo): if show_all or isinstance(registry[name], TemplateResourceInfo):
msg = ('%(p)sRegistered: %(t)s' % msg = ('%(p)sRegistered: %(t)s' %
{'p': prefix, {'p': prefix,
't': six.text_type(registry[name])}) 't': str(registry[name])})
LOG.info(msg) LOG.info(msg)
def remove_item(self, info): def remove_item(self, info):
@ -394,11 +393,11 @@ class ResourceRegistry(object):
""" """
ress = self._registry['resources'] ress = self._registry['resources']
restricted_actions = set() restricted_actions = set()
for name_pattern, resource in six.iteritems(ress): for name_pattern, resource in ress.items():
if fnmatch.fnmatchcase(resource_name, name_pattern): if fnmatch.fnmatchcase(resource_name, name_pattern):
if 'restricted_actions' in resource: if 'restricted_actions' in resource:
actions = resource['restricted_actions'] actions = resource['restricted_actions']
if isinstance(actions, six.string_types): if isinstance(actions, str):
restricted_actions.add(actions) restricted_actions.add(actions)
elif isinstance(actions, collections.Sequence): elif isinstance(actions, collections.Sequence):
restricted_actions |= set(actions) restricted_actions |= set(actions)
@ -429,11 +428,11 @@ class ResourceRegistry(object):
everything. everything.
""" """
ress = self._registry['resources'] ress = self._registry['resources']
for name_pattern, resource in six.iteritems(ress): for name_pattern, resource in ress.items():
if fnmatch.fnmatchcase(resource_name, name_pattern): if fnmatch.fnmatchcase(resource_name, name_pattern):
if 'hooks' in resource: if 'hooks' in resource:
hooks = resource['hooks'] hooks = resource['hooks']
if isinstance(hooks, six.string_types): if isinstance(hooks, str):
if hook == hooks: if hook == hooks:
return True return True
elif isinstance(hooks, collections.Sequence): elif isinstance(hooks, collections.Sequence):
@ -444,7 +443,7 @@ class ResourceRegistry(object):
def remove_resources_except(self, resource_name): def remove_resources_except(self, resource_name):
ress = self._registry['resources'] ress = self._registry['resources']
new_resources = {} new_resources = {}
for name, res in six.iteritems(ress): for name, res in ress.items():
if fnmatch.fnmatchcase(resource_name, name): if fnmatch.fnmatchcase(resource_name, name):
new_resources.update(res) new_resources.update(res)
if resource_name in ress: if resource_name in ress:
@ -477,7 +476,7 @@ class ResourceRegistry(object):
# handle: "OS::*" -> "Dreamhost::*" # handle: "OS::*" -> "Dreamhost::*"
def is_a_glob(resource_type): def is_a_glob(resource_type):
return resource_type.endswith('*') return resource_type.endswith('*')
globs = six.moves.filter(is_a_glob, iter(self._registry)) globs = filter(is_a_glob, iter(self._registry))
for pattern in globs: for pattern in globs:
if self._registry[pattern].matches(resource_type): if self._registry[pattern].matches(resource_type):
yield self._registry[pattern] yield self._registry[pattern]
@ -550,7 +549,7 @@ class ResourceRegistry(object):
msg = _('Non-empty resource type is required ' msg = _('Non-empty resource type is required '
'for resource "%s"') % resource_name 'for resource "%s"') % resource_name
raise exception.StackValidationFailed(message=msg) raise exception.StackValidationFailed(message=msg)
elif not isinstance(resource_type, six.string_types): elif not isinstance(resource_type, str):
msg = _('Resource "%s" type is not a string') % resource_name msg = _('Resource "%s" type is not a string') % resource_name
raise exception.StackValidationFailed(message=msg) raise exception.StackValidationFailed(message=msg)
@ -558,7 +557,7 @@ class ResourceRegistry(object):
info = self.get_resource_info(resource_type, info = self.get_resource_info(resource_type,
resource_name=resource_name) resource_name=resource_name)
except exception.EntityNotFound as exc: except exception.EntityNotFound as exc:
raise exception.StackValidationFailed(message=six.text_type(exc)) raise exception.StackValidationFailed(message=str(exc))
return info.get_class_to_instantiate() return info.get_class_to_instantiate()
@ -590,7 +589,7 @@ class ResourceRegistry(object):
if support_status is not None and not support.is_valid_status( if support_status is not None and not support.is_valid_status(
support_status): support_status):
msg = (_('Invalid support status and should be one of %s') % msg = (_('Invalid support status and should be one of %s') %
six.text_type(support.SUPPORT_STATUSES)) str(support.SUPPORT_STATUSES))
raise exception.Invalid(reason=msg) raise exception.Invalid(reason=msg)
def is_resource(key): def is_resource(key):
@ -650,7 +649,7 @@ class ResourceRegistry(object):
} }
return [resource_description(name, cls, with_description) return [resource_description(name, cls, with_description)
for name, cls in six.iteritems(self._registry) for name, cls in self._registry.items()
if (is_resource(name) and if (is_resource(name) and
name_matches(name) and name_matches(name) and
status_matches(cls) and status_matches(cls) and
@ -693,7 +692,7 @@ class Environment(object):
if env_fmt.PARAMETERS in env: if env_fmt.PARAMETERS in env:
self.params = env[env_fmt.PARAMETERS] self.params = env[env_fmt.PARAMETERS]
else: else:
self.params = dict((k, v) for (k, v) in six.iteritems(env) self.params = dict((k, v) for (k, v) in env.items()
if k not in (env_fmt.PARAMETER_DEFAULTS, if k not in (env_fmt.PARAMETER_DEFAULTS,
env_fmt.ENCRYPTED_PARAM_NAMES, env_fmt.ENCRYPTED_PARAM_NAMES,
env_fmt.EVENT_SINKS, env_fmt.EVENT_SINKS,

View File

@ -16,14 +16,11 @@ import collections
import itertools import itertools
import weakref import weakref
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@six.add_metaclass(abc.ABCMeta) class Function(metaclass=abc.ABCMeta):
class Function(object):
"""Abstract base class for template functions.""" """Abstract base class for template functions."""
def __init__(self, stack, fn_name, args): def __init__(self, stack, fn_name, args):
@ -98,12 +95,12 @@ class Function(object):
return all_dep_attrs(self.args) return all_dep_attrs(self.args)
def res_dep_attrs(resource_name): def res_dep_attrs(resource_name):
return six.moves.zip(itertools.repeat(resource_name), return zip(itertools.repeat(resource_name),
self.dep_attrs(resource_name)) self.dep_attrs(resource_name))
resource_names = self.stack.enabled_rsrc_names() resource_names = self.stack.enabled_rsrc_names()
return itertools.chain.from_iterable(six.moves.map(res_dep_attrs, return itertools.chain.from_iterable(map(res_dep_attrs,
resource_names)) resource_names))
def __reduce__(self): def __reduce__(self):
@ -160,8 +157,7 @@ class Function(object):
__hash__ = None __hash__ = None
@six.add_metaclass(abc.ABCMeta) class Macro(Function, metaclass=abc.ABCMeta):
class Macro(Function):
"""Abstract base class for template macros. """Abstract base class for template macros.
A macro differs from a function in that it controls how the template is A macro differs from a function in that it controls how the template is
@ -260,7 +256,7 @@ def resolve(snippet):
if isinstance(snippet, collections.Mapping): if isinstance(snippet, collections.Mapping):
return dict((k, resolve(v)) for k, v in snippet.items()) return dict((k, resolve(v)) for k, v in snippet.items())
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
return [resolve(v) for v in snippet] return [resolve(v) for v in snippet]
@ -270,7 +266,7 @@ def resolve(snippet):
def validate(snippet, path=None): def validate(snippet, path=None):
if path is None: if path is None:
path = [] path = []
elif isinstance(path, six.string_types): elif isinstance(path, str):
path = [path] path = [path]
if isinstance(snippet, Function): if isinstance(snippet, Function):
@ -281,11 +277,11 @@ def validate(snippet, path=None):
except Exception as e: except Exception as e:
raise exception.StackValidationFailed( raise exception.StackValidationFailed(
path=path + [snippet.fn_name], path=path + [snippet.fn_name],
message=six.text_type(e)) message=str(e))
elif isinstance(snippet, collections.Mapping): elif isinstance(snippet, collections.Mapping):
for k, v in six.iteritems(snippet): for k, v in snippet.items():
validate(v, path + [k]) validate(v, path + [k])
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
basepath = list(path) basepath = list(path)
parent = basepath.pop() if basepath else '' parent = basepath.pop() if basepath else ''
@ -305,13 +301,13 @@ def dependencies(snippet, path=''):
elif isinstance(snippet, collections.Mapping): elif isinstance(snippet, collections.Mapping):
def mkpath(key): def mkpath(key):
return '.'.join([path, six.text_type(key)]) return '.'.join([path, str(key)])
deps = (dependencies(value, deps = (dependencies(value,
mkpath(key)) for key, value in snippet.items()) mkpath(key)) for key, value in snippet.items())
return itertools.chain.from_iterable(deps) return itertools.chain.from_iterable(deps)
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
def mkpath(idx): def mkpath(idx):
return ''.join([path, '[%d]' % idx]) return ''.join([path, '[%d]' % idx])
@ -340,7 +336,7 @@ def dep_attrs(snippet, resource_name):
elif isinstance(snippet, collections.Mapping): elif isinstance(snippet, collections.Mapping):
attrs = (dep_attrs(val, resource_name) for val in snippet.values()) attrs = (dep_attrs(val, resource_name) for val in snippet.values())
return itertools.chain.from_iterable(attrs) return itertools.chain.from_iterable(attrs)
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
attrs = (dep_attrs(value, resource_name) for value in snippet) attrs = (dep_attrs(value, resource_name) for value in snippet)
return itertools.chain.from_iterable(attrs) return itertools.chain.from_iterable(attrs)
@ -363,7 +359,7 @@ def all_dep_attrs(snippet):
elif isinstance(snippet, collections.Mapping): elif isinstance(snippet, collections.Mapping):
res_attrs = (all_dep_attrs(value) for value in snippet.values()) res_attrs = (all_dep_attrs(value) for value in snippet.values())
return itertools.chain.from_iterable(res_attrs) return itertools.chain.from_iterable(res_attrs)
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
res_attrs = (all_dep_attrs(value) for value in snippet) res_attrs = (all_dep_attrs(value) for value in snippet)
return itertools.chain.from_iterable(res_attrs) return itertools.chain.from_iterable(res_attrs)

View File

@ -11,8 +11,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
class NodeData(object): class NodeData(object):
"""Data about a node in the graph, to be passed along to other nodes.""" """Data about a node in the graph, to be passed along to other nodes."""
@ -53,8 +51,8 @@ class NodeData(object):
"""Return a dict of all available top-level attribute values.""" """Return a dict of all available top-level attribute values."""
attrs = {k: v attrs = {k: v
for k, v in self._attributes.items() for k, v in self._attributes.items()
if isinstance(k, six.string_types)} if isinstance(k, str)}
for v in six.itervalues(attrs): for v in attrs.items():
if isinstance(v, Exception): if isinstance(v, Exception):
raise v raise v
return attrs return attrs
@ -69,7 +67,7 @@ class NodeData(object):
def attribute_names(self): def attribute_names(self):
"""Iterate over valid top-level attribute names.""" """Iterate over valid top-level attribute names."""
for key in self._attributes: for key in self._attributes:
if isinstance(key, six.string_types): if isinstance(key, str):
yield key yield key
else: else:
yield key[0] yield key[0]
@ -80,7 +78,7 @@ class NodeData(object):
This is the format that is serialised and stored in the database's This is the format that is serialised and stored in the database's
SyncPoints. SyncPoints.
""" """
for v in six.itervalues(self._attributes): for v in self._attributes.values():
if isinstance(v, Exception): if isinstance(v, Exception):
raise v raise v

View File

@ -14,7 +14,6 @@
import collections import collections
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -274,9 +273,9 @@ class Property(object):
def _get_string(self, value): def _get_string(self, value):
if value is None: if value is None:
value = self.has_default() and self.default() or '' value = self.has_default() and self.default() or ''
if not isinstance(value, six.string_types): if not isinstance(value, str):
if isinstance(value, (bool, int)): if isinstance(value, (bool, int)):
value = six.text_type(value) value = str(value)
else: else:
raise ValueError(_('Value must be a string; got %r') % value) raise ValueError(_('Value must be a string; got %r') % value)
return value return value
@ -306,24 +305,23 @@ class Property(object):
# via a provider resource, in particular lists-of-dicts which # via a provider resource, in particular lists-of-dicts which
# cannot be handled correctly via comma_delimited_list # cannot be handled correctly via comma_delimited_list
if self.schema.allow_conversion: if self.schema.allow_conversion:
if isinstance(value, six.string_types): if isinstance(value, str):
return value return value
elif isinstance(value, collections.Sequence): elif isinstance(value, collections.Sequence):
return jsonutils.dumps(value) return jsonutils.dumps(value)
raise TypeError(_('"%s" is not a map') % value) raise TypeError(_('"%s" is not a map') % value)
return dict(self._get_children(six.iteritems(value), return dict(self._get_children(value.items(),
validate=validate, validate=validate,
translation=translation)) translation=translation))
def _get_list(self, value, validate=False, translation=None): def _get_list(self, value, validate=False, translation=None):
if value is None: if value is None:
value = self.has_default() and self.default() or [] value = self.has_default() and self.default() or []
if self.schema.allow_conversion and isinstance(value, if self.schema.allow_conversion and isinstance(value, str):
six.string_types):
value = param_utils.delim_string_to_list(value) value = param_utils.delim_string_to_list(value)
if (not isinstance(value, collections.Sequence) or if (not isinstance(value, collections.Sequence) or
isinstance(value, six.string_types)): isinstance(value, str)):
raise TypeError(_('"%s" is not a list') % repr(value)) raise TypeError(_('"%s" is not a list') % repr(value))
return [v[1] for v in self._get_children(enumerate(value), return [v[1] for v in self._get_children(enumerate(value),
@ -341,7 +339,7 @@ class Property(object):
value = self.has_default() and self.default() or False value = self.has_default() and self.default() or False
if isinstance(value, bool): if isinstance(value, bool):
return value return value
if isinstance(value, six.string_types): if isinstance(value, str):
normalised = value.lower() normalised = value.lower()
if normalised not in ['true', 'false']: if normalised not in ['true', 'false']:
raise ValueError(_('"%s" is not a valid boolean') % normalised) raise ValueError(_('"%s" is not a valid boolean') % normalised)
@ -430,7 +428,7 @@ class Properties(collections.Mapping):
else: else:
path = [key] path = [key]
raise exception.StackValidationFailed( raise exception.StackValidationFailed(
path=path, message=six.text_type(e)) path=path, message=str(e))
# are there unimplemented Properties # are there unimplemented Properties
if not prop.implemented() and key in self.data: if not prop.implemented() and key in self.data:
@ -486,7 +484,7 @@ class Properties(collections.Mapping):
# the resolver function could raise any number of exceptions, # the resolver function could raise any number of exceptions,
# so handle this generically # so handle this generically
except Exception as e: except Exception as e:
raise ValueError(six.text_type(e)) raise ValueError(str(e))
def _get_property_value(self, key, validate=False): def _get_property_value(self, key, validate=False):
if key not in self: if key not in self:
@ -652,7 +650,7 @@ class Properties(collections.Mapping):
return {}, {} return {}, {}
param_prop_defs = [param_prop_def_items(n, s, template_type) param_prop_defs = [param_prop_def_items(n, s, template_type)
for n, s in six.iteritems(schemata(schema)) for n, s in schemata(schema).items()
if s.implemented] if s.implemented]
param_items, prop_items = zip(*param_prop_defs) param_items, prop_items = zip(*param_prop_defs)
return dict(param_items), dict(prop_items) return dict(param_items), dict(prop_items)

View File

@ -17,7 +17,7 @@ from heat.engine import properties
from heat.engine import resource from heat.engine import resource
from heat.engine import support from heat.engine import support
from six.moves.urllib import parse as urlparse from urllib.parse import urlencode
COMMON_PROPERTIES = ( COMMON_PROPERTIES = (
@ -231,7 +231,7 @@ class BaseAlarm(resource.Resource):
for queue in kwargs.pop(queue_type, []): for queue in kwargs.pop(queue_type, []):
query = {'queue_name': queue} query = {'queue_name': queue}
yield 'trust+zaqar://?%s' % urlparse.urlencode(query) yield 'trust+zaqar://?%s' % urlencode(query)
action_props = {arg_types[0]: list(get_urls(*arg_types)) action_props = {arg_types[0]: list(get_urls(*arg_types))
for arg_types in ((ALARM_ACTIONS, ALARM_QUEUES), for arg_types in ((ALARM_ACTIONS, ALARM_QUEUES),

View File

@ -13,7 +13,6 @@
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
import six
from heat.common import exception from heat.common import exception
from heat.common import grouputils from heat.common import grouputils
@ -327,7 +326,7 @@ class AutoScalingGroup(cooldown.CooldownMixin, instgrp.InstanceGroup):
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
try: try:
notif.update({'suffix': 'error', notif.update({'suffix': 'error',
'message': six.text_type(resize_ex), 'message': str(resize_ex),
'capacity': grouputils.get_size(self), 'capacity': grouputils.get_size(self),
}) })
notification.send(**notif) notification.send(**notif)

View File

@ -11,9 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
@ -200,7 +197,7 @@ class LaunchConfiguration(resource.Resource):
for sg in server.security_groups] for sg in server.security_groups]
} }
lc_props = function.resolve(self.properties.data) lc_props = function.resolve(self.properties.data)
for key, value in six.iteritems(instance_props): for key, value in instance_props.items():
# the properties which are specified in launch configuration, # the properties which are specified in launch configuration,
# will override the attributes from the instance # will override the attributes from the instance
lc_props.setdefault(key, value) lc_props.setdefault(key, value)

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -101,9 +99,9 @@ class AWSScalingPolicy(heat_sp.AutoScalingPolicy):
def get_reference_id(self): def get_reference_id(self):
if self.resource_id is not None: if self.resource_id is not None:
return six.text_type(self._get_ec2_signed_url()) return str(self._get_ec2_signed_url())
else: else:
return six.text_type(self.name) return str(self.name)
def resource_mapping(): def resource_mapping():

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
from requests import exceptions from requests import exceptions
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -95,7 +94,7 @@ class NestedStack(stack_resource.StackResource):
def get_reference_id(self): def get_reference_id(self):
identifier = self.nested_identifier() identifier = self.nested_identifier()
if identifier is None: if identifier is None:
return six.text_type(self.name) return str(self.name)
return identifier.arn() return identifier.arn()

View File

@ -11,8 +11,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 heat.engine.resources import signal_responder from heat.engine.resources import signal_responder
from heat.engine.resources import wait_condition as wc_base from heat.engine.resources import wait_condition as wc_base
from heat.engine import support from heat.engine import support
@ -39,9 +37,9 @@ class WaitConditionHandle(wc_base.BaseWaitConditionHandle):
def get_reference_id(self): def get_reference_id(self):
if self.resource_id: if self.resource_id:
wc = signal_responder.WAITCONDITION wc = signal_responder.WAITCONDITION
return six.text_type(self._get_ec2_signed_url(signal_type=wc)) return str(self._get_ec2_signed_url(signal_type=wc))
else: else:
return six.text_type(self.name) return str(self.name)
def metadata_update(self, new_metadata=None): def metadata_update(self, new_metadata=None):
"""DEPRECATED. Should use handle_signal instead.""" """DEPRECATED. Should use handle_signal instead."""

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
from oslo_log import log as logging from oslo_log import log as logging
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -138,13 +137,13 @@ class ElasticIp(resource.Resource):
def get_reference_id(self): def get_reference_id(self):
eip = self._ipaddress() eip = self._ipaddress()
if eip: if eip:
return six.text_type(eip) return str(eip)
else: else:
return six.text_type(self.name) return str(self.name)
def _resolve_attribute(self, name): def _resolve_attribute(self, name):
if name == self.ALLOCATION_ID: if name == self.ALLOCATION_ID:
return six.text_type(self.resource_id) return str(self.resource_id)
class ElasticIpAssociation(resource.Resource): class ElasticIpAssociation(resource.Resource):

View File

@ -15,7 +15,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
cfg.CONF.import_opt('max_server_name_length', 'heat.common.config') cfg.CONF.import_opt('max_server_name_length', 'heat.common.config')
@ -396,7 +395,7 @@ class Instance(resource.Resource, sh.SchedulerHintsMixin):
LOG.info('%(name)s._resolve_attribute(%(attname)s) == %(res)s', LOG.info('%(name)s._resolve_attribute(%(attname)s) == %(res)s',
{'name': self.name, 'attname': name, 'res': res}) {'name': self.name, 'attname': name, 'res': res})
return six.text_type(res) if res else None return str(res) if res else None
def _port_data_delete(self): def _port_data_delete(self):
# delete the port data which implicit-created # delete the port data which implicit-created
@ -415,7 +414,7 @@ class Instance(resource.Resource, sh.SchedulerHintsMixin):
unsorted_nics = [] unsorted_nics = []
for entry in network_interfaces: for entry in network_interfaces:
nic = (entry nic = (entry
if not isinstance(entry, six.string_types) if not isinstance(entry, str)
else {'NetworkInterfaceId': entry, else {'NetworkInterfaceId': entry,
'DeviceIndex': len(unsorted_nics)}) 'DeviceIndex': len(unsorted_nics)})
unsorted_nics.append(nic) unsorted_nics.append(nic)
@ -520,7 +519,7 @@ class Instance(resource.Resource, sh.SchedulerHintsMixin):
hint = tm[self.NOVA_SCHEDULER_HINT_KEY] hint = tm[self.NOVA_SCHEDULER_HINT_KEY]
hint_value = tm[self.NOVA_SCHEDULER_HINT_VALUE] hint_value = tm[self.NOVA_SCHEDULER_HINT_VALUE]
if hint in scheduler_hints: if hint in scheduler_hints:
if isinstance(scheduler_hints[hint], six.string_types): if isinstance(scheduler_hints[hint], str):
scheduler_hints[hint] = [scheduler_hints[hint]] scheduler_hints[hint] = [scheduler_hints[hint]]
scheduler_hints[hint].append(hint_value) scheduler_hints[hint].append(hint_value)
else: else:

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import properties from heat.engine import properties
@ -102,7 +100,7 @@ class VPCGatewayAttachment(resource.Resource):
default_client_name = 'neutron' default_client_name = 'neutron'
def _vpc_route_tables(self, ignore_errors=False): def _vpc_route_tables(self, ignore_errors=False):
for res in six.itervalues(self.stack): for res in self.stack.values():
if res.has_interface('AWS::EC2::RouteTable'): if res.has_interface('AWS::EC2::RouteTable'):
try: try:
vpc_id = self.properties[self.VPC_ID] vpc_id = self.properties[self.VPC_ID]

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import properties from heat.engine import properties
@ -169,12 +167,12 @@ class NeutronSecurityGroup(object):
rule['direction'] = 'egress' rule['direction'] = 'egress'
for rule in updated[self.sg.SECURITY_GROUP_INGRESS]: for rule in updated[self.sg.SECURITY_GROUP_INGRESS]:
rule['direction'] = 'ingress' rule['direction'] = 'ingress'
updated_rules = list(six.itervalues(updated)) updated_rules = list(updated.values())
updated_all = updated_rules[0] + updated_rules[1] updated_all = updated_rules[0] + updated_rules[1]
ids_to_delete = [id for id, rule in existing.items() ids_to_delete = [id for id, rule in existing.items()
if rule not in updated_all] if rule not in updated_all]
rules_to_create = [rule for rule in updated_all rules_to_create = [rule for rule in updated_all
if rule not in six.itervalues(existing)] if rule not in existing.values()]
return ids_to_delete, rules_to_create return ids_to_delete, rules_to_create

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
from oslo_log import log as logging from oslo_log import log as logging
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -80,7 +79,7 @@ class User(stack_user.StackUser):
# If a non-string (e.g embedded IAM dict policy) is passed, we # If a non-string (e.g embedded IAM dict policy) is passed, we
# ignore the policy (don't reject it because we previously ignored # ignore the policy (don't reject it because we previously ignored
# and we don't want to break templates which previously worked # and we don't want to break templates which previously worked
if not isinstance(policy, six.string_types): if not isinstance(policy, str):
LOG.debug("Ignoring policy %s, must be string " LOG.debug("Ignoring policy %s, must be string "
"resource name", policy) "resource name", policy)
continue continue
@ -118,7 +117,7 @@ class User(stack_user.StackUser):
def access_allowed(self, resource_name): def access_allowed(self, resource_name):
policies = (self.properties[self.POLICIES] or []) policies = (self.properties[self.POLICIES] or [])
for policy in policies: for policy in policies:
if not isinstance(policy, six.string_types): if not isinstance(policy, str):
LOG.debug("Ignoring policy %s, must be string " LOG.debug("Ignoring policy %s, must be string "
"resource name", policy) "resource name", policy)
continue continue

View File

@ -14,7 +14,6 @@ import os
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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -623,7 +622,7 @@ backend servers
'Interval must be larger than Timeout'} 'Interval must be larger than Timeout'}
def get_reference_id(self): def get_reference_id(self):
return six.text_type(self.name) return str(self.name)
def _resolve_attribute(self, name): def _resolve_attribute(self, name):
"""We don't really support any of these yet.""" """We don't really support any of these yet."""

View File

@ -10,8 +10,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 six from urllib.parse import urlparse
from six.moves.urllib import parse as urlparse
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -165,11 +164,11 @@ class S3Bucket(resource.Resource):
self.client_plugin().ignore_not_found(ex) self.client_plugin().ignore_not_found(ex)
def get_reference_id(self): def get_reference_id(self):
return six.text_type(self.resource_id) return str(self.resource_id)
def _resolve_attribute(self, name): def _resolve_attribute(self, name):
url = self.client().get_auth()[0] url = self.client().get_auth()[0]
parsed = list(urlparse.urlparse(url)) parsed = list(urlparse(url))
if name == self.DOMAIN_NAME: if name == self.DOMAIN_NAME:
return parsed[1].split(':')[0] return parsed[1].split(':')[0]
elif name == self.WEBSITE_URL: elif name == self.WEBSITE_URL:

View File

@ -11,8 +11,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 heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
from heat.engine import properties from heat.engine import properties
@ -157,7 +155,7 @@ class AodhAlarm(alarm_base.BaseAlarm):
# make sure the matching_metadata appears in the query like this: # make sure the matching_metadata appears in the query like this:
# {field: metadata.$prefix.x, ...} # {field: metadata.$prefix.x, ...}
for m_k, m_v in six.iteritems(mmd): for m_k, m_v in mmd.items():
key = 'metadata.%s' % prefix key = 'metadata.%s' % prefix
if m_k.startswith('metadata.'): if m_k.startswith('metadata.'):
m_k = m_k[len('metadata.'):] m_k = m_k[len('metadata.'):]
@ -168,7 +166,7 @@ class AodhAlarm(alarm_base.BaseAlarm):
# NOTE(prazumovsky): type of query value must be a string, but # NOTE(prazumovsky): type of query value must be a string, but
# matching_metadata value type can not be a string, so we # matching_metadata value type can not be a string, so we
# must convert value to a string type. # must convert value to a string type.
query.append(dict(field=key, op='eq', value=six.text_type(m_v))) query.append(dict(field=key, op='eq', value=str(m_v)))
if self.MATCHING_METADATA in kwargs: if self.MATCHING_METADATA in kwargs:
del kwargs[self.MATCHING_METADATA] del kwargs[self.MATCHING_METADATA]
if self.QUERY in kwargs: if self.QUERY in kwargs:

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -192,12 +190,12 @@ class CertificateContainer(GenericContainer):
} }
def create_container(self): def create_container(self):
info = dict((k, v) for k, v in six.iteritems(self.properties) info = dict((k, v) for k, v in self.properties.items()
if v is not None) if v is not None)
return self.client_plugin().create_certificate(**info) return self.client_plugin().create_certificate(**info)
def get_refs(self): def get_refs(self):
return [v for k, v in six.iteritems(self.properties) return [v for k, v in self.properties.items()
if (k != self.NAME and v is not None)] if (k != self.NAME and v is not None)]
@ -239,12 +237,12 @@ class RSAContainer(GenericContainer):
} }
def create_container(self): def create_container(self):
info = dict((k, v) for k, v in six.iteritems(self.properties) info = dict((k, v) for k, v in self.properties.items()
if v is not None) if v is not None)
return self.client_plugin().create_rsa(**info) return self.client_plugin().create_rsa(**info)
def get_refs(self): def get_refs(self):
return [v for k, v in six.iteritems(self.properties) return [v for k, v in self.properties.items()
if (k != self.NAME and v is not None)] if (k != self.NAME and v is not None)]

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -228,8 +226,8 @@ class Order(resource.Resource):
raise exception.ResourcePropertyDependency( raise exception.ResourcePropertyDependency(
prop1=self.PROFILE, prop2=self.CA_ID prop1=self.PROFILE, prop2=self.CA_ID
) )
declared_props = sorted([k for k, v in six.iteritems( declared_props = sorted([k for k, v in self.properties.items()
self.properties) if k != self.TYPE and v is not None]) if k != self.TYPE and v is not None])
allowed_props = sorted(self.ALLOWED_PROPERTIES_FOR_TYPE[ allowed_props = sorted(self.ALLOWED_PROPERTIES_FOR_TYPE[
self.properties[self.TYPE]]) self.properties[self.TYPE]])
diff = sorted(set(declared_props) - set(allowed_props)) diff = sorted(set(declared_props) - set(allowed_props))

View File

@ -13,7 +13,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 six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -308,7 +307,7 @@ class CinderVolume(vb.BaseVolume, sh.SchedulerHintsMixin):
cinder = self.client() cinder = self.client()
vol = cinder.volumes.get(self.resource_id) vol = cinder.volumes.get(self.resource_id)
if name == self.METADATA_ATTR: if name == self.METADATA_ATTR:
return six.text_type(jsonutils.dumps(vol.metadata)) return str(jsonutils.dumps(vol.metadata))
elif name == self.METADATA_VALUES_ATTR: elif name == self.METADATA_VALUES_ATTR:
return vol.metadata return vol.metadata
if name == self.DISPLAY_NAME_ATTR: if name == self.DISPLAY_NAME_ATTR:
@ -317,7 +316,7 @@ class CinderVolume(vb.BaseVolume, sh.SchedulerHintsMixin):
return vol.description return vol.description
elif name == self.ATTACHMENTS_LIST: elif name == self.ATTACHMENTS_LIST:
return vol.attachments return vol.attachments
return six.text_type(getattr(vol, name)) return str(getattr(vol, name))
def check_create_complete(self, vol_id): def check_create_complete(self, vol_id):
complete = super(CinderVolume, self).check_create_complete(vol_id) complete = super(CinderVolume, self).check_create_complete(vol_id)
@ -353,7 +352,7 @@ class CinderVolume(vb.BaseVolume, sh.SchedulerHintsMixin):
if self.client_plugin().is_client_exception(ex): if self.client_plugin().is_client_exception(ex):
raise exception.Error(_( raise exception.Error(_(
"Failed to extend volume %(vol)s - %(err)s") % { "Failed to extend volume %(vol)s - %(err)s") % {
'vol': self.resource_id, 'err': six.text_type(ex)}) 'vol': self.resource_id, 'err': str(ex)})
else: else:
raise raise
return True return True

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
@ -103,7 +101,7 @@ class DesignateRecordSet(resource.Resource):
self).client(version=self.client_plugin().V2) self).client(version=self.client_plugin().V2)
def handle_create(self): def handle_create(self):
args = dict((k, v) for k, v in six.iteritems(self.properties) if v) args = dict((k, v) for k, v in self.properties.items() if v)
args['type_'] = args.pop(self.TYPE) args['type_'] = args.pop(self.TYPE)
if not args.get(self.NAME): if not args.get(self.NAME):
args[self.NAME] = self.physical_resource_name() args[self.NAME] = self.physical_resource_name()

View File

@ -10,7 +10,6 @@
# 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 six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -126,7 +125,7 @@ class DesignateZone(resource.Resource):
raise_invalid_exception(self.SECONDARY, self.MASTERS) raise_invalid_exception(self.SECONDARY, self.MASTERS)
def handle_create(self): def handle_create(self):
args = dict((k, v) for k, v in six.iteritems(self.properties) if v) args = dict((k, v) for k, v in self.properties.items() if v)
args['type_'] = args.pop(self.TYPE) args['type_'] = args.pop(self.TYPE)
zone = self.client().zones.create(**args) zone = self.client().zones.create(**args)

View File

@ -11,8 +11,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_log import log as logging from oslo_log import log as logging
from heat.common import exception from heat.common import exception
@ -208,7 +206,7 @@ class AutoScalingResourceGroup(aws_asg.AutoScalingGroup):
template_version=template_version) template_version=template_version)
def _attribute_output_name(self, *attr_path): def _attribute_output_name(self, *attr_path):
return ', '.join(six.text_type(a) for a in attr_path) return ', '.join(str(a) for a in attr_path)
def get_attribute(self, key, *path): def get_attribute(self, key, *path):
if key == self.CURRENT_SIZE: if key == self.CURRENT_SIZE:
@ -280,7 +278,7 @@ class AutoScalingResourceGroup(aws_asg.AutoScalingGroup):
def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn): def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn):
for attr in self.referenced_attrs(): for attr in self.referenced_attrs():
if isinstance(attr, six.string_types): if isinstance(attr, str):
key, path = attr, [] key, path = attr, []
else: else:
key, path = attr[0], list(attr[1:]) key, path = attr[0], list(attr[1:])

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
import functools import functools
import six
from oslo_log import log as logging from oslo_log import log as logging
@ -460,7 +459,7 @@ class InstanceGroup(stack_resource.StackResource):
def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn): def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn):
for attr in self.referenced_attrs(): for attr in self.referenced_attrs():
if isinstance(attr, six.string_types): if isinstance(attr, str):
key = attr key = attr
else: else:
key = attr[0] key = attr[0]

View File

@ -11,7 +11,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 uuid import uuid
from heat.engine import properties from heat.engine import properties
@ -47,7 +46,7 @@ class NoneResource(resource.Resource):
self.translate_properties(self.properties, client_resolve) self.translate_properties(self.properties, client_resolve)
def handle_create(self): def handle_create(self):
self.resource_id_set(six.text_type(uuid.uuid4())) self.resource_id_set(str(uuid.uuid4()))
# set is_placeholder flag when resource trying to replace original # set is_placeholder flag when resource trying to replace original
# resource with a placeholder resource. # resource with a placeholder resource.
self.data_set(self.IS_PLACEHOLDER, 'True') self.data_set(self.IS_PLACEHOLDER, 'True')

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.common import password_gen from heat.common import password_gen
@ -235,7 +233,7 @@ class RandomString(resource.Resource):
if self.resource_id is not None: if self.resource_id is not None:
return self.data().get('value') return self.data().get('value')
else: else:
return six.text_type(self.name) return str(self.name)
def resource_mapping(): def resource_mapping():

View File

@ -13,7 +13,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 six
import tempfile import tempfile
from heat.common import auth_plugin from heat.common import auth_plugin
@ -49,7 +48,7 @@ class TempCACertFile(object):
try: try:
self._cacert_temp_file = tempfile.NamedTemporaryFile() self._cacert_temp_file = tempfile.NamedTemporaryFile()
self._cacert_temp_file.write( self._cacert_temp_file.write(
six.text_type(self._cacert).encode('utf-8')) str(self._cacert).encode('utf-8'))
# Add seek func to make sure the writen context will flush to # Add seek func to make sure the writen context will flush to
# tempfile with python 2.7. we can use flush() for python 2.7 # tempfile with python 2.7. we can use flush() for python 2.7
# but not 3.5. # but not 3.5.
@ -264,7 +263,7 @@ class RemoteStack(resource.Resource):
location = "remote cloud" location = "remote cloud"
else: else:
location = 'region "%s"' % self._region_name location = 'region "%s"' % self._region_name
exc_info = dict(location=location, exc=six.text_type(ex)) exc_info = dict(location=location, exc=str(ex))
msg = _('Cannot establish connection to Heat endpoint at ' msg = _('Cannot establish connection to Heat endpoint at '
'%(location)s due to "%(exc)s"') % exc_info '%(location)s due to "%(exc)s"') % exc_info
raise exception.StackValidationFailed(message=msg) raise exception.StackValidationFailed(message=msg)
@ -285,7 +284,7 @@ class RemoteStack(resource.Resource):
location = "remote cloud" location = "remote cloud"
else: else:
location = 'region "%s"' % self._region_name location = 'region "%s"' % self._region_name
exc_info = dict(location=location, exc=six.text_type(ex)) exc_info = dict(location=location, exc=str(ex))
msg = _('Failed validating stack template using Heat endpoint at ' msg = _('Failed validating stack template using Heat endpoint at '
'%(location)s due to "%(exc)s"') % exc_info '%(location)s due to "%(exc)s"') % exc_info
raise exception.StackValidationFailed(message=msg) raise exception.StackValidationFailed(message=msg)

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
import functools import functools
import six
from oslo_log import log as logging from oslo_log import log as logging
@ -155,7 +154,7 @@ class ResourceChain(stack_resource.StackResource):
return {} return {}
def _attribute_output_name(self, *attr_path): def _attribute_output_name(self, *attr_path):
return ', '.join(six.text_type(a) for a in attr_path) return ', '.join(str(a) for a in attr_path)
def get_attribute(self, key, *path): def get_attribute(self, key, *path):
if key == self.ATTR_ATTRIBUTES and not path: if key == self.ATTR_ATTRIBUTES and not path:
@ -198,7 +197,7 @@ class ResourceChain(stack_resource.StackResource):
def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn): def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn):
for attr in self.referenced_attrs(): for attr in self.referenced_attrs():
if isinstance(attr, six.string_types): if isinstance(attr, str):
key, path = attr, [] key, path = attr, []
else: else:
key, path = attr[0], list(attr[1:]) key, path = attr[0], list(attr[1:])
@ -227,7 +226,7 @@ class ResourceChain(stack_resource.StackResource):
@staticmethod @staticmethod
def _resource_names(resource_types): def _resource_names(resource_types):
"""Returns a list of unique resource names to create.""" """Returns a list of unique resource names to create."""
return [six.text_type(i) for i, t in enumerate(resource_types)] return [str(i) for i, t in enumerate(resource_types)]
def _build_resource_definition(self, resource_name, resource_type, def _build_resource_definition(self, resource_name, resource_type,
depends_on=None): depends_on=None):

View File

@ -15,7 +15,6 @@ import collections
import copy import copy
import functools import functools
import itertools import itertools
import six
from oslo_log import log as logging from oslo_log import log as logging
@ -306,7 +305,8 @@ class ResourceGroup(stack_resource.StackResource):
first_name = next(self._resource_names()) first_name = next(self._resource_names())
test_tmpl = self._assemble_nested([first_name], test_tmpl = self._assemble_nested([first_name],
include_all=True) include_all=True)
res_def = next(six.itervalues(test_tmpl.resource_definitions(None))) res_def = next(iter(list(test_tmpl.resource_definitions(None).values())
))
# make sure we can resolve the nested resource type # make sure we can resolve the nested resource type
self.stack.env.get_class_to_instantiate(res_def.resource_type) self.stack.env.get_class_to_instantiate(res_def.resource_type)
@ -339,12 +339,12 @@ class ResourceGroup(stack_resource.StackResource):
if self.REMOVAL_RSRC_LIST in r: if self.REMOVAL_RSRC_LIST in r:
# Tolerate string or int list values # Tolerate string or int list values
for n in r[self.REMOVAL_RSRC_LIST]: for n in r[self.REMOVAL_RSRC_LIST]:
str_n = six.text_type(n) str_n = str(n)
if (str_n in current_blacklist or if (str_n in current_blacklist or
self.resource_id is None or self.resource_id is None or
str_n in insp.member_names(include_failed=True)): str_n in insp.member_names(include_failed=True)):
yield str_n yield str_n
elif isinstance(n, six.string_types): elif isinstance(n, str):
try: try:
refids = self.get_output(self.REFS_MAP) refids = self.get_output(self.REFS_MAP)
except (exception.NotFound, except (exception.NotFound,
@ -399,9 +399,9 @@ class ResourceGroup(stack_resource.StackResource):
def is_blacklisted(name): def is_blacklisted(name):
return name in name_blacklist return name in name_blacklist
candidates = six.moves.map(six.text_type, itertools.count()) candidates = map(str, itertools.count())
return itertools.islice(six.moves.filterfalse(is_blacklisted, return itertools.islice(itertools.filterfalse(is_blacklisted,
candidates), candidates),
size) size)
@ -488,7 +488,7 @@ class ResourceGroup(stack_resource.StackResource):
def _attribute_output_name(self, *attr_path): def _attribute_output_name(self, *attr_path):
if attr_path[0] == self.REFS: if attr_path[0] == self.REFS:
return self.REFS return self.REFS
return ', '.join(six.text_type(a) for a in attr_path) return ', '.join(str(a) for a in attr_path)
def get_attribute(self, key, *path): def get_attribute(self, key, *path):
if key == self.REMOVED_RSRC_LIST: if key == self.REMOVED_RSRC_LIST:
@ -546,7 +546,7 @@ class ResourceGroup(stack_resource.StackResource):
def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn): def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn):
for attr in self.referenced_attrs(): for attr in self.referenced_attrs():
if isinstance(attr, six.string_types): if isinstance(attr, str):
key, path = attr, [] key, path = attr, []
else: else:
key, path = attr[0], list(attr[1:]) key, path = attr[0], list(attr[1:])
@ -611,7 +611,7 @@ class ResourceGroup(stack_resource.StackResource):
if isinstance(snippet, collections.Mapping): if isinstance(snippet, collections.Mapping):
return dict((k, ignore_param_resolve(v)) return dict((k, ignore_param_resolve(v))
for k, v in snippet.items()) for k, v in snippet.items())
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
return [ignore_param_resolve(v) for v in snippet] return [ignore_param_resolve(v) for v in snippet]
@ -639,7 +639,7 @@ class ResourceGroup(stack_resource.StackResource):
def recurse(x): def recurse(x):
return self._handle_repl_val(res_name, x) return self._handle_repl_val(res_name, x)
if isinstance(val, six.string_types): if isinstance(val, str):
return val.replace(repl_var, res_name) return val.replace(repl_var, res_name)
elif isinstance(val, collections.Mapping): elif isinstance(val, collections.Mapping):
return {k: recurse(v) for k, v in val.items()} return {k: recurse(v) for k, v in val.items()}
@ -706,7 +706,7 @@ class ResourceGroup(stack_resource.StackResource):
old_resources = sorted(valid_resources, key=replace_priority) old_resources = sorted(valid_resources, key=replace_priority)
existing_names = set(n for n, d in valid_resources) existing_names = set(n for n, d in valid_resources)
new_names = six.moves.filterfalse(lambda n: n in existing_names, new_names = itertools.filterfalse(lambda n: n in existing_names,
names) names)
res_def = self.get_resource_def(include_all) res_def = self.get_resource_def(include_all)
definitions = scl_template.member_definitions( definitions = scl_template.member_definitions(

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
from oslo_log import log as logging from oslo_log import log as logging
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -186,9 +185,9 @@ class AutoScalingPolicy(signal_responder.SignalResponder):
if self.resource_id is None: if self.resource_id is None:
return return
if name == self.ALARM_URL: if name == self.ALARM_URL:
return six.text_type(self._get_ec2_signed_url()) return str(self._get_ec2_signed_url())
elif name == self.SIGNAL_URL: elif name == self.SIGNAL_URL:
return six.text_type(self._get_heat_signal_url()) return str(self._get_heat_signal_url())
def resource_mapping(): def resource_mapping():

View File

@ -12,8 +12,7 @@
# under the License. # under the License.
import copy import copy
import six import itertools
from six import itertools
import uuid import uuid
from oslo_config import cfg from oslo_config import cfg
@ -745,7 +744,7 @@ class SoftwareDeploymentGroup(resource_group.ResourceGroup):
def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn): def _nested_output_defns(self, resource_names, get_attr_fn, get_res_fn):
for attr in self.referenced_attrs(): for attr in self.referenced_attrs():
key = attr if isinstance(attr, six.string_types) else attr[0] key = attr if isinstance(attr, str) else attr[0]
n_attr = self._member_attribute_name(key) n_attr = self._member_attribute_name(key)
output_name = self._attribute_output_name(self.ATTR_ATTRIBUTES, output_name = self._attribute_output_name(self.ATTR_ATTRIBUTES,
n_attr) n_attr)

View File

@ -15,8 +15,6 @@ import collections
import copy import copy
import functools import functools
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
@ -150,8 +148,8 @@ class StructuredDeployment(sd.SoftwareDeployment):
def get_input_key_arg(snippet, input_key): def get_input_key_arg(snippet, input_key):
if len(snippet) != 1: if len(snippet) != 1:
return None return None
fn_name, fn_arg = next(six.iteritems(snippet)) fn_name, fn_arg = next(iter(snippet.items()))
if (fn_name == input_key and isinstance(fn_arg, six.string_types)): if (fn_name == input_key and isinstance(fn_arg, str)):
return fn_arg return fn_arg
@staticmethod @staticmethod
@ -175,8 +173,8 @@ class StructuredDeployment(sd.SoftwareDeployment):
check_input_val check_input_val
) )
return dict((k, parse(v)) for k, v in six.iteritems(snippet)) return dict((k, parse(v)) for k, v in snippet.items())
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
return [parse(v) for v in snippet] return [parse(v) for v in snippet]
else: else:

View File

@ -14,8 +14,7 @@
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 oslo_utils import timeutils from oslo_utils import timeutils
import six import urllib.parse as parse
from six.moves.urllib import parse
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -344,7 +343,7 @@ class SwiftSignal(resource.Resource):
def _resolve_attribute(self, key): def _resolve_attribute(self, key):
if key == self.DATA: if key == self.DATA:
return six.text_type(jsonutils.dumps(self.get_data())) return str(jsonutils.dumps(self.get_data()))
def resource_mapping(): def resource_mapping():

View File

@ -14,7 +14,6 @@
import datetime import datetime
import eventlet import eventlet
from oslo_utils import timeutils from oslo_utils import timeutils
import six
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -218,12 +217,12 @@ class TestResource(resource.Resource):
obj.get(entity_id) obj.get(entity_id)
except Exception as exc: except Exception as exc:
LOG.debug('%s.%s(%s) %s' % (client_name, self.entity, LOG.debug('%s.%s(%s) %s' % (client_name, self.entity,
entity_id, six.text_type(exc))) entity_id, str(exc)))
else: else:
# just sleep some more # just sleep some more
eventlet.sleep(1) eventlet.sleep(1)
if isinstance(started_at, six.string_types): if isinstance(started_at, str):
started_at = timeutils.parse_isotime(started_at) started_at = timeutils.parse_isotime(started_at)
started_at = timeutils.normalize_time(started_at) started_at = timeutils.normalize_time(started_at)

View File

@ -14,7 +14,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
from oslo_utils import timeutils from oslo_utils import timeutils
import six
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -158,7 +157,7 @@ class HeatWaitCondition(resource.Resource):
'key': key, 'key': key,
'res': res}) 'res': res})
return six.text_type(jsonutils.dumps(res)) return str(jsonutils.dumps(res))
def resource_mapping(): def resource_mapping():

View File

@ -11,7 +11,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from six.moves.urllib import parse from urllib import parse
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
@ -129,7 +127,7 @@ class Bay(resource.Resource):
def handle_update(self, json_snippet, tmpl_diff, prop_diff): def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff: if prop_diff:
patch = [{'op': 'replace', 'path': '/' + k, 'value': v} patch = [{'op': 'replace', 'path': '/' + k, 'value': v}
for k, v in six.iteritems(prop_diff)] for k, v in prop_diff.items()]
self.client().bays.update(self.resource_id, patch) self.client().bays.update(self.resource_id, patch)
return self.resource_id return self.resource_id

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -218,7 +216,7 @@ class Cluster(resource.Resource):
def handle_update(self, json_snippet, tmpl_diff, prop_diff): def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff: if prop_diff:
patch = [{'op': 'replace', 'path': '/' + k, 'value': v} patch = [{'op': 'replace', 'path': '/' + k, 'value': v}
for k, v in six.iteritems(prop_diff)] for k, v in prop_diff.items()]
self.client().clusters.update(self.resource_id, patch) self.client().clusters.update(self.resource_id, patch)
return self.resource_id return self.resource_id

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
@ -290,7 +288,7 @@ class ClusterTemplate(resource.Resource):
def handle_update(self, json_snippet, tmpl_diff, prop_diff): def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff: if prop_diff:
patch = [{'op': 'replace', 'path': '/' + k, 'value': v} patch = [{'op': 'replace', 'path': '/' + k, 'value': v}
for k, v in six.iteritems(prop_diff)] for k, v in prop_diff.items()]
self.client().cluster_templates.update(self.resource_id, patch) self.client().cluster_templates.update(self.resource_id, patch)
return self.resource_id return self.resource_id

View File

@ -13,7 +13,6 @@
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import encodeutils from oslo_utils import encodeutils
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -197,7 +196,7 @@ class ManilaShare(resource.Resource):
if self.resource_id is None: if self.resource_id is None:
return return
share = self._request_share() share = self._request_share()
return six.text_type(getattr(share, name)) return str(getattr(share, name))
def handle_create(self): def handle_create(self):
# Request IDs of entities from manila # Request IDs of entities from manila
@ -345,7 +344,7 @@ class ManilaShare(resource.Resource):
result[self.ACCESS_RULES] = [] result[self.ACCESS_RULES] = []
for rule in rules: for rule in rules:
result[self.ACCESS_RULES].append( result[self.ACCESS_RULES].append(
{(k, v) for (k, v) in six.iteritems(rule) {(k, v) for (k, v) in rule.items()
if k in self._ACCESS_RULE_PROPERTIES}) if k in self._ACCESS_RULE_PROPERTIES})
return result return result

View File

@ -13,7 +13,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 six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -212,7 +211,7 @@ class MistralExternalResource(resource.Resource):
LOG.debug('ExternalResource id set to %(rid)s from Mistral ' LOG.debug('ExternalResource id set to %(rid)s from Mistral '
'execution %(eid)s output' % {'eid': execution_id, 'execution %(eid)s output' % {'eid': execution_id,
'rid': rsrc_id}) 'rid': rsrc_id})
self.resource_id_set(six.text_type(rsrc_id)[:255]) self.resource_id_set(str(rsrc_id)[:255])
return success return success
def _resolve_attribute(self, name): def _resolve_attribute(self, name):

View File

@ -14,7 +14,6 @@
import copy import copy
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
import six
import yaml import yaml
from heat.common import exception from heat.common import exception
@ -553,7 +552,7 @@ class Workflow(signal_responder.SignalResponder,
if props.get(self.TASK_DEFAULTS) is not None: if props.get(self.TASK_DEFAULTS) is not None:
definition[defn_name][self.TASK_DEFAULTS.replace('_', '-')] = { definition[defn_name][self.TASK_DEFAULTS.replace('_', '-')] = {
k.replace('_', '-'): v for k, v in k.replace('_', '-'): v for k, v in
six.iteritems(props.get(self.TASK_DEFAULTS)) if v} props.get(self.TASK_DEFAULTS).items() if v}
return yaml.dump(definition, Dumper=yaml.CSafeDumper return yaml.dump(definition, Dumper=yaml.CSafeDumper
if hasattr(yaml, 'CSafeDumper') if hasattr(yaml, 'CSafeDumper')
@ -632,8 +631,8 @@ class Workflow(signal_responder.SignalResponder,
'created_at': execution.created_at, 'created_at': execution.created_at,
'updated_at': execution.updated_at, 'updated_at': execution.updated_at,
'state': execution.state, 'state': execution.state,
'input': jsonutils.loads(six.text_type(execution.input)), 'input': jsonutils.loads(str(execution.input)),
'output': jsonutils.loads(six.text_type(execution.output)) 'output': jsonutils.loads(str(execution.output))
} }
return [parse_execution_response( return [parse_execution_response(
@ -646,7 +645,7 @@ class Workflow(signal_responder.SignalResponder,
self.INPUT: self.properties.get(self.INPUT)} self.INPUT: self.properties.get(self.INPUT)}
elif name == self.ALARM_URL and self.resource_id is not None: elif name == self.ALARM_URL and self.resource_id is not None:
return six.text_type(self._get_ec2_signed_url()) return str(self._get_ec2_signed_url())
def resource_mapping(): def resource_mapping():

View File

@ -12,7 +12,7 @@
# under the License. # under the License.
import re import re
from six.moves import urllib from urllib.parse import urlparse
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -115,7 +115,7 @@ class MonascaNotification(resource.Resource):
if self.properties[self.TYPE] == self.WEBHOOK: if self.properties[self.TYPE] == self.WEBHOOK:
try: try:
parsed_address = urllib.parse.urlparse(address) parsed_address = urlparse(address)
except Exception: except Exception:
msg = _('Address "%(addr)s" should have correct format ' msg = _('Address "%(addr)s" should have correct format '
'required by "%(wh)s" type of "%(type)s" ' 'required by "%(wh)s" type of "%(type)s" '

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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import constraints from heat.engine import constraints
@ -62,7 +60,7 @@ class ExtraRoute(neutron.NeutronResource):
def add_dependencies(self, deps): def add_dependencies(self, deps):
super(ExtraRoute, self).add_dependencies(deps) super(ExtraRoute, self).add_dependencies(deps)
for resource in six.itervalues(self.stack): for resource in self.stack.values():
# depend on any RouterInterface in this template with the same # depend on any RouterInterface in this template with the same
# router_id as this router_id # router_id as this router_id
if resource.has_interface('OS::Neutron::RouterInterface'): if resource.has_interface('OS::Neutron::RouterInterface'):

View File

@ -10,7 +10,6 @@
# 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 six
from oslo_log import log as logging from oslo_log import log as logging
@ -238,7 +237,7 @@ class FloatingIP(neutron.NeutronResource):
except Exception as exc: except Exception as exc:
LOG.info("Ignoring Neutron error while " LOG.info("Ignoring Neutron error while "
"getting FloatingIP dependencies: %s", "getting FloatingIP dependencies: %s",
six.text_type(exc)) str(exc))
return False return False
else: else:
try: try:
@ -265,7 +264,7 @@ class FloatingIP(neutron.NeutronResource):
def add_dependencies(self, deps): def add_dependencies(self, deps):
super(FloatingIP, self).add_dependencies(deps) super(FloatingIP, self).add_dependencies(deps)
for resource in six.itervalues(self.stack): for resource in self.stack.values():
# depend on any RouterGateway in this template with the same # depend on any RouterGateway in this template with the same
# network_id as this floating_network_id # network_id as this floating_network_id
if resource.has_interface('OS::Neutron::RouterGateway'): if resource.has_interface('OS::Neutron::RouterGateway'):
@ -388,7 +387,7 @@ class FloatingIPAssociation(neutron.NeutronResource):
def add_dependencies(self, deps): def add_dependencies(self, deps):
super(FloatingIPAssociation, self).add_dependencies(deps) super(FloatingIPAssociation, self).add_dependencies(deps)
for resource in six.itervalues(self.stack): for resource in self.stack.values():
if resource.has_interface('OS::Neutron::RouterInterface'): if resource.has_interface('OS::Neutron::RouterInterface'):
def port_on_subnet(resource, subnet): def port_on_subnet(resource, subnet):

View File

@ -13,7 +13,6 @@
# under the License. # under the License.
import collections import collections
import six
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import properties from heat.engine import properties
@ -111,7 +110,7 @@ class L2Gateway(neutron.NeutronResource):
return dict((k, L2Gateway._remove_none_value_props(v)) for k, v return dict((k, L2Gateway._remove_none_value_props(v)) for k, v
in props.items() if v is not None) in props.items() if v is not None)
elif (isinstance(props, collections.Sequence) and elif (isinstance(props, collections.Sequence) and
not isinstance(props, six.string_types)): not isinstance(props, str)):
return list(L2Gateway._remove_none_value_props(l) for l in props return list(L2Gateway._remove_none_value_props(l) for l in props
if l is not None) if l is not None)
return props return props

View File

@ -13,7 +13,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 six
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -437,7 +436,7 @@ class Port(neutron.NeutronResource):
# It is not known which subnet a port might be assigned # It is not known which subnet a port might be assigned
# to so all subnets in a network should be created before # to so all subnets in a network should be created before
# the ports in that network. # the ports in that network.
for res in six.itervalues(self.stack): for res in self.stack.values():
if res.has_interface('OS::Neutron::Subnet'): if res.has_interface('OS::Neutron::Subnet'):
try: try:
dep_network = res.properties.get(subnet.Subnet.NETWORK) dep_network = res.properties.get(subnet.Subnet.NETWORK)

View File

@ -11,8 +11,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -266,7 +264,7 @@ class Router(neutron.NeutronResource):
external_gw = self.properties[self.EXTERNAL_GATEWAY] external_gw = self.properties[self.EXTERNAL_GATEWAY]
if external_gw: if external_gw:
external_gw_net = external_gw.get(self.EXTERNAL_GATEWAY_NETWORK) external_gw_net = external_gw.get(self.EXTERNAL_GATEWAY_NETWORK)
for res in six.itervalues(self.stack): for res in self.stack.values():
if res.has_interface('OS::Neutron::Subnet'): if res.has_interface('OS::Neutron::Subnet'):
try: try:
subnet_net = res.properties.get(subnet.Subnet.NETWORK) subnet_net = res.properties.get(subnet.Subnet.NETWORK)
@ -639,7 +637,7 @@ class RouterGateway(neutron.NeutronResource):
def add_dependencies(self, deps): def add_dependencies(self, deps):
super(RouterGateway, self).add_dependencies(deps) super(RouterGateway, self).add_dependencies(deps)
for resource in six.itervalues(self.stack): for resource in self.stack.values():
# depend on any RouterInterface in this template with the same # depend on any RouterInterface in this template with the same
# router_id as this router_id # router_id as this router_id
if resource.has_interface('OS::Neutron::RouterInterface'): if resource.has_interface('OS::Neutron::RouterInterface'):

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
from oslo_log import log as logging from oslo_log import log as logging
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -125,7 +124,7 @@ class NovaFloatingIp(resource.Resource):
self.POOL_ATTR: floating_ip['floatingip']['floating_network_id'], self.POOL_ATTR: floating_ip['floatingip']['floating_network_id'],
self.IP: floating_ip['floatingip']['floating_ip_address'] self.IP: floating_ip['floatingip']['floating_ip_address']
} }
return six.text_type(attributes[key]) return str(attributes[key])
class NovaFloatingIpAssociation(resource.Resource): class NovaFloatingIpAssociation(resource.Resource):

View File

@ -10,7 +10,6 @@
# 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 six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -194,7 +193,7 @@ class KeyPair(resource.Resource):
def _resolve_attribute(self, key): def _resolve_attribute(self, key):
attr_fn = {self.PRIVATE_KEY_ATTR: self.private_key, attr_fn = {self.PRIVATE_KEY_ATTR: self.private_key,
self.PUBLIC_KEY_ATTR: self.public_key} self.PUBLIC_KEY_ATTR: self.public_key}
return six.text_type(attr_fn[key]) return str(attr_fn[key])
def get_reference_id(self): def get_reference_id(self):
return self.resource_id return self.resource_id

View File

@ -16,7 +16,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
from oslo_utils import uuidutils from oslo_utils import uuidutils
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -936,8 +935,8 @@ class Server(server_base.BaseServer, sh.SchedulerHintsMixin,
server, server_data = resource_data server, server_data = resource_data
result = { result = {
# there's a risk that flavor id will be int type, so cast to str # there's a risk that flavor id will be int type, so cast to str
self.FLAVOR: six.text_type(server_data.get(self.FLAVOR)['id']), self.FLAVOR: str(server_data.get(self.FLAVOR)['id']),
self.IMAGE: six.text_type(server_data.get(self.IMAGE)['id']), self.IMAGE: str(server_data.get(self.IMAGE)['id']),
self.NAME: server_data.get(self.NAME), self.NAME: server_data.get(self.NAME),
self.METADATA: server_data.get(self.METADATA), self.METADATA: server_data.get(self.METADATA),
self.NETWORKS: self._get_live_networks(server, resource_properties) self.NETWORKS: self._get_live_networks(server, resource_properties)
@ -977,7 +976,7 @@ class Server(server_base.BaseServer, sh.SchedulerHintsMixin,
reality_net_ids.get(net_id).pop(idx) reality_net_ids.get(net_id).pop(idx)
break break
for key, value in six.iteritems(reality_nets): for key, value in reality_nets.items():
for address in reality_nets[key]: for address in reality_nets[key]:
new_net = {self.NETWORK_ID: key, new_net = {self.NETWORK_ID: key,
self.NETWORK_FIXED_IP: address['addr']} self.NETWORK_FIXED_IP: address['addr']}
@ -1224,7 +1223,7 @@ class Server(server_base.BaseServer, sh.SchedulerHintsMixin,
return return
if not nets: if not nets:
return return
for res in six.itervalues(self.stack): for res in self.stack.values():
if res.has_interface('OS::Neutron::Subnet'): if res.has_interface('OS::Neutron::Subnet'):
try: try:
subnet_net = res.properties.get(subnet.Subnet.NETWORK) subnet_net = res.properties.get(subnet.Subnet.NETWORK)

View File

@ -12,8 +12,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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -298,7 +296,7 @@ class SaharaJob(signal_responder.SignalResponder, resource.Resource):
def _resolve_attribute(self, name): def _resolve_attribute(self, name):
if name == self.DEFAULT_EXECUTION_URL: if name == self.DEFAULT_EXECUTION_URL:
return six.text_type(self._get_ec2_signed_url()) return str(self._get_ec2_signed_url())
elif name == self.EXECUTIONS: elif name == self.EXECUTIONS:
try: try:
job_execs = self.client().job_executions.find( job_execs = self.client().job_executions.find(

View File

@ -14,7 +14,6 @@
# limitations under the License. # limitations under the License.
import re import re
import six
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import encodeutils from oslo_utils import encodeutils
@ -284,7 +283,7 @@ class SaharaNodeGroupTemplate(resource.Resource):
return props return props
def handle_create(self): def handle_create(self):
props = dict((k, v) for k, v in six.iteritems(self.properties)) props = dict((k, v) for k, v in self.properties.items())
args = self._prepare_properties(props) args = self._prepare_properties(props)
node_group_template = self.client().node_group_templates.create(**args) node_group_template = self.client().node_group_templates.create(**args)
LOG.info("Node Group Template '%s' has been created", LOG.info("Node Group Template '%s' has been created",
@ -335,7 +334,7 @@ class SaharaNodeGroupTemplate(resource.Resource):
self.properties[self.PLUGIN_NAME], self.properties[self.PLUGIN_NAME],
self.properties[self.HADOOP_VERSION]) self.properties[self.HADOOP_VERSION])
allowed_processes = [item for sublist in allowed_processes = [item for sublist in
list(six.itervalues(plugin.node_processes)) list(plugin.node_processes.values())
for item in sublist] for item in sublist]
unsupported_processes = [] unsupported_processes = []
for process in self.properties[self.NODE_PROCESSES]: for process in self.properties[self.NODE_PROCESSES]:
@ -564,7 +563,7 @@ class SaharaClusterTemplate(resource.Resource):
return props return props
def handle_create(self): def handle_create(self):
props = dict((k, v) for k, v in six.iteritems(self.properties)) props = dict((k, v) for k, v in self.properties.items())
args = self._prepare_properties(props) args = self._prepare_properties(props)
cluster_template = self.client().cluster_templates.create(**args) cluster_template = self.client().cluster_templates.create(**args)
LOG.info("Cluster Template '%s' has been created", LOG.info("Cluster Template '%s' has been created",

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 heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
from heat.engine import attributes from heat.engine import attributes
@ -322,7 +320,7 @@ class Cluster(res_base.BaseSenlinResource):
actions.append(action) actions.append(action)
# Update cluster # Update cluster
if any(p in prop_diff for p in UPDATE_PROPS): if any(p in prop_diff for p in UPDATE_PROPS):
params = dict((k, v) for k, v in six.iteritems(prop_diff) params = dict((k, v) for k, v in prop_diff.items()
if k in UPDATE_PROPS) if k in UPDATE_PROPS)
params['cluster'] = cluster_obj params['cluster'] = cluster_obj
if self.PROFILE in params: if self.PROFILE in params:
@ -336,7 +334,7 @@ class Cluster(res_base.BaseSenlinResource):
actions.append(action) actions.append(action)
# Resize Cluster # Resize Cluster
if any(p in prop_diff for p in RESIZE_PROPS): if any(p in prop_diff for p in RESIZE_PROPS):
params = dict((k, v) for k, v in six.iteritems(prop_diff) params = dict((k, v) for k, v in prop_diff.items()
if k in RESIZE_PROPS) if k in RESIZE_PROPS)
if self.DESIRED_CAPACITY in params: if self.DESIRED_CAPACITY in params:
params['adjustment_type'] = 'EXACT_CAPACITY' params['adjustment_type'] = 'EXACT_CAPACITY'

View File

@ -12,8 +12,7 @@
# under the License. # under the License.
from oslo_log import log as logging from oslo_log import log as logging
import six from urllib.parse import urlparse
from six.moves.urllib import parse as urlparse
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -224,10 +223,10 @@ class SwiftContainer(resource.Resource):
self.client().get_container(self.resource_id) self.client().get_container(self.resource_id)
def get_reference_id(self): def get_reference_id(self):
return six.text_type(self.resource_id) return str(self.resource_id)
def _resolve_attribute(self, key): def _resolve_attribute(self, key):
parsed = list(urlparse.urlparse(self.client().url)) parsed = list(urlparse(self.client().url))
if key == self.DOMAIN_NAME: if key == self.DOMAIN_NAME:
return parsed[1].split(':')[0] return parsed[1].split(':')[0]
elif key == self.WEBSITE_URL: elif key == self.WEBSITE_URL:

View File

@ -12,7 +12,6 @@
# under the License. # under the License.
from oslo_log import log as logging from oslo_log import log as logging
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -501,9 +500,9 @@ class Instance(resource.Resource):
# we retrieve it and try to update it so check again # we retrieve it and try to update it so check again
if self.client_plugin().is_over_limit(exc): if self.client_plugin().is_over_limit(exc):
LOG.debug("API rate limit: %(ex)s. Retrying.", LOG.debug("API rate limit: %(ex)s. Retrying.",
{'ex': six.text_type(exc)}) {'ex': str(exc)})
return False return False
if "No change was requested" in six.text_type(exc): if "No change was requested" in str(exc):
LOG.warning("Unexpected instance state change " LOG.warning("Unexpected instance state change "
"during update. Retrying.") "during update. Retrying.")
return False return False
@ -518,8 +517,8 @@ class Instance(resource.Resource):
def _update_flavor(self, instance, new_flavor): def _update_flavor(self, instance, new_flavor):
if new_flavor: if new_flavor:
current_flav = six.text_type(instance.flavor['id']) current_flav = str(instance.flavor['id'])
new_flav = six.text_type(new_flavor) new_flav = str(new_flavor)
if new_flav != current_flav: if new_flav != current_flav:
dmsg = "Resizing instance flavor from %(old)s to %(new)s" dmsg = "Resizing instance flavor from %(old)s to %(new)s"
LOG.debug(dmsg % {"old": current_flav, "new": new_flav}) LOG.debug(dmsg % {"old": current_flav, "new": new_flav})

View File

@ -20,7 +20,8 @@ from heat.engine import properties
from heat.engine import resource from heat.engine import resource
from heat.engine import support from heat.engine import support
from six.moves.urllib import parse as urlparse from urllib.parse import quote
from urllib.parse import urlencode
class ZaqarQueue(resource.Resource): class ZaqarQueue(resource.Resource):
@ -120,7 +121,7 @@ class ZaqarQueue(resource.Resource):
queue_name = self.physical_resource_name() queue_name = self.physical_resource_name()
return '%s/v%s/queues/%s' % (client.api_url.rstrip('/'), return '%s/v%s/queues/%s' % (client.api_url.rstrip('/'),
client.api_version, client.api_version,
urlparse.quote(queue_name)) quote(queue_name))
def _resolve_attribute(self, name): def _resolve_attribute(self, name):
if name == self.QUEUE_ID: if name == self.QUEUE_ID:
@ -243,7 +244,7 @@ class ZaqarSignedQueueURL(resource.Resource):
'project_id': data[self.PROJECT], 'project_id': data[self.PROJECT],
'queue_name': self.properties[self.QUEUE], 'queue_name': self.properties[self.QUEUE],
} }
return urlparse.urlencode(query) return urlencode(query)
def handle_delete(self): def handle_delete(self):
# We can't delete a signed URL # We can't delete a signed URL

View File

@ -10,12 +10,15 @@
# 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.
from urllib.parse import unquote
from urllib.parse import urlencode
from urllib.parse import urljoin
from urllib.parse import urlparse
from keystoneclient.contrib.ec2 import utils as ec2_utils from keystoneclient.contrib.ec2 import utils as ec2_utils
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 six.moves.urllib import parse as urlparse
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -152,7 +155,7 @@ class SignalResponder(stack_user.StackUser):
endpoint = heat_client_plugin.get_heat_cfn_url() endpoint = heat_client_plugin.get_heat_cfn_url()
signal_url = ''.join([endpoint, signal_type]) signal_url = ''.join([endpoint, signal_type])
host_url = urlparse.urlparse(signal_url) host_url = urlparse(signal_url)
path = self.identifier().arn_url_path() path = self.identifier().arn_url_path()
@ -160,7 +163,7 @@ class SignalResponder(stack_user.StackUser):
# processing in the CFN API (ec2token.py) has an unquoted path, so we # processing in the CFN API (ec2token.py) has an unquoted path, so we
# need to calculate the signature with the path component unquoted, but # need to calculate the signature with the path component unquoted, but
# ensure the actual URL contains the quoted version... # ensure the actual URL contains the quoted version...
unquoted_path = urlparse.unquote(host_url.path + path) unquoted_path = unquote(host_url.path + path)
request = {'host': host_url.netloc.lower(), request = {'host': host_url.netloc.lower(),
'verb': SIGNAL_VERB[signal_type], 'verb': SIGNAL_VERB[signal_type],
'path': unquoted_path, 'path': unquoted_path,
@ -174,7 +177,7 @@ class SignalResponder(stack_user.StackUser):
signer = ec2_utils.Ec2Signer(secret_key) signer = ec2_utils.Ec2Signer(secret_key)
request['params']['Signature'] = signer.generate(request) request['params']['Signature'] = signer.generate(request)
qs = urlparse.urlencode(request['params']) qs = urlencode(request['params'])
url = "%s%s?%s" % (signal_url.lower(), url = "%s%s?%s" % (signal_url.lower(),
path, qs) path, qs)
@ -206,7 +209,7 @@ class SignalResponder(stack_user.StackUser):
if project_id is not None: if project_id is not None:
path = project_id + path[path.find('/'):] path = project_id + path[path.find('/'):]
url = urlparse.urljoin(url, '%s/signal' % path) url = urljoin(url, '%s/signal' % path)
self.data_set('heat_signal_url', url) self.data_set('heat_signal_url', url)
return url return url

View File

@ -18,7 +18,6 @@ from oslo_config import cfg
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import excutils from oslo_utils import excutils
from oslo_utils import reflection from oslo_utils import reflection
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -397,7 +396,7 @@ class StackResource(resource.Resource):
if not class_name.endswith('_Remote'): if not class_name.endswith('_Remote'):
return False return False
full_message = six.text_type(ex) full_message = str(ex)
if full_message.find('\n') > -1: if full_message.find('\n') > -1:
message, msg_trace = full_message.split('\n', 1) message, msg_trace = full_message.split('\n', 1)
else: else:

View File

@ -14,7 +14,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
from requests import exceptions from requests import exceptions
import six
from heat.common import exception from heat.common import exception
from heat.common import grouputils from heat.common import grouputils
@ -98,7 +97,7 @@ class TemplateResource(stack_resource.StackResource):
try: try:
return urlfetch.get(template_name, allowed_schemes=allowed_schemes) return urlfetch.get(template_name, allowed_schemes=allowed_schemes)
except (IOError, exceptions.RequestException) as r_exc: except (IOError, exceptions.RequestException) as r_exc:
args = {'name': template_name, 'exc': six.text_type(r_exc)} args = {'name': template_name, 'exc': str(r_exc)}
msg = _('Could not fetch remote template ' msg = _('Could not fetch remote template '
'"%(name)s": %(exc)s') % args '"%(name)s": %(exc)s') % args
raise exception.NotFound(msg_fmt=msg) raise exception.NotFound(msg_fmt=msg)
@ -290,7 +289,7 @@ class TemplateResource(stack_resource.StackResource):
def validate_template(self): def validate_template(self):
if self.validation_exception is not None: if self.validation_exception is not None:
msg = six.text_type(self.validation_exception) msg = str(self.validation_exception)
raise exception.StackValidationFailed(message=msg) raise exception.StackValidationFailed(message=msg)
return super(TemplateResource, self).validate_template() return super(TemplateResource, self).validate_template()
@ -317,7 +316,7 @@ class TemplateResource(stack_resource.StackResource):
def get_reference_id(self): def get_reference_id(self):
if self.resource_id is None: if self.resource_id is None:
return six.text_type(self.name) return str(self.name)
if STACK_ID_OUTPUT in self.attributes.cached_attrs: if STACK_ID_OUTPUT in self.attributes.cached_attrs:
return self.attributes.cached_attrs[STACK_ID_OUTPUT] return self.attributes.cached_attrs[STACK_ID_OUTPUT]

View File

@ -14,7 +14,6 @@
import collections import collections
from oslo_log import log as logging from oslo_log import log as logging
import six
from heat.common import exception from heat.common import exception
from heat.common.i18n import _ from heat.common.i18n import _
@ -70,7 +69,7 @@ class BaseWaitConditionHandle(signal_responder.SignalResponder):
raise ValueError(_("Metadata format invalid")) raise ValueError(_("Metadata format invalid"))
new_entry = signal_data.copy() new_entry = signal_data.copy()
unique_id = six.text_type(new_entry.pop(self.UNIQUE_ID)) unique_id = str(new_entry.pop(self.UNIQUE_ID))
new_rsrc_metadata = latest_rsrc_metadata.copy() new_rsrc_metadata = latest_rsrc_metadata.copy()
if unique_id in new_rsrc_metadata: if unique_id in new_rsrc_metadata:
@ -92,12 +91,12 @@ class BaseWaitConditionHandle(signal_responder.SignalResponder):
def get_status(self): def get_status(self):
"""Return a list of the Status values for the handle signals.""" """Return a list of the Status values for the handle signals."""
return [v[self.STATUS] return [v[self.STATUS]
for v in six.itervalues(self.metadata_get(refresh=True))] for v in self.metadata_get(refresh=True).values()]
def get_status_reason(self, status): def get_status_reason(self, status):
"""Return a list of reasons associated with a particular status.""" """Return a list of reasons associated with a particular status."""
return [v[self.REASON] return [v[self.REASON]
for v in six.itervalues(self.metadata_get(refresh=True)) for v in self.metadata_get(refresh=True).values()
if v[self.STATUS] == status] if v[self.STATUS] == status]

View File

@ -11,6 +11,7 @@
# 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 functools
import sys import sys
import types import types
@ -18,7 +19,6 @@ import eventlet
from oslo_log import log as logging from oslo_log import log as logging
from oslo_utils import encodeutils from oslo_utils import encodeutils
from oslo_utils import excutils from oslo_utils import excutils
import six
from heat.common.i18n import _ from heat.common.i18n import _
from heat.common.i18n import repr_wrapper from heat.common.i18n import repr_wrapper
@ -40,9 +40,9 @@ def task_description(task):
if name is not None and isinstance(task, (types.MethodType, if name is not None and isinstance(task, (types.MethodType,
types.FunctionType)): types.FunctionType)):
if getattr(task, '__self__', None) is not None: if getattr(task, '__self__', None) is not None:
return '%s from %s' % (six.text_type(name), task.__self__) return '%s from %s' % (str(name), task.__self__)
else: else:
return six.text_type(name) return str(name)
return encodeutils.safe_decode(repr(task)) return encodeutils.safe_decode(repr(task))
@ -57,7 +57,7 @@ class Timeout(BaseException):
def __init__(self, task_runner, timeout): def __init__(self, task_runner, timeout):
"""Initialise with the TaskRunner and a timeout period in seconds.""" """Initialise with the TaskRunner and a timeout period in seconds."""
message = _('%s Timed out') % six.text_type(task_runner) message = _('%s Timed out') % str(task_runner)
super(Timeout, self).__init__(message) super(Timeout, self).__init__(message)
self._duration = timeutils.Duration(timeout) self._duration = timeutils.Duration(timeout)
@ -91,7 +91,6 @@ class TimedCancel(Timeout):
return False return False
@six.python_2_unicode_compatible
class ExceptionGroup(Exception): class ExceptionGroup(Exception):
"""Container for multiple exceptions. """Container for multiple exceptions.
@ -111,7 +110,6 @@ class ExceptionGroup(Exception):
return str([str(ex) for ex in self.exceptions]) return str([str(ex) for ex in self.exceptions])
@six.python_2_unicode_compatible
class TaskRunner(object): class TaskRunner(object):
"""Wrapper for a resumable task (co-routine).""" """Wrapper for a resumable task (co-routine)."""
@ -142,12 +140,12 @@ class TaskRunner(object):
def __str__(self): def __str__(self):
"""Return a human-readable string representation of the task.""" """Return a human-readable string representation of the task."""
text = 'Task %s' % self.name text = 'Task %s' % self.name
return six.text_type(text) return str(text)
def _sleep(self, wait_time): def _sleep(self, wait_time):
"""Sleep for the specified number of seconds.""" """Sleep for the specified number of seconds."""
if ENABLE_SLEEP and wait_time is not None: if ENABLE_SLEEP and wait_time is not None:
LOG.debug('%s sleeping', six.text_type(self)) LOG.debug('%s sleeping', str(self))
eventlet.sleep(wait_time) eventlet.sleep(wait_time)
def __call__(self, wait_time=1, timeout=None, progress_callback=None): def __call__(self, wait_time=1, timeout=None, progress_callback=None):
@ -174,7 +172,7 @@ class TaskRunner(object):
assert self._runner is None, "Task already started" assert self._runner is None, "Task already started"
assert not self._done, "Task already cancelled" assert not self._done, "Task already cancelled"
LOG.debug('%s starting', six.text_type(self)) LOG.debug('%s starting', str(self))
if timeout is not None: if timeout is not None:
self._timeout = Timeout(self, timeout) self._timeout = Timeout(self, timeout)
@ -186,7 +184,7 @@ class TaskRunner(object):
else: else:
self._runner = False self._runner = False
self._done = True self._done = True
LOG.debug('%s done (not resumable)', six.text_type(self)) LOG.debug('%s done (not resumable)', str(self))
def step(self): def step(self):
"""Run another step of the task. """Run another step of the task.
@ -206,15 +204,15 @@ class TaskRunner(object):
self._timeout.trigger(self._runner) self._timeout.trigger(self._runner)
else: else:
LOG.debug('%s running', six.text_type(self)) LOG.debug('%s running', str(self))
try: try:
poll_period = next(self._runner) poll_period = next(self._runner)
except StopIteration: except StopIteration:
self._done = True self._done = True
LOG.debug('%s complete', six.text_type(self)) LOG.debug('%s complete', str(self))
else: else:
if isinstance(poll_period, six.integer_types): if isinstance(poll_period, int):
self._poll_period = max(poll_period, 1) self._poll_period = max(poll_period, 1)
else: else:
self._poll_period = 1 self._poll_period = 1
@ -270,7 +268,7 @@ class TaskRunner(object):
return return
if not self.started() or grace_period is None: if not self.started() or grace_period is None:
LOG.debug('%s cancelled', six.text_type(self)) LOG.debug('%s cancelled', str(self))
self._done = True self._done = True
if self.started(): if self.started():
self._runner.close() self._runner.close()
@ -312,7 +310,7 @@ def wrappertask(task):
self.cleanup() self.cleanup()
""" """
@six.wraps(task) @functools.wraps(task)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
parent = task(*args, **kwargs) parent = task(*args, **kwargs)
@ -401,7 +399,7 @@ class DependencyTaskGroup(object):
if name is None: if name is None:
name = '(%s) %s' % (getattr(task, '__name__', name = '(%s) %s' % (getattr(task, '__name__',
task_description(task)), task_description(task)),
six.text_type(dependencies)) str(dependencies))
self.name = name self.name = name
def __repr__(self): def __repr__(self):
@ -415,7 +413,7 @@ class DependencyTaskGroup(object):
thrown_exceptions = [] thrown_exceptions = []
try: try:
while any(six.itervalues(self._runners)): while any(list(self._runners.values())):
try: try:
for k, r in self._ready(): for k, r in self._ready():
r.start() r.start()
@ -452,9 +450,9 @@ class DependencyTaskGroup(object):
raise ExceptionGroup(v for t, v, tb in raised_exceptions) raise ExceptionGroup(v for t, v, tb in raised_exceptions)
else: else:
if thrown_exceptions: if thrown_exceptions:
six.reraise(*thrown_exceptions[-1]) raise thrown_exceptions[-1][1]
else: else:
six.reraise(*raised_exceptions[0]) raise raised_exceptions[0][1]
finally: finally:
del raised_exceptions del raised_exceptions
del thrown_exceptions del thrown_exceptions
@ -466,7 +464,7 @@ class DependencyTaskGroup(object):
def get_grace_period(key): def get_grace_period(key):
return grace_period return grace_period
for k, r in six.iteritems(self._runners): for k, r in self._runners.items():
if not r.started() or r.done(): if not r.started() or r.done():
gp = None gp = None
else: else:
@ -474,13 +472,13 @@ class DependencyTaskGroup(object):
try: try:
r.cancel(grace_period=gp) r.cancel(grace_period=gp)
except Exception as ex: except Exception as ex:
LOG.debug('Exception cancelling task: %s', six.text_type(ex)) LOG.debug('Exception cancelling task: %s', str(ex))
def _cancel_recursively(self, key, runner): def _cancel_recursively(self, key, runner):
try: try:
runner.cancel() runner.cancel()
except Exception as ex: except Exception as ex:
LOG.debug('Exception cancelling task: %s', six.text_type(ex)) LOG.debug('Exception cancelling task: %s', str(ex))
node = self._graph[key] node = self._graph[key]
for dependent_node in node.required_by(): for dependent_node in node.required_by():
node_runner = self._runners[dependent_node] node_runner = self._runners[dependent_node]
@ -510,4 +508,4 @@ class DependencyTaskGroup(object):
def running(k_r): def running(k_r):
return k_r[0] in self._graph and k_r[1].started() return k_r[0] in self._graph and k_r[1].started()
return six.moves.filter(running, six.iteritems(self._runners)) return filter(running, iter(self._runners.items()))

View File

@ -11,14 +11,14 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from itertools import filterfalse
import uuid import uuid
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 oslo_utils import timeutils from oslo_utils import timeutils
import requests import requests
import six from urllib.parse import urlparse
from six.moves.urllib import parse as urlparse
from heat.common import crypt from heat.common import crypt
from heat.common import exception from heat.common import exception
@ -88,8 +88,7 @@ class SoftwareConfigService(object):
cnxt, server_id) cnxt, server_id)
# filter out the sds with None config # filter out the sds with None config
flt_sd = six.moves.filterfalse(lambda sd: sd.config is None, flt_sd = filterfalse(lambda sd: sd.config is None, all_sd)
all_sd)
# sort the configs by config name, to give the list of metadata a # sort the configs by config name, to give the list of metadata a
# deterministic and controllable order. # deterministic and controllable order.
flt_sd_s = sorted(flt_sd, key=lambda sd: sd.config.name) flt_sd_s = sorted(flt_sd, key=lambda sd: sd.config.name)
@ -153,7 +152,7 @@ class SoftwareConfigService(object):
raise exception.ConcurrentTransaction(action=action) raise exception.ConcurrentTransaction(action=action)
def _refresh_swift_software_deployment(self, cnxt, sd, deploy_signal_id): def _refresh_swift_software_deployment(self, cnxt, sd, deploy_signal_id):
container, object_name = urlparse.urlparse( container, object_name = urlparse(
deploy_signal_id).path.split('/')[-2:] deploy_signal_id).path.split('/')[-2:]
swift_plugin = cnxt.clients.client_plugin('swift') swift_plugin = cnxt.clients.client_plugin('swift')
swift = swift_plugin.client() swift = swift_plugin.client()
@ -281,7 +280,7 @@ class SoftwareConfigService(object):
'stack_user_project_id': stack_user_project_id, 'stack_user_project_id': stack_user_project_id,
'action': action, 'action': action,
'status': status, 'status': status,
'status_reason': six.text_type(status_reason)}) 'status_reason': str(status_reason)})
self._push_metadata_software_deployments( self._push_metadata_software_deployments(
cnxt, server_id, stack_user_project_id) cnxt, server_id, stack_user_project_id)
return api.format_software_deployment(sd) return api.format_software_deployment(sd)
@ -332,7 +331,7 @@ class SoftwareConfigService(object):
if status == rpc_api.SOFTWARE_DEPLOYMENT_FAILED: if status == rpc_api.SOFTWARE_DEPLOYMENT_FAILED:
# build a status reason out of all of the values of outputs # build a status reason out of all of the values of outputs
# flagged as error_output # flagged as error_output
status_reasons = [' : '.join((k, six.text_type(status_reasons[k]))) status_reasons = [' : '.join((k, str(status_reasons[k])))
for k in status_reasons] for k in status_reasons]
status_reason = ', '.join(status_reasons) status_reason = ', '.join(status_reasons)
else: else:
@ -362,7 +361,7 @@ class SoftwareConfigService(object):
if status: if status:
update_data['status'] = status update_data['status'] = status
if status_reason: if status_reason:
update_data['status_reason'] = six.text_type(status_reason) update_data['status_reason'] = str(status_reason)
if updated_at: if updated_at:
update_data['updated_at'] = timeutils.normalize_time( update_data['updated_at'] = timeutils.normalize_time(
timeutils.parse_isotime(updated_at)) timeutils.parse_isotime(updated_at))

View File

@ -17,7 +17,6 @@ import copy
import functools import functools
import hashlib import hashlib
import six
from stevedore import extension from stevedore import extension
from heat.common import exception from heat.common import exception
@ -37,8 +36,8 @@ _template_classes = None
def get_version(template_data, available_versions): def get_version(template_data, available_versions):
version_keys = set(key for key, version in available_versions) version_keys = set(key for key, version in available_versions)
candidate_keys = set(k for k, v in six.iteritems(template_data) if candidate_keys = set(k for k, v in template_data.items() if
isinstance(v, six.string_types)) isinstance(v, str))
keys_present = version_keys & candidate_keys keys_present = version_keys & candidate_keys
@ -61,7 +60,7 @@ def _get_template_extension_manager():
def raise_extension_exception(extmanager, ep, err): def raise_extension_exception(extmanager, ep, err):
raise TemplatePluginNotRegistered(name=ep.name, error=six.text_type(err)) raise TemplatePluginNotRegistered(name=ep.name, error=str(err))
class TemplatePluginNotRegistered(exception.HeatException): class TemplatePluginNotRegistered(exception.HeatException):
@ -296,7 +295,7 @@ class Template(collections.Mapping):
sections (e.g. parameters are check by parameters schema class). sections (e.g. parameters are check by parameters schema class).
""" """
t_digest = hashlib.sha256( t_digest = hashlib.sha256(
six.text_type(self.t).encode('utf-8')).hexdigest() str(self.t).encode('utf-8')).hexdigest()
# TODO(kanagaraj-manickam) currently t_digest is stored in self. which # TODO(kanagaraj-manickam) currently t_digest is stored in self. which
# is used to check whether already template is validated or not. # is used to check whether already template is validated or not.
@ -315,7 +314,7 @@ class Template(collections.Mapping):
raise exception.InvalidTemplateSection(section=k) raise exception.InvalidTemplateSection(section=k)
# check resources # check resources
for res in six.itervalues(self[self.RESOURCES]): for res in self[self.RESOURCES].values():
try: try:
if not res or not res.get('Type'): if not res or not res.get('Type'):
message = _('Each Resource must contain ' message = _('Each Resource must contain '
@ -358,10 +357,10 @@ def parse(functions, stack, snippet, path='', template=None):
if isinstance(snippet, collections.Mapping): if isinstance(snippet, collections.Mapping):
def mkpath(key): def mkpath(key):
return '.'.join([path, six.text_type(key)]) return '.'.join([path, str(key)])
if len(snippet) == 1: if len(snippet) == 1:
fn_name, args = next(six.iteritems(snippet)) fn_name, args = next(iter(snippet.items()))
Func = functions.get(fn_name) Func = functions.get(fn_name)
if Func is not None: if Func is not None:
try: try:
@ -376,11 +375,11 @@ def parse(functions, stack, snippet, path='', template=None):
except (ValueError, TypeError, KeyError) as e: except (ValueError, TypeError, KeyError) as e:
raise exception.StackValidationFailed( raise exception.StackValidationFailed(
path=path, path=path,
message=six.text_type(e)) message=str(e))
return dict((k, recurse(v, mkpath(k))) return dict((k, recurse(v, mkpath(k)))
for k, v in six.iteritems(snippet)) for k, v in snippet.items())
elif (not isinstance(snippet, six.string_types) and elif (not isinstance(snippet, str) and
isinstance(snippet, collections.Iterable)): isinstance(snippet, collections.Iterable)):
def mkpath(idx): def mkpath(idx):

View File

@ -29,13 +29,14 @@ commands =
# B110: Try, Except, Pass detected. # B110: Try, Except, Pass detected.
# B310: Audit url open for permitted schemes # B310: Audit url open for permitted schemes
# B311: Standard pseudo-random generators are not suitable for security/cryptographic purposes # B311: Standard pseudo-random generators are not suitable for security/cryptographic purposes
# B322: The input method is safe in Python 3.
# B404: Import of subprocess module # B404: Import of subprocess module
# B410: Import of lxml module # B410: Import of lxml module
# B504: Test for SSL use with no version specified # B504: Test for SSL use with no version specified
# B506: Test for use of yaml load # B506: Test for use of yaml load
# B603: Test for use of subprocess with shell equals true # B603: Test for use of subprocess with shell equals true
# B607: Test for starting a process with a partial path # B607: Test for starting a process with a partial path
bandit -r heat -x tests --skip B101,B104,B107,B110,B310,B311,B404,B410,B504,B506,B603,B607 bandit -r heat -x tests --skip B101,B104,B107,B110,B310,B311,B322,B404,B410,B504,B506,B603,B607
doc8 {posargs} doc8 {posargs}
[testenv:venv] [testenv:venv]