Statistics
| Branch: | Tag: | Revision:

root / ncclient / transport / hello.py @ e91a5349

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
"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
def build(capabilities, encoding='utf-8'):
25
    "Given a list of capability URI's returns encoded <hello> message"
26
    spec = {
27
        'tag': _('hello', BASE_NS),
28
        'children': [{
29
            'tag': 'capabilities',
30
            'children': # this is fun :-)
31
                [{ 'tag': 'capability', 'text': uri} for uri in capabilities]
32
            }]
33
        }
34
    return TreeBuilder(spec).to_string(encoding)
35

    
36
def parse(raw):
37
    "Returns tuple of (session-id, ['capability_uri', ...])"
38
    sid, capabilities = 0, []
39
    root = ET.fromstring(raw)
40
    for child in root.getchildren():
41
        if __(child.tag) == 'session-id':
42
            sid = child.text
43
        elif __(child.tag) == 'capabilities':
44
            for cap in child.getiterator(_('capability', BASE_NS)):
45
                capabilities.append(cap.text)
46
            # cisco doesn't namespace hello message
47
            for cap in child.getiterator('capability'): 
48
                capabilities.append(cap.text)
49
    return sid, capabilities
50

    
51

    
52
class HelloListener(Listener):
53
    
54
    def __init__(self, init_cb, error_cb):
55
        self._init_cb, self._error_cb = init_cb, error_cb
56
    
57
    def __str__(self):
58
        return 'HelloListener'
59
    
60
    def callback(self, root, raw):
61
        if __(root[0]) == 'hello':
62
            try:
63
                id, capabilities = parse(raw)
64
            except Exception as e:
65
                self._error_cb(e)
66
            else:
67
                self._init_cb(id, capabilities)
68
    
69
    def errback(self, err):
70
        self._error_cb(err)