pyats.connections package

Submodules

class pyats.connections.bases.BaseConnection(*, device, alias, via, **kwargs)

Bases: pyats.connections.bases.BasePipeline, pyats.async_.synchronize.Lockable

Class to be inherited by user’s own implementation of connection class. The goal of this base connection class is to provide a set of front-end standard for all connection implementations to follow:

  • must have standard apis such as connect/disconnect

  • must have basic ability to interact with the device: send/receive

  • must avoid race-conditions in forked environments.

This class inherits from async.Lockable base class, which enables connection classes to be both thread & multiprocessing safe.

__init__

instantiates this pipeline instance and store arguments internally.

Parameters
  • (obj) (device) –

  • (str) (via) –

  • (str)

  • (dict) (kwargs) –

Note

this api only supports keyword-only arguments for clarity’s sake.

config(*args, **kwargs)

Deprecated in v3.0.0, installed here for backwards compatibility.

configure()

placeholder API to be implemented by the subclass: sends one or more multiline configurations to the device via this connection and expect some form of return. This api should block until expected output is received, and should be prompt-aware in CLI implementations.

Note

implementation shall use the @BaseConnection.lock decorator to add lock/unlock multiprocessing capability.

execute()

placeholder API to be implemented by the subclass: sends a command to the device via this connection and expect some form of return. This api should block until expected output is received - and should be prompt-aware in CLI implementations.

Note

implementation shall use the @BaseConnection.lock decorator to add lock/unlock multiprocessing capability.

receive()

send

placeholder API to be implemented by the subclass: low-level receive that retrieves arbitrary information received from the device through this connection. Should not block - should be generic enough to be a building block for higher-level apis to build on. Should probably have a timeout value.

Note

implementation shall use the @BaseConnection.lock decorator to add lock/unlock multiprocessing capability.

send()

placeholder API to be implemented by the subclass: low-level send that sends raw information via the connection to the device. This api should not block, and should be generic enough to be a building block for higher-level apis to build on.

Note

implementation shall use the @BaseConnection.lock decorator to add lock/unlock multiprocessing capability.

class pyats.connections.bases.BasePipeline(*, device, alias, via, **kwargs)

Bases: object

Internal base class intended to describe a ‘pipeline’, eg, something that can be connected & disconnected. The goal of this base class is to enable code sharing between internal implementations,

A pipeline is defined as something that can:
  • connect & disconnect

  • contains pipeline information

This class is not to be used directly by any user. It is only useful when implementing a “connection-like” object that relies on method redirects.

__init__

instantiates this pipeline instance and store arguments internally.

Parameters
  • (obj) (device) –

  • (str) (via) –

  • (str)

  • (dict) (kwargs) –

Note

this api only supports keyword-only arguments for clarity’s sake.

connect()

placeholder API to be implemented by the subclass: creates/opens the connection to given device.

property connected

returns True/False for whether this pipeline instance is up

Type

placeholder property to be implemented by the subclass

property connection_info

Based on given via & device objects, find the connection detail, such as ip, port & etc and return a dictionary.

Returns

Return type

dict of key/values detailing the connection

property device

device property

returns the actual device object this pipeline connects to. This retrieves (evaluates) the weak reference to connection and returns a real object.

disconnect()

placeholder API to be implemented by the subclass: closing/disconnects the connection to given device.

class pyats.connections.hooks.ServiceHook(connection, servicename, **kwargs)

Bases: object

ServiceHook allows users to hook (dynamicaly) to a particular connection service and intercept/record its input arguments and return values each time it is called.

To implement a hook, subclass this ServiceHook class and implement your own, meaningful enter(), exit() and possibly, error_handle() methods.

__init__ method, called when a service hook is attached to a connection service. This will replace the given connection’s service with this hookspec.

Parameters
  • (BaseConnect) (connection) –

  • (str) (service) –

  • kwargs (any kwargs to be stored into this object) –

property connection
enter(*args, **kwargs)

Enter api, called right before the hooked service is executed. All arguments provided to the hooked service api is passed to this method.

Note

This is a placeholder intended for users to replace in their implementation of ServiceHooks.

error_handle(e)

Error handler, called with the exception that occured while the hooked service ran.

Note

This is a placeholder intended for users to replace in their implementation of ServiceHooks.

exit(retval)

Exit api, called right after the hooked service is executed. The return value of the hooked service will be passed in as arguments.

Note

This is a placeholder intended for users to replace in their implementation of ServiceHooks.

class pyats.connections.manager.ConnectionManager(device, default_connection_cls=None)

Bases: object

Connection Manager class

Manager class for managing & handling multiple connections to the given device object. By default, each device object gets assigned its own unique connection manager.

Each connection managed by this class must be provided with with a unique connection alias (name), and will be stored in each instance’s ‘connections’ attribute as a dictionary of alias/object.

instantiates this class. This is mostly called by the parent Device object.

Parameters

(obj) (device) –

connect(*args, **kwargs)

Establish connection to parent device

This API establishes connection to parent device, using the provided connection class. This is a meta API and takes advantage of duck-typing to abstract connection class (implementation), so that users only need to deal with the Device class itself, but be able to connect to different devices using any connection implementations.

passes all arguments to .instantiate() or .instantiate_pool() to create the class obj - depending on whether ‘pool_size’ is > 0, then calls .connect() api to establish the connection

property default_alias

default_alias property

property, retrieving the default connection alias from device’s default connectiond definition. If not found, return ‘default’

