0% found this document useful (0 votes)
10 views

09_Cisco IOS XR Programmability - Student Learning Guide v5.0 - DOCX-DP

The document discusses Cisco IOS XR's programmability features, emphasizing the use of data models for automating network device configuration and operational data collection. It highlights the limitations of traditional CLI methods and introduces NETCONF and YANG as modern solutions for efficient network management. The document also outlines the capabilities of YANG and NETCONF, comparing them to previous approaches and detailing the structure and usage of YANG data models.

Uploaded by

Dúber Pérez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

09_Cisco IOS XR Programmability - Student Learning Guide v5.0 - DOCX-DP

The document discusses Cisco IOS XR's programmability features, emphasizing the use of data models for automating network device configuration and operational data collection. It highlights the limitations of traditional CLI methods and introduces NETCONF and YANG as modern solutions for efficient network management. The document also outlines the capabilities of YANG and NETCONF, comparing them to previous approaches and detailing the structure and usage of YANG data models.

Uploaded by

Dúber Pérez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Course 9: Cisco IOS XR Programmability

Introduction
Typically, a network operation center is a heterogeneous mix of various devices at multiple layers of the
network. Such network centers require bulk automated configurations to be accomplished seamlessly. CLIs
are widely used for configuring and extracting the operational details of a router. But the general
mechanism of CLI scraping is not flexible and optimal. Small changes in the configuration require rewriting
scripts multiple times. Bulk configuration changes through CLIs are cumbersome and error-prone. These
limitations restrict automation and scale. To overcome these limitations, you need an automated mechanism
to manage your network.
Cisco IOS XR supports a programmatic way of configuring and collecting operational data of a network
device using data models. They replace the process of manual configuration, which is proprietary, and
highly text-based. The data models are written in an industry-defined language and are used to automate the
configuration task and retrieve operational data across heterogeneous devices in a network. Although
configurations using CLIs are easier and human-readable, automating the configuration using model-driven
programmability results in scalability.
Model-driven programmability provides a simple, flexible, and rich framework for device programmability.
This programmability framework provides multiple choices to interface with an IOS XR device in terms of
transport, protocol, and encoding. These choices are decoupled from the models for greater flexibility.

Model-Driven Programmability Basics


Network management challenges include complex and mixed environments with various management
interfaces and capabilities. This topic describes how Cisco IOS XR supports a programmatic way of
configuring and collecting operational data of a network device.
The Cisco IOS XR 64-bit software supports a programmatic way of writing configurations for any network
device by using data models.
You can use data models to:
• Programmatically configure a network device.
• Programmatically collect operation data of a network device.
• Provide a common model for configuration and operational state data.
• Automate configuration and operation of multiple routers across a network.

Data models help to manipulate configuration data and retrieve operational data. The data models replace
the process of manual configuration and are written in an industry-defined language. Although
configurations using CLIs are easier and are humanly readable, automating the configuration by using data
models results in scalability. Data models provide a well-defined hierarchy of the configurational and
operational data of a router. This common framework helps you to program and manage a network with
ease.
Data models handle the following types of data on routers:
• Configuration data: A set of writable data that is required for transforming a system from an initial
default state into its current state. A few examples are configuring entries of the IP routing tables,
configuring the interface MTU to use a specific value, and configuring an Ethernet interface to run at a
given speed.
• Operational state data: A set of data that is obtained by the system at run time and influences the
behavior of the system like that of configuration data. However, in contrast to configuration data,
operational state data is transient. The data is modified by interactions with internal components or
other systems, using specialized protocols. Two examples are entries obtained from routing protocols
such as Open Shortest Path First (OSPF), and attributes of the network interfaces.

Next-Generation Configuration Management


If you sum up the way that devices have been managed for 25 years, you can see that there has been no
good way to handle machine-to-machine communication with the network. Expect scripting and custom
parsers were the best that the industry had to offer. They are now unacceptable as the rate of change
continues to increase, the number of devices increases and demands placed on the network are higher.
Next-generation configuration management, in general, must provide the following:
• Easier-to-use management interfaces.
• Support for client-side validation and error checking.
• Structured data.
• Decoupling of protocols.
• Built-in backup/restore capability.
• Should be both human and machine friendly.

Newer application programming interfaces (APIs) require clear and well-defined ways to interact with
them. They should also be able to use custom and open-source tooling to easily consume the APIs.
APIs should support the ability to offer client-side validation. When you use a next-generation approach that
is purely model-driven, it becomes a great by-product. Rather than have the device do error checking, the
management applications that use the device's API and model automatically handle it.
Data needs to be structured such that it is easy to access and modify in a standard way.
Users should have the flexibility to pick and choose from preferred management, transport, and encoding
protocols.
Next-generation APIs should support the ability of multiple types of configurations, making it simpler to
perform backups and restores, but also to improve how changes are made. As a result, changes should have
the ability to be staged and applied as a transaction.
As next-generation programmatic interfaces are being built, there are a few key attributes that must be met:
• They must support various types of transport: HTTP, SSH, and TLS.
• They must be flexible and support various types of encoding formats, such as XML and JSON.
• There must be efficient and easy-to-use tooling that helps consume the new APIs—for example
programming libraries.
• There must be extensible and open APIs: REST, RESTCONF, Network Configuration Protocol
(NETCONF), and Google-defined remote procedure call (gRPC).

Also, they must be model-driven. Being model-driven is what helps any transport, API, encoding, and data
format.

Cisco IOS XR NETCONF and YANG


You can use the YANG data modeling language to model a configuration and state data that NETCONF
manipulates. You can also use it to model NETCONF procedure calls and notifications. Use YANG to
model the NETCONF operations and content layers.
The figure below illustrates how YANG sits on top of NETCONF to translate a more device-oriented
language (NETCONF) to a more human-readable language (YANG). While NETCONF provides a
standardized way of communicating with different types of devices, YANG provides a framework for
describing configurations by using syntax and semantics that are closer to human languages.

