unicon.eal package

Submodules

unicon.eal.bases module

All the base classes here

class unicon.eal.bases.BaseSpawn(spawn_command, size=None, timeout=None, hostname=None)

Bases: object

base class

abstract close(*args, **kwargs)
abstract expect(*args, **kwargs)
abstract match_buffer(pat_list)
abstract read_update_buffer(size=None)
abstract send(*args, **kwargs)
abstract sendline(*args, **kwargs)
abstract trim_buffer()

unicon.eal.dialog_processor module

Module:

unicon.eal.dialog_processor

Authors:

ATS TEAM (ats-dev@cisco.com, CSG( STEP) - India)

Description:

This module defines different types of DialogProcessors. DialogProcessor creates an event loop using a Dialog instance over a spawned connection, which performs pattern matching with the device response buffer

This module implements two different types of DialogProcessor: 1. SimpleDialogProcessor = Uses an internal timer for the even loop 2. DialogProcessor = Uses signal (SIGALRM) as a timer for the event loop

Dependencies:
  1. Dialog processor can be performed only on instance of Dialog

  2. Dialog instance under process is expected to have at least one exit point

  3. Dialog and Spawn has to be created before processing and also should be an instance of unicon.eal.dialog.Dialog and unicon.eal.expect.spawn respectively

class unicon.eal.dialog_processor.AlarmBasedDialogProcessor(dialog, spawn, context={}, timeout=None, **kwargs)

Bases: unicon.eal.dialog_processor.BaseDialogProcessor

Dialog Processor based on SIGALRM

This Dialog processor creates an event loop which raises an SIGALARM signal on timeout. Once user invokes process method it will start the event loop, which will read the spawn buffer performs a match with the list of statements provided in the Dialog inst, on a match it invokes the action corresponding to the statement which matched. Also in addition, it performs dependency injection by inspecting the signature of action method.

Loop Exit Conditions:

1. Pattern of any statements matched, and its 'loop_continue' flag is
   Disabled
2. SIGALRM raised on timer expiry

Example

dia = Dialog([..])
sp = Spawn('telnet ..')

dp1 = DialogProcessor(dia, sp)
dp1.process()

dp2 = DialogProcessor(dialog=dia,
                      spawn=sp,
                      context={'enable_password':'lab'},
                      timeout=20)
dp2.process()

Note

  1. Dialog instance under process is expected to have at least one exit point

  2. This is a non blocking DialogProcessor, which aborts the event loop whenever SIGALRM is raised, even if action is under processing

  3. This is not thread safe, DialogProcessor should always be invoked on the main thread

Initialize Dialog Processor

Dialog = Dialog to be processed spawn = Handle on which Dialog to be processed context = Device context information timeout = Timeout for this processing

expect_eval_statements(pat_list)

Reads the buffer content and checks for a match in pattern list. If there is pattern match, then executes the corresponding statements callback

This method returns True, if loop_continue of matched statement is False(so that caller can break the event loop)

process()

starts the event loop, performs the actual transaction,

which reads the spawn buffer and tries a pattern match with the list of statement provided in the Dialog On a match this invokes a corresponding action, it also runs a timer, which aborts the loop on timeout

loop Exit Conditions::
  • Pattern of any statements matched, and its ‘loop_continue’ flag is Disabled

  • SIGALRM raised

process_timeout_statement()

Method for processing timeout statement which is part of Dialog. This invokes timeout statement action. Return None, if loop_continue is False. Return True, if loop_continueis True.

reset_alarm_handler()

Reset the timer Restores the bkup_handler and relative time left

timeout_handler(signum, stack)

Method for handling timeout scenarios

class unicon.eal.dialog_processor.BaseDialogProcessor(dialog, spawn, context={}, timeout=None)

Bases: object

Base Dialog Processor

Performs Initialization, Dependency injections and also defines the work flow for dialog processing

Initialize Dialog Processor Dialog = Dialog to be processed spawn = Handle on which Dialog to be processed context = Device context information timeout = Timeout for this processing

perform_di(context)

perform dependency injection for spawn

at this point we only get functions
  1. which have all default and positional arguments resolved through statement.args.

  2. All or few of the default arguments overridden through

    statement.args

  3. Spawn if present, only appears as positional argument.