property default_connection_cls

default_connection_cls property

retrieves the current known default connecition class. if no class is known, try and load one from entrypoint, or try and default to unicon.

destroy(alias=None)

Destroy a connection to device

This is the API to destroy a connection object to the target device. It will first disconnect the connection, the remove the object from device connection manager.

Parameters

(str) (alias) – Defaults: ‘default’

Examples

>>> device.destroy(alias = 'vty1')
destroy_all()

Destroys all connections

This API attempts to disconnect a live connection and remove the object from this connection manager.

Parameters

None

Returns

Return type

None

property device

device property

retrieves the parent device object through its weak reference.

disconnect(alias=None)

Disconnects device connection

This API disconnects the given connection alias from the device. The connection object is still there - simply in a disconnected state.

Parameters

(str) (alias) – Defaults: ‘default’

Examples

>>> device.disconnect()
disconnect_all()

Disconnects all connections

This API disconnects all live connections managed by this connection manager. Note that when a connection is disconnected, it is only a state change: the object persists and is not deleted

Parameters

None

Returns

Return type

None

instantiate(cls=None, alias=None, via=None, pool_size=None, pool_timeout=None, *args, **kwargs)

Creates the connection object to parent device

This API creates the connection object(by instantiating the class) to parent device, using the provided connection class. This is a meta API and takes advantage of duck-typing to abstract connection class (implementation), so that users only need to deal with the Device class itself, but be able to connect to different devices using any connection implementations.

Behaviors:

  • default alias is ‘default’ (or otherwise specified to __init__)

  • if an alias object already exists, re-use it and connect it

  • if connection class is not provided, use that provided in the via definition or in the ‘default’ via.

  • a new connection class instance is created with the above given information and stored in self.connections dictionary

Parameters
  • (class) (cls) – as input, and establishes connection to the device. Default to unicon.Unicon

  • (str) (via) – Defaults: ‘default’

  • (str) – of the device in the YAML file. Defaults: None

  • (int) (pool_timeout) – size that can be used with Pcall

  • (int) – session to free up in pool. Default: 0 (forever)

  • args (all other arguments to propagate to the connection cls) –

  • kwargs (all other arguments to propagate to the connection cls) –

Examples

>>> from unicon import Unicon
>>> device.connect(cls=Unicon)
>>> device.connect(alias = 'vty1', via = 'mgmt.a')
>>> device.connect(alias = 'vty2', via = 'mgmt.b')
>>> device.connect(alias = 'vty3', via = 'x', pool_size = 3)
Returns

Return type

None

Raises
  • Exception if not able to figure out how to instantiate connection

  • object

instantiate_pool(size, alias, factory=None, via=None, timeout=0, **kwargs)
is_connected(alias=None)

Checks for connection to device

This is an API that returns whether there is an active connection to the given device.

Parameters

alias (str) – connection alias to operate on. Defaults: ‘default’

Examples

>>> device.is_connected()
start_pool(*args, **kwargs)
temp_default_alias(alias)

Temporarly change the connection_mgr.default_alias This context manager changed the defautl connection alias to the provide alias, then set it back to what deafult was.

class pyats.connections.manager.Connections(*args)

Bases: object

The Connections class keeps track of connections to a device.

This class implements ‘AttrDict’ behavior with special case handling for the ‘default’ key. The ‘default’ connection points to the user connection that has last connected without specifying an alias: e.g device.connect(via=’cli’), hence implying the ‘default’.

Users can set the active ‘default’ alias using the device.default_connection_alias setter which updates the _default_alias of this class.

pop(key)
class pyats.connections.pool.ConnectionPool(*, device, alias, via, factory, pool_size, pool_timeout=None, **kwargs)

Bases: pyats.connections.bases.BasePipeline

Connection-like class, designed to manage multiple simultaneous sessions of the same connection (type/path) and allow sharing in a multi-process/thread environment, distributing the workload between sessions on a first-come first-serve basis.

This class is not intended to be instantiated by user script. It is transparently called and used by the upstream ConnectionManager. When used properly, pool instances appear as a straight-forward connection instance to the user, following all the rules & guidelines.

__init__

instantiates this ConnectionPool. This constructor has similar arguments to BaseConnection implementations, support for near-duck-typing usages.

As this instantiates a “pool” of connections, its session objects are instantiated as part of this constructor.

Parameters
  • (obj) (device) –

  • (str) (via) –

  • (str)

  • (class) (factory) – managed by this pool

  • (int) (pool_timeout) –

  • (int) – session to free up. Default to None (forever)

  • (dict) (kwargs) –

allocate()

Allocate

Allot a free connection from the pool and lock it.

Parameters

None

Returns

Return type

Return free connection from the pool

allot(method, *args, **kwargs)

Allot a free connection from the pool and call the wanted method on that connection, returning its output. Any errors arising from the call will be propagated to the caller.

Parameters
  • (str) (method) –

  • args/kwargs (all other arguments to be passed to the called method) –

Returns

Return type

output from the call

connect()

Implementation of parent BasePipeline.connect(). This method starts up all child workers (sessions) in this pool in a thread pool.

Returns

Return type

list of returns from each worker’s connect() call.

property connected

property, returns whether ALL workers are currently connected.

Returns

  • True if all workers are connected

  • False otherwise

disconnect()

Implementation of parent BasePipeline.disconnect(). This method disconnects all current child workers (sessions) in a thread pool.

Returns

Return type

None