gNMI Service API

class ydk.gnmi.services.gNMIService

Supports gNMI Set/Get/Subscribe operations on model API entities. It also allows to get gNMI server capabilities.

set(provider, entity)

Create, update, or delete single entity or multiple entities in the server configuration.

Parameters
  • provider – (gNMIServiceProvider) Provider instance.

  • entity

    (Entity) instance, which represents single container in device supported model. Each Entity instance must be annotated with YFilter, which defines set operation:

    • YFilter.replace - add new configuration or replace the whole configuration tree

    • YFilter.update - update or create configuration in existing tree

    • YFilter.delete - delete part or entire configuration tree

    For multiple containers the Entity instances must be encapsulated into Python list or YDK EntityCollection Config.

Returns

True if successful, False if not.

Raises

YServiceProviderError if an error has occurred.

get(provider, read_filter, read_mode='CONFIG')

Read the entity.

Parameters
  • provider – (gNMIServiceProvider) Provider instance.

  • read_filter

    (Entity) instance, which represents single container in device supported model.

    For multiple containers the Entity instances must be encapsulated into Python list or YDK EntityCollection Filter.

  • read_mode – (str) One of the values: CONFIG, STATE, OPERATIONAL, or ALL.

Returns

For single entity filter - an instance of Entity as identified by the read_filter or None, if operation fails.

For multiple filters - collection of Entity instances encapsulated into Python list or YDK EntityCollection Config accordingly to the type of read_filter.

Raises

YServiceProviderError if an error has occurred.

