Debian Codegraph @

lib/jnpr/junos/factory/cfgtable.py

raw
1 from copy import deepcopy
2 import re
3
4 from lxml import etree
5 from lxml.builder import E
6 from jnpr.junos.factory.table import Table
7 from jnpr.junos import jxml
8 from jnpr.junos.utils.config import Config
9
10
11 class CfgTable(Table):
12 __isfrozen = False
13
14 # -----------------------------------------------------------------------
15 # CONSTRUCTOR
16 # -----------------------------------------------------------------------
17 def __init__(self, dev=None, xml=None, path=None, mode=None):
18 Table.__init__(self, dev, xml, path) # call parent constructor
19
20 self._init_get()
21 self._data_dict = self.DEFINE # crutch
22 self.ITEM_NAME_XPATH = self._data_dict.get("key", "name")
23 self.view = self._data_dict.get("view")
24 self._options = self._data_dict.get("options")
25 self.mode = mode
26 if "set" in self._data_dict:
27 Config.__init__(self, dev, mode) # call parent constructor
28
29 self._init_set()
30 if self._view:
31 self.fields = self._view.FIELDS.copy()
32 else:
33 raise ValueError(
34 "%s set table view is not defined.\n" % (self.__class__.__name__)
35 )
36 if "key-field" in self._data_dict:
37 key_name = self._data_dict.get("key-field", None)
38 if isinstance(key_name, list):
39 self.key_field = key_name
40 elif isinstance(key_name, str):
41 self.key_field = [key_name]
42 else:
43 raise TypeError(
44 "Key-field %s is of invalid type %s.\n"
45 % (key_name, type(key_name))
46 )
47 else:
48 raise ValueError("Table should have key-field attribute defined\n")
49 self._type = "set"
50 self._init_field()
51 else:
52 self._type = "get"
53 self.ITEM_XPATH = self._data_dict[self._type]
54
55 # no new attributes.
56 self._freeze()
57
58 # -----------------------------------------------------------------------
59 # PROPERTIES
60 # -----------------------------------------------------------------------
61
62 @property
63 def required_keys(self):
64 """
65 return a list of the keys required when invoking :get():
66 and :get_keys():
67 """
68 return self._data_dict.get("required_keys")
69
70 @property
71 def keys_required(self):
72 """True/False - if this Table requires keys"""
73 return self.required_keys is not None
74
75 # -----------------------------------------------------------------------
76 # PRIVATE METHODS
77 # -----------------------------------------------------------------------
78 def _init_get(self):
79 self._get_xpath = None
80
81 # for debug purposes
82 self._get_cmd = None
83 self._get_opt = None
84
85 def _init_set(self):
86 self._insert_node = None
87
88 # lxml object of configuration xml
89 self._config_xml_req = None
90
91 # To check if field value is set.
92 self._is_field_set = False
93
94 # for debug purposes
95 self._load_rsp = None
96 self._commit_rsp = None
97
98 def _buildxml(self, namesonly=False):
99 """
100 Return an lxml Element starting with <configuration> and comprised
101 of the elements specified in the xpath expression.
102
103 For example, and xpath = 'interfaces/interface' would produce:
104
105 <configuration>
106 <interfaces>
107 <interface/>
108 </interfaces>
109 </configuration>
110
111 If :namesonly: is True, then the XML will be encoded only to
112 retrieve the XML name keys at the 'end' of the XPath expression.
113
114 This return value can then be passed to dev.rpc.get_config()
115 to retrieve the specifc data
116 """
117 xpath = self._data_dict[self._type]
118 self._get_xpath = "//configuration/" + xpath
119 top = E("configuration")
120 dot = top
121 for name in xpath.split("/"):
122 dot.append(E(name))
123 dot = dot[0]
124
125 if namesonly is True:
126 dot.attrib["recurse"] = "false"
127 return top
128
129 def _build_config_xml(self, top):
130 """
131 used to encode the field values into the configuration XML
132 for set table,each of the field=<value> pairs are defined by user:
133 """
134 for field_name, opt in self.fields.items():
135 dot = top
136 # create an XML element with the key/value
137 field_value = getattr(self, field_name, None)
138 # If field value is not set ignore it
139 if field_value is None:
140 continue
141
142 if isinstance(field_value, (list, tuple, set)):
143 [self._validate_value(field_name, v, opt) for v in field_value]
144 else:
145 self._validate_value(field_name, field_value, opt)
146
147 field_dict = self.fields[field_name]
148
149 if "group" in field_dict:
150 group_xpath = self._view.GROUPS[field_dict["group"]]
151 dot = self._encode_xpath(top, group_xpath.split("/"))
152
153 lxpath = field_dict["xpath"].split("/")
154 if len(lxpath) > 1:
155 dot = self._encode_xpath(top, lxpath[0 : len(lxpath) - 1])
156
157 add_field = self._grindfield(lxpath[-1], field_value)
158 for _add in add_field:
159 if len(_add.attrib) > 0:
160 for i in dot.iter():
161 if i.tag == _add.tag:
162 i.attrib.update(_add.attrib)
163 break
164 else:
165 dot.append(_add)
166 elif field_name in self.key_field:
167 dot.insert(0, _add)
168 else:
169 dot.append(_add)
170
171 def _validate_value(self, field_name, value, opt):
172 """
173 Validate value set for field against the constraints and
174 data type check define in yml table/view defination.
175
176 :param field_name: Name of field as mentioned in yaml table/view
177 :param value: Value set by user for field_name.
178 :param opt: Dictionary of data type and constraint check.
179 :return:
180 """
181
182 def _get_field_type(ftype):
183 ft = {
184 "str": str,
185 "int": int,
186 "float": float,
187 "bool": bool,
188 }.get(ftype, None)
189
190 if ft is None:
191 raise TypeError("Unsupported type %s\n" % (ftype))
192 return ft
193
194 def _validate_enum_value(field_name, value, enum_value):
195 if isinstance(enum_value, list):
196 if value not in enum_value:
197 raise ValueError(
198 "Invalid value %s assigned " "to field %s" % (value, field_name)
199 )
200 elif isinstance(enum_value, str):
201 if not value == enum_value:
202 raise ValueError(
203 "Invalid value %s assigned " "to field %s" % (value, field_name)
204 )
205 else:
206 raise TypeError(
207 "Value of enum should " "be either a string or list of strings.\n"
208 )
209
210 def _validate_type(field_name, value, opt):
211 if isinstance(opt["type"], dict):
212 if "enum" in opt["type"]:
213 _validate_enum_value(field_name, value, opt["type"]["enum"])
214 else:
215 # More user defined type check can be added in future.
216 # raise execption for now.
217 raise TypeError("Unsupported type %s\n" % (opt["type"]))
218
219 elif isinstance(opt["type"], str):
220 field_type = _get_field_type(opt["type"])
221 if not isinstance(value, field_type):
222 raise TypeError(
223 "Invalid value %s asigned to field %s,"
224 " value should be of type %s\n"
225 % (value, field_name, field_type)
226 )
227 else:
228 raise TypeError(
229 "Invalid value %s, should be either of"
230 " type string or dictionary.\n" % (opt["type"])
231 )
232
233 def _validate_min_max_value(field_name, value, opt):
234 if isinstance(value, (int, float)):
235 if value < opt["minValue"] or value > opt["maxValue"]:
236 raise ValueError(
237 "Invalid value %s assigned "
238 "to field %s.\n" % (value, field_name)
239 )
240 elif isinstance(value, str):
241 if len(value) < opt["minValue"] or len(value) > opt["maxValue"]:
242 raise ValueError(
243 "Invalid value %s assigned "
244 "to field %s.\n" % (value, field_name)
245 )
246
247 if isinstance(value, dict):
248 # in case user want to pass operation attr for ex:
249 # <unit operation="delete"/>
250 pass
251 elif isinstance(value, (list, tuple, dict, set)):
252 raise ValueError("%s value is invalid %s\n" % (field_name, value))
253 else:
254 if "type" in opt:
255 _validate_type(field_name, value, opt)
256 if ("minValue" or "maxValue") in opt:
257 _validate_min_max_value(field_name, value, opt)
258
259 def _grindkey(self, key_xpath, key_value):
260 """returns list of XML elements for key values"""
261 simple = lambda: [E(key_xpath.replace("_", "-"), key_value)]
262 composite = lambda: [
263 E(xp.replace("_", "-"), xv) for xp, xv in zip(key_xpath, key_value)
264 ]
265 return simple() if isinstance(key_xpath, str) else composite()
266
267 def _grindxpath(self, key_xpath, key_value):
268 """returns xpath elements for key values"""
269 simple = lambda: "[{}='{}']".format(key_xpath.replace("_", "-"), key_value)
270 composite = lambda: "[{}]".format(
271 " and ".join(
272 [
273 "{}='{}'".format(xp.replace("_", "-"), xv)
274 for xp, xv in zip(key_xpath, key_value)
275 ]
276 )
277 )
278 return simple() if isinstance(key_xpath, str) else composite()
279
280 def _grindfield(self, xpath, value):
281 """returns list of xml elements for field name-value pairs"""
282 lst = []
283 if isinstance(value, (list, tuple, set)):
284 for v in value:
285 lst.append(E(xpath.replace("_", "-"), str(v)))
286 elif isinstance(value, bool):
287 if value is True:
288 lst.append(E(xpath.replace("_", "-")))
289 elif value is False:
290 lst.append(E(xpath.replace("_", "-"), {"operation": "delete"}))
291 elif isinstance(value, dict):
292 lst.append(E(xpath.replace("_", "-"), value))
293 else:
294 lst.append(E(xpath.replace("_", "-"), str(value)))
295 return lst
296
297 def _encode_requiredkeys(self, get_cmd, kvargs):
298 """
299 used to encode the required_keys values into the XML get-command.
300 each of the required_key=<value> pairs are defined in :kvargs:
301 """
302 rqkeys = self._data_dict["required_keys"]
303 for key_name in self.required_keys:
304 # create an XML element with the key/value
305 key_value = kvargs.get(key_name)
306 if key_value is None:
307 raise ValueError("Missing required-key: '%s'" % (key_name))
308 key_xpath = rqkeys[key_name]
309 add_keylist_xml = self._grindkey(key_xpath, key_value)
310
311 # now link this item into the XML command, where key_name
312 # designates the XML parent element
313 key_name = key_name.replace("_", "-")
314 dot = get_cmd.find(".//" + key_name)
315 if dot is None:
316 raise RuntimeError(
317 "Unable to find parent XML for key: '%s'" % (key_name)
318 )
319 for _at, _add in enumerate(add_keylist_xml):
320 dot.insert(_at, _add)
321
322 # Add required key values to _get_xpath
323 xid = re.search(r"\b{}\b".format(key_name), self._get_xpath).start() + len(
324 key_name
325 )
326
327 self._get_xpath = (
328 self._get_xpath[:xid]
329 + self._grindxpath(key_xpath, key_value)
330 + self._get_xpath[xid:]
331 )
332
333 def _encode_namekey(self, get_cmd, dot, namekey_value):
334 """
335 encodes the specific namekey_value into the get command so that the
336 returned XML configuration is the complete hierarchy of data.
337 """
338 namekey_xpath = self._data_dict.get("key", "name")
339 keylist_xml = self._grindkey(namekey_xpath, namekey_value)
340 for _add in keylist_xml:
341 dot.append(_add)
342
343 def _encode_getfields(self, get_cmd, dot):
344 for field_xpath in self._data_dict["get_fields"]:
345 dot.append(E(field_xpath))
346
347 def _encode_xpath(self, top, lst):
348 """
349 Create xml element hierarchy for given field. Return container
350 node to which field and its value will appended as child elements.
351 """
352 dot = top
353 for index in range(1, len(lst) + 1):
354 xp = "/".join(lst[0:index])
355 if not len(top.xpath(xp)):
356 dot.append(E(lst[index - 1]))
357 dot = dot.find(lst[index - 1])
358 return dot
359
360 def _keyspec(self):
361 """returns tuple (keyname-xpath, item-xpath)"""
362 return (self._data_dict.get("key", "name"), self._data_dict[self._type])
363
364 def _init_field(self):
365 """
366 Initialize fields of set table to it's default value
367 (if mentioned in yml Table/View) else set to None.
368 """
369 for fname, opt in self.fields.items():
370 self.__dict__[fname] = opt["default"] if "default" in opt else None
371
372 def _mandatory_check(self):
373 """Mandatory checks for set table/view"""
374 for key in self.key_field:
375 value = getattr(self, key)
376 if value is None:
377 raise ValueError("%s key-field value is not set.\n" % (key))
378
379 def _freeze(self):
380 """
381 Freeze class object so that user cannot add new attributes (fields).
382 """
383 self.__isfrozen = True
384
385 def _unfreeze(self):
386 """
387 Unfreeze class object, should be called from within class only.
388 """
389 self.__isfrozen = False
390
391 # ----------------------------------------------------------------------
392 # reset - Assign 'set' Table field values to default or None
393 # ----------------------------------------------------------------------
394 def reset(self):
395 """
396 Initialize fields of set table to it's default value
397 (if mentioned in Table/View) else set to None.
398 """
399 return self._init_field()
400
401 # ----------------------------------------------------------------------
402 # get_table_xml - retrieve lxml configuration object for set table
403 # ----------------------------------------------------------------------
404 def get_table_xml(self):
405 """
406 It returns lxml object of configuration xml that is generated
407 from table data (field=value) pairs. To get a valid xml this
408 method should be used after append() is called.
409 """
410 return self._config_xml_req
411
412 # ----------------------------------------------------------------------
413 # append - append Table data to lxml configuration object
414 # ----------------------------------------------------------------------
415 def append(self):
416 """
417 It creates lxml nodes with field name as xml tag and its value
418 given by user as text of xml node. The generated xml nodes are
419 appended to configuration xml at appropriate hierarchy.
420
421 .. warning::
422 xml node that are appended cannot be changed later hence
423 care should be taken to assign correct value to table fields
424 before calling append.
425 """
426
427 # mandatory check for 'set' table fields
428 self._mandatory_check()
429
430 set_cmd = self._buildxml()
431 top = set_cmd.find(self._data_dict[self._type])
432 self._build_config_xml(top)
433 if self._config_xml_req is None:
434 self._config_xml_req = set_cmd
435 self._insert_node = top.getparent()
436 else:
437 self._insert_node.extend(top.getparent())
438
439 self.reset() # Reset field values
440 self._is_field_set = False
441
442 # ----------------------------------------------------------------------
443 # get - retrieve Table data
444 # ----------------------------------------------------------------------
445
446 def get(self, *vargs, **kvargs):
447 """
448 Retrieve configuration data for this table. By default all child
449 keys of the table are loaded. This behavior can be overridden by
450 with kvargs['nameonly']=True
451
452 :param str vargs[0]: identifies a unique item in the table,
453 same as calling with :kvargs['key']: value
454
455 :param str namesonly:
456 *OPTIONAL* True/False*, when set to True will cause only the
457 the name-keys to be retrieved.
458
459 :param str key:
460 *OPTIONAL* identifies a unique item in the table
461
462 :param dict options:
463 *OPTIONAL* options to pass to get-configuration. By default
464 {'inherit': 'inherit', 'groups': 'groups'} is sent.
465 """
466 if self._lxml is not None:
467 return self
468
469 if self._path is not None:
470 # for loading from local file-path
471 self.xml = etree.parse(self._path).getroot()
472 return self
473
474 if self.keys_required is True and not len(kvargs):
475 raise ValueError("This table has required-keys\n", self.required_keys)
476
477 self._clearkeys()
478
479 # determine if we need to get only the names of keys, or all of the
480 # hierarchical data from the config. The caller can explicitly set
481 # :namesonly: in the call.
482
483 if "namesonly" in kvargs:
484 namesonly = kvargs.get("namesonly")
485 else:
486 namesonly = False
487
488 get_cmd = self._buildxml(namesonly=namesonly)
489
490 # if this table requires additional keys, for the hierarchical
491 # use-cases then make sure these are provided by the caller. Then
492 # encode them into the 'get-cmd' XML
493
494 if self.keys_required is True:
495 self._encode_requiredkeys(get_cmd, kvargs)
496
497 try:
498 # see if the caller provided a named item. this must
499 # be an actual name of a thing, and not an index number.
500 # ... at least for now ...
501 named_item = kvargs.get("key") or vargs[0]
502 dot = get_cmd.find(self._data_dict[self._type])
503 self._encode_namekey(get_cmd, dot, named_item)
504
505 if "get_fields" in self._data_dict:
506 self._encode_getfields(get_cmd, dot)
507
508 except:
509 # caller not requesting a specific table item
510 pass
511
512 # Check for options in get
513 if "options" in kvargs:
514 options = kvargs.get("options") or {}
515 else:
516 if self._options is not None:
517 options = self._options
518 else:
519 options = jxml.INHERIT_GROUPS
520
521 # for debug purposes
522 self._get_cmd = get_cmd
523 self._get_opt = options
524
525 # retrieve the XML configuration
526 # Check to see if running on box
527 if self._dev.ON_JUNOS:
528 try:
529 from junos import Junos_Configuration
530
531 # If part of commit script use the context
532 if Junos_Configuration is not None:
533 # Convert the onbox XML to ncclient reply
534 config = jxml.conf_transform(
535 deepcopy(jxml.cscript_conf(Junos_Configuration)),
536 subSelectionXPath=self._get_xpath,
537 )
538 self.xml = config.getroot()
539 else:
540 self.xml = self.RPC.get_config(get_cmd, options=options)
541 # If onbox import missing fallback to RPC - possibly raise
542 # exception in future
543 except ImportError:
544 self.xml = self.RPC.get_config(get_cmd, options=options)
545 else:
546 self.xml = self.RPC.get_config(get_cmd, options=options)
547
548 # return self for call-chaining, yo!
549 return self
550
551 # -----------------------------------------------------------------------
552 # set - configure Table data in running configuration.
553 # -----------------------------------------------------------------------
554
555 def set(self, **kvargs):
556 """
557 Load configuration data in running db.
558 It performs following operation in sequence.
559
560 * lock(): Locks candidate configuration db.
561 * load(): Load structured configuration xml in candidate db.
562 * commit(): Commit configuration to runnning db.
563 * unlock(): Unlock candidate db.
564
565 This method should be used after append() is called to
566 get the desired results.
567
568 :param bool overwrite:
569 Determines if the contents completely replace the existing
570 configuration. Default is ``False``.
571
572 :param bool merge:
573 If set to ``True`` will set the load-config action to merge.
574 the default load-config action is 'replace'
575
576 :param str comment: If provided logs this comment with the commit.
577
578 :param int confirm: If provided activates confirm safeguard with
579 provided value as timeout (minutes).
580
581 :param int timeout: If provided the command will wait for completion
582 using the provided value as timeout (seconds).
583 By default the device timeout is used.
584
585 :param bool sync: On dual control plane systems, requests that
586 the candidate configuration on one control plane
587 be copied to the other control plane, checked for
588 correct syntax, and committed on both Routing
589 Engines.
590
591 :param bool force_sync: On dual control plane systems, forces the
592 candidate configuration on one control plane
593 to be copied to the other control plane.
594
595 :param bool full: When true requires all the daemons to check and
596 evaluate the new configuration.
597
598 :param bool detail: When true return commit detail as XML
599
600 :returns: Class object:
601
602 :raises: ConfigLoadError:
603 When errors detected while loading
604 configuration. You can use the Exception errs
605 variable to identify the specific problems
606
607 CommitError:
608 When errors detected in candidate configuration.
609 You can use the Exception errs variable
610 to identify the specific problems
611
612 RuntimeError:
613 If field value is set and append() is not
614 invoked before calling this method, it will
615 raise an exception with appropriate error
616 message.
617
618 .. warning::
619 If the function does not receive a reply prior to the timeout
620 a RpcTimeoutError will be raised. It is possible the commit
621 was successful. Manual verification may be required.
622 """
623 if self._is_field_set:
624 raise RuntimeError(
625 "Field value is changed, append() " "must be called before set()"
626 )
627
628 self.lock()
629
630 try:
631 # Invoke config class load() api, with xml object.
632 self._load_rsp = super(CfgTable, self).load(self._config_xml_req, **kvargs)
633 self._commit_rsp = self.commit(**kvargs)
634 finally:
635 self.unlock()
636
637 return self
638
639 # -----------------------------------------------------------------------
640 # OVERLOADS
641 # -----------------------------------------------------------------------
642
643 def __setitem__(self, t_field, value):
644 """
645 implements []= to set Field value
646 """
647 if t_field in self.fields:
648 # pass 'up' to standard setattr method
649 self.__setattr__(t_field, value)
650 else:
651 raise ValueError("Unknown field: %s" % (t_field))
652
653 def __setattr__(self, attribute, value):
654 if self.__isfrozen and not hasattr(self, attribute):
655 raise ValueError("Unknown field: %s" % (attribute))
656 else:
657 # pass 'up' to standard setattr method
658 object.__setattr__(self, attribute, value)
659 if hasattr(self, "fields") and attribute in self.fields:
660 object.__setattr__(self, "_is_field_set", True)
661
662 def __enter__(self):
663 return super(CfgTable, self).__enter__()
664
665 def __exit__(self, exc_type, exc_val, exc_tb):
666 return super(CfgTable, self).__exit__(exc_type, exc_val, exc_tb)
667
668 # -----------------------------------------------------------------------
669 # load - configure Table data in candidate configuration.
670 # -----------------------------------------------------------------------
671
672 def load(self, **kvargs):
673 """
674 Load configuration xml having table data (field=value)
675 in candidate db.
676 This method should be used after append() is called to
677 get the desired results.
678
679 :param bool overwrite:
680 Determines if the contents completely replace the existing
681 configuration. Default is ``False``.
682
683 :param bool merge:
684 If set to ``True`` will set the load-config action to merge.
685 the default load-config action is 'replace'
686
687 :returns: Class object.
688
689 :raises: ConfigLoadError:
690 When errors detected while loading
691 configuration. You can use the Exception errs
692 variable to identify the specific problems
693 RuntimeError:
694 If field value is set and append() is not
695 invoked before calling this method, it will
696 raise an exception with appropriate error
697 message.
698 """
699 if self._is_field_set:
700 raise RuntimeError(
701 "Field value is changed, append() " "must be called before load()"
702 )
703
704 # pass up to config class load() api, with xml object as vargs[0].
705 self._load_rsp = super(CfgTable, self).load(self._config_xml_req, **kvargs)
706 return self