Fix [H405] pep rule in heat/engine

Fix [H405] rule in heat/engine python
files.

Implements bp docstring-improvements

Change-Id: Iaa1541eb03c4db837ef3a0e4eb22393ba32e270f
changes/86/224786/5
Peter Razumovsky 7 years ago
parent a2ec480f3c
commit 2da170c435
  1. 25
      heat/engine/api.py
  2. 32
      heat/engine/attributes.py
  3. 37
      heat/engine/constraints.py
  4. 111
      heat/engine/dependencies.py
  5. 26
      heat/engine/environment.py
  6. 13
      heat/engine/event.py
  7. 28
      heat/engine/function.py
  8. 21
      heat/engine/lifecycle_plugin.py
  9. 9
      heat/engine/parameter_groups.py
  10. 83
      heat/engine/parameters.py
  11. 24
      heat/engine/plugin_manager.py
  12. 40
      heat/engine/properties.py
  13. 245
      heat/engine/resource.py
  14. 78
      heat/engine/rsrc_defn.py
  15. 70
      heat/engine/scheduler.py
  16. 183
      heat/engine/service.py
  17. 8
      heat/engine/service_stack_watch.py
  18. 244
      heat/engine/stack.py
  19. 23
      heat/engine/stack_lock.py
  20. 14
      heat/engine/sync_point.py
  21. 37
      heat/engine/template.py
  22. 15
      heat/engine/timestamp.py
  23. 14
      heat/engine/update.py
  24. 36
      heat/engine/watchrule.py
  25. 25
      heat/engine/worker.py