Note NETCONF is not the only protocol. Network Services Orchestrator (NSO) also uses Network Element
Drivers (NEDs) to support other protocols.
The IETF defines the YANG data modeling language in RFC 6020 and augments it with several other
RFCs:
• RFC-7317 YANG for System Management
• RFC-7277 YANG for IP Management
• RFC-7224 IANA Intf. Type YANG Module
• RFC-7223 YANG for Intf. Management
• RFC-6991 Common YANG Data Types
• RFC-6536 NETCONF Access Control
• RFC-6470 NETCONF Base Notifications
• RFC-6244 Architecture for Network Management Using NETCONF and YANG
• RFC-6087 Guidelines for YANG Authors
• RFC-6022 YANG for NETCONF Monitoring

NETCONF Capabilities
NETCONF has many capabilities, some of which perform granular services.
The following are the NETCONF capabilities:
• The distinction between configuration and state data.
• Multiple configuration data stores (candidate, running, startup).
• Configuration change transactions.
• Configuration testing and validation support.
• Selective data retrieval with filtering.
• Streaming and playback of event notifications.
• Extensible procedure call mechanism.

NETCONF versus Other Approaches


Before NETCONF, CLI scripting was the primary approach to automating configuration changes to the
network. CLI scripting limitations include the lack of transaction management, no structured error
management, and the ever-changing structure and syntax of commands that make scripts fragile and costly
to maintain. These side effects to programmatic access emerge because CLIs are designed for use by
humans and not by APIs.
You could use Simple Network Management Protocol (SNMP) as another approach to writing changes,
although in practice it is mostly used to improve performance and monitor applications. It lacks a defined
discovery process, which makes it hard to find the correct MIB modules, includes limitations that are
inherent in the UDP protocol, and lacks useful standard security and commit mechanisms.
The NETCONF protocol addresses the shortcomings of existing practices and protocols for configuration
management. The background work preceding the design phase is documented in RFC 3535 Overview of
the 2002 IAB Network Management Workshop.
Note The device configuration data, and the protocol itself, are encoded with the XML.

YANG Capabilities
The YANG service model has many capabilities.
These are the YANG capabilities:
• Human readable, easy-to-learn representation.
• Hierarchical configuration data models.
• Reusable types and groupings (structured types).
• Extensibility through augmentation mechanisms.
• Supports the definition of operations (RPCs).
• Formal constraints for configuration validation.
• Data modularity through modules and submodules.
• Versioning rules and development support.

YANG versus Other Modeling Languages


The rapid industry adoption of NETCONF made it a priority to define a data-modeling language to
complement NETCONF. Modeling languages such as Structure of Management Information (SMI), an
SNMP feature, Unified Modeling Language (UML), XML Schema, and others existed. However, none of
these languages were targeted specifically to configuration management requirements. They lack critical
capabilities, such as being easily read and understood by human implementers, and fall short in providing
mechanisms to validate models of configuration data for semantics and syntax.
The key YANG capabilities include the following:
• Human readable, easy-to-learn representation makes it easier for operators and engineers to understand.
• Hierarchical configuration data models give the required structure.
• Reusable types and groupings (structured types) make data modeling more consistent and easier to
deploy or redeploy.
• Extensibility through augmentation mechanisms.
• Supports the definition of operations through remote-procedure calls (RPCs).
• Formal constraints for configuration validation ensure validation of every step.
• Data modularity through modules and submodules gives stability when adding or removing modules.
• Versioning rules and development support.

Note YANG defines the data structure and formal constraints for validating device configuration data (XML).
Data Models
The data models characteristics are as follows:
• Describe a constrained set of data in the form of a schema language.
• Use well-defined parameters to standardize the representation of data.
• Are not used to send information to devices.
• Device configuration can be validated against a data model.
• It can define attributes and answers to such questions as the following:
– What is the range of a valid VLAN ID?
– Can a VLAN name contain spaces?
– Should the values be enumerated and support only “up” or “down” for an admin state?
– Should the value be a string or an integer?

Open models were not used to be augmented by a vendor. Instead, vendors have their native models.
Augmentation is used for building a hierarchical view where subtrees are defined in other models.
YANG data models can be of two main classes, open or native.
The figure shows data models for different protocols.

YANG Data Model


The YANG data model characteristics are as follows:
• The data modeling language is defined in RFC 6020.
• Model configuration and operational data.
• Provides semantics to better define data.
• Extensible and modular.
• Protocol independent.
• You can translate it into equivalent XML or JSON.

YANG data models can be represented in a hierarchical, tree-based structure with nodes. This
representation makes the models easy to understand.
Each feature has a defined YANG model, which is synthesized from schemas.
A model in a tree format includes:
• Top-level nodes and their subtrees
• Subtrees that augment nodes in other YANG models
• Custom RPCs

YANG defines four node types. Each node has a name. Depending on the node type, the node either defines
a value or contains a set of child nodes.
The node types for data modeling are:
• Leaf node: Contains a single value of a specific type.
• Leaf-list node: This contains a sequence of leaf nodes.
• List node: A node that may exist multiple times in a data tree. A list has no value, but rather a set of
child nodes.
• Container node: Contains a grouping of related nodes that have only child nodes, which can be any of
the four-node types.

The following are the YANG data models:


• Industry-standard
• Cisco common
• Cisco platform-specific

The publicly available YANG data model information is located on these websites:
• https://github.com/YangModels/yang
• https://github.com/openconfig/public

The main differences between native and open data models include the following:
• Native data models provide the most configuration and operation coverage.
• Open models map to native data models.
• Departures from open models are specified as a deviation module.

A growing number of major vendors (such as Cisco and many others) already support NETCONF and
YANG to some degree, and the support is growing as the service providers increasingly make NETCONF
and YANG a requirement in their projects.

The module is the base unit of definition in YANG. A module defines a single data model. A module can
define a complete, cohesive model, or augment an existing data model with additional nodes. Submodules
are partial modules that contribute definitions to a module. A module can include any number of
submodules, but each submodule can belong to only one module. The names of all standard modules and
submodules must be unique. It is recommended that developers of enterprise modules choose names for
their modules that will have a low probability of colliding with standard or other enterprise modules—for
example, by using the enterprise or organization name as a prefix for the module name.
YANG models the hierarchical organization of data as a tree in which each node has a name and a value or
a set of child nodes.