process(*args, **kwargs)

performs the actual transaction with the device

property session

Returns the session dict of the processor

substitute_hostname(pat_list)

Perform hostname substitution in state patterns

Replaces all %N with the hostname, if hostname is provided

Returns the pattern (whether or not it was modified).

class unicon.eal.dialog_processor.DialogProcessor(*args, **kwargs)

Bases: object

Factory class for DialogProcessor

In threaded environment we can’t use AlarmBasedDialogProcessor, hence because of this unicon simply stops working in threads in case it is using dialogs, which mostly is the case. This factory class serves the appropriate DialogProcessor class based on whether the code is running in thread or not.

class unicon.eal.dialog_processor.ExDialogProcessor(dialog, spawn, context={}, timeout=None)

Bases: unicon.eal.dialog_processor.BaseDialogProcessor

Dialog Processor based on SIGALRM

This Dialog processor creates an event loop which raises an SIGALARM signal on timeout. Once user invokes process method it will start the event loop, which will read the spawn buffer performs a match with the list of statements provided in the Dialog inst, on a match it invokes the action corresponding to the statement which matched. Also in addition, it performs dependency injection by inspecting the signature of action method.

Loop Exit Conditions:

1. Pattern of any statements matched, and its 'loop_continue' flag is
   Disabled
2. SIGALRM raised on timer expiry

Example

dia = Dialog([..])
sp = Spawn('telnet ..')

dp1 = DialogProcessor(dia, sp)
dp1.process()

dp2 = DialogProcessor(dialog=dia,
                      spawn=sp,
                      context={'enable_password':'lab'},
                      timeout=20)
dp2.process()

Note

  1. Dialog instance under process is expected to have at least one exit point

  2. This is a non blocking DialogProcessor, which aborts the event loop whenever SIGALRM is raised, even if action is under processing

  3. This is not thread safe, DialogProcessor should always be invoked on the main thread

Initialize Dialog Processor

Dialog = Dialog to be processed spawn = Handle on which Dialog to be processed context = Device context information timeout = Timeout for this processing

expect_eval_statements(pat_list)

Reads the buffer content and checks for a match in pattern list. If there is pattern match, then executes the corresponding statements callback

This method returns True, if loop_continue of matched statement is False(so that caller can break the event loop)

process(context=None)

starts the event loop, performs the actual transaction,

which reads the spawn buffer and tries a pattern match with the list of statement provided in the Dialog On a match this invokes a corresponding action, it also runs a timer, which aborts the loop on timeout

loop Exit Conditions::
  • Pattern of any statements matched, and its ‘loop_continue’ flag is Disabled

  • SIGALRM raised

reset_alarm_handler()

Reset the timer Restores the bkup_handler and relative time left

timeout_handler(signum, stack)

Method for handling timeout scenarios

class unicon.eal.dialog_processor.ProRecAlarmDialogProcessor(dialog, spawn, context={}, timeout=None, **kwargs)

Bases: unicon.eal.dialog_processor.PromptRecoveryCommon, unicon.eal.dialog_processor.AlarmBasedDialogProcessor

Dialog processor for prompt recovery feature. Sub class of PromptRecoveryCommon and AlarmBasedDialogProcessor. If prompt_recovery is True, prompt_recovery_commands will be sent to the spawn after normal timeout elapse.

prompt_recovery_reset_timer()

Reset the Dialog Timeout timer to prompt_recovery_interval

timeout_handler(signum, stack)

Method for handling timeout scenarios

class unicon.eal.dialog_processor.ProRecSimpleDialogProcessor(dialog, spawn, context={}, timeout=None, **kwargs)

Bases: unicon.eal.dialog_processor.PromptRecoveryCommon, unicon.eal.dialog_processor.SimpleDialogProcessor

Dialog processor for prompt recovery feature. Sub class of SimpleDialogProcessor. If prompt_recovery is True, prompt_recovery_commands will be sent to the spawn after normal timeout elapse.

prompt_recovery_reset_timer()

Reset the Dialog Timeout timer to prompt_recovery_interval

timeout_handler()

Method for handling timeout scenarios

class unicon.eal.dialog_processor.PromptRecoveryCommon(dialog, spawn, context={}, timeout=None, **kwargs)

