1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
|
# 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; version 2 only
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
Plugin framework.
The classes in this module make heavy use of Python container emulation. If
you are unfamiliar with this Python feature, see
http://docs.python.org/ref/sequence-types.html
"""
import re
import inspect
import errors
class ReadOnly(object):
"""
Base class for classes with read-only attributes.
Be forewarned that Python does not offer true read-only user defined
classes. In particular, do not rely upon the read-only-ness of this
class for security purposes.
The point of this class is not to make it impossible to set or delete
attributes, but to make it impossible to accidentally do so. The plugins
are not thread-safe: in the server, they are loaded once and the same
instances will be used to process many requests. Therefore, it is
imperative that they not set any instance attributes after they have
been initialized. This base class enforces that policy.
For example:
>>> class givenname(ReadOnly):
>>> def __init__(self):
>>> self.whatever = 'some value' # Hasn't been locked yet
>>> lock(self)
>>>
>>> def finalize(self, api):
>>> # After the instance has been locked, attributes can still be
>>> # set, but only in a round-about, unconventional way:
>>> object.__setattr__(self, 'api', api)
>>>
>>> def normalize(self, value):
>>> # After the instance has been locked, trying to set an
>>> # attribute in the normal way will raise AttributeError.
>>> self.value = value # Not thread safe!
>>> return self.actually_normalize()
>>>
>>> def actually_normalize(self):
>>> # Again, this is not thread safe:
>>> return unicode(self.value).strip()
"""
__locked = False
def __lock__(self):
"""
Puts this instance into a read-only state, after which attempting to
set or delete an attribute will raise AttributeError.
"""
assert self.__locked is False, '__lock__() can only be called once'
self.__locked = True
def __islocked__(self):
"""
Returns True if this instance is locked, False otherwise.
"""
return self.__locked
def __setattr__(self, name, value):
"""
Raises an AttributeError if `ReadOnly.__lock__()` has already been
called; otherwise calls object.__setattr__().
"""
if self.__locked:
raise AttributeError('read-only: cannot set %s.%s' %
(self.__class__.__name__, name)
)
return object.__setattr__(self, name, value)
def __delattr__(self, name):
"""
Raises an AttributeError if `ReadOnly.__lock__()` has already been
called; otherwise calls object.__delattr__().
"""
if self.__locked:
raise AttributeError('read-only: cannot del %s.%s' %
(self.__class__.__name__, name)
)
return object.__delattr__(self, name)
def lock(readonly):
"""
Locks a `ReadOnly` instance.
This is mostly a convenience function to call `ReadOnly.__lock__()`. It
also verifies that the locking worked using `ReadOnly.__islocked__()`
:param readonly: An instance of the `ReadOnly` class.
"""
if not isinstance(readonly, ReadOnly):
raise ValueError('not a ReadOnly instance: %r' % readonly)
readonly.__lock__()
assert readonly.__islocked__(), 'Ouch! The locking failed?'
return readonly
class Plugin(ReadOnly):
"""
Base class for all plugins.
"""
__public__ = frozenset()
__api = None
def __get_name(self):
"""
Convenience property to return the class name.
"""
return self.__class__.__name__
name = property(__get_name)
def __get_doc(self):
"""
Convenience property to return the class docstring.
"""
return self.__class__.__doc__
doc = property(__get_doc)
def __get_api(self):
"""
Returns the `API` instance passed to `finalize()`, or
or returns None if `finalize()` has not yet been called.
"""
return self.__api
api = property(__get_api)
@classmethod
def implements(cls, arg):
"""
Returns True if this cls.__public__ frozenset contains `arg`;
returns False otherwise.
There are three different ways this can be called:
With a <type 'str'> argument, e.g.:
>>> class base(ProxyTarget):
>>> __public__ = frozenset(['some_attr', 'another_attr'])
>>> base.implements('some_attr')
True
>>> base.implements('an_unknown_attribute')
False
With a <type 'frozenset'> argument, e.g.:
>>> base.implements(frozenset(['some_attr']))
True
>>> base.implements(frozenset(['some_attr', 'an_unknown_attribute']))
False
With any object that has a `__public__` attribute that is
<type 'frozenset'>, e.g.:
>>> class whatever(object):
>>> __public__ = frozenset(['another_attr'])
>>> base.implements(whatever)
True
Unlike ProxyTarget.implemented_by(), this returns an abstract answer
because only the __public__ frozenset is checked... a ProxyTarget
need not itself have attributes for all names in __public__
(subclasses might provide them).
"""
assert type(cls.__public__) is frozenset
if isinstance(arg, str):
return arg in cls.__public__
if type(getattr(arg, '__public__', None)) is frozenset:
return cls.__public__.issuperset(arg.__public__)
if type(arg) is frozenset:
return cls.__public__.issuperset(arg)
raise TypeError(
"must be str, frozenset, or have frozenset '__public__' attribute"
)
@classmethod
def implemented_by(cls, arg):
"""
Returns True if:
1. ``arg`` is an instance of or subclass of this class, and
2. ``arg`` (or ``arg.__class__`` if instance) has an attribute for
each name in this class's ``__public__`` frozenset
Otherwise, returns False.
Unlike `Plugin.implements`, this returns a concrete answer because
the attributes of the subclass are checked.
:param arg: An instance of or subclass of this class.
"""
if inspect.isclass(arg):
subclass = arg
else:
subclass = arg.__class__
assert issubclass(subclass, cls), 'must be subclass of %r' % cls
for name in cls.__public__:
if not hasattr(subclass, name):
return False
return True
def finalize(self, api):
"""
After all the plugins are instantiated, `API` calls this method,
passing itself as the only argument. This is where plugins should
check that other plugins they depend upon have actually been loaded.
:param api: An `API` instance.
"""
assert self.__api is None, 'finalize() can only be called once'
assert api is not None, 'finalize() argument cannot be None'
self.__api = api
def __repr__(self):
"""
Returns a fully qualified module_name.class_name() representation that
could be used to construct this Plugin instance.
"""
return '%s.%s()' % (
self.__class__.__module__,
self.__class__.__name__
)
class Proxy(ReadOnly):
"""
Allows access to only certain attributes on a `Plugin`.
Think of a proxy as an agreement that "I will have at most these
attributes". This is different from (although similar to) an interface,
which can be thought of as an agreement that "I will have at least these
attributes".
"""
__slots__ = (
'__base',
'__target',
'__name_attr',
'__public__',
'name',
'doc',
)
def __init__(self, base, target, name_attr='name'):
"""
:param base: A subclass of `Plugin`.
:param target: An instance ``base`` or a subclass of ``base``.
:param name_attr: The name of the attribute on ``target`` from which
to derive ``self.name``.
"""
if not inspect.isclass(base):
raise TypeError(
'`base` must be a class, got %r' % base
)
if not isinstance(target, base):
raise ValueError(
'`target` must be an instance of `base`, got %r' % target
)
self.__base = base
self.__target = target
self.__name_attr = name_attr
self.__public__ = base.__public__
self.name = getattr(target, name_attr)
self.doc = target.doc
lock(self)
assert type(self.__public__) is frozenset
def implements(self, arg):
"""
Returns True if this proxy implements `arg`. Calls the corresponding
classmethod on ProxyTarget.
Unlike ProxyTarget.implements(), this is not a classmethod as a Proxy
only implements anything as an instance.
"""
return self.__base.implements(arg)
def __clone__(self, name_attr):
"""
Returns a Proxy instance identical to this one except the proxy name
might be derived from a different attribute on the target. The same
base and target will be used.
"""
return self.__class__(self.__base, self.__target, name_attr)
def __iter__(self):
"""
Iterates (in ascending order) though the attribute names this proxy is
allowing access to.
"""
for name in sorted(self.__public__):
yield name
def __getitem__(self, key):
"""
If this proxy allows access to an attribute named `key`, return that
attribute.
"""
if key in self.__public__:
return getattr(self.__target, key)
raise KeyError('no proxy attribute %r' % key)
def __getattr__(self, name):
"""
If this proxy allows access to an attribute named `name`, return that
attribute.
"""
if name in self.__public__:
return getattr(self.__target, name)
raise AttributeError('no proxy attribute %r' % name)
def __call__(self, *args, **kw):
"""
Attempts to call target.__call__(); raises KeyError if `__call__` is
not an attribute this proxy allows access to.
"""
return self['__call__'](*args, **kw)
def __repr__(self):
"""
Returns a Python expression that could be used to construct this Proxy
instance given the appropriate environment.
"""
return '%s(%s, %r, %r)' % (
self.__class__.__name__,
self.__base.__name__,
self.__target,
self.__name_attr,
)
def check_name(name):
"""
Verifies that ``name`` is suitable for a `NameSpace` member name.
Raises `errors.NameSpaceError` if ``name`` is not a valid Python
identifier suitable for use as the name of `NameSpace` member.
:param name: Identifier to test.
"""
assert type(name) is str, 'must be %r' % str
regex = r'^[a-z][_a-z0-9]*[a-z0-9]$'
if re.match(regex, name) is None:
raise errors.NameSpaceError(name, regex)
return name
class NameSpace(ReadOnly):
"""
A read-only namespace with handy container behaviours.
Each member of a NameSpace instance must have a ``name`` attribute whose
value:
1. Is unique among the members
2. Passes the `check_name()` function
Beyond that, no restrictions are placed on the members: they can be
classes or instances, and of any type.
The members can be accessed as attributes on the NameSpace instance or
through a dictionary interface. For example, assuming ``obj`` is a member
in the NameSpace instance ``namespace``, you could do this:
>>> obj is getattr(namespace, obj.name) # As attribute
True
>>> obj is namespace[obj.name] # As dictionary item
True
Here is a more detailed example:
>>> class member(object):
... def __init__(self, i):
... self.name = 'member_%d' % i
...
>>> def get_members(cnt):
... for i in xrange(cnt):
... yield member(i)
...
>>> namespace = NameSpace(get_members(2))
>>> namespace.member_0 is namespace['member_0']
True
>>> len(namespace) # Returns the number of members in namespace
2
>>> list(namespace) # As iterable, iterates through the member names
['member_0', 'member_1']
>>> list(namespace()) # Calling a NameSpace iterates through the members
[<__main__.member object at 0x836710>, <__main__.member object at 0x836750>]
>>> 'member_1' in namespace # NameSpace.__contains__()
True
"""
def __init__(self, members):
"""
:param members: An iterable providing the members.
"""
self.__d = dict()
self.__names = tuple(self.__member_iter(members))
lock(self)
assert set(self.__d) == set(self.__names)
def __member_iter(self, members):
"""
Helper method called only from `NameSpace.__init__()`.
:param members: Same iterable passed to `NameSpace.__init__()`.
"""
for member in members:
name = check_name(member.name)
assert not (
name in self.__d or hasattr(self, name)
), 'already has member named %r' % name
self.__d[name] = member
setattr(self, name, member)
yield name
def __len__(self):
"""
Returns the number of members in this NameSpace.
"""
return len(self.__d)
def __contains__(self, name):
"""
Returns True if instance contains a member named ``name``, otherwise
False.
:param name: The name of a potential member
"""
return name in self.__d
def __getitem__(self, name):
"""
Returns the member named ``name``.
Raises KeyError if this NameSpace does not contain a member named
``name``.
:param name: The name of member to retrieve
"""
if name in self.__d:
return self.__d[name]
raise KeyError('NameSpace has no member named %r' % name)
def __iter__(self):
"""
Iterates through the member names in the same order as the members
were passed to the constructor.
"""
for name in self.__names:
yield name
def __call__(self):
"""
Iterates through the members in the same order they were passed to the
constructor.
"""
for name in self.__names:
yield self.__d[name]
def __repr__(self):
"""
Returns pseudo-valid Python expression that could be used to construct
this NameSpace instance.
"""
return '%s(<%d members>)' % (self.__class__.__name__, len(self))
class MagicDict(ReadOnly):
"""
A read-only dict whose items can also be accessed as attributes.
Although a MagicDict is read-only, the underlying dict can change (and is
assumed to).
One of these is created for each allowed base in a `Registrar` instance.
"""
def __init__(self, d):
"""
:param d: The ``dict`` instance to proxy.
"""
assert type(d) is dict, '`d` must be %r, got %r' % (dict, type(d))
self.__d = d
lock(self)
def __len__(self):
"""
Returns number of items in underlying ``dict``.
"""
return len(self.__d)
def __iter__(self):
"""
Iterates through keys of underlying ``dict`` in ascending order.
"""
for name in sorted(self.__d):
yield name
def __contains__(self, key):
"""
Returns True if underlying dict contains ``key``, False otherwise.
:param key: The key to query upon.
"""
return key in self.__d
def __getitem__(self, key):
"""
Returns value from underlying dict corresponding to ``key``.
:param key: The key of the value to retrieve.
"""
if key in self.__d:
return self.__d[key]
raise KeyError('no item at key %r' % key)
def __getattr__(self, name):
"""
Returns value from underlying dict corresponding to ``name``.
:param name: The name of the attribute to retrieve.
"""
if name in self.__d:
return self.__d[name]
raise AttributeError('no attribute %r' % name)
class Registrar(ReadOnly):
"""
Collects plugin classes as they are registered.
The Registrar does not instantiate plugins... it only implements the
override logic and stores the plugins in a namespace per allowed base
class.
The plugins are instantiated when `API.finalize()` is called.
"""
def __init__(self, *allowed):
"""
:param allowed: Base classes from which plugins accepted by this
Registrar must subclass.
"""
class Val(ReadOnly):
"""
Internal class used so that only one mapping is needed.
"""
def __init__(self, base):
assert inspect.isclass(base)
self.base = base
self.name = base.__name__
self.sub_d = dict()
self.dictproxy = MagicDict(self.sub_d)
lock(self)
self.__allowed = allowed
self.__d = {}
self.__registered = set()
for base in self.__allowed:
val = Val(base)
assert not (
val.name in self.__d or hasattr(self, val.name)
)
self.__d[val.name] = val
setattr(self, val.name, val.dictproxy)
lock(self)
def __findbases(self, klass):
"""
Iterates through allowed bases that ``klass`` is a subclass of.
Raises `errors.SubclassError` if ``klass`` is not a subclass of any
allowed base.
:param klass: The class to find bases for.
"""
assert inspect.isclass(klass)
found = False
for base in self.__allowed:
if issubclass(klass, base):
found = True
yield base
if not found:
raise errors.SubclassError(klass, self.__allowed)
def __call__(self, klass, override=False):
"""
Register the plugin ``klass``.
:param klass: A subclass of `Plugin` to attempt to register.
:param override: If true, override an already registered plugin.
"""
if not inspect.isclass(klass):
raise TypeError('plugin must be a class: %r' % klass)
# Raise DuplicateError if this exact class was already registered:
if klass in self.__registered:
raise errors.DuplicateError(klass)
# Find the base class or raise SubclassError:
for base in self.__findbases(klass):
sub_d = self.__d[base.__name__].sub_d
# Check override:
if klass.__name__ in sub_d:
# Must use override=True to override:
if not override:
raise errors.OverrideError(base, klass)
else:
# There was nothing already registered to override:
if override:
raise errors.MissingOverrideError(base, klass)
# The plugin is okay, add to sub_d:
sub_d[klass.__name__] = klass
# The plugin is okay, add to __registered:
self.__registered.add(klass)
def __getitem__(self, key):
"""
Returns the MagicDict for plugins subclassed from the base named ``key``.
"""
if key not in self.__d:
raise KeyError('no base class named %r' % key)
return self.__d[key].dictproxy
def __contains__(self, key):
"""
Returns True if a base class named ``key`` is in this Registrar.
"""
return key in self.__d
def __iter__(self):
"""
Iterates through a (base, registered_plugins) tuple for each allowed
base.
"""
for base in self.__allowed:
sub_d = self.__d[base.__name__].sub_d
yield (base, tuple(sub_d[k] for k in sorted(sub_d)))
class API(ReadOnly):
"""
Dynamic API object through which `Plugin` instances are accessed.
"""
__finalized = False
def __init__(self, *allowed):
self.__d = dict()
self.register = Registrar(*allowed)
lock(self)
def finalize(self):
"""
Finalize the registration, instantiate the plugins.
"""
assert not self.__finalized, 'finalize() can only be called once'
instances = {}
def plugin_iter(base, classes):
for klass in classes:
if klass not in instances:
instances[klass] = klass()
plugin = instances[klass]
yield Proxy(base, plugin)
for (base, classes) in self.register:
namespace = NameSpace(plugin_iter(base, classes))
name = base.__name__
assert not (
name in self.__d or hasattr(self, name)
)
self.__d[name] = namespace
object.__setattr__(self, name, namespace)
for plugin in instances.values():
plugin.finalize(self)
lock(plugin)
assert plugin.api is self
object.__setattr__(self, '_API__finalized', True)
def __len__(self):
"""
Returns the number of namespaces in this API.
"""
return len(self.__d)
def __iter__(self):
"""
Iterates through the names of the namespaces in this API.
"""
for key in sorted(self.__d):
yield key
def __contains__(self, key):
"""
Returns True if this API contains a `NameSpace` named ``key``.
"""
return key in self.__d
def __getitem__(self, key):
"""
Returns the `NameSpace` instance named ``key``.
"""
if key in self.__d:
return self.__d[key]
raise KeyError('API has no NameSpace %r' % key)
|