API reference

Client API

Contains Batfish client commands that query the Batfish service.

pybatfish.client.commands.bf_add_issue_config(issue_config)[source]

Add or update the active network’s configuration for an issue .

Parameters:issue_config (pybatfish.settings.issues.IssueConfig) – The IssueConfig object to add or update
pybatfish.client.commands.bf_auto_complete(completion_type, query, max_suggestions=None)[source]

Get a list of autocomplete suggestions that match the provided query based on the variable type.

If completion is not supported for the provided variable type a BatfishException will be raised.

Usage Example:

>>> from pybatfish.client.commands import bf_auto_complete, bf_set_network
>>> from pybatfish.datamodel.primitives import AutoCompleteSuggestion, VariableType
>>> name = bf_set_network()
>>> bf_auto_complete(VariableType.ROUTING_PROTOCOL_SPEC, "b") 
[AutoCompleteSuggestion(description=None, insertion_index=0, is_partial=False, rank=2147483647, text='bgp'),
    AutoCompleteSuggestion(description=None, insertion_index=0, is_partial=False, rank=2147483647, text='ebgp'),
    AutoCompleteSuggestion(description=None, insertion_index=0, is_partial=False, rank=2147483647, text='ibgp')]
Parameters:
  • completion_type (VariableType) – The type of parameter to suggest autocompletions for
  • query (str) – The partial string to match suggestions on
  • max_suggestions (int) – Optional max number of suggestions to be returned
pybatfish.client.commands.bf_delete_issue_config(major, minor)[source]

Deletes the issue config for the active network.

pybatfish.client.commands.bf_delete_network(name)[source]

Delete network by name.

Parameters:name (string) – name of the network to delete
pybatfish.client.commands.bf_delete_node_role_dimension(dimension)[source]

Deletes the definition of the given role dimension for the active network.

pybatfish.client.commands.bf_delete_reference_book(book_name)[source]

Deletes the reference book with the specified name for the active network.

pybatfish.client.commands.bf_delete_snapshot(name)[source]

Delete named snapshot from current network.

Parameters:name (string) – name of the snapshot to delete
pybatfish.client.commands.bf_extract_answer_summary(answer_dict)[source]

Get the answer for a previously asked question.

pybatfish.client.commands.bf_fork_snapshot(base_name, name=None, overwrite=False, background=False, deactivate_interfaces=None, deactivate_nodes=None, restore_interfaces=None, restore_nodes=None, add_files=None, extra_args=None)[source]

Copy an existing snapshot and deactivate or reactivate specified interfaces, nodes, and links on the copy.

Parameters:
  • base_name (string) – name of the snapshot to copy
  • name (string) – name of the snapshot to initialize
  • overwrite (bool) – whether or not to overwrite an existing snapshot with the same name
  • background (bool) – whether or not to run the task in the background
  • deactivate_interfaces (list[Interface]) – list of interfaces to deactivate in new snapshot
  • deactivate_nodes (list[str]) – list of names of nodes to deactivate in new snapshot
  • restore_interfaces (list[Interface]) – list of interfaces to reactivate
  • restore_nodes (list[str]) – list of names of nodes to reactivate
  • add_files (str) – path to zip file or directory containing files to add
  • extra_args (dict) – extra arguments to be passed to the parse command.
Returns:

name of initialized snapshot, JSON dictionary of task status if background=True, or None if the call fails

Return type:

Union[str, Dict, None]

pybatfish.client.commands.bf_generate_dataplane(snapshot=None, extra_args=None)[source]

Generates the data plane for the supplied snapshot. If no snapshot argument is given, uses the last snapshot initialized.

pybatfish.client.commands.bf_get_analysis_answers(name, snapshot=None, reference_snapshot=None)[source]

Get the answers for a previously asked analysis.

pybatfish.client.commands.bf_get_answer(questionName, snapshot, reference_snapshot=None)[source]

Get the answer for a previously asked question.

Parameters:
  • questionName – the unique identifier of the previously asked question
  • snapshot – the snapshot the question is run on
  • reference_snapshot – if present, the snapshot against which the answer was computed differentially.
pybatfish.client.commands.bf_get_issue_config(major, minor)[source]

Returns the issue config for the active network.

pybatfish.client.commands.bf_get_node_role_dimension(dimension)[source]

Returns the definition of the given node role dimension for the active network.

pybatfish.client.commands.bf_get_node_roles()[source]

Returns the definitions of node roles for the active network.

pybatfish.client.commands.bf_get_reference_book(book_name)[source]

