Debian Codegraph @

ipapython/install/core.py

raw
1 #
2 # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
3 #
4
5 """
6 The framework core.
7 """
8
9 import abc
10 import collections
11 import functools
12 import itertools
13 import sys
14
15 import six
16
17 from . import util
18 from .util import from_
19
20 __all__ = ['InvalidStateError', 'KnobValueError', 'Property', 'knob',
21 'Configurable', 'group', 'Component', 'Composite']
22
23 NoneType = type(None)
24 builtin_type = type
25
26 # Configurable states
27 _VALIDATE_PENDING = 'VALIDATE_PENDING'
28 _VALIDATE_RUNNING = 'VALIDATE_RUNNING'
29 _EXECUTE_PENDING = 'EXECUTE_PENDING'
30 _EXECUTE_RUNNING = 'EXECUTE_RUNNING'
31 _STOPPED = 'STOPPED'
32 _FAILED = 'FAILED'
33 _CLOSED = 'CLOSED'
34
35 _missing = object()
36 _counter = itertools.count()
37
38
39 @functools.cmp_to_key
40 def _class_key(a, b):
41 if a is b:
42 return 0
43 elif issubclass(a, b):
44 return -1
45 elif issubclass(b, a):
46 return 1
47 else:
48 return 0
49
50
51 class InvalidStateError(Exception):
52 pass
53
54
55 class KnobValueError(ValueError):
56 def __init__(self, name, message):
57 super(KnobValueError, self).__init__(message)
58 self.name = name
59
60
61 class PropertyBase(metaclass=util.InnerClassMeta):
62 # shut up pylint
63 __outer_class__ = None
64 __outer_name__ = None
65
66 _order = None
67
68 @property
69 def default(self):
70 raise AttributeError('default')
71
72 def __init__(self, outer):
73 pass
74
75 def __get__(self, obj, obj_type):
76 while obj is not None:
77 try:
78 return obj.__dict__[self.__outer_name__]
79 except KeyError:
80 pass
81 obj = obj._get_fallback()
82
83 try:
84 return self.default
85 except AttributeError:
86 raise AttributeError(self.__outer_name__)
87
88 def __set__(self, obj, value):
89 try:
90 obj.__dict__[self.__outer_name__] = value
91 except KeyError:
92 raise AttributeError(self.__outer_name__)
93
94 def __delete__(self, obj):
95 try:
96 del obj.__dict__[self.__outer_name__]
97 except KeyError:
98 raise AttributeError(self.__outer_name__)
99
100
101 def Property(default=_missing):
102 class_dict = {}
103 if default is not _missing:
104 class_dict['default'] = default
105
106 return util.InnerClassMeta('Property', (PropertyBase,), class_dict)
107
108
109 class KnobBase(PropertyBase):
110 type = None
111 sensitive = False
112 deprecated = False
113 description = None
114 cli_names = (None,)
115 cli_deprecated_names = ()
116 cli_metavar = None
117
118 def __init__(self, outer):
119 self.outer = outer
120
121 def validate(self, value):
122 pass
123
124 @classmethod
125 def group(cls):
126 return cls.__outer_class__.group()
127
128 @classmethod
129 def is_cli_positional(cls):
130 return all(n is not None and not n.startswith('-')
131 for n in cls.cli_names)
132
133 @classmethod
134 def default_getter(cls, func):
135 @property
136 def default(self):
137 return func(self.outer)
138 cls.default = default
139
140 return cls
141
142 @classmethod
143 def validator(cls, func):
144 def validate(self, value):
145 func(self.outer, value)
146 super(cls, self).validate(value)
147 cls.validate = validate
148
149 return cls
150
151
152 def _knob(type=_missing, default=_missing, bases=_missing, _order=_missing,
153 sensitive=_missing, deprecated=_missing, description=_missing,
154 group=_missing, cli_names=_missing, cli_deprecated_names=_missing,
155 cli_metavar=_missing):
156 if type is None:
157 type = NoneType
158
159 if bases is _missing:
160 bases = (KnobBase,)
161 elif isinstance(bases, builtin_type):
162 bases = (bases,)
163
164 if cli_names is None or isinstance(cli_names, str):
165 cli_names = (cli_names,)
166 elif cli_names is not _missing:
167 cli_names = tuple(cli_names)
168
169 if isinstance(cli_deprecated_names, str):
170 cli_deprecated_names = (cli_deprecated_names,)
171 elif cli_deprecated_names is not _missing:
172 cli_deprecated_names = tuple(cli_deprecated_names)
173
174 class_dict = {}
175 if type is not _missing:
176 class_dict['type'] = type
177 if default is not _missing:
178 class_dict['default'] = default
179 if _order is not _missing:
180 class_dict['_order'] = _order
181 if sensitive is not _missing:
182 class_dict['sensitive'] = sensitive
183 if deprecated is not _missing:
184 class_dict['deprecated'] = deprecated
185 if description is not _missing:
186 class_dict['description'] = description
187 if group is not _missing:
188 class_dict['group'] = group
189 if cli_names is not _missing:
190 class_dict['cli_names'] = cli_names
191 if cli_deprecated_names is not _missing:
192 class_dict['cli_deprecated_names'] = cli_deprecated_names
193 if cli_metavar is not _missing:
194 class_dict['cli_metavar'] = cli_metavar
195
196 return util.InnerClassMeta('Knob', bases, class_dict)
197
198
199 def knob(type, default=_missing, **kwargs):
200 """
201 Define a new knob.
202 """
203 return _knob(
204 type, default,
205 _order=next(_counter),
206 **kwargs
207 )
208
209
210 def extend_knob(base, default=_missing, bases=_missing, group=_missing,
211 **kwargs):
212 """
213 Extend an existing knob.
214 """
215 if bases is _missing:
216 bases = (base,)
217
218 if group is _missing:
219 group = staticmethod(base.group)
220
221 return _knob(
222 _missing, default,
223 bases=bases,
224 _order=_missing,
225 group=group,
226 **kwargs
227 )
228
229
230 class Configurable(metaclass=abc.ABCMeta):
231 """
232 Base class of all configurables.
233
234 FIXME: details of validate/execute, properties and knobs
235 """
236
237 @classmethod
238 def properties(cls):
239 """
240 Iterate over properties defined for the configurable.
241 """
242
243 assert not hasattr(super(Configurable, cls), 'properties')
244
245 seen = set()
246
247 for owner_cls in cls.__mro__:
248 result = []
249
250 for name, prop_cls in owner_cls.__dict__.items():
251 if name in seen:
252 continue
253 seen.add(name)
254
255 if not isinstance(prop_cls, type):
256 continue
257 if not issubclass(prop_cls, PropertyBase):
258 continue
259
260 result.append((prop_cls._order, owner_cls, name))
261
262 result = sorted(result, key=lambda r: r[0])
263
264 for _order, owner_cls, name in result:
265 yield owner_cls, name
266
267 @classmethod
268 def knobs(cls):
269 for owner_cls, name in cls.properties():
270 prop_cls = getattr(owner_cls, name)
271 if issubclass(prop_cls, KnobBase):
272 yield owner_cls, name
273
274 @classmethod
275 def group(cls):
276 assert not hasattr(super(Configurable, cls), 'group')
277
278 def __init__(self, **kwargs):
279 """
280 Initialize the configurable.
281 """
282
283 cls = self.__class__
284 for owner_cls, name in cls.properties():
285 if name.startswith('_'):
286 continue
287 prop_cls = getattr(owner_cls, name)
288 if not isinstance(prop_cls, type):
289 continue
290 if not issubclass(prop_cls, PropertyBase):
291 continue
292
293 try:
294 value = kwargs.pop(name)
295 except KeyError:
296 pass
297 else:
298 setattr(self, name, value)
299
300 for owner_cls, name in cls.knobs():
301 if name.startswith('_'):
302 continue
303 if not isinstance(self, owner_cls):
304 continue
305 value = getattr(self, name, None)
306 if value is None:
307 continue
308
309 prop_cls = getattr(owner_cls, name)
310 prop = prop_cls(self)
311 try:
312 prop.validate(value)
313 except ValueError as e:
314 raise KnobValueError(name, str(e))
315
316 if kwargs:
317 extra = sorted(kwargs)
318 raise TypeError(
319 "{0}() got {1} unexpected keyword arguments: {2}".format(
320 type(self).__name__,
321 len(extra),
322 ', '.join(repr(name) for name in extra)))
323
324 self._reset()
325
326 def _reset(self):
327 assert not hasattr(super(Configurable, self), '_reset')
328
329 self.__state = _VALIDATE_PENDING
330 self.__gen = util.run_generator_with_yield_from(self._configure())
331
332 def _get_components(self):
333 assert not hasattr(super(Configurable, self), '_get_components')
334
335 raise TypeError("{0} is not composite".format(self))
336
337 def _get_fallback(self):
338 pass
339
340 @abc.abstractmethod
341 def _configure(self):
342 """
343 Coroutine which defines the logic of the configurable.
344 """
345
346 assert not hasattr(super(Configurable, self), '_configure')
347
348 self.__transition(_VALIDATE_RUNNING, _EXECUTE_PENDING)
349
350 while self.__state != _EXECUTE_RUNNING:
351 yield
352
353 def run(self):
354 """
355 Run the configurable.
356 """
357
358 self.validate()
359 if self.__state == _EXECUTE_PENDING:
360 return self.execute()
361 return None
362
363 def validate(self):
364 """
365 Run the validation part of the configurable.
366 """
367
368 for _nothing in self._validator():
369 pass
370
371 def _validator(self):
372 """
373 Coroutine which runs the validation part of the configurable.
374 """
375
376 return self.__runner(_VALIDATE_PENDING,
377 _VALIDATE_RUNNING,
378 self._handle_validate_exception)
379
380 def execute(self):
381 """
382 Run the execution part of the configurable.
383 """
384 return_value = 0
385
386 for rval in self._executor():
387 if rval is not None and rval > return_value:
388 return_value = rval
389
390 return return_value
391
392 def _executor(self):
393 """
394 Coroutine which runs the execution part of the configurable.
395 """
396
397 return self.__runner(_EXECUTE_PENDING,
398 _EXECUTE_RUNNING,
399 self._handle_execute_exception)
400
401 def done(self):
402 """
403 Return True if the configurable has finished.
404 """
405
406 return self.__state in (_STOPPED, _FAILED, _CLOSED)
407
408 def run_until_executing(self, gen):
409 while self.__state != _EXECUTE_RUNNING:
410 try:
411 yield next(gen)
412 except StopIteration:
413 break
414
415 def __runner(self, pending_state, running_state, exc_handler):
416 self.__transition(pending_state, running_state)
417
418 def step_next():
419 return next(self.__gen)
420
421 step = step_next
422
423 while True:
424 try:
425 step()
426 except StopIteration:
427 self.__transition(running_state, _STOPPED)
428 break
429 except GeneratorExit:
430 self.__transition(running_state, _CLOSED)
431 break
432 except BaseException:
433 exc_info = sys.exc_info()
434 try:
435 exc_handler(exc_info)
436 except BaseException:
437 self.__transition(running_state, _FAILED)
438 raise
439
440 if self.__state != running_state:
441 break
442
443 try:
444 yield
445 except BaseException:
446 exc_info = sys.exc_info()
447
448 def step_throw():
449 return self.__gen.throw(*exc_info)
450
451 step = step_throw
452 else:
453 step = step_next
454
455 def _handle_exception(self, exc_info):
456 assert not hasattr(super(Configurable, self), '_handle_exception')
457
458 six.reraise(*exc_info)
459
460 def _handle_validate_exception(self, exc_info):
461 assert not hasattr(super(Configurable, self),
462 '_handle_validate_exception')
463 self._handle_exception(exc_info)
464
465 def _handle_execute_exception(self, exc_info):
466 assert not hasattr(super(Configurable, self),
467 '_handle_execute_exception')
468 self._handle_exception(exc_info)
469
470 def __transition(self, from_state, to_state):
471 if self.__state != from_state:
472 raise InvalidStateError(self.__state)
473
474 self.__state = to_state
475
476
477 def group(cls):
478 def group():
479 return cls
480
481 cls.group = staticmethod(group)
482
483 return cls
484
485
486 class ComponentMeta(util.InnerClassMeta, abc.ABCMeta):
487 pass
488
489
490 class ComponentBase(Configurable, metaclass=ComponentMeta):
491 # shut up pylint
492 __outer_class__ = None
493 __outer_name__ = None
494
495 _order = None
496
497 @classmethod
498 def group(cls):
499 result = super(ComponentBase, cls).group()
500 if result is not None:
501 return result
502 else:
503 return cls.__outer_class__.group()
504
505 def __init__(self, parent, **kwargs):
506 self.__parent = parent
507
508 super(ComponentBase, self).__init__(**kwargs)
509
510 @property
511 def parent(self):
512 return self.__parent
513
514 def __get__(self, obj, obj_type):
515 obj.__dict__[self.__outer_name__] = self
516 return self
517
518 def _get_fallback(self):
519 return self.__parent
520
521 def _handle_exception(self, exc_info):
522 try:
523 super(ComponentBase, self)._handle_exception(exc_info)
524 except BaseException:
525 exc_info = sys.exc_info()
526 self.__parent._handle_exception(exc_info)
527
528
529 def Component(cls):
530 class_dict = {}
531 class_dict['_order'] = next(_counter)
532
533 return ComponentMeta('Component', (ComponentBase, cls), class_dict)
534
535
536 class Composite(Configurable):
537 """
538 Configurable composed of any number of components.
539
540 Provides knobs of all child components.
541 """
542
543 @classmethod
544 def properties(cls):
545 name_dict = {}
546 owner_dict = collections.OrderedDict()
547
548 for owner_cls, name in super(Composite, cls).properties():
549 name_dict[name] = owner_cls
550 owner_dict.setdefault(owner_cls, []).append(name)
551
552 for owner_cls, name in cls.components():
553 comp_cls = getattr(cls, name)
554
555 for owner_cls, name in comp_cls.knobs():
556 if hasattr(cls, name):
557 continue
558
559 try:
560 last_owner_cls = name_dict[name]
561 except KeyError:
562 name_dict[name] = owner_cls
563 owner_dict.setdefault(owner_cls, []).append(name)
564 else:
565 knob_cls = getattr(owner_cls, name)
566 last_knob_cls = getattr(last_owner_cls, name)
567 if issubclass(knob_cls, last_knob_cls):
568 name_dict[name] = owner_cls
569 owner_dict[last_owner_cls].remove(name)
570 owner_dict.setdefault(owner_cls, [])
571 if name not in owner_dict[owner_cls]:
572 owner_dict[owner_cls].append(name)
573 elif not issubclass(last_knob_cls, knob_cls):
574 raise TypeError("{0}.knobs(): conflicting definitions "
575 "of '{1}' in {2} and {3}".format(
576 cls.__name__,
577 name,
578 last_owner_cls.__name__,
579 owner_cls.__name__))
580
581 for owner_cls in sorted(owner_dict, key=_class_key):
582 for name in owner_dict[owner_cls]:
583 yield owner_cls, name
584
585 @classmethod
586 def components(cls):
587 assert not hasattr(super(Composite, cls), 'components')
588
589 seen = set()
590
591 for owner_cls in cls.__mro__:
592 result = []
593
594 for name, comp_cls in owner_cls.__dict__.items():
595 if name in seen:
596 continue
597 seen.add(name)
598
599 if not isinstance(comp_cls, type):
600 continue
601 if not issubclass(comp_cls, ComponentBase):
602 continue
603
604 result.append((comp_cls._order, owner_cls, name))
605
606 result = sorted(result, key=lambda r: r[0])
607
608 for _order, owner_cls, name in result:
609 yield owner_cls, name
610
611 def __getattr__(self, name):
612 for owner_cls, knob_name in self.knobs():
613 if knob_name == name:
614 break
615 else:
616 raise AttributeError(name)
617
618 for component in self.__components:
619 if isinstance(component, owner_cls):
620 break
621 else:
622 raise AttributeError(name)
623
624 return getattr(component, name)
625
626 def _reset(self):
627 self.__components = list(self._get_components())
628
629 super(Composite, self)._reset()
630
631 def _get_components(self):
632 for _owner_cls, name in self.components():
633 yield getattr(self, name)
634
635 def _configure(self):
636 validate = [(c, c._validator()) for c in self.__components]
637 while True:
638 new_validate = []
639 for child, validator in validate:
640 try:
641 next(validator)
642 except StopIteration:
643 pass
644 else:
645 new_validate.append((child, validator))
646 if not new_validate:
647 break
648 validate = new_validate
649
650 yield
651
652 if not self.__components:
653 return
654
655 yield from_(super(Composite, self)._configure())
656
657 execute = [(c, c._executor()) for c in self.__components
658 if not c.done()]
659 while True:
660 new_execute = []
661 for child, executor in execute:
662 try:
663 next(executor)
664 except StopIteration:
665 pass
666 else:
667 new_execute.append((child, executor))
668 if not new_execute:
669 break
670 execute = new_execute
671
672 yield