Statistics
| Branch: | Tag: | Revision:

root / ncclient / subject.py @ ee4bb099

History | View | Annotate | Download (1.6 kB)

1
# Copyright 2009 Shikhar Bhushan
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

    
15
from threading import Lock
16

    
17
import logging
18

    
19
logger = logging.getLogger('ncclient.subject')
20

    
21
class Subject:
22
        
23
    def __init__(self, listeners=[]):
24
        self._listeners = set(listeners)
25
        self._lock = Lock()
26
    
27
    def has_listener(self, listener):
28
        with self._lock:
29
            return (listener in self._listeners)
30
    
31
    def add_listener(self, listener):
32
        with self._lock:
33
            self._listeners.add(listener)
34
    
35
    def remove_listener(self, listener):
36
        with self._lock:
37
            self._listeners.discard(listener)
38
    
39
    def dispatch(self, event, *args, **kwds):
40
        # holding the lock while doing callbacks could lead to a deadlock
41
        # if one of the above methods is called
42
        with self._lock:
43
            listeners = list(self._listeners)
44
        for l in listeners:
45
            try:
46
                logger.debug('dispatching [%s] to [%s]' % (event, l))
47
                getattr(l, event)(*args, **kwds)
48
            except Exception as e:
49
                logger.warning(e)