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
|
"""\
plugins.py - generic plugin system
Basic plugin architecture (metaclass tricks) by Marty Alchin from
http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/
GenericPluginMeta slightly modified to
- store plugins as dict
- support plugin class hierarchies
Extended by GenericDetectPlugin to
- support auto-detection of the adequate plugin
Example usage of the plugins module:
p = __import__(plugins)
Example non-auto-detection plugin:
class NonDetectPluginType(object):
__metaclass__ = p.GenericPluginMeta
class PluginA(NonDetectPluginType):
name = "PA"
class PluginB(NonDetectPluginType):
name = "PB"
Example auto-detection plugin:
class MyPluginType(p.GenericDetectPlugin):
__metaclass__ = p.GenericPluginMeta
# The calling convention for constructor
# detect(context, <mystuff...>)
# is defined here, and the same <mystuff...> is used
# to construct the exceptions.
[no_match_exception = ...]
[ambigous_match_exception = ...]
[
@classmethod
def validate(cls, obj, *args, **kwargs):
return True # or False, depending on params
]
class MyPluginA(MyPluginType):
name = "MA"
def __init__(self, context):
super(MyPluginA, self).__init__(self, context)
if not some_detection_successful:
raise self.no_match_exception()
class MyPluginB(MyPluginType):
name = "MB"
def __init__(self, context):
super(MyPluginB, self).__init__(self, context)
if not other_detection_successful:
raise self.no_match_exception()
"""
import sys
import logging
import types
import functools
import inspect
class NoPluginsRegistered(Exception):
"""Raised when looking for plugins but none are registered"""
def __init__(self, cls):
super(NoPluginsRegistered, self).__init__()
self.cls = cls
def __str__(self):
return "No plugins of type %s registered" % (self.cls.__name__)
class DuplicatePluginName(Exception):
"""Raised when another plugin tries to register the same name"""
pass
class PluginNoMatch(Exception):
"""Raised when no registered plugin matches the given args"""
def __init__(self, *args, **kwargs):
super(PluginNoMatch, self).__init__()
self.args = args
self.kwargs = kwargs
def __str__(self):
return "%s(%s,%s)" % (self.__class__.__name__,
self.args, self.kwargs)
class AmbigousPluginDetection(Exception):
"""Raised when more than one registered plugin matches the given args"""
def __init__(self, matches, cls, context, *args, **kwargs):
self.matches = matches
self.cls = cls
self.context = context
self.args = args
self.kwargs = kwargs
def __str__(self):
return "%s(%s.%s, %s, %s, %s, %s)" % (self.__class__.__name__,
self.cls.__module__,
self.cls.__name__,
self.matches,
self.context,
self.args,
self.kwargs)
class AbstractMethodsInConcreteClass(Exception):
"""Raised when an abstract method is detected in a non-abstract class
The method has been marked @abstractmethod in an ancestor, and must be
implemented if this class is not abstract itself.
"""
def __init__(self, cls, methods):
self.cls = cls
self.methods = methods
def __str__(self):
methods = " ".join((k for k,v in self.methods))
return "Class %s.%s must implement the %s abstract methods." \
% (self.cls.__module__,
self.cls.__name__,
methods)
class AbstractMethodError(Exception):
"""Raised when an abstract method is called"""
def __init__(self, name, module):
self.name = name
self.module = module
def __str__(self):
# FIXME: Class name?
return "Abstract method %s called someplace in %s" \
% (repr(self.name), repr(self.module))
def abstractmethod(fun):
"""The decorator for abstract methods in plugins
This decorator has two effects:
* If the abstract method should ever be called, it will raise
an AbstractMethodError.
* If the class the method is defined has GenericPluginMeta as
__metaclass__, __name__ is not None (i.e. it is a non-abstract
Plugin class), and the method has not been overwritten with a
method without @abstractmethod, there will be a
AbstractMethodsInConcreteClass at module loading time, i.e.
before the actual program is run!
"""
@functools.wraps(fun)
def f(self, *args, **kwargs):
# fun(self, *args, **kwargs)
raise AbstractMethodError(name=fun.__name__,
module=fun.__module__)
f.abstract_method = True
return f
class PluginDict(dict):
"""Helper for GenericPluginMeta class
Behaves basically like a standard dict, but will raise an exception
when asked to update an existing value.
"""
# This is the important difference between PluginDict and dict.
def __setitem__(self, key, value):
if self.has_key(key):
raise DuplicatePluginName()
else:
super(PluginDict, self).__setitem__(key, value)
class GenericPluginMeta(type):
"""Simple plugin metaclass with named plugins
Simple usage:
>>> class Plugin(object):
... pass
...
>>> class PluginA(Plugin):
... __name__ = 'a'
...
>>> class PluginA(Plugin):
... __name__ = 'b'
...
>>> print Plugin.plugins.keys()
['a', 'b']
Advanced features:
You can add abstract subclasses of Plugin by giving them a __name__ = None,
define an @abstractmethod method in that abstract subclass, and much more.
"""
def __init__(cls, name, bases, attrs):
logging.debug("META_INIT %s %s %s %s", cls, name, bases, attrs)
if not hasattr(cls, 'plugins'):
# This branch only executes when processing the mount point itself.
# So, since this is a new plugin type, not an implementation, this
# class shouldn't be registered as a plugin. Instead, it sets up a
# list where plugins can be registered later.
cls.plugins = PluginDict()
elif cls.name is not None:
# This must be a plugin implementation, which should be registered.
# Simply appending it to the list is all that's needed to keep
# track of it later.
logging.debug("Registering %s together with %s", cls, cls.plugins)
def abstract_method_filter(member):
return hasattr(member, '__call__') \
and hasattr(member, 'abstract_method')
ams = inspect.getmembers(cls, abstract_method_filter)
if ams:
raise AbstractMethodsInConcreteClass(cls, ams)
cls.plugins[cls.name] = cls
else:
# This must be an abstract subclass of plugins.
pass
class GenericDetectPlugin(object):
"""Advanced plugin class where the plugins detect whether they apply
Use it by defining a subclass with the proper properties and methods overwritten.
Example:
>>> class FooDetectPlugin(GenericDetectPlugin):
... @classmethod
... def validate(cls, obj, foo, bar):
... return cls.__name__ == 'A'
...
>>> class FooDetectPluginA(FooDetectPlugin):
... __name__ = 'A'
...
>>> class FooDetectPluginB(FooDetectPlugin):
... __name__ = 'B'
...
>>> FooDetectPlugin.detect('FOO', 'BAR')
"""
"""You may override this with a more plugin specific subclass of PluginNoMatch"""
no_match_exception = PluginNoMatch
"""You may override this with a more plugin specific subclass of AmbigousPluginDetection"""
ambigous_match_exception = AmbigousPluginDetection
def __init__(self, context):
super(GenericDetectPlugin, self).__init__()
self.context = context
@classmethod
def validate(cls, obj, *args, **kwargs):
"""Override this in subclass to validate the given args
@param cls subclass of GenericDetectPlugin and type of obj
@param obj instance of cls which is to be validated
@param args the same args as given to detect()
@param kwargs the same kwargs as given to detect()
"""
logging.debug("GDval")
return True
@classmethod
def detect(cls, context, *args, **kwargs):
"""Detect which plugin matches the given arguments
It might make sense to document the exact calling conventions in
derived classes:
>>> class FooDetectPlugin(GenericDetectPlugin):
... @classmethod
... def detect(cls, context, foo, bar):
... "detect plugin from foo and bar values yadda yadda"
... return super(FooDetectPlugin, cls).detect(cls, context, foo, bar)
"""
logging.debug("DETECT %s", cls)
if len(cls.plugins) < 1:
raise NoPluginsRegistered(cls)
matches = PluginDict()
for key, klass in cls.plugins.iteritems():
try:
t = klass(context, *args, **kwargs)
logging.debug("KLASS %s unvalidated, %s", klass,
klass.validate)
if klass.validate(t, *args, **kwargs):
logging.debug("KLASS %s validated", klass)
matches[key] = t
except PluginNoMatch, e:
pass
if len(matches) > 1:
raise cls.ambigous_match_exception(matches,
cls, context,
*args, **kwargs)
elif len(matches) < 1:
raise cls.no_match_exception(*args, **kwargs)
return matches[matches.keys()[0]]
def selftest():
class PluginNoMatchA(PluginNoMatch):
pass
class AmbigousPluginDetectionA(AmbigousPluginDetection):
pass
class TestDetectPluginA(GenericDetectPlugin):
__metaclass__ = GenericPluginMeta
no_match_exception = PluginNoMatchA
ambigous_match_exception = AmbigousPluginDetectionA
@classmethod
def validate(cls, obj, *args, **kwargs):
logging.debug("Aval")
return False
class TestDetectPluginB(GenericDetectPlugin):
__metaclass__ = GenericPluginMeta
class TestDetectPluginC(GenericDetectPlugin):
__metaclass__ = GenericPluginMeta
@classmethod
def validate(cls, obj, *args, **kwargs):
logging.debug("Cval")
return False
class TestDetectPluginA1(TestDetectPluginA):
name = "A1"
class TestDetectPluginA2(TestDetectPluginA):
name = "A2"
class TestDetectPluginA3(TestDetectPluginA):
name = "A3"
class TestDetectPluginB1(TestDetectPluginB):
name = "B1"
class TestDetectPluginB2(TestDetectPluginB):
name = "B2"
class TestDetectPluginB3(TestDetectPluginB):
name = "B3"
class TestDetectPluginC1(TestDetectPluginC):
name = "C1"
class TestDetectPluginC2(TestDetectPluginC):
name = "C2"
class TestDetectPluginC3(TestDetectPluginC):
name = "C3"
@classmethod
def validate(cls, obj, *args, **kwargs):
logging.debug("C3val")
return True
ctx = None
print "GenericPluginMeta", dir(GenericPluginMeta)
print "GenericDetectPlugin", dir(GenericDetectPlugin)
print "TestDetectPluginA", dir(TestDetectPluginA)
print "TestDetectPluginA", dir(TestDetectPluginA)
print "TestDetectPluginB", dir(TestDetectPluginB)
print "TestDetectPluginC", dir(TestDetectPluginC)
try:
a = TestDetectPluginA.detect(ctx)
except:
logging.error("aaaa", exc_info=True)
try:
b = TestDetectPluginB.detect(ctx)
except:
logging.error("bbbb", exc_info=True)
try:
c = TestDetectPluginC.detect(ctx)
except:
logging.error("cccc", exc_info=True)
|