root / ncclient / transport / hello.py @ 41e2ed46
History | View | Annotate | Download (2.5 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 |
"All to do with NETCONF <hello> messages"
|
16 |
|
17 |
from xml.etree import cElementTree as ET |
18 |
|
19 |
from ncclient.glue import Listener |
20 |
from ncclient.content import TreeBuilder, BASE_NS |
21 |
from ncclient.content import qualify as _ |
22 |
from ncclient.content import unqualify as __ |
23 |
|
24 |
class HelloHandler(Listener): |
25 |
|
26 |
def __init__(self, init_cb, error_cb): |
27 |
self._init_cb = init_cb
|
28 |
self._error_cb = error_cb
|
29 |
|
30 |
def __str__(self): |
31 |
return 'HelloListener' |
32 |
|
33 |
def callback(self, root, raw): |
34 |
if __(root[0]) == 'hello': |
35 |
try:
|
36 |
id, capabilities = HelloHandler.parse(raw)
|
37 |
except Exception as e: |
38 |
self._error_cb(e)
|
39 |
else:
|
40 |
self._init_cb(id, capabilities) |
41 |
|
42 |
def errback(self, err): |
43 |
self._error_cb(err)
|
44 |
|
45 |
@staticmethod
|
46 |
def build(capabilities, encoding='utf-8'): |
47 |
"Given a list of capability URI's returns encoded <hello> message"
|
48 |
spec = { |
49 |
'tag': _('hello', BASE_NS), |
50 |
'children': [{
|
51 |
'tag': 'capabilities', |
52 |
'children': # this is fun :-) |
53 |
[{ 'tag': 'capability', 'text': uri} for uri in capabilities] |
54 |
}] |
55 |
} |
56 |
return TreeBuilder(spec).to_string(encoding)
|
57 |
|
58 |
@staticmethod
|
59 |
def parse(raw): |
60 |
"Returns tuple of ('session-id', ['capability_uri', ...])"
|
61 |
sid, capabilities = 0, []
|
62 |
root = ET.fromstring(raw) |
63 |
for child in root.getchildren(): |
64 |
if __(child.tag) == 'session-id': |
65 |
sid = child.text |
66 |
elif __(child.tag) == 'capabilities': |
67 |
for cap in child.getiterator(_('capability', BASE_NS)): |
68 |
capabilities.append(cap.text) |
69 |
# cisco doesn't namespace hello message
|
70 |
for cap in child.getiterator('capability'): |
71 |
capabilities.append(cap.text) |
72 |
return sid, capabilities
|