| 1 |
import warnings |
| 2 |
from contextlib import contextmanager |
| 3 |
from copy import deepcopy |
| 4 |
from lxml import etree |
| 5 |
import json |
| 6 |
import sys |
| 7 |
from jinja2 import Template, meta |
| 8 |
|
| 9 |
from jnpr.junos.factory.viewfields import ViewFields |
| 10 |
from jnpr.junos.factory.to_json import TableViewJSONEncoder |
| 11 |
|
| 12 |
|
| 13 |
class View(object): |
| 14 |
""" |
| 15 |
View is the base-class that makes extracting values from XML |
| 16 |
data appear as objects with attributes. |
| 17 |
""" |
| 18 |
|
| 19 |
ITEM_NAME_XPATH = "name" |
| 20 |
FIELDS = {} |
| 21 |
EVAL = {} |
| 22 |
GROUPS = None |
| 23 |
|
| 24 |
# ------------------------------------------------------------------------- |
| 25 |
# CONSTRUCTOR |
| 26 |
# ------------------------------------------------------------------------- |
| 27 |
|
| 28 |
def __init__(self, table, view_xml): |
| 29 |
""" |
| 30 |
:table: |
| 31 |
instance of the RunstatTable |
| 32 |
|
| 33 |
:view_xml: |
| 34 |
this should be an lxml etree Elemenet object. This |
| 35 |
constructor also accepts a list with a single item/XML |
| 36 |
""" |
| 37 |
# if as_xml is passed as a list, make sure it only has |
| 38 |
# a single item, common response from an xpath search |
| 39 |
if isinstance(view_xml, list): |
| 40 |
if 1 == len(view_xml): |
| 41 |
view_xml = view_xml[0] |
| 42 |
else: |
| 43 |
raise ValueError("constructor only accepts a single item") |
| 44 |
|
| 45 |
# now ensure that the thing provided is an lxml etree Element |
| 46 |
if not isinstance(view_xml, etree._Element): |
| 47 |
raise ValueError("constructor only accecpts lxml.etree._Element") |
| 48 |
|
| 49 |
self._table = table |
| 50 |
self.ITEM_NAME_XPATH = table.ITEM_NAME_XPATH |
| 51 |
self._init_xml(view_xml) |
| 52 |
|
| 53 |
def _init_xml(self, given_xml): |
| 54 |
self._xml = given_xml |
| 55 |
if self.GROUPS is not None: |
| 56 |
self._groups = {} |
| 57 |
for xg_name, xg_xpath in self.GROUPS.items(): |
| 58 |
xg_xml = self._xml.xpath(xg_xpath) |
| 59 |
# @@@ this is technically an error; need to trap it |
| 60 |
if not len(xg_xml): |
| 61 |
continue |
| 62 |
self._groups[xg_name] = xg_xml[0] |
| 63 |
|
| 64 |
# ------------------------------------------------------------------------- |
| 65 |
# PROPERTIES |
| 66 |
# ------------------------------------------------------------------------- |
| 67 |
|
| 68 |
@property |
| 69 |
def T(self): |
| 70 |
"""return the Table instance for the View""" |
| 71 |
return self._table |
| 72 |
|
| 73 |
@property |
| 74 |
def D(self): |
| 75 |
"""return the Device instance for this View""" |
| 76 |
return self.T.D |
| 77 |
|
| 78 |
@property |
| 79 |
def name(self): |
| 80 |
"""return the name of view item""" |
| 81 |
if self.ITEM_NAME_XPATH is None: |
| 82 |
return [] |
| 83 |
# return self._table.D.hostname |
| 84 |
if isinstance(self.ITEM_NAME_XPATH, str): |
| 85 |
# xpath union key |
| 86 |
if " | " in self.ITEM_NAME_XPATH: |
| 87 |
if "Null" in self.ITEM_NAME_XPATH: |
| 88 |
return self._check_key_delimiter_null( |
| 89 |
self._xml, self.ITEM_NAME_XPATH |
| 90 |
) |
| 91 |
return self._xml.xpath(self.ITEM_NAME_XPATH)[0].text.strip() |
| 92 |
# simple key |
| 93 |
return self._xml.findtext(self.ITEM_NAME_XPATH).strip() |
| 94 |
else: |
| 95 |
# composite key |
| 96 |
# keys with missing XPATH nodes are set to None |
| 97 |
keys = [] |
| 98 |
for item_name_xpath in self.ITEM_NAME_XPATH: |
| 99 |
if " | " in item_name_xpath: |
| 100 |
key_with_null_cleaned = self._check_key_delimiter_null( |
| 101 |
self._xml, item_name_xpath |
| 102 |
) |
| 103 |
if key_with_null_cleaned: |
| 104 |
keys.append(key_with_null_cleaned) |
| 105 |
else: |
| 106 |
try: |
| 107 |
keys.append(self.xml.xpath(item_name_xpath)[0].text.strip()) |
| 108 |
except: |
| 109 |
keys.append(None) |
| 110 |
if keys: |
| 111 |
return tuple(keys) |
| 112 |
else: |
| 113 |
return keys |
| 114 |
|
| 115 |
# ALIAS key <=> name |
| 116 |
key = name |
| 117 |
|
| 118 |
def _check_key_delimiter_null(self, xml, item_name_xpath): |
| 119 |
""" |
| 120 |
Case where key is provided like key: re-name | Null |
| 121 |
|
| 122 |
:param xml: xml object retrieved from device |
| 123 |
:param item_name_xpath: key xpath |
| 124 |
:return: key if fetched else [] |
| 125 |
""" |
| 126 |
if "Null" in item_name_xpath: |
| 127 |
# Let try get value for valid xpath key |
| 128 |
xpath_key = [x for x in item_name_xpath.split(" | ") if x != "Null"] |
| 129 |
if xpath_key: |
| 130 |
val = xml.xpath(xpath_key[0]) |
| 131 |
if val: |
| 132 |
return val[0].text.strip() |
| 133 |
else: |
| 134 |
# To handle Null key |
| 135 |
return [] |
| 136 |
|
| 137 |
@property |
| 138 |
def xml(self): |
| 139 |
"""returns the XML associated to the item""" |
| 140 |
return self._xml |
| 141 |
|
| 142 |
# ------------------------------------------------------------------------- |
| 143 |
# METHODS |
| 144 |
# ------------------------------------------------------------------------- |
| 145 |
|
| 146 |
def keys(self): |
| 147 |
"""list of view keys, i.e. field names""" |
| 148 |
return self.FIELDS.keys() |
| 149 |
|
| 150 |
def values(self): |
| 151 |
"""list of view values""" |
| 152 |
return [getattr(self, field) for field in self.keys()] |
| 153 |
|
| 154 |
def items(self): |
| 155 |
"""list of tuple(key,value)""" |
| 156 |
return zip(self.keys(), self.values()) |
| 157 |
|
| 158 |
def _updater_instance(self, more): |
| 159 |
"""called from extend""" |
| 160 |
if hasattr(more, "fields"): |
| 161 |
self.FIELDS = deepcopy(self.__class__.FIELDS) |
| 162 |
self.FIELDS.update(more.fields.end) |
| 163 |
|
| 164 |
if hasattr(more, "groups"): |
| 165 |
self.GROUPS = deepcopy(self.__class__.GROUPS) |
| 166 |
self.GROUPS.update(more.groups) |
| 167 |
|
| 168 |
if hasattr(more, "eval"): |
| 169 |
self.EVAL = deepcopy(self.__class__.EVAL) |
| 170 |
self.EVAL.update(more.eval) |
| 171 |
|
| 172 |
def _updater_class(self, more): |
| 173 |
"""called from extend""" |
| 174 |
if hasattr(more, "fields"): |
| 175 |
self.FIELDS.update(more.fields.end) |
| 176 |
|
| 177 |
if hasattr(more, "groups"): |
| 178 |
self.GROUPS.update(more.groups) |
| 179 |
|
| 180 |
if hasattr(more, "eval"): |
| 181 |
self.EVAL.update(more.eval) |
| 182 |
|
| 183 |
@contextmanager |
| 184 |
def updater(self, fields=True, groups=False, all=True, **kvargs): |
| 185 |
""" |
| 186 |
provide the ability for subclassing objects to extend the |
| 187 |
definitions of the fields. this is implemented as a |
| 188 |
context manager with the form called from the subclass |
| 189 |
constructor: |
| 190 |
|
| 191 |
with self.extend() as more: |
| 192 |
more.fields = <dict> |
| 193 |
more.groups = <dict> # optional |
| 194 |
""" |
| 195 |
# --------------------------------------------------------------------- |
| 196 |
# create a new object class so we can attach stuff to it arbitrarily. |
| 197 |
# then pass that object to the caller, yo! |
| 198 |
# --------------------------------------------------------------------- |
| 199 |
|
| 200 |
more = type("RunstatViewMore", (object,), {})() |
| 201 |
if fields is True: |
| 202 |
more.fields = ViewFields() |
| 203 |
|
| 204 |
# --------------------------------------------------------------------- |
| 205 |
# callback through context manager |
| 206 |
# --------------------------------------------------------------------- |
| 207 |
|
| 208 |
yield more |
| 209 |
updater = self._updater_class if all is True else self._updater_instance |
| 210 |
updater(more) |
| 211 |
|
| 212 |
def asview(self, view_cls): |
| 213 |
"""create a new View object for this item""" |
| 214 |
return view_cls(self._table, self._xml) |
| 215 |
|
| 216 |
def refresh(self): |
| 217 |
""" |
| 218 |
~~~ EXPERIMENTAL ~~~ |
| 219 |
refresh the data from the Junos device. this only works if the table |
| 220 |
provides an "args_key", does not update the original table, just this |
| 221 |
specific view/item |
| 222 |
""" |
| 223 |
warnings.warn("Experimental method: refresh") |
| 224 |
|
| 225 |
if self._table.can_refresh is not True: |
| 226 |
raise RuntimeError("table does not support this feature") |
| 227 |
|
| 228 |
# create a new table instance that gets only the specific named |
| 229 |
# value of this view |
| 230 |
|
| 231 |
tbl_xml = self._table._rpc_get(self.name) |
| 232 |
new_xml = tbl_xml.xpath(self._table.ITEM_XPATH)[0] |
| 233 |
self._init_xml(new_xml) |
| 234 |
return self |
| 235 |
|
| 236 |
def to_json(self): |
| 237 |
""" |
| 238 |
:returns: JSON encoded string of entire View contents |
| 239 |
""" |
| 240 |
return json.dumps(self, cls=TableViewJSONEncoder) |
| 241 |
|
| 242 |
# ------------------------------------------------------------------------- |
| 243 |
# OVERLOADS |
| 244 |
# ------------------------------------------------------------------------- |
| 245 |
|
| 246 |
def __repr__(self): |
| 247 |
"""returns the name of the View with the associate item name""" |
| 248 |
return "%s:%s" % (self.__class__.__name__, self.name) |
| 249 |
|
| 250 |
def __getattr__(self, name): |
| 251 |
""" |
| 252 |
returns a view item value, called as :obj.name: |
| 253 |
""" |
| 254 |
expression = self.EVAL.get(name) |
| 255 |
if expression: |
| 256 |
variables = meta.find_undeclared_variables(expression) |
| 257 |
t = Template(expression) |
| 258 |
expression = t.render({k: self.__getitem__(k) for k in variables}) |
| 259 |
val = eval(expression) |
| 260 |
setattr(self, name, val) |
| 261 |
return val |
| 262 |
|
| 263 |
item = self.FIELDS.get(name) |
| 264 |
if item is None: |
| 265 |
raise ValueError("Unknown field: '%s'" % name) |
| 266 |
|
| 267 |
if "table" in item: |
| 268 |
# if this is a sub-table, then return that now |
| 269 |
return item["table"](self.D, self._xml) |
| 270 |
|
| 271 |
# otherwise, not a sub-table, and handle the field |
| 272 |
astype = item.get("astype", str) |
| 273 |
if "group" in item: |
| 274 |
if item["group"] in self._groups: |
| 275 |
found = self._groups[item["group"]].xpath(item["xpath"]) |
| 276 |
else: |
| 277 |
return |
| 278 |
else: |
| 279 |
found = self._xml.xpath(item["xpath"]) |
| 280 |
|
| 281 |
len_found = len(found) |
| 282 |
|
| 283 |
if astype is bool: |
| 284 |
# handle the boolean flag case separately |
| 285 |
return bool(len_found) |
| 286 |
|
| 287 |
if not len_found: |
| 288 |
# even for the case of numbers, do not set the value. we |
| 289 |
# want to detect "does not exist" vs. defaulting to 0 |
| 290 |
# -- 2013-nov-19, JLS. |
| 291 |
return None |
| 292 |
|
| 293 |
try: |
| 294 |
# added exception handler to catch malformed xpath expressesion |
| 295 |
# -- 2013-nov-19, JLS. |
| 296 |
# added support to handle multiple xpath values, i.e. a list of |
| 297 |
# things that have the same xpath expression (common in configs) |
| 298 |
# -- 2031-dec-06, JLS |
| 299 |
# added support to use the element tag if the text is empty |
| 300 |
def _munch(x): |
| 301 |
if sys.version < "3": |
| 302 |
as_str = x if isinstance(x, str) else x.text |
| 303 |
if isinstance(as_str, unicode): |
| 304 |
as_str = as_str.encode("ascii", "replace") |
| 305 |
else: |
| 306 |
as_str = x if isinstance(x, str) else x.text |
| 307 |
if as_str is not None: |
| 308 |
as_str = as_str.strip() |
| 309 |
if not as_str: |
| 310 |
as_str = x.tag # use 'not' to test for empty |
| 311 |
return astype(as_str) |
| 312 |
|
| 313 |
if 1 == len_found: |
| 314 |
return _munch(found[0]) |
| 315 |
# -- 2020-March-26, if string function (like string-before or string-after) is used as xpath (instead of as xpath condition), lxml will return ElementUnicodeResult object, which will be converted wrongly by the next interation, we should return the original UnicodeResult |
| 316 |
if isinstance(found, etree._ElementUnicodeResult): |
| 317 |
return found |
| 318 |
|
| 319 |
return [_munch(this) for this in found] |
| 320 |
|
| 321 |
except: |
| 322 |
raise RuntimeError("Unable to handle field:'%s'" % name) |
| 323 |
|
| 324 |
# and if we are here, then we didn't handle the field. |
| 325 |
raise RuntimeError("Unable to handle field:'%s'" % name) |
| 326 |
|
| 327 |
def __getitem__(self, name): |
| 328 |
""" |
| 329 |
allow the caller to extract field values using :obj['name']: |
| 330 |
the same way they would do :obj.name: |
| 331 |
""" |
| 332 |
return getattr(self, name) |