jnpr.junos.factory

jnpr.junos.factory.cfgtable

class jnpr.junos.factory.cfgtable.CfgTable(dev=None, xml=None, path=None, mode=None)[source]

Bases: Table

__init__(dev=None, xml=None, path=None, mode=None)[source]
Dev:

Device instance

Xml:

lxml Element instance

Path:

file path to XML, to be used rather than :dev:

Use_filter:

Default usage is SAX parsing, disable this variable to use DOM

append()[source]

It creates lxml nodes with field name as xml tag and its value given by user as text of xml node. The generated xml nodes are appended to configuration xml at appropriate hierarchy.

Warning

xml node that are appended cannot be changed later hence care should be taken to assign correct value to table fields before calling append.

get(*vargs, **kvargs)[source]

Retrieve configuration data for this table. By default all child keys of the table are loaded. This behavior can be overridden by with kvargs[‘nameonly’]=True

Parameters:
  • vargs[0] (str) – identifies a unique item in the table, same as calling with :kvargs[‘key’]: value

  • namesonly (str) – OPTIONAL True/False*, when set to True will cause only the the name-keys to be retrieved.

  • key (str) – OPTIONAL identifies a unique item in the table

  • options (dict) – OPTIONAL options to pass to get-configuration. By default {‘inherit’: ‘inherit’, ‘groups’: ‘groups’} is sent.

get_table_xml()[source]

It returns lxml object of configuration xml that is generated from table data (field=value) pairs. To get a valid xml this method should be used after append() is called.

property keys_required

True/False - if this Table requires keys

load(**kvargs)[source]

Load configuration xml having table data (field=value) in candidate db. This method should be used after append() is called to get the desired results.

Parameters:
  • overwrite (bool) – Determines if the contents completely replace the existing configuration. Default is False.

  • merge (bool) – If set to True will set the load-config action to merge. the default load-config action is ‘replace’

Returns:

Class object.

Raises:
ConfigLoadError:

When errors detected while loading configuration. You can use the Exception errs variable to identify the specific problems

RuntimeError:

If field value is set and append() is not invoked before calling this method, it will raise an exception with appropriate error message.

property required_keys

return a list of the keys required when invoking :get(): and :get_keys():

reset()[source]

Initialize fields of set table to it’s default value (if mentioned in Table/View) else set to None.

set(**kvargs)[source]

Load configuration data in running db. It performs following operation in sequence.

  • lock(): Locks candidate configuration db.

  • load(): Load structured configuration xml in candidate db.

  • commit(): Commit configuration to runnning db.

  • unlock(): Unlock candidate db.

This method should be used after append() is called to get the desired results.

Parameters:
  • overwrite (bool) – Determines if the contents completely replace the existing configuration. Default is False.

  • merge (bool) – If set to True will set the load-config action to merge. the default load-config action is ‘replace’

  • comment (str) – If provided logs this comment with the commit.

  • confirm (int) – If provided activates confirm safeguard with provided value as timeout (minutes).

  • timeout (int) – If provided the command will wait for completion using the provided value as timeout (seconds). By default the device timeout is used.

  • sync (bool) – On dual control plane systems, requests that the candidate configuration on one control plane be copied to the other control plane, checked for correct syntax, and committed on both Routing Engines.

  • force_sync (bool) – On dual control plane systems, forces the candidate configuration on one control plane to be copied to the other control plane.

  • full (bool) – When true requires all the daemons to check and evaluate the new configuration.

  • detail (bool) – When true return commit detail as XML

Returns:

Class object:

Raises:
ConfigLoadError:

When errors detected while loading configuration. You can use the Exception errs variable to identify the specific problems

CommitError:

When errors detected in candidate configuration. You can use the Exception errs variable to identify the specific problems

RuntimeError:

If field value is set and append() is not invoked before calling this method, it will raise an exception with appropriate error message.

Warning

If the function does not receive a reply prior to the timeout a RpcTimeoutError will be raised. It is possible the commit was successful. Manual verification may be required.

jnpr.junos.factory.factory_cls

jnpr.junos.factory.factory_cls.FactoryCMDChildTable(title=None, regex=None, key='name', delimiter=None, table_name=None, view=None, key_items=None, item=None, eval=None)[source]
jnpr.junos.factory.factory_cls.FactoryCMDTable(cmd, args=None, item=None, key_items=None, key='name', view=None, table_name=None, title=None, delimiter=None, eval=None, platform='juniper_junos', use_textfsm=False, **kwargs)[source]
jnpr.junos.factory.factory_cls.FactoryCMDView(fields, **kvargs)[source]
Fields:

