| 1 |
import warnings |
| 2 |
from pprint import pformat |
| 3 |
|
| 4 |
try: |
| 5 |
from collections.abc import MutableMapping |
| 6 |
except ImportError: |
| 7 |
from collections import MutableMapping |
| 8 |
|
| 9 |
import jnpr.junos.facts |
| 10 |
from jnpr.junos.facts import __doc__ as facts_doc |
| 11 |
import jnpr.junos.exception |
| 12 |
|
| 13 |
|
| 14 |
class _FactCache(MutableMapping): |
| 15 |
""" |
| 16 |
A dictionary-like object which performs on-demand fact gathering. |
| 17 |
|
| 18 |
This class should not be used directly. An instance of this class is |
| 19 |
available as the :attr:`facts` attribute of a Device object. |
| 20 |
|
| 21 |
**Dictionary magic methods:** |
| 22 |
* :meth:`__getitem__`: Gets the value of a given key in the dict. |
| 23 |
* :meth:`__delitem__`: Called when a key is deleted from the dict. |
| 24 |
* :meth:`__setitem__`: Called when a key is set on the dict. |
| 25 |
* :meth:`__iter__`: Called when iterating over the keys of the dict. |
| 26 |
* :meth:`__len__`: Called when getting the length of the dict. |
| 27 |
* :meth:`__repr__`: Called when representing the dict as a string. |
| 28 |
|
| 29 |
**Additional methods:** |
| 30 |
* :meth:`_refresh`: Refreshes the fact cache. |
| 31 |
""" |
| 32 |
|
| 33 |
def __init__(self, device): |
| 34 |
""" |
| 35 |
_FactCache object constructor. |
| 36 |
|
| 37 |
:param device: The device object for which fact gathering will be |
| 38 |
performed. |
| 39 |
""" |
| 40 |
self._device = device |
| 41 |
self._cache = dict() |
| 42 |
self._call_stack = list() |
| 43 |
self._callbacks = jnpr.junos.facts._callbacks |
| 44 |
self._exception_on_failure = False |
| 45 |
self._warnings_on_failure = False |
| 46 |
self._should_warn = False |
| 47 |
|
| 48 |
def __getitem__(self, key): |
| 49 |
""" |
| 50 |
Return the value of a particular key in the dictionary. |
| 51 |
|
| 52 |
If the fact has already been cached, the value is simply returned from |
| 53 |
the cache. If the value has not been cached, then the appropriate |
| 54 |
callback function is invoked to gather the fact from the device. The |
| 55 |
value is cached, and then returned. |
| 56 |
|
| 57 |
If _warnings_on_failure is True, then a warning is logged if there is |
| 58 |
an error gathering a fact from the device. |
| 59 |
|
| 60 |
:param key: The key who's value is returned. |
| 61 |
|
| 62 |
:returns value: The value of the key fact. If key is a known fact, but |
| 63 |
there is an error gathering the fact, then the value None is |
| 64 |
returned. |
| 65 |
|
| 66 |
:raises KeyError: |
| 67 |
When key is not a known fact (there is no callback present to |
| 68 |
gather the fact.) |
| 69 |
|
| 70 |
:raises jnpr.junos.exception.FactLoopError: |
| 71 |
When there is a loop attempting to gather the fact. |
| 72 |
|
| 73 |
:raises other exceptions as defined by the fact gathering modules: |
| 74 |
When an error is encountered and _exception_on_failure is True. |
| 75 |
""" |
| 76 |
if key not in self._callbacks: |
| 77 |
# Not a fact that we know how to provide. |
| 78 |
raise KeyError( |
| 79 |
"%s: There is no function to gather the %s fact" % (key, key) |
| 80 |
) |
| 81 |
if key not in self._cache: |
| 82 |
# A known fact, but not yet cached. Go get it and cache it. |
| 83 |
if self._callbacks[key] in self._call_stack: |
| 84 |
raise jnpr.junos.exception.FactLoopError( |
| 85 |
"A loop was detected while gathering the %s fact. The %s " |
| 86 |
"module has already been called. Please report this error." |
| 87 |
% (key, self._callbacks[key].__module__) |
| 88 |
) |
| 89 |
else: |
| 90 |
# Add the callback we are about to invoke to the _call_stack in |
| 91 |
# order to detect loops in fact gathering. |
| 92 |
self._call_stack.append(self._callbacks[key]) |
| 93 |
try: |
| 94 |
# Invoke the callback |
| 95 |
new_facts = self._callbacks[key](self._device) |
| 96 |
except jnpr.junos.exception.FactLoopError: |
| 97 |
raise |
| 98 |
except Exception: |
| 99 |
# An exception was raised. No facts were returned. |
| 100 |
# Raise the exception to the user? |
| 101 |
if self._exception_on_failure: |
| 102 |
raise |
| 103 |
# Warn the user? |
| 104 |
if self._warnings_on_failure: |
| 105 |
self._should_warn = True |
| 106 |
# Set all of the facts which should have been returned |
| 107 |
# by this callback to the default value of None. |
| 108 |
for new_key in self._callbacks: |
| 109 |
if self._callbacks[key] is self._callbacks[new_key]: |
| 110 |
self._cache[new_key] = None |
| 111 |
else: |
| 112 |
# No exception |
| 113 |
for new_key in new_facts: |
| 114 |
if ( |
| 115 |
new_key not in self._callbacks |
| 116 |
or self._callbacks[key] is not self._callbacks[new_key] |
| 117 |
): |
| 118 |
# The callback returned a fact it didn't advertise |
| 119 |
raise RuntimeError( |
| 120 |
"The %s module returned the %s " |
| 121 |
"fact, but does not list %s as a " |
| 122 |
"provided fact. Please report this " |
| 123 |
"error." |
| 124 |
% (self._callbacks[key].__module__, new_key, new_key) |
| 125 |
) |
| 126 |
else: |
| 127 |
# Cache the returned fact |
| 128 |
self._cache[new_key] = new_facts[new_key] |
| 129 |
finally: |
| 130 |
# Always pop the current callback from _call_stack, |
| 131 |
# regardless of whether or not an exception was raised. |
| 132 |
self._call_stack.pop() |
| 133 |
if key in self._cache: |
| 134 |
# key fact is cached. Return it. |
| 135 |
if self._device._fact_style == "both": |
| 136 |
# Compare old and new-style values. |
| 137 |
if key in self._device._ofacts: |
| 138 |
# Skip key comparisons for certain keys. |
| 139 |
# |
| 140 |
# The old facts gathering code has an up_time key. |
| 141 |
# The new facts gathering code maintains this key for RE0 |
| 142 |
# and RE1 facts, but it's not comparable (because it |
| 143 |
# depends on when the fact was gathered and is therefore |
| 144 |
# not really a "fact".) The new re_info fact omits the |
| 145 |
# up_time field for this reason. |
| 146 |
# |
| 147 |
# The old facts gathering code didn't return a correct |
| 148 |
# value for the master fact when the system was a VC. |
| 149 |
# The new fact gathering code still returns the master fact |
| 150 |
# but returns a correct value for VCs. It also returns a |
| 151 |
# new re_master fact which is much more useful. |
| 152 |
if key not in ["RE0", "RE1", "master"]: |
| 153 |
if self._cache[key] != self._device._ofacts[key]: |
| 154 |
warnings.warn( |
| 155 |
"New and old-style facts do not " |
| 156 |
"match for the %s fact.\n" |
| 157 |
" New-style value: %s\n" |
| 158 |
" Old-style value: %s\n" |
| 159 |
% (key, self._cache[key], self._device._ofacts[key]), |
| 160 |
RuntimeWarning, |
| 161 |
) |
| 162 |
return self._cache[key] |
| 163 |
else: |
| 164 |
# key fact was not returned by callback |
| 165 |
raise RuntimeError( |
| 166 |
"The %s module claims to provide the %s " |
| 167 |
"fact, but failed to return it. Please report " |
| 168 |
"this error." % (self._callbacks[key].__module__, key) |
| 169 |
) |
| 170 |
|
| 171 |
def __delitem__(self, key): |
| 172 |
""" |
| 173 |
Facts are read-only. Don't allow deleting an item. |
| 174 |
""" |
| 175 |
raise RuntimeError("facts are read-only!") |
| 176 |
|
| 177 |
def __setitem__(self, key, value): |
| 178 |
""" |
| 179 |
Facts are read-only. Don't allow setting an item. |
| 180 |
""" |
| 181 |
raise RuntimeError("facts are read-only!") |
| 182 |
|
| 183 |
def __iter__(self): |
| 184 |
""" |
| 185 |
An iterator of known facts. |
| 186 |
|
| 187 |
:returns iterator: of all of the 'non-hidden' facts we know how to |
| 188 |
gather, regardless of whether or not they've already been cached. Fact |
| 189 |
names which are hidden start with an underscore and are not returned. |
| 190 |
""" |
| 191 |
callbacks = {} |
| 192 |
for key in self._callbacks: |
| 193 |
if not key.startswith("_"): |
| 194 |
callbacks[key] = self._callbacks[key] |
| 195 |
return iter(callbacks) |
| 196 |
|
| 197 |
def __len__(self): |
| 198 |
""" |
| 199 |
The length of all known facts. |
| 200 |
|
| 201 |
:returns length: of all of the facts we know how to gather, |
| 202 |
regardless of whether or not they've already been cached. |
| 203 |
""" |
| 204 |
return len(self._callbacks) |
| 205 |
|
| 206 |
def __str__(self): |
| 207 |
""" |
| 208 |
A string representation of the facts dictionary. |
| 209 |
|
| 210 |
:returns string: a string representation of the dictionary. |
| 211 |
Because this returns the value of every fact, it has the |
| 212 |
side-effect of causing any ungathered facts to be gathered and then |
| 213 |
cached. |
| 214 |
""" |
| 215 |
string = "" |
| 216 |
for key in sorted(self): |
| 217 |
if not key.startswith("_"): |
| 218 |
current = "'%s': %s" % (key, repr(self.get(key))) |
| 219 |
if string: |
| 220 |
string = ", ".join([string, current]) |
| 221 |
else: |
| 222 |
string = current |
| 223 |
return "{" + string + "}" |
| 224 |
|
| 225 |
def __repr__(self): |
| 226 |
""" |
| 227 |
A formated string representation of the facts dictionary. |
| 228 |
|
| 229 |
:returns string: a formated string representation of the dictionary. |
| 230 |
Because this returns the value of every fact, it has the |
| 231 |
side-effect of causing any ungathered facts to be gathered and then |
| 232 |
cached. |
| 233 |
""" |
| 234 |
return pformat(dict(self)) |
| 235 |
|
| 236 |
def _refresh( |
| 237 |
self, exception_on_failure=False, warnings_on_failure=False, keys=None |
| 238 |
): |
| 239 |
""" |
| 240 |
Empty the cache to force a refresh of one or more facts. |
| 241 |
|
| 242 |
Empties the fact gathering cache for all keys (if keys == None) or a |
| 243 |
set of keys. This causes the fact to be gathered and cached upon next |
| 244 |
access. If either eception_on_failure or warnings_on_failure is true, |
| 245 |
then all facts are accessed by getting the string representation of the |
| 246 |
facts. This causes all facts to immediately be populated so that any |
| 247 |
exceptions or warnings are generated during the call to _refresh(). |
| 248 |
|
| 249 |
:param exception_on_failure: A boolean which indicates if an exception |
| 250 |
should be raised upon a failure gathering facts. |
| 251 |
|
| 252 |
:param warnings_on_failure: A boolean which indicates if an warning |
| 253 |
should be logged upon a failure gathering facts. |
| 254 |
|
| 255 |
:param keys: A single key as a string, or an iterable of keys (such |
| 256 |
as a list, set, or or tuple.) The specified keys are emptied from |
| 257 |
the cache. If None, all keys are emptied from the cache. |
| 258 |
|
| 259 |
:raises RuntimeError: |
| 260 |
When keys contains an unknown fact. |
| 261 |
""" |
| 262 |
refresh_keys = None |
| 263 |
if keys is not None: |
| 264 |
if isinstance("str", type(keys)): |
| 265 |
refresh_keys = (keys,) |
| 266 |
else: |
| 267 |
refresh_keys = keys |
| 268 |
if refresh_keys is not None: |
| 269 |
for key in refresh_keys: |
| 270 |
if key in self._callbacks: |
| 271 |
if key in self._cache: |
| 272 |
del self._cache[key] |
| 273 |
else: |
| 274 |
raise RuntimeError( |
| 275 |
"The %s fact can not be refreshed. %s " |
| 276 |
"is not a known fact." % (key, key) |
| 277 |
) |
| 278 |
else: |
| 279 |
self._cache = dict() |
| 280 |
if exception_on_failure or warnings_on_failure: |
| 281 |
self._exception_on_failure = exception_on_failure |
| 282 |
self._warnings_on_failure = warnings_on_failure |
| 283 |
try: |
| 284 |
str(self._device.facts) |
| 285 |
except Exception: |
| 286 |
if exception_on_failure: |
| 287 |
raise |
| 288 |
finally: |
| 289 |
if warnings_on_failure and self._should_warn: |
| 290 |
warnings.warn( |
| 291 |
"Facts gathering is incomplete. " |
| 292 |
"To know the reason call " |
| 293 |
'"dev.facts_refresh(' |
| 294 |
'exception_on_failure=True)"', |
| 295 |
RuntimeWarning, |
| 296 |
) |
| 297 |
self._exception_on_failure = False |
| 298 |
self._warnings_on_failure = False |
| 299 |
self._should_warn = False |
| 300 |
|
| 301 |
# In case optimization flag is enabled, it strips of docstring and __doc__ becomes None |
| 302 |
if __doc__ is None: |
| 303 |
__doc__ = "" |
| 304 |
|
| 305 |
# Precede the class's documentation with the documentation on the specific |
| 306 |
# facts from the jnpr.junos.facts package. |
| 307 |
__doc__ = facts_doc + "Implementation details on the _FactCache class:" + __doc__ |