Statistics
| Branch: | Tag: | Revision:

root / ncclient / listeners.py @ ee4bb099

History | View | Annotate | Download (2.3 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
import logging
16
from weakref import WeakValueDictionary
17

    
18
import content
19

    
20
logger = logging.getLogger('ncclient.listeners')
21

    
22
session_listeners = {}
23
def session_listener_factory(session):
24
    try:
25
        return session_listeners[session]
26
    except KeyError:
27
        session_listeners[session] = SessionListener()
28
        return session_listeners[session]
29

    
30
class SessionListener(object):
31
    
32
    def __init__(self):
33
        self._id2rpc = WeakValueDictionary()
34
        self._expecting_close = False
35
        self._subscription = None
36
    
37
    def __str__(self):
38
        return 'SessionListener'
39
    
40
    def set_subscription(self, id):   
41
        self._subscription = id
42
    
43
    def expect_close(self):
44
        self._expecting_close = True
45
    
46
    def register(self, id, op):
47
        self._id2rpc[id] = op
48
    
49
    ### Events
50
    
51
    def reply(self, raw):
52
        try:
53
            id = content.parse_message_root(raw)
54
            if id is None:
55
                pass
56
            elif id == 'notification':
57
                self._id2rpc[self._sub_id]._notify(raw)
58
            else:
59
                self._id2rpc[id]._response_cb(raw)
60
        except Exception as e:
61
            logger.warning(e)
62
    
63
    def error(self, err):
64
        from ssh import SessionCloseError
65
        if err is SessionCloseError:
66
            logger.debug('received session close, expecting_close=%s' %
67
                         self._expecting_close)
68
            if not self._expecting_close:
69
                raise err
70

    
71
class DebugListener:
72
    
73
    def __str__(self):
74
        return 'DebugListener'
75
    
76
    def reply(self, raw):
77
        logger.debug('DebugListener:reply:\n%s' % raw)
78
    
79
    def error(self, err):
80
        logger.debug('DebugListener:error:\n%s' % err)