YANG Modules
Each module should have the following sections:
• Module name that should be the same as the module’s filename (case-sensitive equality between
module name and filename prevents a warning message when you validate a module).
• Header information describes the module and gives information about the module itself:
– Namespace (mandatory): Defines the Uniform Resource Identifier (URI) of the XML namespace.
– Prefix (mandatory): The prefix statement defines the prefix associated with the module and its
namespace. The prefix statement’s argument is the prefix string that you use as a prefix to access a
module.
– Organization, contact (optional): Describes the module origin (such as a company, or author).
– Description (optional): Describes the module (what it is, what it does, and so on).
• Revision information: Provides versioning of the module and facilitates the importing of modules
based on revisions.
• Imports and includes: The import and include statements make definitions available to other modules
and submodules.
• Type definitions: In addition to built-in data types, you can define custom types and use them later in
the data models.
• Reusable node declarations: In addition to type definitions, you can define and reuse a more complex
set of YANG codes.
• Configuration and operational data declarations: The main part of the module, where you define the
actual data model.
• Action (RPC) and notification declarations: Defines NETCONF RPCs and notifications to use within
the module.

YANG Imports and Includes


A module uses the “include” statement to include its submodules, and the “import” statement to reference
external modules. Similarly, a submodule uses the “import” statement to reference other modules and uses
the “include” statement to reference other submodules within its module. A module or submodule must not
include submodules from other modules, and a submodule must not import its module.
Use the import and include statements to make definitions available to other modules and submodules:
• For a module or submodule to reference definitions in an external module, you must import the external
module.
• For a module to reference definitions in one of its submodules, the module must include the submodule.
• For a submodule to reference definitions in a second submodule of the same module, the first
submodule must include the second submodule.

There must not be any circular chains of imports or includes. For example, if submodule “a” includes
submodule “b,” “b” cannot include “a.” When you reference a definition in an external module, you must
use a locally defined prefix, followed by “:” and the external identifier. References to definitions in the local
module can use the prefix notation. Because built-in data types do not belong to any module and have no
prefix, references to built-in data types (for example, int32) cannot use the prefix notation.
YANG Modules and Submodules
The output shows the YANG module “include” option where the submodule is included.

YANG Model Examples


The output shows the YANG module container example configuration. Container contains a single structure
containing zero or more values or other statements.

The output shows the YANG module presented in the XML format. The XML format representation is
especially useful in large and complex models where a basic editor is no longer the best choice for viewing
and editing the YANG data model.

The output shows the YANG module presented in the JSON format. The JSON format is popular because it
is simple and easy to read and understand.

The output shows the CLI format. The CLI format is well known for many years.

1. 0Which protocol uses XML-based data encoding and provides mechanisms to install, manipulate,
and delete device configurations?
a. gRPC
b. NETCONF
c. Python
d. UDP
0NETCONF Fundamentals
This topic describes the foundational principles of NETCONF.
NETCONF is an IETF network management protocol designed specifically for configuration management.
The following are the NETCONF capabilities:
• The distinction between configuration and state data.
• Multiple configuration data stores (candidate, running, startup).
• Configuration change transactions.
• Configuration testing and validation support.
• Selective data retrieval with filtering.
• Streaming and playback of event notifications.
• Extensible procedure call mechanism.

NETCONF is a next-generation network management protocol that is designed specifically to help with
transactional-based network management and to improve upon the weaknesses of SNMP. NETCONF also
makes a distinction between configuration and state data.
One of the most unique attributes of NETCONF is that it uses multiple configuration data stores (candidate,
running, startup), though a device is not required to implement this feature to "support" the protocol.
NETCONF utilizes a candidate configuration, which is simply a configuration with all proposed changes
applied in an uncommitted state. It is the equivalent of entering CLI commands that do not take effect right
away. You would then "commit" all the changes as a single transaction. After they are committed, you
would see them in the running configuration.
NETCONF supports device transactions, which means that when you make an API call configuring
multiple objects and one fails, the entire transaction fails, and you do not end up with a partial
configuration. They are also configurable and platform-dependent. You can still force a change so that it
fails on error or rolls back on error.
NETCONF offers the ability to use filters that are based on XML documents or expressions and to
selectively request specific components of configuration or operational state data.
The NETCONF characteristics are as follows:
• Provides mechanisms to create, replace, merge, and delete device configurations.
• Provides mechanisms to retrieve operational data.
• Uses an XML-based data encoding for the configuration data, and protocol messages.
• Uses RPC mechanism to facilitate communication between a client and server.

NETCONF provides mechanisms to create, replace, merge, and delete the configuration of network devices.
NETCONF also provides mechanisms to retrieve operational data. It uses XML data encoding for the
configuration data, and protocol messages. NETCONF uses a simple RPC mechanism to facilitate
communication between a client and a server. The client can be a script or application that runs as part of a
network manager. The server is a network device such as a router.
A NETCONF session is a logical connection between a network configuration application (client) and a
network device (router). The configuration attributes can be changed during any authorized session.
NETCONF is connection oriented, with SSH as the underlying transport. NETCONF sessions are
established with a hello message, where features and capabilities are announced. Sessions are terminated
with the use of close or kill messages.

NETCONF can be partitioned into four layers:


• Content layer: Includes configuration and notification data. Content is embedded as XML objects.
Within the operations, tags are XML documents specifying the data that you want to retrieve or
configure. It is the content that is an XML representation of YANG models or XML Schema
definitions.
• Operations layer: Defines a set of base protocol operations that are invoked as RPC methods with
XML-encoded parameters.
• Messages layer: Provides a simple, transport-independent framing mechanism for encoding RPCs and
notifications. NETCONF encodes everything in XML, starting with the XML header and message. The
first element in the XML document is always the rpc element, which is denoted as <rpc>. It is simply
telling the server that an RPC will be used on the device. These RPCs map directly back to specific
operations on the device.
• Secure transport layer: Provides a communication path between the client and the server.

Main NETCONF Protocol Operations


In the following table, you can see the main NETCONF protocol operations:

Operation Description

get-config Retrieve all or part of a specified configuration.

edit-config Loads all or part of a specified configuration (merge, replace, create, delete, remove).

copy-config Create or replace an entire configuration data store.

Get Retrieve all or part of running configuration and device operational data.
Operation Description