dictionary of fields, structure of which is ~internal~ and should not be defined explicitly. use the RunstatMaker.Fields() mechanism to create theserather than hardcoding the dictionary structures; since they might change over time.

Kvargs:

‘view_name’ to name the class. this could be useful for debug or eventual callback mechanisms.

‘groups’ is a dict of name/xpath assocaited to fields this technique would be used to extract fields from node-set elements like port <if-device-flags>.

‘extends’ names the base View class to extend. using this technique you can add to existing defined Views.

jnpr.junos.factory.factory_cls.FactoryCfgTable(table_name=None, data_dict={})[source]
jnpr.junos.factory.factory_cls.FactoryOpTable(cmd, args=None, args_key=None, item=None, key='name', view=None, table_name=None, use_filter=True)[source]
jnpr.junos.factory.factory_cls.FactoryTable(item, key='name', view=None, table_name=None, use_filter=True)[source]
jnpr.junos.factory.factory_cls.FactoryView(fields, **kvargs)[source]
Fields:

dictionary of fields, structure of which is ~internal~ and should not be defined explicitly. use the RunstatMaker.Fields() mechanism to create theserather than hardcoding the dictionary structures; since they might change over time.

Kvargs:

‘view_name’ to name the class. this could be useful for debug or eventual callback mechanisms.

‘groups’ is a dict of name/xpath assocaited to fields this technique would be used to extract fields from node-set elements like port <if-device-flags>.

‘extends’ names the base View class to extend. using this technique you can add to existing defined Views.

jnpr.junos.factory.factory_loader

This file contains the FactoryLoader class that is used to dynamically create Runstat Table and View objects from a <dict> of data. The <dict> can originate from any kind of source: YAML, JSON, program. For examples of YAML refer to the .yml files in this jnpr.junos.op directory.

class jnpr.junos.factory.factory_loader.FactoryLoader[source]

Bases: object

Used to load a <dict> of data that contains Table and View definitions.

The primary method is :load(): which will return a <dict> of item-name and item-class definitions.

If you want to import these definitions directly into your namespace, (like a module) you would do the following:

loader = FactoryLoader() catalog = loader.load( <catalog_dict> ) globals().update( catalog )

If you did not want to do this, you can access the items as the catalog. For example, if your <catalog_dict> contained a Table called MyTable, then you could do something like:

MyTable = catalog[‘MyTable’] table = MyTable(dev) table.get() …

__init__()[source]
load(catalog_dict, envrion={})[source]

jnpr.junos.factory.optable

class jnpr.junos.factory.optable.OpTable(dev=None, xml=None, path=None, use_filter=True)[source]

Bases: Table

get(*vargs, **kvargs)[source]

Retrieve the XML table data from the Device instance and returns back the Table instance - for call-chaining purposes.

If the Table was created with a :path: rather than a Device, then this method will load the XML from that file. In this case, the *vargs, and **kvargs are not used.

ALIAS: __call__

Vargs:

[0] is the table :arg_key: value. This is used so that the caller can retrieve just one item from the table without having to know the Junos RPC argument.

Kvargs:

these are the name/value pairs relating to the specific Junos XML command attached to the table. For example, if the RPC is ‘get-route-information’, there are parameters such as ‘table’ and ‘destination’. Any valid RPC argument can be passed to :kvargs: to further filter the results of the :get(): operation. neato!

NOTES:

If you need to create a ‘stub’ for unit-testing purposes, you want to create a subclass of your table and overload this methods.

jnpr.junos.factory.optable.generate_sax_parser_input(obj)[source]

Used to generate xml object from Table/view to be used in SAX parsing Args: obj: self object which contains table/view details

Returns: lxml etree object to be used as sax parser input

jnpr.junos.factory.table

class jnpr.junos.factory.table.Table(dev=None, xml=None, path=None, use_filter=True)[source]

Bases: object

property D

the Device instance

ITEM_NAME_XPATH = 'name'
ITEM_XPATH = None
property RPC

the Device.rpc instance

USE_FILTER = None
VIEW = None
__init__(dev=None, xml=None, path=None, use_filter=True)[source]
Dev:

Device instance

Xml:

lxml Element instance

Path:

file path to XML, to be used rather than :dev:

Use_filter:

Default usage is SAX parsing, disable this variable to use DOM

get(*vargs, **kvargs)[source]
property hostname
property is_container

True if this table does not have records, but is a container of fields False otherwise

items()[source]

returns list of tuple(name,values) for each table entry

property key_list

the list of keys, as property for caching

