root / ncclient / transport / hello.py @ 1d540e60
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, self._error_cb = init_cb, error_cb |
28 |
|
29 |
def __str__(self): |
30 |
return 'HelloListener' |
31 |
|
32 |
def callback(self, root, raw): |
33 |
if __(root[0]) == 'hello': |
34 |
try:
|
35 |
id, capabilities = HelloHandler.parse(raw)
|
36 |
except Exception as e: |
37 |
self._error_cb(e)
|
38 |
else:
|
39 |
self._init_cb(id, capabilities) |
40 |
|
41 |
def errback(self, err): |
42 |
self._error_cb(err)
|
43 |
|
44 |
@staticmethod
|
45 |
def build(capabilities, encoding='utf-8'): |
46 |
"Given a list of capability URI's returns encoded <hello> message"
|
47 |
spec = { |
48 |
'tag': _('hello', BASE_NS), |
49 |
'children': [{
|
50 |
'tag': 'capabilities', |
51 |
'children': # this is fun :-) |
52 |
[{ 'tag': 'capability', 'text': uri} for uri in capabilities] |
53 |
}] |
54 |
} |
55 |
return TreeBuilder(spec).to_string(encoding)
|
56 |
|
57 |
@staticmethod
|
58 |
def parse(raw): |
59 |
"Returns tuple of ('session-id', ['capability_uri', ...])"
|
60 |
sid, capabilities = 0, []
|
61 |
root = ET.fromstring(raw) |
62 |
for child in root.getchildren(): |
63 |
if __(child.tag) == 'session-id': |
64 |
sid = child.text |
65 |
elif __(child.tag) == 'capabilities': |
66 |
for cap in child.getiterator(_('capability', BASE_NS)): |
67 |
capabilities.append(cap.text) |
68 |
# cisco doesn't namespace hello message
|
69 |
for cap in child.getiterator('capability'): |
70 |
capabilities.append(cap.text) |
71 |
return sid, capabilities
|