get-schema Retrieve device schema (model).

lock Lock entire configuration data store (for example, candidate).

unlock Remove lock on entire configuration data store (for example, candidate).

close-session Request graceful session termination.

NETCONF defines one or more configuration data stores and allows configuration operations on the data
stores. A configuration data store is a complete set of configuration data that is required for getting a device
from its initial default state into a desired operational state. The configuration data store does not include
state data or executive commands.

NETCONF Example
NETCONF Request (Client to Router)
<rpc message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<get-config>
<source><running/></source>
<filter>
<cdp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-cdp-cfg"/>
</filter>
</get-config>
</rpc>

The example shows how a NETCONF <get-config> request works with the Cisco Discovery Protocol
feature.
The client initiates a message to get the current configuration of Cisco Discovery Protocol running on the
router. The router then responds with the current Cisco Discovery Protocol configuration.
The <rpc> element in the request and response messages encloses a NETCONF request sent between the
client and the router. The message-id attribute in the <rpc> element is mandatory. This attribute is a string
chosen by the sender, and it encodes an integer. The receiver of the <rpc> element does not decode or
interpret this string but simply saves it to be used in the <rpc-reply> message. The sender must ensure that
the message-id value is normalized. When the client receives information from the server, the <rpc-reply>
message contains the same message-id.
NETCONF Response (Router to Client)
<?xml version="1.0"?>
<rpc-reply message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<data>
<cdp xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-cdp-cfg">
<timer>10</timer>
<enable>true</enable>
<log-adjacency></log-adjacency>
<hold-time>200</hold-time>
<advertise-v1-only></advertise-v1-only>
</cdp>
</data>
</rpc-reply>

NETCONF Edit-Config Operations


You can perform the following NETCONF edit-config operations:

Operation Description

Merge Merge configuration with existing configuration (default).

Replace Replace configuration with existing configuration.

Create Create configuration if nonexistent. Otherwise, return error.

Delete Delete configuration if nonexistent. Otherwise, return error.

Remove Remove configuration. Ignore if configuration is nonexistent.

NETCONF Actions
You can perform the following NETCONF actions:

Actions YANG Models

logmsg Cisco-IOS-XR-syslog-act.yang

snmp Cisco-IOS-XR-snmp-test-trap-act.yang

rollback Cisco-IOS-XR-cfgmgr-rollback-act.yang

ping Cisco-IOS-XR-ping-act.yang
Cisco-IOS-XR-ipv4-ping-act.yang
Cisco-IOS-XR-ipv6-ping-act.yang

traceroute Cisco-IOS-XR-traceroute-act.yang
Cisco-IOS-XR-ipv4-traceroute-act.yang
Cisco-IOS-XR-ipv6-traceroute-act.yang

crypto Cisco-IOS-XR-crypto-act.yang

Actions YANG Models

clear ospf Cisco-IOS-XR-ipv4-ospf-act.yang


Cisco-IOS-XR-ipv6-ospfv3-act.yang

clear isis Cisco-IOS-XR-isis-act.yang

clear bgp Cisco-IOS-XR-ipv4-bgp-act.yang


IOS-XR actions are RPC statements that trigger an operation or execute a command on the router. IOS-XR
actions are defined as YANG models using RPC statements. An action is executed when the router receives
the corresponding NETCONF RPC request. Once the router executes an action, it replies with a NETCONF
RPC response. For example, the ping command is Cisco supported action. That means that a YANG model
is defined for the ping command using RPC statements. So, the ping command can be executed on the
router by initiating the corresponding NETCONF RPC request.

NETCONF Action Ping Example


NETCONF Request (Client to Router)
<rpc message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<ping xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ping-act">
<destination>
<destination>192.168.1.1</destination>
</destination>
</ping>
</rpc>

The example shows how a NETCONF action request to run the ping command on a router.
NETCONF Response (Router to Client)
<rpc-reply message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<ping-response xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ping-act">
<ipv4>
<destination>192.168.1.1</destination>
<repeat-count>5</repeat-count>
<data-size>100</data-size>
<timeout>2</timeout>

The example shows the NETCONF action response from the router.
<pattern>0xabcd</pattern>
<rotate-pattern>0</rotate-pattern>
<reply-list>
<result>!</result>
<result>!</result>
<result>!</result>
<result>!</result>
<result>!</result>
</reply-list>

<hits>5</hits>
<total>5</total>
<success-rate>100</success-rate>
<rtt-min>1</rtt-min>
<rtt-avg>1</rtt-avg>
<rtt-max>1</rtt-max>
</ipv4>
</ping-response>
</rpc-reply>
NETCONF Router Configuration
The following command is an example of router configurations that enable NETCONF.
ssh server v2 ssh server netconf
!
netconf-yang agent
ssh

1. 0What NETCONF edit-config operation will create configuration if the configuration does not exist?
a. Create
b. Delete
c. Merge
d. Remove
e. Replace
0gRPC Fundamentals
This topic describes the foundational principles of gRPC.
The following are gRPC characteristics:
• Provides the infrastructure to build a device management service to exchange configuration and
operational data between a client and a server.
• The structure of the data is defined by YANG models.
• Definition of interface based on Protocol Buffers (Protobuf).
• Requests are encoded and sent to the router with the use of JSON

gRPC is an open-source RPC framework. gRPC provides the infrastructure to build a device management
service to exchange configuration and operational data between a client and a server and the structure of the
data is defined by YANG models.
Cisco gRPC IDL uses the Protocol Buffers interface definition language (IDL) to define service methods,
and define parameters and return types as Protocol Buffers message types. The gRPC requests are encoded
and sent to the router with the use of JSON. Clients can invoke the RPC calls defined in the IDL to program
the router.

gRPC Router Configuration


Example of router configurations that enable gRPC:
grpc
tls
port 57500

Protocol Operations in Cisco IDL

Operation* Description

GetConfig Retrieves configuration

MergeConfig Merges configuration

DeleteConfig Deletes configuration

ReplaceConfig Replaces configuration

CommitReplace Replaces entire configuration


Operation* Description

GetOper Retrieves operational data

CilConfig Merges configuration data in CLI format

ShowCmdTextOutput Retrieves CLI show-command output data