keys()[source]
savexml(path, hostname=False, timestamp=False, append=None)[source]

Save a copy of the table XML data to a local file. The name of the output file (:path:) can include the name of the Device host, the timestamp of this action, as well as any user-defined appended value. These ‘add-ons’ will be added to the :path: value prior to the file extension in the order (hostname,timestamp,append), separated by underscore (_).

For example, if both hostname=True and append=’BAZ1’, then when :path: = ‘/var/tmp/foo.xml’ and the Device.hostname is “srx123”, the final file-path will be “/var/tmp/foo_srx123_BAZ1.xml”

Path:

file-path to write the XML file on the local filesystem

Hostname:

if True, will append the hostname to the :path:

Timestamp:
if True, will append the timestamp to the :path: using the default

timestamp format

if <str> the timestamp will use the value as the timestamp format as

defied by strftime()

Append:

any <str> value that you’d like appended to the :path: value preceding the filename extension.

to_json()[source]
Returns:

JSON encoded string of entire Table contents

values()[source]

returns list of table entry items()

property view

returns the current view assigned to this table

jnpr.junos.factory.view

class jnpr.junos.factory.view.View(table, view_xml)[source]

Bases: object

View is the base-class that makes extracting values from XML data appear as objects with attributes.

property D

return the Device instance for this View

EVAL = {}
FIELDS = {}
GROUPS = None
ITEM_NAME_XPATH = 'name'
property T

return the Table instance for the View

__init__(table, view_xml)[source]
Table:

instance of the RunstatTable

View_xml:

this should be an lxml etree Elemenet object. This constructor also accepts a list with a single item/XML

asview(view_cls)[source]

create a new View object for this item

items()[source]

list of tuple(key,value)

property key

return the name of view item

keys()[source]

list of view keys, i.e. field names

property name

return the name of view item

refresh()[source]

~~~ EXPERIMENTAL ~~~ refresh the data from the Junos device. this only works if the table provides an “args_key”, does not update the original table, just this specific view/item

to_json()[source]
Returns:

JSON encoded string of entire View contents

updater(fields=True, groups=False, all=True, **kvargs)[source]

provide the ability for subclassing objects to extend the definitions of the fields. this is implemented as a context manager with the form called from the subclass constructor:

with self.extend() as more:

more.fields = <dict> more.groups = <dict> # optional

values()[source]

list of view values

property xml

returns the XML associated to the item

jnpr.junos.factory.viewfields

class jnpr.junos.factory.viewfields.ViewFields[source]

Bases: object

Used to dynamically create a field dictionary used with the RunstatView class

__init__()[source]
astype(name, xpath=None, astype=<class 'int'>, **kvargs)[source]

field string value will be passed to function :astype:

This is typically used to do simple type conversions, but also works really well if you set :astype: to a function that does a basic converstion like look at the value and change it to a True/False. For example:

astype=lambda x: True if x == ‘enabled’ else False

property end
flag(name, xpath=None, **kvargs)[source]

field is a flag, results in True/False if the xpath element exists or not. Model this as a boolean type <bool>

group(name, xpath=None, **kvargs)[source]

field is an apply group, results in value of group attr if the xpath element has the associated group attribute.

int(name, xpath=None, **kvargs)[source]

field is an integer

str(name, xpath=None, **kvargs)[source]

field is a string

table(name, table)[source]

field is a RunstatTable

Module contents

class jnpr.junos.factory.FactoryLoader[source]

Bases: object

Used to load a <dict> of data that contains Table and View definitions.

The primary method is :load(): which will return a <dict> of item-name and item-class definitions.

If you want to import these definitions directly into your namespace, (like a module) you would do the following:

loader = FactoryLoader() catalog = loader.load( <catalog_dict> ) globals().update( catalog )

If you did not want to do this, you can access the items as the catalog. For example, if your <catalog_dict> contained a Table called MyTable, then you could do something like:

MyTable = catalog[‘MyTable’] table = MyTable(dev) table.get() …

__init__()[source]
load(catalog_dict, envrion={})[source]
jnpr.junos.factory.loadyaml(path)[source]

Load a YAML file at :path: that contains Table and View definitions. Returns a <dict> of item-name anditem-class definition.

If you want to import these definitions directly into your namespace, (like a module) you would do the following:

globals().update( loadyaml( <path-to-yaml-file> ))

If you did not want to do this, you can access the items as the <dict>. For example, if your YAML file contained a Table called MyTable, then you could do something like:

catalog = loadyaml( <path-to-yaml-file> ) MyTable = catalog[‘MyTable’]

table = MyTable(dev) table.get() …