Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
Base classes for all front-end plugins. """
RequiresRoot, VersionError, RequirementError, OptionError, InvocationError)
""" Return the number of entries in an entry. This is primarly for the failed output parameter so we don't print empty values.
We also use this to determine if a non-zero return value is needed. """ num_entries = 0 for f in entry: if type(entry[f]) is dict: num_entries = num_entries + entry_count(entry[f]) else: num_entries = num_entries + len(entry[f])
return num_entries
""" Base class for plugins that have `Param` `NameSpace` attributes.
Subclasses of `HasParam` will on one or more attributes store `NameSpace` instances containing zero or more `Param` instances. These parameters might describe, for example, the arguments and options a command takes, or the attributes an LDAP entry can include, or whatever else the subclass sees fit.
Although the interface a subclass must implement is very simple, it must conform to a specific naming convention: if you want a namespace ``SubClass.foo``, you must define a ``Subclass.takes_foo`` attribute and a ``SubCLass.get_foo()`` method, and you may optionally define a ``SubClass.check_foo()`` method.
A quick big-picture example ===========================
Say you want the ``options`` instance attribute on your subclass to be a `Param` `NameSpace`... then according to the enforced naming convention, your subclass must define a ``takes_options`` attribute and a ``get_options()`` method. For example:
>>> from ipalib import Str, Int >>> class Example(HasParam): ... ... options = None # This will be replaced with your namespace ... ... takes_options = (Str('one'), Int('two')) ... ... def get_options(self): ... return self._get_param_iterable('options') ... >>> eg = Example()
The ``Example.takes_options`` attribute is a ``tuple`` defining the parameters you want your ``Example.options`` namespace to contain. Your ``Example.takes_options`` attribute will be accessed via `HasParam._get_param_iterable()`, which, among other things, enforces the ``('takes_' + name)`` naming convention. For example:
>>> eg._get_param_iterable('options') (Str('one'), Int('two'))
The ``Example.get_options()`` method simply returns ``Example.takes_options`` by calling `HasParam._get_param_iterable()`. Your ``Example.get_options()`` method will be called via `HasParam._filter_param_by_context()`, which, among other things, enforces the ``('get_' + name)`` naming convention. For example:
>>> list(eg._filter_param_by_context('options')) [Str('one'), Int('two')]
At this point, the ``eg.options`` instance attribute is still ``None``:
>>> eg.options is None True
`HasParam._create_param_namespace()` will create the ``eg.options`` namespace from the parameters yielded by `HasParam._filter_param_by_context()`. For example:
>>> eg._create_param_namespace('options') >>> eg.options NameSpace(<2 members>, sort=False) >>> list(eg.options) # Like dict.__iter__() ['one', 'two']
Your subclass can optionally define a ``check_options()`` method to perform sanity checks. If it exists, the ``check_options()`` method is called by `HasParam._create_param_namespace()` with a single value, the `NameSpace` instance it created. For example:
>>> class Example2(Example): ... ... def check_options(self, namespace): ... for param in namespace(): # Like dict.itervalues() ... if param.name == 'three': ... raise ValueError("I dislike the param 'three'") ... print ' ** Looks good! **' # Note output below ... >>> eg = Example2() >>> eg._create_param_namespace('options') ** Looks good! ** >>> eg.options NameSpace(<2 members>, sort=False)
However, if we subclass again and add a `Param` named ``'three'``:
>>> class Example3(Example2): ... ... takes_options = (Str('one'), Int('two'), Str('three')) ... >>> eg = Example3() >>> eg._create_param_namespace('options') Traceback (most recent call last): ... ValueError: I dislike the param 'three' >>> eg.options is None # eg.options was not set True
The Devil and the details =========================
In the above example, ``takes_options`` is a ``tuple``, but it can also be a param spec (see `create_param()`), or a callable that returns an iterable containing one or more param spec. Regardless of how ``takes_options`` is defined, `HasParam._get_param_iterable()` will return a uniform iterable, conveniently hiding the details.
The above example uses the simplest ``get_options()`` method possible, but you could instead implement a ``get_options()`` method that would, for example, produce (or withhold) certain parameters based on the whether certain plugins are loaded.
Think of ``takes_options`` as declarative, a simple definition of *what* parameters should be included in the namespace. You should only implement a ``takes_options()`` method if a `Param` must reference attributes on your plugin instance (for example, for validation rules); you should not use a ``takes_options()`` method to filter the parameters or add any other procedural behaviour.
On the other hand, think of the ``get_options()`` method as imperative, a procedure for *how* the parameters should be created and filtered. In the example above the *how* just returns the *what* unchanged, but arbitrary logic can be implemented in the ``get_options()`` method. For example, you might filter certain parameters from ``takes_options`` base on some criteria, or you might insert additional parameters provided by other plugins.
The typical use case for using ``get_options()`` this way is to procedurally generate the arguments and options for all the CRUD commands operating on a specific LDAP object: the `Object` plugin defines the possible LDAP entry attributes (as `Param`), and then the CRUD commands intelligently build their ``args`` and ``options`` namespaces based on which attribute is the primary key. In this way new LDAP attributes (aka parameters) can be added to the single point of definition (the `Object` plugin), and all the corresponding CRUD commands pick up these new parameters without requiring modification. For an example of how this is done, see the `ipalib.crud.Create` base class.
However, there is one type of filtering you should not implement in your ``get_options()`` method, because it's already provided at a higher level: you should not filter parameters based on the value of ``api.env.context`` nor (preferably) on any values in ``api.env``. `HasParam._filter_param_by_context()` already does this by calling `Param.use_in_context()` for each parameter. Although the base `Param.use_in_context()` implementation makes a decision solely on the value of ``api.env.context``, subclasses can override this with implementations that consider arbitrary ``api.env`` values. """ # HasParam is the base class for most frontend plugins, that make it to users # This flag indicates that the command should not be available in the cli
""" Return an iterable of params defined by the attribute named ``name``.
A sequence of params can be defined one of three ways: as a ``tuple``; as a callable that returns an iterable; or as a param spec (a `Param` or ``str`` instance). This method returns a uniform iterable regardless of how the param sequence was defined.
For example, when defined with a tuple:
>>> class ByTuple(HasParam): ... takes_args = (Param('foo'), Param('bar')) ... >>> by_tuple = ByTuple() >>> list(by_tuple._get_param_iterable('args')) [Param('foo'), Param('bar')]
Or you can define your param sequence with a callable when you need to reference attributes on your plugin instance (for validation rules, etc.). For example:
>>> class ByCallable(HasParam): ... def takes_args(self): ... yield Param('foo', self.validate_foo) ... yield Param('bar', self.validate_bar) ... ... def validate_foo(self, _, value, **kw): ... if value != 'Foo': ... return _("must be 'Foo'") ... ... def validate_bar(self, _, value, **kw): ... if value != 'Bar': ... return _("must be 'Bar'") ... >>> by_callable = ByCallable() >>> list(by_callable._get_param_iterable('args')) [Param('foo', validate_foo), Param('bar', validate_bar)]
Lastly, as a convenience for when a param sequence contains a single param, your defining attribute may a param spec (either a `Param` or an ``str`` instance). For example:
>>> class BySpec(HasParam): ... takes_args = Param('foo') ... takes_options = 'bar?' ... >>> by_spec = BySpec() >>> list(by_spec._get_param_iterable('args')) [Param('foo')] >>> list(by_spec._get_param_iterable('options')) ['bar?']
For information on how an ``str`` param spec is interpreted, see the `create_param()` and `parse_param_spec()` functions in the `ipalib.parameters` module.
Also see `HasParam._filter_param_by_context()`. """ return tuple() '%s.%s must be a tuple, callable, or spec; got %r' % ( self.name, src_name, src ) )
""" Filter params on attribute named ``name`` by environment ``env``.
For example:
>>> from ipalib.config import Env >>> class Example(HasParam): ... ... takes_args = ( ... Str('foo_only', include=['foo']), ... Str('not_bar', exclude=['bar']), ... 'both', ... ) ... ... def get_args(self): ... return self._get_param_iterable('args') ... ... >>> eg = Example() >>> foo = Env(context='foo') >>> bar = Env(context='bar') >>> another = Env(context='another') >>> (foo.context, bar.context, another.context) (u'foo', u'bar', u'another') >>> list(eg._filter_param_by_context('args', foo)) [Str('foo_only', include=['foo']), Str('not_bar', exclude=['bar']), Str('both')] >>> list(eg._filter_param_by_context('args', bar)) [Str('both')] >>> list(eg._filter_param_by_context('args', another)) [Str('not_bar', exclude=['bar']), Str('both')] """ '%s.%s()' % (self.name, get_name) ) '%s.%s must be a callable; got %r' % (self.name, get_name, get) ) # Force specified environment. The way it is done is violation of ReadOnly promise. # Unfortunately, all alternatives are worse from both performance and code complexity # points of view. See following threads on freeipa-devel@ for references: # https://www.redhat.com/archives/freeipa-devel/2011-August/msg00000.html # https://www.redhat.com/archives/freeipa-devel/2011-August/msg00011.html
self._filter_param_by_context(name, env), sort=False )
""" A public IPA atomic operation.
All plugins that subclass from `Command` will be automatically available as a CLI command and as an XML-RPC method.
Plugins that subclass from Command are registered in the ``api.Command`` namespace. For example:
>>> from ipalib import create_api >>> api = create_api() >>> class my_command(Command): ... pass ... >>> api.register(my_command) >>> api.finalize() >>> list(api.Command) ['my_command'] >>> api.Command.my_command # doctest:+ELLIPSIS ipalib.frontend.my_command() """
# Create stubs for attributes that are set in _on_finalize()
""" Perform validation and then execute the command.
If not in a server context, the call will be forwarded over XML-RPC and the executed an the nearest IPA server. """ 'raw: %s(%s)', self.name, ', '.join(self._repr_iter(**params)) ) '%s(%s)', self.name, ', '.join(self._repr_iter(**params)) ) isinstance(ret, dict) and 'summary' in self.output and 'summary' not in ret ): else:
values=values, errors=errors, )
""" Iterate through ``repr()`` of *safe* values of args and options.
This method uses `parameters.Param.safe_value()` to mask passwords when logging. Logging the exact call is extremely useful, but we obviously don't want to log the cleartext password.
For example:
>>> class my_cmd(Command): ... takes_args = ('login',) ... takes_options=(Password('passwd'),) ... >>> c = my_cmd() >>> c.finalize() >>> list(c._repr_iter(login=u'Okay.', passwd=u'Private!')) ["u'Okay.'", "passwd=u'********'"] """
""" Merge (args, options) into params. """
else: else: else:
# If any options remain, they are either internal or unknown option=unused_keys.pop())
""" Creates a LDAP entry from attributes in args and options. """
else:
""" Split params into (args, options). """
""" Return a dictionary of normalized values.
For example:
>>> class my_command(Command): ... takes_options = ( ... Param('first', normalizer=lambda value: value.lower()), ... Param('last'), ... ) ... >>> c = my_command() >>> c.finalize() >>> c.normalize(first=u'JOHN', last=u'DOE') {'last': u'DOE', 'first': u'john'} """ (k, self.params[k].normalize(v)) for (k, v) in kw.iteritems() )
""" Return a dictionary of values converted to correct type.
>>> from ipalib import Int >>> class my_command(Command): ... takes_args = ( ... Int('one'), ... 'two', ... ) ... >>> c = my_command() >>> c.finalize() >>> c.convert(one=1, two=2) {'two': u'2', 'one': 1} """ (k, self.params[k].convert(v)) for (k, v) in kw.iteritems() )
for param in self.params(): if kw.get(param.name, None) is None: continue
""" Return a dictionary of defaults for all missing required values.
For example:
>>> from ipalib import Str >>> class my_command(Command): ... takes_args = Str('color', default=u'Red') ... >>> c = my_command() >>> c.finalize() >>> c.get_default() {'color': u'Red'} >>> c.get_default(color=u'Yellow') {} """
""" Return default value for parameter `name`. """
""" Generator method used by `Command.get_default` and `Command.get_default_of`. """ # Find out what additional parameters are needed to dynamically create # the default values with default_from.
# Parameter is specified, convert and validate the value. else: # Parameter is not specified, use default value. Convert # and validate the value, it might not be returned so # there's no guarantee it will be converted and validated # later. # Default value is not available from the previous step, # get it now. At this point it is certain that the value # will be returned, so let the caller care about conversion # and validation.
""" Validate all values.
If any value fails the validation, `ipalib.errors.ValidationError` (or a subclass thereof) will be raised. """
""" Compare the version the client provided to the version of the server.
If the client major version does not match then return an error. If the client minor version is less than or equal to the server then let the request proceed. """ raise VersionError(cver=ver.version, sver=server_ver.version, server= self.env.xmlrpc_uri)
raise VersionError(cver=client_version, sver=API_VERSION, server=self.env.xmlrpc_uri) raise VersionError(cver=client_version, sver=API_VERSION, server=self.env.xmlrpc_uri)
""" Dispatch to `Command.execute` or `Command.forward`.
If running in a server context, `Command.execute` is called and the actually work this command performs is executed locally.
If running in a non-server context, `Command.forward` is called, which forwards this call over XML-RPC to the exact same command on the nearest IPA server and the actual work this command performs is executed remotely. """ else: API_VERSION, result, messages.VersionMissing(server_version=API_VERSION))
""" Perform the actual work this command does.
This method should be implemented only against functionality in self.api.Backend. For example, a hypothetical user_add.execute() might be implemented like this:
>>> class user_add(Command): ... def execute(self, **kw): ... return self.api.Backend.ldap.add(**kw) ... """
""" Forward call over XML-RPC to this same command on server. """
""" Finalize plugin initialization.
This method creates the ``args``, ``options``, and ``params`` namespaces. This is not done in `Command.__init__` because subclasses (like `crud.Add`) might need to access other plugins loaded in self.api to determine what their custom `Command.get_args` and `Command.get_options` methods should yield. """ else: sorted(params_nosort, key=get_key), sort=False ) # Sort params so that the ones with default_from come after the ones # that the default_from might depend on and save the result in # params_by_default namespace.
self.name, tuple, type(self.has_output), self.has_output) ) self.name, i, (str, Output), type(o), o) )
""" Iterate through parameters for ``Command.args`` namespace.
This method gets called by `HasParam._create_param_namespace()`.
Subclasses can override this to customize how the arguments are determined. For an example of why this can be useful, see the `ipalib.crud.Create` subclass. """
""" Sanity test for args namespace.
This method gets called by `HasParam._create_param_namespace()`. """ '%s: required argument after optional' % arg.name ) '%s: only final argument can be multivalue' % arg.name )
""" Iterate through parameters for ``Command.options`` namespace.
This method gets called by `HasParam._create_param_namespace()`.
For commands that return entries two special options are generated: --all makes the command retrieve/display all attributes --raw makes the command display attributes as they are stored
Subclasses can override this to customize how the arguments are determined. For an example of why this can be useful, see the `ipalib.crud.Create` subclass. """ cli_name='all', doc=_('Retrieve and print all attributes from the server. Affects command output.'), exclude='webui', flags=['no_output'], ) cli_name='raw', doc=_('Print entries as stored on the server. Only affects output format.'), exclude='webui', flags=['no_output'], ) doc=_('Client version. Used to determine if server will accept request.'), exclude='webui', flags=['no_option', 'no_output'], )
""" Validate the return value to make sure it meets the interface contract. """ nice, dict, type(output), output) ) nice, sorted(missing), output) ) nice, sorted(extra), output) ) nice, o.name, o.type, type(value), value) )
logger_functions = dict( debug=logger.debug, info=logger.info, warning=logger.warning, error=logger.error, ) for message in output.get('messages', ()): try: function = logger_functions[message['type']] except KeyError: logger.error('Server sent a message with a wrong type') function = logger.error function(message.get('message'))
""" Generic output method. Prints values the output argument according to their type and self.output.
Entry attributes are labeled and printed in the order specified in self.output_params. Attributes that aren't present in self.output_params are not printed unless the command was invokend with the --all option. Attribute labelling is disabled if the --raw option was given.
Subclasses can override this method, if custom output is needed. """
rv = 0
self.log_messages(output, root_logger)
order = [p.name for p in self.output_params()] if options.get('all', False): order.insert(0, 'dn') print_all = True else: print_all = False
if options.get('raw', False): labels = None else: labels = dict((p.name, unicode(p.label)) for p in self.output_params()) flags = dict((p.name, p.flags) for p in self.output_params())
for o in self.output: outp = self.output[o] if 'no_display' in outp.flags: continue result = output[o]
if o.lower() == 'count' and result == 0: rv = 1 elif o.lower() == 'failed': if entry_count(result) == 0: # Don't display an empty failed list continue else: # Return an error to the shell rv = 1 if isinstance(outp, ListOfEntries): textui.print_entries(result, order, labels, flags, print_all) elif isinstance(result, (tuple, list)): textui.print_entries(result, order, labels, flags, print_all) elif isinstance(outp, Entry): textui.print_entry(result, order, labels, flags, print_all) elif isinstance(result, dict): textui.print_entry(result, order, labels, flags, print_all) elif isinstance(result, unicode): if o == 'summary': textui.print_summary(result) else: textui.print_indented(result) elif isinstance(result, bool): # the Delete commands return a boolean indicating # success or failure. Ignore these. pass elif isinstance(result, int): textui.print_count(result, '%s %%d' % unicode(self.output[o].doc))
return rv
# list of attributes we want exported to JSON 'name', 'takes_args', )
# list of options we want only to mention their presence and not to write # their attributes 'all', 'raw', 'attrs', 'addattr', 'delattr', 'setattr', 'version', )
""" Get only options we want exported to JSON """ for option in self.get_options(): if option.name not in self.json_only_presence_options: yield option else: yield { 'name': option.name }
json_dict = dict( (a, getattr(self, a)) for a in self.json_friendly_attributes )
json_dict['takes_options'] = list(self.get_json_options())
return json_dict
""" A command that is explicitly executed locally or remotely.
This is for commands that makes sense to execute either locally or remotely to return a perhaps different result. The best example of this is the `ipalib.plugins.f_misc.env` plugin which returns the key/value pairs describing the configuration state: it can be """
Flag('server?', doc=_('Forward to server instead of running locally'), ), )
""" Dispatch to forward() or execute() based on ``server`` option.
When running in a client context, this command is executed remotely if ``options['server']`` is true; otherwise it is executed locally.
When running in a server context, this command is always executed locally and the value of ``options['server']`` is ignored. """
""" A command that is explicitly executed locally.
This is for commands that makes sense to execute only locally such as the help command. """
""" Dispatch to forward() onlly. """ return self.forward(*args, **options)
# Create stubs for attributes that are set in _on_finalize()
# Can override in subclasses:
self.__get_attrs('Method'), sort=False, name_attr='attr_name' ) self.__get_attrs('Property'), sort=False, name_attr='attr_name' ) '%s (Object) has multiple primary keys: %s' % ( self.name, ', '.join(p.name for p in pkeys), ) ) filter(lambda p: not p.primary_key, self.params()), sort=False ) else:
""" Yield all Param whose name is not in ``names``. """
""" Construct an LDAP DN. """
""" This method gets called by `HasParam._create_param_namespace()`. """ else: yield props.pop(key).param else: return 1 return 2
""" Base class implementing the attribute-to-object association.
`Attribute` plugins are associated with an `Object` plugin to group a common set of commands that operate on a common set of parameters.
The association between attribute and object is done using a simple naming convention: the first part of the plugin class name (up to the first underscore) is the object name, and rest is the attribute name, as this table shows:
=============== =========== ============== Class name Object name Attribute name =============== =========== ============== noun_verb noun verb user_add user add user_first_name user first_name =============== =========== ==============
For example:
>>> class user_add(Attribute): ... pass ... >>> instance = user_add() >>> instance.obj_name 'user' >>> instance.attr_name 'add'
In practice the `Attribute` class is not used directly, but rather is only the base class for the `Method` and `Property` classes. Also see the `Object` class. """
'^(?P<obj>[a-z][a-z0-9]+)_(?P<attr>[a-z][a-z0-9]+(?:_[a-z][a-z0-9]+)*)$' )
# Create stubs for attributes that are set in _on_finalize()
""" Returns the obj instance this attribute is associated with, or None if no association has been set. """
""" A command with an associated object.
A `Method` plugin must have a corresponding `Object` plugin. The association between object and method is done through a simple naming convention: the first part of the method name (up to the first under score) is the object name, as the examples in this table show:
============= =========== ============== Method name Object name Attribute name ============= =========== ============== user_add user add noun_verb noun verb door_open_now door open_now ============= =========== ==============
There are three different places a method can be accessed. For example, say you created a `Method` plugin and its corresponding `Object` plugin like this:
>>> from ipalib import create_api >>> api = create_api() >>> class user_add(Method): ... def run(self, **options): ... return dict(result='Added the user!') ... >>> class user(Object): ... pass ... >>> api.register(user_add) >>> api.register(user) >>> api.finalize()
First, the ``user_add`` plugin can be accessed through the ``api.Method`` namespace:
>>> list(api.Method) ['user_add'] >>> api.Method.user_add() # Will call user_add.run() {'result': 'Added the user!'}
Second, because `Method` is a subclass of `Command`, the ``user_add`` plugin can also be accessed through the ``api.Command`` namespace:
>>> list(api.Command) ['user_add'] >>> api.Command.user_add() # Will call user_add.run() {'result': 'Added the user!'}
And third, ``user_add`` can be accessed as an attribute on the ``user`` `Object`:
>>> list(api.Object) ['user'] >>> list(api.Object.user.methods) ['add'] >>> api.Object.user.methods.add() # Will call user_add.run() {'result': 'Added the user!'}
The `Attribute` base class implements the naming convention for the attribute-to-object association. Also see the `Object` and the `Property` classes. """
# FIXME: This is a hack till Param.label is updated to require a # LazyText instance: sorted(self.__rules_iter(), key=lambda f: getattr(f, '__name__')) ) sorted(self.__kw_iter(), key=lambda keyvalue: keyvalue[0]) )
""" Iterates through the attributes in this instance to retrieve the methods implementing validation rules. """
""" An LDAP update with an associated object (always update).
All plugins that subclass from `Updater` will be automatically available as a server update function.
Plugins that subclass from Updater are registered in the ``api.Updater`` namespace. For example:
>>> from ipalib import create_api >>> api = create_api() >>> class my(Object): ... pass ... >>> api.register(my) >>> class my_update(Updater): ... pass ... >>> api.register(my_update) >>> api.finalize() >>> list(api.Updater) ['my_update'] >>> api.Updater.my_update # doctest:+ELLIPSIS ipalib.frontend.my_update() """
self.debug( 'raw: %s', self.name )
return self.execute(**options) |