Statistics
| Branch: | Tag: | Revision:

root / ncclient / transport / session.py @ 94265508

History | View | Annotate | Download (4.1 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 Thread, Lock, Event
16
from Queue import Queue
17

    
18
from . import logger
19
from ncclient.capabilities import Capabilities, CAPABILITIES
20

    
21

    
22
class Subject:
23

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

    
52

    
53
class Session(Thread, Subject):
54
    
55
    def __init__(self):
56
        Thread.__init__(self, name='session')
57
        Subject.__init__(self)
58
        self._client_capabilities = CAPABILITIES
59
        self._server_capabilities = None # yet
60
        self._id = None # session-id
61
        self._q = Queue()
62
        self._connected = False # to be set/cleared by subclass implementation
63
    
64
    def _post_connect(self):
65
        from ncclient.content.builders import HelloBuilder
66
        self.send(HelloBuilder.build(self._client_capabilities))
67
        error = None
68
        init_event = Event()
69
        # callbacks
70
        def ok_cb(id, capabilities):
71
            self._id, self._server_capabilities = id, Capabilities(capabilities)
72
            init_event.set()
73
        def err_cb(err):
74
            error = err
75
            init_event.set()
76
        listener = HelloListener(ok_cb, err_cb)
77
        self.add_listener(listener)
78
        # start the subclass' main loop
79
        self.start()
80
        # we expect server's hello message
81
        init_event.wait()
82
        # received hello message or an error happened
83
        self.remove_listener(listener)
84
        if error:
85
            raise error
86
        logger.info('initialized: session-id=%s | server_capabilities=%s' %
87
                     (self.id, self.server_capabilities))
88
    
89
    def send(self, message):
90
        logger.debug('queueing:%s' % message)
91
        self._q.put(message)
92
    
93
    def connect(self):
94
        raise NotImplementedError
95

    
96
    def run(self):
97
        raise NotImplementedError
98
    
99
    ### Properties
100
    
101
    @property
102
    def client_capabilities(self):
103
        return self._client_capabilities
104
    
105
    @property
106
    def server_capabilities(self):
107
        return self._server_capabilities
108
    
109
    @property
110
    def connected(self):
111
        return self._connected
112
    
113
    @property
114
    def id(self):
115
        return self._id
116

    
117

    
118
class HelloListener:
119
    
120
    def __init__(self, init_cb, error_cb):
121
        self._init_cb, self._error_cb = init_cb, error_cb
122
    
123
    def __str__(self):
124
        return 'HelloListener'
125
    
126
    ### Events
127
    
128
    def received(self, raw):
129
        logger.debug(raw)
130
        from ncclient.content.parsers import HelloParser
131
        try:
132
            id, capabilities = HelloParser.parse(raw)
133
        except Exception as e:
134
            self._error_cb(e)
135
        else:
136
            self._init_cb(id, capabilities)
137
    
138
    def error(self, err):
139
        self._error_cb(err)