File: Pattern.py

package info (click to toggle)
atheist 0.20110402-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,348 kB
  • sloc: python: 4,764; xml: 626; makefile: 113; cpp: 54; ansic: 5; sh: 5
file content (347 lines) | stat: -rw-r--r-- 10,489 bytes parent folder | download | duplicates (3)
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
# -*- mode: python; coding: utf-8 -*-

"""patterns module includes classes and structures of design patterns.

.. moduleauthor:: Arco Research Group

"""

from __future__ import with_statement

import logging
from thread import allocate_lock
import threading


class Singleton(type):

    """A metaclass for make any other class a Singleton_ (the design pattern).
    Example of use::

    class MySingletonClass:
        __metaclass__ = Singleton
        # your code goes here :)

    .. _Singleton: http://en.wikipedia.org/wiki/Singleton_pattern
    """
    def __init__(cls, name, bases, dct):
        cls.__lock = threading.Lock()
        cls.__instance = None
        type.__init__(cls, name, bases, dct)

    def __call__(cls, *args, **kw):
        with cls.__lock:
            if cls.__instance is None:
                cls.__instance = type.__call__(cls, *args, **kw)
        return cls.__instance

    def loaded(cls):
        return cls.__instance != None


class Flyweight(type):
    '''Flyweight dessign pattern (for identical objects)

    class Sample(object):
        __metaclass__ = Flyweight

        def __init__(self, key, [...]):
            [...]
    '''

    def __init__(cls, name, bases, dct):
        cls.__instances = {}
        type.__init__(cls, name, bases, dct)

    def __call__(cls, key, *args, **kw):
        instance = cls.__instances.get(key)
        if instance is None:
            instance = type.__call__(cls, key, *args, **kw)
            cls.__instances[key] = instance
        return instance



# Observer Pattern

class Observable:
    '''Observer design pattern implementation.

    Observable class:
    * Constructor can optionally receive two params.

    topics   : A list of topic names (as strings)
    logger   : A logger from logging module

    * Store a manage a dictionary with key:IdTopic, value:list of subscribers
    '''

    # Exceptions
    class ObserverException(Exception):
        def __str__(self):
            return "%s: %s" % (self.__class__.__name__, Exception.__str__(self))

    class TopicAlreadyExists(ObserverException): pass
    class NotSuchTopic(ObserverException): pass
    class InvalidTopicName(ObserverException): pass
    class InvalidSubscriber(ObserverException): pass
    class NotASubscriber(ObserverException): pass

    def __init__(self, topics=['default'],
                 logger=logging.getLogger('Observable')):

        self._logger = logger
        self._logger.propagate = 0

        self.__topics = {}
        for topic in topics:
            if not isinstance(topic, str):
                raise self.InvalidTopicName()

            self.__topics[topic] = []

    def getTopicNames(self):
        return self.__topics.keys()

    def addTopic(self, topicName):
        if topicName in self.__topics.keys():
            raise self.TopicAlreadyExists()

        if not isinstance(topicName, str):
            raise self.InvalidTopicName()

        self.__topics[topicName] = []
        self._logger.info('New topic created for %s instance: %s' %
                           (str(self.__class__.__name__), topicName))

    def removeTopic(self, topicName):
        try:
            del self.__topics[topicName]

        except KeyError:
            raise self.NotSuchTopic()

    def attach(self, subscriber, topicName='default'):
        if not callable(subscriber):
            raise self.InvalidSubscriber()

        try:
            if subscriber in self.__topics[topicName]: return
            self.__topics[topicName].append(subscriber)

        except KeyError:
            raise self.NotSuchTopic()

    def detach(self, subscriber, topicName='default'):
        try:
            self.__topics[topicName].remove(subscriber)

        except ValueError:
            raise self.NotASubscriber()

        except KeyError:
            raise self.NotSuchTopic()

    def _notify(self, sub, value):
        sub(value)

    def notify(self, topicName, value):
        try:
            for sub in self.__topics[topicName]:
                try:
                    self._notify(sub, value)
                except Exception, e:
                    self._logger.warning('The subscriber %s raises an exception' % sub)
                    self._logger.debug('Subscriber exception: %s' % e)

        except KeyError:
            raise self.NotSuchTopic()

    def status(self):
        '''Return the topic configurations compound by dictionary with
        key:IdTopic and value:List of subscribers'''

        return self.__topics.copy()