Returns the reference book with the specified for the active network.

pybatfish.client.commands.bf_get_reference_library()[source]

Returns the reference library for the active network.

pybatfish.client.commands.bf_get_snapshot_inferred_node_role_dimension(dimension)[source]

Gets the suggested definition and hypothetical assignments of node roles for the given inferred dimension for the active network and snapshot.

pybatfish.client.commands.bf_get_snapshot_inferred_node_roles()[source]

Gets suggested definitions and hypothetical assignments of node roles for the active network and snapshot.

pybatfish.client.commands.bf_get_snapshot_node_role_dimension(dimension)[source]

Returns the defintion and assignments of node roles for the given dimension for the active network and snapshot.

pybatfish.client.commands.bf_get_snapshot_node_roles()[source]

Returns the definitions and assignments of node roles for the active network and snapshot.

pybatfish.client.commands.bf_init_snapshot(upload, name=None, overwrite=False, background=False, extra_args=None)[source]

Initialize a new snapshot.

Parameters:
  • upload (zip file or directory) – snapshot to upload
  • name (string) – name of the snapshot to initialize
  • overwrite (bool) – whether or not to overwrite an existing snapshot with the same name
  • background (bool) – whether or not to run the task in the background
  • extra_args (dict) – extra arguments to be passed to the parse command.
Returns:

name of initialized snapshot, or JSON dictionary of task status if background=True

Return type:

Union[str, Dict]

pybatfish.client.commands.bf_list_networks()[source]

List networks the session’s API key can access.

Returns:a list of network names
pybatfish.client.commands.bf_list_snapshots(verbose=False)[source]

List snapshots for the current network.

Parameters:verbose – If true, return the full output of Batfish, including snapshot metadata.
Returns:a list of snapshot names or the full json response containing snapshots and metadata (if verbose=True)
pybatfish.client.commands.bf_put_node_role_dimension(dimension)[source]

Put a role dimension in the active network.

Overwrites the old dimension if one of the same name already exists.

Individual roles within the dimension must have a valid (java) regex. The node list within those roles, if present, is ignored by the server.

Parameters:dimension (pybatfish.datamodel.referencelibrary.NodeRoleDimension) – The NodeRoleDimension object for the dimension to add
pybatfish.client.commands.bf_put_node_roles(node_roles_data)[source]

Writes the definitions of node roles for the active network. Completely replaces any existing definitions.

pybatfish.client.commands.bf_read_question_settings(question_class, json_path=None)[source]

Retrieves the network-wide JSON settings tree for the specified question class.

Parameters:
  • question_class (string) – The class of question whose settings are to be read
  • json_path (list) – If supplied, return only the subtree reached by successively traversing each key in json_path starting from the root.
pybatfish.client.commands.bf_put_reference_book(book)[source]

Put a reference book in the active network.

If a book with the same name exists, it is overwritten.

Parameters:book (pybatfish.datamodel.referencelibrary.ReferenceBook) – The ReferenceBook object to add
pybatfish.client.commands.bf_set_network(name=None, prefix='pcp')[source]

Configure the network used for analysis.

Parameters:
  • name (string) – name of the network to set. If None, a name will be generated using prefix.
  • prefix – prefix to prepend to auto-generated network names if name is empty
Returns:

The name of the configured network, if configured successfully.

Return type:

string

Raises:

BatfishException – if configuration fails

pybatfish.client.commands.bf_set_snapshot(name=None, index=None)[source]

Set the current snapshot by name or index.

Parameters:
  • name (string) – name of the snapshot to set as the current snapshot
  • index (int) – set the current snapshot to the index-th most recent snapshot
Returns:

the name of the successfully set snapshot

Return type:

str

pybatfish.client.commands.bf_upload_diagnostics(dry_run=True, netconan_config=None, contact_info=None)[source]

Fetch, anonymize, and optionally upload snapshot diagnostics information.

This runs a series of diagnostic questions on the current snapshot (including collecting parsing and conversion information).

The information collected is anonymized with Netconan which either anonymizes passwords and IP addresses (default) or uses the settings in the provided netconan_config.

The anonymous information is then either saved locally (if dry_run is True) or uploaded to Batfish developers (if dry_run is False). The uploaded information will be accessible only to Batfish developers and will be used to help diagnose any issues you encounter.

If contact_info is supplied (e.g. email address), Batfish developers may contact you if they have follow-up questions or to update you when the issues you encountered are resolved.