Bases: object

Common functions which can be use by prompt recovery Alarm and Simple based dialog processor.

initialize_prompt_recovery()

Initialize prompt recovery settings.

prompt_recovery_handler()

Sends prompt recovery commands to spawn.

prompt_recovery_reset_timer()

Reset the timeout timer to prompt recovery interval after sending prompt recovery command.

property prompt_recovery_timeout
timeout_handler()

Method for handling timeout scenarios

class unicon.eal.dialog_processor.SimpleDialogProcessor(dialog, spawn, context={}, timeout=None, **kwargs)

Bases: unicon.eal.dialog_processor.BaseDialogProcessor

Simple Dialog Processor

This Dialog processor creates an event loop which runs an internal timer On invocation of process method, this will read the spawn buffer and performs a match with the list of statements provided in the Dialog inst, on a match it invokes the action corresponding to the statement which matched. Also in addition, it performs dependency injection by inspecting the signature of action method.

Loop Exit Conditions:

1. Pattern of any statements matched, and its 'loop_continue' flag is
   Disabled
2. Internal Timer expired

Example

dia = Dialog([..])
sp = Spawn('telnet ..')

dp1 = SimpleDialogProcessor(dia, sp)
dp1.process()

dp2 = SimpleDialogProcessor(dia, sp, context={'enable_password':'lab'})
dp2.process()

Note

  1. Dialog instance under process is expected to have at least one exit point.

  2. This is a partially blocking DialogProcessor, which waits until

Initialize Dialog Processor Dialog = Dialog to be processed spawn = Handle on which Dialog to be processed context = Device context information timeout = Timeout for this processing

eof_handler()

Handle EOFError using __eof__ statement

expect_eval_statements(pat_list)

Reads the buffer content and checks for a match in pattern list. If there is pattern match, then executes the corresponding statements callback

This method returns True, if loop_continue of matched statement is False(so that caller can break the event loop)

process()

Process a dialog

starts the event loop and performs the actual transaction with the device, which reads the spawn buffer and tries a pattern match with the list of statement provided in the Dialog On a match this invokes a corresponding action, it also runs a timer, which aborts the loop on timeout

Loop Exit Condition:

1. Pattern of any statements matched, and its
   'loop_continue' flag is Disabled
2. TimeoutError raised on timeout.
process_timeout_statement()

Method for processing timeout statement which is part of Dialog. This invokes timeout statement action. Return None, if loop_continue is False. Return True, if loop_continueis True.

timeout_handler()

Method for handling timeout scenarios

unicon.eal.dialogs module

Module:

unicon.eal.dialogs

Description:

Dialog module provides classes and structures for creating several pattern/action pairs, so that multiple interactions can be handled in a single expect transaction. This concept is equivalent of writing nested expect blocks in Tcl/Expect where we have a platform pattern and callback pairs.

Example

d = Dialog([
    [r'Username: ', lambda: spawn: spawn.sendline('admin'), loop_continue=True]
    [r'Password', lambda: spawn: spawn.sendline('lab'), loop_continue=True]
])
class unicon.eal.dialogs.Dialog(statement_list=[])

Bases: object

Dialog is a set of statement objects.

Description:

It is just an enclosure for list of all the statements and all the session dependencies. It’s instance can be reused for interacting with different spawn instances.

Timeout is not the part of dialog instance, that means same dialog can be reused to handle an interaction with different timeouts.

Example

dialog = Dialog([
    Statement(pattern=r"^username:$",
              action=lambda spawn: spawn.sendline("admin"),
              args=None,
              loop_continue=True,
              continue_timer=False ),
    Statement(pattern=r"^password:$",
              action=lambda spawn: spawn.sendline("admin"),
              args=None,
              loop_continue=True,
              continue_timer=False ),
    Statement(pattern=r"^host-prompt#$",
              action=None,
              args=None,
              loop_continue=False,
              continue_timer=False ),
])

It is also possible to construct a dialog instance by supplying list of
statement arguments.

dialog = Dialog([
    [r"^username$", lambda spawn: spawn.sendline("admin"), None, True, False],
    [r"^password:$", lambda spawn: spawn.sendline("admin"), None, True, False],
    [r"^hostname#$", None, None, False, False]
])
append(statement)