subscribe(provider, subscription, qos=0, mode='ONCE, encoding='PROTO', callback_function=None)

Subscribe to telemetry updates.

Parameters
  • provider – (gNMIServiceProvider) Provider instance.

  • subscription – (gNMISubscription) Single instance or Python list of instances of objects, which represent the subscription.

  • qos – (long) QOS indicating the packet marking.

  • mode – (str) Subscription mode: one of STREAM, ONCE or POLL.

  • encoding – (str) Encoding method for the output: one of JSON, BYTES, PROTO, ASCII, or JSON_IETF.

  • callback_function – (func(str)) Callback function, which is used to process the subscription data. The subscription data returned to the user as a string representation of protobuf SubscribeResponse message. If not specified, the response is printed to system stdout.

Raises

YServiceProviderError if an error has occurred.

capabilities(provider)

Get gNMI server capabilities

Parameters

provider – (gNMIServiceProvider) Provider instance.

Returns

(str) JSON encoded string, which represents gNMI server capabilities.

class ydk.gnmi.services.gNMISubscription

Instance of this class defines subscription for a single entity. Members of the class are:

  • entity: (Entity) Instance of the subscription entity. This parameter must be set by the user.

  • subscription_mode: (str) Expected one of the following string values: TARGET_DEFINED, ON_CHANGE, or SAMPLE; default value is ON_CHANGE.

  • sample_interval: (long) Time interval in nanoseconds between samples in STREAM mode; default value is 60000000000 (1 minute).

  • suppress_redundant: (bool) Indicates whether values that not changed should be sent in a STREAM subscription; default value is False

  • heartbeat_interval: (long) Specifies the maximum allowable silent period in nanoseconds when suppress_redundant is True. If not specified, the heartbeat_interval is set to 360000000000 (10 minutes) or sample_interval whatever is bigger.

gNMI Service Examples

To enable YDK logging include the following code:

1import logging
2logger = logging.getLogger("ydk")
3logger.setLevel(logging.INFO)
4handler = logging.StreamHandler()
5formatter = logging.Formatter(("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
6handler.setFormatter(formatter)
7logger.addHandler(handler)

To enable GRPC trace set environment variables as followed:

1export GRPC_VERBOSITY=debug
2export GRPC_TRACE=transport_security

gNMI ‘set’ example

Example of instantiating and using objects of gNMIServiceProvider with gNMIService is shown below (assuming you have openconfig bundle installed).

 1from ydk.models.openconfig import openconfig_bgp
 2from ydk.path import Repository
 3from ydk.gnmi.providers import gNMIServiceProvider
 4from ydk.gnmi.services import gNMIService
 5
 6repository = Repository('/Users/test/yang_models_location')
 7provider = gNMIServiceProvider(repo=repository, address='10.0.0.1', port=57400, username='admin', password='admin')
 8gnmi_service = gNMIService()
 9
10# Create entire BGP configuration
11bgp = openconfig_bgp.Bgp()
12bgp.global_.config.as_ = 65172
13neighbor = bgp.Neighbors.Neighbor()
14neighbor.neighbor_address = '172.16.255.2'
15neighbor.config.neighbor_address = '172.16.255.2'
16neighbor.config.peer_as = 65172
17bgp.neighbors.neighbor.append(neighbor)
18
19bgp.yfilter = YFilter.replace       # Define set/create operation
20
21ok = gnmi_service.set(provider, bgp) # Perform create operation
22
23# Delete one neighbor
24bgp = openconfig_bgp.Bgp()
25neighbor = bgp.Neighbors.Neighbor()
26neighbor.neighbor_address = '172.16.255.2'
27bgp.neighbors.neighbor.append(neighbor)
28
29bgp.yfilter = YFilter.delete        # Define set/delete operation
30
31ok = gnmi_service.set(provider, bgp) # Perform delete operation

gNMI ‘get’ example

Example of instantiating and using objects of gNMIServiceProvider with gNMIService is shown below (assuming you have openconfig bundle installed).

 1from ydk.models.openconfig import openconfig_bgp
 2from ydk.path import Repository
 3from ydk.gnmi.providers import gNMIServiceProvider
 4from ydk.gnmi.services import gNMIService
 5
 6repository = Repository('/Users/test/yang_models_location')
 7provider = gNMIServiceProvider(repo=repository, address='10.0.0.1', port=57400, username='admin', password='admin')
 8gnmi_service = gNMIService()
 9
10capabilities = provider.get_capabilities() # Get list of capabilities
11
12bgp = openconfig_bgp.Bgp()
13
14bgp_read = gnmi_service.get(provider, bgp) # Perform get operation

gNMI ‘subscribe’ example

Example of subscribing to telemetry using gNMIServiceProvider with gNMIService is shown below (assuming you have openconfig bundle installed).

NOTE: The gNMIService class can be used with multiprocessing.Pool for the subscribe operation as shown below as the subcription is a long-lived connection.

 1from ydk.models.openconfig import openconfig_interfaces
 2from ydk.path import Repository
 3from ydk.gnmi.providers import gNMIServiceProvider
 4from ydk.gnmi.services import gNMIService, gNMISubscription
 5
 6import datetime
 7
 8# Callback function to handle telemetry data
 9def print_telemetry_data(s):
10    if 'update' in s:
11        current_dt = datetime.datetime.now()
12        print("\n===> Received subscribe response at %s: \n%s" %
13              (current_dt.strftime("%Y-%m-%d %H:%M:%S"), s))
14
15# Function to subscribe to telemetry data
16def subscribe(func):
17    # Initialize gNMI Service and Provider
18    gnmi = gNMIService()
19    repository = Repository('/home/yan/ydk-workspace/ydk-gen/scripts/repository/10.30.110.84')
20    provider = gNMIServiceProvider(repo=repository, address='10.30.110.85', port=57400,
21                                   username='admin', password='admin')
22
23    # Create telemetry subscription entity
24    interfaces = openconfig_interfaces.Interfaces()
25    interface = openconfig_interfaces.Interfaces.Interface()
26    interface.name = '"MgmtEth0/RP0/CPU0/0"'
27    interfaces.interface.append(interface)
28
29    # Build subscription
30    subscription = gNMISubscription()
31    subscription.entity = interfaces
32    subscription.subscription_mode = 'SAMPLE'
33    subscription.sample_interval = 10 * 1000000000
34    subscription.suppress_redundant = False
35    subscription.heartbeat_interval = 100 * 1000000000
36
37    # Subscribe for updates in STREAM mode.
38    gnmi.subscribe(provider, subscription, 10, 'STREAM', "PROTO", func)
39
40if __name__ == "__main__":
41    subscribe(print_telemetry_data)