reclass icon indicating copy to clipboard operation
reclass copied to clipboard

Implement mutators

Open lottspot opened this issue 7 years ago • 5 comments

This patch introduces a new Mutators data type to entities. This data type is a stack of python callables which perform arbitrary modifications to a populated node or inventory dictionary before it is returned to the caller.

Writing mutators is simple; we simply need to provide a python callable within a module somewhere along PYTHONPATH (cli has been modified in this patch to append inventory_base_uri to sys.path for sane default behavior)

# mutator_mod.py
def some_callable(nodename, inventory):
  thisnode = inventory['nodes'][nodename]
  thisnode['parameters']['related_nodes'] = []
  for name, node in inventory['nodes'].items():
    if nodename in node['parameters'].get('related_to', []):
      thisnode['parameters']['related_nodes'].append(name)

Mutators are then specified in class or node definitions, just as other reclass datatypes.

# nodes/mynode.yml
parameters:
  hello: world
mutators:
  - mutator_pkg.mutator_mod.some_callable
# nodes/myrelatednode.yml
parameters:
  related_to:
    - mynode

This configuration would apply the mutator when all of the following conditions are satisfied:

  1. mynode is loaded
  2. Core calls _mutate with arguments named 'inventory' and 'nodename'

Core will only call _mutate with those arguments within Core.nodeinfo. So from the CLI, this mutator would be applied using reclass -n mynode, which would then produce the following output:

__reclass__:
  environment: base
  name: mynode
  node: ./mynode
  timestamp: Sat Aug  6 18:14:47 2016
  uri: yaml_fs:///mnt/files/shared/projects/reclass/.env/inventory/nodes/./mynode.yml
applications: []
classes: []
environment: base
parameters:
  hello: world
  related_nodes:
  - myrelatednode

The purpose of implementing this feature is to offer a way to create dynamic node parameters, primarily as a way to build relationships between nodes or classes based on other parameters.

lottspot avatar Aug 06 '16 22:08 lottspot

I guess it would actually be more accurate to point out that mutators need to be functions, and that arbitrary callables won't work. That's a limitation imposed by inspect.getargspec, which is a crucial piece of deciding whether a mutator should be run.

lottspot avatar Aug 07 '16 12:08 lottspot

Let's not merge this yet-- I need to resolve lottspot/reclass/issues/4 first

lottspot avatar Dec 28 '16 14:12 lottspot

Any news on this feature?

bbinet avatar Feb 08 '17 10:02 bbinet

This feature is still very much on my radar to complete. I hope to be able to carve out some time soon to hammer out the remaining issues and wrap this up.

lottspot avatar Feb 08 '17 15:02 lottspot

@lottspot, what is the situation that motivates this feature?

ketzacoatl avatar May 09 '18 00:05 ketzacoatl