Parameters:
  • dry_run (bool) – if True, upload is skipped and the anonymized files will be stored locally for review. If False, anonymized files will be uploaded to the Batfish developers
  • netconan_config (string) – path to Netconan configuration file
  • contact_info (str) – optional contact info associated with this upload
Returns:

location of anonymized files (local directory if doing dry run, otherwise upload ID)

Return type:

string

pybatfish.client.commands.bf_write_question_settings(settings, question_class, json_path=None)[source]

Write the network-wide JSON settings tree for the specified question class.

Parameters:
  • settings (dict) – The JSON representation of the settings to be written
  • question_class (string) – The class of question to configure
  • json_path (list) – If supplied, write settings to the subtree reached by successively traversing each key in json_path starting from the root. Any absent keys along the path will be created.

Session parameters

class pybatfish.client.session.Session(host='localhost', port_v1=9997, port_v2=9996, ssl=False, verify_ssl_certs=True, load_questions=True)[source]

Keeps session configuration needed to connect to a Batfish server.

Variables:
  • host – The host of the batfish service
  • port_v1 – The port batfish service is running on (9997 by default)
  • port_v2 – The additional port of batfish service (9996 by default)
  • ssl – Whether to use SSL when connecting to Batfish (False by default)
  • api_key – Your API key
delete_network(name)[source]

Delete network by name.

Parameters:name (str) – name of the network to delete
delete_node_role_dimension(dimension)[source]

Deletes the definition of the given role dimension for the active network.

Parameters:dimension (str) – name of the dimension to delete
delete_reference_book(name)[source]

Deletes the reference book with the specified name for the active network.

Parameters:name (str) – name of the reference book to delete
delete_snapshot(name)[source]

Delete specified snapshot from current network.

Parameters:name (str) – name of the snapshot to delete
extract_facts(nodes='/.*/', output_directory=None)[source]

Extract and return a dictionary of facts about the specified nodes on the current network snapshot.

If an output directory is specified, facts for each node will be written to a separate YAML file in that directory.

Parameters:
  • nodes (Text) – NodeSpecifier, specifying which nodes to extract facts for.
  • output_directory (Text) – path to directory to write facts to
Returns:

facts about the specified nodes on the current network snapshot

Return type:

dict

fork_snapshot(base_name, name=None, overwrite=False, deactivate_interfaces=None, deactivate_nodes=None, restore_interfaces=None, restore_nodes=None, add_files=None, extra_args=None)[source]

Copy an existing snapshot and deactivate or reactivate specified interfaces, nodes, and links on the copy.

Parameters:
  • base_name (str) – name of the snapshot to copy
  • name (str) – name of the snapshot to initialize
  • overwrite (bool) – whether or not to overwrite an existing snapshot with the same name
  • deactivate_interfaces (list[Interface]) – list of interfaces to deactivate in new snapshot
  • deactivate_nodes (list[str]) – list of names of nodes to deactivate in new snapshot
  • restore_interfaces (list[Interface]) – list of interfaces to reactivate
  • restore_nodes (list[str]) – list of names of nodes to reactivate
  • add_files (str) – path to zip file or directory containing files to add
  • extra_args (dict) – extra arguments to be passed to the parse command.
Returns:

name of initialized snapshot or None if the call fails

Return type:

Optional[str]

generate_dataplane(snapshot=None, extra_args=None)[source]

Generates the data plane for the supplied snapshot. If no snapshot is specified, uses the last snapshot initialized.

Parameters:
  • snapshot (str) – name of the snapshot to generate dataplane for
  • extra_args (dict) – extra arguments to be passed to Batfish
classmethod get(type_='bf', **params)[source]

Instantiate and return a Session object of the specified type with the specified params.

get_answer(question, snapshot, reference_snapshot=None)[source]

Get the answer for a previously asked question.

Parameters:
  • question (str) – the unique identifier of the previously asked question
  • snapshot (str) – name of the snapshot the question was run on
  • reference_snapshot (str) – if present, gets the answer for a differential question asked against the specified reference snapshot
Returns:

answer to the specified question

Return type:

Answer

get_base_url()[source]

Generate the base URL for connecting to Batfish coordinator.

get_base_url2()[source]

Generate the base URL for V2 of the coordinator APIs.

get_component_versions()[source]

Get a dictionary of backend components (e.g. Batfish, Z3) and their versions.

get_info()[source]

Get basic info about the Batfish service (including name, version, …).

get_node_role_dimension(dimension, inferred=False)[source]

Returns the definition of the given node role dimension for the active network or inferred definition for the active snapshot.

