abfaa01984a40b70d77362a45f4f67344c644dd9
[tiramisu.git] / tiramisu / config.py
1 # -*- coding: utf-8 -*-
2 "pretty small and local configuration management tool"
3 # Copyright (C) 2012-2013 Team tiramisu (see AUTHORS for all contributors)
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 #
19 # The original `Config` design model is unproudly borrowed from
20 # the rough pypy's guys: http://codespeak.net/svn/pypy/dist/pypy/config/
21 # the whole pypy projet is under MIT licence
22 # ____________________________________________________________
23 from time import time
24 from tiramisu.error import PropertiesOptionError, ConfigError
25 from tiramisu.option import OptionDescription, Option, SymLinkOption, \
26     BaseInformation
27 from tiramisu.setting import groups, Settings, default_encoding, storage_type
28 from tiramisu.value import Values
29 from tiramisu.i18n import _
30
31
32 def gen_id(config):
33     return str(id(config)) + str(time())
34
35
36 class SubConfig(BaseInformation):
37     "sub configuration management entry"
38     __slots__ = ('_impl_context', '_impl_descr')
39
40     def __init__(self, descr, context):
41         """ Configuration option management master class
42
43         :param descr: describes the configuration schema
44         :type descr: an instance of ``option.OptionDescription``
45         :param context: the current root config
46         :type context: `Config`
47         """
48         # main option description
49         if not isinstance(descr, OptionDescription):
50             raise ValueError(_('descr must be an optiondescription, not {0}'
51                                ).format(type(descr)))
52         self._impl_descr = descr
53         # sub option descriptions
54         if not isinstance(context, SubConfig):
55             raise ValueError('context must be a SubConfig')
56         self._impl_context = context
57
58     def cfgimpl_reset_cache(self, only_expired=False, only=('values',
59                                                             'settings')):
60         self.cfgimpl_get_context().cfgimpl_reset_cache(only_expired, only)
61
62     def cfgimpl_get_home_by_path(self, path, force_permissive=False,
63                                  force_properties=None):
64         """:returns: tuple (config, name)"""
65         path = path.split('.')
66         for step in path[:-1]:
67             self = self._getattr(step,
68                                  force_permissive=force_permissive,
69                                  force_properties=force_properties)
70         return self, path[-1]
71
72     def __hash__(self):
73         return hash(self.cfgimpl_get_description().impl_getkey(self))
74
75     def __eq__(self, other):
76         "Config's comparison"
77         if not isinstance(other, Config):
78             return False
79         return self.cfgimpl_get_description().impl_getkey(self) == \
80             other.cfgimpl_get_description().impl_getkey(other)
81
82     def __ne__(self, other):
83         "Config's comparison"
84         if not isinstance(other, Config):
85             return False
86         return not self == other
87
88     # ______________________________________________________________________
89     def __iter__(self):
90         """Pythonesque way of parsing group's ordered options.
91         iteration only on Options (not OptionDescriptions)"""
92         for child in self.cfgimpl_get_description().impl_getchildren():
93             if not isinstance(child, OptionDescription):
94                 try:
95                     yield child._name, getattr(self, child._name)
96                 except GeneratorExit:
97                     raise StopIteration
98                 except PropertiesOptionError:
99                     pass  # option with properties
100
101     def iter_all(self):
102         """A way of parsing options **and** groups.
103         iteration on Options and OptionDescriptions."""
104         for child in self.cfgimpl_get_description().impl_getchildren():
105             try:
106                 yield child._name, getattr(self, child._name)
107             except GeneratorExit:
108                 raise StopIteration
109             except PropertiesOptionError:
110                 pass  # option with properties
111
112     def iter_groups(self, group_type=None):
113         """iteration on groups objects only.
114         All groups are returned if `group_type` is `None`, otherwise the groups
115         can be filtered by categories (families, or whatever).
116
117         :param group_type: if defined, is an instance of `groups.GroupType`
118                            or `groups.MasterGroupType` that lives in
119                            `setting.groups`
120         """
121         if group_type is not None:
122             if not isinstance(group_type, groups.GroupType):
123                 raise TypeError(_("unknown group_type: {0}").format(group_type))
124         for child in self.cfgimpl_get_description().impl_getchildren():
125             if isinstance(child, OptionDescription):
126                 try:
127                     if group_type is None or (group_type is not None and
128                                               child.impl_get_group_type()
129                                               == group_type):
130                         yield child._name, getattr(self, child._name)
131                 except GeneratorExit:
132                     raise StopIteration
133                 except PropertiesOptionError:
134                     pass
135     # ______________________________________________________________________
136
137     def __str__(self):
138         "Config's string representation"
139         lines = []
140         for name, grp in self.iter_groups():
141             lines.append("[{0}]".format(name))
142         for name, value in self:
143             try:
144                 lines.append("{0} = {1}".format(name, value))
145             except UnicodeEncodeError:
146                 lines.append("{0} = {1}".format(name,
147                                                 value.encode(default_encoding)))
148             except PropertiesOptionError:
149                 pass
150         return '\n'.join(lines)
151
152     __repr__ = __str__
153
154     def cfgimpl_get_context(self):
155         return self._impl_context
156
157     def cfgimpl_get_description(self):
158         if self._impl_descr is None:
159             raise ConfigError(_('no option description found for this config'
160                                 ' (may be metaconfig without meta)'))
161         else:
162             return self._impl_descr
163
164     def cfgimpl_get_settings(self):
165         return self.cfgimpl_get_context()._impl_settings
166
167     def cfgimpl_get_values(self):
168         return self.cfgimpl_get_context()._impl_values
169
170     # ____________________________________________________________
171     # attribute methods
172     def __setattr__(self, name, value):
173         "attribute notation mechanism for the setting of the value of an option"
174         if name.startswith('_impl_'):
175             #self.__dict__[name] = value
176             object.__setattr__(self, name, value)
177             return
178         self._setattr(name, value)
179
180     def _setattr(self, name, value, force_permissive=False):
181         if '.' in name:
182             homeconfig, name = self.cfgimpl_get_home_by_path(name)
183             return homeconfig.__setattr__(name, value)
184         child = getattr(self.cfgimpl_get_description(), name)
185         if not isinstance(child, SymLinkOption):
186             self.cfgimpl_get_values().setitem(child, value,
187                                               force_permissive=force_permissive)
188         else:
189             context = self.cfgimpl_get_context()
190             path = context.cfgimpl_get_description().impl_get_path_by_opt(
191                 child._opt)
192             context._setattr(path, value, force_permissive=force_permissive)
193
194     def __delattr__(self, name):
195         child = getattr(self.cfgimpl_get_description(), name)
196         del(self.cfgimpl_get_values()[child])
197
198     def __getattr__(self, name):
199         return self._getattr(name)
200
201     def _getattr(self, name, force_permissive=False, force_properties=None,
202                  validate=True):
203         """
204         attribute notation mechanism for accessing the value of an option
205         :param name: attribute name
206         :return: option's value if name is an option name, OptionDescription
207                  otherwise
208         """
209         # attribute access by passing a path,
210         # for instance getattr(self, "creole.general.family.adresse_ip_eth0")
211         if '.' in name:
212             homeconfig, name = self.cfgimpl_get_home_by_path(
213                 name, force_permissive=force_permissive,
214                 force_properties=force_properties)
215             return homeconfig._getattr(name, force_permissive=force_permissive,
216                                        force_properties=force_properties,
217                                        validate=validate)
218         # special attributes
219         if name.startswith('_impl_') or name.startswith('cfgimpl_') \
220                 or name.startswith('impl_'):
221             # if it were in __dict__ it would have been found already
222             return object.__getattribute__(self, name)
223         opt_or_descr = getattr(self.cfgimpl_get_description(), name)
224         # symlink options
225         if isinstance(opt_or_descr, SymLinkOption):
226             context = self.cfgimpl_get_context()
227             path = context.cfgimpl_get_description().impl_get_path_by_opt(
228                 opt_or_descr._opt)
229             return context._getattr(path, validate=validate,
230                                     force_properties=force_properties,
231                                     force_permissive=force_permissive)
232         elif isinstance(opt_or_descr, OptionDescription):
233             self.cfgimpl_get_settings().validate_properties(
234                 opt_or_descr, True, False, force_permissive=force_permissive,
235                 force_properties=force_properties)
236             return SubConfig(opt_or_descr, self.cfgimpl_get_context())
237         else:
238             return self.cfgimpl_get_values().getitem(
239                 opt_or_descr,
240                 validate=validate,
241                 force_properties=force_properties,
242                 force_permissive=force_permissive)
243
244     def find(self, bytype=None, byname=None, byvalue=None, type_='option'):
245         """
246             finds a list of options recursively in the config
247
248             :param bytype: Option class (BoolOption, StrOption, ...)
249             :param byname: filter by Option._name
250             :param byvalue: filter by the option's value
251             :returns: list of matching Option objects
252         """
253         return self.cfgimpl_get_context()._find(bytype, byname, byvalue,
254                                                 first=False,
255                                                 type_=type_,
256                                                 _subpath=self.cfgimpl_get_path()
257                                                 )
258
259     def find_first(self, bytype=None, byname=None, byvalue=None,
260                    type_='option', display_error=True):
261         """
262             finds an option recursively in the config
263
264             :param bytype: Option class (BoolOption, StrOption, ...)
265             :param byname: filter by Option._name
266             :param byvalue: filter by the option's value
267             :returns: list of matching Option objects
268         """
269         return self.cfgimpl_get_context()._find(
270             bytype, byname, byvalue, first=True, type_=type_,
271             _subpath=self.cfgimpl_get_path(), display_error=display_error)
272
273     def _find(self, bytype, byname, byvalue, first, type_='option',
274               _subpath=None, check_properties=True, display_error=True):
275         """
276         convenience method for finding an option that lives only in the subtree
277
278         :param first: return only one option if True, a list otherwise
279         :return: find list or an exception if nothing has been found
280         """
281         def _filter_by_name():
282             try:
283                 if byname is None or path == byname or \
284                         path.endswith('.' + byname):
285                     return True
286             except IndexError:
287                 pass
288             return False
289
290         def _filter_by_value():
291             if byvalue is None:
292                 return True
293             try:
294                 value = getattr(self, path)
295                 if value == byvalue:
296                     return True
297             except PropertiesOptionError:  # a property is a restriction
298                                            # upon the access of the value
299                 pass
300             return False
301
302         def _filter_by_type():
303             if bytype is None:
304                 return True
305             if isinstance(option, bytype):
306                 return True
307             return False
308
309         #def _filter_by_attrs():
310         #    if byattrs is None:
311         #        return True
312         #    for key, val in byattrs.items():
313         #        print "----", path, key
314         #        if path == key or path.endswith('.' + key):
315         #            if value == val:
316         #                return True
317         #            else:
318         #                return False
319         #    return False
320         if type_ not in ('option', 'path', 'context', 'value'):
321             raise ValueError(_('unknown type_ type {0}'
322                                'for _find').format(type_))
323         find_results = []
324         opts, paths = self.cfgimpl_get_description()._cache_paths
325         for index in range(0, len(paths)):
326             option = opts[index]
327             if isinstance(option, OptionDescription):
328                 continue
329             path = paths[index]
330             if _subpath is not None and not path.startswith(_subpath + '.'):
331                 continue
332             if not _filter_by_name():
333                 continue
334             if not _filter_by_value():
335                 continue
336             #remove option with propertyerror, ...
337             if check_properties:
338                 try:
339                     value = getattr(self, path)
340                 except PropertiesOptionError:
341                     # a property restricts the access of the value
342                     continue
343             if not _filter_by_type():
344                 continue
345             #if not _filter_by_attrs():
346             #    continue
347             if type_ == 'value':
348                 retval = value
349             elif type_ == 'path':
350                 retval = path
351             elif type_ == 'option':
352                 retval = option
353             elif type_ == 'context':
354                 retval = self.cfgimpl_get_context()
355             if first:
356                 return retval
357             else:
358                 find_results.append(retval)
359         if find_results == []:
360             if display_error:
361                 raise AttributeError(_("no option found in config"
362                                        " with these criteria"))
363             else:
364                 #translation is slow
365                 raise AttributeError()
366         else:
367             return find_results
368
369     def make_dict(self, flatten=False, _currpath=None, withoption=None,
370                   withvalue=None):
371         """exports the whole config into a `dict`, for example:
372
373         >>> print cfg.make_dict()
374         {'od2.var4': None, 'od2.var5': None, 'od2.var6': None}
375
376
377
378         :param flatten: returns a dict(name=value) instead of a dict(path=value)
379                         ::
380
381                             >>> print cfg.make_dict(flatten=True)
382                             {'var5': None, 'var4': None, 'var6': None}
383
384         :param withoption: returns the options that are present in the very same
385                            `OptionDescription` than the `withoption` itself::
386
387                                 >>> print cfg.make_dict(withoption='var1')
388                                 {'od2.var4': None, 'od2.var5': None,
389                                 'od2.var6': None,
390                                 'od2.var1': u'value',
391                                 'od1.var1': None,
392                                 'od1.var3': None,
393                                 'od1.var2': None}
394
395         :param withvalue: returns the options that have the value `withvalue`
396                           ::
397
398                             >>> print c.make_dict(withoption='var1',
399                                                   withvalue=u'value')
400                             {'od2.var4': None,
401                             'od2.var5': None,
402                             'od2.var6': None,
403                             'od2.var1': u'value'}
404
405         :returns: dict of Option's name (or path) and values
406         """
407         pathsvalues = []
408         if _currpath is None:
409             _currpath = []
410         if withoption is None and withvalue is not None:
411             raise ValueError(_("make_dict can't filtering with value without "
412                                "option"))
413         if withoption is not None:
414             mypath = self.cfgimpl_get_path()
415             for path in self.cfgimpl_get_context()._find(bytype=Option,
416                                                          byname=withoption,
417                                                          byvalue=withvalue,
418                                                          first=False,
419                                                          type_='path',
420                                                          _subpath=mypath):
421                 path = '.'.join(path.split('.')[:-1])
422                 opt = self.cfgimpl_get_context().cfgimpl_get_description(
423                 ).impl_get_opt_by_path(path)
424                 if mypath is not None:
425                     if mypath == path:
426                         withoption = None
427                         withvalue = None
428                         break
429                     else:
430                         tmypath = mypath + '.'
431                         if not path.startswith(tmypath):
432                             raise AttributeError(_('unexpected path {0}, '
433                                                    'should start with {1}'
434                                                    '').format(path, mypath))
435                         path = path[len(tmypath):]
436                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
437         #withoption can be set to None below !
438         if withoption is None:
439             for opt in self.cfgimpl_get_description().impl_getchildren():
440                 path = opt._name
441                 self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
442         if _currpath == []:
443             options = dict(pathsvalues)
444             return options
445         return pathsvalues
446
447     def _make_sub_dict(self, opt, path, pathsvalues, _currpath, flatten):
448         if isinstance(opt, OptionDescription):
449             try:
450                 pathsvalues += getattr(self, path).make_dict(flatten,
451                                                              _currpath +
452                                                              path.split('.'))
453             except PropertiesOptionError:
454                 pass  # this just a hidden or disabled option
455         else:
456             try:
457                 value = self._getattr(opt._name)
458                 if flatten:
459                     name = opt._name
460                 else:
461                     name = '.'.join(_currpath + [opt._name])
462                 pathsvalues.append((name, value))
463             except PropertiesOptionError:
464                 pass  # this just a hidden or disabled option
465
466     def cfgimpl_get_path(self):
467         descr = self.cfgimpl_get_description()
468         context_descr = self.cfgimpl_get_context().cfgimpl_get_description()
469         return context_descr.impl_get_path_by_opt(descr)
470
471
472 class CommonConfig(SubConfig):
473     "abstract base class for the Config and the MetaConfig"
474     __slots__ = ('_impl_values', '_impl_settings', '_impl_meta')
475
476     def _init_storage(self, config_id, is_persistent):
477         if config_id is None:
478             config_id = gen_id(self)
479         import_lib = 'tiramisu.storage.{0}.storage'.format(storage_type)
480         return __import__(import_lib, globals(), locals(), ['Storage'],
481                           -1).Storage(config_id, is_persistent)
482
483     def _impl_build_all_paths(self):
484         self.cfgimpl_get_description().impl_build_cache()
485
486     def read_only(self):
487         "read only is a global config's setting, see `settings.py`"
488         self.cfgimpl_get_settings().read_only()
489
490     def read_write(self):
491         "read write is a global config's setting, see `settings.py`"
492         self.cfgimpl_get_settings().read_write()
493
494     def getowner(self, path):
495         """convenience method to retrieve an option's owner
496         from the config itself
497         """
498         opt = self.cfgimpl_get_description().impl_get_opt_by_path(path)
499         return self.cfgimpl_get_values().getowner(opt)
500
501     def unwrap_from_path(self, path, force_permissive=False):
502         """convenience method to extract and Option() object from the Config()
503         and it is **fast**: finds the option directly in the appropriate
504         namespace
505
506         :returns: Option()
507         """
508         if '.' in path:
509             homeconfig, path = self.cfgimpl_get_home_by_path(
510                 path, force_permissive=force_permissive)
511             return getattr(homeconfig.cfgimpl_get_description(), path)
512         return getattr(self.cfgimpl_get_description(), path)
513
514     def cfgimpl_get_path(self):
515         return None
516
517     def cfgimpl_get_meta(self):
518         return self._impl_meta
519
520
521 # ____________________________________________________________
522 class Config(CommonConfig):
523     "main configuration management entry"
524     __slots__ = tuple()
525
526     def __init__(self, descr, config_id=None, is_persistent=False):
527         """ Configuration option management master class
528
529         :param descr: describes the configuration schema
530         :type descr: an instance of ``option.OptionDescription``
531         :param context: the current root config
532         :type context: `Config`
533         """
534         storage = self._init_storage(config_id, is_persistent)
535         self._impl_settings = Settings(self, storage)
536         self._impl_values = Values(self, storage)
537         super(Config, self).__init__(descr, self)
538         self._impl_build_all_paths()
539         self._impl_meta = None
540         self._impl_informations = {}
541
542     def cfgimpl_reset_cache(self,
543                             only_expired=False,
544                             only=('values', 'settings')):
545         if 'values' in only:
546             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
547         if 'settings' in only:
548             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
549
550
551 class MetaConfig(CommonConfig):
552     __slots__ = ('_impl_children',)
553
554     def __init__(self, children, meta=True, config_id=None, is_persistent=False):
555         if not isinstance(children, list):
556             raise ValueError(_("metaconfig's children must be a list"))
557         self._impl_descr = None
558         if meta:
559             for child in children:
560                 if not isinstance(child, CommonConfig):
561                     raise ValueError(_("metaconfig's children "
562                                        "must be config, not {0}"
563                                        ).format(type(child)))
564                 if self._impl_descr is None:
565                     self._impl_descr = child.cfgimpl_get_description()
566                 elif not self._impl_descr is child.cfgimpl_get_description():
567                     raise ValueError(_('all config in metaconfig must '
568                                        'have the same optiondescription'))
569                 if child.cfgimpl_get_meta() is not None:
570                     raise ValueError(_("child has already a metaconfig's"))
571                 child._impl_meta = self
572
573         if config_id is None:
574             config_id = gen_id(self)
575         self._impl_children = children
576         storage = self._init_storage(config_id, is_persistent)
577         self._impl_settings = Settings(self, storage)
578         self._impl_values = Values(self, storage)
579         self._impl_meta = None
580         self._impl_informations = {}
581
582     def cfgimpl_get_children(self):
583         return self._impl_children
584
585     def cfgimpl_get_context(self):
586         "a meta config is a config wich has a setting, that is itself"
587         return self
588
589     def cfgimpl_reset_cache(self,
590                             only_expired=False,
591                             only=('values', 'settings')):
592         if 'values' in only:
593             self.cfgimpl_get_values().reset_cache(only_expired=only_expired)
594         if 'settings' in only:
595             self.cfgimpl_get_settings().reset_cache(only_expired=only_expired)
596         for child in self._impl_children:
597             child.cfgimpl_reset_cache(only_expired=only_expired, only=only)
598
599     def set_contexts(self, path, value):
600         for child in self._impl_children:
601             try:
602                 if not isinstance(child, MetaConfig):
603                     setattr(child, path, value)
604                 else:
605                     child.set_contexts(path, value)
606             except PropertiesOptionError:
607                 pass
608
609     def find_first_contexts(self, byname=None, bypath=None, byvalue=None,
610                             type_='context', display_error=True):
611         ret = []
612         try:
613             if bypath is None and byname is not None and \
614                     self.cfgimpl_get_description() is not None:
615                 bypath = self._find(bytype=None, byvalue=None, byname=byname,
616                                     first=True, type_='path',
617                                     check_properties=False)
618         except ConfigError:
619             pass
620         for child in self._impl_children:
621             try:
622                 if not isinstance(child, MetaConfig):
623                     if bypath is not None:
624                         if byvalue is not None:
625                             if getattr(child, bypath) == byvalue:
626                                 ret.append(child)
627                         else:
628                             #not raise
629                             getattr(child, bypath)
630                             ret.append(child)
631                     else:
632                         ret.append(child.find_first(byname=byname,
633                                                     byvalue=byvalue,
634                                                     type_=type_,
635                                                     display_error=False))
636                 else:
637                     ret.extend(child.find_first_contexts(byname=byname,
638                                                          bypath=bypath,
639                                                          byvalue=byvalue,
640                                                          type_=type_,
641                                                          display_error=False))
642             except AttributeError:
643                 pass
644         return ret
645
646
647 def mandatory_warnings(config):
648     """convenience function to trace Options that are mandatory and
649     where no value has been set
650
651     :returns: generator of mandatory Option's path
652
653     """
654     #if value in cache, properties are not calculated
655     config.cfgimpl_reset_cache(only=('values',))
656     for path in config.cfgimpl_get_description().impl_getpaths(
657             include_groups=True):
658         try:
659             config._getattr(path, force_properties=frozenset(('mandatory',)))
660         except PropertiesOptionError, err:
661             if err.proptype == ['mandatory']:
662                 yield path
663     config.cfgimpl_reset_cache(only=('values',))