*All configuration operations provide an implicit commit.


1. 0In what format, the gRPC requests are encoded and sent to the router?
a. CLI
b. JSON
c. XML
d. YAML
0Cisco IOS XR Service Layer
This topic describes the basics of the Cisco IOS XR services layer and the service layer API architecture.
Service Layer API is a model-driven API over gRPC. gRPC enables you to bring your applications, routing
protocols, and controllers in a rich set of languages including C++, Python, GO, and many more. Service
Layer API is available out of the box and no extra packages are required. In IOS XR, routing protocols use
RIB, the MPLS label manager, BFD, and other modules, to program the forwarding plane. You can expose
these protocols through the service layer API.
The Service Layer API gives direct access to the Network Infrastructure Layer (Service-Adaptation Layer).
The following are Cisco IOS XR Service Layer advantages:
• High Performance: Direct access to the Network Infrastructure Layer, without going through a
Network state database, results in higher performance than equivalent Management APIs.
– For example, Batch updates straight to the RIB, Label Switch Database (over gRPC)
• Flexibility: The Service Layer API gives you the flexibility to bring your Protocol or Controller over
gRPC.
• Offload low-level tasks to IOS XR: IOS XR infrastructure layer handles the following. Hence, you can
focus on higher-layer protocols and controller logic:
– Conflict resolution
– Transactional notifications
– Data plane abstraction

The following lists service layer standardization efforts.


The Network Processing Forum (NPF) took the first stab at it back in 2003/2004 with its Service API
definitions:
• IPv4 Unicast Forwarding Service API Revision 2 (June 2004)
• IPv6 Unicast Forwarding Service API Revision 2 (June 2004)
• IPv6 Unicast Forwarding Service API (September 2003)
• MPLS Forwarding Service API (September 2003)
• IPv4 Unicast Forwarding Service API (April 2003)

I2RS (interface to the Routing System) at IETF


• Ongoing standardization exercise.
• Primary focus on RIB and Label Switch Database APIs.