@ -28,11 +28,12 @@ LOG = logging.getLogger(__name__)
def extract_args(params):
'''
"""Extract arguments passed as parameters and return them as a dictionary.
Extract any arguments passed as parameters through the API and return them
as a dictionary. This allows us to filter the passed args and do type
conversion where appropriate
'''
"""
kwargs = {}
timeout_mins = params.get(rpc_api.PARAM_TIMEOUT)
if timeout_mins not in ('0', 0, None):
@ -170,10 +171,11 @@ def translate_filters(params):
def format_stack_outputs(stack, outputs):
'''
"""Return a representation of the given output template.
Return a representation of the given output template for the given stack
that matches the API output expectations.
'''
"""
def format_stack_output(k):
output = {
rpc_api.OUTPUT_DESCRIPTION: outputs[k].get('Description',
@ -189,10 +191,11 @@ def format_stack_outputs(stack, outputs):
def format_stack(stack, preview=False):
'''
"""Return a representation of the given stack.
Return a representation of the given stack that matches the API output
expectations.
'''
"""
updated_time = stack.updated_time and stack.updated_time.isoformat()
created_time = stack.created_time or timeutils.utcnow()
info = {
@ -222,7 +225,7 @@ def format_stack(stack, preview=False):
info.update(update_info)
# allow users to view the outputs of stacks
if (stack.action != stack.DELETE and stack.status != stack.IN_PROGRESS):
if stack.action != stack.DELETE and stack.status != stack.IN_PROGRESS:
info[rpc_api.STACK_OUTPUTS] = format_stack_outputs(stack,
stack.outputs)
@ -273,10 +276,11 @@ def format_resource_properties(resource):
def format_stack_resource(resource, detail=True, with_props=False,
with_attr=None):
'''
"""Return a representation of the given resource.
Return a representation of the given resource that matches the API output
expectations.
'''
"""
created_time = resource.created_time and resource.created_time.isoformat()
last_updated_time = (resource.updated_time and
resource.updated_time.isoformat()) or created_time
@ -432,8 +436,7 @@ def format_watch_data(wd):
def format_validate_parameter(param):
"""
Format a template parameter for validate template API call
"""Format a template parameter for validate template API call.
Formats a template parameter and its schema information from the engine's
internal representation (i.e. a Parameter object and its associated

@ -27,10 +27,9 @@ LOG = logging.getLogger(__name__)
class Schema(constr.Schema):
"""
Simple schema class for attributes.
"""Simple schema class for attributes.
Schema objects are serialisable to dictionaries following a superset of
Schema objects are serializable to dictionaries following a superset of
the HOT input Parameter schema using dict().
"""
@ -76,29 +75,22 @@ class Schema(constr.Schema):
@classmethod
def from_attribute(cls, schema_dict):
"""
Return a Property Schema corresponding to a Attribute Schema.
"""
"""Return a Property Schema corresponding to a Attribute Schema."""
msg = 'Old attribute schema is not supported'
assert isinstance(schema_dict, cls), msg
return schema_dict
def schemata(schema):
"""
Return dictionary of Schema objects for given dictionary of schemata.
"""
"""Return dictionary of Schema objects for given dictionary of schemata."""
return dict((n, Schema.from_attribute(s)) for n, s in schema.items())
class Attribute(object):
"""
An Attribute schema.
"""
"""An Attribute schema."""
def __init__(self, attr_name, schema):
"""
Initialise with a name and description.
"""Initialise with a name and schema.
:param attr_name: the name of the attribute
:param schema: attribute schema
@ -110,9 +102,7 @@ class Attribute(object):
return self.schema.support_status
def as_output(self, resource_name, template_type='cfn'):
"""
Return an Output schema entry for a provider template with the given
resource name.
"""Output entry for a provider template with the given resource name.
:param resource_name: the logical name of the provider resource
:param template_type: the template type to generate
@ -151,7 +141,8 @@ class Attributes(collections.Mapping):
@staticmethod
def as_outputs(resource_name, resource_class, template_type='cfn'):
"""
"""Dict of Output entries for a provider template with resource name.
:param resource_name: logical name of the resource
:param resource_class: resource implementation class
:returns: The attributes of the specified resource_class as a template
@ -266,13 +257,12 @@ class DynamicSchemeAttributes(Attributes):
def select_from_attribute(attribute_value, path):
'''
Select an element from an attribute value.
"""Select an element from an attribute value.
:param attribute_value: the attribute value.
:param path: a list of path components to select from the attribute.
:returns: the selected attribute component value.
'''
"""
def get_path_component(collection, key):
if not isinstance(collection, (collections.Mapping,
collections.Sequence)):

@ -34,10 +34,9 @@ MEMOIZE = core.get_memoization_decorator(conf=cfg.CONF,
class Schema(collections.Mapping):
"""
Schema base class for validating properties or parameters.
"""Schema base class for validating properties or parameters.
Schema objects are serialisable to dictionaries following a superset of
Schema objects are serializable to dictionaries following a superset of
the HOT input Parameter schema using dict().
Serialises to JSON in the form::
@ -245,8 +244,7 @@ class Schema(collections.Mapping):
class AnyIndexDict(collections.Mapping):
"""
A Mapping that returns the same value for any integer index.
"""A Mapping that returns the same value for any integer index.
Used for storing the schema for a list. When converted to a dictionary,
it contains a single item with the key '*'.
@ -271,10 +269,9 @@ class AnyIndexDict(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.
Constraints are serialisable to dictionaries following the HOT input
Constraints are serializable to dictionaries following the HOT input
Parameter constraints schema using dict().
"""
@ -326,10 +323,9 @@ class Constraint(collections.Mapping):
class Range(Constraint):
"""
Constrain values within a range.
"""Constrain values within a range.
Serialises to JSON as::
Serializes to JSON as::
{
'range': {'min': <min>, 'max': <max>},
@ -394,10 +390,9 @@ class Range(Constraint):
class Length(Range):
"""
Constrain the length of values within a range.
"""Constrain the length of values within a range.
Serialises to JSON as::
Serializes to JSON as::
{
'length': {'min': <min>, 'max': <max>},
@ -439,10 +434,9 @@ class Length(Range):
class AllowedValues(Constraint):
"""
Constrain values to a predefined set.
"""Constrain values to a predefined set.
Serialises to JSON as::
Serializes to JSON as::
{
'allowed_values': [<allowed1>, <allowed2>, ...],
@ -486,10 +480,9 @@ class AllowedValues(Constraint):
class AllowedPattern(Constraint):
"""
Constrain values to a predefined regular expression pattern.
"""Constrain values to a predefined regular expression pattern.
Serialises to JSON as::
Serializes to JSON as::
{
'allowed_pattern': <pattern>,
@ -522,9 +515,7 @@ class AllowedPattern(Constraint):
class CustomConstraint(Constraint):
"""
A constraint delegating validation to an external class.
"""
"""A constraint delegating validation to an external class."""
valid_types = (Schema.STRING_TYPE, Schema.INTEGER_TYPE, Schema.NUMBER_TYPE,
Schema.BOOLEAN_TYPE, Schema.LIST_TYPE)

@ -26,105 +26,101 @@ class CircularDependencyException(exception.HeatException):
@six.python_2_unicode_compatible
class Node(object):
'''A node in a dependency graph.'''
"""A node in a dependency graph."""
def __init__(self, requires=None, required_by=None):
'''
"""Initialisation of the node.
Initialise the node, optionally with a set of keys this node
requires and/or a set of keys that this node is required by.
'''
"""
self.require = requires and requires.copy() or set()
self.satisfy = required_by and required_by.copy() or set()
def copy(self):
'''Return a copy of the node.'''
"""Return a copy of the node."""
return Node(self.require, self.satisfy)
def reverse_copy(self):
'''Return a copy of the node with the edge directions reversed.'''
"""Return a copy of the node with the edge directions reversed."""
return Node(self.satisfy, self.require)
def required_by(self, source=None):
'''
List the keys that require this node, and optionally add a
new one.
'''
"""List the keys that require this node, and optionally add new one."""
if source is not None:
self.satisfy.add(source)
return iter(self.satisfy)
def requires(self, target=None):
'''
Add a key that this node requires, and optionally add a
new one.
'''
"""Add a key that this node requires, and optionally add a new one."""
if target is not None:
self.require.add(target)
return iter(self.require)
def __isub__(self, target):
'''Remove a key that this node requires.'''
"""Remove a key that this node requires."""
self.require.remove(target)
return self
def __nonzero__(self):
'''Return True if this node is not a leaf (it requires other nodes).'''
"""Return True if this node is not a leaf (it requires other nodes)."""
return bool(self.require)
def __bool__(self):
'''Return True if this node is not a leaf (it requires other nodes).'''
"""Return True if this node is not a leaf (it requires other nodes)."""
return self.__nonzero__()
def stem(self):
'''Return True if this node is a stem (required by nothing).'''
"""Return True if this node is a stem (required by nothing)."""
return not bool(self.satisfy)
def disjoint(self):
'''Return True if this node is both a leaf and a stem.'''
"""Return True if this node is both a leaf and a stem."""
return (not self) and self.stem()
def __len__(self):
'''Count the number of keys required by this node.'''
"""Count the number of keys required by this node."""
return len(self.require)
def __iter__(self):
'''Iterate over the keys required by this node.'''
"""Iterate over the keys required by this node."""
return iter(self.require)
def __str__(self):
'''Return a human-readable string representation of the node.'''
"""Return a human-readable string representation of the node."""
text = '{%s}' % ', '.join(str(n) for n in self)
return six.text_type(text)
def __repr__(self):
'''Return a string representation of the node.'''
"""Return a string representation of the node."""
return repr(self.require)
@six.python_2_unicode_compatible
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."""
def __init__(self, *args):
super(Graph, self).__init__(Node, *args)
def map(self, func):
'''
"""A dict mapping the supplied function onto each node in the graph.
Return a dictionary derived from mapping the supplied function onto
each node in the graph.
'''
"""
return dict((k, func(n)) for k, n in self.items())
def copy(self):
'''Return a copy of the graph.'''
"""Return a copy of the graph."""
return Graph(self.map(lambda n: n.copy()))
def reverse_copy(self):
'''Return a copy of the graph with the edges reversed.'''
"""Return a copy of the graph with the edges reversed."""
return Graph(self.map(lambda n: n.reverse_copy()))
def edges(self):
'''Return an iterator over all of the edges in the graph.'''
"""Return an iterator over all of the edges in the graph."""
def outgoing_edges(rqr, node):
if node.disjoint():
yield (rqr, None)
@ -135,7 +131,7 @@ class Graph(collections.defaultdict):
for i in six.iteritems(self))
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."""
node = self[key]
for src in node.required_by():
@ -146,18 +142,17 @@ class Graph(collections.defaultdict):
return super(Graph, self).__delitem__(key)
def __str__(self):
'''Convert the graph to a human-readable string.'''
"""Convert the graph to a human-readable string."""
pairs = ('%s: %s' % (str(k), str(v)) for k, v in six.iteritems(self))
text = '{%s}' % ', '.join(pairs)
return six.text_type(text)
@staticmethod
def toposort(graph):
'''
Return a topologically sorted iterator over a dependency graph.
"""Return a topologically sorted iterator over a dependency graph.
This is a destructive operation for the graph.
'''
"""
for iteration in six.moves.xrange(len(graph)):
for key, node in six.iteritems(graph):
if not node:
@ -172,20 +167,20 @@ class Graph(collections.defaultdict):
@six.python_2_unicode_compatible
class Dependencies(object):
'''Helper class for calculating a dependency graph.'''
"""Helper class for calculating a dependency graph."""
def __init__(self, edges=None):
'''
Initialise, optionally with a list of edges, in the form of
(requirer, required) tuples.
'''
"""Initialise, optionally with a list of edges.
Each edge has the form of (requirer, required) tuple.
"""
edges = edges or []
self._graph = Graph()
for e in edges:
self += e
def __iadd__(self, edge):
'''Add another edge, in the form of a (requirer, required) tuple.'''
"""Add another edge, in the form of a (requirer, required) tuple."""
requirer, required = edge
if required is None:
@ -198,28 +193,25 @@ class Dependencies(object):
return self
def required_by(self, last):
'''
List the keys that require the specified node.
'''
"""List the keys that require the specified node."""
if last not in self._graph:
raise KeyError
return self._graph[last].required_by()
def requires(self, target):
'''
List the keys that require the specified node.
'''
"""List the keys that require the specified node."""
if target not in self._graph:
raise KeyError
return self._graph[target].requires()
def __getitem__(self, last):
'''
"""Partial dependency graph consisting of the specified node.
Return a partial dependency graph consisting of the specified node and
all those that require it only.
'''
"""
if last not in self._graph:
raise KeyError
@ -244,25 +236,20 @@ class Dependencies(object):
return Dependencies(edges)
def leaves(self):
'''
Return an iterator over all of the leaf nodes in the graph.
'''
"""Return an iterator over all of the leaf nodes in the graph."""
return (requirer for requirer, required in self._graph.items()
if not required)
def roots(self):
'''
Return an iterator over all of the root nodes in the graph.
'''
"""Return an iterator over all of the root nodes in the graph."""
return (requirer for requirer, required in self.graph(
reverse=True).items() if not required)
def translate(self, transform):
'''
Translate all of the nodes using a transform function.
"""Translate all of the nodes using a transform function.
Returns a new Dependencies object.
'''
"""
def transform_key(key):
return transform(key) if key is not None else None
@ -270,29 +257,27 @@ class Dependencies(object):
return type(self)(tuple(map(transform_key, e)) for e in edges)
def __str__(self):
'''
Return a human-readable string representation of the dependency graph
'''
"""Return a human-readable string repr of the dependency graph."""
return six.text_type(self._graph)
def __repr__(self):
'''Return a consistent string representation of the object.'''
"""Return a consistent string representation of the object."""
edge_reprs = list(repr(e) for e in self._graph.edges())
edge_reprs.sort()
text = 'Dependencies([%s])' % ', '.join(edge_reprs)
return text
def graph(self, reverse=False):
'''Return a copy of the underlying dependency graph.'''
"""Return a copy of the underlying dependency graph."""
if reverse:
return self._graph.reverse_copy()
else:
return self._graph.copy()
def __iter__(self):
'''Return a topologically sorted iterator.'''
"""Return a topologically sorted iterator."""
return Graph.toposort(self.graph())
def __reversed__(self):
'''Return a reverse topologically sorted iterator.'''
"""Return a reverse topologically sorted iterator."""
return Graph.toposort(self.graph(reverse=True))

@ -63,7 +63,7 @@ class ResourceInfo(object):
"""Base mapping of resource type to implementation."""
def __new__(cls, registry, path, value, **kwargs):
'''Create a new ResourceInfo of the appropriate class.'''
"""Create a new ResourceInfo of the appropriate class."""
if cls != ResourceInfo:
# Call is already for a subclass, so pass it through
@ -221,8 +221,10 @@ class ResourceRegistry(object):
registry[name] = hook
def _register_info(self, path, info):
"""place the new info in the correct location in the registry.
path: a list of keys ['resources', 'my_server', 'OS::Nova::Server']
"""Place the new info in the correct location in the registry.
:param path: a list of keys ['resources', 'my_server',
'OS::Nova::Server']
"""
descriptive_path = '/'.join(path)
name = path[-1]
@ -285,7 +287,7 @@ class ResourceRegistry(object):
registry.pop(info.path[-1])
def matches_hook(self, resource_name, hook):
'''Return whether a resource have a hook set in the environment.
"""Return whether a resource have a hook set in the environment.
For a given resource and a hook type, we check to see if the the passed
group of resources has the right hook associated with the name.
@ -307,7 +309,7 @@ class ResourceRegistry(object):
A hook value is either `pre-create`, `pre-update` or a list of those
values. Resources support wildcard matching. The asterisk sign matches
everything.
'''
"""
ress = self._registry['resources']
for name_pattern, resource in six.iteritems(ress):
if fnmatch.fnmatchcase(resource_name, name_pattern):
@ -365,7 +367,8 @@ class ResourceRegistry(object):
def get_resource_info(self, resource_type, resource_name=None,
registry_type=None, ignore=None):
"""Find possible matches to the resource type and name.
chain the results from the global and user registry to find
Chain the results from the global and user registry to find
a match.
"""
# use cases
@ -381,6 +384,7 @@ class ResourceRegistry(object):
# - filter_by(is_user=False)
# 4) as_dict() to write to the db
# - filter_by(is_user=True)
if self.global_registry is not None:
giter = self.global_registry.iterable_by(resource_type,
resource_name)
@ -446,7 +450,7 @@ class ResourceRegistry(object):
support_status=None,
type_name=None,
version=None):
'''Return a list of valid resource types.'''
"""Return a list of valid resource types."""
# validate the support status
if support_status is not None and not support.is_valid_status(
@ -509,8 +513,10 @@ class Environment(object):
def __init__(self, env=None, user_env=True):
"""Create an Environment from a dict of varying format.
1) old-school flat parameters
2) or newer {resource_registry: bla, parameters: foo}
Next formats are available:
1) old-school flat parameters
2) or newer {resource_registry: bla, parameters: foo}
:param env: the json environment
:param user_env: boolean, if false then we manage python resources too.
@ -601,7 +607,7 @@ def get_child_environment(parent_env, child_params, item_to_remove=None,
environment.
1. resource_registry must be merged (child env should be loaded after the
parent env to take presdence).
parent env to take presence).
2. child parameters must overwrite the parent's as they won't be relevant
in the child template.

@ -22,16 +22,17 @@ from heat.objects import event as event_object
class Event(object):
'''Class representing a Resource state change.'''
"""Class representing a Resource state change."""
def __init__(self, context, stack, action, status, reason,
physical_resource_id, resource_properties, resource_name,
resource_type, uuid=None, timestamp=None, id=None):
'''
"""Initialisation of the event.
Initialise from a context, stack, and event information. The timestamp
and database ID may also be initialised if the event is already in the
database.
'''
"""
self.context = context
self.stack = stack
self.action = action
@ -50,7 +51,7 @@ class Event(object):
@classmethod
def load(cls, context, event_id, event=None, stack=None):
'''Retrieve an Event from the database.'''
"""Retrieve an Event from the database."""
from heat.engine import stack as parser
ev = (event if event is not None else
@ -68,7 +69,7 @@ class Event(object):
ev.resource_type, ev.uuid, ev.created_at, ev.id)
def store(self):
'''Store the Event in the database.'''
"""Store the Event in the database."""
ev = {
'resource_name': self.resource_name,
'physical_resource_id': self.physical_resource_id,
@ -106,7 +107,7 @@ class Event(object):
return self.id
def identifier(self):
'''Return a unique identifier for the event.'''
"""Return a unique identifier for the event."""
if self.uuid is None:
return None

@ -21,13 +21,10 @@ import six
@six.add_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):
"""
Initialise with a Stack, the function name and the arguments.
"""Initialise with a Stack, the function name and the arguments.
All functions take the form of a single-item map in JSON::
@ -49,8 +46,7 @@ class Function(object):
return stack
def validate(self):
"""
Validate arguments without resolving the function.
"""Validate arguments without resolving the function.
Function subclasses must override this method to validate their
args.
@ -59,8 +55,7 @@ class Function(object):
@abc.abstractmethod
def result(self):
"""
Return the result of resolving the function.
"""Return the result of resolving the function.
Function subclasses must override this method to calculate their
results.
@ -74,8 +69,7 @@ class Function(object):
return dep_attrs(self.args, resource_name)
def __reduce__(self):
"""
Return a representation of the function suitable for pickling.
"""Return a representation of the function suitable for pickling.
This allows the copy module (which works by pickling and then
unpickling objects) to copy a template. Functions in the copy will
@ -84,8 +78,7 @@ class Function(object):
return dict, ([(self.fn_name, self.args)],)
def __repr__(self):
"""
Return a string representation of the function.
"""Return a string representation of the function.
The representation includes the function name, arguments and result
(if available), as well as the name of the function class.
@ -155,8 +148,7 @@ def validate(snippet):
def dependencies(snippet, path=''):
"""
Return an iterator over Resource dependencies in a template snippet.
"""Return an iterator over Resource dependencies in a template snippet.
The snippet should be already parsed to insert Function objects where
appropriate.
@ -187,12 +179,12 @@ def dependencies(snippet, path=''):
def dep_attrs(snippet, resource_name):
"""
Return an iterator over dependent attributes for specified resource_name
in a template snippet.
"""Iterator over dependent attrs for resource_name in a template snippet.
The snippet should be already parsed to insert Function objects where
appropriate.
:returns: an iterator over dependent attributes for specified resource_name
in a template snippet.
"""
if isinstance(snippet, Function):

@ -13,32 +13,27 @@
class LifecyclePlugin(object):
'''
Base class for pre-op and post-op work on a stack.
"""Base class for pre-op and post-op work on a stack.
Implementations should extend this class and override the methods.
'''
"""
def do_pre_op(self, cnxt, stack, current_stack=None, action=None):
'''
Method to be run by heat before stack operations.
'''
"""Method to be run by heat before stack operations."""
pass
def do_post_op(self, cnxt, stack, current_stack=None, action=None,
is_stack_failure=False):
'''
Method to be run by heat after stack operations, including failures.
"""Method to be run by heat after stack operations, including failures.
On failure to execute all the registered pre_ops, this method will be
called if and only if the corresponding pre_op was successfully called.
On failures of the actual stack operation, this method will
be called if all the pre operations were successfully called.
'''
"""
pass
def get_ordinal(self):
'''
An ordinal used to order class instances for pre and post
operation execution.
"""Order class instances for pre and post operation execution.
The values returned by get_ordinal are used to create a partial order
for pre and post operation method invocations. The default ordinal
@ -49,5 +44,5 @@ class LifecyclePlugin(object):
class1inst will be executed after the method on class2inst.
If class1inst.ordinal() == class2inst.ordinal(), then the order of
method invocation is indeterminate.
'''
"""
return 100

@ -23,9 +23,7 @@ PARAMETERS = 'parameters'
class ParameterGroups(object):
'''
The ParameterGroups specified by the stack's template.
'''
"""The ParameterGroups specified by the stack's template."""
def __init__(self, tmpl):
self.tmpl = tmpl
self.parameters = tmpl.parameters(None, {}, param_defaults={})
@ -37,10 +35,11 @@ class ParameterGroups(object):
self.parameter_groups = tmpl.get(PARAMETER_GROUPS)
def validate(self):
'''
"""Validate parameters in current parameter group.
Validate that a parameter belongs to only one Parameter Group
and that each parameter name references a valid parameter.
'''
"""
LOG.debug('Validating Parameter Groups.')
LOG.debug(self.parameter_names)
if self.parameter_groups:

@ -36,7 +36,7 @@ PARAMETER_KEYS = (
class Schema(constr.Schema):
'''Parameter schema.'''
"""Parameter schema."""
KEYS = (
TYPE, DESCRIPTION, DEFAULT, SCHEMA, CONSTRAINTS, HIDDEN, LABEL
@ -127,8 +127,7 @@ class Schema(constr.Schema):
@classmethod
def from_dict(cls, param_name, schema_dict):
"""
Return a Parameter Schema object from a legacy schema dictionary.
"""Return a Parameter Schema object from a legacy schema dictionary.
:param param_name: name of the parameter owning the schema; used
for more verbose logging
@ -176,10 +175,10 @@ class Schema(constr.Schema):
@six.python_2_unicode_compatible
class Parameter(object):
'''A template parameter.'''
"""A template parameter."""
def __new__(cls, name, schema, value=None):
'''Create a new Parameter of the appropriate type.'''
"""Create a new Parameter of the appropriate type."""
if cls is not Parameter:
return super(Parameter, cls).__new__(cls)
@ -203,10 +202,11 @@ class Parameter(object):
return ParamClass(name, schema, value)
def __init__(self, name, schema, value=None):
'''
"""Initialisation of the parameter.
Initialise the Parameter with a name, schema and optional user-supplied
value.
'''
"""
self.name = name
self.schema = schema
self.user_value = value
@ -241,7 +241,7 @@ class Parameter(object):
raise exception.InvalidSchemaError(message=msg)
def value(self):
'''Get the parameter value, optionally sanitising it for output.'''
"""Get the parameter value, optionally sanitising it for output."""
if self.user_value is not None:
return self.user_value
@ -251,31 +251,32 @@ class Parameter(object):
raise exception.UserParameterMissing(key=self.name)
def has_value(self):
'''Parameter has a user or default value.'''
"""Parameter has a user or default value."""
return self.user_value is not None or self.has_default()
def hidden(self):
'''
"""Return if parameter is hidden.
Return whether the parameter should be sanitised in any output to
the user.
'''
"""
return self.schema.hidden
def description(self):
'''Return the description of the parameter.'''
"""Return the description of the parameter."""
return self.schema.description or ''
def label(self):
'''Return the label or param name.'''
"""Return the label or param name."""
return self.schema.label or self.name
def has_default(self):
'''Return whether the parameter has a default value.'''
"""Return whether the parameter has a default value."""
return (self.schema.default is not None or
self.user_default is not None)
def default(self):
'''Return the default value of the parameter.'''
"""Return the default value of the parameter."""
if self.user_default is not None:
return self.user_default
return self.schema.default
@ -284,7 +285,7 @@ class Parameter(object):
self.user_default = value
def __str__(self):
'''Return a string representation of the parameter.'''
"""Return a string representation of the parameter."""
value = self.value()
if self.hidden():
return six.text_type('******')
@ -293,14 +294,14 @@ class Parameter(object):
class NumberParam(Parameter):
'''A template parameter of type "Number".'''
"""A template parameter of type "Number"."""
def __int__(self):
'''Return an integer representation of the parameter.'''
"""Return an integer representation of the parameter."""
return int(super(NumberParam, self).value())
def __float__(self):
'''Return a float representation of the parameter.'''
"""Return a float representation of the parameter."""
return float(super(NumberParam, self).value())
def _validate(self, val, context):
@ -315,7 +316,7 @@ class NumberParam(Parameter):
class BooleanParam(Parameter):
'''A template parameter of type "Boolean".'''
"""A template parameter of type "Boolean"."""
def _validate(self, val, context):
try:
@ -333,14 +334,14 @@ class BooleanParam(Parameter):
class StringParam(Parameter):
'''A template parameter of type "String".'''
"""A template parameter of type "String"."""
def _validate(self, val, context):
self.schema.validate_value(val, context)
class CommaDelimitedListParam(Parameter, collections.Sequence):
'''A template parameter of type "CommaDelimitedList".'''
"""A template parameter of type "CommaDelimitedList"."""
def __init__(self, name, schema, value=None):
super(CommaDelimitedListParam, self).__init__(name, schema, value)
@ -373,11 +374,11 @@ class CommaDelimitedListParam(Parameter, collections.Sequence):
raise exception.UserParameterMissing(key=self.name)
def __len__(self):
'''Return the length of the list.'''
"""Return the length of the list."""
return len(self.parsed)
def __getitem__(self, index):
'''Return an item from the list.'''
"""Return an item from the list."""
return self.parsed[index]
def __str__(self):
@ -442,10 +443,11 @@ class JsonParam(Parameter):
class Parameters(collections.Mapping):
'''
The parameters of a stack, with type checking, defaults &c. specified by
"""Parameters of a stack.
The parameters of a stack, with type checking, defaults etc., specified by
the stack's template.
'''
"""
PSEUDO_PARAMETERS = (
PARAM_STACK_ID, PARAM_STACK_NAME, PARAM_REGION
@ -455,10 +457,11 @@ class Parameters(collections.Mapping):
def __init__(self, stack_identifier, tmpl, user_params=None,
param_defaults=None):
'''
"""Initialisation of the parameter.
Create the parameter container for a stack from the stack name and
template, optionally setting the user-supplied parameter values.
'''
"""
user_params = user_params or {}
param_defaults = param_defaults or {}
@ -484,12 +487,11 @@ class Parameters(collections.Mapping):
self.params[pd].set_default(param_defaults[pd])
def validate(self, validate_value=True, context=None):
'''
Validates all parameters.
"""Validates all parameters.
This method validates if all user-provided parameters are actually
defined in the template, and if all parameters are valid.
'''
"""
self._validate_tmpl_parameters()
self._validate_user_parameters()
@ -497,33 +499,32 @@ class Parameters(collections.Mapping):
param.validate(validate_value, context)
def __contains__(self, key):
'''Return whether the specified parameter exists.'''
"""Return whether the specified parameter exists."""
return key in self.params
def __iter__(self):
'''Return an iterator over the parameter names.'''
"""Return an iterator over the parameter names."""
return iter(self.params)
def __len__(self):
'''Return the number of parameters defined.'''
"""Return the number of parameters defined."""
return len(self.params)
def __getitem__(self, key):
'''Get a parameter value.'''
"""Get a parameter value."""
return self.params[key].value()
def map(self, func, filter_func=lambda p: True):
'''
"""Map the supplied filter function onto each Parameter.
Map the supplied filter function onto each Parameter (with an
optional filter function) and return the resulting dictionary.
'''
"""
return dict((n, func(p))
for n, p in six.iteritems(self.params) if filter_func(p))
def set_stack_id(self, stack_identifier):
'''
Set the StackId pseudo parameter value
'''
"""Set the StackId pseudo parameter value."""
if stack_identifier is not None:
self.params[self.PARAM_STACK_ID].schema.set_default(
stack_identifier.arn())

@ -26,10 +26,10 @@ LOG = log.getLogger(__name__)
class PluginManager(object):
'''A class for managing plugin modules.'''
"""A class for managing plugin modules."""
def __init__(self, *extra_packages):
'''Initialise the Heat Engine plugin package, and any others.
"""Initialise the Heat Engine plugin package, and any others.
The heat.engine.plugins package is always created, if it does not
exist, from the plugin directories specified in the config file, and
@ -40,8 +40,7 @@ class PluginManager(object):
will load all modules in the heat.engine.resources package as well as
any user-supplied plugin modules.
'''
"""
def packages():
for package_name in extra_packages:
yield sys.modules[package_name]
@ -58,23 +57,22 @@ class PluginManager(object):
self.modules = list(modules())
def map_to_modules(self, function):
'''Iterate over the results of calling a function on every module.'''
"""Iterate over the results of calling a function on every module."""
return six.moves.map(function, self.modules)
class PluginMapping(object):
'''A class for managing plugin mappings.'''
"""A class for managing plugin mappings."""
def __init__(self, names, *args, **kwargs):
'''Initialise with the mapping name(s) and arguments.
"""Initialise with the mapping name(s) and arguments.
`names` can be a single name or a list of names. The first name found
in a given module is the one used. Each module is searched for a
function called <name>_mapping() which is called to retrieve the
mappings provided by that module. Any other arguments passed will be
passed to the mapping functions.
'''
"""
if isinstance(names, six.string_types):
names = [names]
@ -83,10 +81,10 @@ class PluginMapping(object):
self.kwargs = kwargs
def load_from_module(self, module):
'''Return the mapping specified in the given module.
"""Return the mapping specified in the given module.
If no such mapping is specified, an empty dictionary is returned.
'''
"""
for mapping_name in self.names:
mapping_func = getattr(module, mapping_name, None)
if callable(mapping_func):
@ -107,10 +105,10 @@ class PluginMapping(object):
return {}
def load_all(self, plugin_manager):
'''Iterate over the mappings from all modules in the plugin manager.
"""Iterate over the mappings from all modules in the plugin manager.
Mappings are returned as a list of (key, value) tuples.
'''
"""
mod_dicts = plugin_manager.map_to_modules(self.load_from_module)
return itertools.chain.from_iterable(six.iteritems(d) for d
in mod_dicts)

@ -38,8 +38,7 @@ SCHEMA_KEYS = (
class Schema(constr.Schema):
"""
Schema class for validating resource properties.
"""Schema class for validating resource properties.
This class is used for defining schema constraints for resource properties.
It inherits generic validation features from the base Schema class and add
@ -74,9 +73,7 @@ class Schema(constr.Schema):
@classmethod
def from_legacy(cls, schema_dict):
"""
Return a Property Schema object from a legacy schema dictionary.
"""
"""Return a Property Schema object from a legacy schema dictionary."""
# Check for fully-fledged Schema objects
if isinstance(schema_dict, cls):
@ -134,8 +131,7 @@ class Schema(constr.Schema):
@classmethod
def from_parameter(cls, param):
"""
Return a Property Schema corresponding to a Parameter Schema.
"""Return a Property Schema corresponding to a Parameter Schema.
Convert a parameter schema from a provider template to a property
Schema for the corresponding resource facade.
@ -169,8 +165,7 @@ class Schema(constr.Schema):
default=param.default)
def allowed_param_prop_type(self):
"""
Return allowed type of Property Schema converted from parameter.
"""Return allowed type of Property Schema converted from parameter.
Especially, when generating Schema from parameter, Integer Property