append a statement to the end of the dialog instance

extract_statements()

extract statement from the arguments. it ignores any special statement like the timeout statement

get_pattern_list()

get list of patterns from all the statements

insert(index, statement)

insert a statement at a given index

process(*args, **kwargs)

a duck type function easy processing of a dialog.

this method created a dialog processor instance and processes the current dialog.

Example

d.process(s, timeout=30) Here s is the spawn instance.

remove(statement)

remove a statement of the dialog instance

validate()

validate all the statement arguments

class unicon.eal.dialogs.DialogMaker(*args, **kwargs)

Bases: object

add_statement(statement, pos=- 1)
class unicon.eal.dialogs.Statement(pattern, action=None, args=None, loop_continue=False, continue_timer=False, trim_buffer=True, matched_retries=None, matched_retry_sleep=None, di_params=['spawn', 'context', 'session'], debug_statement=False)

Bases: object

Statement is a building block of a dialog.

Description:

Dialogs are nothing but a set of statements. Statement contains five things:

  • pattern: a match is used to invoke the callback.

  • action: a function which is called in case the pattern is matched.

  • args: a dict containing all the arguments required by callback function.

  • loop_continue: When it is true, the dialog doesn’t exit and continues to look for the match.

  • continue_timer: timer is restarted after every match.

  • trim_buffer: When it is False, matched content will not be removed from buffer.

  • matched_retries: retry times if statement pattern is matched, default is 0

  • matched_retry_sleep: sleep between retries, default is 0.02 sec

Example

This is how a statement could be instantiated:

def simple_callback(spawn):
    spawn.sendline("lab")

st = Statement(pattern=r"^.*pat$",
               action=simple_callback,
               loop_continue=False,
               continue_timer=False
              )
Raises

StatementValidationError

validate()

verify the sanity of the arguments in the statement

validate_action()

check callback function and its arguments

validate_continue_timer()

validate continue_timer is boolean

validate_debug_statement()

validate debug_statement is boolean

validate_loop_continue()

validate loop_continue is boolean

validate_pattern()

check if the pattern provided is or correct type

validate_trim_buffer()

validate trim_buffer is boolean

unicon.eal.dialogs.statement_action_helper(action)

Helper fuction for statement actions.

Translates action string into a callable and argument.

Parameters

action (str) – action string from statement

Returns

callable, payload (tuple)

unicon.eal.dialogs.statement_decorator(*pargs, **pkwargs)

Decorator to add to create Action Dialog

unicon.eal.expect module

unicon.eal.helpers module

shorthand helper dialogs

unicon.eal.helpers.sendline(spawn, command='')

unicon.eal.utils module

class unicon.eal.utils.ExpectMatch

Bases: object

This class stores the Matched content details Also stores the last match index and regexp object

class unicon.eal.utils.MatchMode(mode_id, mode_name)

Bases: object

class unicon.eal.utils.PicklableSreMatch(sre_match)

Bases: object

group(idx=0)
groupdict()
groups()
class unicon.eal.utils.Timer(duration)

Bases: object

expired()
has_time_left()
reset()
start()
unicon.eal.utils.expect_log(*args, **kwargs)

This function is removed, please use ‘debug=True’ or set device logger Level to get the internl debug logging

Eg:

device.connect(‘debug=True’) device.log.setLevel(10)

Or you can pass from testbed yaml file:
connections:
defaults:

class: unicon.Unicon debug: True

unicon.eal.utils.timeout_occurrence(**kwargs)

Signal for timeout

Module contents

Package:

eal

Description:

Expect Abstraction Library (EAL) is a package which provides Tcl/Expect like API, using paramiko library as a backend. Paramiko is an open source python library for handling ssh connections. EAL uses paramiko’s invoke_shell api to create an interactive shell session on the connected channel. Channel here, is a socket like object.

EAL creates a shell session on the connected channel and uses stdin and stdout for interacting with it. It abstracts all the paramiko level configurations and exposes Expect like API’s e.g send, expect, dialogs etc.

The whole unicon uses EAL as backend for implementing APIs for device connection. In unicon framework, EAL is the lower most level of of abstraction for device interactions.