Debian Codegraph @

lib/jnpr/junos/decorators.py

raw
1 # stdlib
2 from functools import wraps
3 import re
4 import sys
5
6 from lxml import etree
7 from ncclient.operations.rpc import RPCError
8 from ncclient.xml_ import NCElement
9 from jnpr.junos import jxml as JXML
10
11
12 def timeoutDecorator(function):
13 @wraps(function)
14 def wrapper(*args, **kwargs):
15 if "dev_timeout" in kwargs:
16 try:
17 dev = args[0].dev
18 except:
19 dev = args[0]
20 restore_timeout = dev.timeout
21 dev.timeout = kwargs.pop("dev_timeout", None)
22 try:
23 result = function(*args, **kwargs)
24 dev.timeout = restore_timeout
25 return result
26 except Exception:
27 dev.timeout = restore_timeout
28 raise
29 else:
30 try:
31 return function(*args, **kwargs)
32 except Exception:
33 raise
34
35 return wrapper
36
37
38 def normalizeDecorator(function):
39 @wraps(function)
40 def wrapper(*args, **kwargs):
41 if "normalize" in kwargs:
42 normalize = kwargs.pop("normalize", None)
43 try:
44 dev = args[0].dev
45 except:
46 dev = args[0]
47
48 if dev._normalize != normalize:
49 restore_transform = dev.transform
50
51 if normalize is False:
52 try:
53 dev.transform = dev._nc_transform
54 result = function(*args, **kwargs)
55 dev.transform = restore_transform
56 return result
57 except Exception:
58 dev.transform = restore_transform
59 raise
60 else:
61 try:
62 dev.transform = dev._norm_transform
63 result = function(*args, **kwargs)
64 dev.transform = restore_transform
65 return result
66 except Exception:
67 dev.transform = restore_transform
68 raise
69 else:
70 try:
71 return function(*args, **kwargs)
72 except Exception:
73 raise
74 else:
75 try:
76 return function(*args, **kwargs)
77 except Exception:
78 raise
79
80 return wrapper
81
82
83 def ignoreWarnDecorator(function):
84 """
85 Ignore warnings if all <rpc-error> elements are at severity 'warning' and
86 match one of the values of the ignore_warning argument.
87
88 For example::
89 dev.rpc.get(ignore_warning=True)
90 dev.rpc.get(ignore_warning='vrrp subsystem not running')
91 dev.rpc.get(ignore_warning=['vrrp subsystem not running',
92 'statement not found'])
93 cu.load(cnf, ignore_warning='statement not found')
94
95 :ignore_warning: A boolean, string or list of string.
96 If the value is True, it will ignore all warnings regarldess of the
97 warning message. If the value is a string, it will ignore warning(s) if
98 the message of each warning matches the string. If the value is a list
99 of strings, ignore warning(s) if the message of each warning matches at
100 least one of the strings in the list.
101
102 .. note::
103 When the value of ignore_warning is a string, or list of strings,
104 the string is actually used as a case-insensitive regular
105 expression pattern. If the string contains only alpha-numeric
106 characters, as shown in the above examples, this results in a
107 case-insensitive substring match. However, any regular expression
108 pattern supported by the re library may be used for more
109 complicated match conditions.
110 """
111
112 @wraps(function)
113 def wrapper(self, *args, **kwargs):
114 ignore_warning = kwargs.pop("ignore_warning", False)
115 rsp = None
116 try:
117 rsp = function(self, *args, **kwargs)
118 except RPCError as ex:
119 if hasattr(ex, "xml") and ignore_warning:
120 if hasattr(ex, "errors"):
121 errors = ex.errors
122 else:
123 errors = [ex]
124 for err in errors:
125 if err.severity == "warning":
126 if (
127 sys.version < "3"
128 and isinstance(ignore_warning, (str, unicode))
129 ) or (sys.version >= "3" and isinstance(ignore_warning, str)):
130 if not re.search(ignore_warning, err.message, re.I):
131 # Message did not match.
132 raise ex
133 elif isinstance(ignore_warning, list):
134 for warn_msg in ignore_warning:
135 if re.search(warn_msg, err.message, re.I):
136 # Warning matches.
137 # Break skips else.
138 break
139 else:
140 # Message didn't match any of the
141 # ignore_warn pattern values.
142 raise ex
143 else:
144 # Not a warning (probably an error).
145 raise ex
146 # Every err was a warning that matched ignore_warning.
147 # Prepare the response which will get returned.
148 # ex.xml contains the raw xml response which was
149 # received, but might be rooted at an <rpc-error> element.
150 # Set rsp to the root <rpc-reply> element.
151 rsp = ex.xml.getroottree().getroot()
152 # 1) A normal response has been run through the XSLT
153 # transformation, but ex.xml has not. Do that now.
154 encode = None if sys.version < "3" else "unicode"
155 rsp = NCElement(
156 etree.tostring(rsp, encoding=encode), self.transform()
157 )._NCElement__doc
158 # 2) Now remove all of the <rpc-error> elements from
159 # the response. We've already confirmed they are
160 # all warnings
161 rsp = etree.fromstring(str(JXML.strip_rpc_error_transform(rsp)))
162 else:
163 # ignore_warning was false, or an RPCError which doesn't have
164 # an XML attribute. Raise it up for the caller to deal with.
165 raise ex
166 return rsp
167
168 return wrapper
169
170
171 def checkSAXParserDecorator(function):
172 @wraps(function)
173 def wrapper(*args, **kwargs):
174 # args[0] is self
175 use_filter = kwargs.pop("use_filter", args[0]._use_filter)
176 restore_value = args[0]._use_filter
177 args[0]._use_filter = use_filter
178 try:
179 if args[0].D != None:
180 func = args[0].D.transform
181 result = function(*args, **kwargs)
182 args[0]._use_filter = restore_value
183 if args[0].D != None:
184 args[0].D.transform = func
185 return result
186 except Exception:
187 args[0]._use_filter = restore_value
188 raise
189
190 return wrapper