| 1 |
# stdlib |
| 2 |
from inspect import isclass |
| 3 |
from time import time |
| 4 |
from datetime import datetime |
| 5 |
import os |
| 6 |
|
| 7 |
# 3rd-party |
| 8 |
from lxml import etree |
| 9 |
|
| 10 |
import json |
| 11 |
from jnpr.junos.factory.to_json import TableJSONEncoder |
| 12 |
|
| 13 |
_TSFMT = "%Y%m%d%H%M%S" |
| 14 |
|
| 15 |
|
| 16 |
class Table(object): |
| 17 |
ITEM_XPATH = None |
| 18 |
ITEM_NAME_XPATH = "name" |
| 19 |
VIEW = None |
| 20 |
USE_FILTER = None |
| 21 |
|
| 22 |
def __init__(self, dev=None, xml=None, path=None, use_filter=True): |
| 23 |
""" |
| 24 |
:dev: Device instance |
| 25 |
:xml: lxml Element instance |
| 26 |
:path: file path to XML, to be used rather than :dev: |
| 27 |
:use_filter: Default usage is SAX parsing, disable this variable to use DOM |
| 28 |
""" |
| 29 |
self._dev = dev |
| 30 |
self.xml = xml |
| 31 |
self.view = self.VIEW |
| 32 |
self._key_list = [] |
| 33 |
self._path = path |
| 34 |
self._lxml = xml |
| 35 |
self._use_filter = self.USE_FILTER and use_filter |
| 36 |
if self._dev is not None: |
| 37 |
self._use_filter = self._use_filter and self._dev._use_filter |
| 38 |
|
| 39 |
# ------------------------------------------------------------------------- |
| 40 |
|
| 41 |
# PROPERTIES |
| 42 |
# ------------------------------------------------------------------------- |
| 43 |
|
| 44 |
@property |
| 45 |
def D(self): |
| 46 |
"""the Device instance""" |
| 47 |
return self._dev |
| 48 |
|
| 49 |
@property |
| 50 |
def RPC(self): |
| 51 |
"""the Device.rpc instance""" |
| 52 |
return self.D.rpc |
| 53 |
|
| 54 |
@property |
| 55 |
def view(self): |
| 56 |
"""returns the current view assigned to this table""" |
| 57 |
return self._view |
| 58 |
|
| 59 |
@view.setter |
| 60 |
def view(self, cls): |
| 61 |
"""assigns a new view to the table""" |
| 62 |
if cls is None: |
| 63 |
self._view = None |
| 64 |
return |
| 65 |
|
| 66 |
if not isclass(cls): |
| 67 |
raise ValueError("Must be given RunstatView class") |
| 68 |
|
| 69 |
self._view = cls |
| 70 |
|
| 71 |
@property |
| 72 |
def hostname(self): |
| 73 |
return self.D.hostname |
| 74 |
|
| 75 |
@property |
| 76 |
def is_container(self): |
| 77 |
""" |
| 78 |
True if this table does not have records, but is a container of fields |
| 79 |
False otherwise |
| 80 |
""" |
| 81 |
return self.ITEM_XPATH is None |
| 82 |
|
| 83 |
@property |
| 84 |
def key_list(self): |
| 85 |
"""the list of keys, as property for caching""" |
| 86 |
return self._key_list |
| 87 |
|
| 88 |
# ------------------------------------------------------------------------- |
| 89 |
# PRIVATE METHODS |
| 90 |
# ------------------------------------------------------------------------- |
| 91 |
|
| 92 |
def _assert_data(self): |
| 93 |
if self.xml is None: |
| 94 |
raise RuntimeError("Table is empty, use get()") |
| 95 |
|
| 96 |
def _tkey(self, this, key_list): |
| 97 |
"""keys with missing XPATH nodes are set to None""" |
| 98 |
keys = [] |
| 99 |
for k in key_list: |
| 100 |
try: |
| 101 |
keys.append(this.xpath(k)[0].text) |
| 102 |
except: |
| 103 |
# Case where key is provided like key: re-name | Null |
| 104 |
if " | " in k and "Null" in k: |
| 105 |
continue |
| 106 |
keys.append(None) |
| 107 |
return tuple(keys) |
| 108 |
|
| 109 |
def _keys_composite(self, xpath, key_list): |
| 110 |
"""composite keys return a tuple of key-items""" |
| 111 |
return [self._tkey(item, key_list) for item in self.xml.xpath(xpath)] |
| 112 |
|
| 113 |
def _keys_simple(self, xpath): |
| 114 |
return [x.text.strip() for x in self.xml.xpath(xpath)] |
| 115 |
|
| 116 |
def _keyspec(self): |
| 117 |
"""returns tuple (keyname-xpath, item-xpath)""" |
| 118 |
return (self.ITEM_NAME_XPATH, self.ITEM_XPATH) |
| 119 |
|
| 120 |
def _clearkeys(self): |
| 121 |
self._key_list = [] |
| 122 |
|
| 123 |
# ------------------------------------------------------------------------- |
| 124 |
# PUBLIC METHODS |
| 125 |
# ------------------------------------------------------------------------- |
| 126 |
|
| 127 |
# ------------------------------------------------------------------------ |
| 128 |
# keys |
| 129 |
# ------------------------------------------------------------------------ |
| 130 |
|
| 131 |
def _keys(self): |
| 132 |
"""return a list of data item keys from the Table XML""" |
| 133 |
|
| 134 |
self._assert_data() |
| 135 |
key_value, xpath = self._keyspec() |
| 136 |
|
| 137 |
if isinstance(key_value, str): |
| 138 |
# Check if pipe is in the key_value, if so append xpath |
| 139 |
# to each value |
| 140 |
if " | " in key_value: |
| 141 |
return self._keys_simple( |
| 142 |
" | ".join( |
| 143 |
[xpath + "/" + x for x in key_value.split(" | ") if x != "Null"] |
| 144 |
) |
| 145 |
) |
| 146 |
return self._keys_simple(xpath + "/" + key_value) |
| 147 |
|
| 148 |
# user explicitly passed key as Null in Table |
| 149 |
if key_value is None: |
| 150 |
return [] |
| 151 |
|
| 152 |
if not isinstance(key_value, list): |
| 153 |
raise RuntimeError( |
| 154 |
"What to do with key, table:'%s'" % self.__class__.__name__ |
| 155 |
) |
| 156 |
|
| 157 |
# ok, so it's a list, which means we need to extract tuple values |
| 158 |
return self._keys_composite(xpath, key_value) |
| 159 |
|
| 160 |
def keys(self): |
| 161 |
# if the key_list has been cached, then use it |
| 162 |
if len(self.key_list): |
| 163 |
return self.key_list |
| 164 |
|
| 165 |
# otherwise, build the list of keys into the cache |
| 166 |
self._key_list = self._keys() |
| 167 |
return self._key_list |
| 168 |
|
| 169 |
# ------------------------------------------------------------------------ |
| 170 |
# values |
| 171 |
# ------------------------------------------------------------------------ |
| 172 |
|
| 173 |
def values(self): |
| 174 |
"""returns list of table entry items()""" |
| 175 |
|
| 176 |
self._assert_data() |
| 177 |
if self.view is None: |
| 178 |
# no View, so provide XML for each item |
| 179 |
return [this for this in self] |
| 180 |
else: |
| 181 |
# view object for each item |
| 182 |
return [list(this.items()) for this in self] |
| 183 |
|
| 184 |
# ------------------------------------------------------------------------ |
| 185 |
# items |
| 186 |
# ------------------------------------------------------------------------ |
| 187 |
|
| 188 |
def items(self): |
| 189 |
"""returns list of tuple(name,values) for each table entry""" |
| 190 |
return list(zip(self.keys(), self.values())) |
| 191 |
|
| 192 |
# ------------------------------------------------------------------------ |
| 193 |
# get - loads the data from source |
| 194 |
# ------------------------------------------------------------------------ |
| 195 |
|
| 196 |
def get(self, *vargs, **kvargs): |
| 197 |
# implemented by either OpTable or CfgTable |
| 198 |
# @@@ perhaps this should raise an exception rather than just 'pass',?? |
| 199 |
pass |
| 200 |
|
| 201 |
# ------------------------------------------------------------------------ |
| 202 |
# savexml - saves the table XML to a local file |
| 203 |
# ------------------------------------------------------------------------ |
| 204 |
|
| 205 |
def savexml(self, path, hostname=False, timestamp=False, append=None): |
| 206 |
""" |
| 207 |
Save a copy of the table XML data to a local file. The name of the |
| 208 |
output file (:path:) can include the name of the Device host, the |
| 209 |
timestamp of this action, as well as any user-defined appended value. |
| 210 |
These 'add-ons' will be added to the :path: value prior to the file |
| 211 |
extension in the order (hostname,timestamp,append), separated by |
| 212 |
underscore (_). |
| 213 |
|
| 214 |
For example, if both hostname=True and append='BAZ1', then when |
| 215 |
:path: = '/var/tmp/foo.xml' and the Device.hostname is "srx123", the |
| 216 |
final file-path will be "/var/tmp/foo_srx123_BAZ1.xml" |
| 217 |
|
| 218 |
:path: |
| 219 |
file-path to write the XML file on the local filesystem |
| 220 |
|
| 221 |
:hostname: |
| 222 |
if True, will append the hostname to the :path: |
| 223 |
|
| 224 |
:timestamp: |
| 225 |
if True, will append the timestamp to the :path: using the default |
| 226 |
timestamp format |
| 227 |
if <str> the timestamp will use the value as the timestamp format as |
| 228 |
defied by strftime() |
| 229 |
|
| 230 |
:append: |
| 231 |
any <str> value that you'd like appended to the :path: value |
| 232 |
preceding the filename extension. |
| 233 |
""" |
| 234 |
fname, fext = os.path.splitext(path) |
| 235 |
|
| 236 |
if hostname is True: |
| 237 |
fname += "_%s" % self.D.hostname |
| 238 |
|
| 239 |
if timestamp is not False: |
| 240 |
tsfmt = _TSFMT if timestamp is True else timestamp |
| 241 |
tsfmt_val = datetime.fromtimestamp(time()).strftime(tsfmt) |
| 242 |
fname += "_%s" % tsfmt_val |
| 243 |
|
| 244 |
if append is not None: |
| 245 |
fname += "_%s" % append |
| 246 |
|
| 247 |
path = fname + fext |
| 248 |
with open(path, "wb+") as f: |
| 249 |
pass |
| 250 |
return etree.ElementTree(self.xml).write(path) |
| 251 |
|
| 252 |
def to_json(self): |
| 253 |
""" |
| 254 |
:returns: JSON encoded string of entire Table contents |
| 255 |
""" |
| 256 |
return json.dumps(self, cls=TableJSONEncoder) |
| 257 |
|
| 258 |
# ------------------------------------------------------------------------- |
| 259 |
# OVERLOADS |
| 260 |
# ------------------------------------------------------------------------- |
| 261 |
|
| 262 |
__call__ = get |
| 263 |
|
| 264 |
def __repr__(self): |
| 265 |
cls_name = self.__class__.__name__ |
| 266 |
source = self.D.hostname if self.D is not None else self._path |
| 267 |
|
| 268 |
if self.xml is None: |
| 269 |
return "%s:%s - Table empty" % (cls_name, source) |
| 270 |
else: |
| 271 |
n_items = len(self.keys()) |
| 272 |
return "%s:%s: %s items" % (cls_name, source, n_items) |
| 273 |
|
| 274 |
def __len__(self): |
| 275 |
self._assert_data() |
| 276 |
return len(self.keys()) |
| 277 |
|
| 278 |
def __iter__(self): |
| 279 |
"""iterate over each time in the table""" |
| 280 |
self._assert_data() |
| 281 |
|
| 282 |
as_xml = lambda table, view_xml: view_xml |
| 283 |
view_as = self.view or as_xml |
| 284 |
|
| 285 |
for this in self.xml.xpath(self.ITEM_XPATH): |
| 286 |
yield view_as(self, this) |
| 287 |
|
| 288 |
def __getitem__(self, value): |
| 289 |
""" |
| 290 |
returns a table item. If a table view is set (should be by default) |
| 291 |
then the item will be converted to the view upon return. if there is |
| 292 |
no table view, then the XML object will be returned. |
| 293 |
|
| 294 |
:value: |
| 295 |
for <string>, this will perform a select based on key-name |
| 296 |
for <tuple>, this will perform a select based on compsite key-name |
| 297 |
for <int>, this will perform a select based by position, like <list> |
| 298 |
[0] is the first item |
| 299 |
[-1] is the last item |
| 300 |
when it is a <slice> then this will return a <list> of View widgets |
| 301 |
""" |
| 302 |
self._assert_data() |
| 303 |
keys = self.keys() |
| 304 |
|
| 305 |
if isinstance(value, int): |
| 306 |
# if selection by index, then grab the key at this index and |
| 307 |
# recursively call this method using that key, yo! |
| 308 |
return self.__getitem__(keys[value]) |
| 309 |
|
| 310 |
if isinstance(value, slice): |
| 311 |
# implements the 'slice' mechanism |
| 312 |
return [self.__getitem__(key) for key in keys[value]] |
| 313 |
|
| 314 |
# ---[ get_xpath ] ---------------------------------------------------- |
| 315 |
|
| 316 |
def get_xpath(find_value): |
| 317 |
namekey_xpath, item_xpath = self._keyspec() |
| 318 |
xnkv = '[{}="{}"]' |
| 319 |
|
| 320 |
if isinstance(find_value, str): |
| 321 |
# find by name, simple key |
| 322 |
return item_xpath + xnkv.format(namekey_xpath, find_value) |
| 323 |
|
| 324 |
if isinstance(find_value, tuple): |
| 325 |
# composite key (value1, value2, ...) will create an |
| 326 |
# iterative xpath of the fmt statement for each key/value pair |
| 327 |
# skip over missing keys |
| 328 |
kv = [] |
| 329 |
for k, v in zip(namekey_xpath, find_value): |
| 330 |
if v is not None: |
| 331 |
kv.append(xnkv.format(k.replace("_", "-"), v)) |
| 332 |
xpf = "".join(kv) |
| 333 |
return item_xpath + xpf |
| 334 |
|
| 335 |
# ---[END: get_xpath ] ------------------------------------------------ |
| 336 |
|
| 337 |
found = self.xml.xpath(get_xpath(value)) |
| 338 |
if not len(found): |
| 339 |
return None |
| 340 |
|
| 341 |
as_xml = lambda table, view_xml: view_xml |
| 342 |
use_view = self.view or as_xml |
| 343 |
|
| 344 |
return use_view(table=self, view_xml=found[0]) |
| 345 |
|
| 346 |
def __contains__(self, key): |
| 347 |
"""membership for use with 'in'""" |
| 348 |
return bool(key in self.keys()) |