Statistics
| Branch: | Tag: | Revision:

root / ncclient / rpc / reply.py @ cc8de468

History | View | Annotate | Download (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 xml.etree import cElementTree as ET
16

    
17
from ncclient.content import multiqualify as _
18
from ncclient.content import unqualify as __
19

    
20
import logging
21
logger = logging.getLogger('ncclient.operations.reply')
22

    
23
class RPCReply:
24
    
25
    def __init__(self, raw):
26
        self._raw = raw
27
        self._parsed = False
28
        self._errors = []
29
    
30
    def __repr__(self):
31
        return self._raw
32
    
33
    def parse(self):
34
        if self._parsed: return
35
        root = ET.fromstring(self._raw) # <rpc-reply> element
36
        
37
        if __(root.tag) != 'rpc-reply':
38
            raise ValueError('Root element is not RPC reply')
39
        
40
        # per rfc 4741 an <ok/> tag is sent when there are no errors or warnings
41
        oktags = _('ok')
42
        for oktag in oktags:
43
            if root.find(oktag) is not None:
44
                logger.debug('parsed [%s]' % oktag)
45
                self._parsed = True
46
                return
47
        
48
        # create RPCError objects from <rpc-error> elements
49
        errtags = _('rpc-error')
50
        for errtag in errtags:
51
            for err in root.getiterator(errtag): # a particular <rpc-error>
52
                logger.debug('parsed [%s]' % errtag)
53
                d = {}
54
                for err_detail in err.getchildren(): # <error-type> etc..
55
                    tag = __(err_detail.tag)
56
                    d[tag] = (err_detail.text.strip() if tag != 'error-info'
57
                              else ET.tostring(err_detail, 'utf-8'))
58
                self._errors.append(RPCError(d))
59
            if self._errors:
60
                break
61
        
62
        self._parsed = True
63
    
64
    @property
65
    def raw(self):
66
        return self._raw
67
    
68
    @property
69
    def ok(self):
70
        if not self._parsed: self.parse()
71
        return not self._errors # empty list => false
72
    
73
    @property
74
    def errors(self):
75
        'List of RPCError objects. Will be empty if no <rpc-error> elements in reply.'
76
        if not self._parsed: self.parse()
77
        return self._errors
78

    
79

    
80
class RPCError(Exception): # raise it if you like
81
    
82
    def __init__(self, err_dict):
83
        self._dict = err_dict
84
        if self.message is not None:
85
            Exception.__init__(self, self.message)
86
        else:
87
            Exception.__init__(self)
88
    
89
    @property
90
    def raw(self):
91
        return self._element.tostring()
92
    
93
    @property
94
    def type(self):
95
        return self.get('error-type', None)
96
    
97
    @property
98
    def severity(self):
99
        return self.get('error-severity', None)
100
    
101
    @property
102
    def tag(self):
103
        return self.get('error-tag', None)
104
    
105
    @property
106
    def path(self):
107
        return self.get('error-path', None)
108
    
109
    @property
110
    def message(self):
111
        return self.get('error-message', None)
112
    
113
    @property
114
    def info(self):
115
        return self.get('error-info', None)
116

    
117
    ## dictionary interface
118
    
119
    __getitem__ = lambda self, key: self._dict.__getitem__(key)
120
    
121
    __iter__ = lambda self: self._dict.__iter__()
122
    
123
    __contains__ = lambda self, key: self._dict.__contains__(key)
124
    
125
    keys = lambda self: self._dict.keys()
126
    
127
    get = lambda self, key, default: self._dict.get(key, default)
128
        
129
    iteritems = lambda self: self._dict.iteritems()
130
    
131
    iterkeys = lambda self: self._dict.iterkeys()
132
    
133
    itervalues = lambda self: self._dict.itervalues()
134
    
135
    values = lambda self: self._dict.values()
136
    
137
    items = lambda self: self._dict.items()
138
    
139
    __repr__ = lambda self: repr(self._dict)