2008-09-29 10:41:30 -05:00
|
|
|
# Authors:
|
|
|
|
# Martin Nagy <mnagy@redhat.com>
|
2008-12-30 15:05:08 -06:00
|
|
|
# Jason Gerard DeRose <jderose@redhat.com>
|
2008-09-29 10:41:30 -05:00
|
|
|
#
|
|
|
|
# Copyright (C) 2008 Red Hat
|
|
|
|
# see file 'COPYING' for use and warranty information
|
|
|
|
#
|
2010-12-09 06:59:11 -06:00
|
|
|
# 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.
|
2008-09-29 10:41:30 -05:00
|
|
|
#
|
|
|
|
# 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
|
2010-12-09 06:59:11 -06:00
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2008-09-29 10:41:30 -05:00
|
|
|
|
2008-10-20 12:53:07 -05:00
|
|
|
"""
|
2008-12-30 14:52:36 -06:00
|
|
|
Process-wide static configuration and environment.
|
2008-10-20 12:53:07 -05:00
|
|
|
|
2008-12-30 14:52:36 -06:00
|
|
|
The standard run-time instance of the `Env` class is initialized early in the
|
|
|
|
`ipalib` process and is then locked into a read-only state, after which no
|
|
|
|
further changes can be made to the environment throughout the remaining life
|
|
|
|
of the process.
|
|
|
|
|
|
|
|
For the per-request thread-local information, see `ipalib.request`.
|
2008-10-20 12:53:07 -05:00
|
|
|
"""
|
|
|
|
|
2008-10-03 10:08:37 -05:00
|
|
|
import os
|
2008-10-24 16:07:07 -05:00
|
|
|
from os import path
|
2008-10-24 02:51:36 -05:00
|
|
|
import sys
|
2008-12-30 01:45:48 -06:00
|
|
|
|
2015-08-10 11:29:33 -05:00
|
|
|
import six
|
2016-08-24 06:37:30 -05:00
|
|
|
# pylint: disable=import-error
|
2015-09-14 05:52:29 -05:00
|
|
|
from six.moves.urllib.parse import urlparse, urlunparse
|
2015-09-14 07:03:58 -05:00
|
|
|
from six.moves.configparser import RawConfigParser, ParsingError
|
2016-08-24 06:37:30 -05:00
|
|
|
# pylint: enable=import-error
|
2015-08-10 11:29:33 -05:00
|
|
|
|
|
|
|
from ipapython.dn import DN
|
2015-07-31 03:15:01 -05:00
|
|
|
from ipalib.base import check_name
|
|
|
|
from ipalib.constants import CONFIG_SECTION
|
|
|
|
from ipalib.constants import OVERRIDE_ERROR, SET_ERROR, DEL_ERROR
|
2008-10-14 14:22:44 -05:00
|
|
|
|
2015-09-11 06:43:28 -05:00
|
|
|
if six.PY3:
|
|
|
|
unicode = str
|
2008-09-29 10:41:30 -05:00
|
|
|
|
2008-10-24 02:51:36 -05:00
|
|
|
class Env(object):
|
|
|
|
"""
|
2008-12-22 22:02:43 -06:00
|
|
|
Store and retrieve environment variables.
|
|
|
|
|
|
|
|
First an foremost, the `Env` class provides a handy container for
|
2008-12-23 02:11:03 -06:00
|
|
|
environment variables. These variables can be both set *and* retrieved
|
|
|
|
either as attributes *or* as dictionary items.
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2008-12-23 02:59:31 -06:00
|
|
|
For example, you can set a variable as an attribute:
|
2008-12-22 22:02:43 -06:00
|
|
|
|
|
|
|
>>> env = Env()
|
|
|
|
>>> env.attr = 'I was set as an attribute.'
|
2008-12-23 02:11:03 -06:00
|
|
|
>>> env.attr
|
2010-02-22 13:29:26 -06:00
|
|
|
u'I was set as an attribute.'
|
2008-12-22 22:02:43 -06:00
|
|
|
>>> env['attr'] # Also retrieve as a dictionary item
|
2010-02-22 13:29:26 -06:00
|
|
|
u'I was set as an attribute.'
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2008-12-23 02:59:31 -06:00
|
|
|
Or you can set a variable as a dictionary item:
|
2008-12-22 22:02:43 -06:00
|
|
|
|
|
|
|
>>> env['item'] = 'I was set as a dictionary item.'
|
2008-12-23 02:11:03 -06:00
|
|
|
>>> env['item']
|
2010-02-22 13:29:26 -06:00
|
|
|
u'I was set as a dictionary item.'
|
2008-12-22 22:02:43 -06:00
|
|
|
>>> env.item # Also retrieve as an attribute
|
2010-02-22 13:29:26 -06:00
|
|
|
u'I was set as a dictionary item.'
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2009-01-02 02:14:37 -06:00
|
|
|
The variable names must be valid lower-case Python identifiers that neither
|
|
|
|
start nor end with an underscore. If your variable name doesn't meet these
|
|
|
|
criteria, a ``ValueError`` will be raised when you try to set the variable
|
|
|
|
(compliments of the `base.check_name()` function). For example:
|
|
|
|
|
|
|
|
>>> env.BadName = 'Wont work as an attribute'
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2010-02-12 10:01:23 -06:00
|
|
|
ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'BadName'
|
2009-01-02 02:14:37 -06:00
|
|
|
>>> env['BadName'] = 'Also wont work as a dictionary item'
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2010-02-12 10:01:23 -06:00
|
|
|
ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'BadName'
|
2009-01-02 02:14:37 -06:00
|
|
|
|
2008-12-30 16:02:15 -06:00
|
|
|
The variable values can be ``str``, ``int``, or ``float`` instances, or the
|
|
|
|
``True``, ``False``, or ``None`` constants. When the value provided is an
|
|
|
|
``str`` instance, some limited automatic type conversion is performed, which
|
|
|
|
allows values of specific types to be set easily from configuration files or
|
2008-12-22 22:02:43 -06:00
|
|
|
command-line options.
|
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
So in addition to their actual values, the ``True``, ``False``, and ``None``
|
|
|
|
constants can be specified with an ``str`` equal to what ``repr()`` would
|
|
|
|
return. For example:
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2008-12-23 00:09:35 -06:00
|
|
|
>>> env.true = True
|
2008-12-23 02:11:03 -06:00
|
|
|
>>> env.also_true = 'True' # Equal to repr(True)
|
2008-12-22 22:02:43 -06:00
|
|
|
>>> env.true
|
|
|
|
True
|
2008-12-23 00:09:35 -06:00
|
|
|
>>> env.also_true
|
|
|
|
True
|
2008-12-22 22:02:43 -06:00
|
|
|
|
|
|
|
Note that the automatic type conversion is case sensitive. For example:
|
|
|
|
|
2009-01-05 04:28:27 -06:00
|
|
|
>>> env.not_false = 'false' # Not equal to repr(False)!
|
|
|
|
>>> env.not_false
|
2010-02-22 13:29:26 -06:00
|
|
|
u'false'
|
2008-12-22 22:02:43 -06:00
|
|
|
|
|
|
|
If an ``str`` value looks like an integer, it's automatically converted to
|
2014-06-19 12:06:19 -05:00
|
|
|
the ``int`` type.
|
2008-12-22 22:02:43 -06:00
|
|
|
|
|
|
|
>>> env.lucky = '7'
|
|
|
|
>>> env.lucky
|
|
|
|
7
|
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
Leading and trailing white-space is automatically stripped from ``str``
|
|
|
|
values. For example:
|
2008-12-22 22:02:43 -06:00
|
|
|
|
|
|
|
>>> env.message = ' Hello! ' # Surrounded by double spaces
|
|
|
|
>>> env.message
|
2010-02-22 13:29:26 -06:00
|
|
|
u'Hello!'
|
2008-12-23 02:11:03 -06:00
|
|
|
>>> env.number = ' 42 ' # Still converted to an int
|
2008-12-22 22:02:43 -06:00
|
|
|
>>> env.number
|
|
|
|
42
|
2009-01-05 04:28:27 -06:00
|
|
|
>>> env.false = ' False ' # Still equal to repr(False)
|
|
|
|
>>> env.false
|
2008-12-22 22:02:43 -06:00
|
|
|
False
|
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
Also, empty ``str`` instances are converted to ``None``. For example:
|
|
|
|
|
|
|
|
>>> env.empty = ''
|
|
|
|
>>> env.empty is None
|
|
|
|
True
|
|
|
|
|
2008-12-23 00:09:35 -06:00
|
|
|
`Env` variables are all set-once (first-one-wins). Once a variable has been
|
|
|
|
set, trying to override it will raise an ``AttributeError``. For example:
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2008-12-23 00:09:35 -06:00
|
|
|
>>> env.date = 'First'
|
|
|
|
>>> env.date = 'Second'
|
2008-12-22 22:02:43 -06:00
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2010-02-22 13:29:26 -06:00
|
|
|
AttributeError: cannot override Env.date value u'First' with 'Second'
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
An `Env` instance can be *locked*, after which no further variables can be
|
|
|
|
set. Trying to set variables on a locked `Env` instance will also raise
|
2008-12-22 22:02:43 -06:00
|
|
|
an ``AttributeError``. For example:
|
|
|
|
|
|
|
|
>>> env = Env()
|
2008-12-23 02:11:03 -06:00
|
|
|
>>> env.okay = 'This will work.'
|
2008-12-22 22:02:43 -06:00
|
|
|
>>> env.__lock__()
|
2008-12-23 02:11:03 -06:00
|
|
|
>>> env.nope = 'This wont work!'
|
2008-12-22 22:02:43 -06:00
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2008-12-23 02:11:03 -06:00
|
|
|
AttributeError: locked: cannot set Env.nope to 'This wont work!'
|
2008-12-22 22:02:43 -06:00
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
`Env` instances also provide standard container emulation for membership
|
|
|
|
testing, counting, and iteration. For example:
|
|
|
|
|
|
|
|
>>> env = Env()
|
|
|
|
>>> 'key1' in env # Has key1 been set?
|
|
|
|
False
|
|
|
|
>>> env.key1 = 'value 1'
|
|
|
|
>>> 'key1' in env
|
|
|
|
True
|
|
|
|
>>> env.key2 = 'value 2'
|
|
|
|
>>> len(env) # How many variables have been set?
|
|
|
|
2
|
|
|
|
>>> list(env) # What variables have been set?
|
|
|
|
['key1', 'key2']
|
|
|
|
|
|
|
|
Lastly, in addition to all the handy container functionality, the `Env`
|
|
|
|
class provides high-level methods for bootstraping a fresh `Env` instance
|
|
|
|
into one containing all the run-time and configuration information needed
|
|
|
|
by the built-in freeIPA plugins.
|
|
|
|
|
|
|
|
These are the `Env` bootstraping methods, in the order they must be called:
|
|
|
|
|
|
|
|
1. `Env._bootstrap()` - initialize the run-time variables and then
|
|
|
|
merge-in variables specified on the command-line.
|
|
|
|
|
|
|
|
2. `Env._finalize_core()` - merge-in variables from the configuration
|
|
|
|
files and then merge-in variables from the internal defaults, after
|
|
|
|
which at least all the standard variables will be set. After this
|
2009-01-05 04:28:27 -06:00
|
|
|
method is called, the plugins will be loaded, during which
|
|
|
|
third-party plugins can merge-in defaults for additional variables
|
|
|
|
they use (likely using the `Env._merge()` method).
|
2008-12-23 02:11:03 -06:00
|
|
|
|
|
|
|
3. `Env._finalize()` - one last chance to merge-in variables and then
|
|
|
|
the instance is locked. After this method is called, no more
|
|
|
|
environment variables can be set during the remaining life of the
|
|
|
|
process.
|
|
|
|
|
2009-01-05 04:28:27 -06:00
|
|
|
However, normally none of these three bootstraping methods are called
|
|
|
|
directly and instead only `plugable.API.bootstrap()` is called, which itself
|
|
|
|
takes care of correctly calling the `Env` bootstrapping methods.
|
2008-10-24 02:51:36 -05:00
|
|
|
"""
|
|
|
|
|
|
|
|
__locked = False
|
|
|
|
|
2009-05-13 02:04:35 -05:00
|
|
|
def __init__(self, **initialize):
|
2008-10-24 02:51:36 -05:00
|
|
|
object.__setattr__(self, '_Env__d', {})
|
2008-10-24 16:35:58 -05:00
|
|
|
object.__setattr__(self, '_Env__done', set())
|
2009-05-13 02:04:35 -05:00
|
|
|
if initialize:
|
|
|
|
self._merge(**initialize)
|
2008-10-24 16:07:07 -05:00
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
def __lock__(self):
|
|
|
|
"""
|
|
|
|
Prevent further changes to environment.
|
|
|
|
"""
|
|
|
|
if self.__locked is True:
|
2015-08-24 05:40:33 -05:00
|
|
|
raise Exception(
|
2008-12-23 02:11:03 -06:00
|
|
|
'%s.__lock__() already called' % self.__class__.__name__
|
|
|
|
)
|
|
|
|
object.__setattr__(self, '_Env__locked', True)
|
|
|
|
|
|
|
|
def __islocked__(self):
|
|
|
|
"""
|
|
|
|
Return ``True`` if locked.
|
|
|
|
"""
|
|
|
|
return self.__locked
|
|
|
|
|
2008-12-22 18:29:11 -06:00
|
|
|
def __setattr__(self, name, value):
|
|
|
|
"""
|
|
|
|
Set the attribute named ``name`` to ``value``.
|
|
|
|
|
|
|
|
This just calls `Env.__setitem__()`.
|
|
|
|
"""
|
|
|
|
self[name] = value
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
"""
|
|
|
|
Set ``key`` to ``value``.
|
|
|
|
"""
|
|
|
|
if self.__locked:
|
|
|
|
raise AttributeError(
|
2008-12-22 22:02:43 -06:00
|
|
|
SET_ERROR % (self.__class__.__name__, key, value)
|
2008-12-22 18:29:11 -06:00
|
|
|
)
|
2008-12-30 01:45:48 -06:00
|
|
|
check_name(key)
|
2008-12-22 18:29:11 -06:00
|
|
|
if key in self.__d:
|
|
|
|
raise AttributeError(OVERRIDE_ERROR %
|
|
|
|
(self.__class__.__name__, key, self.__d[key], value)
|
|
|
|
)
|
2008-12-23 02:11:03 -06:00
|
|
|
assert not hasattr(self, key)
|
2015-08-10 11:29:33 -05:00
|
|
|
if isinstance(value, six.string_types):
|
2010-02-11 08:05:13 -06:00
|
|
|
value = value.strip()
|
2015-09-17 11:46:14 -05:00
|
|
|
if isinstance(value, bytes):
|
2010-02-11 08:05:13 -06:00
|
|
|
value = value.decode('utf-8')
|
2008-12-22 18:29:11 -06:00
|
|
|
m = {
|
|
|
|
'True': True,
|
|
|
|
'False': False,
|
|
|
|
'None': None,
|
2008-12-23 02:11:03 -06:00
|
|
|
'': None,
|
2008-12-22 18:29:11 -06:00
|
|
|
}
|
|
|
|
if value in m:
|
|
|
|
value = m[value]
|
|
|
|
elif value.isdigit():
|
|
|
|
value = int(value)
|
2014-06-13 05:40:32 -05:00
|
|
|
elif key == 'basedn':
|
Use DN objects instead of strings
* Convert every string specifying a DN into a DN object
* Every place a dn was manipulated in some fashion it was replaced by
the use of DN operators
* Add new DNParam parameter type for parameters which are DN's
* DN objects are used 100% of the time throughout the entire data
pipeline whenever something is logically a dn.
* Many classes now enforce DN usage for their attributes which are
dn's. This is implmented via ipautil.dn_attribute_property(). The
only permitted types for a class attribute specified to be a DN are
either None or a DN object.
* Require that every place a dn is used it must be a DN object.
This translates into lot of::
assert isinstance(dn, DN)
sprinkled through out the code. Maintaining these asserts is
valuable to preserve DN type enforcement. The asserts can be
disabled in production.
The goal of 100% DN usage 100% of the time has been realized, these
asserts are meant to preserve that.
The asserts also proved valuable in detecting functions which did
not obey their function signatures, such as the baseldap pre and
post callbacks.
* Moved ipalib.dn to ipapython.dn because DN class is shared with all
components, not just the server which uses ipalib.
* All API's now accept DN's natively, no need to convert to str (or
unicode).
* Removed ipalib.encoder and encode/decode decorators. Type conversion
is now explicitly performed in each IPASimpleLDAPObject method which
emulates a ldap.SimpleLDAPObject method.
* Entity & Entry classes now utilize DN's
* Removed __getattr__ in Entity & Entity clases. There were two
problems with it. It presented synthetic Python object attributes
based on the current LDAP data it contained. There is no way to
validate synthetic attributes using code checkers, you can't search
the code to find LDAP attribute accesses (because synthetic
attriutes look like Python attributes instead of LDAP data) and
error handling is circumscribed. Secondly __getattr__ was hiding
Python internal methods which broke class semantics.
* Replace use of methods inherited from ldap.SimpleLDAPObject via
IPAdmin class with IPAdmin methods. Directly using inherited methods
was causing us to bypass IPA logic. Mostly this meant replacing the
use of search_s() with getEntry() or getList(). Similarly direct
access of the LDAP data in classes using IPAdmin were replaced with
calls to getValue() or getValues().
* Objects returned by ldap2.find_entries() are now compatible with
either the python-ldap access methodology or the Entity/Entry access
methodology.
* All ldap operations now funnel through the common
IPASimpleLDAPObject giving us a single location where we interface
to python-ldap and perform conversions.
* The above 4 modifications means we've greatly reduced the
proliferation of multiple inconsistent ways to perform LDAP
operations. We are well on the way to having a single API in IPA for
doing LDAP (a long range goal).
* All certificate subject bases are now DN's
* DN objects were enhanced thusly:
- find, rfind, index, rindex, replace and insert methods were added
- AVA, RDN and DN classes were refactored in immutable and mutable
variants, the mutable variants are EditableAVA, EditableRDN and
EditableDN. By default we use the immutable variants preserving
important semantics. To edit a DN cast it to an EditableDN and
cast it back to DN when done editing. These issues are fully
described in other documentation.
- first_key_match was removed
- DN equalty comparison permits comparison to a basestring
* Fixed ldapupdate to work with DN's. This work included:
- Enhance test_updates.py to do more checking after applying
update. Add test for update_from_dict(). Convert code to use
unittest classes.
- Consolidated duplicate code.
- Moved code which should have been in the class into the class.
- Fix the handling of the 'deleteentry' update action. It's no longer
necessary to supply fake attributes to make it work. Detect case
where subsequent update applies a change to entry previously marked
for deletetion. General clean-up and simplification of the
'deleteentry' logic.
- Rewrote a couple of functions to be clearer and more Pythonic.
- Added documentation on the data structure being used.
- Simplfy the use of update_from_dict()
* Removed all usage of get_schema() which was being called prior to
accessing the .schema attribute of an object. If a class is using
internal lazy loading as an optimization it's not right to require
users of the interface to be aware of internal
optimization's. schema is now a property and when the schema
property is accessed it calls a private internal method to perform
the lazy loading.
* Added SchemaCache class to cache the schema's from individual
servers. This was done because of the observation we talk to
different LDAP servers, each of which may have it's own
schema. Previously we globally cached the schema from the first
server we connected to and returned that schema in all contexts. The
cache includes controls to invalidate it thus forcing a schema
refresh.
* Schema caching is now senstive to the run time context. During
install and upgrade the schema can change leading to errors due to
out-of-date cached schema. The schema cache is refreshed in these
contexts.
* We are aware of the LDAP syntax of all LDAP attributes. Every
attribute returned from an LDAP operation is passed through a
central table look-up based on it's LDAP syntax. The table key is
the LDAP syntax it's value is a Python callable that returns a
Python object matching the LDAP syntax. There are a handful of LDAP
attributes whose syntax is historically incorrect
(e.g. DistguishedNames that are defined as DirectoryStrings). The
table driven conversion mechanism is augmented with a table of
hard coded exceptions.
Currently only the following conversions occur via the table:
- dn's are converted to DN objects
- binary objects are converted to Python str objects (IPA
convention).
- everything else is converted to unicode using UTF-8 decoding (IPA
convention).
However, now that the table driven conversion mechanism is in place
it would be trivial to do things such as converting attributes
which have LDAP integer syntax into a Python integer, etc.
* Expected values in the unit tests which are a DN no longer need to
use lambda expressions to promote the returned value to a DN for
equality comparison. The return value is automatically promoted to
a DN. The lambda expressions have been removed making the code much
simpler and easier to read.
* Add class level logging to a number of classes which did not support
logging, less need for use of root_logger.
* Remove ipaserver/conn.py, it was unused.
* Consolidated duplicate code wherever it was found.
* Fixed many places that used string concatenation to form a new
string rather than string formatting operators. This is necessary
because string formatting converts it's arguments to a string prior
to building the result string. You can't concatenate a string and a
non-string.
* Simplify logic in rename_managed plugin. Use DN operators to edit
dn's.
* The live version of ipa-ldap-updater did not generate a log file.
The offline version did, now both do.
https://fedorahosted.org/freeipa/ticket/1670
https://fedorahosted.org/freeipa/ticket/1671
https://fedorahosted.org/freeipa/ticket/1672
https://fedorahosted.org/freeipa/ticket/1673
https://fedorahosted.org/freeipa/ticket/1674
https://fedorahosted.org/freeipa/ticket/1392
https://fedorahosted.org/freeipa/ticket/2872
2012-05-13 06:36:35 -05:00
|
|
|
value = DN(value)
|
2015-09-17 10:56:45 -05:00
|
|
|
assert type(value) in (unicode, int, float, bool, type(None), DN)
|
2008-12-22 18:29:11 -06:00
|
|
|
object.__setattr__(self, key, value)
|
|
|
|
self.__d[key] = value
|
|
|
|
|
2008-12-22 22:02:43 -06:00
|
|
|
def __getitem__(self, key):
|
|
|
|
"""
|
|
|
|
Return the value corresponding to ``key``.
|
|
|
|
"""
|
|
|
|
return self.__d[key]
|
|
|
|
|
|
|
|
def __delattr__(self, name):
|
|
|
|
"""
|
2009-01-05 04:28:27 -06:00
|
|
|
Raise an ``AttributeError`` (deletion is never allowed).
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> env = Env()
|
|
|
|
>>> env.name = 'A value'
|
|
|
|
>>> del env.name
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
AttributeError: locked: cannot delete Env.name
|
2008-12-22 22:02:43 -06:00
|
|
|
"""
|
|
|
|
raise AttributeError(
|
|
|
|
DEL_ERROR % (self.__class__.__name__, name)
|
|
|
|
)
|
|
|
|
|
2008-12-23 02:11:03 -06:00
|
|
|
def __contains__(self, key):
|
|
|
|
"""
|
|
|
|
Return True if instance contains ``key``; otherwise return False.
|
|
|
|
"""
|
|
|
|
return key in self.__d
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
"""
|
|
|
|
Return number of variables currently set.
|
|
|
|
"""
|
|
|
|
return len(self.__d)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
"""
|
|
|
|
Iterate through keys in ascending order.
|
|
|
|
"""
|
|
|
|
for key in sorted(self.__d):
|
|
|
|
yield key
|
|
|
|
|
2008-12-30 01:45:48 -06:00
|
|
|
def _merge(self, **kw):
|
|
|
|
"""
|
2008-12-30 04:11:45 -06:00
|
|
|
Merge variables from ``kw`` into the environment.
|
2008-12-30 01:45:48 -06:00
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
Any variables in ``kw`` that have already been set will be ignored
|
|
|
|
(meaning this method will *not* try to override them, which would raise
|
|
|
|
an exception).
|
2008-12-30 01:45:48 -06:00
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
This method returns a ``(num_set, num_total)`` tuple containing first
|
|
|
|
the number of variables that were actually set, and second the total
|
|
|
|
number of variables that were provided.
|
2008-12-30 01:45:48 -06:00
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> env = Env()
|
2008-12-30 04:11:45 -06:00
|
|
|
>>> env._merge(one=1, two=2)
|
2008-12-30 01:45:48 -06:00
|
|
|
(2, 2)
|
2008-12-30 04:11:45 -06:00
|
|
|
>>> env._merge(one=1, three=3)
|
2008-12-30 01:45:48 -06:00
|
|
|
(1, 2)
|
2008-12-30 04:11:45 -06:00
|
|
|
>>> env._merge(one=1, two=2, three=3)
|
2008-12-30 01:45:48 -06:00
|
|
|
(0, 3)
|
2008-12-30 04:11:45 -06:00
|
|
|
|
|
|
|
Also see `Env._merge_from_file()`.
|
2008-12-30 14:52:36 -06:00
|
|
|
|
|
|
|
:param kw: Variables provides as keyword arguments.
|
2008-12-30 01:45:48 -06:00
|
|
|
"""
|
|
|
|
i = 0
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
for (key, value) in kw.items():
|
2008-12-30 01:45:48 -06:00
|
|
|
if key not in self:
|
|
|
|
self[key] = value
|
|
|
|
i += 1
|
|
|
|
return (i, len(kw))
|
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
def _merge_from_file(self, config_file):
|
2008-12-30 01:45:48 -06:00
|
|
|
"""
|
2008-12-30 04:11:45 -06:00
|
|
|
Merge variables from ``config_file`` into the environment.
|
|
|
|
|
|
|
|
Any variables in ``config_file`` that have already been set will be
|
|
|
|
ignored (meaning this method will *not* try to override them, which
|
|
|
|
would raise an exception).
|
|
|
|
|
|
|
|
If ``config_file`` does not exist or is not a regular file, or if there
|
|
|
|
is an error parsing ``config_file``, ``None`` is returned.
|
|
|
|
|
|
|
|
Otherwise this method returns a ``(num_set, num_total)`` tuple
|
|
|
|
containing first the number of variables that were actually set, and
|
|
|
|
second the total number of variables found in ``config_file``.
|
|
|
|
|
|
|
|
Also see `Env._merge()`.
|
2008-12-30 14:52:36 -06:00
|
|
|
|
2016-09-27 10:23:17 -05:00
|
|
|
:param config_file: Path of the configuration file to load.
|
2008-12-30 01:45:48 -06:00
|
|
|
"""
|
2008-12-30 04:11:45 -06:00
|
|
|
if not path.isfile(config_file):
|
2008-12-30 01:45:48 -06:00
|
|
|
return
|
|
|
|
parser = RawConfigParser()
|
|
|
|
try:
|
2008-12-30 04:11:45 -06:00
|
|
|
parser.read(config_file)
|
2008-12-30 01:45:48 -06:00
|
|
|
except ParsingError:
|
|
|
|
return
|
|
|
|
if not parser.has_section(CONFIG_SECTION):
|
|
|
|
parser.add_section(CONFIG_SECTION)
|
|
|
|
items = parser.items(CONFIG_SECTION)
|
|
|
|
if len(items) == 0:
|
2008-12-30 04:11:45 -06:00
|
|
|
return (0, 0)
|
2008-12-30 01:45:48 -06:00
|
|
|
i = 0
|
|
|
|
for (key, value) in items:
|
|
|
|
if key not in self:
|
|
|
|
self[key] = value
|
|
|
|
i += 1
|
2010-10-15 14:03:51 -05:00
|
|
|
if 'config_loaded' not in self: # we loaded at least 1 file
|
|
|
|
self['config_loaded'] = True
|
2008-12-30 01:45:48 -06:00
|
|
|
return (i, len(items))
|
|
|
|
|
2009-05-11 03:34:52 -05:00
|
|
|
def _join(self, key, *parts):
|
|
|
|
"""
|
|
|
|
Append path components in ``parts`` to base path ``self[key]``.
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
>>> env = Env()
|
|
|
|
>>> env.home = '/people/joe'
|
|
|
|
>>> env._join('home', 'Music', 'favourites')
|
2010-02-22 13:29:26 -06:00
|
|
|
u'/people/joe/Music/favourites'
|
2009-05-11 03:34:52 -05:00
|
|
|
"""
|
|
|
|
if key in self and self[key] is not None:
|
|
|
|
return path.join(self[key], *parts)
|
|
|
|
|
2008-10-24 21:02:14 -05:00
|
|
|
def __doing(self, name):
|
2008-10-24 16:35:58 -05:00
|
|
|
if name in self.__done:
|
2015-08-24 05:40:33 -05:00
|
|
|
raise Exception(
|
2008-10-24 16:35:58 -05:00
|
|
|
'%s.%s() already called' % (self.__class__.__name__, name)
|
|
|
|
)
|
|
|
|
self.__done.add(name)
|
|
|
|
|
2008-10-24 21:02:14 -05:00
|
|
|
def __do_if_not_done(self, name):
|
|
|
|
if name not in self.__done:
|
|
|
|
getattr(self, name)()
|
|
|
|
|
|
|
|
def _isdone(self, name):
|
|
|
|
return name in self.__done
|
|
|
|
|
2008-10-24 16:07:07 -05:00
|
|
|
def _bootstrap(self, **overrides):
|
|
|
|
"""
|
|
|
|
Initialize basic environment.
|
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
This method will perform the following steps:
|
|
|
|
|
|
|
|
1. Initialize certain run-time variables. These run-time variables
|
|
|
|
are strictly determined by the external environment the process
|
|
|
|
is running in; they cannot be specified on the command-line nor
|
|
|
|
in the configuration files.
|
|
|
|
|
|
|
|
2. Merge-in the variables in ``overrides`` by calling
|
|
|
|
`Env._merge()`. The intended use of ``overrides`` is to merge-in
|
|
|
|
variables specified on the command-line.
|
|
|
|
|
2008-12-30 14:52:36 -06:00
|
|
|
3. Intelligently fill-in the *in_tree*, *context*, *conf*, and
|
2008-12-30 16:14:33 -06:00
|
|
|
*conf_default* variables if they haven't been set already.
|
2008-12-30 04:11:45 -06:00
|
|
|
|
|
|
|
Also see `Env._finalize_core()`, the next method in the bootstrap
|
|
|
|
sequence.
|
|
|
|
|
|
|
|
:param overrides: Variables specified via command-line options.
|
2008-10-24 16:07:07 -05:00
|
|
|
"""
|
2008-10-24 21:02:14 -05:00
|
|
|
self.__doing('_bootstrap')
|
2008-12-23 00:09:35 -06:00
|
|
|
|
2009-05-11 03:34:52 -05:00
|
|
|
# Set run-time variables (cannot be overridden):
|
2008-12-23 00:09:35 -06:00
|
|
|
self.ipalib = path.dirname(path.abspath(__file__))
|
|
|
|
self.site_packages = path.dirname(self.ipalib)
|
|
|
|
self.script = path.abspath(sys.argv[0])
|
|
|
|
self.bin = path.dirname(self.script)
|
2009-01-30 21:53:32 -06:00
|
|
|
self.home = os.environ.get('HOME', None)
|
2009-05-11 03:34:52 -05:00
|
|
|
|
|
|
|
# Merge in overrides:
|
2008-12-30 04:11:45 -06:00
|
|
|
self._merge(**overrides)
|
2009-05-11 03:34:52 -05:00
|
|
|
|
|
|
|
# Determine if running in source tree:
|
2008-10-24 16:07:07 -05:00
|
|
|
if 'in_tree' not in self:
|
2016-06-02 02:58:52 -05:00
|
|
|
self.in_tree = (
|
2009-05-11 03:34:52 -05:00
|
|
|
self.bin == self.site_packages
|
|
|
|
and path.isfile(path.join(self.bin, 'setup.py'))
|
2016-06-02 02:58:52 -05:00
|
|
|
)
|
2011-01-19 10:24:31 -06:00
|
|
|
if self.in_tree and 'mode' not in self:
|
|
|
|
self.mode = 'developer'
|
|
|
|
|
2009-05-11 03:34:52 -05:00
|
|
|
# Set dot_ipa:
|
|
|
|
if 'dot_ipa' not in self:
|
|
|
|
self.dot_ipa = self._join('home', '.ipa')
|
|
|
|
|
|
|
|
# Set context
|
2008-10-24 16:07:07 -05:00
|
|
|
if 'context' not in self:
|
|
|
|
self.context = 'default'
|
2009-05-11 03:34:52 -05:00
|
|
|
|
|
|
|
# Set confdir:
|
|
|
|
if 'confdir' not in self:
|
|
|
|
if self.in_tree:
|
|
|
|
self.confdir = self.dot_ipa
|
|
|
|
else:
|
|
|
|
self.confdir = path.join('/', 'etc', 'ipa')
|
|
|
|
|
|
|
|
# Set conf (config file for this context):
|
2008-10-24 16:07:07 -05:00
|
|
|
if 'conf' not in self:
|
2009-05-11 03:34:52 -05:00
|
|
|
self.conf = self._join('confdir', '%s.conf' % self.context)
|
2008-10-24 16:07:07 -05:00
|
|
|
|
2009-05-11 03:34:52 -05:00
|
|
|
# Set conf_default (default base config used in all contexts):
|
|
|
|
if 'conf_default' not in self:
|
|
|
|
self.conf_default = self._join('confdir', 'default.conf')
|
2009-01-30 21:53:32 -06:00
|
|
|
|
2011-11-03 05:42:17 -05:00
|
|
|
# Set plugins_on_demand:
|
|
|
|
if 'plugins_on_demand' not in self:
|
|
|
|
self.plugins_on_demand = (self.context == 'cli')
|
|
|
|
|
2008-10-24 21:02:14 -05:00
|
|
|
def _finalize_core(self, **defaults):
|
|
|
|
"""
|
|
|
|
Complete initialization of standard IPA environment.
|
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
This method will perform the following steps:
|
2008-10-24 21:02:14 -05:00
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
1. Call `Env._bootstrap()` if it hasn't already been called.
|
|
|
|
|
|
|
|
2. Merge-in variables from the configuration file ``self.conf``
|
|
|
|
(if it exists) by calling `Env._merge_from_file()`.
|
|
|
|
|
|
|
|
3. Merge-in variables from the defaults configuration file
|
|
|
|
``self.conf_default`` (if it exists) by calling
|
|
|
|
`Env._merge_from_file()`.
|
|
|
|
|
2012-12-19 03:25:24 -06:00
|
|
|
4. Intelligently fill-in the *in_server* , *logdir*, *log*, and
|
|
|
|
*jsonrpc_uri* variables if they haven't already been set.
|
2008-12-30 04:11:45 -06:00
|
|
|
|
2008-12-30 14:52:36 -06:00
|
|
|
5. Merge-in the variables in ``defaults`` by calling `Env._merge()`.
|
|
|
|
In normal circumstances ``defaults`` will simply be those
|
|
|
|
specified in `constants.DEFAULT_CONFIG`.
|
2008-12-30 04:11:45 -06:00
|
|
|
|
2008-12-30 14:52:36 -06:00
|
|
|
After this method is called, all the environment variables used by all
|
|
|
|
the built-in plugins will be available. As such, this method should be
|
|
|
|
called *before* any plugins are loaded.
|
2008-10-24 21:02:14 -05:00
|
|
|
|
|
|
|
After this method has finished, the `Env` instance is still writable
|
2008-12-23 02:28:00 -06:00
|
|
|
so that 3rd-party plugins can set variables they may require as the
|
|
|
|
plugins are registered.
|
2008-12-30 04:11:45 -06:00
|
|
|
|
|
|
|
Also see `Env._finalize()`, the final method in the bootstrap sequence.
|
2008-12-30 14:52:36 -06:00
|
|
|
|
|
|
|
:param defaults: Internal defaults for all built-in variables.
|
2008-10-24 21:02:14 -05:00
|
|
|
"""
|
|
|
|
self.__doing('_finalize_core')
|
|
|
|
self.__do_if_not_done('_bootstrap')
|
2009-05-11 03:34:52 -05:00
|
|
|
|
|
|
|
# Merge in context config file and then default config file:
|
2008-11-07 03:26:38 -06:00
|
|
|
if self.__d.get('mode', None) != 'dummy':
|
2008-12-29 22:23:34 -06:00
|
|
|
self._merge_from_file(self.conf)
|
|
|
|
self._merge_from_file(self.conf_default)
|
2009-05-11 03:34:52 -05:00
|
|
|
|
|
|
|
# Determine if in_server:
|
2008-10-24 21:02:14 -05:00
|
|
|
if 'in_server' not in self:
|
|
|
|
self.in_server = (self.context == 'server')
|
2009-05-11 03:34:52 -05:00
|
|
|
|
|
|
|
# Set logdir:
|
|
|
|
if 'logdir' not in self:
|
|
|
|
if self.in_tree or not self.in_server:
|
|
|
|
self.logdir = self._join('dot_ipa', 'log')
|
2008-10-24 21:02:14 -05:00
|
|
|
else:
|
2009-05-11 03:34:52 -05:00
|
|
|
self.logdir = path.join('/', 'var', 'log', 'ipa')
|
|
|
|
|
|
|
|
# Set log file:
|
|
|
|
if 'log' not in self:
|
|
|
|
self.log = self._join('logdir', '%s.log' % self.context)
|
|
|
|
|
2012-12-19 03:25:24 -06:00
|
|
|
# Derive jsonrpc_uri from xmlrpc_uri
|
|
|
|
if 'jsonrpc_uri' not in self:
|
|
|
|
if 'xmlrpc_uri' in self:
|
|
|
|
xmlrpc_uri = self.xmlrpc_uri
|
|
|
|
else:
|
|
|
|
xmlrpc_uri = defaults.get('xmlrpc_uri')
|
|
|
|
if xmlrpc_uri:
|
|
|
|
(scheme, netloc, uripath, params, query, fragment
|
2015-09-14 05:52:29 -05:00
|
|
|
) = urlparse(xmlrpc_uri)
|
2012-12-19 03:25:24 -06:00
|
|
|
uripath = uripath.replace('/xml', '/json', 1)
|
2015-09-14 05:52:29 -05:00
|
|
|
self.jsonrpc_uri = urlunparse((
|
2012-12-19 03:25:24 -06:00
|
|
|
scheme, netloc, uripath, params, query, fragment))
|
|
|
|
|
2016-06-21 07:41:17 -05:00
|
|
|
if 'server' not in self:
|
|
|
|
if 'jsonrpc_uri' in self:
|
|
|
|
jsonrpc_uri = self.jsonrpc_uri
|
|
|
|
else:
|
|
|
|
jsonrpc_uri = defaults.get('jsonrpc_uri')
|
|
|
|
if jsonrpc_uri:
|
|
|
|
parsed = urlparse(jsonrpc_uri)
|
|
|
|
self.server = parsed.netloc
|
|
|
|
|
2008-12-30 01:45:48 -06:00
|
|
|
self._merge(**defaults)
|
2008-10-24 21:02:14 -05:00
|
|
|
|
2008-10-24 21:21:27 -05:00
|
|
|
def _finalize(self, **lastchance):
|
2008-10-24 21:02:14 -05:00
|
|
|
"""
|
|
|
|
Finalize and lock environment.
|
|
|
|
|
2008-12-30 04:11:45 -06:00
|
|
|
This method will perform the following steps:
|
|
|
|
|
|
|
|
1. Call `Env._finalize_core()` if it hasn't already been called.
|
|
|
|
|
|
|
|
2. Merge-in the variables in ``lastchance`` by calling
|
|
|
|
`Env._merge()`.
|
|
|
|
|
|
|
|
3. Lock this `Env` instance, after which no more environment
|
|
|
|
variables can be set on this instance. Aside from unit-tests
|
|
|
|
and example code, normally only one `Env` instance is created,
|
|
|
|
which means that after this step, no more variables can be set
|
|
|
|
during the remaining life of the process.
|
|
|
|
|
2008-12-23 02:28:00 -06:00
|
|
|
This method should be called after all plugins have been loaded and
|
2008-12-30 04:11:45 -06:00
|
|
|
after `plugable.API.finalize()` has been called.
|
2008-12-30 14:52:36 -06:00
|
|
|
|
|
|
|
:param lastchance: Any final variables to merge-in before locking.
|
2008-10-24 21:02:14 -05:00
|
|
|
"""
|
|
|
|
self.__doing('_finalize')
|
|
|
|
self.__do_if_not_done('_finalize_core')
|
2008-12-30 04:11:45 -06:00
|
|
|
self._merge(**lastchance)
|
2008-10-24 21:02:14 -05:00
|
|
|
self.__lock__()
|