root / src / session.py @ 45fef9ac
History | View | Annotate | Download (2.4 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 content import Creator, Parser |
16 |
|
17 |
from threading import Thread |
18 |
from listener import Subject, Listener |
19 |
|
20 |
class SessionError(ncclientError): pass |
21 |
|
22 |
class Session(Thread, Subject, Listener): |
23 |
|
24 |
def __init__(self, capabilities=None): |
25 |
Thread.__init__(self, name='session') |
26 |
Subject.__init__(self, listeners=[self]) |
27 |
Thread.setDaemon(True)
|
28 |
self.client_capabilities = capabilities
|
29 |
self.server_capabilities = None # yet |
30 |
self.id = None # session-id |
31 |
self.is_connected = False |
32 |
self._q = Queue.Queue()
|
33 |
|
34 |
def _make_hello(self): |
35 |
pass
|
36 |
|
37 |
def _init(self, id, capabilities): |
38 |
self.id = id |
39 |
self.capabilities[SERVER] = capabilities
|
40 |
self.is_connected = True |
41 |
|
42 |
@override
|
43 |
def _close(self): |
44 |
raise NotImplementedError |
45 |
|
46 |
def connect(self): |
47 |
self._greet()
|
48 |
Thread.start() |
49 |
|
50 |
def send(self, msg): |
51 |
if self.is_connected: |
52 |
self._q.add(msg)
|
53 |
else:
|
54 |
raise SessionError('Attempted to send message while not connected') |
55 |
|
56 |
### Thread methods
|
57 |
|
58 |
@override
|
59 |
def run(self): |
60 |
raise NotImplementedError |
61 |
|
62 |
### Subject methods
|
63 |
|
64 |
def add_listener(self, listener): |
65 |
if not self.is_connected: |
66 |
raise SessionError('Listeners may only be added after session initialisation') |
67 |
else:
|
68 |
Subject.add_listner(self, listener)
|
69 |
|
70 |
### Listener methods
|
71 |
# these are relevant for the initial greeting only
|
72 |
|
73 |
def reply(self, data): |
74 |
p = Parser(data) |
75 |
s = p['session']
|
76 |
id = s['@id']
|
77 |
capabilities = Capabilities() |
78 |
capabilities.fromXML(p['capabilities'])
|
79 |
self._init(id, capabilities) |
80 |
self.remove_listener(self) |
81 |
|
82 |
def error(self, data): |
83 |
self._close()
|
84 |
raise SSHError('Session initialization failed') |
85 |
|