1 """ abstract vpp object and object registry """
6 class VppObject(metaclass=abc.ABCMeta):
7 """ Abstract vpp object """
10 def add_vpp_config(self) -> None:
11 """ Add the configuration for this object to vpp. """
15 def query_vpp_config(self) -> bool:
16 """Query the vpp configuration.
18 :return: True if the object is configured"""
22 def remove_vpp_config(self) -> None:
23 """ Remove the configuration for this object from vpp. """
26 def object_id(self) -> str:
27 """ Return a unique string representing this object. """
28 return "Undefined. for <%s %s>" % (self.__class__.__name__, id(self))
30 def __str__(self) -> str:
31 return self.object_id()
33 def __repr__(self) -> str:
34 return '<%s>' % self.object_id()
36 def __hash__(self) -> int:
37 return hash(self.object_id())
39 def __eq__(self, other) -> bool:
40 if not isinstance(other, self.__class__):
42 if other.object_id() == self.object_id():
46 # This can be removed when python2 support is dropped.
47 def __ne__(self, other):
48 return not self.__eq__(other)
51 class VppObjectRegistry:
52 """ Class which handles automatic configuration cleanup. """
55 def __init__(self) -> None:
56 self.__dict__ = self._shared_state
57 if not hasattr(self, "_object_registry"):
58 self._object_registry = []
59 if not hasattr(self, "_object_dict"):
60 self._object_dict = dict()
62 def register(self, obj: VppObject, logger) -> None:
63 """ Register an object in the registry. """
64 if obj.object_id() not in self._object_dict:
65 self._object_registry.append(obj)
66 self._object_dict[obj.object_id()] = obj
67 logger.debug("REG: registering %s" % obj)
69 logger.debug("REG: duplicate add, ignoring (%s)" % obj)
71 def unregister_all(self, logger) -> None:
72 """ Remove all object registrations from registry. """
73 logger.debug("REG: removing all object registrations")
74 self._object_registry = []
75 self._object_dict = dict()
77 def remove_vpp_config(self, logger) -> None:
79 Remove configuration (if present) from vpp and then remove all objects
82 if not self._object_registry:
83 logger.info("REG: No objects registered for auto-cleanup.")
85 logger.info("REG: Removing VPP configuration for registered objects")
86 # remove the config in reverse order as there might be dependencies
88 for obj in reversed(self._object_registry):
89 if obj.query_vpp_config():
90 logger.info("REG: Removing configuration for %s" % obj)
91 obj.remove_vpp_config()
92 if obj.query_vpp_config():
96 "REG: Skipping removal for %s, configuration not present" %
98 self.unregister_all(logger)
100 logger.error("REG: Couldn't remove configuration for object(s):")
102 logger.error(repr(obj))
103 raise Exception("Couldn't remove configuration for object(s): %s" %
104 (", ".join(str(x) for x in failed)))