OpenConfig gRIBi interface (https://github.com/openconfig/gribi )


• The latest entrant into this space is focused on the RIB API for now.
Cisco IOS XR Network Stack
The following figure shows the Cisco IOS XR network stack.

The Network Infrastructure Layer or Service Adaptation Layer has the following characteristics:
• Acts as the bridge between the Application Layer and the HW.
• Presents abstractions to the Application and Protocol Layer.
• Highly Performant API outside the Central Config and Oper Database context.

Components of Service Layer API


The following are the components of the Service Layer API architecture:
• Functionality Verticals/Domains: The verticals define the broader capability categories supported by
the API. The following are the supported verticals. Each vertical supports data structure and RPCs
defined in GPB.
– Initialization: Handles global initialization, and sets up an event notification channel by using
gRPC streaming capabilities. The initialization RPCs are mandatory. Use the initialization RPCs to
connect a client to the gRPC server on the router. Also, to send heartbeats and termination requests
from the server to the client.
– IPv4, IPv6 Route (RIB): Handles route manipulations (add, update, delete) for a certain VRF.
– MPLS: Handles allocation of label blocks and any incoming MPLS label mapping to a forwarding
function.
– Interface: Handles subscription of the registered clients to the interface state event notifications.
– IPv4, IPv6 BFD: Manages BFD sessions, and corresponding BFD session state notifications.
• ProtobufSchema/Model: Use any potential modeling technique to model the service layer API. Use
the GPB Protobuf IDL.
• gRPC: gRPC utilizes GPB Protobuf IDL by default to convert the models into bindings in various
languages(c++, python, Golang, and more). The gRPC server (running on the router) and the gRPC
client use the generated bindings to serialize data and encode or decode the request or response between
the server and the client.
• Service Layer gRPC clients: Based on the business needs, the gRPC clients for the service layer can
exist in one of the following ways:
– On-box (agents/protocol-stacks running natively or in containers)
– Off-box (within Controllers or other open-source tools)

Use Case: Programmable Route Downloads


The following figure shows a programmable route downloads example.
Use Case: Traffic Engineering and Path Selection
The following figure shows the traffic engineering and path selection examples.

Use Case: Bring Your Own Protocol or Agent


The following figure shows bring your own protocol or agent example.

Cisco IOS XR Service Layer Primary Tenets


The following are Cisco IOS XR Service Layer primary tenets:
• Performance
– Batch updates straight to RIB, LSD (and more in the future).
– Streaming Notifications (BFD events and Interface events).
• API for the “Do-it-yourself” system
– Bring your own Protocol–use the same APIs that Network OS protocol stacks use internally, over
gRPC.
– Enable a Network stack with just what you need, but with an exhaustive API.
• Offload low-level tasks to network OS
– Users can focus on higher layer protocols and Controller logic.
– Lower-Level Functionality–for example, Route Conflict resolution (RIB), Label Mgmt, and
offloaded to the network OS.

Enable Service Layer


To bring your controller on IOS XR, first, enable the service layer on the router and then write your Service
Layer Client API.
Enable the Service Layer.
Router(config)# grpc
Router(config-grpc)# port 57777
Router(config-grpc)# service-layer
Router(config-grpc)# no-tls

Verify if the Service Layer is operational.


Router# show running-config grpc
grpc
port 57777
no-tls
service-layer

Verify the gRPC State


Use the following commands to verify the gRPC state.
Router# show service-layer state
------------service layer state----------
config on: YES
standby connected : NO
idt done: NO
blocked on ndt: NO
connected to RIB for IPv4: YES
connected to RIB for IPv6: YES
Initialization state: estab sync
pending requests: 0
BFD Connection: UP
MPLS Connection: UP
Interface Connection: UP
Objects accepted: NO
interface registered: NO
bfd registered for IPv4: NO
bfd registered for IPv6: NO

Write Your Service Layer Client API


You can write a Service Layer API based on your business needs. Follow these steps to write a Service
Layer API client for a particular functionality vertical.
• Import Bindings: After generating the bindings, import the binding in your code.
• Open Notification Channel: Use the initialization functionality vertical to create a notification channel
to register the client to the gRPC server running on the router.
• Register against Vertical: Register for a functionality vertical to utilize an RPC using the registration
RPC before making calls. The system rejects any calls without prior registration.
• Use RPCs: Once registered against a vertical, select the RPC of your choice. Then complete the object
fields in the gRPC stub.

1. 0Which Cisco IOS XR Service Layer telnet can collect streaming notifications?
a. API for the “Do-it-yourself” system
b. Offload high-level tasks to network OS
c. Offload low-level tasks to network OS
d. Performance
0On-Box Automation Scripts
This topic describes the on-box automation scripts that you can use to automate network operations.
Network automation is imperative to deploy and manage the networks with large-scale cloud-computing
architectures. The automation can be achieved through standard model-driven data models. To cater to the
automation requirements, you can use the Cisco IOS XR infrastructure to make API calls and run scripts
from an external controller. These off-box scripts take advantage of the exposed interfaces such as
NETCONF, SNMP, and SSH to work on the network element. However, there is a need to maintain an
external controller to interact with the router.
To simplify the operational infrastructure, the automation scripts can be run on the router, eliminating the
need for an external controller. The executions of the various types of scripts are faster and reliable as it is
not dependent on the speed or network reachability of the external controller. Most script types interact with
IOS XR Software using standard protocols such as NETCONF. You can download scripts to the router,
configure scripts, view operational data, and set responses to events in the router.
In summary, on-box scripting is similar to off-box scripting, with the exception that the management
software that runs in an external controller is now part of the router software. The scripts programmatically
automate configuration and operational tasks on the network devices. You can create customized scripts that
are based on your network requirement and execute scripts on routers by running Cisco IOS XR operating
system. The packages that support scripting are provided in the software image.
The following are the automation script features:
• Operational simplicity by using automation scripts.
• Model-driven CLI to show YANG operational data.
• Model-driven CLI to display running configuration in XML and JSON formats.
• Manage automation scripts using YANG RPCs.
• Contextual script infrastructure.

Operational simplicity using automation scripts provides you the flexibility to deploy your automation
code on your router instead of running it on external controllers. With automation now available on-box and
integrated into the IOS XR Software, the router processes data locally using Python libraries that provide
direct access to the underlying device operations to execute CLI commands, monitor router configurations,
and status continuously. With on-box automation, you can efficiently control the end-to-end operations
from script enablement to deployment without depending on the connectivity, resource, and speed of an
external controller.
Model-driven CLI to show YANG operational data enables you to use a traditional CLI command to
display YANG data model structures on the router console and obtain operational data from the router in
JSON or XML formats. The functionality helps you transition smoothly between CLI and YANG models,
easing data retrieval from your router and network. This feature introduces the show yang operational
command.
Model-driven CLI to display running configuration in XML and JSON formats enables you to display
the configuration data for Cisco IOS XR platforms in both JSON and XML formats. This feature introduces
the show run | [xml | json] command.
Manage automation scripts using YANG RPCs enables you to use remote procedure calls (RPCs) on
YANG data models to perform the same automated operations as CLIs, such as edit configurations or
retrieve router information.
When you create and run Python scripts on the router, the contextual script infrastructure enables a
contextual interaction between the scripts, the IOS XR Software, and the external servers. This context,
programmed in the script, uses Cisco IOS XR Python packages, modules, and libraries to:
• Obtain operational data from the router.
• Set configurations and conditions.

Detect events in the network and trigger an appropriate action.

Types of Automation Scripts


There are four types of on-box automation scripts that you can use to automate your network operations:
• Configuration (Config) scripts
• Execution (Exec) scripts
• Process scripts
• EEM scripts

Scope of the Script


The following table shows the scopes of on-box scripts:

Scripts Scope

Config Scripts Enforce contextual and conditional changes to configurations, validate configurations before
committing the changes to detect and notify potential errors. If configuration does not comply
with the rules that are defined in the script, an action can be invoked. For example, generate a
warning, syslog message, or halt a commit operation.

Exec Scripts Run operational commands or RPCs, process the output, generate syslogs, configure system,
perform system action commands such as system reload, process restarts, and collect logs for
further evaluation.

Process Scripts Daemonize to continuously run as an agent on the router to execute additional checks outside
traditional ZTP. Daemonized scripts are similar to exec scripts but run continuously. The script
executes operational commands on the router and analyzes the output.

EEM Scripts Run operational commands or RPCs, generate, and determine the next steps like logging the
root cause or changing device configuration. Event policies can upload the output of event
scripts to an on-box or off-box location for further analysis.

Invoke the Script


The following table shows how scripts are invoked:

Scripts Invoke

Config Scripts All config scripts are processed automatically when commit command is executed on the
router.
Scripts Invoke

Exec Scripts Exec script is invoked manually via CLI command or RPC.

Process Scripts Process script is activated via configuration CLI command.

EEM Scripts Event scripts are invoked by defined event policies in response to a system event and allow
for immediate action to take effect.

Benefit of the Script


The following table shows the benefits of on-box scripts:

Scripts Benefit

Config Scripts Simplifies complex configurations and averts potential errors before a configuration is
committed. Ensures that the network configuration complies with rules and policies that are
defined in the script.

Exec Scripts Collects operational information, and decreases the time that is involved in troubleshooting
issues.
Provides flexibility in changing the input parameters for every script run. This fosters dynamic
automation of operational information.

Process Scripts Runs scripts as a daemon to continuously perform tasks that are not transient.

EEM Scripts Automates log collection upon detecting error conditions that are defined by event policies.
Uploads the output of event scripts to an on-box or off-box location for further analysis.

Cisco IOS XR Python Packages


With on-box Python scripting, automation scripts that were run from an external controller are now run on
the router. To achieve this functionality, Cisco IOS XR Software provides contextual support by using SDK
libraries and standard protocols. The following Python third-party application packages are supported by the
scripting infrastructure and can be used to create automation scripts.

Package Description

appdirs Chooses the appropriate platform-specific directories for user data.

asn1crypto Parses and serializes Abstract Syntax Notation One (ASN.1) data structures.

chardet Universal character encoding autodetector.

concurrent.futures Provides a high-level interface for asynchronously executing callables.

ecdsa Implements Elliptic Curve Digital Signature Algorithm (ECDSA) cryptography library to
create keypairs (signing key and verifying key), sign messages, and verify the signatures.
Package Description

enum Enumerates symbolic names (members) bound to unique, constant values.

The following are additional Python third-party application packages:


• email—manages email messages.
• google.protobuf—supports language-neutral, platform-neutral, extensible mechanism for serializing
structured data.
• hashlib—implements a common interface to many different secure hash and message digest algorithms.
• ipaddress—provides the capability to create, manipulate and operate on IPv4 and IPv6 addresses and
networks.
• jinja2—supports adding functionality useful for templating environments.
• json—provides a lightweight data-interchange format.
• libffi—provides a portable, high-level programming interface to call any function specified by a call
interface description at run time.
• ncclient—offers an intuitive API that maps the XML-encoded nature of NETCONF to Python
constructs and idioms, and makes writing network-management scripts easier.
• netaddr—enables system-independent network address manipulation and processing of Layer 3
network addresses.
• netns—shows all the named network namespaces.
• packaging—add the necessary files and structure to create the package.
• pdb—defines an interactive source code debugger for Python programs.
• pkg_resources—provides run time facilities for finding, introspecting, activating and using installed
distributions.
• pyasn1—provides a collection of ASN.1 modules expressed in form of pyasn1 classes. Includes
protocols PDUs definition (SNMP, LDAP, and so on) and various data structures (X.509, PKCS).
• pycparser—parses C code into an AST and can serve as a front end for C compilers or analysis tools.
• pyparsing—provides a library of classes to construct the grammar directly in Python code.
• python3—defines functions, classes, variables, and runnable code.
• pyyaml—YAML parser and emitter for the Python programming language.
• requests—allows sending HTTP/1.1 requests using Python.
• scapy —manipulates packets and allows FastPacket prototyping using default values that work.
• serial—encapsulates the access for the serial port.
• six—provides simple utilities for wrapping over differences between Python 2 and Python 3.
• subprocess—spawns new processes, connects to input/output/error pipes, and obtains return codes.
• urllib3—HTTP client for Python.
Cisco IOS XR Python Libraries
Cisco IOS XR Software provides support for the following SDK libraries and standard protocols.

Library Syntax

xrlog # To generate syslogs #


from cisco.script_mgmt import xrlog
syslog =
xrlog.getSysLogger('template_exec')

netconf # To connect to netconf client #


from iosxr.netconf.netconf_lib import
NetconfClient
nc = NetconfClient(debug=True)

xrclihelper # To run native xr cli and config commands #


from iosxr.xrcli.xrcli_helper import *
helper = XrcliHelper(debug = True)

config_validation # To validate configuration #


import cisco.config_validation as xr

eem # For EEM operations #


from iosxr import eem

Sample Script Templates—Config Script


The following example shows a code snippet for the config script. Use this snippet in your script to import
the libraries required to validate configuration and generate syslogs.
#Needed for config validation
import cisco.config_validation as xr
#Used for generating syslogs
from cisco.script_mgmt import xrlog
syslog = xrlog.getSysLogger('Add script name here')
def check_config(root):
#Add config validations
pass
xr.register_validate_callback([<Add config path here>],check_config)

Sample Script Templates—Exec Script


Use this sample code snippet in the exec script to import Python libraries to connect to NETCONF client
and also to generate syslogs.
#To connect to netconf client
from iosxr.netconf.netconf_lib import NetconfClient
#To generate syslogs
syslog = xrlog.getSysLogger('template_exec')
def test_exec():
"""
Testcase for exec script
"""
nc = NetconfClient(debug=True)
nc.connect()
#Netconf or processing operations
nc.close()
if __name__ == '__main__':
test_exec()

Sample Script Templates—Process Script


Use the following sample code snippet to trigger a process script and perform various actions on the script.
You can use this snippet to create your own custom process script. Any exec script can be used as a process
script.
The following are the steps to trigger the script:
1. Add and configure the script as shown in README.MD.
2. Register the application with Appmgr.
appmgr process-script my-process-app
executable test_process.py
run args --threshold <threshold-value>

3. Activate the registered application.


appmgr process-script activate name my-process-app

Sample Script Templates—Check Script Status


Router# show appmgr process-script-table
Name Executable Activated Status Restart Policy Config
Pending
--------------- ------------------ --------- ------------- ----------------
--------------
my-process-app test_process.py Yes Running On Failure No

Sample Script Templates—More Operations


Router# appmgr process-script ?
activate Activate process script
deactivate Deactivate process script
kill Kill process script
restart Restart process script
start Start process script
stop Stop process script
"""

Sample Script Templates—Netconf Client


#To connect to netconf client
from iosxr.netconf.netconf_lib import NetconfClient
#To generate syslogs
syslog = xrlog.getSysLogger('template_exec')
def test_process():
"""
Testcase for process script
"""
nc = NetconfClient(debug=True)
nc.connect()
#Netconf or any other operations
nc.close()
if __name__ == '__main__':
test_process()

Sample Script Templates—EEM Script


You can use the following sample code to import Python libraries to create a custom EEM script and
generate syslogs.
User and AAA configuration are required configuration for EEM script:
event manager event-trigger <trigger-name>
type syslog pattern "PROC_RESTART_NAME"

event manager action <action-name>


username <user>
type script script-name <script-name> checksum sha256 <checksum>

event manager policy-map policy1


trigger event <trigger-name>
action <action-name>

Sample Script Templates—Verify EEM Script


Check for syslog EVENT SCRIPT EXECUTED: User restarted <process-name>
"""
#Needed for eem operations
from iosxr import eem
#Used to generate syslogs
from cisco.script_mgmt import xrlog
syslog = xrlog.getSysLogger(<add your script name here>)
# event_dict consists of details of the event
rc, event_dict = eem.event_reqinfo()
#You can process the information as needed and take action for example: generate a
syslog. Syslog type can be emergency, alert, critical, error, exception, warning,
notification, info, debug
syslog.info(<Add you syslog here>)

1. 0What on-box automation script runs as a daemon to continuously perform tasks that are not
transient?
a. Config Scripts
b. EEM Scripts
c. Exec Scripts
d. Process Scripts
0YANG Development Kit
This topic describes YANG Development Kit (YDK) a software development kit that provides APIs that are
modeled in YANG.
The YDK is a software development kit that provides APIs that are modeled in YANG. The main goal of
the YDK is to reduce the learning curve by expressing the model semantics in API and abstracting protocol
and encoding details. YDK can generate APIs in a variety of programming languages by using YANG
models. These APIs can then be used to simplify the implementation of applications for network
automation.
YDK has two main components: an API generator (YDK-gen) and a set of generated APIs. Today, YDK-
gen takes YANG models as input and produces either Python APIs (YDK-Py) or C++ (YDK-Cpp) that
mirror the structure of the models.
These abstractions can help the developer. They isolate developers from the protocol, transport, and
encoding specifics and allow them to focus on what is most important—the data structures and the
automation logic. There is no need to code NETCONF RPC specifics or to manipulate XML directly. A set
of predefined services take care of the management protocol, the transport for your management session,
and the encoding and decoding of your data. Furthermore, the APIs perform some level of local validation
based on information embedded in the YANG model. This means that many errors can be caught locally
without having to communicate with the networking device. The abstractions also make the automation
applications more portable. An application could change providers with minimal changes to the code.
Client-Side Validation
The following are the client-side validation characteristics:
• Model constraints that are used during API generation.
• YDK service will automatically perform local (client-side) validation.
• Config (read-write) versus state (read-only).
• Type check (enum, string, and so on)
• Value check (range, pattern, and so on)
• Semantic check (key uniqueness or presence, mandatory leafs, and so on)
• Model deviation check (unsupported leaf, and so on)

YDK takes care of data validation so that you do not have to. Data models not only define a data hierarchy,
but also specify the constraints associated with the data (such as type, valid values, and ranges). YDK
services automatically perform thorough data validation (types, values, semantics, deviations, and so on).
That validation takes place locally before your data is exchanged with the network device.

YDK API Structure


The following are YDK API components:
• Models group Python APIs created for each YANG model.
• BGP, IS-IS, and so on.
• Services perform operations on model objects (interface).
• CRUD, NETCONF, Codec, Executor, and so on.
• Providers implement services (implementation).
• NETCONF, Codec, and so on.
The YDK API is structured into models, services, and providers. The models include Python APIs for each
YANG model, services perform operations on model objects, and providers implement services.

YDK-Py 0.5.0 Package Structure (Bundles)


The YDK uses a bundle structure. There is one core bundle that includes services and providers, and
separate packages exist for each data model. With this structure, you can choose the models in which you
are interested and leave out the others.

Service Providers
from ydk.providers import NetconfServiceProvider
sp_instance = NetconfServiceProvider(address='10.0.0.1',
port=830,
username='test',
password='test',
protocol='ssh')

The first step in any application is to create a service provider instance. In this case, the NETCONF service
provider (defined in ydk.providers.NetconfServiceProvider) is responsible for mapping between the CRUD
service API and the underlying manageability protocol (NETCONF RPCs).

Using the Model APIs


from ydk.models.openconfig import openconfig_bgp
from ydk.models.openconfig import openconfig_bgp_types
# create BGP object
bgp_cfg = openconfig_bgp.Bgp()
# set the Global AS
bgp_cfg.global_.config.as_ = 65001
After establishing the connection, you instantiate the entities and set some data. In this example, first import
the types from the OpenConfig BGP module and then create a BGP configuration object and set the
attributes.

Invoking the CRUD Service


from ydk.services import CRUDService
crud = CRUDService()

The CRUD service provides methods to create, read, update, and delete entities on a device, making use of
the session provided by a service provider (in this case NETCONF). To use the CRUD service, you must
import the CRUDService class, from ydk.services import CRUDService. Then instantiate the CRUD
service, CRUDService().

A YDK-Py "Hello World" Using OpenConfig BGP


The figure shows an example of how to use YDK-Py to create BGP configurations.
A YDK-Py Routing Policy Example
The figure shows a sample of using YDK-Py for configuring community-sets.

What Happens Underneath


YDK performs these actions when running an application:
• Establishes a session with the device.
• Encodes Python data objects to the protocol format (NETCONF XML payload).
• Performs transport operation with the device and collects the response (NETCONF reply).
• Decodes response as Python object and returns the result to the app.
• Raises Python exceptions for any errors that occurred.
Accessing YDK-Py
YDK is available for you to download and install on your computer. Also, you can instantiate a YDK-Py
sandbox on your computer by using Vagrant. The sandbox will provide an Ubuntu (14.04) VM with YDK-
Py pre-installed. Further, you can explore YDK in Cisco dCloud.

1. 0What are two aspects of YDK client-side validation? (Choose two.)


a. Remote static check
b. Semantic check
c. Syntactic check
d. YDK service will automatically perform local validation
e. YDK service will automatically perform remote offline validation
0[V5.0 Video]
[Short video description]
0Summary
0Progress Check
1. 0Which YANG model node type contains a single value of a specific type?
a. container node
b. leaf node
c. leaf-list node
d. list node
2. 0Which YANG model section is optional?
a. module name
b. namespace
c. organization and contact
d. prefix
3. 0Which NETCONF edit-config operation will replace the configuration with existing configuration?
a. create
b. delete
c. merge
d. replace
4. 0Which NETCONF edit-config operation will return error when nonexisting configuration should be
deleted?
a. create
b. delete
c. merge
d. replace
5. 0Which YANG model includes the clear ospf action?
a. copy-config
b. edit-config
c. get
d. get-config
6. 0Which two types of data do data models handle on routers? (Choose two.)
a. configuration data
b. maintenance data
c. operational state data
d. quantitative data
e. statistical data
7. 0Which on-box automation script performs system action commands such as system reload, process
restarts, and collect logs for further evaluation?
a. Config Scripts
b. EEM Scripts
c. Exec Scripts
d. Process Scripts
0Answer Key
Model-Driven Programmability Basics
1. B

NETCONF Fundamentals
1. A

gRPC Fundamentals
1. B

Cisco IOS XR Service Layer


1. D

On-Box Automation Scripts


1. D

YANG Development Kit


1. B, D

Progress Check
1. B
2. C
3. D
4. B
5. D
6. A, C
7. C

You might also like