class ObjectObservable(Observable):
    '''Observer design pattern implementation based in interfaces.

    Observable class:
    * Constructor can optionally receive two params.

    topics   : A dictionary k:id_topic v:callback_name (as string)
    logger   : A logger from logging module

    * Store a manage a dictionary with key:IdTopic, value:list of subscribers'''

    class InvalidObserverInterface(Observable.ObserverException): pass
    class InvalidCallbackName(Observable.ObserverException): pass

    def __init__(self, topics={'default':'update'},
                 logger=logging.getLogger('Observable')):

        Observable.__init__(self, topics.keys(), logger)

        #Topics:
        # key: id_topic
        # val:(str_callback, [subscribers_callbacks])
        self.__interface = {}

        for topicName, topicCb in topics.items():
            if not isinstance(topicName, str):
                raise self.InvalidTopic(topicName)

            if not isinstance(topicCb, str):
                raise self.InvalidObserverInterface(topicCb)

            self.__interface[topicName] = topicCb


    def addTopic(self, topic, callbackName):
        '''Register a new topic. If the topic exists raise the
        TopicAlreadyExists exception'''

        if not isinstance(callbackName, str):
            raise self.InvalidCallbackName()

        if topic in self.__interface.keys():
            raise Observable.TopicAlreadyExists(topic)

        Observable.addTopic(self, topic)
        self.__interface[topic] = callbackName

        self._logger.debug('Added topic [%s] with callback [%s]' %
                           (str(topic), callbackName))


    def removeTopic(self, topicName):
        '''Unregister a topic. If the topic not exists raise the
        NotSuchTopic exception'''

        try:
            del self.__interface[topic]
            Observable.removeTopic(self, topicName)
            self._logger.debug('Removed topic [%s]' % str(topic))

        except KeyError:
            raise self.NotSuchTopic()


    def attach(self, subscriber, topicName='default'):
        '''Subscribe a class into topic. If topic not is specified,
        the subscriber is registered into default topic. If the topic
        not exits raise NotSuchTopic exception'''

        try:
            meth = getattr(subscriber, self.__interface[topicName])
            Observable.attach(self, meth, topicName)
            self._logger.debug('Subscribed [%s]' % str(subscriber))

        except KeyError:
            raise self.NotSuchTopic(topicName)

        except AttributeError:
            raise self.InvalidObserverInterface()


    def detach(self, subscriber, topic='default'):
        '''Unsubscribe a subscriber class from a topic. If topic not
        exist raise the NotSuchTopic exception. If the subscriber not
        is subcribed into topic raise the NotSuchObserver exception'''

        try:
            meth = getattr(subscriber, self.__interface[topic])

            Observable.detach(self, meth, topic)
            self._logger.debug('Unsubscribe [%s] from [%s]' % \
                                (str(subscriber), str(topic)))

        except AttributeError:
            raise self.InvalidObserverInterface()

        except KeyError:
            raise Observable.NotSuchTopic()

class ObjectObservableAsync(ObjectObservable):
    '''Observer design pattern implementation.
    Observable Asynchronous class (one thread by notification).

    * Constructor can optionally receive four params:

    topics   : A dictionary k:id_topic v:callback_name (as string)
    pollSize: Size of thread poll for asyncronous notifications (15 by default)
    logger   : A logger from logging module

    * Store a manage a dictionary with key:IdTopic, value:list of subscribers
    * Store and manage the thread poll of asyncronous notifications
    * Wait to end all the notifications
    * If the thread poll is full the notifications will be ignore'''

    class CallbackThread(threading.Thread):
        def __init__(self, callback, value, onExit):
            threading.Thread.__init__(self)
            self._cb = callback
            self._val = value
            self._onExit = onExit

        def run(self):
            try:
                self._cb(self._val)
            finally:
                self._onExit(self.getName())


    def __init__(self, topics={'default':'update'},
                 pollSize=15, logger=logging.getLogger('Observable')):
        ObjectObservable.__init__(self, topics, logger)

        self._poll = pollSize
        self._lockAT = allocate_lock()
        self._activeThreads = 0
        self._threads = {}

    # Private Method

    def _onExit(self, ident):
        '''Unregister the thread of the active threads'''

        self._lockAT.acquire()
        self._activeThreads = self._activeThreads - 1
        try:
            del self._threads[ident]
        except KeyError, e:
            self._log.debug('Thread [%s] already removed' % ident)
        finally:
            self._lockAT.release()

    # Private overwrite method

    def _notify(self, subs_cb, value):
        '''Overwrite the _nofify method to use asyncronous
        notification. Start the method into Thread and register it'''

        if self._poll >= self._activeThreads:
            t = self.CallbackThread(subs_cb, value, self._onExit)

            self._lockAT.acquire()
            self._threads[t.getName()] = t
            self._activeThreads = self._activeThreads + 1
            self._lockAT.release()

            t.start()

        else:
            self._log.error('Unable notify, full poll')

    # Public overwrite method

    def status(self):
        '''Overwrite the status method to return the tuple status
        compound by: Topics - Dictionary k:IdTopic, v:List of
        subscribers Number Threads - Number of active threads
        '''

        return (self._topics.copy(), self._activeThreads)