Parameters:
  • dimension (str) – name of the node role dimension to fetch
  • inferred (bool) – whether or not to fetch active snapshot’s inferred node role dimension
Returns:

the definition of the given node role dimension for the active network, or inferred definition for the active snapshot if inferred=True.

Return type:

NodeRoleDimension

get_node_roles(inferred=False)[source]

Returns the definitions of node roles for the active network or inferred roles for the active snapshot.

Parameters:inferred (bool) – whether or not to fetch the active snapshot’s inferred node roles
Returns:the definitions of node roles for the active network, or inferred definitions for the active snapshot if inferred=True.
Return type:NodeRolesData
get_reference_book(name)[source]

Returns the specified reference book for the active network.

Parameters:name (str) – name of the reference book to fetch
get_reference_library()[source]

Returns the reference library for the active network.

classmethod get_session_types()[source]

Get a dict of possible session types mapping their names to session classes.

get_snapshot(snapshot=None)[source]

Get the specified or active snapshot name.

Parameters:snapshot (str or Text) – if specified, this name is returned instead of active snapshot
Returns:name of the active snapshot, or the specified snapshot if applicable
Return type:str
Raises:ValueError – if there is no active snapshot and no snapshot was specified
get_url(resource)[source]

Get URL for the specified resource.

Parameters:resource (str) – URI of the requested resource
get_work_status(work_item)[source]

Get the status for the specified work item.

init_snapshot(upload, name=None, overwrite=False, extra_args=None)[source]

Initialize a new snapshot.

Parameters:
  • upload (str) – path to the snapshot zip or directory
  • name (str) – name of the snapshot to initialize
  • overwrite (bool) – whether or not to overwrite an existing snapshot with the same name
  • extra_args (dict) – extra arguments to be passed to the parse command
Returns:

name of initialized snapshot

Return type:

str

init_snapshot_from_text(text, filename=None, snapshot_name=None, platform=None, overwrite=False, extra_args=None)[source]

Initialize a snapshot of a single configuration file with given text.

When platform=None the file contains the given text, unmodified. This means that the file text must indicate the platform of the vendor to Batfish, which is usually learned from headers that devices add in “show run”:

boot nxos bootflash:nxos.7.0.3.I4.7.bin   (Cisco NX-OS)
! boot system flash:/vEOS-lab.swi         (Arista EOS)
#TMSH-VERSION: 1.0                        (F5 Big-IP)
!! IOS XR Configuration 5.2.4             (Cisco IOS XR)

Alternately, you may supply the name of the platform in the platform argument.

As usual, the hostname of the node will be parsed from the configuration text itself, and if not present Batfish will default to the provided filename.

Parameters:
  • text (str) – the contents of the file.
  • filename (str) – name of the configuration file created, ‘config’ by default.
  • snapshot_name (str) – name of the snapshot to initialize
  • platform (str) – the RANCID router.db name for the device platform, i.e., “cisco-nx”, “arista”, “f5”, or “cisco-xr” for above examples. See https://www.shrubbery.net/rancid/man/router.db.5.html
  • overwrite (bool) – whether or not to overwrite an existing snapshot with the same name.
  • extra_args (dict) – extra arguments to be passed to the parse command
Returns:

name of initialized snapshot

Return type:

str

list_incomplete_works()[source]

Get pending work that is incomplete.

Returns:JSON dictionary of question name to question object
Return type:dict
list_networks()[source]

List networks the session’s API key can access.

Returns:network names
Return type:list
list_snapshots(verbose=False)[source]

List snapshots for the current network.

Parameters:verbose (bool) – If true, return the full output of Batfish, including snapshot metadata.
Returns:snapshot names or the full JSON response containing snapshots and metadata (if verbose=True)
Return type:list
put_node_role_dimension(dimension)[source]

Put a role dimension in the active network.

Overwrites the old dimension if one of the same name already exists.

Individual roles within the dimension must have a valid (java) regex. The node list within those roles, if present, is ignored by the server.

Parameters:dimension (NodeRoleDimension) – The NodeRoleDimension object for the dimension to add
put_node_roles(node_roles_data)[source]

Writes the definitions of node roles for the active network. Completely replaces any existing definitions.

Parameters:node_roles_data (NodeRolesData) – node roles definitions to add to the active network
put_reference_book(book)[source]

Put a reference book in the active network.

If a book with the same name exists, it is overwritten.

Parameters:book (ReferenceBook) – The ReferenceBook object to add
set_network(name=None, prefix='pcp')[source]

