Debian Codegraph @

lib/jnpr/junos/cfg/resource.py

raw
1 # stdlib
2 from pprint import pformat
3 from copy import deepcopy
4
5 # 3rd-party
6 from lxml.builder import E
7
8 # package modules
9 from jnpr.junos import jxml as JXML
10
11 P_JUNOS_EXISTS = "_exists"
12 P_JUNOS_ACTIVE = "_active"
13
14
15 class Resource(object):
16 PROPERTIES = [P_JUNOS_EXISTS, P_JUNOS_ACTIVE]
17
18 def __init__(self, junos, namevar=None, **kvargs):
19 """
20 Resource or Resource-Manager constructor. All managed resources
21 and resource-managers inherit from this class.
22
23 junos
24 Instance of Device, this is bound to the Resource for
25 device access
26
27 namevar
28 If not None, identifies a specific resource by 'name'. The
29 format of the name is resource dependent. Most resources take
30 a single string name, while others use tuples for compound names.
31 refer to each resource for the 'namevar' definition
32
33 If namevar is None, then the instance is a Resource-Manager (RM).
34 The RM is then used to select specific resources by name using
35 the __getitem__ overload.
36
37 kvargs['P'] or kvargs['parent']
38 Instance to the resource parent. This is set when resources have
39 hierarchical relationships, like rules within rulesets
40
41 kvargs['M']
42 Instance to the resource manager.
43 """
44 self._junos = junos
45 self._name = namevar
46 self._parent = kvargs.get("parent") or kvargs.get("P")
47 self._opts = kvargs
48 self._manager = kvargs.get("M")
49
50 if not namevar:
51 # then this is a resource-manager instance. setup the list and
52 # catalog attributes, but do not load them now. when the caller
53 # invokes the properties, they will auto-load when empty.
54 self._rlist = []
55 self._rcatalog = {}
56 return
57
58 # otherwise, a resource includes public attributes:
59
60 self.properties = []
61 self.properties.extend(Resource.PROPERTIES)
62 if self.__class__ != Resource:
63 self.properties.extend(self.__class__.PROPERTIES)
64
65 # if this resource manages others, then hook that
66 # into the :manages: list
67
68 if hasattr(self, "MANAGES"):
69 self._manages = self.MANAGES.keys()
70 for k, v in self.MANAGES.items():
71 self.__dict__[k] = v(junos, parent=self)
72
73 # setup resource cache-attributes
74
75 self.has = {}
76 self.should = {}
77 self._is_new = False
78
79 # now load the properties from the device.
80 self.read()
81
82 # -----------------------------------------------------------------------
83 # PROPERTIES
84 # -----------------------------------------------------------------------
85
86 @property
87 def active(self):
88 """
89 is this resource configuration active on the Junos device?
90
91 :RuntimeError: if invoked on a manager object
92 """
93 if self.is_mgr:
94 raise RuntimeError("Not on a manager!")
95 return self.has[P_JUNOS_ACTIVE]
96
97 @property
98 def exists(self):
99 """
100 does this resource configuration exist on the Junos device?
101
102 :RuntimError: if invoked on a manager
103 """
104 if self.is_mgr:
105 raise RuntimeError("Not on a manager!")
106 return self.has[P_JUNOS_EXISTS]
107
108 @property
109 def is_mgr(self):
110 """
111 is this a resource manager?
112 """
113 return self._name is None
114
115 @property
116 def is_new(self):
117 """
118 is this a new resource? that is, it does not exist
119 on the Junos device when it was initally retrieved
120
121 :RuntimeError: if invoked on a manager
122 """
123 if self.is_mgr:
124 raise RuntimeError("Not on a manager!")
125 return self._is_new
126
127 @property
128 def name(self):
129 """
130 the name of the resource
131
132 :RuntimeError: if invoked on a manager
133 """
134 if self.is_mgr:
135 raise RuntimeError("Not on a manager!")
136 return self._name
137
138 @name.setter
139 def name(self, value):
140 if self.is_mgr:
141 raise RuntimeError("Not on a manager!")
142 raise AttributeError("name is currently read-only")
143
144 @property
145 def manages(self):
146 """
147 a resource may contain sub-managers for hierarchical
148 oriented resources. this method will return a list
149 of manager names attached to this resource, or
150 :None: if there are not any
151 """
152 if hasattr(self, "_manages"):
153 return self._manages
154 return None
155
156 @manages.setter
157 def manages(self):
158 raise AttributeError("read-only")
159
160 @property
161 def xml(self):
162 """
163 for debugging the resource XML configuration that was
164 read from the Junos device
165 """
166 if self.is_mgr:
167 raise RuntimeError("Not on a manager!")
168 return self._has_xml
169
170 @property
171 def list(self):
172 """
173 returns a list of named resources
174 """
175 if not self.is_mgr:
176 raise RuntimeError("Must be a manager!")
177 if not len(self._rlist):
178 self.list_refresh()
179 return self._rlist
180
181 @property
182 def catalog(self):
183 """
184 returns a dictionary of resources
185 """
186 if not self.is_mgr:
187 raise RuntimeError("Must be a manager!")
188 if not len(self._rcatalog):
189 self.catalog_refresh()
190 return self._rcatalog
191
192 # -------------------------------------------------------------------------
193 # shortcuts
194 # -------------------------------------------------------------------------
195
196 @property
197 def D(self):
198 """returns the Device object bound to this resource/manager"""
199 return self._junos
200
201 @property
202 def R(self):
203 """returns the Device RPC meta object"""
204 return self._junos.rpc
205
206 @property
207 def M(self):
208 """returns the :Resource: manager associated to this resource"""
209 return self._manager
210
211 @property
212 def P(self):
213 """returns the parent of the associated Junos object"""
214 return self._parent
215
216 # -----------------------------------------------------------------------
217 # PUBLIC METHODS
218 # -----------------------------------------------------------------------
219
220 # -------------------------------------------------------------------------
221 # read
222 # -------------------------------------------------------------------------
223
224 def read(self):
225 """
226 read resource configuration from device
227 """
228
229 self._r_has_init()
230 self._has_xml = self._r_config_read_xml()
231
232 if self._has_xml is None or not len(self._has_xml):
233 self._is_new = True
234 self._r_when_new()
235 return None
236
237 # the xml_read_parser *MUST* be implement by the
238 # resource subclass. it is used to parse the XML
239 # into native python structures.
240
241 self._xml_to_py(self._has_xml, self.has)
242
243 # return the python structure represntation
244 return True
245
246 # -------------------------------------------------------------------------
247 # write
248 # -------------------------------------------------------------------------
249
250 def write(self, **kvargs):
251 """
252 write resource configuration stored in :should: back to device
253
254 kvargs['touch']
255 if True, then write() will skip the check to see if any
256 items exist in :should:
257 """
258 if self.is_mgr:
259 raise RuntimeError("Not on a manager!")
260
261 if not len(self.should) and "touch" not in kvargs:
262 return False
263
264 # if this resource did not previously exist,
265 # then mark it now into :should:
266
267 if P_JUNOS_EXISTS not in self.should:
268 self._r_set_exists(self.should, True)
269
270 if self.is_new:
271 self._r_set_active(self.should, True)
272
273 # construct the XML change structure
274 xml_change = self._xml_build_change()
275 if xml_change is None:
276 return False
277
278 # write these changes to the device
279 self._r_config_write_xml(xml_change)
280
281 # copy :should: into :has: and then clear :should:
282 self.has.update(self.should)
283 self.should.clear()
284
285 return True
286
287 # -------------------------------------------------------------------------
288 # activate
289 # -------------------------------------------------------------------------
290
291 def activate(self):
292 """
293 activate resource in Junos config
294 the same as the Junos config-mode "activate" command
295 """
296 # no action needed if it's already active
297 if self.active:
298 return False
299 self._r_set_active(self.should, True)
300 return self.write()
301
302 # -------------------------------------------------------------------------
303 # deactivate
304 # -------------------------------------------------------------------------
305
306 def deactivate(self):
307 """
308 activate resource in Junos config
309 the same as the Junos config-mode "deactivate" command
310 """
311 # no action needed if it's already deactive
312 if not self.active:
313 return False
314 self._r_set_active(self.should, False)
315 return self.write()
316
317 # -------------------------------------------------------------------------
318 # delete
319 # -------------------------------------------------------------------------
320
321 def delete(self):
322 """
323 remove configuration from Junos device
324 the same as the Junos config-mode "delete" command
325 """
326 # cannot delete something that doesn't exist
327 # @@@ should raise?
328
329 if not self.exists:
330 return False
331
332 # remove the config from Junos
333 xml = self._xml_edit_at_res()
334 xml.attrib.update(JXML.DEL)
335 self._xml_hook_on_delete(xml)
336 self._r_config_write_xml(xml)
337
338 # reset the :has: attribute
339 self._r_has_init()
340 return True
341
342 # -------------------------------------------------------------------------
343 # rename
344 # -------------------------------------------------------------------------
345
346 def rename(self, new_name):
347 """
348 rename resource in Junos configuration
349 the same as the Junos config-mode "rename" command
350 """
351 # cannot rename something that doesn't exist
352 # @@@ should raise?
353
354 if not self.exists:
355 return False
356
357 xml = self._xml_edit_at_res()
358 xml.attrib.update(JXML.REN)
359 xml.attrib.update(JXML.NAME(new_name))
360
361 self._r_config_write_xml(xml)
362 self._name = new_name
363
364 return True
365
366 # -------------------------------------------------------------------------
367 # reorder
368 # -------------------------------------------------------------------------
369
370 def reorder(self, **kvargs):
371 """
372 move the configuration within the Junos hierarcy
373 the same as the Junos config-mode "insert" command
374
375 :kvargs:
376 after="<name>"
377 before="<name>"
378 """
379 cmd, name = next(kvargs.iteritems())
380 if cmd != "before" and cmd != "after":
381 raise ValueError("Must be either 'before' or 'after'")
382
383 xml = self._xml_edit_at_res()
384 xml.attrib.update(JXML.INSERT(cmd))
385 xml.attrib.update(JXML.NAME(name))
386
387 self._r_config_write_xml(xml)
388 return True
389
390 def list_refresh(self):
391 """
392 reloads the managed resource list from the Junos device
393 """
394 if not self.is_mgr:
395 raise RuntimeError("Only on a manager!")
396 del self._rlist[:]
397 self._r_list() # invoke the specific resource method
398
399 def catalog_refresh(self):
400 """
401 reloads the resource catalog from the Junos device
402 """
403 if not self.is_mgr:
404 raise RuntimeError("Only on a manager!")
405 self._rcatalog.clear()
406 self._r_catalog() # invoke the specific resource method
407
408 def _r_catalog(self):
409 """
410 provide a 'default' catalog creator method that simply uses
411 the manager list and runs through each resource making
412 a refcopy to the :has: properties
413 """
414 zone_list = self.list
415 for name in zone_list:
416 r = self[name]
417 self._rcatalog[name] = r.has
418
419 def refresh(self):
420 if not self.is_mgr:
421 raise RuntimeError("Only on a manager!")
422 self.list_refresh()
423 self.catalog_refresh()
424
425 def propcopy(self, p_name):
426 """
427 proptery from :has: to :should:
428
429 performs a 'deepcopy' of the property; used to make
430 changes to list, dict type properties
431 """
432 self.should[p_name] = deepcopy(self.has[p_name])
433 return self.should[p_name]
434
435 # -----------------------------------------------------------------------
436 # OVERLOADS
437 # -----------------------------------------------------------------------
438
439 # ---------------------------------------------------------------------
440 # ITEMS: for read/write of resource managed properties
441 # ---------------------------------------------------------------------
442
443 def __getitem__(self, namekey):
444 """
445 implements [] to obtain property value. value will come
446 from :should: if set or from :has: otherwise.
447 """
448
449 if self.is_mgr:
450 # ---------------------------------------------------------------
451 # use is resource-manager accessing specific index/name
452 # to return resource instance
453 # ---------------------------------------------------------------
454
455 self._opts["M"] = self
456 if isinstance(namekey, int):
457 # index, not name
458 namekey = self.list[namekey]
459
460 res = self.__class__(self._junos, namekey, **self._opts)
461 return res
462
463 # ---------------------------------------------------------------
464 # use-case is resource instance for read property
465 # ---------------------------------------------------------------
466
467 if namekey in self.should:
468 return self.should[namekey]
469
470 if namekey in self.has:
471 return self.has[namekey]
472
473 if namekey in self.properties:
474 # it's a valid property, just not set in the resource
475 return None
476
477 raise ValueError("Unknown property request: %s" % namekey)
478
479 def __setitem__(self, r_prop, value):
480 """
481 implements []= to set property value into :should:
482 """
483 if self.is_mgr:
484 raise RuntimeError("Not on a manager!")
485 if r_prop in self.properties:
486 self.should[r_prop] = value
487 else:
488 raise ValueError("Uknown property request: %s" % r_prop)
489
490 def __call__(self, **kvargs):
491 """
492 alternative way to set property values as aggregation of
493 key/value pairs. this will automatically call :write():
494 when completed.
495 """
496 if self.is_mgr:
497 raise RuntimeError("Not on a manager!")
498 if not kvargs:
499 return False
500
501 # validate property names first!
502 for p_name, p_val in kvargs.items():
503 if p_name not in self.properties:
504 raise ValueError("Unknown property: %s" % p_name)
505
506 # now cleared to add all the values
507 self.should.update(kvargs)
508 return self.write()
509
510 # ---------------------------------------------------------------------
511 # ATTRIBUTE: for read/write of resource managed properties
512 # ---------------------------------------------------------------------
513
514 def __getattr__(self, namekey):
515 """
516 returns property value, accessed as attribute <resource>.<property>
517 only for resource instance
518 """
519 if self.is_mgr:
520 raise RuntimeError("not on a resource-manager")
521 return self[namekey]
522
523 def __setattr__(self, name, value):
524 if hasattr(self, "properties") and name in self.properties:
525 # we can set this name/value in the resource property
526 self[name] = value
527 else:
528 # pass 'up' to standard setattr method
529 object.__setattr__(self, name, value)
530
531 # ---------------------------------------------------------------------
532 # PRINT/DEBUG
533 # ---------------------------------------------------------------------
534
535 def __repr__(self):
536 """
537 stringify for debug/printing
538
539 this will show the resource manager (class) name,
540 the resource (Junos) name, and the contents
541 of the :has: dict and the contents of the :should: dict
542 """
543 mgr_name = self.__class__.__name__
544 return (
545 "NAME: %s: %s\nHAS: %s\nSHOULD:%s"
546 % (mgr_name, self._name, pformat(self.has), pformat(self.should))
547 if not self.is_mgr
548 else "Resource Manager: %s" % mgr_name
549 )
550
551 # ---------------------------------------------------------------------
552 # ITERATOR
553 # ---------------------------------------------------------------------
554
555 def __iter__(self):
556 """iterate through each Resource in the Manager list"""
557 for name in self.list:
558 yield self[name]
559
560 # -----------------------------------------------------------------------
561 # XML reading
562 # -----------------------------------------------------------------------
563
564 def _r_config_read_xml(self):
565 """
566 read the resource config from the Junos device
567 """
568 get = self._xml_at_top()
569 self._xml_hook_read_begin(get)
570 got = self._junos.rpc.get_config(get)
571 return self._xml_at_res(got)
572
573 def _xml_at_top(self):
574 """
575 ~| WARNING |~
576 resource subclass *MUST* implement this!
577
578 Create an XML structure that will be used to retrieve
579 the resource configuration from the device.
580 """
581 raise RuntimeError("Resource missing method: %s" % self.__class__.__name__)
582
583 def _xml_at_res(self, xml):
584 """
585 ~| WARNING |~
586 resource subclass *MUST* implement this!
587
588 Return the XML element of the specific resource from
589 the :xml: structure. The :xml: will be the configuration
590 starting at the top of the Junos config, i.e.
591 <configuration>, and the resource needs to "cursor" at
592 the specific resource within that structure
593 """
594 raise RuntimeError("Resource missing method: %s" % self.__class__.__name__)
595
596 # -----------------------------------------------------------------------
597 # XML writing
598 # -----------------------------------------------------------------------
599
600 def _xml_build_change(self):
601 """
602 iterate through the :should: properties creating the
603 necessary configuration change structure. if there
604 are no changes, then return :None:
605 """
606 edit_xml = self._xml_edit_at_res()
607
608 # if there is resource hook to do something
609 # before we build up the xml configuration,
610 # then do that now
611
612 self._xml_hook_build_change_begin(edit_xml)
613
614 # if this resource should be deleted then
615 # handle that case and return
616
617 if not self.should[P_JUNOS_EXISTS]:
618 self._xml_change__exists(edit_xml)
619 return edit_xml
620
621 # otherwise, this is an update, and we need to
622 # construct the XML for change
623
624 changed = False
625 for r_prop in self.properties:
626 if r_prop in self.should:
627 edit_fn = "_xml_change_" + r_prop
628 changed |= getattr(self, edit_fn)(edit_xml)
629
630 # if there is a resource hook to do something
631 # after we've run through all the property methods
632 # then invoke that now
633
634 changed |= self._xml_hook_build_change_end(edit_xml)
635
636 return edit_xml if changed else None
637
638 def _r_config_write_xml(self, xml):
639 """
640 write the xml change to the Junos device,
641 trapping on exceptions.
642 """
643 top_xml = xml.getroottree().getroot()
644
645 try:
646 result = self._junos.rpc.load_config(top_xml, action="replace")
647 except Exception as err:
648 # see if this is OK or just a warning
649 if len(err.rsp.xpath('.//error-severity[. = "error"]')):
650 raise err
651 return err.rsp
652
653 return result
654
655 # ------------------------------------------------------------------------
656 # XML edit cursor methods
657 # ------------------------------------------------------------------------
658
659 def _xml_edit_at_res(self):
660 return self._xml_at_res(self._xml_at_top())
661
662 # ------------------------------------------------------------------------
663 # XML standard properties "writers"
664 # ------------------------------------------------------------------------
665
666 def _xml_change_description(self, xml):
667 Resource.xml_set_or_delete(xml, "description", self.should["description"])
668 return True
669
670 def _xml_change__active(self, xml):
671 if self.should[P_JUNOS_ACTIVE] == self.has[P_JUNOS_ACTIVE]:
672 return False
673 value = "active" if self.should[P_JUNOS_ACTIVE] else "inactive"
674 xml.attrib[value] = value
675 return True
676
677 def _xml_change__exists(self, xml):
678 # if this is a change to create something new,
679 # then invoke the 'on-create' hook and return
680 # the results
681
682 if self.should[P_JUNOS_EXISTS]:
683 return self._xml_hook_on_new(xml)
684
685 # otherwise, we are deleting this resource
686 xml.attrib.update(JXML.DEL)
687
688 # now call the 'on-delete' hook and return
689 # the results
690
691 return self._xml_hook_on_delete(xml)
692
693 # -----------------------------------------------------------------------
694 # XML HOOK methods
695 # -----------------------------------------------------------------------
696
697 def _xml_hook_read_begin(self, xml):
698 """
699 called from :_r_config_read_xml(): after call to :_xml_at_top(): and
700 before the config request is made to the Junos device. This hook
701 allows the subclass to munge the XML get-request with additional items
702 if necessary
703
704 Returns:
705 :True: when :xml: is changed
706 :False: otherwise
707 """
708 return False
709
710 def _xml_hook_build_change_begin(self, xml):
711 """
712 called from :_xml_build_change(): before the individual property
713 methods are invoked. allows the resource to do anything, like pruning
714 stub elements that were generated as part of :_xml_at_top():
715
716 Returns:
717 :True: when :xml: is changed
718 :False: otherwise
719 """
720 return False
721
722 def _xml_hook_build_change_end(self, xml):
723 """
724 called from :_xml_build_change(): after all of the properties
725 methods have been processed.
726
727 Returns:
728 :True: when :xml: is changed
729 :False: otherwise
730 """
731 return False
732
733 def _xml_hook_on_delete(self, xml):
734 """
735 called when an XML write operation is going to delete the resource.
736
737 Returns:
738 :True: when :xml: is changed
739 :False: otherwise
740 """
741 return False
742
743 def _xml_hook_on_new(self, xml):
744 """
745 called when an XML write operation is going to create a new resource.
746
747 Returns:
748 :True: when :xml: is changed
749 :False: otherwise
750 """
751 return False
752
753 # -----------------------------------------------------------------------
754 # Resource HOOK methods
755 # -----------------------------------------------------------------------
756
757 def _r_when_new(self):
758 """
759 called by :read(): when the resource is new; i.e.
760 there is no existing Junos configuration
761 """
762 pass
763
764 def _r_when_delete(self):
765 """
766 ~| not used yet |~
767 """
768 pass
769
770 # -----------------------------------------------------------------------
771 # ~private~ resource methods
772 # -----------------------------------------------------------------------
773
774 def _r_set_active(self, my_props, value):
775 my_props[P_JUNOS_ACTIVE] = value
776
777 def _r_set_exists(self, my_props, value):
778 my_props[P_JUNOS_EXISTS] = value
779
780 def _r_has_init(self):
781 self.has.clear()
782 self.has[P_JUNOS_EXISTS] = False
783 self.has[P_JUNOS_ACTIVE] = False
784
785 @classmethod
786 def _r_has_xml_status(klass, as_xml, as_py):
787 """
788 set the 'exists' and 'active' :has: values
789 """
790 as_py[P_JUNOS_ACTIVE] = False if as_xml.attrib.get("inactive") else True
791 as_py[P_JUNOS_EXISTS] = True
792
793 @classmethod
794 def xml_set_or_delete(klass, xml, ele_name, value):
795 """
796 HELPER function to either set a value or remove the element
797 """
798 if value is not None and not isinstance(value, str):
799 value = str(value)
800 xml.append(E(ele_name, (value if value else JXML.DEL)))
801
802 @classmethod
803 def xmltag_set_or_del(klass, ele_name, value):
804 """
805 HELPER function creates an XML element tag read-only
806 that includes the DEL attribute depending on :value:
807 """
808 return E(ele_name, ({} if value else JXML.DEL))
809
810 @classmethod
811 def copyifexists(klass, xml, ele_name, to_py, py_name=None):
812 ele_val = xml.find(ele_name)
813 if ele_val is not None:
814 to_py[(py_name if py_name else ele_name)] = ele_val.text.strip()
815
816 @classmethod
817 def diff_list(klass, has_list, should_list):
818 # covert lists to perform differencing
819 should = set(should_list)
820 has = set(has_list)
821
822 # return lists (added, removed)
823 return (list(should - has), list(has - should))
824
825 def _xml_list_property_add_del_names(self, xml, prop_name, element_name):
826 """
827 utility method use to process :list: properties. this will add/delete
828 items give the propery type and associated XML element name
829 """
830 (adds, dels) = Resource.diff_list(
831 self.has.get(prop_name, []), self.should[prop_name]
832 )
833 for this in adds:
834 xml.append(E(element_name, E.name(this)))
835 for this in dels:
836 xml.append(E(element_name, JXML.DEL, E.name(this)))