Configure the network used for analysis.

Parameters:
  • name (str) – name of the network to set. If None, a name will be generated
  • prefix – prefix to prepend to auto-generated network names if name is empty
Returns:

name of the configured network

Return type:

str

Raises:

BatfishException – if configuration fails

set_snapshot(name=None, index=None)[source]

Set the current snapshot by name or index.

Parameters:
  • name (str) – name of the snapshot to set as the current snapshot
  • index (int) – set the current snapshot to the index-th most recent snapshot
Returns:

the name of the successfully set snapshot

Return type:

str

upload_diagnostics(dry_run=True, netconan_config=None, contact_info=None)[source]

Fetch, anonymize, and optionally upload snapshot diagnostics information.

This runs a series of diagnostic questions on the current snapshot (including collecting parsing and conversion information).

The information collected is anonymized with Netconan which either anonymizes passwords and IP addresses (default) or uses the settings in the provided netconan_config.

The anonymous information is then either saved locally (if dry_run is True) or uploaded to Batfish developers (if dry_run is False). The uploaded information will be accessible only to Batfish developers and will be used to help diagnose any issues you encounter.

If contact_info is supplied (e.g. email address), Batfish developers may contact you if they have follow-up questions or to update you when the issues you encountered are resolved.

Parameters:
  • dry_run (bool) – if True, upload is skipped and the anonymized files will be stored locally for review. If False, anonymized files will be uploaded to the Batfish developers
  • netconan_config (str) – path to Netconan configuration file
  • contact_info (str) – optional contact info associated with this upload
Returns:

location of anonymized files (local directory if doing dry run, otherwise upload ID)

Return type:

str

validate_facts(expected_facts)[source]

Return a dictionary of mismatched facts between the loaded expected facts and the actual facts.

Parameters:expected_facts (Text) – path to directory to read expected fact YAML files from
Returns:facts about the specified nodes on the current network snapshot
Return type:dict

Question API

class pybatfish.question.question.QuestionBase(dictionary, session)[source]

All questions inherit functionality from this class.

answer(snapshot=None, reference_snapshot=None, include_one_table_keys=None, background=False, extra_args=None)[source]

Ask and return the answer for this question.

Parameters:
  • snapshot (str) – the snapshot on which to answer the question. If not provided, the latest snapshot initialized will be used.
  • reference_snapshot (str) – for differential questions only, the snapshot against which to compare.
  • include_one_table_keys (bool) – if differential is True, include keys only from one table and not both.
  • background (bool) – run this question in background, return immediately
  • extra_args (dict) – extra arguments to be passed with the question.
Return type:

Answer or TableAnswer

Raises:

QuestionValidationException – if the question is malformed

dict()[source]

Return the dictionary representing this question.

get_description()[source]

Return the short description of this question.

get_differential()[source]

Return whether this question is to be asked differentially.

get_include_one_table_keys()[source]

Return whether keys present in only one table should be included when computing answer table diffs.

get_long_description()[source]

Return the long description of this question.

get_name()[source]

Return the name of this question.

json(**kwargs)[source]

Return the json string representing this question.

Keyword arguments passed to json.dumps with default assignments of sort_keys=True and indent=2

make_check()[source]

Make this question a check which asserts that there are no results.

set_assertion(assertion)[source]

Set an assertion for a given question.

Overwrites any previous assertions.

Defines Batfish questions and logic for loading them from disk or Batfish.

pybatfish.question.question.list_questions(tags=None, question_module='pybatfish.question.bfq')[source]

List available questions.

Parameters:
  • tags – if not None, only list questions with given tags. See list_tags() for a list of tags given currently loaded questions.
  • question_module – which module to load the questions from. By default, pybatfish.question.bfq is used.
Returns:

a list of questions, where each question is represented as a dict containing “name”, “description”, and “tags”.

pybatfish.question.question.list_tags()[source]

List tags across all available questions.

pybatfish.question.question.load_dir_questions(questionDir, session, moduleName='pybatfish.question.bfq')[source]

Load question templates from a directory on disk and install them in the given module.

pybatfish.question.question.load_questions(question_dir=None, from_server=False, module_name='pybatfish.question.bfq', session=None)[source]

Load questions from directory or batfish service.

Parameters:
  • question_dir (str) – Load questions from this local directory instead of remote questions from the batfish service.
  • from_server (bool) – if true or question_dir is None, load questions from service.
  • module_name – the name of the module where questions should be loaded. Default is pybatfish.question.bfq
  • session (Session) – Batfish session to load questions from